@mastra/livekit 0.2.0 → 0.3.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/messages.ts","../src/bridge.ts","../src/remote.ts"],"names":["ReadableStream","RequestContext","llm","voice","requestContext","APIStatusError","APIConnectionError","APITimeoutError","APIError"],"mappings":";;;;;;;AAOO,IAAM,+BAAA,GAAkC,4BAAA;AAY/C,SAAS,cAAc,OAAA,EAAkC;AACvD,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,IAAA,IAAQ,QAAQ,OAAA,EAAS;AAClC,IAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,MAAA,KAAA,CAAM,KAAK,IAAI,CAAA;AAAA,IACjB,CAAA,MAAA,IAAW,IAAA,CAAK,IAAA,KAAS,cAAA,EAAgB;AACvC,MAAA,KAAA,CAAM,IAAA,CAAK,KAAK,KAAK,CAAA;AAAA,IACvB,CAAA,MAAA,IAAW,IAAA,CAAK,IAAA,KAAS,eAAA,IAAmB,KAAK,UAAA,EAAY;AAC3D,MAAA,KAAA,CAAM,IAAA,CAAK,KAAK,UAAU,CAAA;AAAA,IAC5B;AAAA,EACF;AACA,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,CAAE,IAAA,EAAK;AAC/B;AAEA,SAAS,mBAAmB,IAAA,EAAkD;AAC5E,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,SAAA,EAAW,OAAO,MAAA;AACpC,EAAA,MAAM,OAAA,GAAU,cAAc,IAAI,CAAA;AAClC,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,MAAM,KAAK,IAAA,CAAK,EAAA;AAChB,EAAA,IAAI,IAAA,CAAK,SAAS,MAAA,EAAQ,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,EAAA,EAAG;AAC7D,EAAA,IAAI,I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AU,KAAK,CAAA,EAAG,OAAA,EAAS,EAAE,SAAA,EAAU,EAAG,CAAA;AAAA,cACtF,CAAA,MAAO;AACL,gBAAA,MAAM,KAAA;AAAA,cACR;AACA,cAAA,IAAI,KAAA,CAAM,SAAA,IAAa,OAAA,GAAU,OAAA,EAAS;AAC1C,cAAA,MAAM,KAAA;AAAA,YACR;AAAA,UACF;AACA,UAAA,IAAI,CAAC,SAAA,EAAW,UAAA,CAAW,KAAA,EAAM;AAEjC,UAAA,gBAAA,CAAiB,SAAS,CAAA;AAAA,QAC5B,SAAS,KAAA,EAAO;AAGd,UAAA,IAAI,SAAA,EAAW;AACb,YAAA,gBAAA,CAAiB,IAAI,CAAA;AACrB,YAAA;AAAA,UACF;AACA,UAAA,UAAA,CAAW,MAAM,KAAK,CAAA;AAAA,QACxB;AAAA,MACF,CAAA;AAAA,MACA,QAAQ,MAAM;AACZ,QAAA,SAAA,GAAY,IAAA;AACZ,QAAA,sBAAA,EAAwB,KAAA,EAAM;AAAA,MAChC;AAAA,KACD,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-DBVKNDAQ.cjs","sourcesContent":["import type { llm } from '@livekit/agents';\n\n/**\n * Fixed id LiveKit gives the customer Agent's instructions when it injects them as a leading\n * `role: 'system'` message into the chat context passed to `chat()` / `llmNode`. We drop this\n * item so the server-side Mastra agent's own system prompt is authoritative.\n */\nexport const LIVEKIT_INSTRUCTIONS_MESSAGE_ID = 'lk.agent_task.instructions';\n\n/**\n * A message bound for `agent.stream(...)` (in-process) or the Mastra server stream route (remote).\n * `id` carries the LiveKit `ChatMessage.id` so the server can dedupe/upsert by id — making\n * base-class retries, preemptive double-sends, and the interrupted-turn reconciliation recipe idempotent.\n */\nexport type VoiceTurnMessage =\n | { role: 'system'; content: string; id?: string }\n | { role: 'user'; content: string; id?: string }\n | { role: 'assistant'; content: string; id?: string };\n\nfunction textOfMessage(message: llm.ChatMessage): string {\n const parts: string[] = [];\n for (const part of message.content) {\n if (typeof part === 'string') {\n parts.push(part);\n } else if (part.type === 'instructions') {\n parts.push(part.value);\n } else if (part.type === 'audio_content' && part.transcript) {\n parts.push(part.transcript);\n }\n }\n return parts.join('\\n').trim();\n}\n\nfunction toVoiceTurnMessage(item: llm.ChatItem): VoiceTurnMessage | undefined {\n if (item.type !== 'message') return undefined;\n const content = textOfMessage(item);\n if (!content) return undefined;\n const id = item.id;\n if (item.role === 'user') return { role: 'user', content, id };\n if (item.role === 'assistant') return { role: 'assistant', content, id };\n // 'system' and 'developer' both map to a Mastra system message.\n return { role: 'system', content, id };\n}\n\n/**\n * Extracts only the messages added since the agent last spoke. Used when Mastra Memory is\n * the source of truth for conversation history: prior turns are already persisted in the\n * thread, so re-sending them would duplicate history.\n *\n * Two extensions over the naive \"slice after the last assistant message\":\n *\n * - **Interrupted-turn self-heal:** when the last assistant message was cut off by barge-in\n * (`interrupted: true`), the server never persisted it — aborted runs skip persistence — so\n * its heard-only text is missing from the thread. Re-send that fragment (ordered first) this\n * turn to backfill it. It stops being \"the last assistant message\" once a full reply lands,\n * so each interrupted fragment is sent exactly once, on the following turn.\n * - **Instructions filter:** LiveKit injects the customer Agent's `instructions` as a\n * leading `system` message ({@link LIVEKIT_INSTRUCTIONS_MESSAGE_ID}); the server-side Mastra\n * agent owns its own system prompt, so drop it (it would otherwise ship on the first turn,\n * before any assistant message).\n */\nexport function extractNewTurnMessages(chatCtx: llm.ChatContext): VoiceTurnMessage[] {\n const items = chatCtx.items;\n let lastAssistantIdx = -1;\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i];\n if (item?.type === 'message' && item.role === 'assistant') {\n lastAssistantIdx = i;\n break;\n }\n }\n const lastAssistant = lastAssistantIdx >= 0 ? items[lastAssistantIdx] : undefined;\n const healInterrupted =\n lastAssistant?.type === 'message' && lastAssistant.role === 'assistant' && lastAssistant.interrupted;\n // Include the interrupted fragment by starting the slice AT it, otherwise start strictly after.\n const startIdx = healInterrupted ? lastAssistantIdx : lastAssistantIdx + 1;\n\n const messages: VoiceTurnMessage[] = [];\n for (const item of items.slice(startIdx)) {\n if (item.type === 'message' && item.id === LIVEKIT_INSTRUCTIONS_MESSAGE_ID) continue;\n const message = toVoiceTurnMessage(item);\n if (message) messages.push(message);\n }\n return messages;\n}\n\n/**\n * Converts the full LiveKit chat context to Mastra messages. Used when the bridge runs\n * without Mastra Memory and LiveKit's in-session context is the only history. The agent's\n * LiveKit-level instructions are excluded — the Mastra agent applies its own instructions.\n */\nexport function chatContextToMessages(chatCtx: llm.ChatContext): VoiceTurnMessage[] {\n const withoutInstructions = chatCtx.copy({ excludeInstructions: true, excludeFunctionCall: true });\n const messages: VoiceTurnMessage[] = [];\n for (const item of withoutInstructions.items) {\n const message = toVoiceTurnMessage(item);\n if (message) messages.push(message);\n }\n return messages;\n}\n","import { ReadableStream } from 'node:stream/web';\nimport { llm, voice } from '@livekit/agents';\nimport type { Agent as MastraAgent, AgentExecutionOptionsBase } from '@mastra/core/agent';\nimport type { TracingContext } from '@mastra/core/observability';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { chatContextToMessages, extractNewTurnMessages } from './messages';\nimport type { VoiceTurnMessage } from './messages';\n\nconst DEFAULT_INSTRUCTIONS = 'You are a helpful voice assistant powered by a Mastra agent.';\n\n/** Default spoken text for periodic AI re-disclosure. See {@link MastraVoiceAgentOptions.greetingReminder}. */\nexport const DEFAULT_DISCLOSURE_REMINDER = \"Just a reminder, you're speaking with an AI assistant.\";\n\n/**\n * Tracks periodic AI re-disclosure for a single call. `due()` returns the reminder text once\n * `everyMs` has elapsed since the last disclosure (resetting the clock), otherwise `undefined`.\n * Time is injectable so the interval logic is deterministically testable.\n */\nexport class DisclosureReminder {\n private lastAt: number;\n constructor(\n private readonly everyMs: number,\n private readonly text: string,\n now: number = Date.now(),\n ) {\n this.lastAt = now;\n }\n /** Call once per turn: the reminder text if it's due, else `undefined`. Does not reset the clock —\n * call {@link DisclosureReminder.markDelivered} once the reminder is actually threaded into the\n * outgoing reply, so a reminder that never makes it out isn't silently skipped for a full interval. */\n due(now: number = Date.now()): string | undefined {\n if (now - this.lastAt < this.everyMs) return undefined;\n return this.text;\n }\n /** Resets the clock. Call only once the reminder text from {@link due} was actually emitted. */\n markDelivered(now: number = Date.now()): void {\n this.lastAt = now;\n }\n}\n\n/**\n * Wraps `source` in a stream that emits `text` as a single leading chunk (with a trailing space, so\n * TTS pauses before the reply) before piping the rest of `source` through unchanged. Cancelling the\n * wrapper cancels `source` — so barge-in still aborts the underlying generation.\n */\nexport function prependText(source: ReadableStream<string>, text: string): ReadableStream<string> {\n const prefix = text.endsWith(' ') ? text : `${text} `;\n const reader = source.getReader();\n return new ReadableStream<string>({\n start(controller) {\n controller.enqueue(prefix);\n },\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) controller.close();\n else controller.enqueue(value);\n } catch (error) {\n controller.error(error);\n }\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n}\n\nexport type MastraStreamOptions = Partial<AgentExecutionOptionsBase<unknown>>;\n\nexport interface VoiceToolCall {\n toolCallId: string;\n toolName: string;\n args?: unknown;\n}\n\n/**\n * Token usage for one turn, captured from the model's `finish` chunk. Field names mirror LiveKit's\n * `CompletionUsage` so the plugin can forward it into `metrics_collected` without remapping.\n */\nexport interface VoiceTurnUsage {\n /** Tokens in the prompt (LiveKit `promptTokens`). */\n promptTokens: number;\n /** Tokens in the completion (LiveKit `completionTokens`). */\n completionTokens: number;\n /** Cached prompt tokens (LiveKit `promptCachedTokens`). */\n promptCachedTokens: number;\n /** Total tokens for the turn. */\n totalTokens: number;\n}\n\n/**\n * Maps a Mastra `finish` chunk's usage (`payload.output.usage`, AI-SDK `LanguageModelUsage`) to the\n * LiveKit-shaped {@link VoiceTurnUsage}, or `undefined` when the chunk carries no token counts.\n * Handles both the flat V2 usage shape (`inputTokens`/`outputTokens`) and the nested V3 shape\n * (`inputTokens.total`/`outputTokens.total`).\n */\nexport function mapTurnUsage(usage: unknown): VoiceTurnUsage | undefined {\n if (!usage || typeof usage !== 'object') return undefined;\n const u = usage as Record<string, unknown>;\n // Prefer the flat V2 shape (`inputTokens: number`); fall back to the nested V3 shape\n // (`inputTokens: { total, cacheRead }`).\n const totalOf = (v: unknown): number | undefined => {\n if (typeof v === 'number') return v;\n if (v && typeof v === 'object' && typeof (v as { total?: unknown }).total === 'number') {\n return (v as { total: number }).total;\n }\n return undefined;\n };\n const cacheReadOf = (v: unknown): number | undefined =>\n v && typeof v === 'object' && typeof (v as { cacheRead?: unknown }).cacheRead === 'number'\n ? (v as { cacheRead: number }).cacheRead\n : undefined;\n\n const promptTokens = totalOf(u.inputTokens) ?? 0;\n const completionTokens = totalOf(u.outputTokens) ?? 0;\n const promptCachedTokens =\n (typeof u.cachedInputTokens === 'number' ? u.cachedInputTokens : cacheReadOf(u.inputTokens)) ?? 0;\n const totalTokens = typeof u.totalTokens === 'number' ? u.totalTokens : promptTokens + completionTokens;\n // Nothing was reported at all → treat as no usage rather than emitting an all-zero chunk.\n if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0 && promptCachedTokens === 0) {\n return undefined;\n }\n return { promptTokens, completionTokens, promptCachedTokens, totalTokens };\n}\n\nexport interface MastraVoiceAgentMemory {\n thread: string;\n resource?: string;\n}\n\n/**\n * Per-turn context handed to a {@link VoiceReplyGenerator}. LiveKit calls `llmNode` once per\n * detected user turn; the bridge builds this context and asks the generator for the reply.\n */\nexport interface VoiceTurnContext {\n /**\n * The messages to generate a reply from. With Mastra Memory on, only the messages new since\n * the agent last spoke (history comes from the thread); with memory off, the full session.\n *\n * For a workflow / custom generator: pass these straight to a memory-backed `agent.stream(...,\n * { memory })` inside a step so the agent backfills history from the thread (no duplication). A\n * stateless workflow that wants the entire transcript every turn should read `chatCtx` instead\n * (e.g. `chatContextToMessages(chatCtx)`), since there is no thread to backfill from.\n */\n messages: VoiceTurnMessage[];\n /** The raw LiveKit chat context, for generators that want the full transcript or message parts. */\n chatCtx: llm.ChatContext;\n /** Resolved memory mapping for the call, or `false` when memory is disabled. */\n memory: MastraVoiceAgentMemory | false;\n /** Request context forwarded to generation. */\n requestContext?: RequestContext;\n /** Voice-call span context, so each turn's generation nests under the call trace. */\n tracingContext?: TracingContext;\n /**\n * Internal, per-turn side channel for token usage. A generator invokes this once, when the\n * `finish` chunk carries usage, so the caller (e.g. `MastraLLMStream`) can attribute usage to\n * exactly this turn — kept on the context (not on generator options) so overlapping turns from\n * preemptive generation can't misattribute usage. Fire-and-forget; the generator does not await it.\n */\n onUsage?: (usage: VoiceTurnUsage) => void;\n}\n\n/**\n * What a turn produced, handed to {@link VoiceTurnCompleteHook} after the reply finishes.\n */\nexport interface VoiceTurnResult {\n /** The assistant reply text streamed this turn, accumulated from the model's text deltas. */\n text: string;\n /** Tool calls the agent made during the turn, in order. */\n toolCalls: VoiceToolCall[];\n /** True when barge-in cut the turn short before it finished streaming. */\n interrupted: boolean;\n /** Token usage for the turn when the model reported it in its `finish` chunk. */\n usage?: VoiceTurnUsage;\n}\n\n/** {@link VoiceTurnContext} plus the reply it produced. Passed to {@link VoiceTurnCompleteHook}. */\nexport interface VoiceTurnCompleteContext extends VoiceTurnContext {\n /** The reply the agent produced this turn. */\n result: VoiceTurnResult;\n}\n\n/**\n * Called once per turn AFTER the reply has finished streaming to text-to-speech — off the audio\n * path. It runs fire-and-forget: the turn does not await it, so post-turn work (memory\n * maintenance, CRM writes, analytics) never delays what the caller hears or the next turn. A\n * thrown error or rejected promise is logged, not propagated. Because the resolved `memory`\n * mapping (`thread`/`resource`) is on the context, this is the place for a truly non-blocking\n * `memory.updateWorkingMemory(...)`. See {@link MastraVoiceAgentOptions.onTurnComplete}.\n */\nexport type VoiceTurnCompleteHook = (ctx: VoiceTurnCompleteContext) => void | Promise<void>;\n\n/**\n * Produces a stream of text deltas for one conversational turn, or `null` to stay silent.\n * Cancelling the returned stream (LiveKit does this on barge-in) must abort the underlying\n * generation. Built-in implementations: {@link createAgentReplyGenerator} (a Mastra agent) and\n * `createWorkflowReplyGenerator` (a Mastra workflow).\n */\nexport type VoiceReplyGenerator = (\n ctx: VoiceTurnContext,\n) => ReadableStream<string> | null | Promise<ReadableStream<string> | null>;\n\nexport interface AgentReplyGeneratorOptions {\n /** The Mastra agent that generates replies. Tools and memory run inside this agent. */\n agent: MastraAgent;\n /** Extra options merged into every `agent.stream()` call (e.g. `tracingContext`). */\n streamOptions?: MastraStreamOptions;\n /** Speak a short phrase while a tool call runs. See {@link MastraVoiceAgentOptions.toolFeedback}. */\n toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;\n /** Notified as each tool-call chunk arrives, mid-stream. See {@link MastraVoiceAgentOptions.onToolCall}. */\n onToolCall?: (toolCall: VoiceToolCall) => void;\n /** Fired off the audio path after the reply streams. See {@link MastraVoiceAgentOptions.onTurnComplete}. */\n onTurnComplete?: VoiceTurnCompleteHook;\n}\n\n/**\n * A {@link VoiceReplyGenerator} backed by a Mastra agent: runs the agent's full loop (model,\n * tools, memory) and streams its text deltas. On barge-in the returned stream is cancelled,\n * which aborts the in-flight `agent.stream()`.\n */\nexport function createAgentReplyGenerator(options: AgentReplyGeneratorOptions): VoiceReplyGenerator {\n const { agent, streamOptions, toolFeedback, onToolCall, onTurnComplete } = options;\n return ctx => {\n if (ctx.messages.length === 0) return null;\n\n const abortController = new AbortController();\n const mergedOptions: MastraStreamOptions = {\n ...streamOptions,\n abortSignal: abortController.signal,\n };\n if (ctx.memory) mergedOptions.memory = ctx.memory;\n if (ctx.requestContext) mergedOptions.requestContext = ctx.requestContext;\n\n let cancelled = false;\n // Accumulated as the turn streams so the post-turn hook can see what was actually produced.\n let replyText = '';\n const toolCalls: VoiceToolCall[] = [];\n let usage: VoiceTurnUsage | undefined;\n\n // Fire-and-forget after the reply has streamed: off the audio path (the caller already heard\n // the text), and not awaited, so it never delays the next turn. Errors are logged, not thrown.\n const emitTurnComplete = (interrupted: boolean) => {\n if (!onTurnComplete) return;\n const completeCtx: VoiceTurnCompleteContext = {\n ...ctx,\n result: { text: replyText, toolCalls, interrupted, usage },\n };\n Promise.resolve()\n .then(() => onTurnComplete(completeCtx))\n .catch(error => {\n console.warn('@mastra/livekit: onTurnComplete hook threw', error);\n });\n };\n\n return new ReadableStream<string>({\n start: async controller => {\n try {\n const result = await agent.stream(ctx.messages, mergedOptions);\n for await (const chunk of result.fullStream) {\n if (cancelled) break;\n if (chunk.type === 'text-delta') {\n if (chunk.payload.text) {\n replyText += chunk.payload.text;\n controller.enqueue(chunk.payload.text);\n }\n } else if (chunk.type === 'tool-call') {\n const toolCall: VoiceToolCall = {\n toolCallId: chunk.payload.toolCallId,\n toolName: chunk.payload.toolName,\n args: chunk.payload.args,\n };\n toolCalls.push(toolCall);\n // Observer hooks are customer code: a throw must not tear down an otherwise healthy\n // reply stream (same isolation as onTurnComplete).\n try {\n onToolCall?.(toolCall);\n } catch (error) {\n console.warn('@mastra/livekit: onToolCall hook threw', error);\n }\n if (toolFeedback) {\n let filler: string | undefined | void;\n try {\n filler = toolFeedback(toolCall);\n } catch (error) {\n console.warn('@mastra/livekit: toolFeedback hook threw', error);\n }\n if (filler) controller.enqueue(filler.endsWith(' ') ? filler : `${filler} `);\n }\n } else if (chunk.type === 'finish') {\n // Usage is dropped from the spoken stream but surfaced via the per-turn side channel\n // and on the turn result, so the plugin and onTurnComplete consumers can read it.\n const output = (chunk.payload as { output?: { usage?: unknown } }).output;\n const turnUsage = mapTurnUsage(output?.usage);\n if (turnUsage) {\n usage = turnUsage;\n try {\n ctx.onUsage?.(turnUsage);\n } catch (error) {\n console.warn('@mastra/livekit: onUsage hook threw', error);\n }\n }\n } else if (chunk.type === 'error') {\n const error = chunk.payload.error;\n throw error instanceof Error ? error : new Error(String(error));\n }\n }\n if (!cancelled) controller.close();\n // Success, or a clean barge-in break out of the loop: the turn is done either way.\n emitTurnComplete(cancelled);\n } catch (error) {\n // Barge-in cancels the stream and aborts generation; that's not a failure — the turn\n // still completed (interrupted), so the hook still fires for memory reconciliation.\n if (cancelled || abortController.signal.aborted) {\n emitTurnComplete(true);\n return;\n }\n controller.error(error);\n }\n },\n cancel: () => {\n cancelled = true;\n abortController.abort();\n },\n });\n };\n}\n\nexport interface MastraVoiceAgentOptions {\n /**\n * The Mastra agent that generates replies. Tools and memory run inside this agent. Provide\n * either this or {@link MastraVoiceAgentOptions.generate}.\n */\n agent?: MastraAgent;\n /**\n * A lower-level reply generator (e.g. from `createWorkflowReplyGenerator`). Use instead of\n * `agent` to drive replies with a workflow or any custom generator.\n */\n generate?: VoiceReplyGenerator;\n /**\n * Conversation persistence. When set, only messages new since the agent last spoke are\n * sent each turn and Mastra Memory supplies history. When `false`, the full LiveKit\n * in-session context is sent on every turn instead.\n */\n memory?: MastraVoiceAgentMemory | false;\n /** Request context entries forwarded to generation. */\n requestContext?: RequestContext | Record<string, unknown>;\n /**\n * Called when the Mastra agent starts a tool call mid-reply. Return a short phrase (e.g. \"Let\n * me look that up.\") to speak it while the tool runs; it also appears in the transcript. Return\n * nothing to stay silent. Applies to the agent generator built here; the workflow generator\n * takes its own equivalent via `createWorkflowReplyGenerator`.\n */\n toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;\n /**\n * Called as each tool call starts mid-reply (before the tool result is known), the building block\n * for tool-driven side effects — analytics, agent-initiated hang-up — without waiting for the turn\n * to finish. Runs synchronously on the stream; keep it cheap and non-throwing. Applies to the agent\n * generator built here; the workflow generator surfaces tool calls via `onTurnComplete` instead.\n */\n onToolCall?: (toolCall: VoiceToolCall) => void;\n /**\n * Called once per turn after the reply has finished streaming to text-to-speech. Runs off the\n * audio path and fire-and-forget — the turn does not await it — so post-turn memory\n * maintenance, CRM writes, or analytics never delay the caller or the next turn. The context\n * carries the produced reply ({@link VoiceTurnResult}) and the resolved `memory` mapping, so\n * this is where a truly non-blocking `memory.updateWorkingMemory(...)` belongs. A thrown error\n * or rejected promise is logged, not propagated. Applies to the agent generator built here; the\n * workflow generator takes its own via `createWorkflowReplyGenerator`.\n */\n onTurnComplete?: VoiceTurnCompleteHook;\n /**\n * Periodic AI re-disclosure. When set, once `everyMs` has elapsed since the last disclosure the\n * NEXT turn's reply is prefixed with `text` (spoken at the turn boundary, never mid-turn), so long\n * calls keep re-disclosing the AI status. Applies to the agent and workflow/custom generators. The\n * worker derives this from `configuration.greeting.repeatEvery` / `repeatText`; `text` defaults to\n * {@link DEFAULT_DISCLOSURE_REMINDER}.\n */\n greetingReminder?: { everyMs: number; text?: string };\n /** Extra options merged into every `agent.stream()` call (agent generator only). */\n streamOptions?: MastraStreamOptions;\n /** LiveKit agent instructions. Unused for reply generation (the Mastra agent/workflow applies its own). */\n instructions?: string;\n id?: voice.AgentOptions<unknown>['id'];\n stt?: voice.AgentOptions<unknown>['stt'];\n vad?: voice.AgentOptions<unknown>['vad'];\n tts?: voice.AgentOptions<unknown>['tts'];\n turnHandling?: voice.AgentOptions<unknown>['turnHandling'];\n}\n\nfunction toRequestContext(value: RequestContext | Record<string, unknown> | undefined): RequestContext | undefined {\n if (!value) return undefined;\n if (value instanceof RequestContext) return value;\n return new RequestContext<unknown>(Object.entries(value));\n}\n\n/**\n * The session only runs its cascaded reply pipeline when an `llm` instance is present —\n * `llmNode` replaces the inference step, but the gate checks `llm instanceof LLM`. This\n * placeholder satisfies the gate; the Mastra agent/workflow does the actual generation.\n */\nclass MastraPlaceholderLLM extends llm.LLM {\n label(): string {\n return 'mastra.MastraVoiceAgent';\n }\n\n override get model(): string {\n return 'mastra-agent';\n }\n\n override get provider(): string {\n return 'mastra';\n }\n\n chat(): llm.LLMStream {\n throw new Error(\n '@mastra/livekit: reply generation runs through the Mastra agent via llmNode; the placeholder LLM cannot be used for inference.',\n );\n }\n}\n\n/**\n * A LiveKit `voice.Agent` whose replies come from a Mastra agent or workflow.\n *\n * LiveKit keeps ownership of the audio loop (VAD, STT, turn detection, TTS, barge-in) and calls\n * `llmNode` once per detected user turn; the node delegates to a {@link VoiceReplyGenerator}\n * which streams text deltas back. On barge-in LiveKit cancels the returned stream, which aborts\n * the in-flight generation.\n */\nexport class MastraVoiceAgent extends voice.Agent {\n readonly mastraAgent?: MastraAgent;\n readonly memory: MastraVoiceAgentMemory | false;\n readonly requestContext?: RequestContext;\n readonly streamOptions?: MastraStreamOptions;\n private readonly replyGenerator: VoiceReplyGenerator;\n private readonly reminder?: DisclosureReminder;\n\n constructor(options: MastraVoiceAgentOptions) {\n if (options.agent && options.generate) {\n throw new Error(\n '@mastra/livekit: MastraVoiceAgent requires `agent` or `generate`, not both — they are mutually exclusive reply sources.',\n );\n }\n super({\n id: options.id,\n instructions: options.instructions ?? DEFAULT_INSTRUCTIONS,\n stt: options.stt,\n vad: options.vad,\n llm: new MastraPlaceholderLLM(),\n tts: options.tts,\n turnHandling: options.turnHandling,\n });\n this.memory = options.memory ?? false;\n this.requestContext = toRequestContext(options.requestContext);\n this.streamOptions = options.streamOptions;\n if (options.greetingReminder) {\n this.reminder = new DisclosureReminder(\n options.greetingReminder.everyMs,\n options.greetingReminder.text?.trim() || DEFAULT_DISCLOSURE_REMINDER,\n );\n }\n\n if (options.generate) {\n this.replyGenerator = options.generate;\n } else if (options.agent) {\n this.mastraAgent = options.agent;\n this.replyGenerator = createAgentReplyGenerator({\n agent: options.agent,\n streamOptions: options.streamOptions,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n });\n } else {\n throw new Error('@mastra/livekit: MastraVoiceAgent requires `agent` or `generate`.');\n }\n }\n\n override async llmNode(\n chatCtx: llm.ChatContext,\n _toolCtx: llm.ToolContext,\n _modelSettings: voice.ModelSettings,\n ): Promise<ReadableStream<llm.ChatChunk | string> | null> {\n const messages: VoiceTurnMessage[] =\n this.memory === false ? chatContextToMessages(chatCtx) : extractNewTurnMessages(chatCtx);\n if (messages.length === 0) return null;\n\n const reply = await this.replyGenerator({\n messages,\n chatCtx,\n memory: this.memory,\n requestContext: this.requestContext,\n tracingContext: this.streamOptions?.tracingContext,\n });\n if (!reply) return null;\n\n // Periodic AI re-disclosure: when the interval has elapsed, prefix this turn's spoken reply with\n // the reminder. Done at the turn boundary (never mid-turn), riding the same stream so barge-in\n // cancellation still propagates to the underlying generation. The clock only resets once the\n // reminder is actually threaded into the outgoing reply below, not just because it was due.\n // KNOWN LIMIT: \"threaded into the reply\" is stream-build time, not playout. Under LiveKit's\n // preemptive generation a discarded speculative reply still resets the clock, so the next real\n // turn can miss its reminder — hence the documented repeatEvery/preemptiveGeneration\n // incompatibility. A playout-accurate reset needs a confirmed-turn signal llmNode doesn't have.\n const reminder = this.reminder?.due();\n if (!reminder) return reply;\n this.reminder?.markDelivered();\n return prependText(reply, reminder);\n }\n}\n\nexport function createMastraVoiceAgent(options: MastraVoiceAgentOptions): MastraVoiceAgent {\n return new MastraVoiceAgent(options);\n}\n","import { ReadableStream } from 'node:stream/web';\nimport { APIConnectionError, APIError, APIStatusError, APITimeoutError } from '@livekit/agents';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { mapTurnUsage } from './bridge';\nimport type {\n VoiceReplyGenerator,\n VoiceToolCall,\n VoiceTurnCompleteContext,\n VoiceTurnCompleteHook,\n VoiceTurnUsage,\n} from './bridge';\n\nconst DEFAULT_API_PREFIX = '/api';\n/** Connect + first-token budget when not overridden. Plugin mode passes `connOptions.timeoutMs`. */\nexport const DEFAULT_REMOTE_TIMEOUT_MS = 10_000;\n/** Standalone initial-connection retry attempts. Plugin mode forces this to 0 (base class owns retries). */\nexport const DEFAULT_REMOTE_RETRIES = 2;\n\n/** Thrown (as a plain, non-retryable error) when the server emits a chunk that needs client action. */\nconst HITL_UNSUPPORTED_MESSAGE =\n '@mastra/livekit: the agent requested tool approval or suspended a tool call; human-in-the-loop ' +\n 'flows (approve-tool-call / resume-stream) are not supported on the voice path. Remove requireApproval ' +\n 'or suspend from the tools this agent uses on voice calls.';\n\n/**\n * Options for the remote Mastra transport. Shape mirrors the in-process `AgentReplyGeneratorOptions`\n * so `MastraLLM` can accept either source interchangeably.\n */\nexport interface RemoteMastraAgentOptions {\n /** Base URL of the remote Mastra server, e.g. `https://my-app.mastra.cloud`. */\n baseUrl: string;\n /** Agent key in the Mastra config's `agents`. */\n agentId: string;\n /** Path prefix for the Mastra API. Defaults to `'/api'`. */\n apiPrefix?: string;\n /** Static headers, or a (possibly async) resolver invoked per turn — e.g. to mint a fresh token. */\n headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);\n /** Injectable `fetch` for tests/proxies. Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /**\n * Connect + first-token timeout in ms. Plugin mode default: LiveKit's `connOptions.timeoutMs` (10s).\n * Standalone default: {@link DEFAULT_REMOTE_TIMEOUT_MS}.\n */\n timeoutMs?: number;\n /**\n * Initial-connection retry attempts (before the first chunk only). Standalone default:\n * {@link DEFAULT_REMOTE_RETRIES}. In plugin mode the LiveKit base class owns retries and this is\n * forced to 0.\n */\n retries?: number;\n /** Extra fields merged into each stream request body (advanced). */\n body?: Record<string, unknown>;\n}\n\n/** {@link RemoteMastraAgentOptions} plus the per-turn observer hooks the generator threads through. */\nexport interface RemoteAgentReplyGeneratorOptions extends RemoteMastraAgentOptions {\n /** Speak a short phrase while a tool runs. See {@link MastraVoiceAgentOptions.toolFeedback}. */\n toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;\n /** Notified as each tool-call chunk arrives, mid-stream. See {@link MastraVoiceAgentOptions.onToolCall}. */\n onToolCall?: (toolCall: VoiceToolCall) => void;\n /** Fired off the audio path after the reply streams. See {@link MastraVoiceAgentOptions.onTurnComplete}. */\n onTurnComplete?: VoiceTurnCompleteHook;\n}\n\ntype RawChunk = { type?: string; payload?: Record<string, unknown> };\n\nfunction trimTrailingSlash(url: string): string {\n return url.endsWith('/') ? url.slice(0, -1) : url;\n}\n\nfunction toMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function resolveHeaders(headers: RemoteMastraAgentOptions['headers']): Promise<Record<string, string>> {\n if (!headers) return {};\n if (typeof headers === 'function') return (await headers()) ?? {};\n return headers;\n}\n\nfunction serializeRequestContext(\n requestContext: RequestContext | Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!requestContext) return undefined;\n // Mirror client-js `parseClientRequestContext`.\n if (requestContext instanceof RequestContext) return Object.fromEntries(requestContext.entries());\n return requestContext;\n}\n\nasync function safeReadBody(response: Response): Promise<object | null> {\n try {\n const text = await response.text();\n if (!text) return null;\n try {\n const parsed: unknown = JSON.parse(text);\n return parsed && typeof parsed === 'object' ? (parsed as object) : { message: String(parsed) };\n } catch {\n return { message: text };\n }\n } catch {\n return null;\n }\n}\n\n/**\n * Reads a Mastra SSE stream and yields each event's parsed JSON. Framing matches the server's\n * `processMastraStream` (buffer, split on `\\n\\n`, strip `data: `, stop on `[DONE]`); undecodable\n * `data:` lines are skipped. Aborting `signal` cancels the underlying reader.\n */\nexport async function* readMastraSSE(\n body: globalThis.ReadableStream<Uint8Array>,\n signal: AbortSignal,\n): AsyncGenerator<RawChunk> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n const onAbort = () => void reader.cancel().catch(() => {});\n if (signal.aborted) {\n void reader.cancel().catch(() => {});\n return;\n }\n signal.addEventListener('abort', onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const events = buffer.split('\\n\\n');\n buffer = events.pop() ?? '';\n for (const event of events) {\n if (!event.startsWith('data:')) continue;\n const data = event.slice(event.startsWith('data: ') ? 6 : 5).trim();\n if (data === '[DONE]') return;\n if (!data) continue;\n let json: unknown;\n try {\n json = JSON.parse(data);\n } catch {\n continue; // tolerate a stray non-JSON line\n }\n if (json && typeof json === 'object') yield json as RawChunk;\n }\n }\n } finally {\n signal.removeEventListener('abort', onAbort);\n try {\n reader.releaseLock();\n } catch {\n // A read may still be pending when the fetch was aborted; the stream is torn down anyway.\n }\n }\n}\n\n/**\n * A {@link VoiceReplyGenerator} that runs the Mastra agent loop on a **remote** Mastra server over\n * HTTP/SSE. Shaped exactly like the in-process `createAgentReplyGenerator`: it consumes the same\n * chunk vocabulary, drives the same `toolFeedback` / `onToolCall` / `onTurnComplete` seams, and\n * cancelling the returned stream (LiveKit does this on barge-in) tears down the HTTP request so the\n * server aborts generation.\n *\n * Usable standalone via the worker's `generate:` hatch (a minimum-viable remote worker mode), and as\n * the transport `MastraLLM` wraps. Errors are thrown as LiveKit `APIError` subclasses so the plugin's\n * base-class retry loop and `FallbackAdapter` behave; a connect + first-token watchdog prevents\n * indefinite dead air.\n */\nexport function createRemoteAgentReplyGenerator(options: RemoteAgentReplyGeneratorOptions): VoiceReplyGenerator {\n const {\n baseUrl,\n agentId,\n apiPrefix = DEFAULT_API_PREFIX,\n headers,\n fetch: fetchImpl = globalThis.fetch,\n timeoutMs = DEFAULT_REMOTE_TIMEOUT_MS,\n retries = DEFAULT_REMOTE_RETRIES,\n body: extraBody,\n toolFeedback,\n onToolCall,\n onTurnComplete,\n } = options;\n\n if (!fetchImpl) {\n throw new Error('@mastra/livekit: no fetch implementation available; pass `fetch` or run on Node ≥ 22.');\n }\n const url = `${trimTrailingSlash(baseUrl)}${apiPrefix}/agents/${agentId}/stream`;\n\n return ctx => {\n if (ctx.messages.length === 0) return null;\n\n // Reassigned per retry attempt (see the loop below) so a watchdog abort on one attempt can't\n // poison the next; `cancel()` always aborts whichever attempt is currently in flight.\n let currentAbortController: AbortController | undefined;\n let cancelled = false;\n // Accumulated as the turn streams so the post-turn hook sees what was actually produced.\n let replyText = '';\n const toolCalls: VoiceToolCall[] = [];\n let usage: VoiceTurnUsage | undefined;\n\n const emitTurnComplete = (interrupted: boolean) => {\n if (!onTurnComplete) return;\n const completeCtx: VoiceTurnCompleteContext = {\n ...ctx,\n result: { text: replyText, toolCalls, interrupted, usage },\n };\n Promise.resolve()\n .then(() => onTurnComplete(completeCtx))\n .catch(error => {\n console.warn('@mastra/livekit: onTurnComplete hook threw', error);\n });\n };\n\n const requestBody: Record<string, unknown> = {\n messages: ctx.messages,\n // The server schema requires a resource when memory is present; default it to the thread id,\n // matching the worker's own thread bootstrap.\n memory: ctx.memory\n ? { thread: ctx.memory.thread, resource: ctx.memory.resource ?? ctx.memory.thread }\n : undefined,\n requestContext: serializeRequestContext(ctx.requestContext),\n ...extraBody,\n };\n\n return new ReadableStream<string>({\n start: async controller => {\n // `retryable` is the LiveKit contract flag: true only before the first chunk is emitted, so a\n // voice turn is never replayed half-heard. It also gates the standalone connect-retry.\n let retryable = true;\n try {\n for (let attempt = 0; ; attempt++) {\n // A fresh controller per attempt: reusing one across retries meant a watchdog abort on an\n // earlier attempt left every subsequent attempt's fetch already-aborted before it started.\n const abortController = new AbortController();\n currentAbortController = abortController;\n let timedOut = false;\n let watchdog: ReturnType<typeof setTimeout> | undefined;\n const clearWatchdog = () => {\n if (watchdog) {\n clearTimeout(watchdog);\n watchdog = undefined;\n }\n };\n try {\n watchdog = setTimeout(() => {\n timedOut = true;\n abortController.abort();\n }, timeoutMs);\n (watchdog as { unref?: () => void }).unref?.();\n\n const resolvedHeaders = await resolveHeaders(headers);\n if (cancelled) {\n clearWatchdog();\n break;\n }\n const response = await fetchImpl(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'text/event-stream', ...resolvedHeaders },\n body: JSON.stringify(requestBody),\n signal: abortController.signal,\n });\n if (!response.ok) {\n const errorBody = await safeReadBody(response);\n throw new APIStatusError({\n message: `@mastra/livekit: Mastra agent stream request failed with status ${response.status}`,\n options: { statusCode: response.status, body: errorBody, retryable },\n });\n }\n if (!response.body) {\n throw new APIConnectionError({\n message: '@mastra/livekit: Mastra agent stream returned an empty response body',\n options: { retryable },\n });\n }\n\n for await (const chunk of readMastraSSE(\n response.body as unknown as globalThis.ReadableStream<Uint8Array>,\n abortController.signal,\n )) {\n if (cancelled) break;\n // First chunk: the server has committed to this generation — forbid any further\n // retry so the turn can't be replayed mid-stream. The watchdog is NOT cleared here:\n // lifecycle metadata (step-start, text-start, ...) isn't proof the model is\n // producing anything, and disarming on it would turn a post-metadata stall into\n // indefinite dead air. It disarms on the first sign of model output below.\n retryable = false;\n const payload = chunk.payload ?? {};\n switch (chunk.type) {\n case 'text-delta': {\n const text = payload.text;\n if (typeof text === 'string' && text) {\n clearWatchdog();\n replyText += text;\n controller.enqueue(text);\n }\n break;\n }\n case 'tool-call': {\n // A tool call is first-token progress too — the model committed to a tool run,\n // which may legitimately outlast the connect budget before any text streams.\n clearWatchdog();\n const toolCall: VoiceToolCall = {\n toolCallId: String(payload.toolCallId ?? ''),\n toolName: String(payload.toolName ?? ''),\n args: payload.args,\n };\n toolCalls.push(toolCall);\n // Observer hooks are customer code: a throw must not tear down an otherwise\n // healthy reply stream (same isolation as onTurnComplete).\n try {\n onToolCall?.(toolCall);\n } catch (error) {\n console.warn('@mastra/livekit: onToolCall hook threw', error);\n }\n if (toolFeedback) {\n let filler: string | undefined | void;\n try {\n filler = toolFeedback(toolCall);\n } catch (error) {\n console.warn('@mastra/livekit: toolFeedback hook threw', error);\n }\n if (filler) controller.enqueue(filler.endsWith(' ') ? filler : `${filler} `);\n }\n break;\n }\n case 'finish': {\n clearWatchdog();\n const output = payload.output as { usage?: unknown } | undefined;\n const turnUsage = mapTurnUsage(output?.usage);\n if (turnUsage) {\n usage = turnUsage;\n try {\n ctx.onUsage?.(turnUsage);\n } catch (error) {\n console.warn('@mastra/livekit: onUsage hook threw', error);\n }\n }\n break;\n }\n case 'tool-call-approval':\n case 'tool-call-suspended':\n throw new Error(HITL_UNSUPPORTED_MESSAGE);\n case 'error': {\n const error = payload.error;\n throw error instanceof Error ? error : new Error(String(error));\n }\n default:\n break; // ignore everything else (text-start, step-start, tool-result, ...)\n }\n }\n clearWatchdog();\n break; // success, or a clean barge-in break out of the SSE loop\n } catch (error) {\n clearWatchdog();\n if (cancelled) break; // barge-in: not a failure, emit interrupted below\n\n // Classify into the LiveKit error vocabulary. Application errors thrown after streaming\n // began (an `error` chunk, a HITL chunk) are not connection failures — propagate as-is.\n let typed: APIError;\n if (timedOut) {\n typed = new APITimeoutError({ options: { retryable } });\n } else if (error instanceof APIError) {\n typed = error;\n } else if (retryable) {\n typed = new APIConnectionError({ message: toMessage(error), options: { retryable } });\n } else {\n throw error;\n }\n if (typed.retryable && attempt < retries) continue;\n throw typed;\n }\n }\n if (!cancelled) controller.close();\n // Success or clean barge-in: the turn is done either way.\n emitTurnComplete(cancelled);\n } catch (error) {\n // Barge-in never reaches here (handled above); a real failure errors the stream and does\n // not fire onTurnComplete — same contract as the in-process generator.\n if (cancelled) {\n emitTurnComplete(true);\n return;\n }\n controller.error(error);\n }\n },\n cancel: () => {\n cancelled = true;\n currentAbortController?.abort();\n },\n });\n };\n}\n"]}
@@ -0,0 +1,55 @@
1
+ /** A consent decision captured from the caller during a call. */
2
+ export interface ConsentGrant {
3
+ /**
4
+ * The consent item, matching a key in the worker's `configuration.consentPolicy` (e.g.
5
+ * `'summaryStorage'`).
6
+ */
7
+ item: string;
8
+ /** `true` if the caller agreed, `false` if they declined. */
9
+ granted: boolean;
10
+ /** The caller the grant belongs to (the memory `resource`), when the call is memory-scoped. */
11
+ resourceId?: string;
12
+ /** The call thread the grant was captured on, when the call is memory-scoped. */
13
+ threadId?: string;
14
+ }
15
+ export interface ConsentToolOptions {
16
+ /**
17
+ * Persist the caller's decision to YOUR system of record (database, CRM, consent ledger). Called
18
+ * each time the caller answers a consent question — keep it quick, it runs inside the turn. This
19
+ * tool owns extracting the caller's identity from the tool execution context; you own storage, so
20
+ * consent lives in a durable, compliant place rather than an opaque plugin store. Read those
21
+ * grants back at `onCallEnd` (or before any consent-gated step) to enforce the requirement.
22
+ */
23
+ onGrant: (grant: ConsentGrant) => void | Promise<void>;
24
+ /** Tool id the agent calls. Defaults to `'recordConsent'`. */
25
+ id?: string;
26
+ /** Override the description the model sees when deciding to call the tool. */
27
+ description?: string;
28
+ /** Restrict the accepted consent items to this set (becomes an enum). Defaults to any string. */
29
+ items?: readonly string[];
30
+ }
31
+ /**
32
+ * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to
33
+ * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add
34
+ * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /
35
+ * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime
36
+ * grants live only where `onGrant` put them: enforce consent by reading them back from your own
37
+ * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared
38
+ * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the
39
+ * policy, never the grants).
40
+ *
41
+ * ```ts
42
+ * // agent tools
43
+ * recordConsent: createConsentTool({
44
+ * items: ['summaryStorage'],
45
+ * onGrant: async ({ item, granted, resourceId }) => {
46
+ * if (resourceId) await db.saveConsent(resourceId, item, granted);
47
+ * },
48
+ * }),
49
+ * ```
50
+ */
51
+ export declare function createConsentTool(options: ConsentToolOptions): import("@mastra/core/tools").Tool<{
52
+ item: string;
53
+ granted: boolean;
54
+ }, unknown, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, string, unknown>;
55
+ //# sourceMappingURL=consent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consent.d.ts","sourceRoot":"","sources":["../src/consent.ts"],"names":[],"mappings":"AAMA,iEAAiE;AACjE,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,6DAA6D;IAC7D,OAAO,EAAE,OAAO,CAAC;IACjB,+FAA+F;IAC/F,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iFAAiF;IACjF,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC;;;;;;OAMG;IACH,OAAO,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvD,8DAA8D;IAC9D,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,8EAA8E;IAC9E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iGAAiG;IACjG,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3B;AAQD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB;;;6HAiB5D"}
@@ -0,0 +1,50 @@
1
+ /** Details of the agent's decision to end the call, handed to {@link EndCallToolOptions.onEndCall}. */
2
+ export interface EndCallRequest {
3
+ /** Short reason the agent gave for ending the call, if any (e.g. "caller said goodbye"). */
4
+ reason?: string;
5
+ /** The caller the call belongs to (the memory `resource`), when the call is memory-scoped. */
6
+ resourceId?: string;
7
+ /** The call thread, when the call is memory-scoped. */
8
+ threadId?: string;
9
+ }
10
+ export interface EndCallToolOptions {
11
+ /**
12
+ * Tool id the agent calls to end the call. Must match the worker's
13
+ * `configuration.endCall.tool` (both default to `'endCall'`), since that's the name the worker
14
+ * watches for to hang up.
15
+ */
16
+ id?: string;
17
+ /** Override the description the model sees when deciding to call the tool. */
18
+ description?: string;
19
+ /**
20
+ * Optional bookkeeping hook, called when the agent invokes the tool (records the reason, marks
21
+ * the call resolved in your CRM, …). Runs inside the turn — keep it quick. It does NOT hang up
22
+ * the call; the worker does that once the agent's final words finish playing. The tool reads the
23
+ * caller's identity from its execution context and passes it here.
24
+ */
25
+ onEndCall?: (request: EndCallRequest) => void | Promise<void>;
26
+ }
27
+ /**
28
+ * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the
29
+ * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional
30
+ * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the
31
+ * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the
32
+ * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).
33
+ * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on
34
+ * the agent and workflow reply paths alike.
35
+ *
36
+ * ```ts
37
+ * // agent tools
38
+ * endCall: createEndCallTool({
39
+ * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),
40
+ * }),
41
+ * // worker
42
+ * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });
43
+ * ```
44
+ */
45
+ export declare function createEndCallTool(options?: EndCallToolOptions): import("@mastra/core/tools").Tool<{
46
+ reason?: string | null | undefined;
47
+ }, {
48
+ ended: boolean;
49
+ }, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, string, unknown>;
50
+ //# sourceMappingURL=end-call.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"end-call.d.ts","sourceRoot":"","sources":["../src/end-call.ts"],"names":[],"mappings":"AAMA,uGAAuG;AACvG,MAAM,WAAW,cAAc;IAC7B,4FAA4F;IAC5F,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,8EAA8E;IAC9E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/D;AAUD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,kBAAuB;;;;oHA0BjE"}
package/dist/index.cjs CHANGED
@@ -4,6 +4,8 @@ var chunkMWTEZOBS_cjs = require('./chunk-MWTEZOBS.cjs');
4
4
  var crypto = require('crypto');
5
5
  var protocol = require('@livekit/protocol');
6
6
  var livekitServerSdk = require('livekit-server-sdk');
7
+ var tools = require('@mastra/core/tools');
8
+ var zod = require('zod');
7
9
 
8
10
  function stringField(body, key) {
9
11
  const value = body[key];
@@ -86,6 +88,48 @@ async function dispatchVoiceSession(options) {
86
88
  metadata: chunkMWTEZOBS_cjs.serializeSessionMetadata(options.metadata ?? {})
87
89
  });
88
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.";
92
+ 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
+ });
109
+ }
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.";
111
+ 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
+ });
132
+ }
89
133
 
