'use strict'; var chunkHXICAUTW_cjs = require('./chunk-HXICAUTW.cjs'); var chunkQQCQV7ZF_cjs = require('./chunk-QQCQV7ZF.cjs'); var chunkRVD3DGBZ_cjs = require('./chunk-RVD3DGBZ.cjs'); var chunkTIWGWGIO_cjs = require('./chunk-TIWGWGIO.cjs'); var chunkGZ4HWZWE_cjs = require('./chunk-GZ4HWZWE.cjs'); var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs'); var chunkG54X6VE6_cjs = require('./chunk-G54X6VE6.cjs'); var chunk3YQ7NWF6_cjs = require('./chunk-3YQ7NWF6.cjs'); var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs'); var chunkSXKQ7CSX_cjs = require('./chunk-SXKQ7CSX.cjs'); var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs'); var agent = require('@mastra/core/agent'); var durable = require('@mastra/core/agent/durable'); var di = require('@mastra/core/di'); var error = require('@mastra/core/error'); var llm = require('@mastra/core/llm'); var zodToJson = require('@mastra/core/utils/zod-to-json'); var v4 = require('zod/v4'); // src/server/handlers/agents.ts var agents_exports = {}; chunkO7I5CWRX_cjs.__export(agents_exports, { ABORT_AGENT_THREAD_ROUTE: () => ABORT_AGENT_THREAD_ROUTE, APPROVE_NETWORK_TOOL_CALL_ROUTE: () => APPROVE_NETWORK_TOOL_CALL_ROUTE, APPROVE_TOOL_CALL_GENERATE_ROUTE: () => APPROVE_TOOL_CALL_GENERATE_ROUTE, APPROVE_TOOL_CALL_ROUTE: () => APPROVE_TOOL_CALL_ROUTE, CLONE_AGENT_ROUTE: () => CLONE_AGENT_ROUTE, DECLINE_NETWORK_TOOL_CALL_ROUTE: () => DECLINE_NETWORK_TOOL_CALL_ROUTE, DECLINE_TOOL_CALL_GENERATE_ROUTE: () => DECLINE_TOOL_CALL_GENERATE_ROUTE, DECLINE_TOOL_CALL_ROUTE: () => DECLINE_TOOL_CALL_ROUTE, ENHANCE_INSTRUCTIONS_ROUTE: () => ENHANCE_INSTRUCTIONS_ROUTE, GENERATE_AGENT_ROUTE: () => GENERATE_AGENT_ROUTE, GENERATE_AGENT_VNEXT_ROUTE: () => GENERATE_AGENT_VNEXT_ROUTE, GENERATE_LEGACY_ROUTE: () => GENERATE_LEGACY_ROUTE, GET_AGENT_BY_ID_ROUTE: () => GET_AGENT_BY_ID_ROUTE, GET_AGENT_SKILL_ROUTE: () => GET_AGENT_SKILL_ROUTE, GET_PROVIDERS_ROUTE: () => GET_PROVIDERS_ROUTE, LIST_AGENTS_ROUTE: () => LIST_AGENTS_ROUTE, OBSERVE_AGENT_STREAM_ROUTE: () => OBSERVE_AGENT_STREAM_ROUTE, QUEUE_AGENT_MESSAGE_ROUTE: () => QUEUE_AGENT_MESSAGE_ROUTE, REORDER_AGENT_MODEL_LIST_ROUTE: () => REORDER_AGENT_MODEL_LIST_ROUTE, RESET_AGENT_MODEL_ROUTE: () => RESET_AGENT_MODEL_ROUTE, RESUME_STREAM_ROUTE: () => RESUME_STREAM_ROUTE, RESUME_STREAM_UNTIL_IDLE_ROUTE: () => RESUME_STREAM_UNTIL_IDLE_ROUTE, SEND_AGENT_MESSAGE_ROUTE: () => SEND_AGENT_MESSAGE_ROUTE, SEND_AGENT_SIGNAL_ROUTE: () => SEND_AGENT_SIGNAL_ROUTE, SEND_TOOL_APPROVAL_ROUTE: () => SEND_TOOL_APPROVAL_ROUTE, STREAM_GENERATE_LEGACY_ROUTE: () => STREAM_GENERATE_LEGACY_ROUTE, STREAM_GENERATE_ROUTE: () => STREAM_GENERATE_ROUTE, STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE: () => STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE, STREAM_NETWORK_ROUTE: () => STREAM_NETWORK_ROUTE, STREAM_UI_MESSAGE_DEPRECATED_ROUTE: () => STREAM_UI_MESSAGE_DEPRECATED_ROUTE, STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE: () => STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE, STREAM_UNTIL_IDLE_GENERATE_ROUTE: () => STREAM_UNTIL_IDLE_GENERATE_ROUTE, STREAM_VNEXT_DEPRECATED_ROUTE: () => STREAM_VNEXT_DEPRECATED_ROUTE, SUBSCRIBE_AGENT_THREAD_ROUTE: () => SUBSCRIBE_AGENT_THREAD_ROUTE, UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE: () => UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE, UPDATE_AGENT_MODEL_ROUTE: () => UPDATE_AGENT_MODEL_ROUTE, buildProvidersList: () => buildProvidersList, extractVersionOptions: () => extractVersionOptions, getAgentFromSystem: () => getAgentFromSystem, getBrowserToolsFromAgent: () => getBrowserToolsFromAgent, getSerializedAgentTools: () => getSerializedAgentTools, getSerializedProcessors: () => getSerializedProcessors, getSerializedSkillsFromAgent: () => getSerializedSkillsFromAgent, getWorkspaceToolsFromAgent: () => getWorkspaceToolsFromAgent, isProviderConnected: () => isProviderConnected }); function stashVersionOverrides(ctx, versions) { if (!versions) return; const existingRaw = ctx.get(di.MASTRA_VERSIONS_KEY); const existing = existingRaw && typeof existingRaw === "object" && !Array.isArray(existingRaw) ? existingRaw : void 0; const merged = di.mergeVersionOverrides(existing, versions); if (merged) { ctx.set(di.MASTRA_VERSIONS_KEY, merged); } } function ensureDefaultVersionStatus(ctx, versionOptions) { const existingRaw = ctx.get(di.MASTRA_VERSIONS_KEY); if (existingRaw?.defaultStatus) return; const inferredStatus = versionOptions ? "draft" : "published"; const updated = { ...existingRaw, defaultStatus: inferredStatus }; ctx.set(di.MASTRA_VERSIONS_KEY, updated); } function getIsStudioFromContext(requestContext) { return requestContext.get(chunkSXKQ7CSX_cjs.MASTRA_IS_STUDIO_KEY) === true; } function mergeBodyRequestContext(serverRequestContext, bodyRequestContext) { if (!bodyRequestContext || typeof bodyRequestContext !== "object") { return; } for (const [key, value] of Object.entries(bodyRequestContext)) { if (chunkSXKQ7CSX_cjs.isReservedRequestContextKey(key)) continue; if (serverRequestContext.get(key) === void 0) { serverRequestContext.set(key, value); } } } function isProviderConnected(providerId, customProviders) { const cleanId = providerId.includes(".") ? providerId.split(".")[0] : providerId; let provider = llm.PROVIDER_REGISTRY[cleanId]; if (!provider && customProviders) { provider = customProviders[cleanId]; } if (!provider && !cleanId.includes("/")) { const registryKeys = Object.keys(llm.PROVIDER_REGISTRY); const matchingKey = registryKeys.find((key) => { const parts = key.split("/"); return parts.length === 2 && parts[1] === cleanId; }); if (matchingKey) { provider = llm.PROVIDER_REGISTRY[matchingKey]; } if (!provider && customProviders) { const customMatchingKey = Object.keys(customProviders).find((key) => { const parts = key.split("/"); return parts.length === 2 && parts[1] === cleanId; }); if (customMatchingKey) { provider = customProviders[customMatchingKey]; } } } if (!provider) return false; const envVars = Array.isArray(provider.apiKeyEnvVar) ? provider.apiKeyEnvVar : [provider.apiKeyEnvVar]; return envVars.every((envVar) => !!process.env[envVar]); } function resolveLazySchema(schema) { if (typeof schema === "function" && !("~standard" in schema)) { return resolveLazySchema(schema()); } return schema; } function schemaToJsonSchema(schema) { if (!schema) { return void 0; } return chunk3YQ7NWF6_cjs.standardSchemaToJSONSchema(chunk3YQ7NWF6_cjs.toStandardSchema5(schema), { target: "draft-2020-12" }); } async function getSerializedAgentTools(tools, partial = false) { return Object.entries(tools || {}).reduce((acc, [key, tool]) => { const toolId = tool.id ?? `tool-${key}`; let inputSchemaForReturn = void 0; let outputSchemaForReturn = void 0; let requestContextSchemaForReturn = void 0; if (!partial) { try { const inputSchema = schemaToJsonSchema( resolveLazySchema(tool.inputSchema) ); if (inputSchema !== void 0) { inputSchemaForReturn = chunkGZ4HWZWE_cjs.stringify(inputSchema); } const outputSchema = schemaToJsonSchema( resolveLazySchema(tool.outputSchema) ); if (outputSchema !== void 0) { outputSchemaForReturn = chunkGZ4HWZWE_cjs.stringify(outputSchema); } const requestContextSchema = schemaToJsonSchema( resolveLazySchema(tool.requestContextSchema) ); if (requestContextSchema !== void 0) { requestContextSchemaForReturn = chunkGZ4HWZWE_cjs.stringify(requestContextSchema); } } catch (error) { console.error(`Error getting serialized tool`, { toolId: tool.id, error }); } } acc[key] = { ...tool, id: toolId, inputSchema: inputSchemaForReturn, outputSchema: outputSchemaForReturn, requestContextSchema: requestContextSchemaForReturn }; return acc; }, {}); } function getSerializedProcessors(processors) { return processors.map((processor) => { return { id: processor.id, name: processor.name || processor.constructor.name }; }); } async function getSerializedSkillsFromAgent(agent, requestContext) { try { const workspace = await agent.getWorkspace({ requestContext }); if (!workspace?.skills) { return []; } const skillsList = await workspace.skills.list(); return skillsList.map((skill) => ({ name: skill.name, description: skill.description, license: skill.license, path: skill.path })); } catch { return []; } } async function getWorkspaceToolsFromAgent(agent, requestContext) { try { const workspace = await agent.getWorkspace({ requestContext }); if (!workspace) { return []; } try { const mod = await import('@mastra/core/workspace'); if (typeof mod.createWorkspaceTools === "function") { return Object.keys(await mod.createWorkspaceTools(workspace)); } } catch { } const tools = []; const isReadOnly = workspace.filesystem?.readOnly ?? false; const toolsConfig = workspace.getToolsConfig(); const configContext = { workspace, requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {} }; const isEnabled = async (toolName) => { return (await chunkSXKQ7CSX_cjs.resolveToolConfig(toolsConfig, toolName, configContext)).enabled; }; if (workspace.filesystem) { if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.READ_FILE)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.READ_FILE); } if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES); } if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT); } if (!isReadOnly) { if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE); } if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE); } if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.DELETE)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.DELETE); } if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.MKDIR)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.MKDIR); } } if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.GREP)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.FILESYSTEM.GREP); } } if (workspace.canBM25 || workspace.canVector) { if (await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.SEARCH.SEARCH)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.SEARCH.SEARCH); } if (!isReadOnly && await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.SEARCH.INDEX)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.SEARCH.INDEX); } } if (workspace.sandbox) { if (workspace.sandbox.executeCommand && await isEnabled(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND)) { tools.push(chunkSXKQ7CSX_cjs.WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND); } } return tools; } catch { return []; } } function getBrowserToolsFromAgent(agent, onError) { try { const browser = agent.browser; if (!browser) { return []; } return Object.keys(browser.getTools()); } catch (error) { onError?.(error); return []; } } function createBrowserToolsErrorLogger(logger, agentId) { return (error) => logger.warn("Failed to get browser tools for agent", { agentId, error }); } async function getSerializedAgentDefinition({ agent, requestContext, logger }) { let serializedAgentAgents = {}; if ("listAgents" in agent) { try { const agents = await agent.listAgents({ requestContext }); serializedAgentAgents = Object.entries(agents || {}).reduce( (acc, [key, agent2]) => { acc[key] = { id: agent2.id, name: agent2.name ?? key }; return acc; }, {} ); } catch (error) { logger?.warn("Error getting sub-agents for agent", { agentName: agent.name, error }); } } return serializedAgentAgents; } async function formatAgentList({ id, mastra, agent, requestContext, partial = false }) { const logger = mastra.getLogger(); const description = agent.getDescription(); let metadata; if (typeof agent.getMetadata === "function") { try { metadata = await agent.getMetadata({ requestContext }); } catch { } } let instructions; try { instructions = await agent.getInstructions({ requestContext }); } catch (error) { logger.warn("Error getting instructions for agent", { agentName: agent.name, error }); } let tools = {}; try { tools = await agent.listTools({ requestContext }); } catch (error) { logger.warn("Error listing tools for agent", { agentName: agent.name, error }); } let llm$1; try { llm$1 = await agent.getLLM({ requestContext }); } catch (error) { logger.warn("Error getting LLM for agent", { agentName: agent.name, error }); } let defaultGenerateOptionsLegacy; try { defaultGenerateOptionsLegacy = await agent.getDefaultGenerateOptionsLegacy({ requestContext }); } catch (error) { logger.warn("Error getting default generate options for agent", { agentName: agent.name, error }); } let defaultStreamOptionsLegacy; try { defaultStreamOptionsLegacy = await agent.getDefaultStreamOptionsLegacy({ requestContext }); } catch (error) { logger.warn("Error getting default stream options for agent", { agentName: agent.name, error }); } let defaultOptions; try { defaultOptions = await agent.getDefaultOptions({ requestContext }); } catch (error) { logger.warn("Error getting default options for agent", { agentName: agent.name, error }); } const serializedAgentTools = await getSerializedAgentTools(tools, partial); let serializedAgentWorkflows = {}; if ("listWorkflows" in agent) { try { const workflows = await agent.listWorkflows({ requestContext }); serializedAgentWorkflows = Object.entries(workflows || {}).reduce((acc, [key, workflow]) => { return { ...acc, [key]: { name: workflow.name || "Unnamed workflow" } }; }, {}); } catch (error) { logger.error("Error getting workflows for agent", { agentName: agent.name, error }); } } const serializedAgentAgents = await getSerializedAgentDefinition({ agent, requestContext, logger }); let serializedInputProcessors = []; let serializedOutputProcessors = []; try { const configuredProcessorWorkflows = await agent.getConfiguredProcessorWorkflows(); const inputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-input-processor")); const outputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-output-processor")); serializedInputProcessors = getSerializedProcessors(inputProcessorWorkflows); serializedOutputProcessors = getSerializedProcessors(outputProcessorWorkflows); } catch (error) { logger.error("Error getting configured processors for agent", { agentName: agent.name, error }); } const serializedSkills = await getSerializedSkillsFromAgent(agent, requestContext); const workspaceTools = await getWorkspaceToolsFromAgent(agent, requestContext); const browserTools = getBrowserToolsFromAgent(agent, createBrowserToolsErrorLogger(logger, agent.id)); let workspaceId; try { const workspace = await agent.getWorkspace({ requestContext }); workspaceId = workspace?.id; } catch { } const model = llm$1?.getModel(); const supportsMemory = typeof agent.supportsMemory === "function" ? agent.supportsMemory() : true; let models; try { models = await agent.getModelList(requestContext); } catch (error) { logger.warn("Error getting model list for agent", { agentName: agent.name, error }); } const modelList = models?.map((md) => ({ ...md, model: { modelId: md.model.modelId, provider: md.model.provider, modelVersion: md.model.specificationVersion } })); let serializedRequestContextSchema; if (agent.requestContextSchema) { try { serializedRequestContextSchema = chunkGZ4HWZWE_cjs.stringify(zodToJson.zodToJsonSchema(agent.requestContextSchema)); } catch (error) { logger.error("Error serializing requestContextSchema for agent", { agentName: agent.name, error }); } } return { id: agent.id || id, name: agent.name, description, metadata, instructions, agents: serializedAgentAgents, tools: serializedAgentTools, workflows: serializedAgentWorkflows, skills: serializedSkills, workspaceTools, browserTools, workspaceId, inputProcessors: serializedInputProcessors, outputProcessors: serializedOutputProcessors, provider: typeof agent.model === "string" ? llm.parseModelString(agent.model).provider ?? llm$1?.getProvider() : llm$1?.getProvider(), modelId: typeof agent.model === "string" ? llm.parseModelString(agent.model).modelId : llm$1?.getModelId(), modelVersion: model?.specificationVersion, supportsMemory, defaultOptions, modelList, defaultGenerateOptionsLegacy, defaultStreamOptionsLegacy, requestContextSchema: serializedRequestContextSchema, source: agent.source ?? "code", editor: agent.__getEditorConfig?.(), ...agent.toRawConfig()?.status ? { status: agent.toRawConfig().status } : {}, ...agent.toRawConfig()?.activeVersionId ? { activeVersionId: agent.toRawConfig().activeVersionId } : {}, hasDraft: !!(agent.toRawConfig()?.resolvedVersionId && agent.toRawConfig()?.activeVersionId && agent.toRawConfig().resolvedVersionId !== agent.toRawConfig().activeVersionId) }; } function extractVersionOptions(requestContext, bodyRequestContext) { const agentVersionId = requestContext?.get("agentVersionId"); if (typeof agentVersionId === "string" && agentVersionId) { return { versionId: agentVersionId }; } const bodyVersionId = bodyRequestContext?.agentVersionId; if (typeof bodyVersionId === "string" && bodyVersionId) { return { versionId: bodyVersionId }; } return void 0; } async function getAgentFromSystem({ mastra, agentId, versionOptions, requestContext }) { const logger = mastra.getLogger(); if (!agentId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Agent ID is required" }); } let agent$1; try { agent$1 = mastra.getAgentById(agentId); } catch (error) { logger.debug("Error getting agent from mastra, searching agents for agent", error); } if (!agent$1) { logger.debug("Agent not found, looking through sub-agents", { agentId }); const agents = mastra.listAgents(); if (Object.keys(agents || {}).length) { for (const [_, ag] of Object.entries(agents)) { try { const subAgents = await ag.listAgents(); const subAgent = subAgents[agentId]; if (subAgent instanceof agent.Agent) { agent$1 = subAgent; break; } } catch (error) { logger.debug("Error getting agent from agent", error); } } } } if (agent$1 && mastra.getEditor) { try { const editorAgent = mastra.getEditor()?.agent; if (editorAgent) { agent$1 = await editorAgent.applyStoredOverrides( agent$1, versionOptions ?? { status: "published" }, requestContext ); } } catch (error) { logger.debug("Error applying stored overrides to code agent", error); } } if (!agent$1) { logger.debug("Agent not found in code-defined agents, looking in stored agents", { agentId }); try { agent$1 = await mastra.getEditor()?.agent.getById(agentId, versionOptions) ?? null; } catch (error) { logger.debug("Error getting stored agent", error); } } if (!agent$1) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${agentId} not found` }); } return agent$1; } async function formatAgent({ mastra, agent, requestContext, isStudio }) { const description = agent.getDescription(); let metadata; if (typeof agent.getMetadata === "function") { try { metadata = await agent.getMetadata({ requestContext }); } catch { } } const tools = await agent.listTools({ requestContext }); const serializedAgentTools = await getSerializedAgentTools(tools); let serializedAgentWorkflows = {}; if ("listWorkflows" in agent) { const logger = mastra.getLogger(); try { const workflows = await agent.listWorkflows({ requestContext }); serializedAgentWorkflows = Object.entries(workflows || {}).reduce((acc, [key, workflow]) => { return { ...acc, [key]: { name: workflow.name || "Unnamed workflow", steps: Object.entries(workflow.steps).reduce( (acc2, [key2, step]) => { return { ...acc2, [key2]: { id: step.id, description: step.description } }; }, {} ) } }; }, {}); } catch (error) { logger.error("Error getting workflows for agent", { agentName: agent.name, error }); } } const instructionsRequestContext = isStudio ? new Proxy(requestContext, { get(target, prop) { if (prop === "get") { return function(key) { const value = target.get(key); return value ?? `<${key}>`; }; } return Reflect.get(target, prop); } }) : requestContext; const instructions = await agent.getInstructions({ requestContext: instructionsRequestContext }); const llm$1 = await agent.getLLM({ requestContext }); const defaultGenerateOptionsLegacy = await agent.getDefaultGenerateOptionsLegacy({ requestContext }); const defaultStreamOptionsLegacy = await agent.getDefaultStreamOptionsLegacy({ requestContext }); const defaultOptions = await agent.getDefaultOptions({ requestContext }); const model = llm$1?.getModel(); const supportsMemory = typeof agent.supportsMemory === "function" ? agent.supportsMemory() : true; const models = await agent.getModelList(requestContext); const modelList = models?.map((md) => ({ ...md, model: { modelId: md.model.modelId, provider: md.model.provider, modelVersion: md.model.specificationVersion } })); const serializedAgentAgents = await getSerializedAgentDefinition({ agent, requestContext }); let serializedInputProcessors = []; let serializedOutputProcessors = []; try { const configuredProcessorWorkflows = await agent.getConfiguredProcessorWorkflows(); const inputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-input-processor")); const outputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-output-processor")); serializedInputProcessors = getSerializedProcessors(inputProcessorWorkflows); serializedOutputProcessors = getSerializedProcessors(outputProcessorWorkflows); } catch (error) { mastra.getLogger().error("Error getting configured processors for agent", { agentName: agent.name, error }); } const serializedSkills = await getSerializedSkillsFromAgent(agent, requestContext); const workspaceTools = await getWorkspaceToolsFromAgent(agent, requestContext); const browserTools = getBrowserToolsFromAgent(agent, createBrowserToolsErrorLogger(mastra.getLogger(), agent.id)); let workspaceId; try { const workspace = await agent.getWorkspace({ requestContext }); workspaceId = workspace?.id; } catch { } let serializedRequestContextSchema; if (agent.requestContextSchema) { try { serializedRequestContextSchema = chunkGZ4HWZWE_cjs.stringify(zodToJson.zodToJsonSchema(agent.requestContextSchema)); } catch (error) { mastra.getLogger().error("Error serializing requestContextSchema for agent", { agentName: agent.name, error }); } } return { name: agent.name, description, metadata, instructions, tools: serializedAgentTools, agents: serializedAgentAgents, workflows: serializedAgentWorkflows, skills: serializedSkills, workspaceTools, browserTools, workspaceId, inputProcessors: serializedInputProcessors, outputProcessors: serializedOutputProcessors, provider: typeof agent.model === "string" ? llm.parseModelString(agent.model).provider ?? llm$1?.getProvider() : llm$1?.getProvider(), modelId: typeof agent.model === "string" ? llm.parseModelString(agent.model).modelId : llm$1?.getModelId(), modelVersion: model?.specificationVersion, supportsMemory, modelList, defaultOptions, defaultGenerateOptionsLegacy, defaultStreamOptionsLegacy, requestContextSchema: serializedRequestContextSchema, source: agent.source ?? "code", editor: agent.__getEditorConfig?.(), ...agent.toRawConfig()?.status ? { status: agent.toRawConfig().status } : {} }; } var LIST_AGENTS_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "GET", path: "/agents", responseType: "json", queryParamSchema: v4.z.object({ partial: v4.z.string().optional() }), responseSchema: chunkQQCQV7ZF_cjs.listAgentsResponseSchema, summary: "List all agents", description: "Returns a list of all available agents in the system (both code-defined and stored)", tags: ["Agents"], requiresAuth: true, requiresPermission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.AGENTS_READ, handler: async ({ mastra, requestContext, partial }) => { try { const codeAgents = mastra.listAgents(); const isPartial = partial === "true"; const editor = mastra.getEditor?.(); const logger = mastra.getLogger(); const serializedCodeAgentsMap = await Promise.allSettled( Object.entries(codeAgents).map(async ([id, agent]) => { let mergedAgent = agent; if (editor) { try { mergedAgent = await editor.agent.applyStoredOverrides(agent, void 0, requestContext); } catch { } } return formatAgentList({ id, mastra, agent: mergedAgent, requestContext, partial: isPartial }); }) ); const serializedAgents = {}; for (let i = 0; i < serializedCodeAgentsMap.length; i++) { const settled = serializedCodeAgentsMap[i]; if (settled.status === "fulfilled") { const { id, ...rest } = settled.value; serializedAgents[id] = { id, ...rest }; } else { const agentId = Object.keys(codeAgents)[i]; logger.warn("Failed to serialize agent", { agentId, error: settled.reason }); } } try { const editor2 = mastra.getEditor(); let storedAgentsResult; try { storedAgentsResult = await editor2?.agent.list(); } catch (error) { console.error("Error listing stored agents:", error); storedAgentsResult = null; } const codeAgentIds = /* @__PURE__ */ new Set(); for (const [key, agent] of Object.entries(codeAgents)) { codeAgentIds.add(key); if (agent?.id) codeAgentIds.add(agent.id); } if (storedAgentsResult?.agents) { for (const storedAgentConfig of storedAgentsResult.agents) { if (codeAgentIds.has(storedAgentConfig.id)) continue; try { const agent = await editor2?.agent.getById(storedAgentConfig.id, { status: "draft" }); if (!agent) continue; const serialized = await formatAgentList({ id: agent.id, mastra, agent, requestContext, partial: isPartial }); if (!serializedAgents[serialized.id]) { serializedAgents[serialized.id] = serialized; } } catch (agentError) { const logger2 = mastra.getLogger(); logger2.warn("Failed to serialize stored agent", { agentId: storedAgentConfig.id, error: agentError }); } } } } catch (storageError) { const logger2 = mastra.getLogger(); logger2.debug("Could not fetch stored agents", { error: storageError }); } const fgaProvider = mastra.getServer?.()?.fga; const user = requestContext?.get("user"); if (fgaProvider && user) { const agentList = Object.values(serializedAgents); const accessible = await fgaProvider.filterAccessible( user, agentList, "agent", chunkRVD3DGBZ_cjs.MastraFGAPermissions.AGENTS_READ ); const accessibleSet = new Set(accessible.map((a) => a.id)); for (const id of Object.keys(serializedAgents)) { if (!accessibleSet.has(id)) { delete serializedAgents[id]; } } } return serializedAgents; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error getting agents"); } } }); var GET_AGENT_BY_ID_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "GET", path: "/agents/:agentId", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, queryParamSchema: chunkQQCQV7ZF_cjs.agentVersionQuerySchema, responseSchema: chunkQQCQV7ZF_cjs.serializedAgentSchema, summary: "Get agent by ID", description: "Returns details for a specific agent including configuration, tools, and memory settings. Use query params to control which stored config version is used for overrides: ?status=published (active version, default), ?status=draft (latest draft), or ?versionId= (specific version). Use either status or versionId, not both.", tags: ["Agents"], requiresAuth: true, requiresPermission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.AGENTS_READ, handler: async ({ agentId, mastra, requestContext, status, versionId }) => { try { const versionOptions = versionId ? { versionId } : status ? { status } : void 0; const agent = await getAgentFromSystem({ mastra, agentId, versionOptions, requestContext }); const isStudio = getIsStudioFromContext(requestContext); const result = await formatAgent({ mastra, agent, requestContext, isStudio }); return result; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error getting agent"); } } }); var CLONE_AGENT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/clone", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: v4.z.object({ newId: v4.z.string().optional().describe("ID for the cloned agent. If not provided, derived from agent ID."), newName: v4.z.string().optional().describe('Name for the cloned agent. Defaults to "{name} (Clone)".'), metadata: v4.z.record(v4.z.string(), v4.z.unknown()).optional(), authorId: v4.z.string().optional() }), responseSchema: chunkTIWGWGIO_cjs.createStoredAgentResponseSchema, summary: "Clone agent", description: "Clones a code-defined or stored agent to a new stored agent in the database", tags: ["Agents"], requiresAuth: true, handler: async ({ agentId, mastra, newId, newName, metadata, authorId, requestContext }) => { try { const editor = mastra.getEditor(); if (!editor) { return chunkZ7LCIYK7_cjs.handleError(new Error("Editor is not configured on the Mastra instance"), "Error cloning agent"); } const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); const cloneId = chunkGZ4HWZWE_cjs.toSlug(newId || `${agentId}-clone`); const result = await editor.agent.clone(agent, { newId: cloneId, newName, metadata, authorId, requestContext }); return result; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error cloning agent"); } } }); var GENERATE_AGENT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/generate", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.generateResponseSchema, summary: "Generate agent response", description: "Executes an agent with the provided messages and returns the complete response", tags: ["Agents"], requiresAuth: true, requiresPermission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.AGENTS_EXECUTE, handler: async ({ agentId, mastra, abortSignal, requestContext: serverRequestContext, ...params }) => { try { chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params; chunkRVD3DGBZ_cjs.validateBody({ messages }); const versionOptions = extractVersionOptions( serverRequestContext, bodyRequestContext ); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions, requestContext: serverRequestContext }); mergeBodyRequestContext(serverRequestContext, bodyRequestContext); stashVersionOverrides(serverRequestContext, versions); ensureDefaultVersionStatus(serverRequestContext, versionOptions); let authorizedMemoryOption = memoryOption; if (memoryOption) { const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id; const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, memoryOption.resource); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId); if (effectiveThreadId) { const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext }); if (memoryInstance) { const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId }); if (thread) { await chunkRVD3DGBZ_cjs.enforceThreadAccess({ mastra, requestContext: serverRequestContext, threadId: effectiveThreadId, thread, effectiveResourceId, permission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.MEMORY_WRITE }); } } } authorizedMemoryOption = { ...memoryOption, resource: effectiveResourceId ?? memoryOption.resource, thread: effectiveThreadId ?? memoryOption.thread }; } const { structuredOutput, ...restOptions } = rest; const options = { ...restOptions, requestContext: serverRequestContext, memory: authorizedMemoryOption, abortSignal }; const result = structuredOutput ? await agent.generate(messages, { ...options, structuredOutput }) : await agent.generate(messages, options); return result; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error generating from agent"); } } }); var GENERATE_LEGACY_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/generate-legacy", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionLegacyBodySchema, responseSchema: chunkQQCQV7ZF_cjs.generateResponseSchema, summary: "[DEPRECATED] Generate with legacy format", description: "Legacy endpoint for generating agent responses. Use /agents/:agentId/generate instead.", tags: ["Agents", "Legacy"], requiresAuth: true, handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext), requestContext }); chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { messages, resourceId, resourceid, threadId, ...rest } = params; const clientResourceId = resourceId ?? resourceid; const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(requestContext, clientResourceId); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(requestContext, threadId); chunkRVD3DGBZ_cjs.validateBody({ messages }); if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Both threadId or resourceId must be provided" }); } if (effectiveThreadId) { const memory = await agent.getMemory({ requestContext }); if (memory) { const thread = await memory.getThreadById({ threadId: effectiveThreadId }); if (thread) { await chunkRVD3DGBZ_cjs.enforceThreadAccess({ mastra, requestContext, threadId: effectiveThreadId, thread, effectiveResourceId, permission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.MEMORY_WRITE }); } } } const result = await agent.generateLegacy(messages, { ...rest, abortSignal, resourceId: effectiveResourceId ?? "", threadId: effectiveThreadId ?? "" }); return result; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error generating from agent"); } } }); var STREAM_GENERATE_LEGACY_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/stream-legacy", responseType: "datastream-response", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionLegacyBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "[DEPRECATED] Stream with legacy format", description: "Legacy endpoint for streaming agent responses. Use /agents/:agentId/stream instead.", tags: ["Agents", "Legacy"], requiresAuth: true, handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext), requestContext }); chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { messages, resourceId, resourceid, threadId, ...rest } = params; const clientResourceId = resourceId ?? resourceid; const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(requestContext, clientResourceId); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(requestContext, threadId); chunkRVD3DGBZ_cjs.validateBody({ messages }); if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Both threadId or resourceId must be provided" }); } if (effectiveThreadId) { const memory = await agent.getMemory({ requestContext }); if (memory) { const thread = await memory.getThreadById({ threadId: effectiveThreadId }); if (thread) { await chunkRVD3DGBZ_cjs.enforceThreadAccess({ mastra, requestContext, threadId: effectiveThreadId, thread, effectiveResourceId, permission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.MEMORY_WRITE }); } } } const streamResult = await agent.streamLegacy(messages, { ...rest, abortSignal, resourceId: effectiveResourceId ?? "", threadId: effectiveThreadId ?? "" }); const streamResponse = rest.output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({ sendUsage: true, sendReasoning: true, getErrorMessage: (error) => { if (error instanceof Error) { const safeMessage = error.message.replace(/([A-Za-z]:)?[\/][^\s,)]+/g, "").replace(/\s+at\s+[^\n]*/g, "").replace(/Response body:.*/s, "").trim(); return `An error occurred while processing your request. ${safeMessage || "Unknown error"}`; } return "An error occurred while processing your request."; } }); return streamResponse; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error streaming agent response"); } } }); async function buildProvidersList(mastra) { const allProviders = {}; for (const [id, provider] of Object.entries(llm.PROVIDER_REGISTRY)) { allProviders[id] = provider; } if (mastra) { const allGateways = mastra.listGateways(); if (allGateways) { for (const gateway of Object.values(allGateways)) { if (gateway.id === "models.dev") continue; try { const gatewayProviders = await gateway.fetchProviders(); for (const [providerId, config] of Object.entries(gatewayProviders)) { const prefixedId = providerId === gateway.id ? gateway.id : `${gateway.id}/${providerId}`; if (!(prefixedId in allProviders)) { allProviders[prefixedId] = config; } } } catch (error) { console.warn(`Failed to fetch providers from gateway "${gateway.id}":`, error); } } } } return Object.entries(allProviders).map(([id, provider]) => { return { id, name: provider.name, label: provider.label || provider.name, description: provider.description || "", envVar: provider.apiKeyEnvVar, connected: isProviderConnected(id, allProviders), docUrl: provider.docUrl, models: [...provider.models] }; }); } var GET_PROVIDERS_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "GET", path: "/agents/providers", responseType: "json", responseSchema: chunkQQCQV7ZF_cjs.providersResponseSchema, summary: "List AI providers", description: "Returns a list of all configured AI model providers", tags: ["Agents"], requiresAuth: true, requiresPermission: ["agents:read"], handler: async ({ mastra }) => { try { const providers = await buildProvidersList(mastra); return { providers }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error fetching providers"); } } }); var GENERATE_AGENT_VNEXT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/generate/vnext", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.generateResponseSchema, summary: "Generate a response from an agent", description: "Generate a response from an agent", tags: ["Agents"], requiresAuth: true, handler: GENERATE_AGENT_ROUTE.handler }); var STREAM_GENERATE_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/stream", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Stream agent response", description: "Executes an agent with the provided messages and streams the response in real-time", tags: ["Agents"], requiresAuth: true, requiresPermission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.AGENTS_EXECUTE, handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => { try { chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params; chunkRVD3DGBZ_cjs.validateBody({ messages }); const versionOptions = extractVersionOptions( serverRequestContext, bodyRequestContext ); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions, requestContext: serverRequestContext }); mergeBodyRequestContext(serverRequestContext, bodyRequestContext); stashVersionOverrides(serverRequestContext, versions); ensureDefaultVersionStatus(serverRequestContext, versionOptions); let authorizedMemoryOption = memoryOption; if (memoryOption) { const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id; const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, memoryOption.resource); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId); if (effectiveThreadId) { const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext }); if (memoryInstance) { const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId }); if (thread) { await chunkRVD3DGBZ_cjs.enforceThreadAccess({ mastra, requestContext: serverRequestContext, threadId: effectiveThreadId, thread, effectiveResourceId, permission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.MEMORY_WRITE }); } } } authorizedMemoryOption = { ...memoryOption, resource: effectiveResourceId ?? memoryOption.resource, thread: effectiveThreadId ?? memoryOption.thread }; } const { structuredOutput, untilIdle, ...restOptions } = rest; const options = { ...restOptions, requestContext: serverRequestContext, memory: authorizedMemoryOption, abortSignal }; if (untilIdle) { options.untilIdle = untilIdle; } const streamResult = structuredOutput ? await agent.stream(messages, { ...options, structuredOutput }) : await agent.stream(messages, options); return streamResult.fullStream; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error streaming agent response"); } } }); var sendAgentSignalResponseSchema = v4.z.object({ accepted: v4.z.literal(true), runId: v4.z.string(), signal: v4.z.any().optional() }); var sendAgentMessageResponseSchema = sendAgentSignalResponseSchema; var SEND_AGENT_SIGNAL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/signals", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.sendAgentSignalBodySchema, responseSchema: sendAgentSignalResponseSchema, summary: "Send agent signal", description: "Sends a signal to an active agent run or starts a memory thread run when the thread is idle", tags: ["Agents", "Streaming"], requiresAuth: true, requiresPermission: "agents:execute", handler: async ({ mastra, agentId, requestContext: serverRequestContext, signal, runId, resourceId, threadId, ifActive, ifIdle }) => { try { const idleStreamOptions = ifIdle?.streamOptions; const bodyRequestContext = idleStreamOptions?.requestContext; mergeBodyRequestContext(serverRequestContext, bodyRequestContext); const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions, requestContext: serverRequestContext }); stashVersionOverrides(serverRequestContext, idleStreamOptions?.versions); ensureDefaultVersionStatus(serverRequestContext, versionOptions); const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, resourceId); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, threadId); const ifIdleWithContext = { ifIdle: { ...ifIdle ?? {}, streamOptions: { ...idleStreamOptions ?? {}, requestContext: serverRequestContext } } }; if (effectiveThreadId && effectiveResourceId) { const memory = await agent.getMemory({ requestContext: serverRequestContext }); if (memory) { const thread = await memory.getThreadById({ threadId: effectiveThreadId }); await chunkRVD3DGBZ_cjs.validateThreadOwnership(thread, effectiveResourceId); } } if (typeof agent.sendSignal !== "function") { throw new chunk64ITUOXI_cjs.HTTPException(501, { message: "agent signals are not supported by this Mastra core version" }); } const agentSignal = signal; if (runId) { const result2 = await agent.sendSignal(agentSignal, { runId, ...effectiveResourceId ? { resourceId: effectiveResourceId } : {}, ...effectiveThreadId ? { threadId: effectiveThreadId } : {}, ...ifActive ? { ifActive } : {} }); return result2.signal === void 0 ? { accepted: result2.accepted, runId: result2.runId } : { accepted: result2.accepted, runId: result2.runId, signal: result2.signal }; } if (!effectiveResourceId || !effectiveThreadId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "resourceId and threadId are required when runId is not provided" }); } const result = await agent.sendSignal(agentSignal, { resourceId: effectiveResourceId, threadId: effectiveThreadId, ...ifActive ? { ifActive } : {}, ...ifIdleWithContext }); return result.signal === void 0 ? { accepted: result.accepted, runId: result.runId } : { accepted: result.accepted, runId: result.runId, signal: result.signal }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error sending agent signal"); } } }); async function handleAgentMessageRoute({ mastra, agentId, requestContext: serverRequestContext, message, runId, resourceId, threadId, ifActive, ifIdle, methodName }) { const idleStreamOptions = ifIdle?.streamOptions; const bodyRequestContext = idleStreamOptions?.requestContext; mergeBodyRequestContext(serverRequestContext, bodyRequestContext); const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions, requestContext: serverRequestContext }); stashVersionOverrides(serverRequestContext, idleStreamOptions?.versions); ensureDefaultVersionStatus(serverRequestContext, versionOptions); const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, resourceId); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, threadId); const ifIdleWithContext = { ifIdle: { ...ifIdle ?? {}, streamOptions: { ...idleStreamOptions ?? {}, requestContext: serverRequestContext } } }; if (effectiveThreadId && effectiveResourceId) { const memory = await agent.getMemory({ requestContext: serverRequestContext }); if (memory) { const thread = await memory.getThreadById({ threadId: effectiveThreadId }); await chunkRVD3DGBZ_cjs.validateThreadOwnership(thread, effectiveResourceId); } } if (typeof agent[methodName] !== "function") { throw new chunk64ITUOXI_cjs.HTTPException(501, { message: `agent ${methodName} is not supported by this Mastra core version` }); } if (runId) { const result2 = await agent[methodName](message, { runId, ...effectiveResourceId ? { resourceId: effectiveResourceId } : {}, ...effectiveThreadId ? { threadId: effectiveThreadId } : {}, ...ifActive ? { ifActive } : {} }); return result2.signal === void 0 ? { accepted: result2.accepted, runId: result2.runId } : { accepted: result2.accepted, runId: result2.runId, signal: result2.signal }; } if (!effectiveResourceId || !effectiveThreadId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "resourceId and threadId are required when runId is not provided" }); } const result = await agent[methodName](message, { resourceId: effectiveResourceId, threadId: effectiveThreadId, ...ifActive ? { ifActive } : {}, ...ifIdleWithContext }); return result.signal === void 0 ? { accepted: result.accepted, runId: result.runId } : { accepted: result.accepted, runId: result.runId, signal: result.signal }; } var SEND_AGENT_MESSAGE_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/send-message", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.sendAgentMessageBodySchema, responseSchema: sendAgentMessageResponseSchema, summary: "Send agent message", description: "Sends a user message to an active agent run or starts a memory thread run when the thread is idle", tags: ["Agents", "Streaming"], requiresAuth: true, requiresPermission: "agents:execute", handler: async (params) => { try { return await handleAgentMessageRoute({ ...params, methodName: "sendMessage" }); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error sending agent message"); } } }); var QUEUE_AGENT_MESSAGE_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/queue-message", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.queueAgentMessageBodySchema, responseSchema: sendAgentMessageResponseSchema, summary: "Queue agent message", description: "Queues a user message to run after the active thread run completes, or starts a memory thread run when idle", tags: ["Agents", "Streaming"], requiresAuth: true, requiresPermission: "agents:execute", handler: async (params) => { try { return await handleAgentMessageRoute({ ...params, methodName: "queueMessage" }); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error queueing agent message"); } } }); var ABORT_AGENT_THREAD_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/threads/abort", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.abortAgentThreadBodySchema, responseSchema: chunkQQCQV7ZF_cjs.abortAgentThreadResponseSchema, summary: "Abort active agent thread run", description: "Aborts the currently active stream run for a memory thread without changing thread subscriptions", tags: ["Agents", "Streaming"], requiresAuth: true, requiresPermission: "agents:execute", handler: async ({ mastra, agentId, resourceId, threadId, requestContext: serverRequestContext }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, requestContext: serverRequestContext }); if (typeof agent.abortThreadStream !== "function") { throw new chunk64ITUOXI_cjs.HTTPException(501, { message: "agent thread aborts are not supported by this Mastra core version" }); } const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, resourceId); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, threadId); if (!effectiveThreadId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "threadId is required" }); } if (effectiveResourceId) { const memory = await agent.getMemory({ requestContext: serverRequestContext }); if (memory) { const thread = await memory.getThreadById({ threadId: effectiveThreadId }); await chunkRVD3DGBZ_cjs.validateThreadOwnership(thread, effectiveResourceId); } } const aborted = await agent.abortThreadStream({ resourceId: effectiveResourceId, threadId: effectiveThreadId }); return { aborted }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error aborting agent thread"); } } }); var SUBSCRIBE_AGENT_THREAD_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/threads/subscribe", responseType: "stream", streamFormat: "sse", sseFlushOnConnect: true, pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.subscribeAgentThreadBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Subscribe to agent thread runs", description: "Subscribes to future and active stream runs for a memory thread", tags: ["Agents", "Streaming"], requiresAuth: true, requiresPermission: "agents:execute", handler: async ({ mastra, agentId, resourceId, threadId, abortSignal, requestContext: serverRequestContext }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, requestContext: serverRequestContext }); if (typeof agent.subscribeToThread !== "function") { throw new chunk64ITUOXI_cjs.HTTPException(501, { message: "agent thread subscriptions are not supported by this Mastra core version" }); } const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, resourceId); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, threadId); if (!effectiveThreadId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "threadId is required" }); } if (effectiveResourceId) { const memory = await agent.getMemory({ requestContext: serverRequestContext }); if (memory) { const thread = await memory.getThreadById({ threadId: effectiveThreadId }); await chunkRVD3DGBZ_cjs.validateThreadOwnership(thread, effectiveResourceId); } } const subscription = await agent.subscribeToThread({ resourceId: effectiveResourceId, threadId: effectiveThreadId }); let cleanedUp = false; let heartbeat; const clearHeartbeat = () => { if (heartbeat) { clearTimeout(heartbeat); heartbeat = void 0; } }; const cleanup = (closeController) => { if (cleanedUp) return; cleanedUp = true; clearHeartbeat(); subscription.unsubscribe(); if (closeController) { try { closeController.close(); } catch { } } }; return new ReadableStream({ async start(controller) { const scheduleHeartbeat = () => { if (cleanedUp) return; clearHeartbeat(); heartbeat = setTimeout(() => { heartbeat = void 0; if (cleanedUp) return; try { controller.enqueue(": heartbeat\n\n"); } catch { cleanup(); return; } scheduleHeartbeat(); }, 25e3); }; const abortCleanup = () => cleanup(controller); abortSignal?.addEventListener("abort", abortCleanup, { once: true }); scheduleHeartbeat(); try { for await (const part of subscription.stream) { controller.enqueue(part); scheduleHeartbeat(); } cleanup(controller); } catch (error) { cleanup(); controller.error(error); } finally { clearHeartbeat(); abortSignal?.removeEventListener("abort", abortCleanup); } }, cancel() { cleanup(); } }); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error subscribing to agent thread"); } } }); var STREAM_UNTIL_IDLE_GENERATE_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/stream-until-idle", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.streamUntilIdleBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Stream agent response until idle", description: "Executes an agent with the provided messages and streams the response in real-time, also listens for background task completions and streams them in real-time", tags: ["Agents"], requiresAuth: true, requiresPermission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.AGENTS_EXECUTE, handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => { try { chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params; chunkRVD3DGBZ_cjs.validateBody({ messages }); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions( serverRequestContext, bodyRequestContext ), requestContext: serverRequestContext }); mergeBodyRequestContext(serverRequestContext, bodyRequestContext); let authorizedMemoryOption = memoryOption; if (memoryOption) { const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id; const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, memoryOption.resource); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId); if (effectiveThreadId && effectiveResourceId) { const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext }); if (memoryInstance) { const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId }); await chunkRVD3DGBZ_cjs.validateThreadOwnership(thread, effectiveResourceId); } } authorizedMemoryOption = { ...memoryOption, resource: effectiveResourceId ?? memoryOption.resource, thread: effectiveThreadId ?? memoryOption.thread }; } const { structuredOutput, ...restOptions } = rest; const options = { ...restOptions, requestContext: serverRequestContext, memory: authorizedMemoryOption, abortSignal }; const streamResult = structuredOutput ? await agent.streamUntilIdle(messages, { ...options, structuredOutput }) : await agent.streamUntilIdle(messages, options); return streamResult.fullStream; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error streaming agent response"); } } }); var STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/stream/vnext", responseType: "stream", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Stream a response from an agent", description: "[DEPRECATED] This endpoint is deprecated. Please use /stream instead.", tags: ["Agents"], requiresAuth: true, deprecated: true, handler: STREAM_GENERATE_ROUTE.handler }); var OBSERVE_AGENT_STREAM_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/observe", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.observeAgentBodySchema, responseSchema: chunkQQCQV7ZF_cjs.observeAgentResponseSchema, summary: "Observe agent stream", description: "Reconnect to an existing agent stream to receive missed events. Supports position-based resume with offset for efficient reconnection.", tags: ["Agents", "Streaming"], requiresAuth: true, handler: async ({ mastra, agentId, runId, offset, abortSignal }) => { try { let cleanup2 = function(controller) { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } if (handleEvent) { void pubsub.unsubscribe(topic, handleEvent); handleEvent = null; } try { controller.close(); } catch { } }, resetIdleTimer2 = function(controller) { if (idleTimer) clearTimeout(idleTimer); idleTimer = setTimeout(() => cleanup2(controller), IDLE_TIMEOUT_MS); }; const agent$1 = await getAgentFromSystem({ mastra, agentId }); const agentPubsub = agent.isDurableAgentLike(agent$1) ? agent$1.pubsub : void 0; const pubsub = agentPubsub ?? mastra.pubsub; const topic = durable.AGENT_STREAM_TOPIC(runId); let handleEvent = null; let idleTimer = null; const IDLE_TIMEOUT_MS = 5 * 60 * 1e3; const stream = new ReadableStream({ start(controller) { if (abortSignal) { if (abortSignal.aborted) { cleanup2(controller); return; } abortSignal.addEventListener("abort", () => cleanup2(controller), { once: true }); } resetIdleTimer2(controller); handleEvent = (event) => { const isTerminal = event.type === "finish" || event.type === "error"; try { controller.enqueue(event); } catch { } if (isTerminal) { cleanup2(controller); } else { resetIdleTimer2(controller); } }; const subscribePromise = offset !== void 0 ? pubsub.subscribeFromOffset(topic, offset, handleEvent) : pubsub.subscribeWithReplay(topic, handleEvent); subscribePromise.catch((error) => { console.error(`[ObserveAgentStream] Failed to subscribe to ${topic}:`, error); if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } controller.error(error); }); }, cancel() { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } if (handleEvent) { void pubsub.unsubscribe(topic, handleEvent); handleEvent = null; } } }); return stream; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error observing agent stream"); } } }); var APPROVE_TOOL_CALL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/approve-tool-call", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.approveToolCallBodySchema, responseSchema: chunkQQCQV7ZF_cjs.toolCallResponseSchema, summary: "Approve tool call", description: "Approves a pending tool call and continues agent execution", tags: ["Agents", "Tools"], requiresAuth: true, handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } if (!params.toolCallId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Tool call id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const streamResult = await agent.approveToolCall({ ...params, requestContext, abortSignal }); return streamResult.fullStream; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error approving tool call"); } } }); async function validateSubscriptionToolCallThreadAccess({ agent, requestContext, resourceId, threadId }) { const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(requestContext, resourceId); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(requestContext, threadId); if (!effectiveThreadId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "threadId is required" }); } if (effectiveResourceId) { const memory = await agent.getMemory({ requestContext }); if (memory) { const thread = await memory.getThreadById({ threadId: effectiveThreadId }); await chunkRVD3DGBZ_cjs.validateThreadOwnership(thread, effectiveResourceId); } } return { effectiveResourceId: effectiveResourceId ?? "", effectiveThreadId }; } var SEND_TOOL_APPROVAL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/send-tool-approval", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.sendToolApprovalBodySchema, responseSchema: chunkQQCQV7ZF_cjs.sendToolApprovalResponseSchema, summary: "Send tool approval", description: "Approves or declines a pending tool call and publishes resumed chunks to thread subscribers", tags: ["Agents", "Tools"], requiresAuth: true, requiresPermission: "agents:execute", handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => { try { const bodyRequestContext = params.requestContext; const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions, requestContext: serverRequestContext }); if (!params.toolCallId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Tool call id is required" }); } mergeBodyRequestContext(serverRequestContext, bodyRequestContext); chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { effectiveResourceId, effectiveThreadId } = await validateSubscriptionToolCallThreadAccess({ agent, requestContext: serverRequestContext, resourceId: params.resourceId, threadId: params.threadId }); return await agent.sendToolApproval({ ...params, resourceId: effectiveResourceId, threadId: effectiveThreadId, requestContext: serverRequestContext, abortSignal }); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error sending tool approval"); } } }); var DECLINE_TOOL_CALL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/decline-tool-call", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.declineToolCallBodySchema, responseSchema: chunkQQCQV7ZF_cjs.toolCallResponseSchema, summary: "Decline tool call", description: "Declines a pending tool call and continues agent execution without executing the tool", tags: ["Agents", "Tools"], requiresAuth: true, handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } if (!params.toolCallId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Tool call id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const streamResult = await agent.declineToolCall({ ...params, requestContext, abortSignal }); return streamResult.fullStream; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error declining tool call"); } } }); var RESUME_STREAM_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/resume-stream", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.resumeStreamBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Resume agent stream", description: "Resumes a suspended agent stream with custom resume data", tags: ["Agents"], requiresAuth: true, requiresPermission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.AGENTS_EXECUTE, handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => { try { if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { resumeData, runId, toolCallId, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params; const versionOptions = extractVersionOptions( serverRequestContext, bodyRequestContext ); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions }); mergeBodyRequestContext(serverRequestContext, bodyRequestContext); stashVersionOverrides(serverRequestContext, versions); ensureDefaultVersionStatus(serverRequestContext, versionOptions); let authorizedMemoryOption = memoryOption; const clientThreadId = typeof memoryOption?.thread === "string" ? memoryOption.thread : memoryOption?.thread?.id; const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, memoryOption?.resource); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId); if (effectiveThreadId) { const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext }); if (memoryInstance) { const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId }); if (thread) { await chunkRVD3DGBZ_cjs.enforceThreadAccess({ mastra, requestContext: serverRequestContext, threadId: effectiveThreadId, thread, effectiveResourceId, permission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.MEMORY_WRITE }); } } } if (memoryOption || effectiveResourceId || effectiveThreadId) { authorizedMemoryOption = { ...memoryOption, ...effectiveResourceId ? { resource: effectiveResourceId } : {}, ...effectiveThreadId ? { thread: effectiveThreadId } : {} }; } const workflowsStore = await mastra.getStorage()?.getStore("workflows"); const workflowRun = await workflowsStore?.getWorkflowRunById({ workflowName: "agentic-loop", runId }); await chunkRVD3DGBZ_cjs.validateRunOwnership(workflowRun, chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, void 0)); const { structuredOutput, untilIdle, ...restOptions } = rest; const options = { runId, toolCallId, ...restOptions, requestContext: serverRequestContext, memory: authorizedMemoryOption, abortSignal }; if (untilIdle) { options.untilIdle = untilIdle; } const streamResult = structuredOutput ? await agent.resumeStream(resumeData, { ...options, structuredOutput }) : await agent.resumeStream(resumeData, options); return streamResult.fullStream; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error resuming agent stream"); } } }); var RESUME_STREAM_UNTIL_IDLE_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/resume-stream-until-idle", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.resumeStreamUntilIdleBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Resume agent stream until idle", description: "Resumes a suspended agent stream until idle with custom resume data, also listens for background task completions and streams them in real-time", tags: ["Agents"], requiresAuth: true, requiresPermission: "agents:execute", handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => { try { if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const { resumeData, runId, toolCallId, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params; const versionOptions = extractVersionOptions( serverRequestContext, bodyRequestContext ); const agent = await getAgentFromSystem({ mastra, agentId, versionOptions }); if (bodyRequestContext && typeof bodyRequestContext === "object") { for (const [key, value] of Object.entries(bodyRequestContext)) { if (serverRequestContext.get(key) === void 0) { serverRequestContext.set(key, value); } } } stashVersionOverrides(serverRequestContext, versions); ensureDefaultVersionStatus(serverRequestContext, versionOptions); let authorizedMemoryOption = memoryOption; const clientThreadId = typeof memoryOption?.thread === "string" ? memoryOption.thread : memoryOption?.thread?.id; const effectiveResourceId = chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, memoryOption?.resource); const effectiveThreadId = chunkRVD3DGBZ_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId); if (effectiveThreadId) { const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext }); if (memoryInstance) { const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId }); if (thread) { await chunkRVD3DGBZ_cjs.enforceThreadAccess({ mastra, requestContext: serverRequestContext, threadId: effectiveThreadId, thread, effectiveResourceId, permission: chunkRVD3DGBZ_cjs.MastraFGAPermissions.MEMORY_WRITE }); } } } if (memoryOption || effectiveResourceId || effectiveThreadId) { authorizedMemoryOption = { ...memoryOption, ...effectiveResourceId ? { resource: effectiveResourceId } : {}, ...effectiveThreadId ? { thread: effectiveThreadId } : {} }; } const workflowsStore = await mastra.getStorage()?.getStore("workflows"); const workflowRun = await workflowsStore?.getWorkflowRunById({ workflowName: "agentic-loop", runId }); await chunkRVD3DGBZ_cjs.validateRunOwnership(workflowRun, chunkRVD3DGBZ_cjs.getEffectiveResourceId(serverRequestContext, void 0)); const { structuredOutput, ...restOptions } = rest; const options = { runId, toolCallId, ...restOptions, requestContext: serverRequestContext, memory: authorizedMemoryOption, abortSignal }; const streamResult = structuredOutput ? await agent.resumeStreamUntilIdle(resumeData, { ...options, structuredOutput }) : await agent.resumeStreamUntilIdle(resumeData, options); return streamResult.fullStream; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error resuming agent stream"); } } }); var APPROVE_TOOL_CALL_GENERATE_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/approve-tool-call-generate", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.approveToolCallBodySchema, responseSchema: chunkQQCQV7ZF_cjs.generateResponseSchema, summary: "Approve tool call (non-streaming)", description: "Approves a pending tool call and returns the complete response", tags: ["Agents", "Tools"], requiresAuth: true, handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } if (!params.toolCallId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Tool call id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const result = await agent.approveToolCallGenerate({ ...params, requestContext, abortSignal }); return result; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error approving tool call"); } } }); var DECLINE_TOOL_CALL_GENERATE_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/decline-tool-call-generate", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.declineToolCallBodySchema, responseSchema: chunkQQCQV7ZF_cjs.generateResponseSchema, summary: "Decline tool call (non-streaming)", description: "Declines a pending tool call and returns the complete response", tags: ["Agents", "Tools"], requiresAuth: true, handler: async ({ mastra, agentId, abortSignal, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } if (!params.toolCallId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Tool call id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const result = await agent.declineToolCallGenerate({ ...params, requestContext, abortSignal }); return result; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error declining tool call"); } } }); var STREAM_NETWORK_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/network", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Stream agent network", description: "Executes an agent network with multiple agents and streams the response", tags: ["Agents"], requiresAuth: true, handler: async ({ mastra, messages, agentId, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); chunkRVD3DGBZ_cjs.validateBody({ messages }); const streamResult = await agent.network(messages, { ...params }); return streamResult; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error streaming agent loop response"); } } }); var APPROVE_NETWORK_TOOL_CALL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/approve-network-tool-call", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.approveNetworkToolCallBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Approve network tool call", description: "Approves a pending network tool call and continues network agent execution", tags: ["Agents", "Tools"], requiresAuth: true, handler: async ({ mastra, agentId, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const streamResult = await agent.approveNetworkToolCall({ ...params }); return streamResult; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error approving network tool call"); } } }); var DECLINE_NETWORK_TOOL_CALL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/decline-network-tool-call", responseType: "stream", streamFormat: "sse", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.declineNetworkToolCallBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Decline network tool call", description: "Declines a pending network tool call and continues network agent execution without executing the tool", tags: ["Agents", "Tools"], requiresAuth: true, handler: async ({ mastra, agentId, requestContext, ...params }) => { try { const agent = await getAgentFromSystem({ mastra, agentId, versionOptions: extractVersionOptions(requestContext) }); if (!params.runId) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" }); } chunkRVD3DGBZ_cjs.sanitizeBody(params, ["tools"]); const streamResult = await agent.declineNetworkToolCall({ ...params }); return streamResult; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error declining network tool call"); } } }); var UPDATE_AGENT_MODEL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/model", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.updateAgentModelBodySchema, responseSchema: chunkQQCQV7ZF_cjs.modelManagementResponseSchema, summary: "Update agent model", description: "Updates the AI model used by the agent", tags: ["Agents", "Models"], requiresAuth: true, handler: async ({ mastra, agentId, modelId, provider }) => { try { const agent = await getAgentFromSystem({ mastra, agentId }); const newModel = `${provider}/${modelId}`; agent.__updateModel({ model: newModel }); return { message: "Agent model updated" }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error updating agent model"); } } }); var RESET_AGENT_MODEL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/model/reset", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, responseSchema: chunkQQCQV7ZF_cjs.modelManagementResponseSchema, summary: "Reset agent model", description: "Resets the agent model to its original configuration", tags: ["Agents", "Models"], requiresAuth: true, handler: async ({ mastra, agentId }) => { try { const agent = await getAgentFromSystem({ mastra, agentId }); agent.__resetToOriginalModel(); return { message: "Agent model reset to original" }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error resetting agent model"); } } }); var REORDER_AGENT_MODEL_LIST_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/models/reorder", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.reorderAgentModelListBodySchema, responseSchema: chunkQQCQV7ZF_cjs.modelManagementResponseSchema, summary: "Reorder agent model list", description: "Reorders the model list for agents with multiple model configurations", tags: ["Agents", "Models"], requiresAuth: true, handler: async ({ mastra, agentId, reorderedModelIds }) => { try { const agent = await getAgentFromSystem({ mastra, agentId }); const modelList = await agent.getModelList(); if (!modelList || modelList.length === 0) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Agent model list is not found or empty" }); } agent.reorderModels(reorderedModelIds); return { message: "Model list reordered" }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error reordering model list"); } } }); var UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/models/:modelConfigId", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.modelConfigIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.updateAgentModelInModelListBodySchema, responseSchema: chunkQQCQV7ZF_cjs.modelManagementResponseSchema, summary: "Update model in model list", description: "Updates a specific model configuration in the agent model list", tags: ["Agents", "Models"], requiresAuth: true, handler: async ({ mastra, agentId, modelConfigId, model: bodyModel, maxRetries, enabled }) => { try { const agent = await getAgentFromSystem({ mastra, agentId }); const modelList = await agent.getModelList(); if (!modelList || modelList.length === 0) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Agent model list is not found or empty" }); } const modelConfig = modelList.find((config) => config.id === modelConfigId); if (!modelConfig) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Model config with id ${modelConfigId} not found` }); } const newModel = bodyModel?.modelId && bodyModel?.provider ? `${bodyModel.provider}/${bodyModel.modelId}` : modelConfig.model; const updated = { ...modelConfig, model: newModel, ...maxRetries !== void 0 ? { maxRetries } : {}, ...enabled !== void 0 ? { enabled } : {} }; agent.updateModelInModelList(updated); return { message: "Model updated in model list" }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error updating model in model list"); } } }); var ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS = `You are an expert system prompt engineer, specialized in analyzing and enhancing instructions to create clear, effective, and comprehensive system prompts. Your goal is to help users transform their basic instructions into well-structured system prompts that will guide AI behavior effectively. Follow these steps to analyze and enhance the instructions: 1. ANALYSIS PHASE - Identify the core purpose and goals - Extract key constraints and requirements - Recognize domain-specific terminology and concepts - Note any implicit assumptions that should be made explicit 2. PROMPT STRUCTURE Create a system prompt with these components: a) ROLE DEFINITION - Clear statement of the AI's role and purpose - Key responsibilities and scope - Primary stakeholders and users b) CORE CAPABILITIES - Main functions and abilities - Specific domain knowledge required - Tools and resources available c) BEHAVIORAL GUIDELINES - Communication style and tone - Decision-making framework - Error handling approach - Ethical considerations d) CONSTRAINTS & BOUNDARIES - Explicit limitations - Out-of-scope activities - Security and privacy considerations e) SUCCESS CRITERIA - Quality standards - Expected outcomes - Performance metrics 3. QUALITY CHECKS Ensure the prompt is: - Clear and unambiguous - Comprehensive yet concise - Properly scoped - Technically accurate - Ethically sound 4. OUTPUT FORMAT Return your response as JSON with exactly these two fields: - explanation: A brief explanation of the changes you made and why - new_prompt: The complete enhanced system prompt as a single string Remember: A good system prompt should be specific enough to guide behavior but flexible enough to handle edge cases. Focus on creating prompts that are clear, actionable, and aligned with the intended use case.`; async function findConnectedModel(agent) { const modelList = await agent.getModelList(); if (modelList && modelList.length > 0) { for (const modelConfig of modelList) { if (modelConfig.enabled !== false) { const model = modelConfig.model; if (isProviderConnected(model.provider)) { return model; } } } return null; } const defaultModel = await agent.getModel(); if (isProviderConnected(defaultModel.provider)) { return defaultModel; } return null; } var ENHANCE_INSTRUCTIONS_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/instructions/enhance", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.enhanceInstructionsBodySchema, responseSchema: chunkQQCQV7ZF_cjs.enhanceInstructionsResponseSchema, summary: "Enhance agent instructions", description: "Uses AI to enhance or modify agent instructions based on user feedback", tags: ["Agents"], requiresAuth: true, handler: async ({ mastra, agentId, instructions, comment }) => { try { const agent$1 = await getAgentFromSystem({ mastra, agentId }); const model = await findConnectedModel(agent$1); if (!model) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "No model with a configured API key found. Please set the required environment variable for your model provider." }); } const systemPromptAgent = new agent.Agent({ id: "system-prompt-enhancer", name: "system-prompt-enhancer", instructions: ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS, model }); const result = await systemPromptAgent.generate( `We need to improve the system prompt. Current: ${instructions} ${comment ? `User feedback: ${comment}` : ""}`, { structuredOutput: { schema: chunkQQCQV7ZF_cjs.enhanceInstructionsResponseSchema } } ); return await result.object; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error enhancing instructions"); } } }); var STREAM_VNEXT_DEPRECATED_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/streamVNext", responseType: "stream", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Stream a response from an agent", description: "[DEPRECATED] This endpoint is deprecated. Please use /stream instead.", tags: ["Agents"], requiresAuth: true, deprecated: true, handler: async () => { throw new chunk64ITUOXI_cjs.HTTPException(410, { message: "This endpoint is deprecated. Please use /stream instead." }); } }); var STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/stream/vnext/ui", responseType: "stream", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Stream UI messages from an agent", description: "[DEPRECATED] This endpoint is deprecated. Please use the @mastra/ai-sdk package for uiMessage transformations", tags: ["Agents"], requiresAuth: true, deprecated: true, handler: async () => { try { throw new error.MastraError({ category: error.ErrorCategory.USER, domain: error.ErrorDomain.MASTRA_SERVER, id: "DEPRECATED_ENDPOINT", text: "This endpoint is deprecated. Please use the @mastra/ai-sdk package to for uiMessage transformations" }); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "error streaming agent response"); } } }); var STREAM_UI_MESSAGE_DEPRECATED_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/agents/:agentId/stream/ui", responseType: "stream", pathParamSchema: chunkQQCQV7ZF_cjs.agentIdPathParams, bodySchema: chunkQQCQV7ZF_cjs.agentExecutionBodySchema, responseSchema: chunkQQCQV7ZF_cjs.streamResponseSchema, summary: "Stream UI messages from an agent", description: "[DEPRECATED] This endpoint is deprecated. Please use the @mastra/ai-sdk package for uiMessage transformations", tags: ["Agents"], requiresAuth: true, deprecated: true, handler: STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE.handler }); var GET_AGENT_SKILL_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "GET", path: "/agents/:agentId/skills/:skillName", responseType: "json", pathParamSchema: chunkQQCQV7ZF_cjs.agentSkillPathParams, queryParamSchema: chunkHXICAUTW_cjs.skillDisambiguationQuerySchema, responseSchema: chunkHXICAUTW_cjs.getAgentSkillResponseSchema, summary: "Get agent skill", description: "Returns details for a specific skill available to the agent via its workspace", tags: ["Agents", "Skills"], handler: async ({ mastra, agentId, skillName, path, requestContext }) => { try { const agent = agentId ? mastra.getAgentById(agentId) : null; if (!agent) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Agent not found" }); } const workspace = await agent.getWorkspace({ requestContext }); if (!workspace?.skills) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Agent does not have skills configured" }); } const identifier = path ? decodeURIComponent(path) : skillName; const skill = await workspace.skills.get(identifier); if (!skill) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Skill "${identifier}" not found` }); } return { name: skill.name, description: skill.description, license: skill.license, compatibility: skill.compatibility, metadata: skill.metadata, path: skill.path, instructions: skill.instructions, source: skill.source, references: skill.references, scripts: skill.scripts, assets: skill.assets }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error getting agent skill"); } } }); exports.ABORT_AGENT_THREAD_ROUTE = ABORT_AGENT_THREAD_ROUTE; exports.APPROVE_NETWORK_TOOL_CALL_ROUTE = APPROVE_NETWORK_TOOL_CALL_ROUTE; exports.APPROVE_TOOL_CALL_GENERATE_ROUTE = APPROVE_TOOL_CALL_GENERATE_ROUTE; exports.APPROVE_TOOL_CALL_ROUTE = APPROVE_TOOL_CALL_ROUTE; exports.CLONE_AGENT_ROUTE = CLONE_AGENT_ROUTE; exports.DECLINE_NETWORK_TOOL_CALL_ROUTE = DECLINE_NETWORK_TOOL_CALL_ROUTE; exports.DECLINE_TOOL_CALL_GENERATE_ROUTE = DECLINE_TOOL_CALL_GENERATE_ROUTE; exports.DECLINE_TOOL_CALL_ROUTE = DECLINE_TOOL_CALL_ROUTE; exports.ENHANCE_INSTRUCTIONS_ROUTE = ENHANCE_INSTRUCTIONS_ROUTE; exports.GENERATE_AGENT_ROUTE = GENERATE_AGENT_ROUTE; exports.GENERATE_AGENT_VNEXT_ROUTE = GENERATE_AGENT_VNEXT_ROUTE; exports.GENERATE_LEGACY_ROUTE = GENERATE_LEGACY_ROUTE; exports.GET_AGENT_BY_ID_ROUTE = GET_AGENT_BY_ID_ROUTE; exports.GET_AGENT_SKILL_ROUTE = GET_AGENT_SKILL_ROUTE; exports.GET_PROVIDERS_ROUTE = GET_PROVIDERS_ROUTE; exports.LIST_AGENTS_ROUTE = LIST_AGENTS_ROUTE; exports.OBSERVE_AGENT_STREAM_ROUTE = OBSERVE_AGENT_STREAM_ROUTE; exports.QUEUE_AGENT_MESSAGE_ROUTE = QUEUE_AGENT_MESSAGE_ROUTE; exports.REORDER_AGENT_MODEL_LIST_ROUTE = REORDER_AGENT_MODEL_LIST_ROUTE; exports.RESET_AGENT_MODEL_ROUTE = RESET_AGENT_MODEL_ROUTE; exports.RESUME_STREAM_ROUTE = RESUME_STREAM_ROUTE; exports.RESUME_STREAM_UNTIL_IDLE_ROUTE = RESUME_STREAM_UNTIL_IDLE_ROUTE; exports.SEND_AGENT_MESSAGE_ROUTE = SEND_AGENT_MESSAGE_ROUTE; exports.SEND_AGENT_SIGNAL_ROUTE = SEND_AGENT_SIGNAL_ROUTE; exports.SEND_TOOL_APPROVAL_ROUTE = SEND_TOOL_APPROVAL_ROUTE; exports.STREAM_GENERATE_LEGACY_ROUTE = STREAM_GENERATE_LEGACY_ROUTE; exports.STREAM_GENERATE_ROUTE = STREAM_GENERATE_ROUTE; exports.STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE = STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE; exports.STREAM_NETWORK_ROUTE = STREAM_NETWORK_ROUTE; exports.STREAM_UI_MESSAGE_DEPRECATED_ROUTE = STREAM_UI_MESSAGE_DEPRECATED_ROUTE; exports.STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE = STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE; exports.STREAM_UNTIL_IDLE_GENERATE_ROUTE = STREAM_UNTIL_IDLE_GENERATE_ROUTE; exports.STREAM_VNEXT_DEPRECATED_ROUTE = STREAM_VNEXT_DEPRECATED_ROUTE; exports.SUBSCRIBE_AGENT_THREAD_ROUTE = SUBSCRIBE_AGENT_THREAD_ROUTE; exports.UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE = UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE; exports.UPDATE_AGENT_MODEL_ROUTE = UPDATE_AGENT_MODEL_ROUTE; exports.agents_exports = agents_exports; exports.buildProvidersList = buildProvidersList; exports.extractVersionOptions = extractVersionOptions; exports.getAgentFromSystem = getAgentFromSystem; exports.getBrowserToolsFromAgent = getBrowserToolsFromAgent; exports.getSerializedAgentTools = getSerializedAgentTools; exports.getSerializedProcessors = getSerializedProcessors; exports.getSerializedSkillsFromAgent = getSerializedSkillsFromAgent; exports.getWorkspaceToolsFromAgent = getWorkspaceToolsFromAgent; exports.isProviderConnected = isProviderConnected; //# sourceMappingURL=chunk-DZD7RZYY.cjs.map //# sourceMappingURL=chunk-DZD7RZYY.cjs.map