@mastra/livekit 0.5.1-alpha.0 → 0.5.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["RoomServiceClient","RoomEgress","serializeSessionMetadata","AgentDispatchClient","AccessToken","RoomConfiguration","RoomAgentDispatch","serializeSessionMetadata","z","DEFAULT_DESCRIPTION","z","z"],"sources":["../src/recording.ts","../src/dispatch.ts","../src/routes.ts","../src/recording-route.ts","../src/consent.ts","../src/end-call.ts"],"sourcesContent":["import { RoomEgress, RoomServiceClient } from 'livekit-server-sdk';\n\n/**\n * LiveKit auto-egress settings, accepted as a plain object or a RoomEgress instance.\n * Use `room.audioOnly` and `room.fileOutputs` for a single mixed audio recording.\n * Storage credentials belong here on the server, never in session metadata or tokens.\n */\nexport type LiveKitRecordingOptions = NonNullable<ConstructorParameters<typeof RoomEgress>[0]>;\n\n/** A recording-enabled session cannot reuse an existing LiveKit room. */\nexport class LiveKitRecordingRoomConflictError extends Error {\n readonly roomName: string;\n\n constructor(roomName: string) {\n super(\n `@mastra/livekit: recording requires a new room, but room \"${roomName}\" already exists. Use a fresh room name.`,\n );\n this.name = 'LiveKitRecordingRoomConflictError';\n this.roomName = roomName;\n }\n}\n\n/** Creates a fresh room with recording configured before any agent or caller joins. */\nexport async function createRecordingRoom(options: {\n roomName: string;\n serverUrl: string;\n apiKey: string;\n apiSecret: string;\n recording: LiveKitRecordingOptions;\n}) {\n const { recording, roomName } = options;\n if (!recording.room && !recording.participant && !recording.tracks) {\n throw new Error('@mastra/livekit: recording must configure at least one of room, participant, or tracks.');\n }\n\n const client = new RoomServiceClient(options.serverUrl.replace(/^ws/, 'http'), options.apiKey, options.apiSecret);\n // CreateRoom reuses existing rooms without applying room-composite auto-egress.\n // This preflight is not atomic: callers must use a fresh name and serialize room creation.\n const rooms = await client.listRooms([roomName]);\n if (rooms.length > 0) {\n throw new LiveKitRecordingRoomConflictError(roomName);\n }\n\n return client.createRoom({ name: roomName, egress: new RoomEgress(recording) });\n}\n","import { AgentDispatchClient } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { createRecordingRoom } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\nexport interface DispatchVoiceSessionOptions {\n /**\n * Room to dispatch the agent into (created on demand). With recording enabled, use a unique\n * name for each call. An existing room throws LiveKitRecordingRoomConflictError.\n */\n roomName: string;\n /** Must match the worker's `agentName`. Defaults to `'mastra-voice'`. */\n agentName?: string;\n metadata?: LiveKitSessionMetadata;\n /** Create a fresh room with automatic recording before dispatch. Omit to keep dispatch-only behavior. */\n recording?: LiveKitRecordingOptions;\n /** Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n}\n\nfunction toHttpUrl(url: string): string {\n return url.replace(/^ws/, 'http');\n}\n\n/**\n * Programmatically dispatches a Mastra voice agent into a LiveKit room — for\n * server-initiated sessions such as outbound calls or joining an existing room.\n */\nexport async function dispatchVoiceSession(options: DispatchVoiceSessionOptions) {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl) {\n throw new Error('@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.');\n }\n if (!apiKey || !apiSecret) {\n throw new Error(\n '@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.',\n );\n }\n const metadata = serializeSessionMetadata(options.metadata ?? {});\n if (options.recording !== undefined) {\n await createRecordingRoom({\n roomName: options.roomName,\n serverUrl,\n apiKey,\n apiSecret,\n recording: options.recording,\n });\n }\n const client = new AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret);\n return client.createDispatch(options.roomName, options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME, {\n metadata,\n });\n}\n","import { RoomAgentDispatch, RoomConfiguration } from '@livekit/protocol';\nimport type { ContextWithMastra, ApiRoute } from '@mastra/core/server';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { dispatchVoiceSession } from './dispatch';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { LiveKitRecordingRoomConflictError } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\n/** Response body of the connection-details route. Matches LiveKit's frontend starter contract. */\nexport interface LiveKitConnectionDetails {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n}\n\nexport interface ConnectionRequestArgs {\n body: Record<string, unknown>;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitConnectionRouteOptions {\n /**\n * Route path. Defaults to `/voice/livekit/connection-details`. Mastra reserves the\n * `/api` prefix for built-in routes, so custom paths must not start with `/api`.\n */\n path?: string;\n /** LiveKit server URL (`wss://...`). Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n /** LiveKit agent name for explicit dispatch. Must match the worker's `agentName`. */\n agentName?: string;\n /** Token time-to-live. Defaults to `'15m'`. */\n ttl?: string | number;\n /** Defaults to `true` (Mastra custom routes require auth unless opted out). */\n requiresAuth?: boolean;\n /**\n * Room name or a function that derives one from the request. Defaults to a generated name.\n * With recording enabled, use a unique name for each call. An existing room returns HTTP 409\n * before agent dispatch or token issuance.\n */\n roomName?: string | ((args: ConnectionRequestArgs) => string);\n participantIdentity?: string | ((args: ConnectionRequestArgs) => string);\n /**\n * Session metadata delivered to the worker via agent dispatch. Defaults to passing\n * through `agentId`, `threadId`, and `resourceId` from the request body.\n */\n metadata?: (args: ConnectionRequestArgs) => LiveKitSessionMetadata | Promise<LiveKitSessionMetadata>;\n /**\n * Create a fresh room with automatic recording and dispatch the agent before returning a token.\n * The server-side callback receives the resolved room name; return undefined to skip recording.\n * Recording settings and storage credentials are never included in the participant token.\n */\n recording?:\n | LiveKitRecordingOptions\n | ((\n args: ConnectionRequestArgs & { roomName: string },\n ) => LiveKitRecordingOptions | undefined | Promise<LiveKitRecordingOptions | undefined>);\n}\n\nfunction stringField(body: Record<string, unknown>, key: string): string | undefined {\n const value = body[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/**\n * An ApiRoute for `server.apiRoutes` that mints a LiveKit access token with the Mastra\n * voice agent dispatched into the room. Frontends call it to join a voice session:\n *\n * ```ts\n * export const mastra = new Mastra({\n * agents: { support },\n * server: { apiRoutes: [liveKitConnectionRoute({ agentName: 'mastra-voice' })] },\n * });\n * ```\n */\nexport function liveKitConnectionRoute(options: LiveKitConnectionRouteOptions = {}): ApiRoute {\n const handler = async (c: ContextWithMastra) => {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl || !apiKey || !apiSecret) {\n return c.json(\n {\n error:\n 'LiveKit is not configured. Set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET ' +\n '(or pass serverUrl/apiKey/apiSecret to liveKitConnectionRoute).',\n },\n 500,\n );\n }\n\n const body: Record<string, unknown> = await c.req\n .json()\n .then((parsed: unknown) =>\n parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {},\n )\n .catch(() => ({}));\n const args: ConnectionRequestArgs = { body, context: c };\n\n const metadata: LiveKitSessionMetadata = options.metadata\n ? await options.metadata(args)\n : {\n agentId: stringField(body, 'agentId'),\n threadId: stringField(body, 'threadId'),\n resourceId: stringField(body, 'resourceId'),\n };\n\n const roomName =\n typeof options.roomName === 'function'\n ? options.roomName(args)\n : (options.roomName ?? `mastra-voice-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n const identity =\n typeof options.participantIdentity === 'function'\n ? options.participantIdentity(args)\n : (options.participantIdentity ?? metadata.resourceId ?? `user-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n // One memory thread per room unless the caller pins a thread explicitly.\n metadata.threadId ??= roomName;\n\n const recording =\n typeof options.recording === 'function' ? await options.recording({ ...args, roomName }) : options.recording;\n if (recording !== undefined) {\n try {\n await dispatchVoiceSession({\n roomName,\n agentName: options.agentName,\n metadata,\n serverUrl,\n apiKey,\n apiSecret,\n recording,\n });\n } catch (error) {\n if (error instanceof LiveKitRecordingRoomConflictError) {\n return c.json({ error: 'Recording requires a new room. Use a unique roomName for each call.' }, 409);\n }\n throw error;\n }\n }\n\n const token = new AccessToken(apiKey, apiSecret, { identity, ttl: options.ttl ?? '15m' });\n token.addGrant({\n room: roomName,\n roomJoin: true,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n });\n // A pre-created room needs explicit dispatch; token roomConfig only applies at room creation.\n if (recording === undefined) {\n token.roomConfig = new RoomConfiguration({\n agents: [\n new RoomAgentDispatch({\n agentName: options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME,\n metadata: serializeSessionMetadata(metadata),\n }),\n ],\n });\n }\n\n const details: LiveKitConnectionDetails = {\n serverUrl,\n roomName,\n participantName: identity,\n participantToken: await token.toJwt(),\n };\n return c.json(details);\n };\n\n return {\n // Studio calls this default path and /api/system/packages reports it — change all three together.\n path: options.path ?? '/voice/livekit/connection-details',\n method: 'POST',\n requiresAuth: options.requiresAuth,\n handler,\n } as ApiRoute;\n}\n","import type { ApiRoute, ContextWithMastra } from '@mastra/core/server';\nimport type { SpanRecord } from '@mastra/core/storage';\nimport { z } from 'zod/v4';\nimport type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types';\n\nconst traceIdSchema = z.string().min(1).max(256);\nexport const recordingSchema = z.object({\n url: z.url({ protocol: /^https?$/ }),\n expiresAt: z.string().datetime().optional(),\n}) satisfies z.ZodType<LiveKitRecording>;\n\nexport interface LiveKitRecordingResolverArgs {\n traceId: string;\n /** Taken from the stored voice call span, never from the browser request. */\n roomName: string;\n span: SpanRecord;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitRecordingRouteOptions {\n /** Studio discovers this route at its default path: /voice/livekit/recordings/:traceId. */\n path?: string;\n /** Defaults to true. Only disable for a local demo. */\n requiresAuth?: boolean;\n /** Required trace-specific access policy. Only true permits trace lookup and URL resolution. */\n authorize: (args: { traceId: string; context: ContextWithMastra }) => boolean | Promise<boolean>;\n /** Return a playable URL, or undefined if the recording is not available yet. */\n resolveRecording: (args: LiveKitRecordingResolverArgs) => Promise<LiveKitRecording | undefined>;\n}\n\n/** Resolves a voice call trace to a recording without persisting signed URLs in traces. */\nexport function liveKitRecordingRoute(options: LiveKitRecordingRouteOptions): ApiRoute {\n if (typeof options.authorize !== 'function') {\n throw new Error('liveKitRecordingRoute requires an authorize callback.');\n }\n return {\n path: options.path ?? '/voice/livekit/recordings/:traceId',\n method: 'GET',\n requiresAuth: options.requiresAuth ?? true,\n handler: async (context: ContextWithMastra) => {\n context.header('Cache-Control', 'no-store');\n const input = traceIdSchema.safeParse(context.req.param('traceId'));\n if (!input.success) return context.json({ error: 'A valid trace ID is required.' }, 400);\n const traceId = input.data;\n try {\n if ((await options.authorize({ traceId, context })) !== true) {\n return context.json({ error: 'Access to this recording is denied.' }, 403);\n }\n const store = await context.get('mastra').getStorage()?.getStore('observability');\n if (!store) return context.json({ error: 'Trace storage is not configured.' }, 503);\n const trace = await store.getTrace({ traceId });\n const calls =\n trace?.spans.filter(\n span =>\n span.name === 'voice call' &&\n typeof span.metadata?.roomName === 'string' &&\n span.metadata.roomName.length > 0,\n ) ?? [];\n if (!calls.length) return context.json({ error: 'Voice call trace not found.' }, 404);\n if (calls.length !== 1) return context.json({ error: 'This trace contains multiple voice calls.' }, 409);\n const span = calls[0]!;\n const roomName = span.metadata?.roomName;\n if (typeof roomName !== 'string') return context.json({ error: 'Voice call trace not found.' }, 404);\n const recording = await options.resolveRecording({ traceId, roomName, span, context });\n if (!recording) return context.json({ status: 'unavailable' } satisfies LiveKitRecordingResponse);\n // Validate and strip extra fields so storage credentials cannot accidentally become response fields.\n const result = recordingSchema.safeParse(recording);\n if (!result.success) return context.json({ error: 'Unable to load the call recording.' }, 502);\n return context.json({ status: 'ready', ...result.data } satisfies LiveKitRecordingResponse);\n } catch {\n // Storage/provider errors can contain credentials or signed request details.\n return context.json({ error: 'Unable to load the call recording.' }, 502);\n }\n },\n };\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** A consent decision captured from the caller during a call. */\nexport interface ConsentGrant {\n /**\n * The consent item, matching a key in the worker's `configuration.consentPolicy` (e.g.\n * `'summaryStorage'`).\n */\n item: string;\n /** `true` if the caller agreed, `false` if they declined. */\n granted: boolean;\n /** The caller the grant belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread the grant was captured on, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface ConsentToolOptions {\n /**\n * Persist the caller's decision to YOUR system of record (database, CRM, consent ledger). Called\n * each time the caller answers a consent question — keep it quick, it runs inside the turn. This\n * tool owns extracting the caller's identity from the tool execution context; you own storage, so\n * consent lives in a durable, compliant place rather than an opaque plugin store. Read those\n * grants back at `onCallEnd` (or before any consent-gated step) to enforce the requirement.\n */\n onGrant: (grant: ConsentGrant) => void | Promise<void>;\n /** Tool id the agent calls. Defaults to `'recordConsent'`. */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /** Restrict the accepted consent items to this set (becomes an enum). Defaults to any string. */\n items?: readonly string[];\n}\n\nconst DEFAULT_DESCRIPTION =\n \"Record the caller's consent decision for a data-processing item (for example, storing a summary \" +\n 'of the call). Call this as soon as the caller answers a consent question: granted = true if they ' +\n 'agree, false if they decline. Do not proceed with an activity that requires consent until you ' +\n 'have recorded the caller granting it.';\n\n/**\n * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to\n * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add\n * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /\n * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime\n * grants live only where `onGrant` put them: enforce consent by reading them back from your own\n * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared\n * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the\n * policy, never the grants).\n *\n * ```ts\n * // agent tools\n * recordConsent: createConsentTool({\n * items: ['summaryStorage'],\n * onGrant: async ({ item, granted, resourceId }) => {\n * if (resourceId) await db.saveConsent(resourceId, item, granted);\n * },\n * }),\n * ```\n */\nexport function createConsentTool(options: ConsentToolOptions) {\n const items = options.items;\n const itemSchema = items && items.length > 0 ? z.enum([...items] as [string, ...string[]]) : z.string();\n return createTool({\n id: options.id ?? 'recordConsent',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n item: itemSchema.describe(\n \"The consent item the caller is answering for (matches the deployment's required consents).\",\n ),\n granted: z.boolean().describe('True if the caller agreed, false if they declined.'),\n }),\n execute: async ({ item, granted }, { agent }) => {\n await options.onGrant({ item, granted, resourceId: agent?.resourceId, threadId: agent?.threadId });\n return { recorded: true as const, item, granted };\n },\n });\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** Details of the agent's decision to end the call, handed to {@link EndCallToolOptions.onEndCall}. */\nexport interface EndCallRequest {\n /** Short reason the agent gave for ending the call, if any (e.g. \"caller said goodbye\"). */\n reason?: string;\n /** The caller the call belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface EndCallToolOptions {\n /**\n * Tool id the agent calls to end the call. Must match the worker's\n * `configuration.endCall.tool` (both default to `'endCall'`), since that's the name the worker\n * watches for to hang up.\n */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /**\n * Optional bookkeeping hook, called when the agent invokes the tool (records the reason, marks\n * the call resolved in your CRM, …). Runs inside the turn — keep it quick. It does NOT hang up\n * the call; the worker does that once the agent's final words finish playing. The tool reads the\n * caller's identity from its execution context and passes it here.\n */\n onEndCall?: (request: EndCallRequest) => void | Promise<void>;\n}\n\nconst DEFAULT_DESCRIPTION =\n 'End the phone call. Call this only after you have said goodbye and there is nothing left to do — ' +\n 'for example the caller says goodbye, or the task is complete and you have wrapped up. Say your ' +\n 'closing line first, then call this as your final action; the call hangs up once your words finish ' +\n 'playing. Your closing line must be a final statement, never a question — if you are asking the ' +\n 'caller anything (for example whether they need anything else), do NOT call this in that reply; ' +\n 'wait for their answer. Do not call it if the caller still needs something.';\n\n/**\n * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the\n * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional\n * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the\n * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the\n * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).\n * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on\n * the agent and workflow reply paths alike.\n *\n * ```ts\n * // agent tools\n * endCall: createEndCallTool({\n * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),\n * }),\n * // worker\n * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });\n * ```\n */\nexport function createEndCallTool(options: EndCallToolOptions = {}) {\n return createTool({\n id: options.id ?? 'endCall',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n reason: z\n .string()\n .nullish()\n .describe('Short reason the call is ending, e.g. \"caller said goodbye\" or \"task complete\".'),\n }),\n outputSchema: z.object({ ended: z.boolean() }),\n execute: async ({ reason }, { agent }) => {\n try {\n await options.onEndCall?.({\n reason: reason ?? undefined,\n resourceId: agent?.resourceId,\n threadId: agent?.threadId,\n });\n } catch (error) {\n // Bookkeeping is best-effort — the tool must still signal `{ ended: true }` so the worker's\n // end-call detector runs and the call actually hangs up.\n console.warn('@mastra/livekit: onEndCall hook threw', error);\n }\n return { ended: true as const };\n },\n });\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,oCAAb,cAAuD,MAAM;CAC3D;CAEA,YAAY,UAAkB;EAC5B,MACE,6DAA6D,SAAS,yCACxE;EACA,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;AAGA,eAAsB,oBAAoB,SAMvC;CACD,MAAM,EAAE,WAAW,aAAa;CAChC,IAAI,CAAC,UAAU,QAAQ,CAAC,UAAU,eAAe,CAAC,UAAU,QAC1D,MAAM,IAAI,MAAM,yFAAyF;CAG3G,MAAM,SAAS,IAAIA,mBAAAA,kBAAkB,QAAQ,UAAU,QAAQ,OAAO,MAAM,GAAG,QAAQ,QAAQ,QAAQ,SAAS;CAIhH,KAAI,MADgB,OAAO,UAAU,CAAC,QAAQ,CAAC,EAAA,CACrC,SAAS,GACjB,MAAM,IAAI,kCAAkC,QAAQ;CAGtD,OAAO,OAAO,WAAW;EAAE,MAAM;EAAU,QAAQ,IAAIC,mBAAAA,WAAW,SAAS;CAAE,CAAC;AAChF;;;AClBA,SAAS,UAAU,KAAqB;CACtC,OAAO,IAAI,QAAQ,OAAO,MAAM;AAClC;;;;;AAMA,eAAsB,qBAAqB,SAAsC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AAC,SAAS,oDAAoD;EACpF,CAAC;EACD,SAAS,OAAO,EAAE,MAAM,WAAW,EAAE,YAAY;GAC/C,MAAM,QAAQ,QAAQ;IAAE;IAAM;IAAS,YAAY,OAAO;IAAY,UAAU,OAAO;GAAS,CAAC;GACjG,OAAO;IAAE,UAAU;IAAe;IAAM;GAAQ;EAClD;CACF,CAAC;AACH;;;AC/CA,MAAM,sBACJ;;;;;;;;;;;;;;;;;;;AAyBF,SAAgB,kBAAkB,UAA8B,CAAC,GAAG;CAClE,QAAA,GAAA,mBAAA,WAAA,CAAkB;EAChB,IAAI,QAAQ,MAAM;EAClB,aAAa,QAAQ,eAAe;EACpC,aAAaC,IAAAA,EAAE,OAAO,EACpB,QAAQA,IAAAA,EACL,OAAO,CAAC,CACR,QAAQ,CAAC,CACT,SAAS,qFAAiF,EAC/F,CAAC;EACD,cAAcA,IAAAA,EAAE,OAAO,EAAE,OAAOA,IAAAA,EAAE,QAAQ,EAAE,CAAC;EAC7C,SAAS,OAAO,EAAE,UAAU,EAAE,YAAY;GACxC,IAAI;IACF,MAAM,QAAQ,YAAY;KACxB,QAAQ,UAAU,KAAA;KAClB,YAAY,OAAO;KACnB,UAAU,OAAO;IACnB,CAAC;GACH,SAAS,OAAO;IAGd,QAAQ,KAAK,yCAAyC,KAAK;GAC7D;GACA,OAAO,EAAE,OAAO,KAAc;EAChC;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"index.cjs","names":["RoomServiceClient","RoomEgress","serializeSessionMetadata","AgentDispatchClient","AccessToken","RoomConfiguration","RoomAgentDispatch","serializeSessionMetadata","z","DEFAULT_DESCRIPTION","z","createTool","createTool","z"],"sources":["../src/recording.ts","../src/dispatch.ts","../src/routes.ts","../src/recording-route.ts","../src/consent.ts","../src/end-call.ts"],"sourcesContent":["import { RoomEgress, RoomServiceClient } from 'livekit-server-sdk';\n\n/**\n * LiveKit auto-egress settings, accepted as a plain object or a RoomEgress instance.\n * Use `room.audioOnly` and `room.fileOutputs` for a single mixed audio recording.\n * Storage credentials belong here on the server, never in session metadata or tokens.\n */\nexport type LiveKitRecordingOptions = NonNullable<ConstructorParameters<typeof RoomEgress>[0]>;\n\n/** A recording-enabled session cannot reuse an existing LiveKit room. */\nexport class LiveKitRecordingRoomConflictError extends Error {\n readonly roomName: string;\n\n constructor(roomName: string) {\n super(\n `@mastra/livekit: recording requires a new room, but room \"${roomName}\" already exists. Use a fresh room name.`,\n );\n this.name = 'LiveKitRecordingRoomConflictError';\n this.roomName = roomName;\n }\n}\n\n/** Creates a fresh room with recording configured before any agent or caller joins. */\nexport async function createRecordingRoom(options: {\n roomName: string;\n serverUrl: string;\n apiKey: string;\n apiSecret: string;\n recording: LiveKitRecordingOptions;\n}) {\n const { recording, roomName } = options;\n if (!recording.room && !recording.participant && !recording.tracks) {\n throw new Error('@mastra/livekit: recording must configure at least one of room, participant, or tracks.');\n }\n\n const client = new RoomServiceClient(options.serverUrl.replace(/^ws/, 'http'), options.apiKey, options.apiSecret);\n // CreateRoom reuses existing rooms without applying room-composite auto-egress.\n // This preflight is not atomic: callers must use a fresh name and serialize room creation.\n const rooms = await client.listRooms([roomName]);\n if (rooms.length > 0) {\n throw new LiveKitRecordingRoomConflictError(roomName);\n }\n\n return client.createRoom({ name: roomName, egress: new RoomEgress(recording) });\n}\n","import { AgentDispatchClient } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { createRecordingRoom } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\nexport interface DispatchVoiceSessionOptions {\n /**\n * Room to dispatch the agent into (created on demand). With recording enabled, use a unique\n * name for each call. An existing room throws LiveKitRecordingRoomConflictError.\n */\n roomName: string;\n /** Must match the worker's `agentName`. Defaults to `'mastra-voice'`. */\n agentName?: string;\n metadata?: LiveKitSessionMetadata;\n /** Create a fresh room with automatic recording before dispatch. Omit to keep dispatch-only behavior. */\n recording?: LiveKitRecordingOptions;\n /** Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n}\n\nfunction toHttpUrl(url: string): string {\n return url.replace(/^ws/, 'http');\n}\n\n/**\n * Programmatically dispatches a Mastra voice agent into a LiveKit room — for\n * server-initiated sessions such as outbound calls or joining an existing room.\n */\nexport async function dispatchVoiceSession(options: DispatchVoiceSessionOptions) {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl) {\n throw new Error('@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.');\n }\n if (!apiKey || !apiSecret) {\n throw new Error(\n '@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.',\n );\n }\n const metadata = serializeSessionMetadata(options.metadata ?? {});\n if (options.recording !== undefined) {\n await createRecordingRoom({\n roomName: options.roomName,\n serverUrl,\n apiKey,\n apiSecret,\n recording: options.recording,\n });\n }\n const client = new AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret);\n return client.createDispatch(options.roomName, options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME, {\n metadata,\n });\n}\n","import { RoomAgentDispatch, RoomConfiguration } from '@livekit/protocol';\nimport type { ContextWithMastra, ApiRoute } from '@mastra/core/server';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { dispatchVoiceSession } from './dispatch';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { LiveKitRecordingRoomConflictError } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\n/** Response body of the connection-details route. Matches LiveKit's frontend starter contract. */\nexport interface LiveKitConnectionDetails {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n}\n\nexport interface ConnectionRequestArgs {\n body: Record<string, unknown>;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitConnectionRouteOptions {\n /**\n * Route path. Defaults to `/voice/livekit/connection-details`. Mastra reserves the\n * `/api` prefix for built-in routes, so custom paths must not start with `/api`.\n */\n path?: string;\n /** LiveKit server URL (`wss://...`). Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n /** LiveKit agent name for explicit dispatch. Must match the worker's `agentName`. */\n agentName?: string;\n /** Token time-to-live. Defaults to `'15m'`. */\n ttl?: string | number;\n /** Defaults to `true` (Mastra custom routes require auth unless opted out). */\n requiresAuth?: boolean;\n /**\n * Room name or a function that derives one from the request. Defaults to a generated name.\n * With recording enabled, use a unique name for each call. An existing room returns HTTP 409\n * before agent dispatch or token issuance.\n */\n roomName?: string | ((args: ConnectionRequestArgs) => string);\n participantIdentity?: string | ((args: ConnectionRequestArgs) => string);\n /**\n * Session metadata delivered to the worker via agent dispatch. Defaults to passing\n * through `agentId`, `threadId`, and `resourceId` from the request body.\n */\n metadata?: (args: ConnectionRequestArgs) => LiveKitSessionMetadata | Promise<LiveKitSessionMetadata>;\n /**\n * Create a fresh room with automatic recording and dispatch the agent before returning a token.\n * The server-side callback receives the resolved room name; return undefined to skip recording.\n * Recording settings and storage credentials are never included in the participant token.\n */\n recording?:\n | LiveKitRecordingOptions\n | ((\n args: ConnectionRequestArgs & { roomName: string },\n ) => LiveKitRecordingOptions | undefined | Promise<LiveKitRecordingOptions | undefined>);\n}\n\nfunction stringField(body: Record<string, unknown>, key: string): string | undefined {\n const value = body[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/**\n * An ApiRoute for `server.apiRoutes` that mints a LiveKit access token with the Mastra\n * voice agent dispatched into the room. Frontends call it to join a voice session:\n *\n * ```ts\n * export const mastra = new Mastra({\n * agents: { support },\n * server: { apiRoutes: [liveKitConnectionRoute({ agentName: 'mastra-voice' })] },\n * });\n * ```\n */\nexport function liveKitConnectionRoute(options: LiveKitConnectionRouteOptions = {}): ApiRoute {\n const handler = async (c: ContextWithMastra) => {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl || !apiKey || !apiSecret) {\n return c.json(\n {\n error:\n 'LiveKit is not configured. Set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET ' +\n '(or pass serverUrl/apiKey/apiSecret to liveKitConnectionRoute).',\n },\n 500,\n );\n }\n\n const body: Record<string, unknown> = await c.req\n .json()\n .then((parsed: unknown) =>\n parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {},\n )\n .catch(() => ({}));\n const args: ConnectionRequestArgs = { body, context: c };\n\n const metadata: LiveKitSessionMetadata = options.metadata\n ? await options.metadata(args)\n : {\n agentId: stringField(body, 'agentId'),\n threadId: stringField(body, 'threadId'),\n resourceId: stringField(body, 'resourceId'),\n };\n\n const roomName =\n typeof options.roomName === 'function'\n ? options.roomName(args)\n : (options.roomName ?? `mastra-voice-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n const identity =\n typeof options.participantIdentity === 'function'\n ? options.participantIdentity(args)\n : (options.participantIdentity ?? metadata.resourceId ?? `user-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n // One memory thread per room unless the caller pins a thread explicitly.\n metadata.threadId ??= roomName;\n\n const recording =\n typeof options.recording === 'function' ? await options.recording({ ...args, roomName }) : options.recording;\n if (recording !== undefined) {\n try {\n await dispatchVoiceSession({\n roomName,\n agentName: options.agentName,\n metadata,\n serverUrl,\n apiKey,\n apiSecret,\n recording,\n });\n } catch (error) {\n if (error instanceof LiveKitRecordingRoomConflictError) {\n return c.json({ error: 'Recording requires a new room. Use a unique roomName for each call.' }, 409);\n }\n throw error;\n }\n }\n\n const token = new AccessToken(apiKey, apiSecret, { identity, ttl: options.ttl ?? '15m' });\n token.addGrant({\n room: roomName,\n roomJoin: true,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n });\n // A pre-created room needs explicit dispatch; token roomConfig only applies at room creation.\n if (recording === undefined) {\n token.roomConfig = new RoomConfiguration({\n agents: [\n new RoomAgentDispatch({\n agentName: options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME,\n metadata: serializeSessionMetadata(metadata),\n }),\n ],\n });\n }\n\n const details: LiveKitConnectionDetails = {\n serverUrl,\n roomName,\n participantName: identity,\n participantToken: await token.toJwt(),\n };\n return c.json(details);\n };\n\n return {\n // Studio calls this default path and /api/system/packages reports it — change all three together.\n path: options.path ?? '/voice/livekit/connection-details',\n method: 'POST',\n requiresAuth: options.requiresAuth,\n handler,\n } as ApiRoute;\n}\n","import type { ApiRoute, ContextWithMastra } from '@mastra/core/server';\nimport type { SpanRecord } from '@mastra/core/storage';\nimport { z } from 'zod/v4';\nimport type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types';\n\nconst traceIdSchema = z.string().min(1).max(256);\nexport const recordingSchema = z.object({\n url: z.url({ protocol: /^https?$/ }),\n expiresAt: z.string().datetime().optional(),\n}) satisfies z.ZodType<LiveKitRecording>;\n\nexport interface LiveKitRecordingResolverArgs {\n traceId: string;\n /** Taken from the stored voice call span, never from the browser request. */\n roomName: string;\n span: SpanRecord;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitRecordingRouteOptions {\n /** Studio discovers this route at its default path: /voice/livekit/recordings/:traceId. */\n path?: string;\n /** Defaults to true. Only disable for a local demo. */\n requiresAuth?: boolean;\n /** Required trace-specific access policy. Only true permits trace lookup and URL resolution. */\n authorize: (args: { traceId: string; context: ContextWithMastra }) => boolean | Promise<boolean>;\n /** Return a playable URL, or undefined if the recording is not available yet. */\n resolveRecording: (args: LiveKitRecordingResolverArgs) => Promise<LiveKitRecording | undefined>;\n}\n\n/** Resolves a voice call trace to a recording without persisting signed URLs in traces. */\nexport function liveKitRecordingRoute(options: LiveKitRecordingRouteOptions): ApiRoute {\n if (typeof options.authorize !== 'function') {\n throw new Error('liveKitRecordingRoute requires an authorize callback.');\n }\n return {\n path: options.path ?? '/voice/livekit/recordings/:traceId',\n method: 'GET',\n requiresAuth: options.requiresAuth ?? true,\n handler: async (context: ContextWithMastra) => {\n context.header('Cache-Control', 'no-store');\n const input = traceIdSchema.safeParse(context.req.param('traceId'));\n if (!input.success) return context.json({ error: 'A valid trace ID is required.' }, 400);\n const traceId = input.data;\n try {\n if ((await options.authorize({ traceId, context })) !== true) {\n return context.json({ error: 'Access to this recording is denied.' }, 403);\n }\n const store = await context.get('mastra').getStorage()?.getStore('observability');\n if (!store) return context.json({ error: 'Trace storage is not configured.' }, 503);\n const trace = await store.getTrace({ traceId });\n const calls =\n trace?.spans.filter(\n span =>\n span.name === 'voice call' &&\n typeof span.metadata?.roomName === 'string' &&\n span.metadata.roomName.length > 0,\n ) ?? [];\n if (!calls.length) return context.json({ error: 'Voice call trace not found.' }, 404);\n if (calls.length !== 1) return context.json({ error: 'This trace contains multiple voice calls.' }, 409);\n const span = calls[0]!;\n const roomName = span.metadata?.roomName;\n if (typeof roomName !== 'string') return context.json({ error: 'Voice call trace not found.' }, 404);\n const recording = await options.resolveRecording({ traceId, roomName, span, context });\n if (!recording) return context.json({ status: 'unavailable' } satisfies LiveKitRecordingResponse);\n // Validate and strip extra fields so storage credentials cannot accidentally become response fields.\n const result = recordingSchema.safeParse(recording);\n if (!result.success) return context.json({ error: 'Unable to load the call recording.' }, 502);\n return context.json({ status: 'ready', ...result.data } satisfies LiveKitRecordingResponse);\n } catch {\n // Storage/provider errors can contain credentials or signed request details.\n return context.json({ error: 'Unable to load the call recording.' }, 502);\n }\n },\n };\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** A consent decision captured from the caller during a call. */\nexport interface ConsentGrant {\n /**\n * The consent item, matching a key in the worker's `configuration.consentPolicy` (e.g.\n * `'summaryStorage'`).\n */\n item: string;\n /** `true` if the caller agreed, `false` if they declined. */\n granted: boolean;\n /** The caller the grant belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread the grant was captured on, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface ConsentToolOptions {\n /**\n * Persist the caller's decision to YOUR system of record (database, CRM, consent ledger). Called\n * each time the caller answers a consent question — keep it quick, it runs inside the turn. This\n * tool owns extracting the caller's identity from the tool execution context; you own storage, so\n * consent lives in a durable, compliant place rather than an opaque plugin store. Read those\n * grants back at `onCallEnd` (or before any consent-gated step) to enforce the requirement.\n */\n onGrant: (grant: ConsentGrant) => void | Promise<void>;\n /** Tool id the agent calls. Defaults to `'recordConsent'`. */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /** Restrict the accepted consent items to this set (becomes an enum). Defaults to any string. */\n items?: readonly string[];\n}\n\nconst DEFAULT_DESCRIPTION =\n \"Record the caller's consent decision for a data-processing item (for example, storing a summary \" +\n 'of the call). Call this as soon as the caller answers a consent question: granted = true if they ' +\n 'agree, false if they decline. Do not proceed with an activity that requires consent until you ' +\n 'have recorded the caller granting it.';\n\n/**\n * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to\n * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add\n * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /\n * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime\n * grants live only where `onGrant` put them: enforce consent by reading them back from your own\n * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared\n * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the\n * policy, never the grants).\n *\n * ```ts\n * // agent tools\n * recordConsent: createConsentTool({\n * items: ['summaryStorage'],\n * onGrant: async ({ item, granted, resourceId }) => {\n * if (resourceId) await db.saveConsent(resourceId, item, granted);\n * },\n * }),\n * ```\n */\nexport function createConsentTool(options: ConsentToolOptions) {\n const items = options.items;\n const itemSchema = items && items.length > 0 ? z.enum([...items] as [string, ...string[]]) : z.string();\n return createTool({\n id: options.id ?? 'recordConsent',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n item: itemSchema.describe(\n \"The consent item the caller is answering for (matches the deployment's required consents).\",\n ),\n granted: z.boolean().describe('True if the caller agreed, false if they declined.'),\n }),\n execute: async ({ item, granted }, { agent }) => {\n await options.onGrant({ item, granted, resourceId: agent?.resourceId, threadId: agent?.threadId });\n return { recorded: true as const, item, granted };\n },\n });\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** Details of the agent's decision to end the call, handed to {@link EndCallToolOptions.onEndCall}. */\nexport interface EndCallRequest {\n /** Short reason the agent gave for ending the call, if any (e.g. \"caller said goodbye\"). */\n reason?: string;\n /** The caller the call belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface EndCallToolOptions {\n /**\n * Tool id the agent calls to end the call. Must match the worker's\n * `configuration.endCall.tool` (both default to `'endCall'`), since that's the name the worker\n * watches for to hang up.\n */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /**\n * Optional bookkeeping hook, called when the agent invokes the tool (records the reason, marks\n * the call resolved in your CRM, …). Runs inside the turn — keep it quick. It does NOT hang up\n * the call; the worker does that once the agent's final words finish playing. The tool reads the\n * caller's identity from its execution context and passes it here.\n */\n onEndCall?: (request: EndCallRequest) => void | Promise<void>;\n}\n\nconst DEFAULT_DESCRIPTION =\n 'End the phone call. Call this only after you have said goodbye and there is nothing left to do — ' +\n 'for example the caller says goodbye, or the task is complete and you have wrapped up. Say your ' +\n 'closing line first, then call this as your final action; the call hangs up once your words finish ' +\n 'playing. Your closing line must be a final statement, never a question — if you are asking the ' +\n 'caller anything (for example whether they need anything else), do NOT call this in that reply; ' +\n 'wait for their answer. Do not call it if the caller still needs something.';\n\n/**\n * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the\n * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional\n * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the\n * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the\n * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).\n * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on\n * the agent and workflow reply paths alike.\n *\n * ```ts\n * // agent tools\n * endCall: createEndCallTool({\n * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),\n * }),\n * // worker\n * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });\n * ```\n */\nexport function createEndCallTool(options: EndCallToolOptions = {}) {\n return createTool({\n id: options.id ?? 'endCall',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n reason: z\n .string()\n .nullish()\n .describe('Short reason the call is ending, e.g. \"caller said goodbye\" or \"task complete\".'),\n }),\n outputSchema: z.object({ ended: z.boolean() }),\n execute: async ({ reason }, { agent }) => {\n try {\n await options.onEndCall?.({\n reason: reason ?? undefined,\n resourceId: agent?.resourceId,\n threadId: agent?.threadId,\n });\n } catch (error) {\n // Bookkeeping is best-effort — the tool must still signal `{ ended: true }` so the worker's\n // end-call detector runs and the call actually hangs up.\n console.warn('@mastra/livekit: onEndCall hook threw', error);\n }\n return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QAAQ,CAAC,CACT,SAAS,qFAAiF,EAC/F,CAAC;EACD,cAAcA,IAAAA,EAAE,OAAO,EAAE,OAAOA,IAAAA,EAAE,QAAQ,EAAE,CAAC;EAC7C,SAAS,OAAO,EAAE,UAAU,EAAE,YAAY;GACxC,IAAI;IACF,MAAM,QAAQ,YAAY;KACxB,QAAQ,UAAU,KAAA;KAClB,YAAY,OAAO;KACnB,UAAU,OAAO;IACnB,CAAC;GACH,SAAS,OAAO;IAGd,QAAQ,KAAK,yCAAyC,KAAK;GAC7D;GACA,OAAO,EAAE,OAAO,KAAc;EAChC;CACF,CAAC;AACH"}
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_turn_metrics = require("./turn-metrics-CtVHHdJj.cjs");
3
- const require_remote = require("./remote-GSOxa--f.cjs");
3
+ const require_remote = require("./remote-z8wjPDtk.cjs");
4
4
  let _livekit_agents = require("@livekit/agents");
5
5
  let _mastra_core_request_context = require("@mastra/core/request-context");
6
6
  //#region src/llm-plugin.ts
@@ -1 +1 @@
1
- {"version":3,"file":"plugin-entry.cjs","names":["RequestContext","llm","#model","#onTurnMetrics","#memory","#requestContext","#staticGenerator","#remoteOptions","createAgentReplyGenerator","createRemoteAgentReplyGenerator","DEFAULT_API_CONNECT_OPTIONS","#warnedToolCtx","#generator","chatContextToMessages","extractNewTurnMessages","instrumentVoiceReply","VOICE_TURN_METADATA","VOICE_FLUSH_METADATA"],"sources":["../src/llm-plugin.ts"],"sourcesContent":["import { DEFAULT_API_CONNECT_OPTIONS, llm } from '@livekit/agents';\nimport type { APIConnectOptions } from '@livekit/agents';\nimport type { Agent as MastraAgent } from '@mastra/core/agent';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { createAgentReplyGenerator, instrumentVoiceReply } from './bridge';\nimport type {\n MastraVoiceAgentMemory,\n VoiceReplyGenerator,\n VoiceToolCall,\n VoiceTurnCompleteHook,\n VoiceTurnContext,\n VoiceTurnUsage,\n} from './bridge';\nimport { chatContextToMessages, extractNewTurnMessages } from './messages';\nimport { createRemoteAgentReplyGenerator } from './remote';\nimport type { RemoteMastraAgentOptions } from './remote';\nimport type { VoiceTurnMetricsHook } from './turn-metrics';\nimport { VOICE_FLUSH_METADATA, VOICE_TURN_METADATA } from './turn-metrics';\n\nexport type { RemoteMastraAgentOptions } from './remote';\n\n/**\n * Options for {@link MastraLLM}. Provide **exactly one** reply source — `remote` (the headline: a\n * Mastra app on a remote server), `agent` (an in-process Mastra agent), or `generate` (a custom\n * {@link VoiceReplyGenerator}). The `toolFeedback` / `onToolCall` / `onTurnComplete` hooks apply to\n * the `remote` and `agent` sources; a `generate` source owns its own hooks.\n */\nexport interface MastraLLMOptions {\n /** Per-attempt metrics; use observeVoiceSession for playback metrics. */\n onTurnMetrics?: VoiceTurnMetricsHook;\n /** Remote Mastra server. Provide exactly one of `remote`, `agent`, `generate`. */\n remote?: RemoteMastraAgentOptions;\n /** In-process Mastra agent (reuses `createAgentReplyGenerator`). */\n agent?: MastraAgent;\n /** Custom reply source (escape hatch; owns its own tool-feedback / turn-complete behavior). */\n generate?: VoiceReplyGenerator;\n\n /**\n * Conversation persistence, resolved by the customer per call (from SIP/caller identity). When set,\n * only messages new since the agent last spoke are sent each turn and Mastra Memory supplies\n * history. When omitted/false, the full LiveKit chat context is sent every turn.\n *\n * NOTE: incompatible with the session's `preemptiveGeneration` option — a speculative turn\n * persists a partial user message and a partial reply before being discarded. Leave preemptive\n * generation off when using `memory`, or set `memory.options.readOnly` and persist committed\n * turns yourself from the session's conversation-item events.\n *\n * The plugin cannot detect the combination at runtime, so this stays a documented constraint\n * rather than a warning: the LLM interface never receives the session (so the option can't be\n * read), a preemptive `chat()` is shape-identical to a real turn (LiveKit drives the same\n * `generateReply` with a draft transcript and no marker), and the observable signature — a\n * cancelled stream followed by a `chat()` whose trailing user message changed — is exactly what\n * an ordinary barge-in correction looks like, so a heuristic would warn on every barge-in.\n */\n memory?: MastraVoiceAgentMemory | false;\n /** Request context forwarded to generation (tenant, dialed number, ...). */\n requestContext?: RequestContext | Record<string, unknown>;\n\n /** Speak a short filler while a (server-side) tool runs. Applies to the `remote`/`agent` sources. */\n toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;\n /** Notified as each tool-call chunk arrives, mid-stream. Applies to the `remote`/`agent` sources. */\n onToolCall?: (toolCall: VoiceToolCall) => void;\n /** Fired off the audio path after each reply finishes. Applies to the `remote`/`agent` sources. */\n onTurnComplete?: VoiceTurnCompleteHook;\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\nfunction mapUsageToLiveKit(usage: VoiceTurnUsage): llm.CompletionUsage {\n return {\n completionTokens: usage.completionTokens,\n promptTokens: usage.promptTokens,\n promptCachedTokens: usage.promptCachedTokens,\n totalTokens: usage.totalTokens,\n };\n}\n\n/**\n * Tool names carried by a `toolCtx`, across @livekit/agents versions: 1.5+ always passes a\n * `ToolContext` class instance (tools behind getters, `Object.keys` sees only private fields),\n * while 1.4 and the object shorthand pass a plain name→tool map.\n */\nfunction livekitToolNames(toolCtx: object): string[] {\n const instance = toolCtx as { flatten?: unknown };\n if (typeof instance.flatten === 'function') {\n return (instance.flatten as () => object[])().map(tool => {\n const { id, name } = tool as { id?: string; name?: string };\n return id ?? name ?? 'unknown';\n });\n }\n return Object.keys(toolCtx);\n}\n\n/**\n * A standard LiveKit LLM plugin (`llm.LLM`) backed by a Mastra agent. Drop it into the `llm` slot of a\n * customer-owned `voice.AgentSession` and the Mastra app (agent loop, tools, memory, observability)\n * runs wherever it's deployed — most importantly on a **remote** Mastra server reached over HTTP.\n *\n * Tools are defined and executed **server-side** on the Mastra agent; LiveKit-side `toolCtx` is\n * ignored (with a one-time warning). Tool activity surfaces via `toolFeedback` (spoken) and\n * `onToolCall` / `onTurnComplete` (programmatic). `voice.Agent` instructions do **not** reach the\n * Mastra agent — put instructions on the Mastra agent instead.\n *\n * @example\n * ```ts\n * const session = new voice.AgentSession({\n * stt: 'deepgram/nova-3',\n * tts: 'cartesia/sonic-3',\n * llm: new MastraLLM({\n * remote: { baseUrl: process.env.MASTRA_URL!, agentId: 'callCenter' },\n * memory: { thread: callId, resource: callerId },\n * }),\n * });\n * ```\n */\nexport class MastraLLM extends llm.LLM {\n readonly #model: string;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n /** Non-remote sources are built once; remote is built per turn so it can pick up `connOptions.timeoutMs`. */\n readonly #staticGenerator?: VoiceReplyGenerator;\n readonly #remoteOptions?: RemoteMastraAgentOptions & {\n toolFeedback?: MastraLLMOptions['toolFeedback'];\n onToolCall?: MastraLLMOptions['onToolCall'];\n onTurnComplete?: VoiceTurnCompleteHook;\n };\n #warnedToolCtx = false;\n\n constructor(options: MastraLLMOptions) {\n super();\n this.#onTurnMetrics = options.onTurnMetrics;\n const sources = [\n options.remote ? 'remote' : undefined,\n options.agent ? 'agent' : undefined,\n options.generate ? 'generate' : undefined,\n ].filter(Boolean) as string[];\n if (sources.length !== 1) {\n throw new Error(\n `@mastra/livekit: MastraLLM requires exactly one reply source — \\`remote\\`, \\`agent\\`, or \\`generate\\` — ` +\n `but got ${sources.length === 0 ? 'none' : sources.join(' + ')}.`,\n );\n }\n\n this.#memory = options.memory ?? false;\n this.#requestContext = toRequestContext(options.requestContext);\n\n if (options.remote) {\n this.#model = options.remote.agentId;\n this.#remoteOptions = {\n ...options.remote,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n };\n } else if (options.agent) {\n this.#model = options.agent.id ?? options.agent.name;\n this.#staticGenerator = createAgentReplyGenerator({\n agent: options.agent,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n });\n } else {\n this.#model = 'mastra-generator';\n this.#staticGenerator = options.generate;\n }\n }\n\n label(): string {\n return 'mastra.MastraLLM';\n }\n\n override get model(): string {\n return this.#model;\n }\n\n override get provider(): string {\n return 'mastra';\n }\n\n /**\n * Resolves the reply generator for a turn. Non-remote sources are built once; the remote transport\n * is built per turn so its connect + first-token timeout can come from the session's\n * `connOptions.timeoutMs`, with base-class retries owning retry (transport `retries: 0`).\n */\n private resolveGenerator(connOptions: APIConnectOptions): VoiceReplyGenerator {\n if (this.#staticGenerator) return this.#staticGenerator;\n const remote = this.#remoteOptions!;\n return createRemoteAgentReplyGenerator({\n ...remote,\n retries: 0,\n timeoutMs: remote.timeoutMs ?? connOptions.timeoutMs,\n });\n }\n\n override chat({\n chatCtx,\n toolCtx,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): llm.LLMStream {\n // Tools run server-side; warn once if the customer wired LiveKit-side tools.\n if (!this.#warnedToolCtx && toolCtx) {\n const ignored = livekitToolNames(toolCtx);\n if (ignored.length > 0) {\n this.#warnedToolCtx = true;\n console.warn(\n `@mastra/livekit: MastraLLM ignores LiveKit-side tools (${ignored.join(', ')}). ` +\n `Tools are defined and executed server-side on the Mastra agent — move them there.`,\n );\n }\n }\n return new MastraLLMStream(this, {\n chatCtx,\n toolCtx,\n connOptions,\n generator: this.resolveGenerator(connOptions),\n onTurnMetrics: this.#onTurnMetrics,\n memory: this.#memory,\n requestContext: this.#requestContext,\n });\n }\n\n /** No-op in v1: nothing in the LiveKit session/worker ever calls `prewarm()` automatically. */\n override prewarm(): void {}\n}\n\ninterface MastraLLMStreamOptions {\n onTurnMetrics?: VoiceTurnMetricsHook;\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions: APIConnectOptions;\n generator: VoiceReplyGenerator;\n memory: MastraVoiceAgentMemory | false;\n requestContext?: RequestContext;\n}\n\n/**\n * The `llm.LLMStream` `MastraLLM` returns per turn. `run()` extracts the turn's messages, drives\n * the reply generator, and pushes assistant `ChatChunk`s into `this.queue` (NOT `this.output` — the\n * base class drains queue → output and computes TTFT / duration / usage). Barge-in aborts via\n * `this.abortController` and `run()` returns silently.\n */\nclass MastraLLMStream extends llm.LLMStream {\n readonly #generator: VoiceReplyGenerator;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n\n constructor(mastraLLM: MastraLLM, options: MastraLLMStreamOptions) {\n super(mastraLLM, { chatCtx: options.chatCtx, toolCtx: options.toolCtx, connOptions: options.connOptions });\n this.#generator = options.generator;\n this.#onTurnMetrics = options.onTurnMetrics;\n this.#memory = options.memory;\n this.#requestContext = options.requestContext;\n }\n\n protected async run(): Promise<void> {\n const messages =\n this.#memory === false ? chatContextToMessages(this.chatCtx) : extractNewTurnMessages(this.chatCtx);\n // No new input to answer → close without a request (equivalent to the wrapper returning null).\n if (messages.length === 0) return;\n\n let usage: VoiceTurnUsage | undefined;\n const turnCtx: VoiceTurnContext = {\n messages,\n chatCtx: this.chatCtx,\n memory: this.#memory,\n requestContext: this.#requestContext,\n onUsage: turnUsage => {\n usage = turnUsage;\n },\n };\n\n const { reply, identity } = await instrumentVoiceReply(this.#generator, turnCtx, this.#onTurnMetrics);\n if (!reply) return;\n if (this.abortController.signal.aborted) {\n await reply.cancel().catch(() => {});\n return;\n }\n\n // A single provider response id ties all of this turn's chunks together for the base class metrics.\n const id = identity.attemptId;\n const reader = reply.getReader();\n const onAbort = () => void reader.cancel().catch(() => {});\n this.abortController.signal.addEventListener('abort', onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.abortController.signal.aborted) break;\n if (value)\n this.queue.put({\n id,\n delta: {\n role: 'assistant',\n ...(typeof value === 'string' ? { content: value } : {}),\n extra: { [VOICE_TURN_METADATA]: identity, [VOICE_FLUSH_METADATA]: typeof value !== 'string' },\n },\n });\n }\n } catch (error) {\n // Barge-in tears down the reply stream; that surfaces as a read rejection but is not a failure.\n if (this.abortController.signal.aborted) return;\n throw error;\n } finally {\n this.abortController.signal.removeEventListener('abort', onAbort);\n }\n // Return silently on barge-in — throwing would feed the base class's error/retry machinery.\n if (this.abortController.signal.aborted) return;\n // Final usage-only chunk → the base class reads usage from the last chunk that carries it.\n if (usage) this.queue.put({ id, usage: mapUsageToLiveKit(usage) });\n }\n}\n\nexport { MastraLLMStream };\n"],"mappings":";;;;;;AAkEA,SAAS,iBAAiB,OAAyF;CACjH,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,iBAAiBA,6BAAAA,gBAAgB,OAAO;CAC5C,OAAO,IAAIA,6BAAAA,eAAwB,OAAO,QAAQ,KAAK,CAAC;AAC1D;AAEA,SAAS,kBAAkB,OAA4C;CACrE,OAAO;EACL,kBAAkB,MAAM;EACxB,cAAc,MAAM;EACpB,oBAAoB,MAAM;EAC1B,aAAa,MAAM;CACrB;AACF;;;;;;AAOA,SAAS,iBAAiB,SAA2B;CACnD,MAAM,WAAW;CACjB,IAAI,OAAO,SAAS,YAAY,YAC9B,OAAQ,SAAS,QAA2B,CAAC,CAAC,KAAI,SAAQ;EACxD,MAAM,EAAE,IAAI,SAAS;EACrB,OAAO,MAAM,QAAQ;CACvB,CAAC;CAEH,OAAO,OAAO,KAAK,OAAO;AAC5B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,YAAb,cAA+BC,gBAAAA,IAAI,IAAI;CACrC;CACA;CACA;CACA;;CAEA;CACA;CAKA,iBAAiB;CAEjB,YAAY,SAA2B;EACrC,MAAM;EACN,KAAKE,iBAAiB,QAAQ;EAC9B,MAAM,UAAU;GACd,QAAQ,SAAS,WAAW,KAAA;GAC5B,QAAQ,QAAQ,UAAU,KAAA;GAC1B,QAAQ,WAAW,aAAa,KAAA;EAClC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,OAAO,KAAK;IAC1C,IAAI,MAAM;IACV,IAAI,KAAK,gBAAgB,OAAO,SAAS;IACzC,IAAI,OACF,KAAK,MAAM,IAAI;KACb;KACA,OAAO;MACL,MAAM;MACN,GAAI,OAAO,UAAU,WAAW,EAAE,SAAS,MAAM,IAAI,CAAC;MACtD,OAAO;QAAGa,qBAAAA,sBAAsB;QAAWC,qBAAAA,uBAAuB,OAAO,UAAU;MAAS;KAC9F;IACF,CAAC;GACL;EACF,SAAS,OAAO;GAEd,IAAI,KAAK,gBAAgB,OAAO,SAAS;GACzC,MAAM;EACR,UAAU;GACR,KAAK,gBAAgB,OAAO,oBAAoB,SAAS,OAAO;EAClE;EAEA,IAAI,KAAK,gBAAgB,OAAO,SAAS;EAEzC,IAAI,OAAO,KAAK,MAAM,IAAI;GAAE;GAAI,OAAO,kBAAkB,KAAK;EAAE,CAAC;CACnE;AACF"}
1
+ {"version":3,"file":"plugin-entry.cjs","names":["RequestContext","llm","createAgentReplyGenerator","createRemoteAgentReplyGenerator","DEFAULT_API_CONNECT_OPTIONS","chatContextToMessages","extractNewTurnMessages","instrumentVoiceReply","VOICE_TURN_METADATA","VOICE_FLUSH_METADATA"],"sources":["../src/llm-plugin.ts"],"sourcesContent":["import { DEFAULT_API_CONNECT_OPTIONS, llm } from '@livekit/agents';\nimport type { APIConnectOptions } from '@livekit/agents';\nimport type { Agent as MastraAgent } from '@mastra/core/agent';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { createAgentReplyGenerator, instrumentVoiceReply } from './bridge';\nimport type {\n MastraVoiceAgentMemory,\n VoiceReplyGenerator,\n VoiceToolCall,\n VoiceTurnCompleteHook,\n VoiceTurnContext,\n VoiceTurnUsage,\n} from './bridge';\nimport { chatContextToMessages, extractNewTurnMessages } from './messages';\nimport { createRemoteAgentReplyGenerator } from './remote';\nimport type { RemoteMastraAgentOptions } from './remote';\nimport type { VoiceTurnMetricsHook } from './turn-metrics';\nimport { VOICE_FLUSH_METADATA, VOICE_TURN_METADATA } from './turn-metrics';\n\nexport type { RemoteMastraAgentOptions } from './remote';\n\n/**\n * Options for {@link MastraLLM}. Provide **exactly one** reply source — `remote` (the headline: a\n * Mastra app on a remote server), `agent` (an in-process Mastra agent), or `generate` (a custom\n * {@link VoiceReplyGenerator}). The `toolFeedback` / `onToolCall` / `onTurnComplete` hooks apply to\n * the `remote` and `agent` sources; a `generate` source owns its own hooks.\n */\nexport interface MastraLLMOptions {\n /** Per-attempt metrics; use observeVoiceSession for playback metrics. */\n onTurnMetrics?: VoiceTurnMetricsHook;\n /** Remote Mastra server. Provide exactly one of `remote`, `agent`, `generate`. */\n remote?: RemoteMastraAgentOptions;\n /** In-process Mastra agent (reuses `createAgentReplyGenerator`). */\n agent?: MastraAgent;\n /** Custom reply source (escape hatch; owns its own tool-feedback / turn-complete behavior). */\n generate?: VoiceReplyGenerator;\n\n /**\n * Conversation persistence, resolved by the customer per call (from SIP/caller identity). When set,\n * only messages new since the agent last spoke are sent each turn and Mastra Memory supplies\n * history. When omitted/false, the full LiveKit chat context is sent every turn.\n *\n * NOTE: incompatible with the session's `preemptiveGeneration` option — a speculative turn\n * persists a partial user message and a partial reply before being discarded. Leave preemptive\n * generation off when using `memory`, or set `memory.options.readOnly` and persist committed\n * turns yourself from the session's conversation-item events.\n *\n * The plugin cannot detect the combination at runtime, so this stays a documented constraint\n * rather than a warning: the LLM interface never receives the session (so the option can't be\n * read), a preemptive `chat()` is shape-identical to a real turn (LiveKit drives the same\n * `generateReply` with a draft transcript and no marker), and the observable signature — a\n * cancelled stream followed by a `chat()` whose trailing user message changed — is exactly what\n * an ordinary barge-in correction looks like, so a heuristic would warn on every barge-in.\n */\n memory?: MastraVoiceAgentMemory | false;\n /** Request context forwarded to generation (tenant, dialed number, ...). */\n requestContext?: RequestContext | Record<string, unknown>;\n\n /** Speak a short filler while a (server-side) tool runs. Applies to the `remote`/`agent` sources. */\n toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;\n /** Notified as each tool-call chunk arrives, mid-stream. Applies to the `remote`/`agent` sources. */\n onToolCall?: (toolCall: VoiceToolCall) => void;\n /** Fired off the audio path after each reply finishes. Applies to the `remote`/`agent` sources. */\n onTurnComplete?: VoiceTurnCompleteHook;\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\nfunction mapUsageToLiveKit(usage: VoiceTurnUsage): llm.CompletionUsage {\n return {\n completionTokens: usage.completionTokens,\n promptTokens: usage.promptTokens,\n promptCachedTokens: usage.promptCachedTokens,\n totalTokens: usage.totalTokens,\n };\n}\n\n/**\n * Tool names carried by a `toolCtx`, across @livekit/agents versions: 1.5+ always passes a\n * `ToolContext` class instance (tools behind getters, `Object.keys` sees only private fields),\n * while 1.4 and the object shorthand pass a plain name→tool map.\n */\nfunction livekitToolNames(toolCtx: object): string[] {\n const instance = toolCtx as { flatten?: unknown };\n if (typeof instance.flatten === 'function') {\n return (instance.flatten as () => object[])().map(tool => {\n const { id, name } = tool as { id?: string; name?: string };\n return id ?? name ?? 'unknown';\n });\n }\n return Object.keys(toolCtx);\n}\n\n/**\n * A standard LiveKit LLM plugin (`llm.LLM`) backed by a Mastra agent. Drop it into the `llm` slot of a\n * customer-owned `voice.AgentSession` and the Mastra app (agent loop, tools, memory, observability)\n * runs wherever it's deployed — most importantly on a **remote** Mastra server reached over HTTP.\n *\n * Tools are defined and executed **server-side** on the Mastra agent; LiveKit-side `toolCtx` is\n * ignored (with a one-time warning). Tool activity surfaces via `toolFeedback` (spoken) and\n * `onToolCall` / `onTurnComplete` (programmatic). `voice.Agent` instructions do **not** reach the\n * Mastra agent — put instructions on the Mastra agent instead.\n *\n * @example\n * ```ts\n * const session = new voice.AgentSession({\n * stt: 'deepgram/nova-3',\n * tts: 'cartesia/sonic-3',\n * llm: new MastraLLM({\n * remote: { baseUrl: process.env.MASTRA_URL!, agentId: 'callCenter' },\n * memory: { thread: callId, resource: callerId },\n * }),\n * });\n * ```\n */\nexport class MastraLLM extends llm.LLM {\n readonly #model: string;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n /** Non-remote sources are built once; remote is built per turn so it can pick up `connOptions.timeoutMs`. */\n readonly #staticGenerator?: VoiceReplyGenerator;\n readonly #remoteOptions?: RemoteMastraAgentOptions & {\n toolFeedback?: MastraLLMOptions['toolFeedback'];\n onToolCall?: MastraLLMOptions['onToolCall'];\n onTurnComplete?: VoiceTurnCompleteHook;\n };\n #warnedToolCtx = false;\n\n constructor(options: MastraLLMOptions) {\n super();\n this.#onTurnMetrics = options.onTurnMetrics;\n const sources = [\n options.remote ? 'remote' : undefined,\n options.agent ? 'agent' : undefined,\n options.generate ? 'generate' : undefined,\n ].filter(Boolean) as string[];\n if (sources.length !== 1) {\n throw new Error(\n `@mastra/livekit: MastraLLM requires exactly one reply source — \\`remote\\`, \\`agent\\`, or \\`generate\\` — ` +\n `but got ${sources.length === 0 ? 'none' : sources.join(' + ')}.`,\n );\n }\n\n this.#memory = options.memory ?? false;\n this.#requestContext = toRequestContext(options.requestContext);\n\n if (options.remote) {\n this.#model = options.remote.agentId;\n this.#remoteOptions = {\n ...options.remote,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n };\n } else if (options.agent) {\n this.#model = options.agent.id ?? options.agent.name;\n this.#staticGenerator = createAgentReplyGenerator({\n agent: options.agent,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n });\n } else {\n this.#model = 'mastra-generator';\n this.#staticGenerator = options.generate;\n }\n }\n\n label(): string {\n return 'mastra.MastraLLM';\n }\n\n override get model(): string {\n return this.#model;\n }\n\n override get provider(): string {\n return 'mastra';\n }\n\n /**\n * Resolves the reply generator for a turn. Non-remote sources are built once; the remote transport\n * is built per turn so its connect + first-token timeout can come from the session's\n * `connOptions.timeoutMs`, with base-class retries owning retry (transport `retries: 0`).\n */\n private resolveGenerator(connOptions: APIConnectOptions): VoiceReplyGenerator {\n if (this.#staticGenerator) return this.#staticGenerator;\n const remote = this.#remoteOptions!;\n return createRemoteAgentReplyGenerator({\n ...remote,\n retries: 0,\n timeoutMs: remote.timeoutMs ?? connOptions.timeoutMs,\n });\n }\n\n override chat({\n chatCtx,\n toolCtx,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): llm.LLMStream {\n // Tools run server-side; warn once if the customer wired LiveKit-side tools.\n if (!this.#warnedToolCtx && toolCtx) {\n const ignored = livekitToolNames(toolCtx);\n if (ignored.length > 0) {\n this.#warnedToolCtx = true;\n console.warn(\n `@mastra/livekit: MastraLLM ignores LiveKit-side tools (${ignored.join(', ')}). ` +\n `Tools are defined and executed server-side on the Mastra agent — move them there.`,\n );\n }\n }\n return new MastraLLMStream(this, {\n chatCtx,\n toolCtx,\n connOptions,\n generator: this.resolveGenerator(connOptions),\n onTurnMetrics: this.#onTurnMetrics,\n memory: this.#memory,\n requestContext: this.#requestContext,\n });\n }\n\n /** No-op in v1: nothing in the LiveKit session/worker ever calls `prewarm()` automatically. */\n override prewarm(): void {}\n}\n\ninterface MastraLLMStreamOptions {\n onTurnMetrics?: VoiceTurnMetricsHook;\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions: APIConnectOptions;\n generator: VoiceReplyGenerator;\n memory: MastraVoiceAgentMemory | false;\n requestContext?: RequestContext;\n}\n\n/**\n * The `llm.LLMStream` `MastraLLM` returns per turn. `run()` extracts the turn's messages, drives\n * the reply generator, and pushes assistant `ChatChunk`s into `this.queue` (NOT `this.output` — the\n * base class drains queue → output and computes TTFT / duration / usage). Barge-in aborts via\n * `this.abortController` and `run()` returns silently.\n */\nclass MastraLLMStream extends llm.LLMStream {\n readonly #generator: VoiceReplyGenerator;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n\n constructor(mastraLLM: MastraLLM, options: MastraLLMStreamOptions) {\n super(mastraLLM, { chatCtx: options.chatCtx, toolCtx: options.toolCtx, connOptions: options.connOptions });\n this.#generator = options.generator;\n this.#onTurnMetrics = options.onTurnMetrics;\n this.#memory = options.memory;\n this.#requestContext = options.requestContext;\n }\n\n protected async run(): Promise<void> {\n const messages =\n this.#memory === false ? chatContextToMessages(this.chatCtx) : extractNewTurnMessages(this.chatCtx);\n // No new input to answer → close without a request (equivalent to the wrapper returning null).\n if (messages.length === 0) return;\n\n let usage: VoiceTurnUsage | undefined;\n const turnCtx: VoiceTurnContext = {\n messages,\n chatCtx: this.chatCtx,\n memory: this.#memory,\n requestContext: this.#requestContext,\n onUsage: turnUsage => {\n usage = turnUsage;\n },\n };\n\n const { reply, identity } = await instrumentVoiceReply(this.#generator, turnCtx, this.#onTurnMetrics);\n if (!reply) return;\n if (this.abortController.signal.aborted) {\n await reply.cancel().catch(() => {});\n return;\n }\n\n // A single provider response id ties all of this turn's chunks together for the base class metrics.\n const id = identity.attemptId;\n const reader = reply.getReader();\n const onAbort = () => void reader.cancel().catch(() => {});\n this.abortController.signal.addEventListener('abort', onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.abortController.signal.aborted) break;\n if (value)\n this.queue.put({\n id,\n delta: {\n role: 'assistant',\n ...(typeof value === 'string' ? { content: value } : {}),\n extra: { [VOICE_TURN_METADATA]: identity, [VOICE_FLUSH_METADATA]: typeof value !== 'string' },\n },\n });\n }\n } catch (error) {\n // Barge-in tears down the reply stream; that surfaces as a read rejection but is not a failure.\n if (this.abortController.signal.aborted) return;\n throw error;\n } finally {\n this.abortController.signal.removeEventListener('abort', onAbort);\n }\n // Return silently on barge-in — throwing would feed the base class's error/retry machinery.\n if (this.abortController.signal.aborted) return;\n // Final usage-only chunk → the base class reads usage from the last chunk that carries it.\n if (usage) this.queue.put({ id, usage: mapUsageToLiveKit(usage) });\n }\n}\n\nexport { MastraLLMStream };\n"],"mappings":";;;;;;AAkEA,SAAS,iBAAiB,OAAyF;CACjH,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,iBAAiBA,6BAAAA,gBAAgB,OAAO;CAC5C,OAAO,IAAIA,6BAAAA,eAAwB,OAAO,QAAQ,KAAK,CAAC;AAC1D;AAEA,SAAS,kBAAkB,OAA4C;CACrE,OAAO;EACL,kBAAkB,MAAM;EACxB,cAAc,MAAM;EACpB,oBAAoB,MAAM;EAC1B,aAAa,MAAM;CACrB;AACF;;;;;;AAOA,SAAS,iBAAiB,SAA2B;CACnD,MAAM,WAAW;CACjB,IAAI,OAAO,SAAS,YAAY,YAC9B,OAAQ,SAAS,QAA2B,CAAC,CAAC,KAAI,SAAQ;EACxD,MAAM,EAAE,IAAI,SAAS;EACrB,OAAO,MAAM,QAAQ;CACvB,CAAC;CAEH,OAAO,OAAO,KAAK,OAAO;AAC5B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,YAAb,cAA+BC,gBAAAA,IAAI,IAAI;CACrC;CACA;CACA;CACA;;CAEA;CACA;CAKA,iBAAiB;CAEjB,YAAY,SAA2B;EACrC,MAAM;EACN,KAAK,iBAAiB,QAAQ;EAC9B,MAAM,UAAU;GACd,QAAQ,SAAS,WAAW,KAAA;GAC5B,QAAQ,QAAQ,UAAU,KAAA;GAC1B,QAAQ,WAAW,aAAa,KAAA;EAClC,CAAC,CAAC,OAAO,OAAO;EAChB,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,MACR,mHACa,QAAQ,WAAW,IAAI,SAAS,QAAQ,KAAK,KAAK,EAAE,EACnE;EAGF,KAAK,UAAU,QAAQ,UAAU;EACjC,KAAK,kB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A,sBAAsB;QAAWC,qBAAAA,uBAAuB,OAAO,UAAU;MAAS;KAC9F;IACF,CAAC;GACL;EACF,SAAS,OAAO;GAEd,IAAI,KAAK,gBAAgB,OAAO,SAAS;GACzC,MAAM;EACR,UAAU;GACR,KAAK,gBAAgB,OAAO,oBAAoB,SAAS,OAAO;EAClE;EAEA,IAAI,KAAK,gBAAgB,OAAO,SAAS;EAEzC,IAAI,OAAO,KAAK,MAAM,IAAI;GAAE;GAAI,OAAO,kBAAkB,KAAK;EAAE,CAAC;CACnE;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { n as VOICE_TEXT_FLUSH, r as VOICE_TURN_METADATA, t as VOICE_FLUSH_METADATA } from "./turn-metrics-CqqzdLDe.js";
2
- import { a as createAgentReplyGenerator, c as chatContextToMessages, l as extractNewTurnMessages, n as mastraLLMNode, r as observeVoiceSession, s as instrumentVoiceReply, t as createRemoteAgentReplyGenerator } from "./remote-CIMCGicy.js";
2
+ import { a as createAgentReplyGenerator, c as chatContextToMessages, l as extractNewTurnMessages, n as mastraLLMNode, r as observeVoiceSession, s as instrumentVoiceReply, t as createRemoteAgentReplyGenerator } from "./remote-Dgn5fQLl.js";
3
3
  import { DEFAULT_API_CONNECT_OPTIONS, llm } from "@livekit/agents";
4
4
  import { RequestContext } from "@mastra/core/request-context";
5
5
  //#region src/llm-plugin.ts
@@ -1 +1 @@
1
- {"version":3,"file":"plugin-entry.js","names":["#model","#onTurnMetrics","#memory","#requestContext","#staticGenerator","#remoteOptions","#warnedToolCtx","#generator"],"sources":["../src/llm-plugin.ts"],"sourcesContent":["import { DEFAULT_API_CONNECT_OPTIONS, llm } from '@livekit/agents';\nimport type { APIConnectOptions } from '@livekit/agents';\nimport type { Agent as MastraAgent } from '@mastra/core/agent';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { createAgentReplyGenerator, instrumentVoiceReply } from './bridge';\nimport type {\n MastraVoiceAgentMemory,\n VoiceReplyGenerator,\n VoiceToolCall,\n VoiceTurnCompleteHook,\n VoiceTurnContext,\n VoiceTurnUsage,\n} from './bridge';\nimport { chatContextToMessages, extractNewTurnMessages } from './messages';\nimport { createRemoteAgentReplyGenerator } from './remote';\nimport type { RemoteMastraAgentOptions } from './remote';\nimport type { VoiceTurnMetricsHook } from './turn-metrics';\nimport { VOICE_FLUSH_METADATA, VOICE_TURN_METADATA } from './turn-metrics';\n\nexport type { RemoteMastraAgentOptions } from './remote';\n\n/**\n * Options for {@link MastraLLM}. Provide **exactly one** reply source — `remote` (the headline: a\n * Mastra app on a remote server), `agent` (an in-process Mastra agent), or `generate` (a custom\n * {@link VoiceReplyGenerator}). The `toolFeedback` / `onToolCall` / `onTurnComplete` hooks apply to\n * the `remote` and `agent` sources; a `generate` source owns its own hooks.\n */\nexport interface MastraLLMOptions {\n /** Per-attempt metrics; use observeVoiceSession for playback metrics. */\n onTurnMetrics?: VoiceTurnMetricsHook;\n /** Remote Mastra server. Provide exactly one of `remote`, `agent`, `generate`. */\n remote?: RemoteMastraAgentOptions;\n /** In-process Mastra agent (reuses `createAgentReplyGenerator`). */\n agent?: MastraAgent;\n /** Custom reply source (escape hatch; owns its own tool-feedback / turn-complete behavior). */\n generate?: VoiceReplyGenerator;\n\n /**\n * Conversation persistence, resolved by the customer per call (from SIP/caller identity). When set,\n * only messages new since the agent last spoke are sent each turn and Mastra Memory supplies\n * history. When omitted/false, the full LiveKit chat context is sent every turn.\n *\n * NOTE: incompatible with the session's `preemptiveGeneration` option — a speculative turn\n * persists a partial user message and a partial reply before being discarded. Leave preemptive\n * generation off when using `memory`, or set `memory.options.readOnly` and persist committed\n * turns yourself from the session's conversation-item events.\n *\n * The plugin cannot detect the combination at runtime, so this stays a documented constraint\n * rather than a warning: the LLM interface never receives the session (so the option can't be\n * read), a preemptive `chat()` is shape-identical to a real turn (LiveKit drives the same\n * `generateReply` with a draft transcript and no marker), and the observable signature — a\n * cancelled stream followed by a `chat()` whose trailing user message changed — is exactly what\n * an ordinary barge-in correction looks like, so a heuristic would warn on every barge-in.\n */\n memory?: MastraVoiceAgentMemory | false;\n /** Request context forwarded to generation (tenant, dialed number, ...). */\n requestContext?: RequestContext | Record<string, unknown>;\n\n /** Speak a short filler while a (server-side) tool runs. Applies to the `remote`/`agent` sources. */\n toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;\n /** Notified as each tool-call chunk arrives, mid-stream. Applies to the `remote`/`agent` sources. */\n onToolCall?: (toolCall: VoiceToolCall) => void;\n /** Fired off the audio path after each reply finishes. Applies to the `remote`/`agent` sources. */\n onTurnComplete?: VoiceTurnCompleteHook;\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\nfunction mapUsageToLiveKit(usage: VoiceTurnUsage): llm.CompletionUsage {\n return {\n completionTokens: usage.completionTokens,\n promptTokens: usage.promptTokens,\n promptCachedTokens: usage.promptCachedTokens,\n totalTokens: usage.totalTokens,\n };\n}\n\n/**\n * Tool names carried by a `toolCtx`, across @livekit/agents versions: 1.5+ always passes a\n * `ToolContext` class instance (tools behind getters, `Object.keys` sees only private fields),\n * while 1.4 and the object shorthand pass a plain name→tool map.\n */\nfunction livekitToolNames(toolCtx: object): string[] {\n const instance = toolCtx as { flatten?: unknown };\n if (typeof instance.flatten === 'function') {\n return (instance.flatten as () => object[])().map(tool => {\n const { id, name } = tool as { id?: string; name?: string };\n return id ?? name ?? 'unknown';\n });\n }\n return Object.keys(toolCtx);\n}\n\n/**\n * A standard LiveKit LLM plugin (`llm.LLM`) backed by a Mastra agent. Drop it into the `llm` slot of a\n * customer-owned `voice.AgentSession` and the Mastra app (agent loop, tools, memory, observability)\n * runs wherever it's deployed — most importantly on a **remote** Mastra server reached over HTTP.\n *\n * Tools are defined and executed **server-side** on the Mastra agent; LiveKit-side `toolCtx` is\n * ignored (with a one-time warning). Tool activity surfaces via `toolFeedback` (spoken) and\n * `onToolCall` / `onTurnComplete` (programmatic). `voice.Agent` instructions do **not** reach the\n * Mastra agent — put instructions on the Mastra agent instead.\n *\n * @example\n * ```ts\n * const session = new voice.AgentSession({\n * stt: 'deepgram/nova-3',\n * tts: 'cartesia/sonic-3',\n * llm: new MastraLLM({\n * remote: { baseUrl: process.env.MASTRA_URL!, agentId: 'callCenter' },\n * memory: { thread: callId, resource: callerId },\n * }),\n * });\n * ```\n */\nexport class MastraLLM extends llm.LLM {\n readonly #model: string;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n /** Non-remote sources are built once; remote is built per turn so it can pick up `connOptions.timeoutMs`. */\n readonly #staticGenerator?: VoiceReplyGenerator;\n readonly #remoteOptions?: RemoteMastraAgentOptions & {\n toolFeedback?: MastraLLMOptions['toolFeedback'];\n onToolCall?: MastraLLMOptions['onToolCall'];\n onTurnComplete?: VoiceTurnCompleteHook;\n };\n #warnedToolCtx = false;\n\n constructor(options: MastraLLMOptions) {\n super();\n this.#onTurnMetrics = options.onTurnMetrics;\n const sources = [\n options.remote ? 'remote' : undefined,\n options.agent ? 'agent' : undefined,\n options.generate ? 'generate' : undefined,\n ].filter(Boolean) as string[];\n if (sources.length !== 1) {\n throw new Error(\n `@mastra/livekit: MastraLLM requires exactly one reply source — \\`remote\\`, \\`agent\\`, or \\`generate\\` — ` +\n `but got ${sources.length === 0 ? 'none' : sources.join(' + ')}.`,\n );\n }\n\n this.#memory = options.memory ?? false;\n this.#requestContext = toRequestContext(options.requestContext);\n\n if (options.remote) {\n this.#model = options.remote.agentId;\n this.#remoteOptions = {\n ...options.remote,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n };\n } else if (options.agent) {\n this.#model = options.agent.id ?? options.agent.name;\n this.#staticGenerator = createAgentReplyGenerator({\n agent: options.agent,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n });\n } else {\n this.#model = 'mastra-generator';\n this.#staticGenerator = options.generate;\n }\n }\n\n label(): string {\n return 'mastra.MastraLLM';\n }\n\n override get model(): string {\n return this.#model;\n }\n\n override get provider(): string {\n return 'mastra';\n }\n\n /**\n * Resolves the reply generator for a turn. Non-remote sources are built once; the remote transport\n * is built per turn so its connect + first-token timeout can come from the session's\n * `connOptions.timeoutMs`, with base-class retries owning retry (transport `retries: 0`).\n */\n private resolveGenerator(connOptions: APIConnectOptions): VoiceReplyGenerator {\n if (this.#staticGenerator) return this.#staticGenerator;\n const remote = this.#remoteOptions!;\n return createRemoteAgentReplyGenerator({\n ...remote,\n retries: 0,\n timeoutMs: remote.timeoutMs ?? connOptions.timeoutMs,\n });\n }\n\n override chat({\n chatCtx,\n toolCtx,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): llm.LLMStream {\n // Tools run server-side; warn once if the customer wired LiveKit-side tools.\n if (!this.#warnedToolCtx && toolCtx) {\n const ignored = livekitToolNames(toolCtx);\n if (ignored.length > 0) {\n this.#warnedToolCtx = true;\n console.warn(\n `@mastra/livekit: MastraLLM ignores LiveKit-side tools (${ignored.join(', ')}). ` +\n `Tools are defined and executed server-side on the Mastra agent — move them there.`,\n );\n }\n }\n return new MastraLLMStream(this, {\n chatCtx,\n toolCtx,\n connOptions,\n generator: this.resolveGenerator(connOptions),\n onTurnMetrics: this.#onTurnMetrics,\n memory: this.#memory,\n requestContext: this.#requestContext,\n });\n }\n\n /** No-op in v1: nothing in the LiveKit session/worker ever calls `prewarm()` automatically. */\n override prewarm(): void {}\n}\n\ninterface MastraLLMStreamOptions {\n onTurnMetrics?: VoiceTurnMetricsHook;\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions: APIConnectOptions;\n generator: VoiceReplyGenerator;\n memory: MastraVoiceAgentMemory | false;\n requestContext?: RequestContext;\n}\n\n/**\n * The `llm.LLMStream` `MastraLLM` returns per turn. `run()` extracts the turn's messages, drives\n * the reply generator, and pushes assistant `ChatChunk`s into `this.queue` (NOT `this.output` — the\n * base class drains queue → output and computes TTFT / duration / usage). Barge-in aborts via\n * `this.abortController` and `run()` returns silently.\n */\nclass MastraLLMStream extends llm.LLMStream {\n readonly #generator: VoiceReplyGenerator;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n\n constructor(mastraLLM: MastraLLM, options: MastraLLMStreamOptions) {\n super(mastraLLM, { chatCtx: options.chatCtx, toolCtx: options.toolCtx, connOptions: options.connOptions });\n this.#generator = options.generator;\n this.#onTurnMetrics = options.onTurnMetrics;\n this.#memory = options.memory;\n this.#requestContext = options.requestContext;\n }\n\n protected async run(): Promise<void> {\n const messages =\n this.#memory === false ? chatContextToMessages(this.chatCtx) : extractNewTurnMessages(this.chatCtx);\n // No new input to answer → close without a request (equivalent to the wrapper returning null).\n if (messages.length === 0) return;\n\n let usage: VoiceTurnUsage | undefined;\n const turnCtx: VoiceTurnContext = {\n messages,\n chatCtx: this.chatCtx,\n memory: this.#memory,\n requestContext: this.#requestContext,\n onUsage: turnUsage => {\n usage = turnUsage;\n },\n };\n\n const { reply, identity } = await instrumentVoiceReply(this.#generator, turnCtx, this.#onTurnMetrics);\n if (!reply) return;\n if (this.abortController.signal.aborted) {\n await reply.cancel().catch(() => {});\n return;\n }\n\n // A single provider response id ties all of this turn's chunks together for the base class metrics.\n const id = identity.attemptId;\n const reader = reply.getReader();\n const onAbort = () => void reader.cancel().catch(() => {});\n this.abortController.signal.addEventListener('abort', onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.abortController.signal.aborted) break;\n if (value)\n this.queue.put({\n id,\n delta: {\n role: 'assistant',\n ...(typeof value === 'string' ? { content: value } : {}),\n extra: { [VOICE_TURN_METADATA]: identity, [VOICE_FLUSH_METADATA]: typeof value !== 'string' },\n },\n });\n }\n } catch (error) {\n // Barge-in tears down the reply stream; that surfaces as a read rejection but is not a failure.\n if (this.abortController.signal.aborted) return;\n throw error;\n } finally {\n this.abortController.signal.removeEventListener('abort', onAbort);\n }\n // Return silently on barge-in — throwing would feed the base class's error/retry machinery.\n if (this.abortController.signal.aborted) return;\n // Final usage-only chunk → the base class reads usage from the last chunk that carries it.\n if (usage) this.queue.put({ id, usage: mapUsageToLiveKit(usage) });\n }\n}\n\nexport { MastraLLMStream };\n"],"mappings":";;;;;AAkEA,SAAS,iBAAiB,OAAyF;CACjH,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,iBAAiB,gBAAgB,OAAO;CAC5C,OAAO,IAAI,eAAwB,OAAO,QAAQ,KAAK,CAAC;AAC1D;AAEA,SAAS,kBAAkB,OAA4C;CACrE,OAAO;EACL,kBAAkB,MAAM;EACxB,cAAc,MAAM;EACpB,oBAAoB,MAAM;EAC1B,aAAa,MAAM;CACrB;AACF;;;;;;AAOA,SAAS,iBAAiB,SAA2B;CACnD,MAAM,WAAW;CACjB,IAAI,OAAO,SAAS,YAAY,YAC9B,OAAQ,SAAS,QAA2B,CAAC,CAAC,KAAI,SAAQ;EACxD,MAAM,EAAE,IAAI,SAAS;EACrB,OAAO,MAAM,QAAQ;CACvB,CAAC;CAEH,OAAO,OAAO,KAAK,OAAO;AAC5B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,YAAb,cAA+B,IAAI,IAAI;CACrC;CACA;CACA;CACA;;CAEA;CACA;CAKA,iBAAiB;CAEjB,YAAY,SAA2B;EACrC,MAAM;EACN,KAAKC,iBAAiB,QAAQ;EAC9B,MAAM,UAAU;GACd,QAAQ,SAAS,WAAW,KAAA;GAC5B,QAAQ,QAAQ,UAAU,KAAA;GAC1B,QAAQ,WAAW,aAAa,KAAA;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B,OAAO,SAAS;IACzC,IAAI,OACF,KAAK,MAAM,IAAI;KACb;KACA,OAAO;MACL,MAAM;MACN,GAAI,OAAO,UAAU,WAAW,EAAE,SAAS,MAAM,IAAI,CAAC;MACtD,OAAO;QAAG,sBAAsB;QAAW,uBAAuB,OAAO,UAAU;MAAS;KAC9F;IACF,CAAC;GACL;EACF,SAAS,OAAO;GAEd,IAAI,KAAK,gBAAgB,OAAO,SAAS;GACzC,MAAM;EACR,UAAU;GACR,KAAK,gBAAgB,OAAO,oBAAoB,SAAS,OAAO;EAClE;EAEA,IAAI,KAAK,gBAAgB,OAAO,SAAS;EAEzC,IAAI,OAAO,KAAK,MAAM,IAAI;GAAE;GAAI,OAAO,kBAAkB,KAAK;EAAE,CAAC;CACnE;AACF"}
1
+ {"version":3,"file":"plugin-entry.js","names":[],"sources":["../src/llm-plugin.ts"],"sourcesContent":["import { DEFAULT_API_CONNECT_OPTIONS, llm } from '@livekit/agents';\nimport type { APIConnectOptions } from '@livekit/agents';\nimport type { Agent as MastraAgent } from '@mastra/core/agent';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { createAgentReplyGenerator, instrumentVoiceReply } from './bridge';\nimport type {\n MastraVoiceAgentMemory,\n VoiceReplyGenerator,\n VoiceToolCall,\n VoiceTurnCompleteHook,\n VoiceTurnContext,\n VoiceTurnUsage,\n} from './bridge';\nimport { chatContextToMessages, extractNewTurnMessages } from './messages';\nimport { createRemoteAgentReplyGenerator } from './remote';\nimport type { RemoteMastraAgentOptions } from './remote';\nimport type { VoiceTurnMetricsHook } from './turn-metrics';\nimport { VOICE_FLUSH_METADATA, VOICE_TURN_METADATA } from './turn-metrics';\n\nexport type { RemoteMastraAgentOptions } from './remote';\n\n/**\n * Options for {@link MastraLLM}. Provide **exactly one** reply source — `remote` (the headline: a\n * Mastra app on a remote server), `agent` (an in-process Mastra agent), or `generate` (a custom\n * {@link VoiceReplyGenerator}). The `toolFeedback` / `onToolCall` / `onTurnComplete` hooks apply to\n * the `remote` and `agent` sources; a `generate` source owns its own hooks.\n */\nexport interface MastraLLMOptions {\n /** Per-attempt metrics; use observeVoiceSession for playback metrics. */\n onTurnMetrics?: VoiceTurnMetricsHook;\n /** Remote Mastra server. Provide exactly one of `remote`, `agent`, `generate`. */\n remote?: RemoteMastraAgentOptions;\n /** In-process Mastra agent (reuses `createAgentReplyGenerator`). */\n agent?: MastraAgent;\n /** Custom reply source (escape hatch; owns its own tool-feedback / turn-complete behavior). */\n generate?: VoiceReplyGenerator;\n\n /**\n * Conversation persistence, resolved by the customer per call (from SIP/caller identity). When set,\n * only messages new since the agent last spoke are sent each turn and Mastra Memory supplies\n * history. When omitted/false, the full LiveKit chat context is sent every turn.\n *\n * NOTE: incompatible with the session's `preemptiveGeneration` option — a speculative turn\n * persists a partial user message and a partial reply before being discarded. Leave preemptive\n * generation off when using `memory`, or set `memory.options.readOnly` and persist committed\n * turns yourself from the session's conversation-item events.\n *\n * The plugin cannot detect the combination at runtime, so this stays a documented constraint\n * rather than a warning: the LLM interface never receives the session (so the option can't be\n * read), a preemptive `chat()` is shape-identical to a real turn (LiveKit drives the same\n * `generateReply` with a draft transcript and no marker), and the observable signature — a\n * cancelled stream followed by a `chat()` whose trailing user message changed — is exactly what\n * an ordinary barge-in correction looks like, so a heuristic would warn on every barge-in.\n */\n memory?: MastraVoiceAgentMemory | false;\n /** Request context forwarded to generation (tenant, dialed number, ...). */\n requestContext?: RequestContext | Record<string, unknown>;\n\n /** Speak a short filler while a (server-side) tool runs. Applies to the `remote`/`agent` sources. */\n toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;\n /** Notified as each tool-call chunk arrives, mid-stream. Applies to the `remote`/`agent` sources. */\n onToolCall?: (toolCall: VoiceToolCall) => void;\n /** Fired off the audio path after each reply finishes. Applies to the `remote`/`agent` sources. */\n onTurnComplete?: VoiceTurnCompleteHook;\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\nfunction mapUsageToLiveKit(usage: VoiceTurnUsage): llm.CompletionUsage {\n return {\n completionTokens: usage.completionTokens,\n promptTokens: usage.promptTokens,\n promptCachedTokens: usage.promptCachedTokens,\n totalTokens: usage.totalTokens,\n };\n}\n\n/**\n * Tool names carried by a `toolCtx`, across @livekit/agents versions: 1.5+ always passes a\n * `ToolContext` class instance (tools behind getters, `Object.keys` sees only private fields),\n * while 1.4 and the object shorthand pass a plain name→tool map.\n */\nfunction livekitToolNames(toolCtx: object): string[] {\n const instance = toolCtx as { flatten?: unknown };\n if (typeof instance.flatten === 'function') {\n return (instance.flatten as () => object[])().map(tool => {\n const { id, name } = tool as { id?: string; name?: string };\n return id ?? name ?? 'unknown';\n });\n }\n return Object.keys(toolCtx);\n}\n\n/**\n * A standard LiveKit LLM plugin (`llm.LLM`) backed by a Mastra agent. Drop it into the `llm` slot of a\n * customer-owned `voice.AgentSession` and the Mastra app (agent loop, tools, memory, observability)\n * runs wherever it's deployed — most importantly on a **remote** Mastra server reached over HTTP.\n *\n * Tools are defined and executed **server-side** on the Mastra agent; LiveKit-side `toolCtx` is\n * ignored (with a one-time warning). Tool activity surfaces via `toolFeedback` (spoken) and\n * `onToolCall` / `onTurnComplete` (programmatic). `voice.Agent` instructions do **not** reach the\n * Mastra agent — put instructions on the Mastra agent instead.\n *\n * @example\n * ```ts\n * const session = new voice.AgentSession({\n * stt: 'deepgram/nova-3',\n * tts: 'cartesia/sonic-3',\n * llm: new MastraLLM({\n * remote: { baseUrl: process.env.MASTRA_URL!, agentId: 'callCenter' },\n * memory: { thread: callId, resource: callerId },\n * }),\n * });\n * ```\n */\nexport class MastraLLM extends llm.LLM {\n readonly #model: string;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n /** Non-remote sources are built once; remote is built per turn so it can pick up `connOptions.timeoutMs`. */\n readonly #staticGenerator?: VoiceReplyGenerator;\n readonly #remoteOptions?: RemoteMastraAgentOptions & {\n toolFeedback?: MastraLLMOptions['toolFeedback'];\n onToolCall?: MastraLLMOptions['onToolCall'];\n onTurnComplete?: VoiceTurnCompleteHook;\n };\n #warnedToolCtx = false;\n\n constructor(options: MastraLLMOptions) {\n super();\n this.#onTurnMetrics = options.onTurnMetrics;\n const sources = [\n options.remote ? 'remote' : undefined,\n options.agent ? 'agent' : undefined,\n options.generate ? 'generate' : undefined,\n ].filter(Boolean) as string[];\n if (sources.length !== 1) {\n throw new Error(\n `@mastra/livekit: MastraLLM requires exactly one reply source — \\`remote\\`, \\`agent\\`, or \\`generate\\` — ` +\n `but got ${sources.length === 0 ? 'none' : sources.join(' + ')}.`,\n );\n }\n\n this.#memory = options.memory ?? false;\n this.#requestContext = toRequestContext(options.requestContext);\n\n if (options.remote) {\n this.#model = options.remote.agentId;\n this.#remoteOptions = {\n ...options.remote,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n };\n } else if (options.agent) {\n this.#model = options.agent.id ?? options.agent.name;\n this.#staticGenerator = createAgentReplyGenerator({\n agent: options.agent,\n toolFeedback: options.toolFeedback,\n onToolCall: options.onToolCall,\n onTurnComplete: options.onTurnComplete,\n });\n } else {\n this.#model = 'mastra-generator';\n this.#staticGenerator = options.generate;\n }\n }\n\n label(): string {\n return 'mastra.MastraLLM';\n }\n\n override get model(): string {\n return this.#model;\n }\n\n override get provider(): string {\n return 'mastra';\n }\n\n /**\n * Resolves the reply generator for a turn. Non-remote sources are built once; the remote transport\n * is built per turn so its connect + first-token timeout can come from the session's\n * `connOptions.timeoutMs`, with base-class retries owning retry (transport `retries: 0`).\n */\n private resolveGenerator(connOptions: APIConnectOptions): VoiceReplyGenerator {\n if (this.#staticGenerator) return this.#staticGenerator;\n const remote = this.#remoteOptions!;\n return createRemoteAgentReplyGenerator({\n ...remote,\n retries: 0,\n timeoutMs: remote.timeoutMs ?? connOptions.timeoutMs,\n });\n }\n\n override chat({\n chatCtx,\n toolCtx,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): llm.LLMStream {\n // Tools run server-side; warn once if the customer wired LiveKit-side tools.\n if (!this.#warnedToolCtx && toolCtx) {\n const ignored = livekitToolNames(toolCtx);\n if (ignored.length > 0) {\n this.#warnedToolCtx = true;\n console.warn(\n `@mastra/livekit: MastraLLM ignores LiveKit-side tools (${ignored.join(', ')}). ` +\n `Tools are defined and executed server-side on the Mastra agent — move them there.`,\n );\n }\n }\n return new MastraLLMStream(this, {\n chatCtx,\n toolCtx,\n connOptions,\n generator: this.resolveGenerator(connOptions),\n onTurnMetrics: this.#onTurnMetrics,\n memory: this.#memory,\n requestContext: this.#requestContext,\n });\n }\n\n /** No-op in v1: nothing in the LiveKit session/worker ever calls `prewarm()` automatically. */\n override prewarm(): void {}\n}\n\ninterface MastraLLMStreamOptions {\n onTurnMetrics?: VoiceTurnMetricsHook;\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContext;\n connOptions: APIConnectOptions;\n generator: VoiceReplyGenerator;\n memory: MastraVoiceAgentMemory | false;\n requestContext?: RequestContext;\n}\n\n/**\n * The `llm.LLMStream` `MastraLLM` returns per turn. `run()` extracts the turn's messages, drives\n * the reply generator, and pushes assistant `ChatChunk`s into `this.queue` (NOT `this.output` — the\n * base class drains queue → output and computes TTFT / duration / usage). Barge-in aborts via\n * `this.abortController` and `run()` returns silently.\n */\nclass MastraLLMStream extends llm.LLMStream {\n readonly #generator: VoiceReplyGenerator;\n readonly #onTurnMetrics?: VoiceTurnMetricsHook;\n readonly #memory: MastraVoiceAgentMemory | false;\n readonly #requestContext?: RequestContext;\n\n constructor(mastraLLM: MastraLLM, options: MastraLLMStreamOptions) {\n super(mastraLLM, { chatCtx: options.chatCtx, toolCtx: options.toolCtx, connOptions: options.connOptions });\n this.#generator = options.generator;\n this.#onTurnMetrics = options.onTurnMetrics;\n this.#memory = options.memory;\n this.#requestContext = options.requestContext;\n }\n\n protected async run(): Promise<void> {\n const messages =\n this.#memory === false ? chatContextToMessages(this.chatCtx) : extractNewTurnMessages(this.chatCtx);\n // No new input to answer → close without a request (equivalent to the wrapper returning null).\n if (messages.length === 0) return;\n\n let usage: VoiceTurnUsage | undefined;\n const turnCtx: VoiceTurnContext = {\n messages,\n chatCtx: this.chatCtx,\n memory: this.#memory,\n requestContext: this.#requestContext,\n onUsage: turnUsage => {\n usage = turnUsage;\n },\n };\n\n const { reply, identity } = await instrumentVoiceReply(this.#generator, turnCtx, this.#onTurnMetrics);\n if (!reply) return;\n if (this.abortController.signal.aborted) {\n await reply.cancel().catch(() => {});\n return;\n }\n\n // A single provider response id ties all of this turn's chunks together for the base class metrics.\n const id = identity.attemptId;\n const reader = reply.getReader();\n const onAbort = () => void reader.cancel().catch(() => {});\n this.abortController.signal.addEventListener('abort', onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (this.abortController.signal.aborted) break;\n if (value)\n this.queue.put({\n id,\n delta: {\n role: 'assistant',\n ...(typeof value === 'string' ? { content: value } : {}),\n extra: { [VOICE_TURN_METADATA]: identity, [VOICE_FLUSH_METADATA]: typeof value !== 'string' },\n },\n });\n }\n } catch (error) {\n // Barge-in tears down the reply stream; that surfaces as a read rejection but is not a failure.\n if (this.abortController.signal.aborted) return;\n throw error;\n } finally {\n this.abortController.signal.removeEventListener('abort', onAbort);\n }\n // Return silently on barge-in — throwing would feed the base class's error/retry machinery.\n if (this.abortController.signal.aborted) return;\n // Final usage-only chunk → the base class reads usage from the last chunk that carries it.\n if (usage) this.queue.put({ id, usage: mapUsageToLiveKit(usage) });\n }\n}\n\nexport { MastraLLMStream };\n"],"mappings":";;;;;AAkEA,SAAS,iBAA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;AACF"}
@@ -779,7 +779,6 @@ function createRemoteAgentReplyGenerator(options) {
779
779
  const error = payload.error;
780
780
  throw error instanceof Error ? error : new Error(String(error));
781
781
  }
782
- default: break;
783
782
  }
784
783
  }
785
784
  clearWatchdog();
@@ -819,4 +818,4 @@ function createRemoteAgentReplyGenerator(options) {
819
818
  //#endregion
820
819
  export { createAgentReplyGenerator as a, chatContextToMessages as c, MastraVoiceAgent as i, extractNewTurnMessages as l, mastraLLMNode as n, createMastraVoiceAgent as o, observeVoiceSession as r, instrumentVoiceReply as s, createRemoteAgentReplyGenerator as t };
821
820
 
822
- //# sourceMappingURL=remote-CIMCGicy.js.map
821
+ //# sourceMappingURL=remote-Dgn5fQLl.js.map