@mastra/voice-google 0.13.0-alpha.0 → 0.14.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/dist/_types/@internal_voice/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +93 -3
- package/dist/_types/@internal_voice/dist/_types/@internal_core/dist/request-context/index.d.ts +10 -0
- package/dist/docs/SKILL.md +1 -2
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-voice-overview.md +5 -3
- package/dist/docs/references/reference-voice-google.md +50 -8
- package/dist/index.cjs +72 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +45 -18
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +73 -17
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/dist/docs/references/docs-agents-adding-voice.md +0 -381
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/_internal-core/src/logger/index.ts","../../../packages/_internal-core/src/base/MastraBase.ts","../../../packages/_internals/voice/src/voice/voice.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;AAEO,IAAM,gBAAA,GAAmB;EAO9B,GAAA,EAAK,KAcP,CAAA;AAIO,IAAM,QAAA,GAAW;EACtB,KAAA,EAAO,OAAA;EACP,IAAA,EAAM,MAAA;EACN,IAAA,EAAM,MAAA;EACN,KAAA,EAAO,OAET,CAAA;AAsGO,IAAe,eAAf,MAAqD;AAChD,EAAA,IAAA;AACA,EAAA,KAAA;AACA,EAAA,UAAA;EAEV,WAAA,CACE,OAAA,GAII,EAAA,EACJ;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,QAAQ,IAAA,IAAQ,QAAA;AAC5B,IAAA,IAAA,CAAK,KAAA,GAAQ,OAAA,CAAQ,KAAA,IAAS,QAAA,CAAS,KAAA;AACvC,IAAA,IAAA,CAAK,UAAA,GAAa,IAAI,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,IAAI,CAAC,MAAA,CAAO,YAAA,IAAgB,MAAA,CAAO,YAAA,CAAa,WAAW,CAAA,EAAG;AAC5D,QAAA,OAAO,EAAA;AAAA,MACT;AACA,MAAA,OAAO,MAAA,CAAO,YAAA,CAAa,CAAC,CAAA,CAAE,UAAA,IAAc,EAAA;AAAA,IAC9C,CAAC,CAAA,CACA,MAAA,CAAO,CAAC,IAAA,KAAiB,KAAK,MAAA,GAAS,CAAC,CAAA,CACxC,IAAA,CAAK,GAAG,CAAA;AAEX,IAAA,IAAI,CAAC,aAAA,EAAe;AAClB,MAAA,MAAM,IAAI,MAAM,yCAAyC,CAAA;AAAA,IAC3D;AAEA,IAAA,OAAO,aAAA;AAAA,EACT;AACF","file":"index.js","sourcesContent":["import { Transform } from 'node:stream';\n\nexport const RegisteredLogger = {\n AGENT: 'AGENT',\n OBSERVABILITY: 'OBSERVABILITY',\n AUTH: 'AUTH',\n BROWSER: 'BROWSER',\n NETWORK: 'NETWORK',\n WORKFLOW: 'WORKFLOW',\n LLM: 'LLM',\n TTS: 'TTS',\n VOICE: 'VOICE',\n VECTOR: 'VECTOR',\n BUNDLER: 'BUNDLER',\n DEPLOYER: 'DEPLOYER',\n MEMORY: 'MEMORY',\n STORAGE: 'STORAGE',\n EMBEDDINGS: 'EMBEDDINGS',\n MCP_SERVER: 'MCP_SERVER',\n SERVER_CACHE: 'SERVER_CACHE',\n SERVER: 'SERVER',\n WORKSPACE: 'WORKSPACE',\n CHANNEL: 'CHANNEL',\n} as const;\n\nexport type RegisteredLogger = (typeof RegisteredLogger)[keyof typeof RegisteredLogger];\n\nexport const LogLevel = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n NONE: 'silent',\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n\nexport interface BaseLogMessage {\n runId?: string;\n msg: string;\n level: LogLevel;\n time: Date;\n pid: number;\n hostname: string;\n name: string;\n}\n\nexport abstract class LoggerTransport extends Transform {\n constructor(opts: any = {}) {\n super({ ...opts, objectMode: true });\n }\n\n async listLogsByRunId(_args: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return { logs: [], total: 0, page: _args?.page ?? 1, perPage: _args?.perPage ?? 100, hasMore: false };\n }\n\n async listLogs(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return { logs: [], total: 0, page: _args?.page ?? 1, perPage: _args?.perPage ?? 100, hasMore: false };\n }\n}\n\nexport const createCustomTransport = (\n stream: Transform,\n listLogs?: LoggerTransport['listLogs'],\n listLogsByRunId?: LoggerTransport['listLogsByRunId'],\n) => {\n let transport = stream as LoggerTransport;\n if (listLogs) {\n transport.listLogs = listLogs;\n }\n if (listLogsByRunId) {\n transport.listLogsByRunId = listLogsByRunId;\n }\n return transport as LoggerTransport;\n};\n\nexport interface IMastraLogger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n trackException(error: Error, metadata?: Record<string, unknown>): void;\n\n getTransports(): Map<string, LoggerTransport>;\n listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n}\n\nexport abstract class MastraLogger implements IMastraLogger {\n protected name: string;\n protected level: LogLevel;\n protected transports: Map<string, LoggerTransport>;\n\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n } = {},\n ) {\n this.name = options.name || 'Mastra';\n this.level = options.level || LogLevel.ERROR;\n this.transports = new Map(Object.entries(options.transports || {}));\n }\n\n abstract debug(message: string, ...args: any[]): void;\n abstract info(message: string, ...args: any[]): void;\n abstract warn(message: string, ...args: any[]): void;\n abstract error(message: string, ...args: any[]): void;\n\n getTransports() {\n return this.transports;\n }\n\n trackException(_error: Error, _metadata?: Record<string, unknown>) {}\n\n async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId || !this.transports.has(transportId)) {\n return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports.get(transportId)!.listLogs?.(params) ?? {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n }\n );\n }\n\n async listLogsByRunId({\n transportId,\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId || !this.transports.has(transportId) || !runId) {\n return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports\n .get(transportId)!\n .listLogsByRunId?.({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n }\n );\n }\n}\n\nexport type LogFilterContext = {\n component?: RegisteredLogger;\n level: LogLevel;\n message: string;\n args: unknown[];\n};\n\nexport type LogFilter = (ctx: LogFilterContext) => boolean;\n\nexport interface ConsoleLoggerOptions {\n name?: string;\n level?: LogLevel;\n component?: RegisteredLogger;\n filter?: LogFilter;\n}\n\nexport class ConsoleLogger extends MastraLogger {\n protected component?: RegisteredLogger;\n protected filter?: LogFilter;\n\n constructor(options: ConsoleLoggerOptions = {}) {\n super(options);\n this.component = options.component;\n this.filter = options.filter;\n }\n\n child(componentOrBindings: RegisteredLogger | Record<string, unknown>): ConsoleLogger {\n const component =\n typeof componentOrBindings === 'string'\n ? componentOrBindings\n : ((componentOrBindings?.component as RegisteredLogger) ?? this.component);\n return new ConsoleLogger({\n name: this.name,\n level: this.level,\n component,\n filter: this.filter,\n });\n }\n\n private shouldLog(level: LogLevel, message: string, args: unknown[]): boolean {\n if (!this.filter) return true;\n try {\n return this.filter({ component: this.component, level, message, args });\n } catch (e) {\n console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n return true;\n }\n }\n\n private prefix(): string {\n return this.component ? `[${this.component}] ` : '';\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) {\n console.info(`${this.prefix()}${message}`, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (\n (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) &&\n this.shouldLog(LogLevel.INFO, message, args)\n ) {\n console.info(`${this.prefix()}${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (\n (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) &&\n this.shouldLog(LogLevel.WARN, message, args)\n ) {\n console.warn(`${this.prefix()}${message}`, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (\n (this.level === LogLevel.ERROR ||\n this.level === LogLevel.WARN ||\n this.level === LogLevel.INFO ||\n this.level === LogLevel.DEBUG) &&\n this.shouldLog(LogLevel.ERROR, message, args)\n ) {\n console.error(`${this.prefix()}${message}`, ...args);\n }\n }\n\n async listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };\n }\n\n async listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };\n }\n}\n","import type { IMastraLogger } from '../logger';\nimport { ConsoleLogger, RegisteredLogger } from '../logger';\n\nexport class MastraBase {\n component: RegisteredLogger = RegisteredLogger.LLM;\n protected logger: IMastraLogger;\n name?: string;\n #rawConfig?: Record<string, unknown>;\n\n constructor({\n component,\n name,\n rawConfig,\n }: {\n component?: RegisteredLogger;\n name?: string;\n rawConfig?: Record<string, unknown>;\n }) {\n this.component = component || RegisteredLogger.LLM;\n this.name = name;\n this.#rawConfig = rawConfig;\n this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n }\n\n /**\n * Returns the raw storage configuration this primitive was created from,\n * or undefined if it was created from code.\n */\n toRawConfig(): Record<string, unknown> | undefined {\n return this.#rawConfig;\n }\n\n /**\n * Sets the raw storage configuration for this primitive.\n * @internal\n */\n __setRawConfig(rawConfig: Record<string, unknown>): void {\n this.#rawConfig = rawConfig;\n }\n\n /**\n * Set the logger for the agent\n * @param logger\n */\n __setLogger(logger: IMastraLogger) {\n this.logger =\n 'child' in logger && typeof (logger as any).child === 'function'\n ? (logger as any).child({ component: this.component })\n : logger;\n }\n}\n","import { MastraBase } from '@internal/core/base';\nimport type { ToolsInput } from '@internal/core/types';\n\nexport type VoiceEventType = 'speaking' | 'writing' | 'error' | string;\n\nexport interface VoiceEventMap {\n speaker: NodeJS.ReadableStream;\n speaking: { audio?: string };\n writing: { text: string; role: 'assistant' | 'user' };\n error: { message: string; code?: string; details?: unknown };\n [key: string]: unknown;\n}\n\ninterface BuiltInModelConfig {\n name: string;\n apiKey?: string;\n}\n\nexport interface VoiceConfig<T = unknown> {\n listeningModel?: BuiltInModelConfig;\n speechModel?: BuiltInModelConfig;\n speaker?: string;\n name?: string;\n realtimeConfig?: {\n model?: string;\n apiKey?: string;\n options?: T;\n };\n}\n\nexport interface VoiceSpanConfig {\n component: 'VOICE';\n name?: string;\n speaker?: string;\n listeningModel?: { name: string };\n speechModel?: { name: string };\n realtimeModel?: string;\n}\n\nexport interface IMastraVoice<\n TSpeakOptions = unknown,\n TListenOptions = unknown,\n TTools extends ToolsInput = ToolsInput,\n TEventArgs extends VoiceEventMap = VoiceEventMap,\n TSpeakerMetadata = unknown,\n> {\n serializeForSpan(): VoiceSpanConfig;\n speak(\n input: string | NodeJS.ReadableStream,\n options?: {\n speaker?: string;\n } & TSpeakOptions,\n ): Promise<NodeJS.ReadableStream | void>;\n listen(\n audioStream: NodeJS.ReadableStream | unknown,\n options?: TListenOptions,\n ): Promise<string | NodeJS.ReadableStream | void>;\n updateConfig(options: Record<string, unknown>): void;\n connect(options?: Record<string, unknown>): Promise<void>;\n send(audioData: NodeJS.ReadableStream | Int16Array): Promise<void>;\n answer(options?: Record<string, unknown>): Promise<void>;\n addInstructions(instructions?: string): void;\n addTools(tools: TTools): void;\n close(): void;\n on<E extends VoiceEventType>(\n event: E,\n callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void;\n off<E extends VoiceEventType>(\n event: E,\n callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void;\n getSpeakers(): Promise<\n Array<\n {\n voiceId: string;\n } & TSpeakerMetadata\n >\n >;\n getListener(): Promise<{ enabled: boolean }>;\n}\n\nexport abstract class MastraVoice<\n TOptions = unknown,\n TSpeakOptions = unknown,\n TListenOptions = unknown,\n TTools extends ToolsInput = ToolsInput,\n TEventArgs extends VoiceEventMap = VoiceEventMap,\n TSpeakerMetadata = unknown,\n>\n extends MastraBase\n implements IMastraVoice<TSpeakOptions, TListenOptions, TTools, TEventArgs, TSpeakerMetadata>\n{\n protected listeningModel?: BuiltInModelConfig;\n protected speechModel?: BuiltInModelConfig;\n protected speaker?: string;\n protected realtimeConfig?: {\n model?: string;\n apiKey?: string;\n options?: TOptions;\n };\n\n constructor({ listeningModel, speechModel, speaker, realtimeConfig, name }: VoiceConfig<TOptions> = {}) {\n super({\n component: 'VOICE',\n name,\n });\n this.listeningModel = listeningModel;\n this.speechModel = speechModel;\n this.speaker = speaker;\n this.realtimeConfig = realtimeConfig;\n }\n\n /**\n * Custom serialization for tracing/observability spans.\n * Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n * and any provider-specific state held by subclasses. Subclasses that\n * need to expose additional non-sensitive fields can override.\n */\n serializeForSpan(): VoiceSpanConfig {\n return {\n component: 'VOICE',\n name: this.name,\n speaker: this.speaker,\n listeningModel: this.listeningModel ? { name: this.listeningModel.name } : undefined,\n speechModel: this.speechModel ? { name: this.speechModel.name } : undefined,\n realtimeModel: this.realtimeConfig?.model,\n };\n }\n\n /**\n * Convert text to speech\n * @param input Text or text stream to convert to speech\n * @param options Speech options including speaker and provider-specific options\n * @returns Audio stream\n */\n /**\n * Convert text to speech\n * @param input Text or text stream to convert to speech\n * @param options Speech options including speaker and provider-specific options\n * @returns Audio stream or void if in chat mode\n */\n abstract speak(\n input: string | NodeJS.ReadableStream,\n options?: {\n speaker?: string;\n } & TSpeakOptions,\n ): Promise<NodeJS.ReadableStream | void>;\n\n /**\n * Convert speech to text\n * @param audioStream Audio stream to transcribe\n * @param options Provider-specific transcription options\n * @returns Text or text stream\n */\n /**\n * Convert speech to text\n * @param audioStream Audio stream to transcribe\n * @param options Provider-specific transcription options\n * @returns Text, text stream, or void if in chat mode\n */\n abstract listen(\n audioStream: NodeJS.ReadableStream | unknown, // Allow other audio input types for OpenAI realtime API\n options?: TListenOptions,\n ): Promise<string | NodeJS.ReadableStream | void>;\n\n updateConfig(_options: Record<string, unknown>): void {\n this.logger.debug('updateConfig not implemented by this voice provider');\n }\n\n /**\n * Initializes a WebSocket or WebRTC connection for real-time communication\n * @returns Promise that resolves when the connection is established\n */\n async connect(_options?: Record<string, unknown>): Promise<void> {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('connect not implemented by this voice provider');\n }\n\n /**\n * Relay audio data to the voice provider for real-time processing\n * @param audioData Audio data to relay\n */\n async send(_audioData: NodeJS.ReadableStream | Int16Array): Promise<void> {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('relay not implemented by this voice provider');\n }\n\n /**\n * Trigger voice providers to respond\n */\n async answer(_options?: Record<string, unknown>): Promise<void> {\n this.logger.debug('answer not implemented by this voice provider');\n }\n\n /**\n * Equip the voice provider with instructions\n * @param instructions Instructions to add\n */\n addInstructions(_instructions?: string): void {\n // Default implementation - voice providers can override if they support this feature\n }\n\n /**\n * Equip the voice provider with tools\n * @param tools Array of tools to add\n */\n addTools(_tools: TTools): void {\n // Default implementation - voice providers can override if they support this feature\n }\n\n /**\n * Disconnect from the WebSocket or WebRTC connection\n */\n close(): void {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('close not implemented by this voice provider');\n }\n\n /**\n * Register an event listener\n * @param event Event name (e.g., 'speaking', 'writing', 'error')\n * @param callback Callback function that receives event data\n */\n on<E extends VoiceEventType>(\n _event: E,\n _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('on not implemented by this voice provider');\n }\n\n /**\n * Remove an event listener\n * @param event Event name (e.g., 'speaking', 'writing', 'error')\n * @param callback Callback function to remove\n */\n off<E extends VoiceEventType>(\n _event: E,\n _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('off not implemented by this voice provider');\n }\n\n /**\n * Get available speakers/voices\n * @returns Array of available voice IDs and their metadata\n */\n getSpeakers(): Promise<\n Array<\n {\n voiceId: string;\n } & TSpeakerMetadata\n >\n > {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('getSpeakers not implemented by this voice provider');\n return Promise.resolve([]);\n }\n\n /**\n * Get available speakers/voices\n * @returns Array of available voice IDs and their metadata\n */\n getListener(): Promise<{ enabled: boolean }> {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('getListener not implemented by this voice provider');\n return Promise.resolve({ enabled: false });\n }\n}\n","import { PassThrough } from 'node:stream';\n\nimport { SpeechClient } from '@google-cloud/speech';\nimport type { google as SpeechTypes } from '@google-cloud/speech/build/protos/protos';\nimport { TextToSpeechClient } from '@google-cloud/text-to-speech';\nimport type { google as TextToSpeechTypes } from '@google-cloud/text-to-speech/build/protos/protos';\nimport { MastraVoice } from '@internal/voice';\n\n/**\n * Configuration for Google Cloud Voice models\n * @interface GoogleModelConfig\n * @property {string} [apiKey] - Optional Google Cloud API key. If not provided, will use GOOGLE_API_KEY environment variable\n * @property {string} [keyFilename] - Optional path to a service account key file. If not provided, will use GOOGLE_APPLICATION_CREDENTIALS environment variable\n * @property {{ client_email?: string; private_key?: string }} [credentials] - Optional in-memory service account credentials\n */\nexport interface GoogleModelConfig {\n apiKey?: string;\n keyFilename?: string;\n credentials?: {\n client_email?: string;\n private_key?: string;\n [key: string]: unknown;\n };\n}\n\n/**\n * Configuration options for GoogleVoice\n * @interface GoogleVoiceConfig\n */\nexport interface GoogleVoiceConfig {\n /** Configuration for speech synthesis (TTS) */\n speechModel?: GoogleModelConfig;\n /** Configuration for speech recognition (STT) */\n listeningModel?: GoogleModelConfig;\n /** Default voice ID to use for speech synthesis */\n speaker?: string;\n /**\n * Enable Vertex AI mode for enterprise deployments.\n * When true, uses Google Cloud project-based authentication instead of API keys.\n * Requires `project` to be set or GOOGLE_CLOUD_PROJECT environment variable.\n */\n vertexAI?: boolean;\n /**\n * Google Cloud project ID (required when vertexAI is true).\n * Falls back to GOOGLE_CLOUD_PROJECT environment variable.\n */\n project?: string;\n /**\n * Google Cloud region for Vertex AI endpoints.\n * Falls back to GOOGLE_CLOUD_LOCATION environment variable.\n * @default 'us-central1'\n */\n location?: string;\n}\n\ntype AuthConfig = Pick<GoogleModelConfig, 'apiKey' | 'keyFilename' | 'credentials'> & {\n projectId?: string;\n};\n\ntype GoogleClientOptions = AuthConfig;\n\nconst resolveAuthConfig = (\n modelConfig: GoogleModelConfig | undefined,\n fallback: AuthConfig,\n vertexConfig?: { vertexAI?: boolean; project?: string },\n): AuthConfig => {\n const resolved: AuthConfig = {};\n\n // For Vertex AI, prioritize project-based auth over API keys\n if (vertexConfig?.vertexAI) {\n const projectId = vertexConfig.project || process.env.GOOGLE_CLOUD_PROJECT;\n if (projectId) {\n resolved.projectId = projectId;\n }\n }\n\n const apiKey = modelConfig?.apiKey ?? fallback.apiKey;\n // Only use API key if not in Vertex AI mode\n if (apiKey && !vertexConfig?.vertexAI) {\n resolved.apiKey = apiKey;\n }\n\n const keyFilename = modelConfig?.keyFilename ?? fallback.keyFilename;\n if (keyFilename) {\n resolved.keyFilename = keyFilename;\n }\n\n const credentials = modelConfig?.credentials ?? fallback.credentials;\n if (credentials) {\n resolved.credentials = credentials;\n }\n\n return resolved;\n};\n\nconst buildAuthOptions = (\n config: AuthConfig,\n vertexConfig?: { vertexAI?: boolean; location?: string },\n): GoogleClientOptions => {\n const options: GoogleClientOptions = {};\n\n if (config.credentials) {\n options.credentials = config.credentials;\n }\n\n if (config.keyFilename) {\n options.keyFilename = config.keyFilename;\n }\n\n // Only use API key if not using Vertex AI\n if (config.apiKey && !vertexConfig?.vertexAI) {\n options.apiKey = config.apiKey;\n }\n\n // For Vertex AI, set the project ID\n if (config.projectId) {\n options.projectId = config.projectId;\n }\n\n return options;\n};\n\nconst DEFAULT_VOICE = 'en-US-Casual-K';\n\n/**\n * GoogleVoice class provides Text-to-Speech and Speech-to-Text capabilities using Google Cloud services.\n * Supports both standard Google Cloud API authentication and Vertex AI mode for enterprise deployments.\n *\n * @class GoogleVoice\n * @extends MastraVoice\n *\n * @example Standard usage with API key\n * ```typescript\n * const voice = new GoogleVoice({\n * speechModel: { apiKey: 'your-api-key' },\n * speaker: 'en-US-Studio-O',\n * });\n * ```\n *\n * @example Vertex AI mode (recommended for production)\n * ```typescript\n * const voice = new GoogleVoice({\n * vertexAI: true,\n * project: 'your-gcp-project',\n * location: 'us-central1',\n * speaker: 'en-US-Studio-O',\n * });\n * ```\n *\n * @example Vertex AI with service account\n * ```typescript\n * const voice = new GoogleVoice({\n * vertexAI: true,\n * project: 'your-gcp-project',\n * speechModel: {\n * keyFilename: '/path/to/service-account.json',\n * },\n * });\n * ```\n */\nexport class GoogleVoice extends MastraVoice {\n private ttsClient: TextToSpeechClient;\n private speechClient: SpeechClient;\n private readonly vertexAI: boolean;\n private readonly project?: string;\n private readonly location: string;\n\n /**\n * Creates an instance of GoogleVoice\n * @param {GoogleVoiceConfig} config - Configuration options\n * @param {GoogleModelConfig} [config.speechModel] - Configuration for speech synthesis\n * @param {GoogleModelConfig} [config.listeningModel] - Configuration for speech recognition\n * @param {string} [config.speaker] - Default voice ID to use for speech synthesis\n * @param {boolean} [config.vertexAI] - Enable Vertex AI mode\n * @param {string} [config.project] - Google Cloud project ID (required for Vertex AI)\n * @param {string} [config.location] - Google Cloud region (default: 'us-central1')\n */\n constructor({ listeningModel, speechModel, speaker, vertexAI = false, project, location }: GoogleVoiceConfig = {}) {\n const defaultApiKey = process.env.GOOGLE_API_KEY;\n const defaultKeyFilename = process.env.GOOGLE_APPLICATION_CREDENTIALS;\n const defaultSpeaker = DEFAULT_VOICE;\n\n // Resolve Vertex AI configuration\n const resolvedProject = project || process.env.GOOGLE_CLOUD_PROJECT;\n const resolvedLocation = location || process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';\n\n // Validate Vertex AI configuration\n if (vertexAI && !resolvedProject) {\n throw new Error(\n 'Google Cloud project ID is required when using Vertex AI. ' +\n 'Set GOOGLE_CLOUD_PROJECT environment variable or pass project to constructor.',\n );\n }\n\n const vertexConfig = { vertexAI, project: resolvedProject };\n\n const sharedFallback: AuthConfig = {\n apiKey: defaultApiKey ?? speechModel?.apiKey ?? listeningModel?.apiKey,\n keyFilename: defaultKeyFilename ?? speechModel?.keyFilename ?? listeningModel?.keyFilename,\n credentials: speechModel?.credentials ?? listeningModel?.credentials,\n projectId: resolvedProject,\n };\n\n const speechAuthConfig = resolveAuthConfig(speechModel, sharedFallback, vertexConfig);\n const listeningAuthConfig = resolveAuthConfig(listeningModel, sharedFallback, vertexConfig);\n\n super({\n speechModel: {\n name: '',\n apiKey: speechAuthConfig.apiKey ?? defaultApiKey,\n },\n listeningModel: {\n name: '',\n apiKey: listeningAuthConfig.apiKey ?? defaultApiKey,\n },\n speaker: speaker ?? defaultSpeaker,\n });\n\n this.vertexAI = vertexAI;\n this.project = resolvedProject;\n this.location = resolvedLocation;\n\n const ttsOptions = buildAuthOptions(speechAuthConfig, { vertexAI, location: resolvedLocation });\n const speechOptions = buildAuthOptions(listeningAuthConfig, { vertexAI, location: resolvedLocation });\n\n this.ttsClient = new TextToSpeechClient(ttsOptions);\n this.speechClient = new SpeechClient(speechOptions);\n }\n\n /**\n * Check if Vertex AI mode is enabled\n * @returns {boolean} True if using Vertex AI\n */\n isUsingVertexAI(): boolean {\n return this.vertexAI;\n }\n\n /**\n * Get the configured Google Cloud project ID\n * @returns {string | undefined} The project ID or undefined if not set\n */\n getProject(): string | undefined {\n return this.project;\n }\n\n /**\n * Get the configured Google Cloud location/region\n * @returns {string} The location (default: 'us-central1')\n */\n getLocation(): string {\n return this.location;\n }\n\n /**\n * Gets a list of available voices\n * @returns {Promise<Array<{voiceId: string, languageCodes: string[]}>>} List of available voices and their supported languages. Default language is en-US.\n */\n async getSpeakers({ languageCode = 'en-US' }: { languageCode?: string } = {}) {\n const [response] = await this.ttsClient.listVoices({ languageCode: languageCode });\n return (response?.voices || [])\n .filter(voice => voice.name && voice.languageCodes)\n .map(voice => ({\n voiceId: voice.name!,\n languageCodes: voice.languageCodes!,\n }));\n }\n\n private async streamToString(stream: NodeJS.ReadableStream): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n if (typeof chunk === 'string') {\n chunks.push(Buffer.from(chunk));\n } else {\n chunks.push(chunk);\n }\n }\n return Buffer.concat(chunks).toString('utf-8');\n }\n\n /**\n * Converts text to speech\n * @param {string | NodeJS.ReadableStream} input - Text or stream to convert to speech\n * @param {Object} [options] - Speech synthesis options\n * @param {string} [options.speaker] - Voice ID to use\n * @param {string} [options.languageCode] - Language code for the voice\n * @param {TextToSpeechTypes.cloud.texttospeech.v1.ISynthesizeSpeechRequest['audioConfig']} [options.audioConfig] - Audio configuration options\n * @returns {Promise<NodeJS.ReadableStream>} Stream of synthesized audio. Default encoding is LINEAR16.\n */\n async speak(\n input: string | NodeJS.ReadableStream,\n options?: {\n speaker?: string;\n languageCode?: string;\n audioConfig?: TextToSpeechTypes.cloud.texttospeech.v1.ISynthesizeSpeechRequest['audioConfig'];\n },\n ): Promise<NodeJS.ReadableStream> {\n const text = typeof input === 'string' ? input : await this.streamToString(input);\n\n const request: TextToSpeechTypes.cloud.texttospeech.v1.ISynthesizeSpeechRequest = {\n input: { text },\n voice: {\n name: options?.speaker || this.speaker,\n languageCode: options?.languageCode || options?.speaker?.split('-').slice(0, 2).join('-') || 'en-US',\n },\n audioConfig: options?.audioConfig || { audioEncoding: 'LINEAR16' },\n };\n\n const [response] = await this.ttsClient.synthesizeSpeech(request);\n\n if (!response.audioContent) {\n throw new Error('No audio content returned.');\n }\n\n if (typeof response.audioContent === 'string') {\n throw new Error('Audio content is a string.');\n }\n\n const stream = new PassThrough();\n stream.end(Buffer.from(response.audioContent));\n return stream;\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Converts speech to text\n * @param {NodeJS.ReadableStream} audioStream - Audio stream to transcribe. Default encoding is LINEAR16.\n * @param {Object} [options] - Recognition options\n * @param {SpeechTypes.cloud.speech.v1.IRecognitionConfig} [options.config] - Recognition configuration\n * @returns {Promise<string>} Transcribed text\n */\n async listen(\n audioStream: NodeJS.ReadableStream,\n options?: { stream?: boolean; config?: SpeechTypes.cloud.speech.v1.IRecognitionConfig },\n ): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of audioStream) {\n if (typeof chunk === 'string') {\n chunks.push(Buffer.from(chunk));\n } else {\n chunks.push(chunk);\n }\n }\n const buffer = Buffer.concat(chunks);\n\n let request = {\n config: {\n encoding: 'LINEAR16',\n languageCode: 'en-US',\n ...options?.config,\n },\n audio: {\n content: buffer.toString('base64'),\n },\n };\n const [response] = await this.speechClient.recognize(request as SpeechTypes.cloud.speech.v1.IRecognizeRequest);\n\n if (!response.results || response.results.length === 0) {\n throw new Error('No transcription results returned');\n }\n\n const transcription = response.results\n .map((result: any) => {\n if (!result.alternatives || result.alternatives.length === 0) {\n return '';\n }\n return result.alternatives[0].transcript || '';\n })\n .filter((text: string) => text.length > 0)\n .join(' ');\n\n if (!transcription) {\n throw new Error('No valid transcription found in results');\n }\n\n return transcription;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../packages/_internal-core/src/logger/index.ts","../../../packages/_internal-core/src/base/MastraBase.ts","../../../packages/_internals/voice/src/voice/voice.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;AAEO,IAAM,gBAAA,GAAmB;EAO9B,GAAA,EAAK,KAcP,CAAA;AAIO,IAAM,QAAA,GAAW;EACtB,KAAA,EAAO,OAAA;EACP,IAAA,EAAM,MAAA;EACN,IAAA,EAAM,MAAA;EACN,KAAA,EAAO,OAET,CAAA;AAsGO,IAAe,eAAf,MAAqD;AAChD,EAAA,IAAA;AACA,EAAA,KAAA;AACA,EAAA,UAAA;EAEV,WAAA,CACE,OAAA,GAII,EAAA,EACJ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IAAI,CAAC,MAAA,CAAO,YAAA,IAAgB,MAAA,CAAO,YAAA,CAAa,WAAW,CAAA,EAAG;AAC5D,QAAA,OAAO,EAAA;AAAA,MACT;AACA,MAAA,OAAO,MAAA,CAAO,YAAA,CAAa,CAAC,CAAA,CAAE,UAAA,IAAc,EAAA;AAAA,IAC9C,CAAC,CAAA,CACA,MAAA,CAAO,CAAC,IAAA,KAAiB,KAAK,MAAA,GAAS,CAAC,CAAA,CACxC,IAAA,CAAK,GAAG,CAAA;AAEX,IAAA,IAAI,CAAC,aAAA,EAAe;AAClB,MAAA,MAAM,IAAI,MAAM,yCAAyC,CAAA;AAAA,IAC3D;AAEA,IAAA,OAAO,aAAA;AAAA,EACT;AACF","file":"index.js","sourcesContent":["import { Transform } from 'node:stream';\n\nexport const RegisteredLogger = {\n AGENT: 'AGENT',\n OBSERVABILITY: 'OBSERVABILITY',\n AUTH: 'AUTH',\n BROWSER: 'BROWSER',\n NETWORK: 'NETWORK',\n WORKFLOW: 'WORKFLOW',\n LLM: 'LLM',\n TTS: 'TTS',\n VOICE: 'VOICE',\n VECTOR: 'VECTOR',\n BUNDLER: 'BUNDLER',\n DEPLOYER: 'DEPLOYER',\n MEMORY: 'MEMORY',\n STORAGE: 'STORAGE',\n EMBEDDINGS: 'EMBEDDINGS',\n MCP_SERVER: 'MCP_SERVER',\n SERVER_CACHE: 'SERVER_CACHE',\n SERVER: 'SERVER',\n WORKSPACE: 'WORKSPACE',\n CHANNEL: 'CHANNEL',\n} as const;\n\nexport type RegisteredLogger = (typeof RegisteredLogger)[keyof typeof RegisteredLogger];\n\nexport const LogLevel = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n NONE: 'silent',\n} as const;\n\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];\n\nexport interface BaseLogMessage {\n runId?: string;\n msg: string;\n level: LogLevel;\n time: Date;\n pid: number;\n hostname: string;\n name: string;\n}\n\nexport abstract class LoggerTransport extends Transform {\n constructor(opts: any = {}) {\n super({ ...opts, objectMode: true });\n }\n\n async listLogsByRunId(_args: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return { logs: [], total: 0, page: _args?.page ?? 1, perPage: _args?.perPage ?? 100, hasMore: false };\n }\n\n async listLogs(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return { logs: [], total: 0, page: _args?.page ?? 1, perPage: _args?.perPage ?? 100, hasMore: false };\n }\n}\n\nexport const createCustomTransport = (\n stream: Transform,\n listLogs?: LoggerTransport['listLogs'],\n listLogsByRunId?: LoggerTransport['listLogsByRunId'],\n) => {\n let transport = stream as LoggerTransport;\n if (listLogs) {\n transport.listLogs = listLogs;\n }\n if (listLogsByRunId) {\n transport.listLogsByRunId = listLogsByRunId;\n }\n return transport as LoggerTransport;\n};\n\nexport interface IMastraLogger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n trackException(error: Error, metadata?: Record<string, unknown>): void;\n\n getTransports(): Map<string, LoggerTransport>;\n listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }>;\n}\n\nexport abstract class MastraLogger implements IMastraLogger {\n protected name: string;\n protected level: LogLevel;\n protected transports: Map<string, LoggerTransport>;\n\n constructor(\n options: {\n name?: string;\n level?: LogLevel;\n transports?: Record<string, LoggerTransport>;\n } = {},\n ) {\n this.name = options.name || 'Mastra';\n this.level = options.level || LogLevel.ERROR;\n this.transports = new Map(Object.entries(options.transports || {}));\n }\n\n abstract debug(message: string, ...args: any[]): void;\n abstract info(message: string, ...args: any[]): void;\n abstract warn(message: string, ...args: any[]): void;\n abstract error(message: string, ...args: any[]): void;\n\n getTransports() {\n return this.transports;\n }\n\n trackException(_error: Error, _metadata?: Record<string, unknown>) {}\n\n async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId || !this.transports.has(transportId)) {\n return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports.get(transportId)!.listLogs?.(params) ?? {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n }\n );\n }\n\n async listLogsByRunId({\n transportId,\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId || !this.transports.has(transportId) || !runId) {\n return { logs: [], total: 0, page: page ?? 1, perPage: perPage ?? 100, hasMore: false };\n }\n\n return (\n this.transports\n .get(transportId)!\n .listLogsByRunId?.({ runId, fromDate, toDate, logLevel, filters, page, perPage }) ?? {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n }\n );\n }\n}\n\nexport type LogFilterContext = {\n component?: RegisteredLogger;\n level: LogLevel;\n message: string;\n args: unknown[];\n};\n\nexport type LogFilter = (ctx: LogFilterContext) => boolean;\n\nexport interface ConsoleLoggerOptions {\n name?: string;\n level?: LogLevel;\n component?: RegisteredLogger;\n filter?: LogFilter;\n}\n\nexport class ConsoleLogger extends MastraLogger {\n protected component?: RegisteredLogger;\n protected filter?: LogFilter;\n\n constructor(options: ConsoleLoggerOptions = {}) {\n super(options);\n this.component = options.component;\n this.filter = options.filter;\n }\n\n child(componentOrBindings: RegisteredLogger | Record<string, unknown>): ConsoleLogger {\n const component =\n typeof componentOrBindings === 'string'\n ? componentOrBindings\n : ((componentOrBindings?.component as RegisteredLogger) ?? this.component);\n return new ConsoleLogger({\n name: this.name,\n level: this.level,\n component,\n filter: this.filter,\n });\n }\n\n private shouldLog(level: LogLevel, message: string, args: unknown[]): boolean {\n if (!this.filter) return true;\n try {\n return this.filter({ component: this.component, level, message, args });\n } catch (e) {\n console.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n return true;\n }\n }\n\n private prefix(): string {\n return this.component ? `[${this.component}] ` : '';\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) {\n console.info(`${this.prefix()}${message}`, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (\n (this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) &&\n this.shouldLog(LogLevel.INFO, message, args)\n ) {\n console.info(`${this.prefix()}${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (\n (this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) &&\n this.shouldLog(LogLevel.WARN, message, args)\n ) {\n console.warn(`${this.prefix()}${message}`, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (\n (this.level === LogLevel.ERROR ||\n this.level === LogLevel.WARN ||\n this.level === LogLevel.INFO ||\n this.level === LogLevel.DEBUG) &&\n this.shouldLog(LogLevel.ERROR, message, args)\n ) {\n console.error(`${this.prefix()}${message}`, ...args);\n }\n }\n\n async listLogs(\n _transportId: string,\n _params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n return { logs: [], total: 0, page: _params?.page ?? 1, perPage: _params?.perPage ?? 100, hasMore: false };\n }\n\n async listLogsByRunId(_args: {\n transportId: string;\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n return { logs: [], total: 0, page: _args.page ?? 1, perPage: _args.perPage ?? 100, hasMore: false };\n }\n}\n","import type { IMastraLogger } from '../logger';\nimport { ConsoleLogger, RegisteredLogger } from '../logger';\n\nexport class MastraBase {\n component: RegisteredLogger = RegisteredLogger.LLM;\n protected logger: IMastraLogger;\n name?: string;\n #rawConfig?: Record<string, unknown>;\n\n constructor({\n component,\n name,\n rawConfig,\n }: {\n component?: RegisteredLogger;\n name?: string;\n rawConfig?: Record<string, unknown>;\n }) {\n this.component = component || RegisteredLogger.LLM;\n this.name = name;\n this.#rawConfig = rawConfig;\n this.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n }\n\n /**\n * Returns the raw storage configuration this primitive was created from,\n * or undefined if it was created from code.\n */\n toRawConfig(): Record<string, unknown> | undefined {\n return this.#rawConfig;\n }\n\n /**\n * Sets the raw storage configuration for this primitive.\n * @internal\n */\n __setRawConfig(rawConfig: Record<string, unknown>): void {\n this.#rawConfig = rawConfig;\n }\n\n /**\n * Set the logger for the agent\n * @param logger\n */\n __setLogger(logger: IMastraLogger) {\n this.logger =\n 'child' in logger && typeof (logger as any).child === 'function'\n ? (logger as any).child({ component: this.component })\n : logger;\n }\n}\n","import { MastraBase } from '@internal/core/base';\nimport type { ToolsInput } from '@internal/core/types';\n\nexport type VoiceEventType = 'speaking' | 'writing' | 'error' | string;\n\nexport interface VoiceEventMap {\n speaker: NodeJS.ReadableStream;\n speaking: { audio?: string };\n writing: { text: string; role: 'assistant' | 'user' };\n error: { message: string; code?: string; details?: unknown };\n [key: string]: unknown;\n}\n\ninterface BuiltInModelConfig {\n name: string;\n apiKey?: string;\n}\n\nexport interface VoiceConfig<T = unknown> {\n listeningModel?: BuiltInModelConfig;\n speechModel?: BuiltInModelConfig;\n speaker?: string;\n name?: string;\n realtimeConfig?: {\n model?: string;\n apiKey?: string;\n options?: T;\n };\n}\n\nexport interface VoiceSpanConfig {\n component: 'VOICE';\n name?: string;\n speaker?: string;\n listeningModel?: { name: string };\n speechModel?: { name: string };\n realtimeModel?: string;\n}\n\nexport interface IMastraVoice<\n TSpeakOptions = unknown,\n TListenOptions = unknown,\n TTools extends ToolsInput = ToolsInput,\n TEventArgs extends VoiceEventMap = VoiceEventMap,\n TSpeakerMetadata = unknown,\n> {\n serializeForSpan(): VoiceSpanConfig;\n speak(\n input: string | NodeJS.ReadableStream,\n options?: {\n speaker?: string;\n } & TSpeakOptions,\n ): Promise<NodeJS.ReadableStream | void>;\n listen(\n audioStream: NodeJS.ReadableStream | unknown,\n options?: TListenOptions,\n ): Promise<string | NodeJS.ReadableStream | void>;\n updateConfig(options: Record<string, unknown>): void;\n connect(options?: Record<string, unknown>): Promise<void>;\n send(audioData: NodeJS.ReadableStream | Int16Array): Promise<void>;\n answer(options?: Record<string, unknown>): Promise<void>;\n addInstructions(instructions?: string): void;\n addTools(tools: TTools): void;\n close(): void;\n on<E extends VoiceEventType>(\n event: E,\n callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void;\n off<E extends VoiceEventType>(\n event: E,\n callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void;\n getSpeakers(): Promise<\n Array<\n {\n voiceId: string;\n } & TSpeakerMetadata\n >\n >;\n getListener(): Promise<{ enabled: boolean }>;\n}\n\nexport abstract class MastraVoice<\n TOptions = unknown,\n TSpeakOptions = unknown,\n TListenOptions = unknown,\n TTools extends ToolsInput = ToolsInput,\n TEventArgs extends VoiceEventMap = VoiceEventMap,\n TSpeakerMetadata = unknown,\n>\n extends MastraBase\n implements IMastraVoice<TSpeakOptions, TListenOptions, TTools, TEventArgs, TSpeakerMetadata>\n{\n protected listeningModel?: BuiltInModelConfig;\n protected speechModel?: BuiltInModelConfig;\n protected speaker?: string;\n protected realtimeConfig?: {\n model?: string;\n apiKey?: string;\n options?: TOptions;\n };\n\n constructor({ listeningModel, speechModel, speaker, realtimeConfig, name }: VoiceConfig<TOptions> = {}) {\n super({\n component: 'VOICE',\n name,\n });\n this.listeningModel = listeningModel;\n this.speechModel = speechModel;\n this.speaker = speaker;\n this.realtimeConfig = realtimeConfig;\n }\n\n /**\n * Custom serialization for tracing/observability spans.\n * Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n * and any provider-specific state held by subclasses. Subclasses that\n * need to expose additional non-sensitive fields can override.\n */\n serializeForSpan(): VoiceSpanConfig {\n return {\n component: 'VOICE',\n name: this.name,\n speaker: this.speaker,\n listeningModel: this.listeningModel ? { name: this.listeningModel.name } : undefined,\n speechModel: this.speechModel ? { name: this.speechModel.name } : undefined,\n realtimeModel: this.realtimeConfig?.model,\n };\n }\n\n /**\n * Convert text to speech\n * @param input Text or text stream to convert to speech\n * @param options Speech options including speaker and provider-specific options\n * @returns Audio stream\n */\n /**\n * Convert text to speech\n * @param input Text or text stream to convert to speech\n * @param options Speech options including speaker and provider-specific options\n * @returns Audio stream or void if in chat mode\n */\n abstract speak(\n input: string | NodeJS.ReadableStream,\n options?: {\n speaker?: string;\n } & TSpeakOptions,\n ): Promise<NodeJS.ReadableStream | void>;\n\n /**\n * Convert speech to text\n * @param audioStream Audio stream to transcribe\n * @param options Provider-specific transcription options\n * @returns Text or text stream\n */\n /**\n * Convert speech to text\n * @param audioStream Audio stream to transcribe\n * @param options Provider-specific transcription options\n * @returns Text, text stream, or void if in chat mode\n */\n abstract listen(\n audioStream: NodeJS.ReadableStream | unknown, // Allow other audio input types for OpenAI realtime API\n options?: TListenOptions,\n ): Promise<string | NodeJS.ReadableStream | void>;\n\n updateConfig(_options: Record<string, unknown>): void {\n this.logger.debug('updateConfig not implemented by this voice provider');\n }\n\n /**\n * Initializes a WebSocket or WebRTC connection for real-time communication\n * @returns Promise that resolves when the connection is established\n */\n async connect(_options?: Record<string, unknown>): Promise<void> {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('connect not implemented by this voice provider');\n }\n\n /**\n * Relay audio data to the voice provider for real-time processing\n * @param audioData Audio data to relay\n */\n async send(_audioData: NodeJS.ReadableStream | Int16Array): Promise<void> {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('relay not implemented by this voice provider');\n }\n\n /**\n * Trigger voice providers to respond\n */\n async answer(_options?: Record<string, unknown>): Promise<void> {\n this.logger.debug('answer not implemented by this voice provider');\n }\n\n /**\n * Equip the voice provider with instructions\n * @param instructions Instructions to add\n */\n addInstructions(_instructions?: string): void {\n // Default implementation - voice providers can override if they support this feature\n }\n\n /**\n * Equip the voice provider with tools\n * @param tools Array of tools to add\n */\n addTools(_tools: TTools): void {\n // Default implementation - voice providers can override if they support this feature\n }\n\n /**\n * Disconnect from the WebSocket or WebRTC connection\n */\n close(): void {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('close not implemented by this voice provider');\n }\n\n /**\n * Register an event listener\n * @param event Event name (e.g., 'speaking', 'writing', 'error')\n * @param callback Callback function that receives event data\n */\n on<E extends VoiceEventType>(\n _event: E,\n _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('on not implemented by this voice provider');\n }\n\n /**\n * Remove an event listener\n * @param event Event name (e.g., 'speaking', 'writing', 'error')\n * @param callback Callback function to remove\n */\n off<E extends VoiceEventType>(\n _event: E,\n _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void,\n ): void {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('off not implemented by this voice provider');\n }\n\n /**\n * Get available speakers/voices\n * @returns Array of available voice IDs and their metadata\n */\n getSpeakers(): Promise<\n Array<\n {\n voiceId: string;\n } & TSpeakerMetadata\n >\n > {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('getSpeakers not implemented by this voice provider');\n return Promise.resolve([]);\n }\n\n /**\n * Get available speakers/voices\n * @returns Array of available voice IDs and their metadata\n */\n getListener(): Promise<{ enabled: boolean }> {\n // Default implementation - voice providers can override if they support this feature\n this.logger.debug('getListener not implemented by this voice provider');\n return Promise.resolve({ enabled: false });\n }\n}\n","import { PassThrough } from 'node:stream';\n\nimport { SpeechClient, v2 } from '@google-cloud/speech';\nimport type { google as SpeechTypes } from '@google-cloud/speech/build/protos/protos';\nimport { TextToSpeechClient } from '@google-cloud/text-to-speech';\nimport type { google as TextToSpeechTypes } from '@google-cloud/text-to-speech/build/protos/protos';\nimport { MastraVoice } from '@internal/voice';\n\n/**\n * Configuration for Google Cloud Voice models\n * @interface GoogleModelConfig\n * @property {string} [apiKey] - Optional Google Cloud API key. If not provided, will use GOOGLE_API_KEY environment variable\n * @property {string} [keyFilename] - Optional path to a service account key file. If not provided, will use GOOGLE_APPLICATION_CREDENTIALS environment variable\n * @property {{ client_email?: string; private_key?: string }} [credentials] - Optional in-memory service account credentials\n */\nexport interface GoogleModelConfig {\n apiKey?: string;\n keyFilename?: string;\n credentials?: {\n client_email?: string;\n private_key?: string;\n [key: string]: unknown;\n };\n}\n\n/**\n * Configuration options for GoogleVoice\n * @interface GoogleVoiceConfig\n */\nexport interface GoogleVoiceConfig {\n /** Configuration for speech synthesis (TTS) */\n speechModel?: GoogleModelConfig;\n /** Configuration for speech recognition (STT) */\n listeningModel?: GoogleModelConfig;\n /** Default voice ID to use for speech synthesis */\n speaker?: string;\n /**\n * Enable Vertex AI mode for enterprise deployments.\n * When true, uses Google Cloud project-based authentication instead of API keys.\n * Requires `project` to be set or GOOGLE_CLOUD_PROJECT environment variable.\n */\n vertexAI?: boolean;\n /**\n * Google Cloud project ID (required when vertexAI is true).\n * Falls back to GOOGLE_CLOUD_PROJECT environment variable.\n */\n project?: string;\n /**\n * Google Cloud region for Vertex AI endpoints.\n * Falls back to GOOGLE_CLOUD_LOCATION environment variable.\n * @default 'us-central1'\n */\n location?: string;\n}\n\ntype AuthConfig = Pick<GoogleModelConfig, 'apiKey' | 'keyFilename' | 'credentials'> & {\n projectId?: string;\n};\n\ntype GoogleClientOptions = AuthConfig;\n\nconst resolveAuthConfig = (\n modelConfig: GoogleModelConfig | undefined,\n fallback: AuthConfig,\n vertexConfig?: { vertexAI?: boolean; project?: string },\n): AuthConfig => {\n const resolved: AuthConfig = {};\n\n // For Vertex AI, prioritize project-based auth over API keys\n if (vertexConfig?.vertexAI) {\n const projectId = vertexConfig.project || process.env.GOOGLE_CLOUD_PROJECT;\n if (projectId) {\n resolved.projectId = projectId;\n }\n }\n\n const apiKey = modelConfig?.apiKey ?? fallback.apiKey;\n // Only use API key if not in Vertex AI mode\n if (apiKey && !vertexConfig?.vertexAI) {\n resolved.apiKey = apiKey;\n }\n\n const keyFilename = modelConfig?.keyFilename ?? fallback.keyFilename;\n if (keyFilename) {\n resolved.keyFilename = keyFilename;\n }\n\n const credentials = modelConfig?.credentials ?? fallback.credentials;\n if (credentials) {\n resolved.credentials = credentials;\n }\n\n return resolved;\n};\n\nconst buildAuthOptions = (\n config: AuthConfig,\n vertexConfig?: { vertexAI?: boolean; location?: string },\n): GoogleClientOptions => {\n const options: GoogleClientOptions = {};\n\n if (config.credentials) {\n options.credentials = config.credentials;\n }\n\n if (config.keyFilename) {\n options.keyFilename = config.keyFilename;\n }\n\n // Only use API key if not using Vertex AI\n if (config.apiKey && !vertexConfig?.vertexAI) {\n options.apiKey = config.apiKey;\n }\n\n // For Vertex AI, set the project ID\n if (config.projectId) {\n options.projectId = config.projectId;\n }\n\n return options;\n};\n\ntype V2RecognitionConfig = SpeechTypes.cloud.speech.v2.IRecognitionConfig;\n\nexport interface GoogleListenOptionsV1 {\n stream?: boolean;\n config?: SpeechTypes.cloud.speech.v1.IRecognitionConfig;\n}\n\nexport interface GoogleListenOptionsV2 {\n stream?: boolean;\n v2: true;\n config?: V2RecognitionConfig;\n recognizer?: string;\n}\n\nexport type GoogleListenOptions = GoogleListenOptionsV1 | GoogleListenOptionsV2;\n\ntype ISynthesizeSpeechRequest = TextToSpeechTypes.cloud.texttospeech.v1.ISynthesizeSpeechRequest;\n\nexport interface GoogleSpeakOptions {\n speaker?: string;\n languageCode?: string;\n input?: ISynthesizeSpeechRequest['input'];\n voice?: ISynthesizeSpeechRequest['voice'];\n audioConfig?: ISynthesizeSpeechRequest['audioConfig'];\n}\n\nconst DEFAULT_VOICE = 'en-US-Casual-K';\n\n/**\n * GoogleVoice class provides Text-to-Speech and Speech-to-Text capabilities using Google Cloud services.\n * Supports both standard Google Cloud API authentication and Vertex AI mode for enterprise deployments.\n *\n * @class GoogleVoice\n * @extends MastraVoice\n *\n * @example Standard usage with API key\n * ```typescript\n * const voice = new GoogleVoice({\n * speechModel: { apiKey: 'your-api-key' },\n * speaker: 'en-US-Studio-O',\n * });\n * ```\n *\n * @example Vertex AI mode (recommended for production)\n * ```typescript\n * const voice = new GoogleVoice({\n * vertexAI: true,\n * project: 'your-gcp-project',\n * location: 'us-central1',\n * speaker: 'en-US-Studio-O',\n * });\n * ```\n *\n * @example Vertex AI with service account\n * ```typescript\n * const voice = new GoogleVoice({\n * vertexAI: true,\n * project: 'your-gcp-project',\n * speechModel: {\n * keyFilename: '/path/to/service-account.json',\n * },\n * });\n * ```\n */\nexport class GoogleVoice extends MastraVoice {\n private ttsClient: TextToSpeechClient;\n private speechClient: SpeechClient;\n private speechClientV2?: v2.SpeechClient;\n private readonly speechOptionsV2: GoogleClientOptions;\n private readonly vertexAI: boolean;\n private readonly project?: string;\n private readonly location: string;\n\n /**\n * Creates an instance of GoogleVoice\n * @param {GoogleVoiceConfig} config - Configuration options\n * @param {GoogleModelConfig} [config.speechModel] - Configuration for speech synthesis\n * @param {GoogleModelConfig} [config.listeningModel] - Configuration for speech recognition\n * @param {string} [config.speaker] - Default voice ID to use for speech synthesis\n * @param {boolean} [config.vertexAI] - Enable Vertex AI mode\n * @param {string} [config.project] - Google Cloud project ID (required for Vertex AI)\n * @param {string} [config.location] - Google Cloud region (default: 'us-central1')\n */\n constructor({ listeningModel, speechModel, speaker, vertexAI = false, project, location }: GoogleVoiceConfig = {}) {\n const defaultApiKey = process.env.GOOGLE_API_KEY;\n const defaultKeyFilename = process.env.GOOGLE_APPLICATION_CREDENTIALS;\n const defaultSpeaker = DEFAULT_VOICE;\n\n // Resolve Vertex AI configuration\n const resolvedProject = project || process.env.GOOGLE_CLOUD_PROJECT;\n const resolvedLocation = location || process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';\n\n // Validate Vertex AI configuration\n if (vertexAI && !resolvedProject) {\n throw new Error(\n 'Google Cloud project ID is required when using Vertex AI. ' +\n 'Set GOOGLE_CLOUD_PROJECT environment variable or pass project to constructor.',\n );\n }\n\n const vertexConfig = { vertexAI, project: resolvedProject };\n\n const sharedFallback: AuthConfig = {\n apiKey: defaultApiKey ?? speechModel?.apiKey ?? listeningModel?.apiKey,\n keyFilename: defaultKeyFilename ?? speechModel?.keyFilename ?? listeningModel?.keyFilename,\n credentials: speechModel?.credentials ?? listeningModel?.credentials,\n projectId: resolvedProject,\n };\n\n const speechAuthConfig = resolveAuthConfig(speechModel, sharedFallback, vertexConfig);\n const listeningAuthConfig = resolveAuthConfig(listeningModel, sharedFallback, vertexConfig);\n\n super({\n speechModel: {\n name: '',\n apiKey: speechAuthConfig.apiKey ?? defaultApiKey,\n },\n listeningModel: {\n name: '',\n apiKey: listeningAuthConfig.apiKey ?? defaultApiKey,\n },\n speaker: speaker ?? defaultSpeaker,\n });\n\n this.vertexAI = vertexAI;\n this.project = resolvedProject;\n this.location = resolvedLocation;\n\n const ttsOptions = buildAuthOptions(speechAuthConfig, { vertexAI, location: resolvedLocation });\n const speechOptions = buildAuthOptions(listeningAuthConfig, { vertexAI, location: resolvedLocation });\n\n this.ttsClient = new TextToSpeechClient(ttsOptions);\n this.speechClient = new SpeechClient(speechOptions);\n this.speechOptionsV2 = speechOptions;\n }\n\n private getV2SpeechClient(): v2.SpeechClient {\n if (!this.speechClientV2) {\n this.speechClientV2 = new v2.SpeechClient(this.speechOptionsV2);\n }\n return this.speechClientV2;\n }\n\n /**\n * Check if Vertex AI mode is enabled\n * @returns {boolean} True if using Vertex AI\n */\n isUsingVertexAI(): boolean {\n return this.vertexAI;\n }\n\n /**\n * Get the configured Google Cloud project ID\n * @returns {string | undefined} The project ID or undefined if not set\n */\n getProject(): string | undefined {\n return this.project;\n }\n\n /**\n * Get the configured Google Cloud location/region\n * @returns {string} The location (default: 'us-central1')\n */\n getLocation(): string {\n return this.location;\n }\n\n /**\n * Gets a list of available voices\n * @returns {Promise<Array<{voiceId: string, languageCodes: string[]}>>} List of available voices and their supported languages. Default language is en-US.\n */\n async getSpeakers({ languageCode = 'en-US' }: { languageCode?: string } = {}) {\n const [response] = await this.ttsClient.listVoices({ languageCode: languageCode });\n return (response?.voices || [])\n .filter(voice => voice.name && voice.languageCodes)\n .map(voice => ({\n voiceId: voice.name!,\n languageCodes: voice.languageCodes!,\n }));\n }\n\n private async streamToString(stream: NodeJS.ReadableStream): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n if (typeof chunk === 'string') {\n chunks.push(Buffer.from(chunk));\n } else {\n chunks.push(chunk);\n }\n }\n return Buffer.concat(chunks).toString('utf-8');\n }\n\n /**\n * Converts text to speech.\n *\n * When `input` is a string or stream, builds a text-only request (existing behaviour).\n * Pass `options.input` to send richer proto fields (ssml, markup, prompt,\n * customPronunciations, multiSpeakerMarkup) and `options.voice` for fields\n * like modelName or multiSpeakerVoiceConfig.\n *\n * @param {string | NodeJS.ReadableStream} input - Text or stream to convert to speech\n * @param {GoogleSpeakOptions} [options] - Speech synthesis options\n * @returns {Promise<NodeJS.ReadableStream>} Stream of synthesised audio. Default encoding is LINEAR16.\n */\n async speak(input: string | NodeJS.ReadableStream, options?: GoogleSpeakOptions): Promise<NodeJS.ReadableStream> {\n const defaultVoiceName = options?.speaker || this.speaker;\n const defaultLanguageCode = options?.languageCode || defaultVoiceName?.split('-').slice(0, 2).join('-') || 'en-US';\n\n const requestInput: ISynthesizeSpeechRequest['input'] = options?.input\n ? { ...options.input }\n : { text: typeof input === 'string' ? input : await this.streamToString(input) };\n\n // When the caller provides a rich input object but no explicit text field,\n // populate it from the positional `input` argument for convenience.\n if (\n options?.input &&\n !options.input.text &&\n !options.input.ssml &&\n !options.input.markup &&\n !options.input.multiSpeakerMarkup\n ) {\n requestInput!.text = typeof input === 'string' ? input : await this.streamToString(input);\n }\n\n const request: ISynthesizeSpeechRequest = {\n input: requestInput,\n voice: {\n name: defaultVoiceName,\n languageCode: defaultLanguageCode,\n ...options?.voice,\n },\n audioConfig: options?.audioConfig || { audioEncoding: 'LINEAR16' },\n };\n\n const [response] = await this.ttsClient.synthesizeSpeech(request);\n\n if (!response.audioContent) {\n throw new Error('No audio content returned.');\n }\n\n if (typeof response.audioContent === 'string') {\n throw new Error('Audio content is a string.');\n }\n\n const stream = new PassThrough();\n stream.end(Buffer.from(response.audioContent));\n return stream;\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Converts speech to text using Cloud Speech-to-Text v1 or v2.\n *\n * Pass `{ v2: true }` in options to use the v2 API, which supports additional\n * audio formats like AAC-in-MP4 (iOS Safari) via `autoDecodingConfig` or\n * `explicitDecodingConfig`. The v1 path remains the default.\n *\n * @param {NodeJS.ReadableStream} audioStream - Audio stream to transcribe. Default encoding is LINEAR16.\n * @param {GoogleListenOptions} [options] - Recognition options\n * @returns {Promise<string>} Transcribed text\n */\n async listen(audioStream: NodeJS.ReadableStream, options?: GoogleListenOptions): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of audioStream) {\n if (typeof chunk === 'string') {\n chunks.push(Buffer.from(chunk));\n } else {\n chunks.push(chunk);\n }\n }\n const buffer = Buffer.concat(chunks);\n\n if (options && 'v2' in options && options.v2) {\n return this.recognizeV2(buffer, options);\n }\n\n return this.recognizeV1(buffer, options as GoogleListenOptionsV1 | undefined);\n }\n\n private async recognizeV1(buffer: Buffer, options?: GoogleListenOptionsV1): Promise<string> {\n const request = {\n config: {\n encoding: 'LINEAR16',\n languageCode: 'en-US',\n ...options?.config,\n },\n audio: {\n content: buffer.toString('base64'),\n },\n };\n const [response] = await this.speechClient.recognize(request as SpeechTypes.cloud.speech.v1.IRecognizeRequest);\n return this.extractTranscription(response?.results);\n }\n\n private async recognizeV2(buffer: Buffer, options: GoogleListenOptionsV2): Promise<string> {\n const config: V2RecognitionConfig = { ...options.config };\n // Default to auto-decoding if neither decoding config is specified\n if (!config.autoDecodingConfig && !config.explicitDecodingConfig) {\n config.autoDecodingConfig = {};\n }\n if (!config.languageCodes || config.languageCodes.length === 0) {\n config.languageCodes = ['en-US'];\n }\n if (!config.model) {\n config.model = 'long';\n }\n\n let recognizer = options.recognizer;\n if (!recognizer) {\n const project = this.project || (await this.getV2SpeechClient().getProjectId());\n recognizer = `projects/${project}/locations/global/recognizers/_`;\n }\n\n const request: SpeechTypes.cloud.speech.v2.IRecognizeRequest = {\n recognizer,\n config,\n content: buffer,\n };\n\n const client = this.getV2SpeechClient();\n const [response] = await client.recognize(request);\n return this.extractTranscription(response?.results);\n }\n\n private extractTranscription(\n results:\n | SpeechTypes.cloud.speech.v1.ISpeechRecognitionResult[]\n | SpeechTypes.cloud.speech.v2.ISpeechRecognitionResult[]\n | null\n | undefined,\n ): string {\n if (!results || results.length === 0) {\n throw new Error('No transcription results returned');\n }\n\n const transcription = results\n .map((result: any) => {\n if (!result.alternatives || result.alternatives.length === 0) {\n return '';\n }\n return result.alternatives[0].transcript || '';\n })\n .filter((text: string) => text.length > 0)\n .join(' ');\n\n if (!transcription) {\n throw new Error('No valid transcription found in results');\n }\n\n return transcription;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/voice-google",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0-alpha.0",
|
|
4
4
|
"description": "Mastra Google voice integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -29,16 +29,16 @@
|
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/node": "22.19.21",
|
|
32
|
-
"@vitest/coverage-v8": "4.1.
|
|
33
|
-
"@vitest/ui": "4.1.
|
|
32
|
+
"@vitest/coverage-v8": "4.1.10",
|
|
33
|
+
"@vitest/ui": "4.1.10",
|
|
34
34
|
"eslint": "^10.4.1",
|
|
35
35
|
"tsup": "^8.5.1",
|
|
36
36
|
"tsx": "^4.22.4",
|
|
37
37
|
"typescript": "^6.0.3",
|
|
38
|
-
"vitest": "4.1.
|
|
39
|
-
"@internal/lint": "0.0.
|
|
40
|
-
"@internal/types-builder": "0.0.
|
|
41
|
-
"@internal/voice": "0.0.
|
|
38
|
+
"vitest": "4.1.10",
|
|
39
|
+
"@internal/lint": "0.0.113",
|
|
40
|
+
"@internal/types-builder": "0.0.88",
|
|
41
|
+
"@internal/voice": "0.0.13"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"zod": "^3.25.0 || ^4.0.0"
|
|
@@ -1,381 +0,0 @@
|
|
|
1
|
-
# Voice
|
|
2
|
-
|
|
3
|
-
Mastra agents can be enhanced with voice capabilities, allowing them to speak responses and listen to user input. You can configure an agent to use either a single voice provider or combine multiple providers for different operations.
|
|
4
|
-
|
|
5
|
-
## Basic usage
|
|
6
|
-
|
|
7
|
-
The simplest way to add voice to an agent is to use a single provider for both speaking and listening:
|
|
8
|
-
|
|
9
|
-
```typescript
|
|
10
|
-
import { createReadStream } from 'fs'
|
|
11
|
-
import path from 'path'
|
|
12
|
-
import { Agent } from '@mastra/core/agent'
|
|
13
|
-
import { OpenAIVoice } from '@mastra/voice-openai'
|
|
14
|
-
|
|
15
|
-
// Initialize the voice provider with default settings
|
|
16
|
-
const voice = new OpenAIVoice()
|
|
17
|
-
|
|
18
|
-
// Create an agent with voice capabilities
|
|
19
|
-
export const agent = new Agent({
|
|
20
|
-
id: 'voice-agent',
|
|
21
|
-
name: 'Voice Agent',
|
|
22
|
-
instructions: `You are a helpful assistant with both STT and TTS capabilities.`,
|
|
23
|
-
model: 'openai/gpt-5.5',
|
|
24
|
-
voice,
|
|
25
|
-
})
|
|
26
|
-
|
|
27
|
-
// The agent can now use voice for interaction
|
|
28
|
-
const audioStream = await agent.voice.speak("Hello, I'm your AI assistant!", {
|
|
29
|
-
filetype: 'm4a',
|
|
30
|
-
})
|
|
31
|
-
|
|
32
|
-
playAudio(audioStream!)
|
|
33
|
-
|
|
34
|
-
try {
|
|
35
|
-
const transcription = await agent.voice.listen(audioStream)
|
|
36
|
-
console.log(transcription)
|
|
37
|
-
} catch (error) {
|
|
38
|
-
console.error('Error transcribing audio:', error)
|
|
39
|
-
}
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
## Working with audio streams
|
|
43
|
-
|
|
44
|
-
The `speak()` and `listen()` methods work with Node.js streams. Here's how to save and load audio files:
|
|
45
|
-
|
|
46
|
-
### Saving Speech Output
|
|
47
|
-
|
|
48
|
-
The `speak` method returns a stream that you can pipe to a file or speaker.
|
|
49
|
-
|
|
50
|
-
```typescript
|
|
51
|
-
import { createWriteStream } from 'fs'
|
|
52
|
-
import path from 'path'
|
|
53
|
-
|
|
54
|
-
// Generate speech and save to file
|
|
55
|
-
const audio = await agent.voice.speak('Hello, World!')
|
|
56
|
-
const filePath = path.join(process.cwd(), 'agent.mp3')
|
|
57
|
-
const writer = createWriteStream(filePath)
|
|
58
|
-
|
|
59
|
-
audio.pipe(writer)
|
|
60
|
-
|
|
61
|
-
await new Promise<void>((resolve, reject) => {
|
|
62
|
-
writer.on('finish', () => resolve())
|
|
63
|
-
writer.on('error', reject)
|
|
64
|
-
})
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
### Transcribing Audio Input
|
|
68
|
-
|
|
69
|
-
The `listen` method expects a stream of audio data from a microphone or file.
|
|
70
|
-
|
|
71
|
-
```typescript
|
|
72
|
-
import { createReadStream } from 'fs'
|
|
73
|
-
import path from 'path'
|
|
74
|
-
|
|
75
|
-
// Read audio file and transcribe
|
|
76
|
-
const audioFilePath = path.join(process.cwd(), '/agent.m4a')
|
|
77
|
-
const audioStream = createReadStream(audioFilePath)
|
|
78
|
-
|
|
79
|
-
try {
|
|
80
|
-
console.log('Transcribing audio file...')
|
|
81
|
-
const transcription = await agent.voice.listen(audioStream, {
|
|
82
|
-
filetype: 'm4a',
|
|
83
|
-
})
|
|
84
|
-
console.log('Transcription:', transcription)
|
|
85
|
-
} catch (error) {
|
|
86
|
-
console.error('Error transcribing audio:', error)
|
|
87
|
-
}
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
## Speech-to-speech voice interactions
|
|
91
|
-
|
|
92
|
-
For more dynamic and interactive voice experiences, you can use real-time voice providers that support speech-to-speech capabilities:
|
|
93
|
-
|
|
94
|
-
```typescript
|
|
95
|
-
import { Agent } from '@mastra/core/agent'
|
|
96
|
-
import { getMicrophoneStream } from '@mastra/node-audio'
|
|
97
|
-
import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime'
|
|
98
|
-
import { search, calculate } from '../tools'
|
|
99
|
-
|
|
100
|
-
// Initialize the realtime voice provider
|
|
101
|
-
const voice = new OpenAIRealtimeVoice({
|
|
102
|
-
apiKey: process.env.OPENAI_API_KEY,
|
|
103
|
-
model: 'gpt-5.1-realtime',
|
|
104
|
-
speaker: 'alloy',
|
|
105
|
-
})
|
|
106
|
-
|
|
107
|
-
// Create an agent with speech-to-speech voice capabilities
|
|
108
|
-
export const agent = new Agent({
|
|
109
|
-
id: 'speech-to-speech-agent',
|
|
110
|
-
name: 'Speech-to-Speech Agent',
|
|
111
|
-
instructions: `You are a helpful assistant with speech-to-speech capabilities.`,
|
|
112
|
-
model: 'openai/gpt-5.5',
|
|
113
|
-
tools: {
|
|
114
|
-
// Tools configured on Agent are passed to voice provider
|
|
115
|
-
search,
|
|
116
|
-
calculate,
|
|
117
|
-
},
|
|
118
|
-
voice,
|
|
119
|
-
})
|
|
120
|
-
|
|
121
|
-
// Establish a WebSocket connection
|
|
122
|
-
await agent.voice.connect()
|
|
123
|
-
|
|
124
|
-
// Start a conversation
|
|
125
|
-
agent.voice.speak("Hello, I'm your AI assistant!")
|
|
126
|
-
|
|
127
|
-
// Stream audio from a microphone
|
|
128
|
-
const microphoneStream = getMicrophoneStream()
|
|
129
|
-
agent.voice.send(microphoneStream)
|
|
130
|
-
|
|
131
|
-
// When done with the conversation
|
|
132
|
-
agent.voice.close()
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
### Per-session voice for concurrent sessions
|
|
136
|
-
|
|
137
|
-
A static `voice` instance is shared across every request. For one-shot text-to-speech this is fine, but realtime and speech-to-speech providers store one WebSocket, one set of tools, and one request context per instance. If you deploy a single agent that handles several live sessions at once, a shared instance lets one session overwrite another session's tools, instructions, and request context.
|
|
138
|
-
|
|
139
|
-
To give each session its own voice, provide `voice` as a resolver. Mastra runs the resolver on every `getVoice()` call and returns a fresh, session-owned instance:
|
|
140
|
-
|
|
141
|
-
```typescript
|
|
142
|
-
import { Agent } from '@mastra/core/agent'
|
|
143
|
-
import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime'
|
|
144
|
-
|
|
145
|
-
export const agent = new Agent({
|
|
146
|
-
id: 'support-line',
|
|
147
|
-
name: 'Support Line',
|
|
148
|
-
instructions: ({ requestContext }) => `Help user ${requestContext.get('user')}.`,
|
|
149
|
-
model: 'openai/gpt-5.5',
|
|
150
|
-
voice: ({ requestContext }) => new OpenAIRealtimeVoice({ apiKey: requestContext.get('apiKey') }),
|
|
151
|
-
})
|
|
152
|
-
|
|
153
|
-
// Each concurrent session resolves its own voice instance
|
|
154
|
-
const voice = await agent.getVoice({ requestContext })
|
|
155
|
-
await voice.connect()
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
When you use a resolver:
|
|
159
|
-
|
|
160
|
-
- Each call to `getVoice()` returns a new instance, so concurrent sessions never share state.
|
|
161
|
-
- Mastra doesn't add tools or instructions to a resolver instance. Configure those inside the resolver or on the provider.
|
|
162
|
-
- You own the lifecycle of the returned instance, so call `disconnect()` or `close()` when the session ends.
|
|
163
|
-
|
|
164
|
-
The `agent.voice` getter has no request context, so it throws when `voice` is a resolver. Use `agent.getVoice({ requestContext })` instead.
|
|
165
|
-
|
|
166
|
-
### Event System
|
|
167
|
-
|
|
168
|
-
The realtime voice provider emits several events you can listen for:
|
|
169
|
-
|
|
170
|
-
```typescript
|
|
171
|
-
// Listen for speech audio data sent from voice provider
|
|
172
|
-
agent.voice.on('speaking', ({ audio }) => {
|
|
173
|
-
// audio contains ReadableStream or Int16Array audio data
|
|
174
|
-
})
|
|
175
|
-
|
|
176
|
-
// Listen for transcribed text sent from both voice provider and user
|
|
177
|
-
agent.voice.on('writing', ({ text, role }) => {
|
|
178
|
-
console.log(`${role} said: ${text}`)
|
|
179
|
-
})
|
|
180
|
-
|
|
181
|
-
// Listen for errors
|
|
182
|
-
agent.voice.on('error', error => {
|
|
183
|
-
console.error('Voice error:', error)
|
|
184
|
-
})
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
## Examples
|
|
188
|
-
|
|
189
|
-
### End-to-end voice interaction
|
|
190
|
-
|
|
191
|
-
This example demonstrates a voice interaction between two agents. The hybrid voice agent, which uses multiple providers, speaks a question, which is saved as an audio file. The unified voice agent listens to that file, processes the question, generates a response, and speaks it back. Both audio outputs are saved to the `audio` directory.
|
|
192
|
-
|
|
193
|
-
The following files are created:
|
|
194
|
-
|
|
195
|
-
- **hybrid-question.mp3** – Hybrid agent's spoken question.
|
|
196
|
-
- **unified-response.mp3** – Unified agent's spoken response.
|
|
197
|
-
|
|
198
|
-
```typescript
|
|
199
|
-
import 'dotenv/config'
|
|
200
|
-
|
|
201
|
-
import path from 'path'
|
|
202
|
-
import { createReadStream } from 'fs'
|
|
203
|
-
import { Agent } from '@mastra/core/agent'
|
|
204
|
-
import { CompositeVoice } from '@mastra/core/voice'
|
|
205
|
-
import { OpenAIVoice } from '@mastra/voice-openai'
|
|
206
|
-
import { Mastra } from '@mastra/core'
|
|
207
|
-
|
|
208
|
-
// Saves an audio stream to a file in the audio directory, creating the directory if it doesn't exist.
|
|
209
|
-
export const saveAudioToFile = async (
|
|
210
|
-
audio: NodeJS.ReadableStream,
|
|
211
|
-
filename: string,
|
|
212
|
-
): Promise<void> => {
|
|
213
|
-
const audioDir = path.join(process.cwd(), 'audio')
|
|
214
|
-
const filePath = path.join(audioDir, filename)
|
|
215
|
-
|
|
216
|
-
await fs.promises.mkdir(audioDir, { recursive: true })
|
|
217
|
-
|
|
218
|
-
const writer = createWriteStream(filePath)
|
|
219
|
-
audio.pipe(writer)
|
|
220
|
-
return new Promise((resolve, reject) => {
|
|
221
|
-
writer.on('finish', resolve)
|
|
222
|
-
writer.on('error', reject)
|
|
223
|
-
})
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// Saves an audio stream to a file in the audio directory, creating the directory if it doesn't exist.
|
|
227
|
-
export const convertToText = async (input: string | NodeJS.ReadableStream): Promise<string> => {
|
|
228
|
-
if (typeof input === 'string') {
|
|
229
|
-
return input
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
const chunks: Buffer[] = []
|
|
233
|
-
return new Promise((resolve, reject) => {
|
|
234
|
-
inputData.on('data', chunk => chunks.push(Buffer.from(chunk)))
|
|
235
|
-
inputData.on('error', reject)
|
|
236
|
-
inputData.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')))
|
|
237
|
-
})
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
export const hybridVoiceAgent = new Agent({
|
|
241
|
-
id: 'hybrid-voice-agent',
|
|
242
|
-
name: 'Hybrid Voice Agent',
|
|
243
|
-
model: 'openai/gpt-5.5',
|
|
244
|
-
instructions: 'You can speak and listen using different providers.',
|
|
245
|
-
voice: new CompositeVoice({
|
|
246
|
-
input: new OpenAIVoice(),
|
|
247
|
-
output: new OpenAIVoice(),
|
|
248
|
-
}),
|
|
249
|
-
})
|
|
250
|
-
|
|
251
|
-
export const unifiedVoiceAgent = new Agent({
|
|
252
|
-
id: 'unified-voice-agent',
|
|
253
|
-
name: 'Unified Voice Agent',
|
|
254
|
-
instructions: 'You are an agent with both STT and TTS capabilities.',
|
|
255
|
-
model: 'openai/gpt-5.5',
|
|
256
|
-
voice: new OpenAIVoice(),
|
|
257
|
-
})
|
|
258
|
-
|
|
259
|
-
export const mastra = new Mastra({
|
|
260
|
-
agents: { hybridVoiceAgent, unifiedVoiceAgent },
|
|
261
|
-
})
|
|
262
|
-
|
|
263
|
-
const hybridVoiceAgent = mastra.getAgent('hybridVoiceAgent')
|
|
264
|
-
const unifiedVoiceAgent = mastra.getAgent('unifiedVoiceAgent')
|
|
265
|
-
|
|
266
|
-
const question = 'What is the meaning of life in one sentence?'
|
|
267
|
-
|
|
268
|
-
const hybridSpoken = await hybridVoiceAgent.voice.speak(question)
|
|
269
|
-
|
|
270
|
-
await saveAudioToFile(hybridSpoken!, 'hybrid-question.mp3')
|
|
271
|
-
|
|
272
|
-
const audioStream = createReadStream(path.join(process.cwd(), 'audio', 'hybrid-question.mp3'))
|
|
273
|
-
const unifiedHeard = await unifiedVoiceAgent.voice.listen(audioStream)
|
|
274
|
-
|
|
275
|
-
const inputText = await convertToText(unifiedHeard!)
|
|
276
|
-
|
|
277
|
-
const unifiedResponse = await unifiedVoiceAgent.generate(inputText)
|
|
278
|
-
const unifiedSpoken = await unifiedVoiceAgent.voice.speak(unifiedResponse.text)
|
|
279
|
-
|
|
280
|
-
await saveAudioToFile(unifiedSpoken!, 'unified-response.mp3')
|
|
281
|
-
```
|
|
282
|
-
|
|
283
|
-
### Using Multiple Providers
|
|
284
|
-
|
|
285
|
-
For more flexibility, you can use different providers for speaking and listening using the CompositeVoice class:
|
|
286
|
-
|
|
287
|
-
```typescript
|
|
288
|
-
import { Agent } from '@mastra/core/agent'
|
|
289
|
-
import { CompositeVoice } from '@mastra/core/voice'
|
|
290
|
-
import { OpenAIVoice } from '@mastra/voice-openai'
|
|
291
|
-
import { PlayAIVoice } from '@mastra/voice-playai'
|
|
292
|
-
|
|
293
|
-
export const agent = new Agent({
|
|
294
|
-
id: 'voice-agent',
|
|
295
|
-
name: 'Voice Agent',
|
|
296
|
-
instructions: `You are a helpful assistant with both STT and TTS capabilities.`,
|
|
297
|
-
model: 'openai/gpt-5.5',
|
|
298
|
-
|
|
299
|
-
// Create a composite voice using OpenAI for listening and PlayAI for speaking
|
|
300
|
-
voice: new CompositeVoice({
|
|
301
|
-
input: new OpenAIVoice(),
|
|
302
|
-
output: new PlayAIVoice(),
|
|
303
|
-
}),
|
|
304
|
-
})
|
|
305
|
-
```
|
|
306
|
-
|
|
307
|
-
### Using AI SDK
|
|
308
|
-
|
|
309
|
-
Mastra supports using AI SDK's transcription and speech models directly in `CompositeVoice`, giving you access to a wide range of providers through the AI SDK ecosystem:
|
|
310
|
-
|
|
311
|
-
```typescript
|
|
312
|
-
import { Agent } from '@mastra/core/agent'
|
|
313
|
-
import { CompositeVoice } from '@mastra/core/voice'
|
|
314
|
-
import { openai } from '@ai-sdk/openai'
|
|
315
|
-
import { elevenlabs } from '@ai-sdk/elevenlabs'
|
|
316
|
-
import { groq } from '@ai-sdk/groq'
|
|
317
|
-
|
|
318
|
-
export const agent = new Agent({
|
|
319
|
-
id: 'aisdk-voice-agent',
|
|
320
|
-
name: 'AI SDK Voice Agent',
|
|
321
|
-
instructions: `You are a helpful assistant with voice capabilities.`,
|
|
322
|
-
model: 'openai/gpt-5.5',
|
|
323
|
-
|
|
324
|
-
// Pass AI SDK models directly to CompositeVoice
|
|
325
|
-
voice: new CompositeVoice({
|
|
326
|
-
input: openai.transcription('whisper-1'), // AI SDK transcription model
|
|
327
|
-
output: elevenlabs.speech('eleven_turbo_v2'), // AI SDK speech model
|
|
328
|
-
}),
|
|
329
|
-
})
|
|
330
|
-
|
|
331
|
-
// Use voice capabilities as usual
|
|
332
|
-
const audioStream = await agent.voice.speak('Hello!')
|
|
333
|
-
const transcribedText = await agent.voice.listen(audioStream)
|
|
334
|
-
```
|
|
335
|
-
|
|
336
|
-
#### Mix and Match Providers
|
|
337
|
-
|
|
338
|
-
You can mix AI SDK models with Mastra voice providers:
|
|
339
|
-
|
|
340
|
-
```typescript
|
|
341
|
-
import { CompositeVoice } from '@mastra/core/voice'
|
|
342
|
-
import { PlayAIVoice } from '@mastra/voice-playai'
|
|
343
|
-
import { openai } from '@ai-sdk/openai'
|
|
344
|
-
|
|
345
|
-
// Use AI SDK for transcription and Mastra provider for speech
|
|
346
|
-
const voice = new CompositeVoice({
|
|
347
|
-
input: openai.transcription('whisper-1'), // AI SDK
|
|
348
|
-
output: new PlayAIVoice(), // Mastra provider
|
|
349
|
-
})
|
|
350
|
-
```
|
|
351
|
-
|
|
352
|
-
For the complete list of supported AI SDK providers and their capabilities:
|
|
353
|
-
|
|
354
|
-
- [Transcription](https://ai-sdk.dev/docs/providers/openai/transcription)
|
|
355
|
-
- [Speech](https://ai-sdk.dev/docs/providers/elevenlabs/speech)
|
|
356
|
-
|
|
357
|
-
## Supported voice providers
|
|
358
|
-
|
|
359
|
-
Mastra supports multiple voice providers for text-to-speech (TTS) and speech-to-text (STT) capabilities:
|
|
360
|
-
|
|
361
|
-
| Provider | Package | Features | Reference |
|
|
362
|
-
| --------------- | ------------------------------- | ----------------------------------------- | ------------------------------------------------------------------ |
|
|
363
|
-
| OpenAI | `@mastra/voice-openai` | TTS, STT | [Documentation](https://mastra.ai/reference/voice/openai) |
|
|
364
|
-
| OpenAI Realtime | `@mastra/voice-openai-realtime` | Realtime speech-to-speech | [Documentation](https://mastra.ai/reference/voice/openai-realtime) |
|
|
365
|
-
| AWS Nova Sonic | `@mastra/voice-aws-nova-sonic` | Realtime speech-to-speech via AWS Bedrock | [Documentation](https://mastra.ai/reference/voice/aws-nova-sonic) |
|
|
366
|
-
| ElevenLabs | `@mastra/voice-elevenlabs` | High-quality TTS | [Documentation](https://mastra.ai/reference/voice/elevenlabs) |
|
|
367
|
-
| PlayAI | `@mastra/voice-playai` | TTS | [Documentation](https://mastra.ai/reference/voice/playai) |
|
|
368
|
-
| Google | `@mastra/voice-google` | TTS, STT | [Documentation](https://mastra.ai/reference/voice/google) |
|
|
369
|
-
| Deepgram | `@mastra/voice-deepgram` | STT | [Documentation](https://mastra.ai/reference/voice/deepgram) |
|
|
370
|
-
| Murf | `@mastra/voice-murf` | TTS | [Documentation](https://mastra.ai/reference/voice/murf) |
|
|
371
|
-
| Speechify | `@mastra/voice-speechify` | TTS | [Documentation](https://mastra.ai/reference/voice/speechify) |
|
|
372
|
-
| Sarvam | `@mastra/voice-sarvam` | TTS, STT | [Documentation](https://mastra.ai/reference/voice/sarvam) |
|
|
373
|
-
| Azure | `@mastra/voice-azure` | TTS, STT | [Documentation](https://mastra.ai/reference/voice/mastra-voice) |
|
|
374
|
-
| Cloudflare | `@mastra/voice-cloudflare` | TTS | [Documentation](https://mastra.ai/reference/voice/mastra-voice) |
|
|
375
|
-
|
|
376
|
-
## Next steps
|
|
377
|
-
|
|
378
|
-
- [Voice API Reference](https://mastra.ai/reference/voice/mastra-voice): Detailed API documentation for voice capabilities
|
|
379
|
-
- [Text to Speech Examples](https://github.com/mastra-ai/voice-examples/tree/main/text-to-speech): Interactive story generator and other TTS implementations
|
|
380
|
-
- [Speech to Text Examples](https://github.com/mastra-ai/voice-examples/tree/main/speech-to-text): Voice memo app and other STT implementations
|
|
381
|
-
- [Speech to Speech Examples](https://github.com/mastra-ai/voice-examples/tree/main/speech-to-speech): Real-time voice conversation with call analysis
|