@mastra/livekit 0.4.2-alpha.0 → 0.5.0-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.
Files changed (68) hide show
  1. package/dist/bridge.d.ts +23 -4
  2. package/dist/bridge.d.ts.map +1 -1
  3. package/dist/client-entry.cjs +17 -0
  4. package/dist/client-entry.cjs.map +1 -0
  5. package/dist/client-entry.d.ts +8 -0
  6. package/dist/client-entry.d.ts.map +1 -0
  7. package/dist/client-entry.js +16 -0
  8. package/dist/client-entry.js.map +1 -0
  9. package/dist/dispatch.d.ts +7 -1
  10. package/dist/dispatch.d.ts.map +1 -1
  11. package/dist/index.cjs +119 -17
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.ts +6 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +125 -25
  16. package/dist/index.js.map +1 -1
  17. package/dist/llm-plugin.d.ts +4 -0
  18. package/dist/llm-plugin.d.ts.map +1 -1
  19. package/dist/observability.d.ts +3 -0
  20. package/dist/observability.d.ts.map +1 -1
  21. package/dist/plugin-entry.cjs +17 -4
  22. package/dist/plugin-entry.cjs.map +1 -1
  23. package/dist/plugin-entry.d.ts +4 -0
  24. package/dist/plugin-entry.d.ts.map +1 -1
  25. package/dist/plugin-entry.js +15 -5
  26. package/dist/plugin-entry.js.map +1 -1
  27. package/dist/recording-route.d.ts +31 -0
  28. package/dist/recording-route.d.ts.map +1 -0
  29. package/dist/recording-types.d.ts +11 -0
  30. package/dist/recording-types.d.ts.map +1 -0
  31. package/dist/recording.d.ts +21 -0
  32. package/dist/recording.d.ts.map +1 -0
  33. package/dist/{remote-bPj_0lAr.js → remote-CIMCGicy.js} +207 -15
  34. package/dist/remote-CIMCGicy.js.map +1 -0
  35. package/dist/{remote-DlCC6aCn.cjs → remote-GSOxa--f.cjs} +219 -9
  36. package/dist/remote-GSOxa--f.cjs.map +1 -0
  37. package/dist/remote.d.ts.map +1 -1
  38. package/dist/routes.d.ts +14 -0
  39. package/dist/routes.d.ts.map +1 -1
  40. package/dist/speech.d.ts +19 -0
  41. package/dist/speech.d.ts.map +1 -0
  42. package/dist/turn-metrics-CqqzdLDe.js +53 -0
  43. package/dist/turn-metrics-CqqzdLDe.js.map +1 -0
  44. package/dist/turn-metrics-CtVHHdJj.cjs +82 -0
  45. package/dist/turn-metrics-CtVHHdJj.cjs.map +1 -0
  46. package/dist/turn-metrics.d.ts +69 -0
  47. package/dist/turn-metrics.d.ts.map +1 -0
  48. package/dist/voice-stream.d.ts +3 -0
  49. package/dist/voice-stream.d.ts.map +1 -0
  50. package/dist/worker-entry.cjs +31 -4
  51. package/dist/worker-entry.cjs.map +1 -1
  52. package/dist/worker-entry.d.ts +4 -0
  53. package/dist/worker-entry.d.ts.map +1 -1
  54. package/dist/worker-entry.js +29 -5
  55. package/dist/worker-entry.js.map +1 -1
  56. package/dist/worker.d.ts +5 -0
  57. package/dist/worker.d.ts.map +1 -1
  58. package/dist/{workflow-generator-CfNiAc3Z.js → workflow-generator-5nHqlZV7.js} +24 -4
  59. package/dist/workflow-generator-5nHqlZV7.js.map +1 -0
  60. package/dist/{workflow-generator-Bs-JQgFr.cjs → workflow-generator-D67FvbFe.cjs} +24 -4
  61. package/dist/workflow-generator-D67FvbFe.cjs.map +1 -0
  62. package/dist/workflow-generator.d.ts +1 -1
  63. package/dist/workflow-generator.d.ts.map +1 -1
  64. package/package.json +23 -8
  65. package/dist/remote-DlCC6aCn.cjs.map +0 -1
  66. package/dist/remote-bPj_0lAr.js.map +0 -1
  67. package/dist/workflow-generator-Bs-JQgFr.cjs.map +0 -1
  68. package/dist/workflow-generator-CfNiAc3Z.js.map +0 -1
package/dist/bridge.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { ReadableStream } from 'node:stream/web';
2
- import { llm, voice } from '@livekit/agents';
2
+ import { FlushSentinel, llm, voice } from '@livekit/agents';
3
3
  import type { Agent as MastraAgent, AgentExecutionOptionsBase, AgentMemoryOption } from '@mastra/core/agent';
4
4
  import type { TracingContext } from '@mastra/core/observability';
5
5
  import { RequestContext } from '@mastra/core/request-context';
6
6
  import type { VoiceTurnMessage } from './messages.js';
7
+ import { createGenerationMetrics } from './turn-metrics.js';
8
+ import type { VoiceReplyChunk, VoiceTurnMetricsHook } from './turn-metrics.js';
7
9
  /** Default spoken text for periodic AI re-disclosure. See {@link MastraVoiceAgentOptions.greetingReminder}. */
8
10
  export declare const DEFAULT_DISCLOSURE_REMINDER = "Just a reminder, you're speaking with an AI assistant.";
9
11
  /**
@@ -28,7 +30,7 @@ export declare class DisclosureReminder {
28
30
  * TTS pauses before the reply) before piping the rest of `source` through unchanged. Cancelling the
29
31
  * wrapper cancels `source` — so barge-in still aborts the underlying generation.
30
32
  */
31
- export declare function prependText(source: ReadableStream<string>, text: string): ReadableStream<string>;
33
+ export declare function prependText<T>(source: ReadableStream<T>, text: string): ReadableStream<T | string>;
32
34
  export type MastraStreamOptions = Partial<AgentExecutionOptionsBase<unknown>>;
