import { createStoredAgentResponseSchema } from './chunk-SPVKRK56.js';
import { getAgentSkillResponseSchema, skillDisambiguationQuerySchema } from './chunk-ZHULRNJG.js';
import { listAgentsResponseSchema, serializedAgentSchema, agentVersionQuerySchema, agentIdPathParams, generateResponseSchema, agentExecutionBodySchema, agentExecutionLegacyBodySchema, streamResponseSchema, providersResponseSchema, sendAgentSignalBodySchema, sendAgentMessageBodySchema, queueAgentMessageBodySchema, abortAgentThreadResponseSchema, abortAgentThreadBodySchema, subscribeAgentThreadBodySchema, streamUntilIdleBodySchema, observeAgentResponseSchema, observeAgentBodySchema, toolCallResponseSchema, approveToolCallBodySchema, sendToolApprovalResponseSchema, sendToolApprovalBodySchema, listSuspendedRunsResponseSchema, listSuspendedRunsQuerySchema, declineToolCallBodySchema, resumeStreamBodySchema, resumeStreamUntilIdleBodySchema, approveNetworkToolCallBodySchema, declineNetworkToolCallBodySchema, modelManagementResponseSchema, updateAgentModelBodySchema, reorderAgentModelListBodySchema, updateAgentModelInModelListBodySchema, modelConfigIdPathParams, enhanceInstructionsResponseSchema, enhanceInstructionsBodySchema, agentSkillPathParams } from './chunk-R3KUPFCO.js';
import { MastraFGAPermissions, sanitizeBody, validateBody, getEffectiveResourceId, getEffectiveThreadId, enforceThreadAccess, validateThreadOwnership, validateRunOwnership } from './chunk-JBSUT5XF.js';
import { stringify, toSlug } from './chunk-QIQWHDPH.js';
import { WORKSPACE_TOOLS, resolveToolConfig, MASTRA_IS_STUDIO_KEY, isReservedRequestContextKey } from './chunk-5FOSK5R3.js';
import { handleError } from './chunk-7ZWJX3AN.js';
import { createRoute } from './chunk-PIKPS6Q6.js';
import { standardSchemaToJSONSchema, toStandardSchema5 } from './chunk-YZAQOU2I.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { Agent, isDurableAgentLike } from '@mastra/core/agent';
import { AGENT_STREAM_TOPIC } from '@mastra/core/agent/durable';
import { MASTRA_VERSIONS_KEY, mergeVersionOverrides } from '@mastra/core/di';
import { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';
import { PROVIDER_REGISTRY, defaultGateways, parseModelString } from '@mastra/core/llm';
import { zodToJsonSchema } from '@mastra/core/utils/zod-to-json';
import { z } from 'zod/v4';

// src/server/handlers/agents.ts
var agents_exports = {};
__export(agents_exports, {
  ABORT_AGENT_THREAD_ROUTE: () => ABORT_AGENT_THREAD_ROUTE,
  APPROVE_NETWORK_TOOL_CALL_ROUTE: () => APPROVE_NETWORK_TOOL_CALL_ROUTE,
  APPROVE_TOOL_CALL_GENERATE_ROUTE: () => APPROVE_TOOL_CALL_GENERATE_ROUTE,
  APPROVE_TOOL_CALL_ROUTE: () => APPROVE_TOOL_CALL_ROUTE,
  CLONE_AGENT_ROUTE: () => CLONE_AGENT_ROUTE,
  DECLINE_NETWORK_TOOL_CALL_ROUTE: () => DECLINE_NETWORK_TOOL_CALL_ROUTE,
  DECLINE_TOOL_CALL_GENERATE_ROUTE: () => DECLINE_TOOL_CALL_GENERATE_ROUTE,
  DECLINE_TOOL_CALL_ROUTE: () => DECLINE_TOOL_CALL_ROUTE,
  ENHANCE_INSTRUCTIONS_ROUTE: () => ENHANCE_INSTRUCTIONS_ROUTE,
  GENERATE_AGENT_ROUTE: () => GENERATE_AGENT_ROUTE,
  GENERATE_AGENT_VNEXT_ROUTE: () => GENERATE_AGENT_VNEXT_ROUTE,
  GENERATE_LEGACY_ROUTE: () => GENERATE_LEGACY_ROUTE,
  GET_AGENT_BY_ID_ROUTE: () => GET_AGENT_BY_ID_ROUTE,
  GET_AGENT_SKILL_ROUTE: () => GET_AGENT_SKILL_ROUTE,
  GET_PROVIDERS_ROUTE: () => GET_PROVIDERS_ROUTE,
  LIST_AGENTS_ROUTE: () => LIST_AGENTS_ROUTE,
  LIST_SUSPENDED_RUNS_ROUTE: () => LIST_SUSPENDED_RUNS_ROUTE,
  OBSERVE_AGENT_STREAM_ROUTE: () => OBSERVE_AGENT_STREAM_ROUTE,
  QUEUE_AGENT_MESSAGE_ROUTE: () => QUEUE_AGENT_MESSAGE_ROUTE,
  REORDER_AGENT_MODEL_LIST_ROUTE: () => REORDER_AGENT_MODEL_LIST_ROUTE,
  RESET_AGENT_MODEL_ROUTE: () => RESET_AGENT_MODEL_ROUTE,
  RESUME_STREAM_ROUTE: () => RESUME_STREAM_ROUTE,
  RESUME_STREAM_UNTIL_IDLE_ROUTE: () => RESUME_STREAM_UNTIL_IDLE_ROUTE,
  SEND_AGENT_MESSAGE_ROUTE: () => SEND_AGENT_MESSAGE_ROUTE,
  SEND_AGENT_SIGNAL_ROUTE: () => SEND_AGENT_SIGNAL_ROUTE,
  SEND_TOOL_APPROVAL_ROUTE: () => SEND_TOOL_APPROVAL_ROUTE,
  STREAM_GENERATE_LEGACY_ROUTE: () => STREAM_GENERATE_LEGACY_ROUTE,
  STREAM_GENERATE_ROUTE: () => STREAM_GENERATE_ROUTE,
  STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE: () => STREAM_GENERATE_VNEXT_DEPRECATED_ROUTE,
  STREAM_NETWORK_ROUTE: () => STREAM_NETWORK_ROUTE,
  STREAM_UI_MESSAGE_DEPRECATED_ROUTE: () => STREAM_UI_MESSAGE_DEPRECATED_ROUTE,
  STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE: () => STREAM_UI_MESSAGE_VNEXT_DEPRECATED_ROUTE,
  STREAM_UNTIL_IDLE_GENERATE_ROUTE: () => STREAM_UNTIL_IDLE_GENERATE_ROUTE,
  STREAM_VNEXT_DEPRECATED_ROUTE: () => STREAM_VNEXT_DEPRECATED_ROUTE,
  SUBSCRIBE_AGENT_THREAD_ROUTE: () => SUBSCRIBE_AGENT_THREAD_ROUTE,
  UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE: () => UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE,
  UPDATE_AGENT_MODEL_ROUTE: () => UPDATE_AGENT_MODEL_ROUTE,
  buildProvidersList: () => buildProvidersList,
  extractVersionOptions: () => extractVersionOptions,
  getAgentFromSystem: () => getAgentFromSystem,
  getBrowserToolsFromAgent: () => getBrowserToolsFromAgent,
  getSerializedAgentTools: () => getSerializedAgentTools,
  getSerializedProcessors: () => getSerializedProcessors,
  getSerializedSkillsFromAgent: () => getSerializedSkillsFromAgent,
  getWorkspaceToolsFromAgent: () => getWorkspaceToolsFromAgent,
  isProviderConnected: () => isProviderConnected
});
function stashVersionOverrides(ctx, versions) {
  if (!versions) return;
  const existingRaw = ctx.get(MASTRA_VERSIONS_KEY);
  const existing = existingRaw && typeof existingRaw === "object" && !Array.isArray(existingRaw) ? existingRaw : void 0;
  const merged = mergeVersionOverrides(existing, versions);
  if (merged) {
    ctx.set(MASTRA_VERSIONS_KEY, merged);
  }
}
function ensureDefaultVersionStatus(ctx, versionOptions) {
  const existingRaw = ctx.get(MASTRA_VERSIONS_KEY);
  if (existingRaw?.defaultStatus) return;
  const inferredStatus = versionOptions ? "draft" : "published";
  const updated = { ...existingRaw, defaultStatus: inferredStatus };
  ctx.set(MASTRA_VERSIONS_KEY, updated);
}
function getIsStudioFromContext(requestContext) {
  return requestContext.get(MASTRA_IS_STUDIO_KEY) === true;
}
function mergeBodyRequestContext(serverRequestContext, bodyRequestContext) {
  if (!bodyRequestContext || typeof bodyRequestContext !== "object") {
    return;
  }
  for (const [key, value] of Object.entries(bodyRequestContext)) {
    if (isReservedRequestContextKey(key)) continue;
    if (serverRequestContext.get(key) === void 0) {
      serverRequestContext.set(key, value);
    }
  }
}
function isProviderConnected(providerId, customProviders) {
  const cleanId = providerId.includes(".") ? providerId.split(".")[0] : providerId;
  let provider = PROVIDER_REGISTRY[cleanId];
  if (!provider && customProviders) {
    provider = customProviders[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 && 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 standardSchemaToJSONSchema(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 = stringify(inputSchema);
        }
        const outputSchema = schemaToJsonSchema(
          resolveLazySchema(tool.outputSchema)
        );
        if (outputSchema !== void 0) {
          outputSchemaForReturn = stringify(outputSchema);
        }
        const requestContextSchema = schemaToJsonSchema(
          resolveLazySchema(tool.requestContextSchema)
        );
        if (requestContextSchema !== void 0) {
          requestContextSchemaForReturn = 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 skillsList = await agent.listSkills({ requestContext });
    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 resolveToolConfig(toolsConfig, toolName, configContext)).enabled;
    };
    if (workspace.filesystem) {
      if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE)) {
        tools.push(WORKSPACE_TOOLS.FILESYSTEM.READ_FILE);
      }
      if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES)) {
        tools.push(WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES);
      }
      if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT)) {
        tools.push(WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT);
      }
      if (!isReadOnly) {
        if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE);
        }
        if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE);
        }
        if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.DELETE)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.DELETE);
        }
        if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.MKDIR)) {
          tools.push(WORKSPACE_TOOLS.FILESYSTEM.MKDIR);
        }
      }
      if (await isEnabled(WORKSPACE_TOOLS.FILESYSTEM.GREP)) {
        tools.push(WORKSPACE_TOOLS.FILESYSTEM.GREP);
      }
    }
    if (workspace.canBM25 || workspace.canVector) {
      if (await isEnabled(WORKSPACE_TOOLS.SEARCH.SEARCH)) {
        tools.push(WORKSPACE_TOOLS.SEARCH.SEARCH);
      }
      if (!isReadOnly && await isEnabled(WORKSPACE_TOOLS.SEARCH.INDEX)) {
        tools.push(WORKSPACE_TOOLS.SEARCH.INDEX);
      }
    }
    if (workspace.sandbox) {
      if (workspace.sandbox.executeCommand && await isEnabled(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND)) {
        tools.push(WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND);
      }
    }
    return tools;
  } catch {
    return [];
  }
}
function getBrowserToolsFromAgent(agent, onError) {
  try {
    const browser = agent.browser;
    if (!browser) {
      return [];
    }
    return Object.keys(browser.getTools());
  } catch (error) {
    onError?.(error);
    return [];
  }
}
function createBrowserToolsErrorLogger(logger, agentId) {
  return (error) => logger.warn("Failed to get browser tools for agent", { agentId, error });
}
async function getSerializedAgentDefinition({
  agent,
  requestContext,
  logger
}) {
  let serializedAgentAgents = {};
  if ("listAgents" in agent) {
    try {
      const agents = await agent.listAgents({ requestContext });
      serializedAgentAgents = Object.entries(agents || {}).reduce(
        (acc, [key, agent2]) => {
          acc[key] = { id: agent2.id, name: agent2.name ?? key };
          return acc;
        },
        {}
      );
    } catch (error) {
      logger?.warn("Error getting sub-agents for agent", { agentName: agent.name, error });
    }
  }
  return serializedAgentAgents;
}
async function formatAgentList({
  id,
  mastra,
  agent,
  requestContext,
  partial = false
}) {
  const logger = mastra.getLogger();
  const description = agent.getDescription();
  let metadata;
  if (typeof agent.getMetadata === "function") {
    try {
      metadata = await agent.getMetadata({ requestContext });
    } catch {
    }
  }
  let instructions;
  try {
    instructions = await agent.getInstructions({ requestContext });
  } catch (error) {
    logger.warn("Error getting instructions for agent", { agentName: agent.name, error });
  }
  let tools = {};
  try {
    tools = await agent.listTools({ requestContext });
  } catch (error) {
    logger.warn("Error listing tools for agent", { agentName: agent.name, error });
  }
  let llm;
  try {
    llm = 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?.getModel();
  const supportsMemory = typeof agent.supportsMemory === "function" ? agent.supportsMemory() : true;
  let models;
  try {
    models = await agent.getModelList(requestContext);
  } catch (error) {
    logger.warn("Error getting model list for agent", { agentName: agent.name, error });
  }
  const modelList = models?.map((md) => ({
    ...md,
    model: {
      modelId: md.model.modelId,
      provider: md.model.provider,
      modelVersion: md.model.specificationVersion
    }
  }));
  let serializedRequestContextSchema;
  if (agent.requestContextSchema) {
    try {
      serializedRequestContextSchema = 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,
    metadata,
    instructions,
    agents: serializedAgentAgents,
    tools: serializedAgentTools,
    workflows: serializedAgentWorkflows,
    skills: serializedSkills,
    workspaceTools,
    browserTools,
    workspaceId,
    inputProcessors: serializedInputProcessors,
    outputProcessors: serializedOutputProcessors,
    provider: typeof agent.model === "string" ? parseModelString(agent.model).provider ?? llm?.getProvider() : llm?.getProvider(),
    modelId: typeof agent.model === "string" ? parseModelString(agent.model).modelId : llm?.getModelId(),
    modelVersion: model?.specificationVersion,
    supportsMemory,
    defaultOptions,
    modelList,
    defaultGenerateOptionsLegacy,
    defaultStreamOptionsLegacy,
    requestContextSchema: serializedRequestContextSchema,
    source: agent.source ?? "code",
    editor: agent.__getEditorConfig?.(),
    ...agent.toRawConfig()?.status ? { status: agent.toRawConfig().status } : {},
    ...agent.toRawConfig()?.activeVersionId ? { activeVersionId: agent.toRawConfig().activeVersionId } : {},
    hasDraft: !!(agent.toRawConfig()?.resolvedVersionId && agent.toRawConfig()?.activeVersionId && agent.toRawConfig().resolvedVersionId !== agent.toRawConfig().activeVersionId)
  };
}
function extractVersionOptions(requestContext, bodyRequestContext) {
  const agentVersionId = requestContext?.get("agentVersionId");
  if (typeof agentVersionId === "string" && agentVersionId) {
    return { versionId: agentVersionId };
  }
  const bodyVersionId = bodyRequestContext?.agentVersionId;
  if (typeof bodyVersionId === "string" && bodyVersionId) {
    return { versionId: bodyVersionId };
  }
  return void 0;
}
async function getAgentFromSystem({
  mastra,
  agentId,
  versionOptions,
  requestContext
}) {
  const logger = mastra.getLogger();
  if (!agentId) {
    throw new 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();
          const subAgent = subAgents[agentId];
          if (subAgent instanceof Agent) {
            agent = subAgent;
            break;
          }
        } catch (error) {
          logger.debug("Error getting agent from agent", error);
        }
      }
    }
  }
  if (agent && mastra.getEditor) {
    try {
      const editorAgent = mastra.getEditor()?.agent;
      if (editorAgent) {
        agent = await editorAgent.applyStoredOverrides(
          agent,
          versionOptions ?? { status: "published" },
          requestContext
        );
      }
    } catch (error) {
      logger.debug("Error applying stored overrides to code agent", error);
    }
  }
  if (!agent) {
    logger.debug("Agent not found in code-defined agents, looking in stored agents", { agentId });
    try {
      agent = await mastra.getEditor()?.agent.getById(agentId, versionOptions) ?? 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();
  let metadata;
  if (typeof agent.getMetadata === "function") {
    try {
      metadata = await agent.getMetadata({ requestContext });
    } catch {
    }
  }
  const tools = await agent.listTools({ requestContext });
  const serializedAgentTools = await getSerializedAgentTools(tools);
  let serializedAgentWorkflows = {};
  if ("listWorkflows" in agent) {
    const logger = mastra.getLogger();
    try {
      const workflows = await agent.listWorkflows({ requestContext });
      serializedAgentWorkflows = Object.entries(workflows || {}).reduce((acc, [key, workflow]) => {
        return {
          ...acc,
          [key]: {
            name: workflow.name || "Unnamed workflow",
            steps: Object.entries(workflow.steps).reduce(
              (acc2, [key2, step]) => {
                return {
                  ...acc2,
                  [key2]: {
                    id: step.id,
                    description: step.description
                  }
                };
              },
              {}
            )
          }
        };
      }, {});
    } catch (error) {
      logger.error("Error getting workflows for agent", { agentName: agent.name, error });
    }
  }
  const instructionsRequestContext = isStudio ? new Proxy(requestContext, {
    get(target, prop) {
      if (prop === "get") {
        return function(key) {
          const value = target.get(key);
          return value ?? `<${key}>`;
        };
      }
      return Reflect.get(target, prop);
    }
  }) : requestContext;
  const instructions = await agent.getInstructions({ requestContext: instructionsRequestContext });
  const llm = await agent.getLLM({ requestContext });
  const defaultGenerateOptionsLegacy = await agent.getDefaultGenerateOptionsLegacy({
    requestContext
  });
  const defaultStreamOptionsLegacy = await agent.getDefaultStreamOptionsLegacy({ requestContext });
  const defaultOptions = await agent.getDefaultOptions({ requestContext });
  const model = llm?.getModel();
  const supportsMemory = typeof agent.supportsMemory === "function" ? agent.supportsMemory() : true;
  const models = await agent.getModelList(requestContext);
  const modelList = models?.map((md) => ({
    ...md,
    model: {
      modelId: md.model.modelId,
      provider: md.model.provider,
      modelVersion: md.model.specificationVersion
    }
  }));
  const serializedAgentAgents = await getSerializedAgentDefinition({ agent, requestContext });
  let serializedInputProcessors = [];
  let serializedOutputProcessors = [];
  try {
    const configuredProcessorWorkflows = await agent.getConfiguredProcessorWorkflows();
    const inputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-input-processor"));
    const outputProcessorWorkflows = configuredProcessorWorkflows.filter((w) => w.id.endsWith("-output-processor"));
    serializedInputProcessors = getSerializedProcessors(inputProcessorWorkflows);
    serializedOutputProcessors = getSerializedProcessors(outputProcessorWorkflows);
  } catch (error) {
    mastra.getLogger().error("Error getting configured processors for agent", { agentName: agent.name, error });
  }
  const serializedSkills = await getSerializedSkillsFromAgent(agent, requestContext);
  const workspaceTools = await getWorkspaceToolsFromAgent(agent, requestContext);
  const browserTools = getBrowserToolsFromAgent(agent, createBrowserToolsErrorLogger(mastra.getLogger(), agent.id));
  let workspaceId;
  try {
    const workspace = await agent.getWorkspace({ requestContext });
    workspaceId = workspace?.id;
  } catch {
  }
  let serializedRequestContextSchema;
  if (agent.requestContextSchema) {
    try {
      serializedRequestContextSchema = stringify(zodToJsonSchema(agent.requestContextSchema));
    } catch (error) {
      mastra.getLogger().error("Error serializing requestContextSchema for agent", { agentName: agent.name, error });
    }
  }
  return {
    name: agent.name,
    description,
    metadata,
    instructions,
    tools: serializedAgentTools,
    agents: serializedAgentAgents,
    workflows: serializedAgentWorkflows,
    skills: serializedSkills,
    workspaceTools,
    browserTools,
    workspaceId,
    inputProcessors: serializedInputProcessors,
    outputProcessors: serializedOutputProcessors,
    provider: typeof agent.model === "string" ? parseModelString(agent.model).provider ?? llm?.getProvider() : llm?.getProvider(),
    modelId: typeof agent.model === "string" ? parseModelString(agent.model).modelId : llm?.getModelId(),
    modelVersion: model?.specificationVersion,
    supportsMemory,
    modelList,
    defaultOptions,
    defaultGenerateOptionsLegacy,
    defaultStreamOptionsLegacy,
    requestContextSchema: serializedRequestContextSchema,
    source: agent.source ?? "code",
    editor: agent.__getEditorConfig?.(),
    ...agent.toRawConfig()?.status ? { status: agent.toRawConfig().status } : {}
  };
}
var LIST_AGENTS_ROUTE = 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: MastraFGAPermissions.AGENTS_READ,
  handler: async ({ mastra, requestContext, partial }) => {
    try {
      const codeAgents = mastra.listAgents();
      const isPartial = partial === "true";
      const editor = mastra.getEditor?.();
      const logger = mastra.getLogger();
      const serializedCodeAgentsMap = await Promise.allSettled(
        Object.entries(codeAgents).map(async ([id, agent]) => {
          let mergedAgent = agent;
          if (editor) {
            try {
              mergedAgent = await editor.agent.applyStoredOverrides(agent, void 0, requestContext);
            } catch {
            }
          }
          return formatAgentList({ id, mastra, agent: mergedAgent, requestContext, partial: isPartial });
        })
      );
      const serializedAgents = {};
      for (let i = 0; i < serializedCodeAgentsMap.length; i++) {
        const settled = serializedCodeAgentsMap[i];
        if (settled.status === "fulfilled") {
          const { id, ...rest } = settled.value;
          serializedAgents[id] = { id, ...rest };
        } else {
          const agentId = Object.keys(codeAgents)[i];
          logger.warn("Failed to serialize agent", { agentId, error: settled.reason });
        }
      }
      try {
        const editor2 = mastra.getEditor();
        let storedAgentsResult;
        try {
          storedAgentsResult = await editor2?.agent.list();
        } catch (error) {
          console.error("Error listing stored agents:", error);
          storedAgentsResult = null;
        }
        const codeAgentIds = /* @__PURE__ */ new Set();
        for (const [key, agent] of Object.entries(codeAgents)) {
          codeAgentIds.add(key);
          if (agent?.id) codeAgentIds.add(agent.id);
        }
        if (storedAgentsResult?.agents) {
          for (const storedAgentConfig of storedAgentsResult.agents) {
            if (codeAgentIds.has(storedAgentConfig.id)) continue;
            try {
              const agent = await editor2?.agent.getById(storedAgentConfig.id, { status: "draft" });
              if (!agent) continue;
              const serialized = await formatAgentList({
                id: agent.id,
                mastra,
                agent,
                requestContext,
                partial: isPartial
              });
              if (!serializedAgents[serialized.id]) {
                serializedAgents[serialized.id] = serialized;
              }
            } catch (agentError) {
              const logger2 = mastra.getLogger();
              logger2.warn("Failed to serialize stored agent", { agentId: storedAgentConfig.id, error: agentError });
            }
          }
        }
      } catch (storageError) {
        const logger2 = mastra.getLogger();
        logger2.debug("Could not fetch stored agents", { error: storageError });
      }
      const fgaProvider = mastra.getServer?.()?.fga;
      const user = requestContext?.get("user");
      if (fgaProvider && user) {
        const agentList = Object.values(serializedAgents);
        const accessible = await fgaProvider.filterAccessible(
          user,
          agentList,
          "agent",
          MastraFGAPermissions.AGENTS_READ
        );
        const accessibleSet = new Set(accessible.map((a) => a.id));
        for (const id of Object.keys(serializedAgents)) {
          if (!accessibleSet.has(id)) {
            delete serializedAgents[id];
          }
        }
      }
      return serializedAgents;
    } catch (error) {
      return handleError(error, "Error getting agents");
    }
  }
});
var GET_AGENT_BY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/agents/:agentId",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  queryParamSchema: agentVersionQuerySchema,
  responseSchema: 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: MastraFGAPermissions.AGENTS_READ,
  handler: async ({ agentId, mastra, requestContext, status, versionId }) => {
    try {
      const versionOptions = versionId ? { versionId } : status ? { status } : void 0;
      const agent = await getAgentFromSystem({ mastra, agentId, versionOptions, requestContext });
      const isStudio = getIsStudioFromContext(requestContext);
      const result = await formatAgent({
        mastra,
        agent,
        requestContext,
        isStudio
      });
      return result;
    } catch (error) {
      return 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,
        versionOptions: extractVersionOptions(requestContext)
      });
      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: MastraFGAPermissions.AGENTS_EXECUTE,
  handler: async ({ agentId, mastra, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
      validateBody({ messages });
      const versionOptions = extractVersionOptions(
        serverRequestContext,
        bodyRequestContext
      );
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions,
        requestContext: serverRequestContext
      });
      mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
      stashVersionOverrides(serverRequestContext, versions);
      ensureDefaultVersionStatus(serverRequestContext, versionOptions);
      let authorizedMemoryOption = memoryOption;
      if (memoryOption) {
        const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
        const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);
        const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
        if (effectiveThreadId) {
          const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
          if (memoryInstance) {
            const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
            if (thread) {
              await enforceThreadAccess({
                mastra,
                requestContext: serverRequestContext,
                threadId: effectiveThreadId,
                thread,
                effectiveResourceId,
                permission: MastraFGAPermissions.MEMORY_WRITE
              });
            }
          }
        }
        authorizedMemoryOption = {
          ...memoryOption,
          resource: effectiveResourceId ?? memoryOption.resource,
          thread: effectiveThreadId ?? memoryOption.thread
        };
      }
      const { structuredOutput, ...restOptions } = rest;
      const options = {
        ...restOptions,
        requestContext: serverRequestContext,
        memory: authorizedMemoryOption,
        abortSignal
      };
      const result = structuredOutput ? await agent.generate(messages, { ...options, structuredOutput }) : await agent.generate(messages, options);
      return result;
    } catch (error) {
      return 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,
        versionOptions: extractVersionOptions(requestContext),
        requestContext
      });
      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) {
        const memory = await agent.getMemory({ requestContext });
        if (memory) {
          const thread = await memory.getThreadById({ threadId: effectiveThreadId });
          if (thread) {
            await enforceThreadAccess({
              mastra,
              requestContext,
              threadId: effectiveThreadId,
              thread,
              effectiveResourceId,
              permission: MastraFGAPermissions.MEMORY_WRITE
            });
          }
        }
      }
      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,
        versionOptions: extractVersionOptions(requestContext),
        requestContext
      });
      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) {
        const memory = await agent.getMemory({ requestContext });
        if (memory) {
          const thread = await memory.getThreadById({ threadId: effectiveThreadId });
          if (thread) {
            await enforceThreadAccess({
              mastra,
              requestContext,
              threadId: effectiveThreadId,
              thread,
              effectiveResourceId,
              permission: MastraFGAPermissions.MEMORY_WRITE
            });
          }
        }
      }
      const streamResult = await agent.streamLegacy(messages, {
        ...rest,
        abortSignal,
        resourceId: effectiveResourceId ?? "",
        threadId: effectiveThreadId ?? ""
      });
      const streamResponse = rest.output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
        sendUsage: true,
        sendReasoning: true,
        getErrorMessage: (error) => {
          if (error instanceof Error) {
            const safeMessage = error.message.replace(/([A-Za-z]:)?[\/][^\s,)]+/g, "<path>").replace(/\s+at\s+[^\n]*/g, "").replace(/Response body:.*/s, "").trim();
            return `An error occurred while processing your request. ${safeMessage || "Unknown error"}`;
          }
          return "An error occurred while processing your request.";
        }
      });
      return streamResponse;
    } catch (error) {
      return handleError(error, "error streaming agent response");
    }
  }
});
async function buildProvidersList(mastra) {
  const allProviders = {};
  const blockExternalProviders = process.env.AUTO_BLOCK_EXTERNAL_PROVIDERS === "true" || process.env.AUTO_BLOCK_EXTERNAL_PROVIDERS === "1";
  const defaultGatewayIds = new Set(defaultGateways.map((gateway) => gateway.id));
  if (!blockExternalProviders) {
    for (const [id, provider] of Object.entries(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;
        if (blockExternalProviders && defaultGatewayIds.has(gateway.id)) continue;
        try {
          const gatewayProviders = await gateway.fetchProviders();
          for (const [providerId, config] of Object.entries(gatewayProviders)) {
            const prefixedId = providerId === gateway.id ? gateway.id : `${gateway.id}/${providerId}`;
            if (!(prefixedId in allProviders)) {
              allProviders[prefixedId] = config;
            }
          }
        } catch (error) {
          console.warn(`Failed to fetch providers from gateway "${gateway.id}":`, error);
        }
      }
    }
  }
  return Object.entries(allProviders).map(([id, provider]) => {
    return {
      id,
      name: provider.name,
      label: provider.label || provider.name,
      description: provider.description || "",
      envVar: provider.apiKeyEnvVar,
      connected: isProviderConnected(id, allProviders),
      docUrl: provider.docUrl,
      models: [...provider.models]
    };
  });
}
var GET_PROVIDERS_ROUTE = 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,
  requiresPermission: ["agents:read"],
  handler: async ({ mastra }) => {
    try {
      const providers = await buildProvidersList(mastra);
      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: MastraFGAPermissions.AGENTS_EXECUTE,
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, versions, ...rest } = params;
      validateBody({ messages });
      const versionOptions = extractVersionOptions(
        serverRequestContext,
        bodyRequestContext
      );
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions,
        requestContext: serverRequestContext
      });
      mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
      stashVersionOverrides(serverRequestContext, versions);
      ensureDefaultVersionStatus(serverRequestContext, versionOptions);
      let authorizedMemoryOption = memoryOption;
      if (memoryOption) {
        const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
        const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption.resource);
        const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
        if (effectiveThreadId) {
          const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
          if (memoryInstance) {
            const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
            if (thread) {
              await enforceThreadAccess({
                mastra,
                requestContext: serverRequestContext,
                threadId: effectiveThreadId,
                thread,
                effectiveResourceId,
                permission: MastraFGAPermissions.MEMORY_WRITE
              });
            }
          }
        }
        authorizedMemoryOption = {
          ...memoryOption,
          resource: effectiveResourceId ?? memoryOption.resource,
          thread: effectiveThreadId ?? memoryOption.thread
        };
      }
      const { structuredOutput, untilIdle, ...restOptions } = rest;
      const options = {
        ...restOptions,
        requestContext: serverRequestContext,
        memory: authorizedMemoryOption,
        abortSignal
      };
      if (untilIdle) {
        options.untilIdle = untilIdle;
      }
      const streamResult = structuredOutput ? await agent.stream(messages, { ...options, structuredOutput }) : await agent.stream(messages, options);
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error streaming agent response");
    }
  }
});
var sendAgentSignalResponseSchema = z.object({
  accepted: z.literal(true),
  runId: z.string(),
  signal: z.any().optional()
});
function handleSignalRoutingError(error, defaultMessage) {
  if (error instanceof MastraError && error.category === ErrorCategory.USER && !error.status && !error.details?.status) {
    throw new HTTPException(400, { message: error.message, cause: error });
  }
  return handleError(error, defaultMessage);
}
var sendAgentMessageResponseSchema = sendAgentSignalResponseSchema;
var SEND_AGENT_SIGNAL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/signals",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: sendAgentSignalBodySchema,
  responseSchema: sendAgentSignalResponseSchema,
  summary: "Send agent signal",
  description: "Sends a signal to an active agent run or starts a memory thread run when the thread is idle",
  tags: ["Agents", "Streaming"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async ({
    mastra,
    agentId,
    requestContext: serverRequestContext,
    signal,
    runId,
    resourceId,
    threadId,
    ifActive,
    ifIdle
  }) => {
    try {
      const idleStreamOptions = ifIdle?.streamOptions;
      const bodyRequestContext = idleStreamOptions?.requestContext;
      mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
      const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions,
        requestContext: serverRequestContext
      });
      stashVersionOverrides(serverRequestContext, idleStreamOptions?.versions);
      ensureDefaultVersionStatus(serverRequestContext, versionOptions);
      const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
      const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
      const ifIdleWithContext = {
        ifIdle: {
          ...ifIdle ?? {},
          streamOptions: { ...idleStreamOptions ?? {}, requestContext: serverRequestContext }
        }
      };
      if (effectiveThreadId && effectiveResourceId) {
        const memory = await agent.getMemory({ requestContext: serverRequestContext });
        if (memory) {
          const thread = await memory.getThreadById({ threadId: effectiveThreadId });
          await validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      if (typeof agent.sendSignal !== "function") {
        throw new HTTPException(501, { message: "agent signals are not supported by this Mastra core version" });
      }
      const agentSignal = signal;
      if (runId) {
        const result2 = await agent.sendSignal(agentSignal, {
          runId,
          ...effectiveResourceId ? { resourceId: effectiveResourceId } : {},
          ...effectiveThreadId ? { threadId: effectiveThreadId } : {},
          ...ifActive ? { ifActive } : {}
        });
        const settled2 = await result2.accepted;
        const settledRunId2 = "runId" in settled2 ? settled2.runId : runId;
        return result2.signal === void 0 ? { accepted: true, runId: settledRunId2 } : { accepted: true, runId: settledRunId2, signal: result2.signal };
      }
      if (!effectiveResourceId || !effectiveThreadId) {
        throw new HTTPException(400, { message: "resourceId and threadId are required when runId is not provided" });
      }
      const result = await agent.sendSignal(agentSignal, {
        resourceId: effectiveResourceId,
        threadId: effectiveThreadId,
        ...ifActive ? { ifActive } : {},
        ...ifIdleWithContext
      });
      const settled = await result.accepted;
      const settledRunId = "runId" in settled ? settled.runId : result.signal?.id;
      return result.signal === void 0 ? { accepted: true, runId: settledRunId } : { accepted: true, runId: settledRunId, signal: result.signal };
    } catch (error) {
      return handleSignalRoutingError(error, "error sending agent signal");
    }
  }
});
async function handleAgentMessageRoute({
  mastra,
  agentId,
  requestContext: serverRequestContext,
  message,
  runId,
  resourceId,
  threadId,
  ifActive,
  ifIdle,
  methodName
}) {
  const idleStreamOptions = ifIdle?.streamOptions;
  const bodyRequestContext = idleStreamOptions?.requestContext;
  mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
  const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
  const agent = await getAgentFromSystem({
    mastra,
    agentId,
    versionOptions,
    requestContext: serverRequestContext
  });
  stashVersionOverrides(serverRequestContext, idleStreamOptions?.versions);
  ensureDefaultVersionStatus(serverRequestContext, versionOptions);
  const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
  const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
  const ifIdleWithContext = {
    ifIdle: {
      ...ifIdle ?? {},
      streamOptions: { ...idleStreamOptions ?? {}, requestContext: serverRequestContext }
    }
  };
  if (effectiveThreadId && effectiveResourceId) {
    const memory = await agent.getMemory({ requestContext: serverRequestContext });
    if (memory) {
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      await validateThreadOwnership(thread, effectiveResourceId);
    }
  }
  if (typeof agent[methodName] !== "function") {
    throw new HTTPException(501, { message: `agent ${methodName} is not supported by this Mastra core version` });
  }
  if (runId) {
    const result2 = await agent[methodName](message, {
      runId,
      ...effectiveResourceId ? { resourceId: effectiveResourceId } : {},
      ...effectiveThreadId ? { threadId: effectiveThreadId } : {},
      ...ifActive ? { ifActive } : {}
    });
    const settled2 = await result2.accepted;
    const settledRunId2 = settled2 && "runId" in settled2 ? settled2.runId : runId;
    return result2.signal === void 0 ? { accepted: true, runId: settledRunId2 } : { accepted: true, runId: settledRunId2, signal: result2.signal };
  }
  if (!effectiveResourceId || !effectiveThreadId) {
    throw new HTTPException(400, { message: "resourceId and threadId are required when runId is not provided" });
  }
  const result = await agent[methodName](message, {
    resourceId: effectiveResourceId,
    threadId: effectiveThreadId,
    ...ifActive ? { ifActive } : {},
    ...ifIdleWithContext
  });
  const settled = await result.accepted;
  const settledRunId = settled && "runId" in settled ? settled.runId : result.signal?.id;
  return result.signal === void 0 ? { accepted: true, runId: settledRunId } : { accepted: true, runId: settledRunId, signal: result.signal };
}
var SEND_AGENT_MESSAGE_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/send-message",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: sendAgentMessageBodySchema,
  responseSchema: sendAgentMessageResponseSchema,
  summary: "Send agent message",
  description: "Sends a user message to an active agent run or starts a memory thread run when the thread is idle",
  tags: ["Agents", "Streaming"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async (params) => {
    try {
      return await handleAgentMessageRoute({ ...params, methodName: "sendMessage" });
    } catch (error) {
      return handleSignalRoutingError(error, "error sending agent message");
    }
  }
});
var QUEUE_AGENT_MESSAGE_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/queue-message",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: queueAgentMessageBodySchema,
  responseSchema: sendAgentMessageResponseSchema,
  summary: "Queue agent message",
  description: "Queues a user message to run after the active thread run completes, or starts a memory thread run when idle",
  tags: ["Agents", "Streaming"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async (params) => {
    try {
      return await handleAgentMessageRoute({ ...params, methodName: "queueMessage" });
    } catch (error) {
      return handleSignalRoutingError(error, "error queueing agent message");
    }
  }
});
var ABORT_AGENT_THREAD_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/threads/abort",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: abortAgentThreadBodySchema,
  responseSchema: abortAgentThreadResponseSchema,
  summary: "Abort active agent thread run",
  description: "Aborts the currently active stream run for a memory thread without changing thread subscriptions",
  tags: ["Agents", "Streaming"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async ({ mastra, agentId, resourceId, threadId, requestContext: serverRequestContext }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId, requestContext: serverRequestContext });
      if (typeof agent.abortThreadStream !== "function") {
        throw new HTTPException(501, {
          message: "agent thread aborts are not supported by this Mastra core version"
        });
      }
      const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
      const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
      if (!effectiveThreadId) {
        throw new HTTPException(400, { message: "threadId is required" });
      }
      if (effectiveResourceId) {
        const memory = await agent.getMemory({ requestContext: serverRequestContext });
        if (memory) {
          const thread = await memory.getThreadById({ threadId: effectiveThreadId });
          await validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      const aborted = await agent.abortThreadStream({ resourceId: effectiveResourceId, threadId: effectiveThreadId });
      return { aborted };
    } catch (error) {
      return handleError(error, "error aborting agent thread");
    }
  }
});
var SUBSCRIBE_AGENT_THREAD_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/threads/subscribe",
  responseType: "stream",
  streamFormat: "sse",
  sseFlushOnConnect: true,
  pathParamSchema: agentIdPathParams,
  bodySchema: subscribeAgentThreadBodySchema,
  responseSchema: streamResponseSchema,
  summary: "Subscribe to agent thread runs",
  description: "Subscribes to future and active stream runs for a memory thread",
  tags: ["Agents", "Streaming"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async ({ mastra, agentId, resourceId, threadId, abortSignal, requestContext: serverRequestContext }) => {
    try {
      const agent = await getAgentFromSystem({ mastra, agentId, requestContext: serverRequestContext });
      if (typeof agent.subscribeToThread !== "function") {
        throw new HTTPException(501, {
          message: "agent thread subscriptions are not supported by this Mastra core version"
        });
      }
      const effectiveResourceId = getEffectiveResourceId(serverRequestContext, resourceId);
      const effectiveThreadId = getEffectiveThreadId(serverRequestContext, threadId);
      if (!effectiveThreadId) {
        throw new HTTPException(400, { message: "threadId is required" });
      }
      if (effectiveResourceId) {
        const memory = await agent.getMemory({ requestContext: serverRequestContext });
        if (memory) {
          const thread = await memory.getThreadById({ threadId: effectiveThreadId });
          await validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      const subscription = await agent.subscribeToThread({
        resourceId: effectiveResourceId,
        threadId: effectiveThreadId
      });
      let cleanedUp = false;
      let heartbeat;
      const clearHeartbeat = () => {
        if (heartbeat) {
          clearTimeout(heartbeat);
          heartbeat = void 0;
        }
      };
      const cleanup = (closeController) => {
        if (cleanedUp) return;
        cleanedUp = true;
        clearHeartbeat();
        subscription.unsubscribe();
        if (closeController) {
          try {
            closeController.close();
          } catch {
          }
        }
      };
      return new ReadableStream({
        async start(controller) {
          const scheduleHeartbeat = () => {
            if (cleanedUp) return;
            clearHeartbeat();
            heartbeat = setTimeout(() => {
              heartbeat = void 0;
              if (cleanedUp) return;
              try {
                controller.enqueue(": heartbeat\n\n");
              } catch {
                cleanup();
                return;
              }
              scheduleHeartbeat();
            }, 25e3);
          };
          const abortCleanup = () => cleanup(controller);
          abortSignal?.addEventListener("abort", abortCleanup, { once: true });
          scheduleHeartbeat();
          try {
            for await (const part of subscription.stream) {
              controller.enqueue(part);
              scheduleHeartbeat();
            }
            cleanup(controller);
          } catch (error) {
            cleanup();
            controller.error(error);
          } finally {
            clearHeartbeat();
            abortSignal?.removeEventListener("abort", abortCleanup);
          }
        },
        cancel() {
          cleanup();
        }
      });
    } catch (error) {
      return handleError(error, "error subscribing to agent thread");
    }
  }
});
var STREAM_UNTIL_IDLE_GENERATE_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/stream-until-idle",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: streamUntilIdleBodySchema,
  responseSchema: 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: MastraFGAPermissions.AGENTS_EXECUTE,
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      sanitizeBody(params, ["tools"]);
      const { messages, memory: memoryOption, requestContext: bodyRequestContext, ...rest } = params;
      validateBody({ messages });
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(
          serverRequestContext,
          bodyRequestContext
        ),
        requestContext: serverRequestContext
      });
      mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
      let authorizedMemoryOption = memoryOption;
      if (memoryOption) {
        const clientThreadId = typeof memoryOption.thread === "string" ? memoryOption.thread : memoryOption.thread?.id;
        const effectiveResourceId = 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 { 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 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 OBSERVE_AGENT_STREAM_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/observe",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: observeAgentBodySchema,
  responseSchema: observeAgentResponseSchema,
  summary: "Observe agent stream",
  description: "Reconnect to an existing agent stream to receive missed events. Supports position-based resume with offset for efficient reconnection.",
  tags: ["Agents", "Streaming"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, runId, offset, abortSignal }) => {
    try {
      let cleanup2 = function(controller) {
        if (idleTimer) {
          clearTimeout(idleTimer);
          idleTimer = null;
        }
        if (handleEvent) {
          void pubsub.unsubscribe(topic, handleEvent);
          handleEvent = null;
        }
        try {
          controller.close();
        } catch {
        }
      }, resetIdleTimer2 = function(controller) {
        if (idleTimer) clearTimeout(idleTimer);
        idleTimer = setTimeout(() => cleanup2(controller), IDLE_TIMEOUT_MS);
      };
      const agent = await getAgentFromSystem({ mastra, agentId });
      const agentPubsub = isDurableAgentLike(agent) ? agent.pubsub : void 0;
      const pubsub = agentPubsub ?? mastra.pubsub;
      const topic = AGENT_STREAM_TOPIC(runId);
      let handleEvent = null;
      let idleTimer = null;
      const IDLE_TIMEOUT_MS = 5 * 60 * 1e3;
      const stream = new ReadableStream({
        start(controller) {
          if (abortSignal) {
            if (abortSignal.aborted) {
              cleanup2(controller);
              return;
            }
            abortSignal.addEventListener("abort", () => cleanup2(controller), { once: true });
          }
          resetIdleTimer2(controller);
          handleEvent = (event) => {
            const isTerminal = event.type === "finish" || event.type === "error";
            try {
              controller.enqueue(event);
            } catch {
            }
            if (isTerminal) {
              cleanup2(controller);
            } else {
              resetIdleTimer2(controller);
            }
          };
          const subscribePromise = offset !== void 0 ? pubsub.subscribeFromOffset(topic, offset, handleEvent) : pubsub.subscribeWithReplay(topic, handleEvent);
          subscribePromise.catch((error) => {
            console.error(`[ObserveAgentStream] Failed to subscribe to ${topic}:`, error);
            if (idleTimer) {
              clearTimeout(idleTimer);
              idleTimer = null;
            }
            controller.error(error);
          });
        },
        cancel() {
          if (idleTimer) {
            clearTimeout(idleTimer);
            idleTimer = null;
          }
          if (handleEvent) {
            void pubsub.unsubscribe(topic, handleEvent);
            handleEvent = null;
          }
        }
      });
      return stream;
    } catch (error) {
      return handleError(error, "error observing agent stream");
    }
  }
});
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, requestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      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,
        requestContext,
        abortSignal
      });
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error approving tool call");
    }
  }
});
async function validateSubscriptionToolCallThreadAccess({
  agent,
  requestContext,
  resourceId,
  threadId
}) {
  const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
  const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
  if (!effectiveThreadId) {
    throw new HTTPException(400, { message: "threadId is required" });
  }
  if (effectiveResourceId) {
    const memory = await agent.getMemory({ requestContext });
    if (memory) {
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      await validateThreadOwnership(thread, effectiveResourceId);
    }
  }
  return { effectiveResourceId: effectiveResourceId ?? "", effectiveThreadId };
}
var SEND_TOOL_APPROVAL_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/send-tool-approval",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  bodySchema: sendToolApprovalBodySchema,
  responseSchema: sendToolApprovalResponseSchema,
  summary: "Send tool approval",
  description: "Approves or declines a pending tool call and publishes resumed chunks to thread subscribers",
  tags: ["Agents", "Tools"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      const bodyRequestContext = params.requestContext;
      const versionOptions = extractVersionOptions(serverRequestContext, bodyRequestContext);
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions,
        requestContext: serverRequestContext
      });
      if (!params.toolCallId) {
        throw new HTTPException(400, { message: "Tool call id is required" });
      }
      mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
      sanitizeBody(params, ["tools"]);
      const { effectiveResourceId, effectiveThreadId } = await validateSubscriptionToolCallThreadAccess({
        agent,
        requestContext: serverRequestContext,
        resourceId: params.resourceId,
        threadId: params.threadId
      });
      return await agent.sendToolApproval({
        ...params,
        resourceId: effectiveResourceId,
        threadId: effectiveThreadId,
        requestContext: serverRequestContext,
        abortSignal
      });
    } catch (error) {
      return handleError(error, "error sending tool approval");
    }
  }
});
var LIST_SUSPENDED_RUNS_ROUTE = createRoute({
  method: "GET",
  path: "/agents/:agentId/suspended-runs",
  responseType: "json",
  pathParamSchema: agentIdPathParams,
  queryParamSchema: listSuspendedRunsQuerySchema,
  responseSchema: listSuspendedRunsResponseSchema,
  summary: "List suspended runs",
  description: "Lists suspended agent runs from storage \u2014 runs waiting on a tool-call approval or on a tool that suspended. Works after a server restart and across instances.",
  tags: ["Agents", "Tools"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, requestContext, ...query }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      const effectiveResourceId = getEffectiveResourceId(requestContext, query.resourceId);
      const effectiveThreadId = getEffectiveThreadId(requestContext, query.threadId);
      if (effectiveThreadId) {
        const memory = await agent.getMemory({ requestContext });
        if (!memory) {
          throw new HTTPException(403, {
            message: "Access denied: agent has no memory configured to validate thread ownership"
          });
        }
        const thread = await memory.getThreadById({ threadId: effectiveThreadId });
        if (!thread) {
          throw new HTTPException(403, { message: "Access denied: thread not found" });
        }
        await enforceThreadAccess({
          mastra,
          requestContext,
          threadId: effectiveThreadId,
          thread,
          effectiveResourceId
        });
      }
      return await agent.listSuspendedRuns({
        threadId: effectiveThreadId,
        resourceId: effectiveResourceId,
        fromDate: query.fromDate,
        toDate: query.toDate,
        perPage: query.perPage,
        page: query.page
      });
    } catch (error) {
      return handleError(error, "error listing suspended runs");
    }
  }
});
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, requestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      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,
        requestContext,
        abortSignal
      });
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error declining tool call");
    }
  }
});
var RESUME_STREAM_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/resume-stream",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: resumeStreamBodySchema,
  responseSchema: streamResponseSchema,
  summary: "Resume agent stream",
  description: "Resumes a suspended agent stream with custom resume data",
  tags: ["Agents"],
  requiresAuth: true,
  requiresPermission: MastraFGAPermissions.AGENTS_EXECUTE,
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const {
        resumeData,
        runId,
        toolCallId,
        memory: memoryOption,
        requestContext: bodyRequestContext,
        versions,
        ...rest
      } = params;
      const versionOptions = extractVersionOptions(
        serverRequestContext,
        bodyRequestContext
      );
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions
      });
      mergeBodyRequestContext(serverRequestContext, bodyRequestContext);
      stashVersionOverrides(serverRequestContext, versions);
      ensureDefaultVersionStatus(serverRequestContext, versionOptions);
      let authorizedMemoryOption = memoryOption;
      const clientThreadId = typeof memoryOption?.thread === "string" ? memoryOption.thread : memoryOption?.thread?.id;
      const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption?.resource);
      const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
      if (effectiveThreadId) {
        const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
        if (memoryInstance) {
          const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
          if (thread) {
            await enforceThreadAccess({
              mastra,
              requestContext: serverRequestContext,
              threadId: effectiveThreadId,
              thread,
              effectiveResourceId,
              permission: MastraFGAPermissions.MEMORY_WRITE
            });
          }
        }
      }
      if (memoryOption || effectiveResourceId || effectiveThreadId) {
        authorizedMemoryOption = {
          ...memoryOption,
          ...effectiveResourceId ? { resource: effectiveResourceId } : {},
          ...effectiveThreadId ? { thread: effectiveThreadId } : {}
        };
      }
      const workflowsStore = await mastra.getStorage()?.getStore("workflows");
      const workflowRun = await workflowsStore?.getWorkflowRunById({ workflowName: "agentic-loop", runId });
      await validateRunOwnership(workflowRun, getEffectiveResourceId(serverRequestContext, void 0));
      const { structuredOutput, untilIdle, ...restOptions } = rest;
      const options = {
        runId,
        toolCallId,
        ...restOptions,
        requestContext: serverRequestContext,
        memory: authorizedMemoryOption,
        abortSignal
      };
      if (untilIdle) {
        options.untilIdle = untilIdle;
      }
      const streamResult = structuredOutput ? await agent.resumeStream(resumeData, { ...options, structuredOutput }) : await agent.resumeStream(resumeData, options);
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error resuming agent stream");
    }
  }
});
var RESUME_STREAM_UNTIL_IDLE_ROUTE = createRoute({
  method: "POST",
  path: "/agents/:agentId/resume-stream-until-idle",
  responseType: "stream",
  streamFormat: "sse",
  pathParamSchema: agentIdPathParams,
  bodySchema: resumeStreamUntilIdleBodySchema,
  responseSchema: streamResponseSchema,
  summary: "Resume agent stream until idle",
  description: "Resumes a suspended agent stream until idle with custom resume data, also listens for background task completions and streams them in real-time",
  tags: ["Agents"],
  requiresAuth: true,
  requiresPermission: "agents:execute",
  handler: async ({ mastra, agentId, abortSignal, requestContext: serverRequestContext, ...params }) => {
    try {
      if (!params.runId) {
        throw new HTTPException(400, { message: "Run id is required" });
      }
      sanitizeBody(params, ["tools"]);
      const {
        resumeData,
        runId,
        toolCallId,
        memory: memoryOption,
        requestContext: bodyRequestContext,
        versions,
        ...rest
      } = params;
      const versionOptions = extractVersionOptions(
        serverRequestContext,
        bodyRequestContext
      );
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions
      });
      if (bodyRequestContext && typeof bodyRequestContext === "object") {
        for (const [key, value] of Object.entries(bodyRequestContext)) {
          if (serverRequestContext.get(key) === void 0) {
            serverRequestContext.set(key, value);
          }
        }
      }
      stashVersionOverrides(serverRequestContext, versions);
      ensureDefaultVersionStatus(serverRequestContext, versionOptions);
      let authorizedMemoryOption = memoryOption;
      const clientThreadId = typeof memoryOption?.thread === "string" ? memoryOption.thread : memoryOption?.thread?.id;
      const effectiveResourceId = getEffectiveResourceId(serverRequestContext, memoryOption?.resource);
      const effectiveThreadId = getEffectiveThreadId(serverRequestContext, clientThreadId);
      if (effectiveThreadId) {
        const memoryInstance = await agent.getMemory({ requestContext: serverRequestContext });
        if (memoryInstance) {
          const thread = await memoryInstance.getThreadById({ threadId: effectiveThreadId });
          if (thread) {
            await enforceThreadAccess({
              mastra,
              requestContext: serverRequestContext,
              threadId: effectiveThreadId,
              thread,
              effectiveResourceId,
              permission: MastraFGAPermissions.MEMORY_WRITE
            });
          }
        }
      }
      if (memoryOption || effectiveResourceId || effectiveThreadId) {
        authorizedMemoryOption = {
          ...memoryOption,
          ...effectiveResourceId ? { resource: effectiveResourceId } : {},
          ...effectiveThreadId ? { thread: effectiveThreadId } : {}
        };
      }
      const workflowsStore = await mastra.getStorage()?.getStore("workflows");
      const workflowRun = await workflowsStore?.getWorkflowRunById({ workflowName: "agentic-loop", runId });
      await validateRunOwnership(workflowRun, getEffectiveResourceId(serverRequestContext, void 0));
      const { structuredOutput, ...restOptions } = rest;
      const options = {
        runId,
        toolCallId,
        ...restOptions,
        requestContext: serverRequestContext,
        memory: authorizedMemoryOption,
        abortSignal
      };
      const streamResult = structuredOutput ? await agent.resumeStreamUntilIdle(resumeData, { ...options, structuredOutput }) : await agent.resumeStreamUntilIdle(resumeData, options);
      return streamResult.fullStream;
    } catch (error) {
      return handleError(error, "error resuming agent stream");
    }
  }
});
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, requestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      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,
        requestContext,
        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, requestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      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,
        requestContext,
        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, requestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      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, requestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      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, requestContext, ...params }) => {
    try {
      const agent = await getAgentFromSystem({
        mastra,
        agentId,
        versionOptions: extractVersionOptions(requestContext)
      });
      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,
  queryParamSchema: skillDisambiguationQuerySchema,
  responseSchema: getAgentSkillResponseSchema,
  summary: "Get agent skill",
  description: "Returns details for a specific skill available to the agent (inline or workspace)",
  tags: ["Agents", "Skills"],
  handler: async ({ mastra, agentId, skillName, path, requestContext }) => {
    try {
      const agent = agentId ? mastra.getAgentById(agentId) : null;
      if (!agent) {
        throw new HTTPException(404, { message: "Agent not found" });
      }
      const identifier = path ? decodeURIComponent(path) : skillName;
      const skill = await agent.getSkill(identifier, { requestContext });
      if (!skill) {
        throw new 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 handleError(error, "Error getting agent skill");
    }
  }
});

export { ABORT_AGENT_THREAD_ROUTE, 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, LIST_SUSPENDED_RUNS_ROUTE, OBSERVE_AGENT_STREAM_ROUTE, QUEUE_AGENT_MESSAGE_ROUTE, REORDER_AGENT_MODEL_LIST_ROUTE, RESET_AGENT_MODEL_ROUTE, RESUME_STREAM_ROUTE, RESUME_STREAM_UNTIL_IDLE_ROUTE, SEND_AGENT_MESSAGE_ROUTE, SEND_AGENT_SIGNAL_ROUTE, SEND_TOOL_APPROVAL_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_UNTIL_IDLE_GENERATE_ROUTE, STREAM_VNEXT_DEPRECATED_ROUTE, SUBSCRIBE_AGENT_THREAD_ROUTE, UPDATE_AGENT_MODEL_IN_MODEL_LIST_ROUTE, UPDATE_AGENT_MODEL_ROUTE, agents_exports, buildProvidersList, extractVersionOptions, getAgentFromSystem, getBrowserToolsFromAgent, getSerializedAgentTools, getSerializedProcessors, getSerializedSkillsFromAgent, getWorkspaceToolsFromAgent, isProviderConnected };
//# sourceMappingURL=chunk-5NBDNR2B.js.map
//# sourceMappingURL=chunk-5NBDNR2B.js.map