'use strict'; var stream = require('stream'); var v4 = require('zod/v4'); // ../_internals/voice/dist/routes/index.js // ../_internal-core/dist/error/index.js function safeParseErrorObject(obj) { if (typeof obj !== "object" || obj === null) { return String(obj); } try { const stringified = JSON.stringify(obj); if (stringified === "{}") { return String(obj); } return stringified; } catch { return String(obj); } } function getErrorFromUnknown(unknown, options = {}) { const defaultOptions = { fallbackMessage: "Unknown error", maxDepth: 5, supportSerialization: true, serializeStack: true }; const mergedOptions = options ? { ...defaultOptions, ...options } : defaultOptions; const { fallbackMessage, maxDepth, supportSerialization, serializeStack } = mergedOptions; if (unknown && unknown instanceof Error) { if (supportSerialization) { addErrorToJSON(unknown, serializeStack, { maxDepth }); } return unknown; } let error; if (unknown && typeof unknown === "object") { const errorMessage = unknown && "message" in unknown && typeof unknown.message === "string" ? unknown.message : safeParseErrorObject(unknown); const errorCause = "cause" in unknown && unknown.cause !== void 0 ? unknown.cause instanceof Error ? unknown.cause : maxDepth > 0 ? getErrorFromUnknown(unknown.cause, { ...mergedOptions, maxDepth: maxDepth - 1 }) : void 0 : void 0; error = new Error(errorMessage, errorCause ? { cause: errorCause } : void 0); Object.assign(error, unknown); error.stack = "stack" in unknown && typeof unknown.stack === "string" ? unknown.stack : void 0; } else if (unknown && typeof unknown === "string") { error = new Error(unknown); error.stack = void 0; } else { error = new Error(fallbackMessage); } if (supportSerialization) { addErrorToJSON(error, serializeStack, { maxDepth }); } return error; } var DEFAULT_MAX_DEPTH = 5; function addErrorToJSON(error, serializeStack = true, options) { const maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH; const currentDepth = options?.currentDepth ?? 0; if (error.toJSON) { return; } if (error.cause instanceof Error && currentDepth < maxDepth) { addErrorToJSON(error.cause, serializeStack, { maxDepth, currentDepth: currentDepth + 1 }); } Object.defineProperty(error, "toJSON", { value: function() { const json = { message: this.message, name: this.name }; if (serializeStack && this.stack !== void 0) { json.stack = this.stack; } if (this.cause !== void 0) { if (this.cause instanceof Error && "toJSON" in this.cause && typeof this.cause.toJSON === "function") { json.cause = this.cause.toJSON(); } else { json.cause = this.cause; } } const errorAsAny = this; for (const key in errorAsAny) { if (errorAsAny.hasOwnProperty(key) && !(key in json) && key !== "toJSON") { json[key] = errorAsAny[key]; } } return json; }, enumerable: false, writable: true, configurable: true }); } var ErrorDomain = /* @__PURE__ */ ((ErrorDomain2) => { ErrorDomain2["TOOL"] = "TOOL"; ErrorDomain2["AGENT"] = "AGENT"; ErrorDomain2["MCP"] = "MCP"; ErrorDomain2["AGENT_NETWORK"] = "AGENT_NETWORK"; ErrorDomain2["MASTRA_SERVER"] = "MASTRA_SERVER"; ErrorDomain2["MASTRA_OBSERVABILITY"] = "MASTRA_OBSERVABILITY"; ErrorDomain2["MASTRA_WORKFLOW"] = "MASTRA_WORKFLOW"; ErrorDomain2["MASTRA_VOICE"] = "MASTRA_VOICE"; ErrorDomain2["MASTRA_VECTOR"] = "MASTRA_VECTOR"; ErrorDomain2["MASTRA_MEMORY"] = "MASTRA_MEMORY"; ErrorDomain2["LLM"] = "LLM"; ErrorDomain2["EVAL"] = "EVAL"; ErrorDomain2["SCORER"] = "SCORER"; ErrorDomain2["A2A"] = "A2A"; ErrorDomain2["MASTRA_INSTANCE"] = "MASTRA_INSTANCE"; ErrorDomain2["MASTRA"] = "MASTRA"; ErrorDomain2["DEPLOYER"] = "DEPLOYER"; ErrorDomain2["STORAGE"] = "STORAGE"; ErrorDomain2["MODEL_ROUTER"] = "MODEL_ROUTER"; return ErrorDomain2; })(ErrorDomain || {}); var MastraBaseError = class extends Error { id; domain; category; details = {}; message; cause; constructor(errorDefinition, originalError) { const error = originalError ? getErrorFromUnknown(originalError, { serializeStack: false, fallbackMessage: "Unknown error" }) : void 0; const message = errorDefinition.text ?? error?.message ?? "Unknown error"; super(message, { cause: error }); this.id = errorDefinition.id; this.domain = errorDefinition.domain; this.category = errorDefinition.category; this.details = errorDefinition.details ?? {}; this.message = message; this.cause = error; Object.setPrototypeOf(this, new.target.prototype); } /** * Returns a structured representation of the error, useful for logging or API responses. */ toJSONDetails() { return { message: this.message, domain: this.domain, category: this.category, details: this.details }; } toJSON() { return { message: this.message, domain: this.domain, category: this.category, code: this.id, details: this.details, cause: this.cause?.toJSON?.() }; } toString() { return JSON.stringify(this.toJSON()); } }; var MastraError = class extends MastraBaseError { }; // ../_internal-core/dist/routes/index.js function generateRouteOpenAPI({ method, path, summary, description, tags = [], pathParamSchema, queryParamSchema, bodySchema, responseSchema, deprecated }) { const route = { summary: summary || `${method} ${path}`, description, tags, deprecated, responses: { 200: { description: "Successful response" } } }; if (pathParamSchema || queryParamSchema) { route.requestParams = {}; if (pathParamSchema) { route.requestParams.path = pathParamSchema; } if (queryParamSchema) { route.requestParams.query = queryParamSchema; } } if (bodySchema) { route.requestBody = { content: { "application/json": { schema: bodySchema } } }; } if (responseSchema) { route.responses[200] = { description: "Successful response", content: { "application/json": { schema: responseSchema } } }; } return route; } function createRoute(config) { const { summary, description, tags, deprecated, requiresAuth, requiresPermission, onValidationError, ...baseRoute } = config; const openapi = config.method !== "ALL" ? generateRouteOpenAPI({ method: config.method, path: config.path, summary, description, tags, pathParamSchema: config.pathParamSchema, queryParamSchema: config.queryParamSchema, bodySchema: config.bodySchema, responseSchema: config.responseSchema, deprecated }) : void 0; return { ...baseRoute, openapi, deprecated, requiresAuth, requiresPermission, onValidationError }; } var voiceSpeakersResponseSchema = v4.z.array( v4.z.object({ voiceId: v4.z.string() }).passthrough() ); var generateSpeechBodySchema = v4.z.object({ text: v4.z.string(), speakerId: v4.z.string().optional() }); var transcribeSpeechBodySchema = v4.z.object({ audio: v4.z.any(), options: v4.z.record(v4.z.string(), v4.z.any()).optional() }); var transcribeSpeechResponseSchema = v4.z.object({ text: v4.z.string() }); var getListenerResponseSchema = v4.z.any(); var speakResponseSchema = v4.z.any(); var agentIdPathParams = v4.z.object({ agentId: v4.z.string().describe("Agent ID") }); var HTTPException = class extends Error { status; constructor(status, options = {}) { super(options.message, { cause: options.cause }); this.status = status; this.stack = options.stack || this.stack; } }; function isMastraVoiceError(error) { return error instanceof MastraError || typeof error === "object" && error !== null && "domain" in error && error.domain === ErrorDomain.MASTRA_VOICE || error instanceof Error && error.message === "No voice provider configured"; } function handleError(error, defaultMessage) { const apiError = error; const status = apiError.status || apiError.details?.status || 500; throw new HTTPException(status, { message: apiError.message || defaultMessage, stack: apiError.stack, cause: apiError.cause }); } function validateBody(data) { for (const [key, value] of Object.entries(data)) { if (value === void 0 || value === null || value === "") { throw new HTTPException(400, { message: `${key} is required` }); } } } async function getAgentFromSystem({ mastra, agentId, requestContext }) { const logger = mastra.getLogger?.(); if (!agentId) { throw new HTTPException(400, { message: "Agent ID is required" }); } let agent; try { agent = mastra.getAgentById(agentId); } catch (error) { logger?.debug?.("Error getting agent from mastra, searching agents for agent", error); } if (!agent) { logger?.debug?.("Agent not found, looking through sub-agents", { agentId }); const agents = mastra.listAgents?.(); if (Object.keys(agents || {}).length) { for (const ag of Object.values(agents)) { try { const subAgents = await ag.listAgents(); const subAgent = subAgents[agentId]; if (subAgent) { agent = subAgent; break; } } catch (error) { logger?.debug?.("Error getting agent from agent", error); } } } } if (agent && mastra.getEditor) { try { const editorAgent = mastra.getEditor()?.agent; if (editorAgent) { agent = await editorAgent.applyStoredOverrides(agent, { status: "published" }, requestContext); } } catch (error) { logger?.debug?.("Error applying stored overrides to code agent", error); } } if (!agent) { logger?.debug?.("Agent not found in code-defined agents, looking in stored agents", { agentId }); try { agent = await mastra.getEditor?.()?.agent.getById(agentId) ?? null; } catch (error) { logger?.debug?.("Error getting stored agent", error); } } if (!agent) { throw new HTTPException(404, { message: `Agent with id ${agentId} not found` }); } return agent; } var GET_SPEAKERS_ROUTE = createRoute({ method: "GET", path: "/agents/:agentId/voice/speakers", responseType: "json", summary: "Get voice speakers", description: "Returns available voice speakers for the specified agent", tags: ["Agents", "Voice"], requiresAuth: true, pathParamSchema: agentIdPathParams, responseSchema: voiceSpeakersResponseSchema, handler: async ({ mastra, agentId, requestContext }) => { try { if (!agentId) { throw new HTTPException(400, { message: "Agent ID is required" }); } const agent = await getAgentFromSystem({ mastra, agentId, requestContext }); const voice = await agent.getVoice({ requestContext }); const speakers = await Promise.resolve().then(() => voice.getSpeakers()).catch((err) => { if (isMastraVoiceError(err)) { return []; } throw err; }); return speakers; } catch (error) { return handleError(error, "Error getting speakers"); } } }); var GET_SPEAKERS_DEPRECATED_ROUTE = createRoute({ method: "GET", path: "/agents/:agentId/speakers", responseType: "json", summary: "Get available speakers for an agent", description: "[DEPRECATED] Use /agents/:agentId/voice/speakers instead. Get available speakers for an agent", tags: ["Agents", "Voice"], requiresAuth: true, deprecated: true, pathParamSchema: agentIdPathParams, responseSchema: voiceSpeakersResponseSchema, handler: GET_SPEAKERS_ROUTE.handler }); var GENERATE_SPEECH_ROUTE = createRoute({ method: "POST", path: "/agents/:agentId/voice/speak", responseType: "datastream-response", summary: "Generate speech", description: "Generates speech audio from text using the agent voice configuration", tags: ["Agents", "Voice"], requiresAuth: true, pathParamSchema: agentIdPathParams, bodySchema: generateSpeechBodySchema, responseSchema: speakResponseSchema, handler: async ({ mastra, agentId, text, speakerId, requestContext }) => { try { if (!agentId) { throw new HTTPException(400, { message: "Agent ID is required" }); } validateBody({ text }); const agent = await getAgentFromSystem({ mastra, agentId, requestContext }); const voice = await agent.getVoice({ requestContext }); if (!voice) { throw new HTTPException(400, { message: "Agent does not have voice capabilities" }); } const audioStream = await Promise.resolve().then(() => voice.speak(text, { speaker: speakerId })).catch((err) => { if (isMastraVoiceError(err)) { throw new HTTPException(400, { message: err.message }); } throw err; }); if (!audioStream) { throw new HTTPException(500, { message: "Failed to generate speech" }); } const webStream = audioStream instanceof ReadableStream ? audioStream : audioStream instanceof stream.Readable ? stream.Readable.toWeb(audioStream) : audioStream; return new Response(webStream, { headers: { "Content-Type": "audio/mpeg" } }); } catch (error) { return handleError(error, "Error generating speech"); } } }); var GENERATE_SPEECH_DEPRECATED_ROUTE = createRoute({ method: "POST", path: "/agents/:agentId/speak", responseType: "datastream-response", summary: "Convert text to speech", description: "[DEPRECATED] Use /agents/:agentId/voice/speak instead. Convert text to speech using the agent's voice provider", tags: ["Agents", "Voice"], requiresAuth: true, deprecated: true, pathParamSchema: agentIdPathParams, bodySchema: generateSpeechBodySchema, responseSchema: speakResponseSchema, handler: GENERATE_SPEECH_ROUTE.handler }); var TRANSCRIBE_SPEECH_ROUTE = createRoute({ method: "POST", path: "/agents/:agentId/voice/listen", responseType: "json", summary: "Transcribe speech", description: "Transcribes speech audio to text using the agent voice configuration", tags: ["Agents", "Voice"], requiresAuth: true, pathParamSchema: agentIdPathParams, bodySchema: transcribeSpeechBodySchema, responseSchema: transcribeSpeechResponseSchema, handler: async ({ mastra, agentId, audio, options, requestContext }) => { try { if (!agentId) { throw new HTTPException(400, { message: "Agent ID is required" }); } if (!audio) { throw new HTTPException(400, { message: "Audio data is required" }); } const agent = await getAgentFromSystem({ mastra, agentId, requestContext }); const voice = await agent.getVoice({ requestContext }); if (!voice) { throw new HTTPException(400, { message: "Agent does not have voice capabilities" }); } const audioStream = new stream.Readable(); audioStream.push(audio); audioStream.push(null); const text = await voice.listen(audioStream, options); return { text }; } catch (error) { return handleError(error, "Error transcribing speech"); } } }); var TRANSCRIBE_SPEECH_DEPRECATED_ROUTE = createRoute({ method: "POST", path: "/agents/:agentId/listen", responseType: "json", summary: "Convert speech to text", description: "[DEPRECATED] Use /agents/:agentId/voice/listen instead. Convert speech to text using the agent's voice provider. Additional provider-specific options can be passed as query parameters.", tags: ["Agents", "Voice"], requiresAuth: true, deprecated: true, pathParamSchema: agentIdPathParams, bodySchema: transcribeSpeechBodySchema, responseSchema: transcribeSpeechResponseSchema, handler: TRANSCRIBE_SPEECH_ROUTE.handler }); var GET_LISTENER_ROUTE = createRoute({ method: "GET", path: "/agents/:agentId/voice/listener", responseType: "json", summary: "Get voice listener", description: "Returns the voice listener configuration for the agent", tags: ["Agents", "Voice"], requiresAuth: true, pathParamSchema: agentIdPathParams, responseSchema: getListenerResponseSchema, handler: async ({ mastra, agentId, requestContext }) => { try { if (!agentId) { throw new HTTPException(400, { message: "Agent ID is required" }); } const agent = mastra.getAgentById(agentId); if (!agent) { throw new HTTPException(404, { message: "Agent not found" }); } const voice = await agent.getVoice({ requestContext }); const listeners = await Promise.resolve().then(() => voice.getListener()).catch((err) => { if (isMastraVoiceError(err)) { return { enabled: false }; } throw err; }); return listeners; } catch (error) { return handleError(error, "Error getting listeners"); } } }); exports.GENERATE_SPEECH_DEPRECATED_ROUTE = GENERATE_SPEECH_DEPRECATED_ROUTE; exports.GENERATE_SPEECH_ROUTE = GENERATE_SPEECH_ROUTE; exports.GET_LISTENER_ROUTE = GET_LISTENER_ROUTE; exports.GET_SPEAKERS_DEPRECATED_ROUTE = GET_SPEAKERS_DEPRECATED_ROUTE; exports.GET_SPEAKERS_ROUTE = GET_SPEAKERS_ROUTE; exports.TRANSCRIBE_SPEECH_DEPRECATED_ROUTE = TRANSCRIBE_SPEECH_DEPRECATED_ROUTE; exports.TRANSCRIBE_SPEECH_ROUTE = TRANSCRIBE_SPEECH_ROUTE; exports.generateSpeechBodySchema = generateSpeechBodySchema; exports.getListenerResponseSchema = getListenerResponseSchema; exports.speakResponseSchema = speakResponseSchema; exports.transcribeSpeechBodySchema = transcribeSpeechBodySchema; exports.transcribeSpeechResponseSchema = transcribeSpeechResponseSchema; exports.voiceSpeakersResponseSchema = voiceSpeakersResponseSchema; //# sourceMappingURL=chunk-47PVLKIL.cjs.map //# sourceMappingURL=chunk-47PVLKIL.cjs.map