33
35
  export interface VoiceToolCall {
34
36
  toolCallId: string;
@@ -73,6 +75,12 @@ export interface MastraVoiceAgentMemory {
73
75
  * detected user turn; the bridge builds this context and asks the generator for the reply.
74
76
  */
75
77
  export interface VoiceTurnContext {
78
+ /** Stable user-turn identifier, supplied by the worker or plugin. */
79
+ turnId?: string;
80
+ /** Unique generation attempt identifier, including speculative replies and retries. */
81
+ attemptId?: string;
82
+ /** @internal Bridge-side timing collector. */
83
+ metrics?: ReturnType<typeof createGenerationMetrics>;
76
84
  /**
77
85
  * The messages to generate a reply from. With Mastra Memory on, only the messages new since
78
86
  * the agent last spoke (history comes from the thread); with memory off, the full session.
@@ -132,7 +140,7 @@ export type VoiceTurnCompleteHook = (ctx: VoiceTurnCompleteContext) => void | Pr
132
140
  * generation. Built-in implementations: {@link createAgentReplyGenerator} (a Mastra agent) and
133
141
  * `createWorkflowReplyGenerator` (a Mastra workflow).
134
142
  */
135
- export type VoiceReplyGenerator = (ctx: VoiceTurnContext) => ReadableStream<string> | null | Promise<ReadableStream<string> | null>;
143
+ export type VoiceReplyGenerator = (ctx: VoiceTurnContext) => ReadableStream<VoiceReplyChunk> | null | Promise<ReadableStream<VoiceReplyChunk> | null>;
136
144
  export interface AgentReplyGeneratorOptions {
137
145
  /** The Mastra agent that generates replies. Tools and memory run inside this agent. */
138
146
  agent: MastraAgent;
@@ -152,6 +160,8 @@ export interface AgentReplyGeneratorOptions {
152
160
  */
153
161
  export declare function createAgentReplyGenerator(options: AgentReplyGeneratorOptions): VoiceReplyGenerator;
154
162
  export interface MastraVoiceAgentOptions {
163
+ /** Receives per-attempt generation metrics. Playback metrics come from observeVoiceSession. */
164
+ onTurnMetrics?: VoiceTurnMetricsHook;
155
165
  /**
156
166
  * The Mastra agent that generates replies. Tools and memory run inside this agent. Provide
157
167
  * either this or {@link MastraVoiceAgentOptions.generate}.
@@ -229,9 +239,18 @@ export declare class MastraVoiceAgent extends voice.Agent {
229
239
  readonly requestContext?: RequestContext;
230
240
  readonly streamOptions?: MastraStreamOptions;
231
241
  private readonly replyGenerator;
242
+ private readonly onTurnMetrics?;
232
243
  private readonly reminder?;
233
244
  constructor(options: MastraVoiceAgentOptions);
234
- llmNode(chatCtx: llm.ChatContext, _toolCtx: llm.ToolContext, _modelSettings: voice.ModelSettings): Promise<ReadableStream<llm.ChatChunk | string> | null>;
245
+ llmNode(chatCtx: llm.ChatContext, _toolCtx: llm.ToolContext, _modelSettings: voice.ModelSettings): Promise<ReadableStream<llm.ChatChunk | string | FlushSentinel> | null>;
235
246
  }
236
247
  export declare function createMastraVoiceAgent(options: MastraVoiceAgentOptions): MastraVoiceAgent;
248
+ /** @internal Wrap every reply source, including custom generators, with one terminal metric. */
249
+ export declare function instrumentVoiceReply(generator: VoiceReplyGenerator, ctx: VoiceTurnContext, onTurnMetrics?: VoiceTurnMetricsHook): Promise<{
250
+ reply: ReadableStream<VoiceReplyChunk> | null;
251
+ identity: {
252
+ turnId: string;
253
+ attemptId: string;
254
+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,CAAA;KAAE,CAAA;CAAE,CAAC,CA8C7G"}
@@ -0,0 +1,17 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _mastra_client_js = require("@mastra/client-js");
3
+ //#region src/client-entry.ts
4
+ /** Requests a fresh playback URL using the client's authentication and fetch configuration. */
5
+ function getLiveKitRecording(client, traceId, options) {
6
+ return new _mastra_client_js.MastraClient({
7
+ ...client.options,
8
+ apiPrefix: ""
9
+ }).request(`/voice/livekit/recordings/${encodeURIComponent(traceId)}`, {
10
+ retries: 0,
11
+ signal: options?.signal
12
+ });
13
+ }
14
+ //#endregion
15
+ exports.getLiveKitRecording = getLiveKitRecording;
16
+
17
+ //# sourceMappingURL=client-entry.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-entry.cjs","names":["MastraClient"],"sources":["../src/client-entry.ts"],"sourcesContent":["// Browser-safe entry point. Keep server routes, credentials, and worker runtimes out of this module.\nimport { MastraClient } from '@mastra/client-js';\nimport type { LiveKitRecordingResponse } from './recording-types';\n\nexport type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types';\n\n/** Requests a fresh playback URL using the client's authentication and fetch configuration. */\nexport function getLiveKitRecording(\n client: Pick<MastraClient, 'options'>,\n traceId: string,\n options?: { signal?: AbortSignal },\n): Promise<LiveKitRecordingResponse> {\n // Custom integration routes mount at the server root, independently of apiPrefix.\n // A separate client preserves the original client's routing and transport settings.\n const integration = new MastraClient({ ...client.options, apiPrefix: '' });\n return integration.request(`/voice/livekit/recordings/${encodeURIComponent(traceId)}`, {\n retries: 0,\n signal: options?.signal,\n });\n}\n"],"mappings":";;;;AAOA,SAAgB,oBACd,QACA,SACA,SACmC;CAInC,OAAO,IADiBA,kBAAAA,aAAa;EAAE,GAAG,OAAO;EAAS,WAAW;CAAG,CACvD,CAAC,CAAC,QAAQ,6BAA6B,mBAAmB,OAAO,KAAK;EACrF,SAAS;EACT,QAAQ,SAAS;CACnB,CAAC;AACH"}
@@ -0,0 +1,8 @@
1
+ import { MastraClient } from '@mastra/client-js';
2
+ import type { LiveKitRecordingResponse } from './recording-types.js';
3
+ export type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types.js';
4
+ /** Requests a fresh playback URL using the client's authentication and fetch configuration. */
5
+ export declare function getLiveKitRecording(client: Pick<MastraClient, 'options'>, traceId: string, options?: {
6
+ signal?: AbortSignal;
7
+ }): Promise<LiveKitRecordingResponse>;
8
+ //# sourceMappingURL=client-entry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-entry.d.ts","sourceRoot":"","sources":["../src/client-entry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAElE,YAAY,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAEpF,+FAA+F;AAC/F,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,EACrC,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GACjC,OAAO,CAAC,wBAAwB,CAAC,CAQnC"}
@@ -0,0 +1,16 @@
1
+ import { MastraClient } from "@mastra/client-js";
2
+ //#region src/client-entry.ts
3
+ /** Requests a fresh playback URL using the client's authentication and fetch configuration. */
4
+ function getLiveKitRecording(client, traceId, options) {
5
+ return new MastraClient({
6
+ ...client.options,
7
+ apiPrefix: ""
8
+ }).request(`/voice/livekit/recordings/${encodeURIComponent(traceId)}`, {
9
+ retries: 0,
10
+ signal: options?.signal
11
+ });
12
+ }
13
+ //#endregion
14
+ export { getLiveKitRecording };
15
+
16
+ //# sourceMappingURL=client-entry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-entry.js","names":[],"sources":["../src/client-entry.ts"],"sourcesContent":["// Browser-safe entry point. Keep server routes, credentials, and worker runtimes out of this module.\nimport { MastraClient } from '@mastra/client-js';\nimport type { LiveKitRecordingResponse } from './recording-types';\n\nexport type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types';\n\n/** Requests a fresh playback URL using the client's authentication and fetch configuration. */\nexport function getLiveKitRecording(\n client: Pick<MastraClient, 'options'>,\n traceId: string,\n options?: { signal?: AbortSignal },\n): Promise<LiveKitRecordingResponse> {\n // Custom integration routes mount at the server root, independently of apiPrefix.\n // A separate client preserves the original client's routing and transport settings.\n const integration = new MastraClient({ ...client.options, apiPrefix: '' });\n return integration.request(`/voice/livekit/recordings/${encodeURIComponent(traceId)}`, {\n retries: 0,\n signal: options?.signal,\n });\n}\n"],"mappings":";;;AAOA,SAAgB,oBACd,QACA,SACA,SACmC;CAInC,OAAO,IADiB,aAAa;EAAE,GAAG,OAAO;EAAS,WAAW;CAAG,CACvD,CAAC,CAAC,QAAQ,6BAA6B,mBAAmB,OAAO,KAAK;EACrF,SAAS;EACT,QAAQ,SAAS;CACnB,CAAC;AACH"}
@@ -1,10 +1,16 @@
1
1
  import type { LiveKitSessionMetadata } from './metadata.js';
2
+ import type { LiveKitRecordingOptions } from './recording.js';
2
3
  export interface DispatchVoiceSessionOptions {
3
- /** Room to dispatch the agent into (created on demand). */
4
+ /**
5
+ * Room to dispatch the agent into (created on demand). With recording enabled, use a unique
6
+ * name for each call. An existing room throws LiveKitRecordingRoomConflictError.
7
+ */
4
8
  roomName: string;
5
9
  /** Must match the worker's `agentName`. Defaults to `'mastra-voice'`. */
6
10
  agentName?: string;
7
11
  metadata?: LiveKitSessionMetadata;
12
+ /** Create a fresh room with automatic recording before dispatch. Omit to keep dispatch-only behavior. */
13
+ recording?: LiveKitRecordingOptions;
8
14
  /** Defaults to `LIVEKIT_URL`. */
9
15
  serverUrl?: string;
10
16
  /** Defaults to `LIVEKIT_API_KEY`. */
@@ -1 +1 @@
1
- {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../src/dispatch.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEzD,MAAM,WAAW,2BAA2B;IAC1C,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,sBAAsB,CAAC;IAClC,iCAAiC;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qCAAqC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wCAAwC;IACxC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAMD;;;GAGG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,uDAgB9E"}
1
+ {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../src/dispatch.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEzD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE3D,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,sBAAsB,CAAC;IAClC,yGAAyG;IACzG,SAAS,CAAC,EAAE,uBAAuB,CAAC;IACpC,iCAAiC;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qCAAqC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wCAAwC;IACxC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAMD;;;GAGG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,uDA0B9E"}
package/dist/index.cjs CHANGED
@@ -1,9 +1,57 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_workflow_generator = require("./workflow-generator-Bs-JQgFr.cjs");
2
+ const require_workflow_generator = require("./workflow-generator-D67FvbFe.cjs");
3
3
  let _livekit_protocol = require("@livekit/protocol");
4
4
  let livekit_server_sdk = require("livekit-server-sdk");
5
+ let zod_v4 = require("zod/v4");
5
6
  let _mastra_core_tools = require("@mastra/core/tools");
6
7
  let zod = require("zod");
8
+ //#region src/recording.ts
9
+ /** A recording-enabled session cannot reuse an existing LiveKit room. */
10
+ var LiveKitRecordingRoomConflictError = class extends Error {
11
+ roomName;
12
+ constructor(roomName) {
13
+ super(`@mastra/livekit: recording requires a new room, but room "${roomName}" already exists. Use a fresh room name.`);
14
+ this.name = "LiveKitRecordingRoomConflictError";
15
+ this.roomName = roomName;
16
+ }
17
+ };
18
+ /** Creates a fresh room with recording configured before any agent or caller joins. */
19
+ async function createRecordingRoom(options) {
20
+ const { recording, roomName } = options;
21
+ if (!recording.room && !recording.participant && !recording.tracks) throw new Error("@mastra/livekit: recording must configure at least one of room, participant, or tracks.");
22
+ const client = new livekit_server_sdk.RoomServiceClient(options.serverUrl.replace(/^ws/, "http"), options.apiKey, options.apiSecret);
23
+ if ((await client.listRooms([roomName])).length > 0) throw new LiveKitRecordingRoomConflictError(roomName);
24
+ return client.createRoom({
25
+ name: roomName,
26
+ egress: new livekit_server_sdk.RoomEgress(recording)
27
+ });
28
+ }
29
+ //#endregion
30
+ //#region src/dispatch.ts
31
+ function toHttpUrl(url) {
32
+ return url.replace(/^ws/, "http");
33
+ }
34
+ /**
35
+ * Programmatically dispatches a Mastra voice agent into a LiveKit room — for
36
+ * server-initiated sessions such as outbound calls or joining an existing room.
37
+ */
38
+ async function dispatchVoiceSession(options) {
39
+ const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
40
+ const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
41
+ const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
42
+ if (!serverUrl) throw new Error("@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.");
43
+ if (!apiKey || !apiSecret) throw new Error("@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.");
44
+ const metadata = require_workflow_generator.serializeSessionMetadata(options.metadata ?? {});
45
+ if (options.recording !== void 0) await createRecordingRoom({
46
+ roomName: options.roomName,
47
+ serverUrl,
48
+ apiKey,
49
+ apiSecret,
50
+ recording: options.recording
51
+ });
52
+ return new livekit_server_sdk.AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret).createDispatch(options.roomName, options.agentName ?? "mastra-voice", { metadata });
53
+ }
54
+ //#endregion
7
55
  //#region src/routes.ts
8
56
  function stringField(body, key) {
9
57
  const value = body[key];
@@ -39,6 +87,24 @@ function liveKitConnectionRoute(options = {}) {
39
87
  const roomName = typeof options.roomName === "function" ? options.roomName(args) : options.roomName ?? `mastra-voice-${globalThis.crypto.randomUUID().slice(0, 8)}`;
40
88
  const identity = typeof options.participantIdentity === "function" ? options.participantIdentity(args) : options.participantIdentity ?? metadata.resourceId ?? `user-${globalThis.crypto.randomUUID().slice(0, 8)}`;
41
89
  metadata.threadId ??= roomName;
90
+ const recording = typeof options.recording === "function" ? await options.recording({
91
+ ...args,
92
+ roomName
93
+ }) : options.recording;
94
+ if (recording !== void 0) try {
95
+ await dispatchVoiceSession({
96
+ roomName,
97
+ agentName: options.agentName,
98
+ metadata,
99
+ serverUrl,
100
+ apiKey,
101
+ apiSecret,
102
+ recording
103
+ });
104
+ } catch (error) {
105
+ if (error instanceof LiveKitRecordingRoomConflictError) return c.json({ error: "Recording requires a new room. Use a unique roomName for each call." }, 409);
106
+ throw error;
107
+ }
42
108
  const token = new livekit_server_sdk.AccessToken(apiKey, apiSecret, {
43
109
  identity,
44
110
  ttl: options.ttl ?? "15m"
@@ -51,7 +117,7 @@ function liveKitConnectionRoute(options = {}) {
51
117
  canPublishData: true,
52
118
  canUpdateOwnMetadata: true
53
119
  });
54
- token.roomConfig = new _livekit_protocol.RoomConfiguration({ agents: [new _livekit_protocol.RoomAgentDispatch({
120
+ if (recording === void 0) token.roomConfig = new _livekit_protocol.RoomConfiguration({ agents: [new _livekit_protocol.RoomAgentDispatch({
55
121
  agentName: options.agentName ?? "mastra-voice",
56
122
  metadata: require_workflow_generator.serializeSessionMetadata(metadata)
57
123
  })] });
@@ -71,21 +137,55 @@ function liveKitConnectionRoute(options = {}) {
71
137
  };
72
138
  }
73
139
  //#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 livekit_server_sdk.AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret).createDispatch(options.roomName, options.agentName ?? "mastra-voice", { metadata: require_workflow_generator.serializeSessionMetadata(options.metadata ?? {}) });
140
+ //#region src/recording-route.ts
141
+ const traceIdSchema = zod_v4.z.string().min(1).max(256);
142
+ const recordingSchema = zod_v4.z.object({
143
+ url: zod_v4.z.url({ protocol: /^https?$/ }),
144
+ expiresAt: zod_v4.z.string().datetime().optional()
145
+ });
146
+ /** Resolves a voice call trace to a recording without persisting signed URLs in traces. */
147
+ function liveKitRecordingRoute(options) {
148
+ if (typeof options.authorize !== "function") throw new Error("liveKitRecordingRoute requires an authorize callback.");
149
+ return {
150
+ path: options.path ?? "/voice/livekit/recordings/:traceId",
151
+ method: "GET",
152
+ requiresAuth: options.requiresAuth ?? true,
153
+ handler: async (context) => {
154
+ context.header("Cache-Control", "no-store");
155
+ const input = traceIdSchema.safeParse(context.req.param("traceId"));
156
+ if (!input.success) return context.json({ error: "A valid trace ID is required." }, 400);
157
+ const traceId = input.data;
158
+ try {
159
+ if (await options.authorize({
160
+ traceId,
161
+ context
162
+ }) !== true) return context.json({ error: "Access to this recording is denied." }, 403);
163
+ const store = await context.get("mastra").getStorage()?.getStore("observability");
164
+ if (!store) return context.json({ error: "Trace storage is not configured." }, 503);
165
+ const calls = (await store.getTrace({ traceId }))?.spans.filter((span) => span.name === "voice call" && typeof span.metadata?.roomName === "string" && span.metadata.roomName.length > 0) ?? [];
166
+ if (!calls.length) return context.json({ error: "Voice call trace not found." }, 404);
167
+ if (calls.length !== 1) return context.json({ error: "This trace contains multiple voice calls." }, 409);
168
+ const span = calls[0];
169
+ const roomName = span.metadata?.roomName;
170
+ if (typeof roomName !== "string") return context.json({ error: "Voice call trace not found." }, 404);
171
+ const recording = await options.resolveRecording({
172
+ traceId,
173
+ roomName,
174
+ span,
175
+ context
176
+ });
177
+ if (!recording) return context.json({ status: "unavailable" });
178
+ const result = recordingSchema.safeParse(recording);
179
+ if (!result.success) return context.json({ error: "Unable to load the call recording." }, 502);
180
+ return context.json({
181
+ status: "ready",
182
+ ...result.data
183
+ });
184
+ } catch {
185
+ return context.json({ error: "Unable to load the call recording." }, 502);
186
+ }
187
+ }
188
+ };
89
189
  }
90
190
  //#endregion
91
191
  //#region src/consent.ts
@@ -178,10 +278,12 @@ function createEndCallTool(options = {}) {
178
278
  }
179
279
  //#endregion
180
280
  exports.DEFAULT_LIVEKIT_AGENT_NAME = require_workflow_generator.DEFAULT_LIVEKIT_AGENT_NAME;
281
+ exports.LiveKitRecordingRoomConflictError = LiveKitRecordingRoomConflictError;
181
282
  exports.createConsentTool = createConsentTool;
182
283
  exports.createEndCallTool = createEndCallTool;
183
284
  exports.dispatchVoiceSession = dispatchVoiceSession;
184
285
  exports.liveKitConnectionRoute = liveKitConnectionRoute;
286
+ exports.liveKitRecordingRoute = liveKitRecordingRoute;
185
287
  exports.pipeAgentReplyToWriter = require_workflow_generator.pipeAgentReplyToWriter;
186
288
  exports.serializeSessionMetadata = require_workflow_generator.serializeSessionMetadata;
187
289
 
@@ -1 +1 @@
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 { 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-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n const identity =\n typeof options.participantIdentity === 'function'\n ? options.participantIdentity(args)\n : (options.participantIdentity ?? metadata.resourceId ?? `user-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n // One memory thread per room unless the caller pins a thread explicitly.\n metadata.threadId ??= roomName;\n\n const 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 // Studio calls this default path and /api/system/packages reports it — change all three together.\n path: options.path ?? '/voice/livekit/connection-details',\n method: 'POST',\n requiresAuth: options.requiresAuth,\n handler,\n } as ApiRoute;\n}\n","import { 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":";;;;;;;AA+CA,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;G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AC;EACD,cAAcA,IAAAA,EAAE,OAAO,EAAE,OAAOA,IAAAA,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"}
1
+ {"version":3,"file":"index.cjs","names":["RoomServiceClient","RoomEgress","serializeSessionMetadata","AgentDispatchClient","AccessToken","RoomConfiguration","RoomAgentDispatch","serializeSessionMetadata","z","DEFAULT_DESCRIPTION","z","z"],"sources":["../src/recording.ts","../src/dispatch.ts","../src/routes.ts","../src/recording-route.ts","../src/consent.ts","../src/end-call.ts"],"sourcesContent":["import { RoomEgress, RoomServiceClient } from 'livekit-server-sdk';\n\n/**\n * LiveKit auto-egress settings, accepted as a plain object or a RoomEgress instance.\n * Use `room.audioOnly` and `room.fileOutputs` for a single mixed audio recording.\n * Storage credentials belong here on the server, never in session metadata or tokens.\n */\nexport type LiveKitRecordingOptions = NonNullable<ConstructorParameters<typeof RoomEgress>[0]>;\n\n/** A recording-enabled session cannot reuse an existing LiveKit room. */\nexport class LiveKitRecordingRoomConflictError extends Error {\n readonly roomName: string;\n\n constructor(roomName: string) {\n super(\n `@mastra/livekit: recording requires a new room, but room \"${roomName}\" already exists. Use a fresh room name.`,\n );\n this.name = 'LiveKitRecordingRoomConflictError';\n this.roomName = roomName;\n }\n}\n\n/** Creates a fresh room with recording configured before any agent or caller joins. */\nexport async function createRecordingRoom(options: {\n roomName: string;\n serverUrl: string;\n apiKey: string;\n apiSecret: string;\n recording: LiveKitRecordingOptions;\n}) {\n const { recording, roomName } = options;\n if (!recording.room && !recording.participant && !recording.tracks) {\n throw new Error('@mastra/livekit: recording must configure at least one of room, participant, or tracks.');\n }\n\n const client = new RoomServiceClient(options.serverUrl.replace(/^ws/, 'http'), options.apiKey, options.apiSecret);\n // CreateRoom reuses existing rooms without applying room-composite auto-egress.\n // This preflight is not atomic: callers must use a fresh name and serialize room creation.\n const rooms = await client.listRooms([roomName]);\n if (rooms.length > 0) {\n throw new LiveKitRecordingRoomConflictError(roomName);\n }\n\n return client.createRoom({ name: roomName, egress: new RoomEgress(recording) });\n}\n","import { AgentDispatchClient } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { createRecordingRoom } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\nexport interface DispatchVoiceSessionOptions {\n /**\n * Room to dispatch the agent into (created on demand). With recording enabled, use a unique\n * name for each call. An existing room throws LiveKitRecordingRoomConflictError.\n */\n roomName: string;\n /** Must match the worker's `agentName`. Defaults to `'mastra-voice'`. */\n agentName?: string;\n metadata?: LiveKitSessionMetadata;\n /** Create a fresh room with automatic recording before dispatch. Omit to keep dispatch-only behavior. */\n recording?: LiveKitRecordingOptions;\n /** Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n}\n\nfunction toHttpUrl(url: string): string {\n return url.replace(/^ws/, 'http');\n}\n\n/**\n * Programmatically dispatches a Mastra voice agent into a LiveKit room — for\n * server-initiated sessions such as outbound calls or joining an existing room.\n */\nexport async function dispatchVoiceSession(options: DispatchVoiceSessionOptions) {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl) {\n throw new Error('@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.');\n }\n if (!apiKey || !apiSecret) {\n throw new Error(\n '@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.',\n );\n }\n const metadata = serializeSessionMetadata(options.metadata ?? {});\n if (options.recording !== undefined) {\n await createRecordingRoom({\n roomName: options.roomName,\n serverUrl,\n apiKey,\n apiSecret,\n recording: options.recording,\n });\n }\n const client = new AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret);\n return client.createDispatch(options.roomName, options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME, {\n metadata,\n });\n}\n","import { RoomAgentDispatch, RoomConfiguration } from '@livekit/protocol';\nimport type { ContextWithMastra, ApiRoute } from '@mastra/core/server';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { dispatchVoiceSession } from './dispatch';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { LiveKitRecordingRoomConflictError } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\n/** Response body of the connection-details route. Matches LiveKit's frontend starter contract. */\nexport interface LiveKitConnectionDetails {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n}\n\nexport interface ConnectionRequestArgs {\n body: Record<string, unknown>;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitConnectionRouteOptions {\n /**\n * Route path. Defaults to `/voice/livekit/connection-details`. Mastra reserves the\n * `/api` prefix for built-in routes, so custom paths must not start with `/api`.\n */\n path?: string;\n /** LiveKit server URL (`wss://...`). Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n /** LiveKit agent name for explicit dispatch. Must match the worker's `agentName`. */\n agentName?: string;\n /** Token time-to-live. Defaults to `'15m'`. */\n ttl?: string | number;\n /** Defaults to `true` (Mastra custom routes require auth unless opted out). */\n requiresAuth?: boolean;\n /**\n * Room name or a function that derives one from the request. Defaults to a generated name.\n * With recording enabled, use a unique name for each call. An existing room returns HTTP 409\n * before agent dispatch or token issuance.\n */\n roomName?: string | ((args: ConnectionRequestArgs) => string);\n participantIdentity?: string | ((args: ConnectionRequestArgs) => string);\n /**\n * Session metadata delivered to the worker via agent dispatch. Defaults to passing\n * through `agentId`, `threadId`, and `resourceId` from the request body.\n */\n metadata?: (args: ConnectionRequestArgs) => LiveKitSessionMetadata | Promise<LiveKitSessionMetadata>;\n /**\n * Create a fresh room with automatic recording and dispatch the agent before returning a token.\n * The server-side callback receives the resolved room name; return undefined to skip recording.\n * Recording settings and storage credentials are never included in the participant token.\n */\n recording?:\n | LiveKitRecordingOptions\n | ((\n args: ConnectionRequestArgs & { roomName: string },\n ) => LiveKitRecordingOptions | undefined | Promise<LiveKitRecordingOptions | undefined>);\n}\n\nfunction stringField(body: Record<string, unknown>, key: string): string | undefined {\n const value = body[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/**\n * An ApiRoute for `server.apiRoutes` that mints a LiveKit access token with the Mastra\n * voice agent dispatched into the room. Frontends call it to join a voice session:\n *\n * ```ts\n * export const mastra = new Mastra({\n * agents: { support },\n * server: { apiRoutes: [liveKitConnectionRoute({ agentName: 'mastra-voice' })] },\n * });\n * ```\n */\nexport function liveKitConnectionRoute(options: LiveKitConnectionRouteOptions = {}): ApiRoute {\n const handler = async (c: ContextWithMastra) => {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl || !apiKey || !apiSecret) {\n return c.json(\n {\n error:\n 'LiveKit is not configured. Set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET ' +\n '(or pass serverUrl/apiKey/apiSecret to liveKitConnectionRoute).',\n },\n 500,\n );\n }\n\n const body: Record<string, unknown> = await c.req\n .json()\n .then((parsed: unknown) =>\n parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {},\n )\n .catch(() => ({}));\n const args: ConnectionRequestArgs = { body, context: c };\n\n const metadata: LiveKitSessionMetadata = options.metadata\n ? await options.metadata(args)\n : {\n agentId: stringField(body, 'agentId'),\n threadId: stringField(body, 'threadId'),\n resourceId: stringField(body, 'resourceId'),\n };\n\n const roomName =\n typeof options.roomName === 'function'\n ? options.roomName(args)\n : (options.roomName ?? `mastra-voice-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n const identity =\n typeof options.participantIdentity === 'function'\n ? options.participantIdentity(args)\n : (options.participantIdentity ?? metadata.resourceId ?? `user-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n // One memory thread per room unless the caller pins a thread explicitly.\n metadata.threadId ??= roomName;\n\n const recording =\n typeof options.recording === 'function' ? await options.recording({ ...args, roomName }) : options.recording;\n if (recording !== undefined) {\n try {\n await dispatchVoiceSession({\n roomName,\n agentName: options.agentName,\n metadata,\n serverUrl,\n apiKey,\n apiSecret,\n recording,\n });\n } catch (error) {\n if (error instanceof LiveKitRecordingRoomConflictError) {\n return c.json({ error: 'Recording requires a new room. Use a unique roomName for each call.' }, 409);\n }\n throw error;\n }\n }\n\n const token = new AccessToken(apiKey, apiSecret, { identity, ttl: options.ttl ?? '15m' });\n token.addGrant({\n room: roomName,\n roomJoin: true,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n });\n // A pre-created room needs explicit dispatch; token roomConfig only applies at room creation.\n if (recording === undefined) {\n token.roomConfig = new RoomConfiguration({\n agents: [\n new RoomAgentDispatch({\n agentName: options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME,\n metadata: serializeSessionMetadata(metadata),\n }),\n ],\n });\n }\n\n const details: LiveKitConnectionDetails = {\n serverUrl,\n roomName,\n participantName: identity,\n participantToken: await token.toJwt(),\n };\n return c.json(details);\n };\n\n return {\n // Studio calls this default path and /api/system/packages reports it — change all three together.\n path: options.path ?? '/voice/livekit/connection-details',\n method: 'POST',\n requiresAuth: options.requiresAuth,\n handler,\n } as ApiRoute;\n}\n","import type { ApiRoute, ContextWithMastra } from '@mastra/core/server';\nimport type { SpanRecord } from '@mastra/core/storage';\nimport { z } from 'zod/v4';\nimport type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types';\n\nconst traceIdSchema = z.string().min(1).max(256);\nexport const recordingSchema = z.object({\n url: z.url({ protocol: /^https?$/ }),\n expiresAt: z.string().datetime().optional(),\n}) satisfies z.ZodType<LiveKitRecording>;\n\nexport interface LiveKitRecordingResolverArgs {\n traceId: string;\n /** Taken from the stored voice call span, never from the browser request. */\n roomName: string;\n span: SpanRecord;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitRecordingRouteOptions {\n /** Studio discovers this route at its default path: /voice/livekit/recordings/:traceId. */\n path?: string;\n /** Defaults to true. Only disable for a local demo. */\n requiresAuth?: boolean;\n /** Required trace-specific access policy. Only true permits trace lookup and URL resolution. */\n authorize: (args: { traceId: string; context: ContextWithMastra }) => boolean | Promise<boolean>;\n /** Return a playable URL, or undefined if the recording is not available yet. */\n resolveRecording: (args: LiveKitRecordingResolverArgs) => Promise<LiveKitRecording | undefined>;\n}\n\n/** Resolves a voice call trace to a recording without persisting signed URLs in traces. */\nexport function liveKitRecordingRoute(options: LiveKitRecordingRouteOptions): ApiRoute {\n if (typeof options.authorize !== 'function') {\n throw new Error('liveKitRecordingRoute requires an authorize callback.');\n }\n return {\n path: options.path ?? '/voice/livekit/recordings/:traceId',\n method: 'GET',\n requiresAuth: options.requiresAuth ?? true,\n handler: async (context: ContextWithMastra) => {\n context.header('Cache-Control', 'no-store');\n const input = traceIdSchema.safeParse(context.req.param('traceId'));\n if (!input.success) return context.json({ error: 'A valid trace ID is required.' }, 400);\n const traceId = input.data;\n try {\n if ((await options.authorize({ traceId, context })) !== true) {\n return context.json({ error: 'Access to this recording is denied.' }, 403);\n }\n const store = await context.get('mastra').getStorage()?.getStore('observability');\n if (!store) return context.json({ error: 'Trace storage is not configured.' }, 503);\n const trace = await store.getTrace({ traceId });\n const calls =\n trace?.spans.filter(\n span =>\n span.name === 'voice call' &&\n typeof span.metadata?.roomName === 'string' &&\n span.metadata.roomName.length > 0,\n ) ?? [];\n if (!calls.length) return context.json({ error: 'Voice call trace not found.' }, 404);\n if (calls.length !== 1) return context.json({ error: 'This trace contains multiple voice calls.' }, 409);\n const span = calls[0]!;\n const roomName = span.metadata?.roomName;\n if (typeof roomName !== 'string') return context.json({ error: 'Voice call trace not found.' }, 404);\n const recording = await options.resolveRecording({ traceId, roomName, span, context });\n if (!recording) return context.json({ status: 'unavailable' } satisfies LiveKitRecordingResponse);\n // Validate and strip extra fields so storage credentials cannot accidentally become response fields.\n const result = recordingSchema.safeParse(recording);\n if (!result.success) return context.json({ error: 'Unable to load the call recording.' }, 502);\n return context.json({ status: 'ready', ...result.data } satisfies LiveKitRecordingResponse);\n } catch {\n // Storage/provider errors can contain credentials or signed request details.\n return context.json({ error: 'Unable to load the call recording.' }, 502);\n }\n },\n };\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** A consent decision captured from the caller during a call. */\nexport interface ConsentGrant {\n /**\n * The consent item, matching a key in the worker's `configuration.consentPolicy` (e.g.\n * `'summaryStorage'`).\n */\n item: string;\n /** `true` if the caller agreed, `false` if they declined. */\n granted: boolean;\n /** The caller the grant belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread the grant was captured on, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface ConsentToolOptions {\n /**\n * Persist the caller's decision to YOUR system of record (database, CRM, consent ledger). Called\n * each time the caller answers a consent question — keep it quick, it runs inside the turn. This\n * tool owns extracting the caller's identity from the tool execution context; you own storage, so\n * consent lives in a durable, compliant place rather than an opaque plugin store. Read those\n * grants back at `onCallEnd` (or before any consent-gated step) to enforce the requirement.\n */\n onGrant: (grant: ConsentGrant) => void | Promise<void>;\n /** Tool id the agent calls. Defaults to `'recordConsent'`. */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /** Restrict the accepted consent items to this set (becomes an enum). Defaults to any string. */\n items?: readonly string[];\n}\n\nconst DEFAULT_DESCRIPTION =\n \"Record the caller's consent decision for a data-processing item (for example, storing a summary \" +\n 'of the call). Call this as soon as the caller answers a consent question: granted = true if they ' +\n 'agree, false if they decline. Do not proceed with an activity that requires consent until you ' +\n 'have recorded the caller granting it.';\n\n/**\n * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to\n * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add\n * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /\n * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime\n * grants live only where `onGrant` put them: enforce consent by reading them back from your own\n * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared\n * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the\n * policy, never the grants).\n *\n * ```ts\n * // agent tools\n * recordConsent: createConsentTool({\n * items: ['summaryStorage'],\n * onGrant: async ({ item, granted, resourceId }) => {\n * if (resourceId) await db.saveConsent(resourceId, item, granted);\n * },\n * }),\n * ```\n */\nexport function createConsentTool(options: ConsentToolOptions) {\n const items = options.items;\n const itemSchema = items && items.length > 0 ? z.enum([...items] as [string, ...string[]]) : z.string();\n return createTool({\n id: options.id ?? 'recordConsent',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n item: itemSchema.describe(\n \"The consent item the caller is answering for (matches the deployment's required consents).\",\n ),\n granted: z.boolean().describe('True if the caller agreed, false if they declined.'),\n }),\n execute: async ({ item, granted }, { agent }) => {\n await options.onGrant({ item, granted, resourceId: agent?.resourceId, threadId: agent?.threadId });\n return { recorded: true as const, item, granted };\n },\n });\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** Details of the agent's decision to end the call, handed to {@link EndCallToolOptions.onEndCall}. */\nexport interface EndCallRequest {\n /** Short reason the agent gave for ending the call, if any (e.g. \"caller said goodbye\"). */\n reason?: string;\n /** The caller the call belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface EndCallToolOptions {\n /**\n * Tool id the agent calls to end the call. Must match the worker's\n * `configuration.endCall.tool` (both default to `'endCall'`), since that's the name the worker\n * watches for to hang up.\n */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /**\n * Optional bookkeeping hook, called when the agent invokes the tool (records the reason, marks\n * the call resolved in your CRM, …). Runs inside the turn — keep it quick. It does NOT hang up\n * the call; the worker does that once the agent's final words finish playing. The tool reads the\n * caller's identity from its execution context and passes it here.\n */\n onEndCall?: (request: EndCallRequest) => void | Promise<void>;\n}\n\nconst DEFAULT_DESCRIPTION =\n 'End the phone call. Call this only after you have said goodbye and there is nothing left to do — ' +\n 'for example the caller says goodbye, or the task is complete and you have wrapped up. Say your ' +\n 'closing line first, then call this as your final action; the call hangs up once your words finish ' +\n 'playing. Your closing line must be a final statement, never a question — if you are asking the ' +\n 'caller anything (for example whether they need anything else), do NOT call this in that reply; ' +\n 'wait for their answer. Do not call it if the caller still needs something.';\n\n/**\n * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the\n * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional\n * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the\n * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the\n * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).\n * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on\n * the agent and workflow reply paths alike.\n *\n * ```ts\n * // agent tools\n * endCall: createEndCallTool({\n * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),\n * }),\n * // worker\n * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });\n * ```\n */\nexport function createEndCallTool(options: EndCallToolOptions = {}) {\n return createTool({\n id: options.id ?? 'endCall',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n reason: z\n .string()\n .nullish()\n .describe('Short reason the call is ending, e.g. \"caller said goodbye\" or \"task complete\".'),\n }),\n outputSchema: z.object({ ended: z.boolean() }),\n execute: async ({ reason }, { agent }) => {\n try {\n await options.onEndCall?.({\n reason: reason ?? undefined,\n resourceId: agent?.resourceId,\n threadId: agent?.threadId,\n });\n } catch (error) {\n // Bookkeeping is best-effort — the tool must still signal `{ ended: true }` so the worker's\n // end-call detector runs and the call actually hangs up.\n console.warn('@mastra/livekit: onEndCall hook threw', error);\n }\n return { ended: true as const };\n },\n });\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,oCAAb,cAAuD,MAAM;CAC3D;CAEA,YAAY,UAAkB;EAC5B,MACE,6DAA6D,SAAS,yCACxE;EACA,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;AAGA,eAAsB,oBAAoB,SAMvC;CACD,MAAM,EAAE,WAAW,aAAa;CAChC,IAAI,CAAC,UAAU,QAAQ,CAAC,UAAU,eAAe,CAAC,UAAU,QAC1D,MAAM,IAAI,MAAM,yFAAyF;CAG3G,MAAM,SAAS,IAAIA,mBAAAA,kBAAkB,QAAQ,UAAU,QAAQ,OAAO,MAAM,GAAG,QAAQ,QAAQ,QAAQ,SAAS;CAIhH,KAAI,MADgB,OAAO,UAAU,CAAC,QAAQ,CAAC,EAAA,CACrC,SAAS,GACjB,MAAM,IAAI,kC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IA,IAAAA,EAAE,OAAO;CACtG,QAAA,GAAA,mBAAA,WAAA,CAAkB;EAChB,IAAI,QAAQ,MAAM;EAClB,aAAa,QAAQ,eAAeD;EACpC,aAAaC,IAAAA,EAAE,OAAO;GACpB,MAAM,WAAW,SACf,4FACF;GACA,SAASA,IAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS,oDAAoD;EACpF,CAAC;EACD,SAAS,OAAO,EAAE,MAAM,WAAW,EAAE,YAAY;GAC/C,MAAM,QAAQ,QAAQ;IAAE;IAAM;IAAS,YAAY,OAAO;IAAY,UAAU,OAAO;GAAS,CAAC;GACjG,OAAO;IAAE,UAAU;IAAe;IAAM;GAAQ;EAClD;CACF,CAAC;AACH;;;AC/CA,MAAM,sBACJ;;;;;;;;;;;;;;;;;;;AAyBF,SAAgB,kBAAkB,UAA8B,CAAC,GAAG;CAClE,QAAA,GAAA,mBAAA,WAAA,CAAkB;EAChB,IAAI,QAAQ,MAAM;EAClB,aAAa,QAAQ,eAAe;EACpC,aAAaC,IAAAA,EAAE,OAAO,EACpB,QAAQA,IAAAA,EACL,OAAO,CAAC,CACR,QAAQ,CAAC,CACT,SAAS,qFAAiF,EAC/F,CAAC;EACD,cAAcA,IAAAA,EAAE,OAAO,EAAE,OAAOA,IAAAA,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"}
package/dist/index.d.ts CHANGED
@@ -2,6 +2,11 @@ export { liveKitConnectionRoute } from './routes.js';
2
2
  export type { LiveKitConnectionRouteOptions, LiveKitConnectionDetails, ConnectionRequestArgs } from './routes.js';
3
3
  export { dispatchVoiceSession } from './dispatch.js';
4
4
  export type { DispatchVoiceSessionOptions } from './dispatch.js';
5
+ export { LiveKitRecordingRoomConflictError } from './recording.js';
6
+ export type { LiveKitRecordingOptions } from './recording.js';
7
+ export { liveKitRecordingRoute } from './recording-route.js';
8
+ export type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types.js';
9
+ export type { LiveKitRecordingResolverArgs, LiveKitRecordingRouteOptions } from './recording-route.js';
5
10
  export { serializeSessionMetadata } from './metadata.js';
6
11
  export type { LiveKitSessionMetadata } from './metadata.js';
7
12
  export { pipeAgentReplyToWriter } from './workflow-generator.js';
@@ -11,4 +16,5 @@ export type { ConsentGrant, ConsentToolOptions } from './consent.js';
11
16
  export { createEndCallTool } from './end-call.js';
12
17
  export type { EndCallRequest, EndCallToolOptions } from './end-call.js';
13
18
  export { DEFAULT_LIVEKIT_AGENT_NAME } from './constants.js';
19
+ export type { VoiceGenerationMetrics, VoiceSpeechMetrics, VoiceTurnMetrics, VoiceSpeechResult } from './turn-metrics.js';
14
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAClD,YAAY,EAAE,6BAA6B,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAC/G,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAClD,YAAY,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AACtD,YAAY,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,YAAY,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AA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