90
134
  Object.defineProperty(exports, "DEFAULT_LIVEKIT_AGENT_NAME", {
91
135
  enumerable: true,
@@ -99,6 +143,8 @@ Object.defineProperty(exports, "serializeSessionMetadata", {
99
143
  enumerable: true,
100
144
  get: function () { return chunkMWTEZOBS_cjs.serializeSessionMetadata; }
101
145
  });
146
+ exports.createConsentTool = createConsentTool;
147
+ exports.createEndCallTool = createEndCallTool;
102
148
  exports.dispatchVoiceSession = dispatchVoiceSession;
103
149
  exports.liveKitConnectionRoute = liveKitConnectionRoute;
104
150
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/routes.ts","../src/dispatch.ts"],"names":["randomUUID","AccessToken","RoomConfiguration","RoomAgentDispatch","DEFAULT_LIVEKIT_AGENT_NAME","serializeSessionMetadata","AgentDispatchClient"],"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;AAC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,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,IAAU,OAAA,CAAQ,GAAA,CAAI,eAAA;AAC7C,EAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,GAAA,CAAI,kBAAA;AACnD,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,MAAM,IAAI,MAAM,6EAA6E,CAAA;AAAA,EAC/F;AACA,EAAA,IAAI,CAAC,MAAA,IAAU,CAAC,SAAA,EAAW;AACzB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,MAAM,SAAS,IAAIC,oCAAA,CAAoB,UAAU,SAAS,CAAA,EAAG,QAAQ,SAAS,CAAA;AAC9E,EAAA,OAAO,OAAO,cAAA,CAAe,OAAA,CAAQ,QAAA,EAAU,OAAA,CAAQ,aAAaF,4CAAA,EAA4B;AAAA,IAC9F,QAAA,EAAUC,0CAAA,CAAyB,OAAA,CAAQ,QAAA,IAAY,EAAE;AAAA,GAC1D,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"]}
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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AI;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"]}
package/dist/index.d.ts CHANGED
@@ -6,5 +6,9 @@ export { serializeSessionMetadata } from './metadata.js';
6
6
  export type { LiveKitSessionMetadata } from './metadata.js';
7
7
  export { pipeAgentReplyToWriter } from './workflow-generator.js';
8
8
  export type { AgentReplyStreamLike } from './workflow-generator.js';
9
+ export { createConsentTool } from './consent.js';
10
+ export type { ConsentGrant, ConsentToolOptions } from './consent.js';
11
+ export { createEndCallTool } from './end-call.js';
12
+ export type { EndCallRequest, EndCallToolOptions } from './end-call.js';
9
13
  export { DEFAULT_LIVEKIT_AGENT_NAME } from './constants.js';
10
14
  //# 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,0BAA0B,EAAE,MAAM,aAAa,CAAC"}
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;AAC9C,YAAY,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -3,6 +3,8 @@ export { DEFAULT_LIVEKIT_AGENT_NAME, pipeAgentReplyToWriter, serializeSessionMet
3
3
  import { randomUUID } from 'crypto';
4
4
  import { RoomConfiguration, RoomAgentDispatch } from '@livekit/protocol';
5
5
  import { AgentDispatchClient, AccessToken } from 'livekit-server-sdk';
6
+ import { createTool } from '@mastra/core/tools';
7
+ import { z } from 'zod';
6
8
 
7
9
  function stringField(body, key) {
8
10
  const value = body[key];
@@ -85,7 +87,49 @@ async function dispatchVoiceSession(options) {
85
87
  metadata: serializeSessionMetadata(options.metadata ?? {})
86
88
  });
87
89
  }
90
+ 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
+ function createConsentTool(options) {
92
+ const items = options.items;
93
+ const itemSchema = items && items.length > 0 ? z.enum([...items]) : z.string();
94
+ return createTool({
95
+ id: options.id ?? "recordConsent",
96
+ description: options.description ?? DEFAULT_DESCRIPTION,
97
+ inputSchema: z.object({
98
+ item: itemSchema.describe(
99
+ "The consent item the caller is answering for (matches the deployment's required consents)."
100
+ ),
101
+ granted: z.boolean().describe("True if the caller agreed, false if they declined.")
102
+ }),
103
+ execute: async ({ item, granted }, { agent }) => {
104
+ await options.onGrant({ item, granted, resourceId: agent?.resourceId, threadId: agent?.threadId });
105
+ return { recorded: true, item, granted };
106
+ }
107
+ });
108
+ }
109
+ 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.";
110
+ function createEndCallTool(options = {}) {
111
+ return createTool({
112
+ id: options.id ?? "endCall",
113
+ description: options.description ?? DEFAULT_DESCRIPTION2,
114
+ inputSchema: z.object({
115
+ reason: z.string().nullish().describe('Short reason the call is ending, e.g. "caller said goodbye" or "task complete".')
116
+ }),
117
+ outputSchema: z.object({ ended: z.boolean() }),
118
+ execute: async ({ reason }, { agent }) => {
119
+ try {
120
+ await options.onEndCall?.({
121
+ reason: reason ?? void 0,
122
+ resourceId: agent?.resourceId,
123
+ threadId: agent?.threadId
124
+ });
125
+ } catch (error) {
126
+ console.warn("@mastra/livekit: onEndCall hook threw", error);
127
+ }
128
+ return { ended: true };
129
+ }
130
+ });
131
+ }
88
132
 
89
- export { dispatchVoiceSession, liveKitConnectionRoute };
133
+ export { createConsentTool, createEndCallTool, dispatchVoiceSession, liveKitConnectionRoute };
90
134
  //# sourceMappingURL=index.js.map
91
135
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/routes.ts","../src/dispatch.ts"],"names":[],"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,MAAM,CAAA,CAAE,GAAA,CAC3C,MAAK,CACL,IAAA;AAAA,MAAK,CAAC,MAAA,KACL,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,IAAY,CAAC,KAAA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A,IAAU,CAAC,SAAA,EAAW;AACzB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,MAAM,SAAS,IAAI,mBAAA,CAAoB,UAAU,SAAS,CAAA,EAAG,QAAQ,SAAS,CAAA;AAC9E,EAAA,OAAO,OAAO,cAAA,CAAe,OAAA,CAAQ,QAAA,EAAU,OAAA,CAAQ,aAAa,0BAAA,EAA4B;AAAA,IAC9F,QAAA,EAAU,wBAAA,CAAyB,OAAA,CAAQ,QAAA,IAAY,EAAE;AAAA,GAC1D,CAAA;AACH","file":"index.js","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"]}
1
+ {"version":3,"sources":["../src/routes.ts","../src/dispatch.ts","../src/consent.ts","../src/end-call.ts"],"names":["DEFAULT_DESCRIPTION","createTool","z"],"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,IAA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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"]}