import { getAgentSkillResponseSchema } from './chunk-XQJJ5GYN.js';
import { listAgentsResponseSchema, serializedAgentSchema, agentIdPathParams, generateResponseSchema, agentExecutionBodySchema, agentExecutionLegacyBodySchema, streamResponseSchema, providersResponseSchema, toolCallResponseSchema, approveToolCallBodySchema, declineToolCallBodySchema, approveNetworkToolCallBodySchema, declineNetworkToolCallBodySchema, modelManagementResponseSchema, updateAgentModelBodySchema, reorderAgentModelListBodySchema, updateAgentModelInModelListBodySchema, modelConfigIdPathParams, enhanceInstructionsResponseSchema, enhanceInstructionsBodySchema, agentSkillPathParams } from './chunk-HXRJMA6T.js';
import { stringify, toSlug } from './chunk-LII44FTI.js';
import { sanitizeBody, validateBody, getEffectiveResourceId, getEffectiveThreadId, validateThreadOwnership } from './chunk-USR6JK77.js';
import { createStoredAgentResponseSchema } from './chunk-DV66UYBZ.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-OQ5GQJAS.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { Agent } from '@mastra/core/agent';
import { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';
import { PROVIDER_REGISTRY } from '@mastra/core/llm';
import { zodToJsonSchema } from '@mastra/core/utils/zod-to-json';
import { z } from 'zod';

// src/server/handlers/agents.ts
var agents_exports = {};
__export(agents_exports, {
  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,
  REORDER_AGENT_MODEL_LIST_ROUTE: () => REORDER_AGENT_MODEL_LIST_ROUTE,
  RESET_AGENT_MODEL_ROUTE: () => RESET_AGENT_MODEL_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_VNEXT_DEPRECATED_ROUTE: () => STREAM_VNEXT_DEPRECATED_ROUTE,
  UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE: () => UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE,
  UPDATE_AGENT_MODEL_ROUTE: () => UPDATE_AGENT_MODEL_ROUTE,
  getAgentFromSystem: () => getAgentFromSystem,
  getSerializedAgentTools: () => getSerializedAgentTools,
  getSerializedProcessors: () => getSerializedProcessors,
  getSerializedSkillsFromAgent: () => getSerializedSkillsFromAgent,
  getWorkspaceToolsFromAgent: () => getWorkspaceToolsFromAgent,
  isProviderConnected: () => isProviderConnected
});

// src/server/constants.ts
var WORKSPACE_TOOLS_PREFIX = "mastra_workspace";
var WORKSPACE_TOOLS = {
  FILESYSTEM: {
    READ_FILE: `${WORKSPACE_TOOLS_PREFIX}_read_file`,
    WRITE_FILE: `${WORKSPACE_TOOLS_PREFIX}_write_file`,
    EDIT_FILE: `${WORKSPACE_TOOLS_PREFIX}_edit_file`,
    LIST_FILES: `${WORKSPACE_TOOLS_PREFIX}_list_files`,
    DELETE: `${WORKSPACE_TOOLS_PREFIX}_delete`,
    FILE_STAT: `${WORKSPACE_TOOLS_PREFIX}_file_stat`,
    MKDIR: `${WORKSPACE_TOOLS_PREFIX}_mkdir`
  },
  SANDBOX: {
    EXECUTE_COMMAND: `${WORKSPACE_TOOLS_PREFIX}_execute_command`
  },
  SEARCH: {
    SEARCH: `${WORKSPACE_TOOLS_PREFIX}_search`,
    INDEX: `${WORKSPACE_TOOLS_PREFIX}_index`
  }
};
function resolveToolConfig(toolsConfig, toolName) {
  let enabled = true;
  let requireApproval = false;
  let requireReadBeforeWrite;
  if (toolsConfig) {
    if (toolsConfig.enabled !== void 0) {
      enabled = toolsConfig.enabled;
    }
    if (toolsConfig.requireApproval !== void 0) {
      requireApproval = toolsConfig.requireApproval;
    }
    const perToolConfig = toolsConfig[toolName];
    if (perToolConfig) {
      if (perToolConfig.enabled !== void 0) {
        enabled = perToolConfig.enabled;
      }
      if (perToolConfig.requireApproval !== void 0) {
        requireApproval = perToolConfig.requireApproval;
      }
      if (perToolConfig.requireReadBeforeWrite !== void 0) {
        requireReadBeforeWrite = perToolConfig.requireReadBeforeWrite;
      }
    }
  }
  return { enabled, requireApproval, requireReadBeforeWrite };
}

// src/server/handlers/agents.ts
function isProviderConnected(providerId) {
  const cleanId = providerId.includes(".") ? providerId.split(".")[0] : providerId;
  let provider = PROVIDER_REGISTRY[cleanId];
  if (!provider && !cleanId.includes("/")) {
    const registryKeys = Object.keys(PROVIDER_REGISTRY);
    const matchingKey = registryKeys.find((key) => {
      const parts = key.split("/");
      return parts.length === 2 && parts[1] === cleanId;
    });
    if (matchingKey) {
      provider = PROVIDER_REGISTRY[matchingKey];
    }
  }
  if (!provider) return false;
  const envVars = Array.isArray(provider.apiKeyEnvVar) ? provider.apiKeyEnvVar : [provider.apiKeyEnvVar];
  return envVars.every((envVar) => !!process.env[envVar]);
}
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 {
        if (tool.inputSchema) {
          if (tool.inputSchema && typeof tool.inputSchema === "object" && "jsonSchema" in tool.inputSchema) {
            inputSchemaForReturn = stringify(tool.inputSchema.jsonSchema);
          } else if (typeof tool.inputSchema === "function") {
            const inputSchema = tool.inputSchema();
            if (inputSchema && inputSchema.jsonSchema) {
              inputSchemaForReturn = stringify(inputSchema.jsonSchema);
            }
          } else if (tool.inputSchema) {
            inputSchemaForReturn = stringify(
              zodToJsonSchema(tool.inputSchema)
            );
          }
        }
        if (tool.outputSchema) {
          if (tool.outputSchema && typeof tool.outputSchema === "object" && "jsonSchema" in tool.outputSchema) {
            outputSchemaForReturn = stringify(tool.outputSchema.jsonSchema);
          } else if (typeof tool.outputSchema === "function") {
            const outputSchema = tool.outputSchema();
            if (outputSchema && outputSchema.jsonSchema) {
              outputSchemaForReturn = stringify(outputSchema.jsonSchema);
            }
          } else if (tool.outputSchema) {
            outputSchemaForReturn = stringify(
              zodToJsonSchema(tool.outputSchema)
            );
          }
        }
        if (tool.requestContextSchema) {
          if (tool.requestContextSchema && typeof tool.requestContextSchema === "object" && "jsonSchema" in tool.requestContextSchema) {
            requestContextSchemaForReturn = stringify(tool.requestContextSchema.jsonSchema);
          } else if (typeof tool.requestContextSchema === "function") {
            const requestContextSchema = tool.requestContextSchema();
            if (requestContextSchema && requestContextSchema.jsonSchema) {
              requestContextSchemaForReturn = stringify(requestContextSchema.jsonSchema);
            }
          } else if (tool.requestContextSchema) {
            requestContextSchemaForReturn = stringify(
              zodToJsonSchema(tool.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
    }));
  } catch {
    return [];
  }
}
async function getWorkspaceToolsFromAgent(agent, requestContext) {
  try {
    const workspace = await agent.getWorkspace({ requestContext });
    if (!workspace) {
      return [];
    }
    const tools = [];
    const isReadOnly = workspace.filesystem?.readOnly ?? false;
    const toolsConfig = workspace.getToolsConfig();
    const isEnabled = (toolName) => {
      return resolveToolConfig(toolsConfig, toolName).enabled;
    };
    if (workspace.filesystem) {
      if (isEnabled(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE)) {
        tools.push(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE);
      }
      if (isEnabled(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES)) {
        tools.push(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES);
      }
      if (isEnabled(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT)) {
        tools.push(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT);
      }
      if (!isReadOnly) {
        if (isEnabled(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE);
        }
        if (isEnabled(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE);
        }
        if (isEnabled(WORKSPACE_TOOLS.FILESYSTEM.DELETE)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.DELETE);
        }
        if (isEnabled(WORKSPACE_TOOLS.FILESYSTEM.MKDIR)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.MKDIR);
        }
      }
    }
    if (workspace.canBM25 || workspace.canVector) {
      if (isEnabled(WORKSPACE_TOOLS.SEARCH.SEARCH)) {
        tools.push(WORKSPACE_TOOLS.SEARCH.SEARCH);
      }
      if (!isReadOnly && isEnabled(WORKSPACE_TOOLS.SEARCH.INDEX)) {
        tools.push(WORKSPACE_TOOLS.SEARCH.INDEX);
      }
    }
    if (workspace.sandbox) {
      if (workspace.sandbox.executeCommand && isEnabled(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND)) {
        tools.push(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND);
      }
    }
    return tools;
  } catch {
    return [];
  }
}
async function getSerializedAgentDefinition({
  agent,
  requestContext
}) {
  let serializedAgentAgents = {};
  if ("listAgents" in agent) {
    const agents = await agent.listAgents({ requestContext });
    serializedAgentAgents = Object.entries(agents || {}).reduce(
      (acc, [key, agent2]) => {
        return {
          ...acc,
          [key]: { id: agent2.id, name: agent2.name }
        };
      },
      {}
    );
  }
  return serializedAgentAgents;
}
async function formatAgentList({
  id,
  mastra,
  agent,
  requestContext,
  partial = false
}) {
  const description = agent.getDescription();
  const instructions = await agent.getInstructions({ requestContext });
  const tools = await agent.listTools({ requestContext });
  const llm = await agent.getLLM({ requestContext });
  const defaultGenerateOptionsLegacy = await agent.getDefaultGenerateOptionsLegacy({ requestContext });
  const defaultStreamOptionsLegacy = await agent.getDefaultStreamOptionsLegacy({ requestContext });
  const defaultOptions = await agent.getDefaultOptions({ requestContext });
  const serializedAgentTools = await getSerializedAgentTools(tools, partial);
  let serializedAgentWorkflows = {};
  const logger = mastra.getLogger();
  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 });
  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);
  let workspaceId;
  try {
    const workspace = await agent.getWorkspace({ requestContext });
    workspaceId = workspace?.id;
  } catch {
  }
  const model = llm?.getModel();
  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
    }
  }));
  let serializedRequestContextSchema;
  if (agent.requestContextSchema) {
    try {
      serializedRequestContextSchema = stringify(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,
    instructions,
    agents: serializedAgentAgents,
    tools: serializedAgentTools,
    workflows: serializedAgentWorkflows,
    skills: serializedSkills,
    workspaceTools,
    workspaceId,
    inputProcessors: serializedInputProcessors,
    outputProcessors: serializedOutputProcessors,
    provider: llm?.getProvider(),
    modelId: llm?.getModelId(),
    modelVersion: model?.specificationVersion,
    defaultOptions,
    modelList,
    defaultGenerateOptionsLegacy,
    defaultStreamOptionsLegacy,
    requestContextSchema: serializedRequestContextSchema,
    source: agent.source ?? "code"
  };
}
async function getAgentFromSystem({ mastra, agentId }) {
  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 ${agentId} not found, looking through sub-agents`);
    const agents = mastra.listAgents();
    if (Object.keys(agents || {}).length) {
      for (const [_, ag] of Object.entries(agents)) {
        try {
          const subAgents = await ag.listAgents();
          if (subAgents[agentId]) {
            agent = subAgents[agentId];
            break;
          }
        } catch (error) {
          logger.debug("Error getting agent from agent", error);
        }
      }
    }
  }
  if (!agent) {
    logger.debug(`Agent ${agentId} not found in code-defined agents, looking in stored agents`);
    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;
}
async function formatAgent({
  mastra,
  agent,
  requestContext,
  isStudio
}) {
  const description = agent.getDescription();
  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 });
    }
  }
  let proxyRequestContext = requestContext;
  const instructions = await agent.getInstructions({ requestContext: proxyRequestContext });
  const llm = await agent.getLLM({ requestContext });
  const defaultGenerateOptionsLegacy = await agent.getDefaultGenerateOptionsLegacy({
    requestContext: proxyRequestContext
  });
  const defaultStreamOptionsLegacy = await agent.getDefaultStreamOptionsLegacy({ requestContext: proxyRequestContext });
  const defaultOptions = await agent.getDefaultOptions({ requestContext: proxyRequestContext });
  const model = llm?.getModel();
  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: proxyRequestContext });
  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, proxyRequestContext);
  const workspaceTools = await getWorkspaceToolsFromAgent(agent, proxyRequestContext);
  let workspaceId;
  try {
    const workspace = await agent.getWorkspace({ requestContext: proxyRequestContext });
    workspaceId = workspace?.id;
  } catch {
  }
  let serializedRequestContextSchema;
  if (agent.requestContextSchema) {
    try {
      serializedRequestContextSchema = stringify(zodToJsonSchema(agent.requestContextSchema));
    } catch (error) {
      mastra.getLogger().error("Error serializing requestContextSchema for agent", { agentName: agent.name, error });
    }
  }
  return {
    name: agent.name,
    description,
    instructions,
    tools: serializedAgentTools,
    agents: serializedAgentAgents,
    workflows: serializedAgentWorkflows,
    skills: serializedSkills,
    workspaceTools,
    workspaceId,
    inputProcessors: serializedInputProcessors,
    outputProcessors: serializedOutputProcessors,
    provider: llm?.getProvider(),
    modelId: llm?.getModelId(),
    modelVersion: model?.specificationVersion,
    modelList,
    defaultOptions,
    defaultGenerateOptionsLegacy,
    defaultStreamOptionsLegacy,
    requestContextSchema: serializedRequestContextSchema,
    source: agent.source ?? "code"
  };
}
var LIST_AGENTS_ROUTE = createRoute({
  method: "GET",
  path: "/agents",
  responseType: "json",
  queryParamSchema: z.object({
    partial: z.string().optional()
  }),
  responseSchema: 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: "agents:read",
  handler: async ({ mastra, requestContext, partial }) => {
    try {
      const codeAgents = mastra.listAgents();
      const isPartial = partial === "true";
      const serializedCodeAgentsMap = await Promise.all(
        Object.entries(codeAgents).map(async ([id, agent]) => {
          return formatAgentList({ id, mastra, agent, requestContext, partial: isPartial });
        })
      );
      const serializedAgents = serializedCodeAgentsMap.reduce(
        (acc, { id, ...rest }) => {
          acc[id] = { id, ...rest };
          return acc;
        },
        {}
      );
      try {
        const editor = mastra.getEditor();
        let storedAgentsResult;
        try {
          storedAgentsResult = await editor?.agent.list();
        } catch (error) {
          console.error("Error listing stored agents:", error);
          storedAgentsResult = null;
        }
        if (storedAgentsResult?.agents) {
          for (const storedAgentConfig of storedAgentsResult.agents) {
            try {
              const agent = await editor?.agent.getById(storedAgentConfig.id);
              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 logger = mastra.getLogger();
              logger.warn("Failed to serialize stored agent", { agentId: storedAgentConfig.id, error: agentError });
            }
          }
        }
      } catch (storageError) {
        const logger = mastra.getLogger();
        logger.debug("Could not fetch stored agents", { error: storageError });
      }
      return serializedAgents;
    } catch (error) {
      return handleError(error, "Error getting agents");
    }
  }
});
var GET_AGENT_BY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/agents/:agentId",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  responseSchema: serializedAgentSchema,
  summary: "Get agent by ID",
  description: "Returns details for a specific agent including configuration, tools, and memory settings",
  tags: ["Agents"],
  requiresAuth: true,
  requiresPermission: "agents:read",
  handler: async ({ agentId, mastra, requestContext }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      const isStudio = false;
      const result = await formatAgent({
        mastra,
        agent,
        requestContext,
        isStudio
      });
      return result;
    } catch (error) {
      return handleError(error, "Error getting agent");
    }
  }
});
var CLONE_AGENT_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/clone",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: z.object({
    newId: z.string().optional().describe("ID for the cloned agent. If not provided, derived from agent ID."),
    newName: z.string().optional().describe('Name for the cloned agent. Defaults to "{name} (Clone)".'),
    metadata: z.record(z.string(), z.unknown()).optional(),
    authorId: z.string().optional()
  }),
  responseSchema: 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 handleError(new Error("Editor is not configured on the Mastra instance"), "Error cloning agent");
      }
      const agent = await getAgentFromSystem({ mastra, agentId });
      const cloneId = toSlug(newId || `${agentId}-clone`);
      const result = await editor.agent.clone(agent, {
        newId: cloneId,
        newName,
        metadata,
        authorId,
        requestContext
      });
      return result;
    } catch (error) {
      return handleError(error, "Error cloning agent");
    }
  }
});
var GENERATE_AGENT_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/generate",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: generateResponseSchema,
  summary: "Generate agent response",
  description: "Executes an agent with the provided messages and returns the complete response",
  tags: ["Agents"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async ({ agentId, mastra, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;
      validateBody({ messages });
      if (bodyRequestContext && typeof bodyRequestContext === "object") {
        for (const [key, value] of Object.entries(bodyRequestContext)) {
          if (serverRequestContext.get(key) === void 0) {
            serverRequestContext.set(key, value);
          }
        }
      }
      let authorizedMemoryOption = memoryOption;
      if (memoryOption) {
        const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
        const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);
        const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
        if (effectiveThreadId && effectiveResourceId) {
          const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
          if (memoryInstance) {
            const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
            await validateThreadOwnership(thread, effectiveResourceId);
          }
        }
        authorizedMemoryOption = {
          ...memoryOption,
          resource: effectiveResourceId ?? memoryOption.resource,
          thread: effectiveThreadId ?? memoryOption.thread
        };
      }
      const result = await agent.generate(messages, {
        ...rest,
        requestContext: serverRequestContext,
        memory: authorizedMemoryOption,
        abortSignal
      });
      return result;
    } catch (error) {
      return handleError(error, "Error generating from agent");
    }
  }
});
var GENERATE_LEGACY_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/generate-legacy",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionLegacyBodySchema,
  responseSchema: 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 });
      sanitizeBody(params, ["tools"]);
      const { messages, resourceId, resourceid, threadId, ...rest } = params;
      const clientResourceId = resourceId ?? resourceid;
      const effectiveResourceId = getEffectiveResourceId(requestContext, clientResourceId);
      const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
      validateBody({ messages });
      if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) {
        throw new HTTPException(400, { message: "Both threadId or resourceId must be provided" });
      }
      if (effectiveThreadId && effectiveResourceId) {
        const memory = await agent.getMemory({ requestContext });
        if (memory) {
          const thread = await memory.getThreadById({ threadId: effectiveThreadId });
          await validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      const result = await agent.generateLegacy(messages, {
        ...rest,
        abortSignal,
        resourceId: effectiveResourceId ?? "",
        threadId: effectiveThreadId ?? ""
      });
      return result;
    } catch (error) {
      return handleError(error, "Error generating from agent");
    }
  }
});
var STREAM_GENERATE_LEGACY_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/stream-legacy",
  responseType: "datastream-response",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionLegacyBodySchema,
  responseSchema: 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 });
      sanitizeBody(params, ["tools"]);
      const { messages, resourceId, resourceid, threadId, ...rest } = params;
      const clientResourceId = resourceId ?? resourceid;
      const effectiveResourceId = getEffectiveResourceId(requestContext, clientResourceId);
      const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
      validateBody({ messages });
      if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) {
        throw new HTTPException(400, { message: "Both threadId or resourceId must be provided" });
      }
      if (effectiveThreadId && effectiveResourceId) {
        const memory = await agent.getMemory({ requestContext });
        if (memory) {
          const thread = await memory.getThreadById({ threadId: effectiveThreadId });
          await validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      const streamResult = await agent.streamLegacy(messages, {
        ...rest,
        abortSignal,
        resourceId: effectiveResourceId ?? "",
        threadId: effectiveThreadId ?? ""
      });
      const streamResponse = rest.output ? streamResult.toTextStreamResponse({
        headers: {
          "Transfer-Encoding": "chunked"
        }
      }) : streamResult.toDataStreamResponse({
        sendUsage: true,
        sendReasoning: true,
        getErrorMessage: (error) => {
          return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
        },
        headers: {
          "Transfer-Encoding": "chunked"
        }
      });
      return streamResponse;
    } catch (error) {
      return handleError(error, "error streaming agent response");
    }
  }
});
var GET_PROVIDERS_ROUTE = createRoute({
  method: "GET",
  path: "/agents/providers",
  responseType: "json",
  responseSchema: providersResponseSchema,
  summary: "List AI providers",
  description: "Returns a list of all configured AI model providers",
  tags: ["Agents"],
  requiresAuth: true,
  handler: async () => {
    try {
      const providers = Object.entries(PROVIDER_REGISTRY).map(([id, provider]) => {
        return {
          id,
          name: provider.name,
          label: provider.label || provider.name,
          description: provider.description || "",
          envVar: provider.apiKeyEnvVar,
          connected: isProviderConnected(id),
          docUrl: provider.docUrl,
          models: [...provider.models]
          // Convert readonly array to regular array
        };
      });
      return { providers };
    } catch (error) {
      return handleError(error, "Error fetching providers");
    }
  }
});
var GENERATE_AGENT_VNEXT_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/generate/vnext",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: 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 = createRoute({
  method: "POST",
  path: "/agents/:agentId/stream",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: 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: "agents:execute",
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;
      validateBody({ messages });
      if (bodyRequestContext && typeof bodyRequestContext === "object") {
        for (const [key, value] of Object.entries(bodyRequestContext)) {
          if (serverRequestContext.get(key) === void 0) {
            serverRequestContext.set(key, value);
          }
        }
      }
      let authorizedMemoryOption = memoryOption;
      if (memoryOption) {
        const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
        const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);
        const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
        if (effectiveThreadId && effectiveResourceId) {
          const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
          if (memoryInstance) {
            const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
            await validateThreadOwnership(thread, effectiveResourceId);
          }
        }
        authorizedMemoryOption = {
          ...memoryOption,
          resource: effectiveResourceId ?? memoryOption.resource,
          thread: effectiveThreadId ?? memoryOption.thread
        };
      }
      const streamResult = await agent.stream(messages, {
        ...rest,
        requestContext: serverRequestContext,
        memory: authorizedMemoryOption,
        abortSignal
      });
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error streaming agent response");
    }
  }
});
var STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/stream/vnext",
  responseType: "stream",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: 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 APPROVE_TOOL_CALL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/approve-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: approveToolCallBodySchema,
  responseSchema: 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, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      if (!params.toolCallId) {
        throw new HTTPException(400, { message: "Tool call id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const streamResult = await agent.approveToolCall({
        ...params,
        abortSignal
      });
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error approving tool call");
    }
  }
});
var DECLINE_TOOL_CALL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/decline-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: declineToolCallBodySchema,
  responseSchema: 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, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      if (!params.toolCallId) {
        throw new HTTPException(400, { message: "Tool call id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const streamResult = await agent.declineToolCall({
        ...params,
        abortSignal
      });
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error declining tool call");
    }
  }
});
var APPROVE_TOOL_CALL_GENERATE_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/approve-tool-call-generate",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: approveToolCallBodySchema,
  responseSchema: 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, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      if (!params.toolCallId) {
        throw new HTTPException(400, { message: "Tool call id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const result = await agent.approveToolCallGenerate({
        ...params,
        abortSignal
      });
      return result;
    } catch (error) {
      return handleError(error, "error approving tool call");
    }
  }
});
var DECLINE_TOOL_CALL_GENERATE_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/decline-tool-call-generate",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: declineToolCallBodySchema,
  responseSchema: 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, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      if (!params.toolCallId) {
        throw new HTTPException(400, { message: "Tool call id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const result = await agent.declineToolCallGenerate({
        ...params,
        abortSignal
      });
      return result;
    } catch (error) {
      return handleError(error, "error declining tool call");
    }
  }
});
var STREAM_NETWORK_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/network",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: 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, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      sanitizeBody(params, ["tools"]);
      validateBody({ messages });
      const streamResult = await agent.network(messages, {
        ...params
      });
      return streamResult;
    } catch (error) {
      return handleError(error, "error streaming agent loop response");
    }
  }
});
var APPROVE_NETWORK_TOOL_CALL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/approve-network-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: approveNetworkToolCallBodySchema,
  responseSchema: 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, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const streamResult = await agent.approveNetworkToolCall({
        ...params
      });
      return streamResult;
    } catch (error) {
      return handleError(error, "error approving network tool call");
    }
  }
});
var DECLINE_NETWORK_TOOL_CALL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/decline-network-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: declineNetworkToolCallBodySchema,
  responseSchema: 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, ...params }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId });
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const streamResult = await agent.declineNetworkToolCall({
        ...params
      });
      return streamResult;
    } catch (error) {
      return handleError(error, "error declining network tool call");
    }
  }
});
var UPDATE_AGENT_MODEL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/model",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: updateAgentModelBodySchema,
  responseSchema: 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 handleError(error, "error updating agent model");
    }
  }
});
var RESET_AGENT_MODEL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/model/reset",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  responseSchema: 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 handleError(error, "error resetting agent model");
    }
  }
});
var REORDER_AGENT_MODEL_LIST_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/models/reorder",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: reorderAgentModelListBodySchema,
  responseSchema: 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 HTTPException(400, { message: "Agent model list is not found or empty" });
      }
      agent.reorderModels(reorderedModelIds);
      return { message: "Model list reordered" };
    } catch (error) {
      return handleError(error, "error reordering model list");
    }
  }
});
var UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/models/:modelConfigId",
  responseType: "json",
  pathParamSchema: modelConfigIdPathParams,
  bodySchema: updateAgentModelInModelListBodySchema,
  responseSchema: 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 HTTPException(400, { message: "Agent model list is not found or empty" });
      }
      const modelConfig = modelList.find((config) => config.id === modelConfigId);
      if (!modelConfig) {
        throw new 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 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 = createRoute({
  method: "POST",
  path: "/agents/:agentId/instructions/enhance",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: enhanceInstructionsBodySchema,
  responseSchema: 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 = await getAgentFromSystem({ mastra, agentId });
      const model = await findConnectedModel(agent);
      if (!model) {
        throw new 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({
        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: enhanceInstructionsResponseSchema
          }
        }
      );
      return await result.object;
    } catch (error) {
      return handleError(error, "Error enhancing instructions");
    }
  }
});
var STREAM_VNEXT_DEPRECATED_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/streamVNext",
  responseType: "stream",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: 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 HTTPException(410, { message: "This endpoint is deprecated. Please use /stream instead." });
  }
});
var STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/stream/vnext/ui",
  responseType: "stream",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: 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 MastraError({
        category: ErrorCategory.USER,
        domain: 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 handleError(error, "error streaming agent response");
    }
  }
});
var STREAM_UI_MESSAGE_DEPRECATED_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/stream/ui",
  responseType: "stream",
  pathParamSchema: agentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: 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 = createRoute({
  method: "GET",
  path: "/agents/:agentId/skills/:skillName",
  responseType: "json",
  pathParamSchema: agentSkillPathParams,
  responseSchema: 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, requestContext }) => {
    try {
      const agent = agentId ? mastra.getAgentById(agentId) : null;
      if (!agent) {
        throw new HTTPException(404, { message: "Agent not found" });
      }
      const workspace = await agent.getWorkspace({ requestContext });
      if (!workspace?.skills) {
        throw new HTTPException(404, { message: "Agent does not have skills configured" });
      }
      const skill = await workspace.skills.get(skillName);
      if (!skill) {
        throw new HTTPException(404, { message: `Skill "${skillName}" 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 handleError(error, "Error getting agent skill");
    }
  }
});

