import { listStoredAgentsResponseSchema, listStoredAgentsQuerySchema, getStoredAgentResponseSchema, storedAgentIdPathParams, createStoredAgentResponseSchema, createStoredAgentBodySchema, updateStoredAgentResponseSchema, updateStoredAgentBodySchema, handleAutoVersioning, deleteStoredAgentResponseSchema } from './chunk-SYLEQ6LR.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-OQ5GQJAS.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';

// src/server/handlers/stored-agents.ts
var LIST_STORED_AGENTS_ROUTE = createRoute({
  method: "GET",
  path: "/stored/agents",
  responseType: "json",
  queryParamSchema: listStoredAgentsQuerySchema,
  responseSchema: listStoredAgentsResponseSchema,
  summary: "List stored agents",
  description: "Returns a paginated list of all agents stored in the database",
  tags: ["Stored Agents"],
  requiresAuth: true,
  handler: async ({ mastra, page, perPage, orderBy, authorId, metadata }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const result = await agentsStore.listAgentsResolved({
        page,
        perPage,
        orderBy,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return handleError(error, "Error listing stored agents");
    }
  }
});
var GET_STORED_AGENT_ROUTE = createRoute({
  method: "GET",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: storedAgentIdPathParams,
  responseSchema: getStoredAgentResponseSchema,
  summary: "Get stored agent by ID",
  description: "Returns a specific agent from storage by its unique identifier (resolved with active version config)",
  tags: ["Stored Agents"],
  requiresAuth: true,
  handler: async ({ mastra, storedAgentId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const agent = await agentsStore.getAgentByIdResolved({ id: storedAgentId });
      if (!agent) {
        throw new HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });
      }
      return agent;
    } catch (error) {
      return handleError(error, "Error getting stored agent");
    }
  }
});
var CREATE_STORED_AGENT_ROUTE = createRoute({
  method: "POST",
  path: "/stored/agents",
  responseType: "json",
  bodySchema: createStoredAgentBodySchema,
  responseSchema: createStoredAgentResponseSchema,
  summary: "Create stored agent",
  description: "Creates a new agent in storage with the provided configuration",
  tags: ["Stored Agents"],
  requiresAuth: true,
  handler: async ({
    mastra,
    id,
    authorId,
    metadata,
    name,
    description,
    instructions,
    model,
    tools,
    defaultOptions,
    workflows,
    agents,
    integrationTools,
    inputProcessors,
    outputProcessors,
    memory,
    scorers
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const existing = await agentsStore.getAgentById({ id });
      if (existing) {
        throw new HTTPException(409, { message: `Agent with id ${id} already exists` });
      }
      const toolsFromBody = Array.isArray(tools) ? tools : void 0;
      const integrationToolsFromBody = Array.isArray(integrationTools) ? integrationTools : void 0;
      await agentsStore.createAgent({
        agent: {
          id,
          authorId,
          metadata,
          name,
          description,
          instructions,
          model,
          tools: toolsFromBody,
          defaultOptions,
          workflows,
          agents,
          integrationTools: integrationToolsFromBody,
          inputProcessors,
          outputProcessors,
          memory,
          scorers
        }
      });
      const resolved = await agentsStore.getAgentByIdResolved({ id });
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve created agent" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error creating stored agent");
    }
  }
});
var UPDATE_STORED_AGENT_ROUTE = createRoute({
  method: "PATCH",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: storedAgentIdPathParams,
  bodySchema: updateStoredAgentBodySchema,
  responseSchema: updateStoredAgentResponseSchema,
  summary: "Update stored agent",
  description: "Updates an existing agent in storage with the provided fields",
  tags: ["Stored Agents"],
  requiresAuth: true,
  handler: async ({
    mastra,
    storedAgentId,
    // Metadata-level fields
    authorId,
    metadata,
    // Config fields (snapshot-level)
    name,
    description,
    instructions,
    model,
    tools,
    defaultOptions,
    workflows,
    agents,
    integrationTools,
    inputProcessors,
    outputProcessors,
    memory,
    scorers
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const existing = await agentsStore.getAgentById({ id: storedAgentId });
      if (!existing) {
        throw new HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });
      }
      const toolsFromBody = Array.isArray(tools) ? tools : void 0;
      const integrationToolsFromBody = Array.isArray(integrationTools) ? integrationTools : void 0;
      const updatedAgent = await agentsStore.updateAgent({
        id: storedAgentId,
        authorId,
        metadata,
        name,
        description,
        instructions,
        model,
        tools: toolsFromBody,
        defaultOptions,
        workflows,
        agents,
        integrationTools: integrationToolsFromBody,
        inputProcessors,
        outputProcessors,
        memory,
        scorers
      });
      const configFields = {
        name,
        description,
        instructions,
        model,
        tools: toolsFromBody,
        defaultOptions,
        workflows,
        agents,
        integrationTools: integrationToolsFromBody,
        inputProcessors,
        outputProcessors,
        memory,
        scorers
      };
      const providedConfigFields = Object.fromEntries(Object.entries(configFields).filter(([_, v]) => v !== void 0));
      await handleAutoVersioning(agentsStore, storedAgentId, existing, updatedAgent, providedConfigFields);
      mastra.clearStoredAgentCache(storedAgentId);
      const resolved = await agentsStore.getAgentByIdResolved({ id: storedAgentId });
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve updated agent" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error updating stored agent");
    }
  }
});
var DELETE_STORED_AGENT_ROUTE = createRoute({
  method: "DELETE",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: storedAgentIdPathParams,
  responseSchema: deleteStoredAgentResponseSchema,
  summary: "Delete stored agent",
  description: "Deletes an agent from storage by its unique identifier",
  tags: ["Stored Agents"],
  requiresAuth: true,
  handler: async ({ mastra, storedAgentId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const existing = await agentsStore.getAgentById({ id: storedAgentId });
      if (!existing) {
        throw new HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });
      }
      await agentsStore.deleteAgent({ id: storedAgentId });
      mastra.clearStoredAgentCache(storedAgentId);
      return { success: true, message: `Agent ${storedAgentId} deleted successfully` };
    } catch (error) {
      return handleError(error, "Error deleting stored agent");
    }
  }
});

export { CREATE_STORED_AGENT_ROUTE, DELETE_STORED_AGENT_ROUTE, GET_STORED_AGENT_ROUTE, LIST_STORED_AGENTS_ROUTE, UPDATE_STORED_AGENT_ROUTE };
//# sourceMappingURL=chunk-TEE5OFYW.js.map
//# sourceMappingURL=chunk-TEE5OFYW.js.map