'use strict';

var chunkHXICAUTW_cjs = require('./chunk-HXICAUTW.cjs');
var chunkXT6GKIYW_cjs = require('./chunk-XT6GKIYW.cjs');
var chunkYJQYJ5WD_cjs = require('./chunk-YJQYJ5WD.cjs');
var chunkLWK57QIA_cjs = require('./chunk-LWK57QIA.cjs');
var chunkI3BHHWHT_cjs = require('./chunk-I3BHHWHT.cjs');
var chunkWYLVJSGR_cjs = require('./chunk-WYLVJSGR.cjs');
var chunk5UKYK7YK_cjs = require('./chunk-5UKYK7YK.cjs');
var chunkB34S64RC_cjs = require('./chunk-B34S64RC.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var agent = require('@mastra/core/agent');
var di = require('@mastra/core/di');
var error = require('@mastra/core/error');
var llm = require('@mastra/core/llm');
var requestContext = require('@mastra/core/request-context');
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, {
  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,
  RESUME_STREAM_ROUTE: () => RESUME_STREAM_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,
  UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE: () => UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE,
  UPDATE_AGENT_MODEL_ROUTE: () => UPDATE_AGENT_MODEL_ROUTE,
  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(requestContext.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(requestContext.MASTRA_VERSIONS_KEY, merged);
  }
}
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 chunk5UKYK7YK_cjs.standardSchemaToJSONSchema(chunk5UKYK7YK_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 = chunkYJQYJ5WD_cjs.stringify(inputSchema);
        }
        const outputSchema = schemaToJsonSchema(
          resolveLazySchema(tool.outputSchema)
        );
        if (outputSchema !== void 0) {
          outputSchemaForReturn = chunkYJQYJ5WD_cjs.stringify(outputSchema);
        }
        const requestContextSchema = schemaToJsonSchema(
          resolveLazySchema(tool.requestContextSchema)
        );
        if (requestContextSchema !== void 0) {
          requestContextSchemaForReturn = chunkYJQYJ5WD_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 chunkI3BHHWHT_cjs.resolveToolConfig(toolsConfig, toolName, configContext)).enabled;
    };
    if (workspace.filesystem) {
      if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.READ_FILE)) {
        tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.READ_FILE);
      }
      if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES)) {
        tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES);
      }
      if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT)) {
        tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT);
      }
      if (!isReadOnly) {
        if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE)) {
          tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE);
        }
        if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE)) {
          tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE);
        }
        if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.DELETE)) {
          tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.DELETE);
        }
        if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.MKDIR)) {
          tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.MKDIR);
        }
      }
      if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.GREP)) {
        tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.FILESYSTEM.GREP);
      }
    }
    if (workspace.canBM25 || workspace.canVector) {
      if (await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.SEARCH.SEARCH)) {
        tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.SEARCH.SEARCH);
      }
      if (!isReadOnly && await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.SEARCH.INDEX)) {
        tools.push(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.SEARCH.INDEX);
      }
    }
    if (workspace.sandbox) {
      if (workspace.sandbox.executeCommand && await isEnabled(chunkI3BHHWHT_cjs.WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND)) {
        tools.push(chunkI3BHHWHT_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]) => {
          return {
            ...acc,
            [key]: { id: agent2.id, name: agent2.name }
          };
        },
        {}
      );
    } 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 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();
  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 = chunkYJQYJ5WD_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,
    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,
    defaultOptions,
    modelList,
    defaultGenerateOptionsLegacy,
    defaultStreamOptionsLegacy,
    requestContextSchema: serializedRequestContextSchema,
    source: agent.source ?? "code",
    ...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) {
  const agentVersionId = requestContext?.get("agentVersionId");
  if (typeof agentVersionId === "string" && agentVersionId) {
    return { versionId: agentVersionId };
  }
  return void 0;
}
async function getAgentFromSystem({
  mastra,
  agentId,
  versionOptions
}) {
  const logger = mastra.getLogger();
  if (!agentId) {
    throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Agent ID is required" });
  }
  let agent;
  try {
    agent = mastra.getAgentById(agentId);
  } catch (error) {
    logger.debug("Error getting agent from mastra, searching agents for agent", error);
  }
  if (!agent) {
    logger.debug("Agent not found, looking through sub-agents", { agentId });
    const agents = mastra.listAgents();
    if (Object.keys(agents || {}).length) {
      for (const [_, ag] of Object.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 && mastra.getEditor) {
    try {
      const editorAgent = mastra.getEditor()?.agent;
      if (editorAgent) {
        agent = await editorAgent.applyStoredOverrides(agent, versionOptions ?? { status: "published" });
      }
    } catch (error) {
      logger.debug("Error applying stored overrides to code agent", error);
    }
  }
  if (!agent) {
    logger.debug("Agent not found in code-defined agents, looking in stored agents", { agentId });
    try {
      agent = await mastra.getEditor()?.agent.getById(agentId, versionOptions) ?? null;
    } catch (error) {
      logger.debug("Error getting stored agent", error);
    }
  }
  if (!agent) {
    throw new chunk64ITUOXI_cjs.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$1 = 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$1?.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);
  const browserTools = getBrowserToolsFromAgent(agent, createBrowserToolsErrorLogger(mastra.getLogger(), agent.id));
  let workspaceId;
  try {
    const workspace = await agent.getWorkspace({ requestContext: proxyRequestContext });
    workspaceId = workspace?.id;
  } catch {
  }
  let serializedRequestContextSchema;
  if (agent.requestContextSchema) {
    try {
      serializedRequestContextSchema = chunkYJQYJ5WD_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,
    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,
    modelList,
    defaultOptions,
    defaultGenerateOptionsLegacy,
    defaultStreamOptionsLegacy,
    requestContextSchema: serializedRequestContextSchema,
    source: agent.source ?? "code",
    ...agent.toRawConfig()?.status ? { status: agent.toRawConfig().status } : {}
  };
}
var LIST_AGENTS_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/agents",
  responseType: "json",
  queryParamSchema: v4.z.object({
    partial: v4.z.string().optional()
  }),
  responseSchema: chunkXT6GKIYW_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: "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);
            } 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;
        }
        if (storedAgentsResult?.agents) {
          for (const storedAgentConfig of storedAgentsResult.agents) {
            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 });
      }
      return serializedAgents;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting agents");
    }
  }
});
var GET_AGENT_BY_ID_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/agents/:agentId",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  queryParamSchema: chunkXT6GKIYW_cjs.agentVersionQuerySchema,
  responseSchema: chunkXT6GKIYW_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=<id> (specific version). Use either status or versionId, not both.",
  tags: ["Agents"],
  requiresAuth: true,
  requiresPermission: "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 });
      const isStudio = false;
      const result = await formatAgent({
        mastra,
        agent,
        requestContext,
        isStudio
      });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting agent");
    }
  }
});
var CLONE_AGENT_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/clone",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_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: chunkWYLVJSGR_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 chunkB34S64RC_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 = chunkYJQYJ5WD_cjs.toSlug(newId || `${agentId}-clone`);
      const result = await editor.agent.clone(agent, {
        newId: cloneId,
        newName,
        metadata,
        authorId,
        requestContext
      });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error cloning agent");
    }
  }
});
var GENERATE_AGENT_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/generate",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_cjs.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,
        versionOptions: extractVersionOptions(serverRequestContext)
      });
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
      chunkLWK57QIA_cjs.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);
          }
        }
      }
      stashVersionOverrides(serverRequestContext, versions);
      let authorizedMemoryOption = memoryOption;
      if (memoryOption) {
        const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
        const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(serverRequestContext, memoryOption.resource);
        const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId);
        if (effectiveThreadId && effectiveResourceId) {
          const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
          if (memoryInstance) {
            const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
            await chunkLWK57QIA_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 result = structuredOutput ? await agent.generate(messages, { ...options, structuredOutput }) : await agent.generate(messages, options);
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error generating from agent");
    }
  }
});
var GENERATE_LEGACY_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/generate-legacy",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionLegacyBodySchema,
  responseSchema: chunkXT6GKIYW_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)
      });
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const { messages, resourceId, resourceid, threadId, ...rest } = params;
      const clientResourceId = resourceId ?? resourceid;
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, clientResourceId);
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      chunkLWK57QIA_cjs.validateBody({ messages });
      if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) {
        throw new chunk64ITUOXI_cjs.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 chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      const result = await agent.generateLegacy(messages, {
        ...rest,
        abortSignal,
        resourceId: effectiveResourceId ?? "",
        threadId: effectiveThreadId ?? ""
      });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error generating from agent");
    }
  }
});
var STREAM_GENERATE_LEGACY_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/stream-legacy",
  responseType: "datastream-response",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionLegacyBodySchema,
  responseSchema: chunkXT6GKIYW_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)
      });
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const { messages, resourceId, resourceid, threadId, ...rest } = params;
      const clientResourceId = resourceId ?? resourceid;
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, clientResourceId);
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      chunkLWK57QIA_cjs.validateBody({ messages });
      if (effectiveThreadId && !effectiveResourceId || !effectiveThreadId && effectiveResourceId) {
        throw new chunk64ITUOXI_cjs.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 chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      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) => {
          return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
        }
      });
      return streamResponse;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error streaming agent response");
    }
  }
});
var GET_PROVIDERS_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/agents/providers",
  responseType: "json",
  responseSchema: chunkXT6GKIYW_cjs.providersResponseSchema,
  summary: "List AI providers",
  description: "Returns a list of all configured AI model providers",
  tags: ["Agents"],
  requiresAuth: true,
  handler: async ({ mastra }) => {
    try {
      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}`;
                allProviders[prefixedId] = config;
              }
            } catch (error) {
              console.warn(`Failed to fetch providers from gateway "${gateway.id}":`, error);
            }
          }
        }
      }
      const providers = 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]
        };
      });
      return { providers };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error fetching providers");
    }
  }
});
var GENERATE_AGENT_VNEXT_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/generate/vnext",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_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 = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/stream",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_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: "agents:execute",
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(serverRequestContext)
      });
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
      chunkLWK57QIA_cjs.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);
          }
        }
      }
      stashVersionOverrides(serverRequestContext, versions);
      let authorizedMemoryOption = memoryOption;
      if (memoryOption) {
        const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
        const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(serverRequestContext, memoryOption.resource);
        const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId);
        if (effectiveThreadId && effectiveResourceId) {
          const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
          if (memoryInstance) {
            const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
            await chunkLWK57QIA_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.stream(messages, { ...options, structuredOutput }) : await agent.stream(messages, options);
      return streamResult.fullStream;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error streaming agent response");
    }
  }
});
var STREAM_UNTIL_IDLE_GENERATE_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/stream-until-idle",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.streamUntilIdleBodySchema,
  responseSchema: chunkXT6GKIYW_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: "agents:execute",
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(serverRequestContext)
      });
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;
      chunkLWK57QIA_cjs.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 = chunkLWK57QIA_cjs.getEffectiveResourceId(serverRequestContext, memoryOption.resource);
        const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId);
        if (effectiveThreadId && effectiveResourceId) {
          const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
          if (memoryInstance) {
            const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
            await chunkLWK57QIA_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 chunkB34S64RC_cjs.handleError(error, "error streaming agent response");
    }
  }
});
var STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/stream/vnext",
  responseType: "stream",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_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 APPROVE_TOOL_CALL_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/approve-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.approveToolCallBodySchema,
  responseSchema: chunkXT6GKIYW_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" });
      }
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const streamResult = await agent.approveToolCall({
        ...params,
        requestContext,
        abortSignal
      });
      return streamResult.fullStream;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error approving tool call");
    }
  }
});
var DECLINE_TOOL_CALL_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/decline-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.declineToolCallBodySchema,
  responseSchema: chunkXT6GKIYW_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" });
      }
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const streamResult = await agent.declineToolCall({
        ...params,
        requestContext,
        abortSignal
      });
      return streamResult.fullStream;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error declining tool call");
    }
  }
});
var RESUME_STREAM_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/resume-stream",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.resumeStreamBodySchema,
  responseSchema: chunkXT6GKIYW_cjs.streamResponseSchema,
  summary: "Resume agent stream",
  description: "Resumes a suspended agent stream with custom resume data",
  tags: ["Agents"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(serverRequestContext)
      });
      if (!params.runId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Run id is required" });
      }
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const {
        resumeData,
        runId,
        toolCallId,
        memory: memoryOption,
        requestContext: bodyRequestContext,
        versions,
        ...rest
      } = params;
      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);
      let authorizedMemoryOption = memoryOption;
      const clientThreadId = typeof memoryOption?.thread === "string" ? memoryOption.thread : memoryOption?.thread?.id;
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(serverRequestContext, memoryOption?.resource);
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(serverRequestContext, clientThreadId);
      if (effectiveThreadId && effectiveResourceId) {
        const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
        if (memoryInstance) {
          const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
          await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      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 chunkLWK57QIA_cjs.validateRunOwnership(workflowRun, chunkLWK57QIA_cjs.getEffectiveResourceId(serverRequestContext, void 0));
      const { structuredOutput, ...restOptions } = rest;
      const options = {
        runId,
        toolCallId,
        ...restOptions,
        requestContext: serverRequestContext,
        memory: authorizedMemoryOption,
        abortSignal
      };
      const streamResult = structuredOutput ? await agent.resumeStream(resumeData, { ...options, structuredOutput }) : await agent.resumeStream(resumeData, options);
      return streamResult.fullStream;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error resuming agent stream");
    }
  }
});
var APPROVE_TOOL_CALL_GENERATE_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/approve-tool-call-generate",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.approveToolCallBodySchema,
  responseSchema: chunkXT6GKIYW_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" });
      }
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const result = await agent.approveToolCallGenerate({
        ...params,
        requestContext,
        abortSignal
      });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error approving tool call");
    }
  }
});
var DECLINE_TOOL_CALL_GENERATE_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/decline-tool-call-generate",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.declineToolCallBodySchema,
  responseSchema: chunkXT6GKIYW_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" });
      }
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const result = await agent.declineToolCallGenerate({
        ...params,
        requestContext,
        abortSignal
      });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error declining tool call");
    }
  }
});
var STREAM_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/network",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_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)
      });
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      chunkLWK57QIA_cjs.validateBody({ messages });
      const streamResult = await agent.network(messages, {
        ...params
      });
      return streamResult;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error streaming agent loop response");
    }
  }
});
var APPROVE_NETWORK_TOOL_CALL_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/approve-network-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.approveNetworkToolCallBodySchema,
  responseSchema: chunkXT6GKIYW_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" });
      }
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const streamResult = await agent.approveNetworkToolCall({
        ...params
      });
      return streamResult;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error approving network tool call");
    }
  }
});
var DECLINE_NETWORK_TOOL_CALL_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/decline-network-tool-call",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.declineNetworkToolCallBodySchema,
  responseSchema: chunkXT6GKIYW_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" });
      }
      chunkLWK57QIA_cjs.sanitizeBody(params, ["tools"]);
      const streamResult = await agent.declineNetworkToolCall({
        ...params
      });
      return streamResult;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "error declining network tool call");
    }
  }
});
var UPDATE_AGENT_MODEL_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/model",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.updateAgentModelBodySchema,
  responseSchema: chunkXT6GKIYW_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 chunkB34S64RC_cjs.handleError(error, "error updating agent model");
    }
  }
});
var RESET_AGENT_MODEL_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/model/reset",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  responseSchema: chunkXT6GKIYW_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 chunkB34S64RC_cjs.handleError(error, "error resetting agent model");
    }
  }
});
var REORDER_AGENT_MODEL_LIST_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/models/reorder",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.reorderAgentModelListBodySchema,
  responseSchema: chunkXT6GKIYW_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 chunkB34S64RC_cjs.handleError(error, "error reordering model list");
    }
  }
});
var UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/models/:modelConfigId",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.modelConfigIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.updateAgentModelInModelListBodySchema,
  responseSchema: chunkXT6GKIYW_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 chunkB34S64RC_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 = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/instructions/enhance",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.enhanceInstructionsBodySchema,
  responseSchema: chunkXT6GKIYW_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: chunkXT6GKIYW_cjs.enhanceInstructionsResponseSchema
          }
        }
      );
      return await result.object;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error enhancing instructions");
    }
  }
});
var STREAM_VNEXT_DEPRECATED_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/streamVNext",
  responseType: "stream",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_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 = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/stream/vnext/ui",
  responseType: "stream",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_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 chunkB34S64RC_cjs.handleError(error, "error streaming agent response");
    }
  }
});
var STREAM_UI_MESSAGE_DEPRECATED_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/agents/:agentId/stream/ui",
  responseType: "stream",
  pathParamSchema: chunkXT6GKIYW_cjs.agentIdPathParams,
  bodySchema: chunkXT6GKIYW_cjs.agentExecutionBodySchema,
  responseSchema: chunkXT6GKIYW_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 = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/agents/:agentId/skills/:skillName",
  responseType: "json",
  pathParamSchema: chunkXT6GKIYW_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 chunkB34S64RC_cjs.handleError(error, "Error getting agent skill");
    }
  }
});

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.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.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.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.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-VR623NIZ.cjs.map
//# sourceMappingURL=chunk-VR623NIZ.cjs.map