export { APPROVE_NETWORK_TOOL_CALL_ROUTE, APPROVE_TOOL_CALL_GENERATE_ROUTE, APPROVE_TOOL_CALL_ROUTE, CLONE_AGENT_ROUTE, DECLINE_NETWORK_TOOL_CALL_ROUTE, DECLINE_TOOL_CALL_GENERATE_ROUTE, DECLINE_TOOL_CALL_ROUTE, ENHANCE_INSTRUCTIONS_ROUTE, GENERATE_AGENT_ROUTE, GENERATE_AGENT_VNEXT_ROUTE, GENERATE_LEGACY_ROUTE, GET_AGENT_BY_ID_ROUTE, GET_AGENT_SKILL_ROUTE, GET_PROVIDERS_ROUTE, LIST_AGENTS_ROUTE, REORDER_AGENT_MODEL_LIST_ROUTE, RESET_AGENT_MODEL_ROUTE, STREAM_GENERATE_LEGACY_ROUTE, STREAM_GENERATE_ROUTE, STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE, STREAM_NETWORK_ROUTE, STREAM_UI_MESSAGE_DEPRECATED_ROUTE, STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE, STREAM_VNEXT_DEPRECATED_ROUTE, UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE, UPDATE_AGENT_MODEL_ROUTE, agents_exports, getAgentFromSystem, getSerializedAgentTools, getSerializedProcessors, getSerializedSkillsFromAgent, getWorkspaceToolsFromAgent, isProviderConnected };
//# sourceMappingURL=chunk-BPNWGEPT.js.map
//# sourceMappingURL=chunk-BPNWGEPT.js.map