'use strict';

var chunk2KMBCFTE_cjs = require('./chunk-2KMBCFTE.cjs');
var chunk2BIE3CHY_cjs = require('./chunk-2BIE3CHY.cjs');
var chunkQCOIKCVA_cjs = require('./chunk-QCOIKCVA.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunk4LVJBXI2_cjs = require('./chunk-4LVJBXI2.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');

// src/server/handlers/stored-agents.ts
var LIST_STORED_AGENTS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/agents",
  responseType: "json",
  queryParamSchema: chunkQCOIKCVA_cjs.listStoredAgentsQuerySchema,
  responseSchema: chunkQCOIKCVA_cjs.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 chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const result = await agentsStore.listResolved({
        page,
        perPage,
        orderBy,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing stored agents");
    }
  }
});
var GET_STORED_AGENT_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: chunkQCOIKCVA_cjs.storedAgentIdPathParams,
  responseSchema: chunkQCOIKCVA_cjs.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 chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const agent = await agentsStore.getByIdResolved(storedAgentId);
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });
      }
      return agent;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting stored agent");
    }
  }
});
var CREATE_STORED_AGENT_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/agents",
  responseType: "json",
  bodySchema: chunkQCOIKCVA_cjs.createStoredAgentBodySchema,
  responseSchema: chunkQCOIKCVA_cjs.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: providedId,
    authorId,
    metadata,
    name,
    description,
    instructions,
    model,
    tools,
    defaultOptions,
    workflows,
    agents,
    integrationTools,
    inputProcessors,
    outputProcessors,
    memory,
    scorers,
    requestContextSchema
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const id = providedId || chunk2BIE3CHY_cjs.toSlug(name);
      if (!id) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Could not derive agent ID from name. Please provide an explicit id."
        });
      }
      const existing = await agentsStore.getById(id);
      if (existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(409, { message: `Agent with id ${id} already exists` });
      }
      const integrationToolsFromBody = Array.isArray(integrationTools) ? integrationTools : void 0;
      await agentsStore.create({
        agent: {
          id,
          authorId,
          metadata,
          name,
          description,
          instructions,
          model,
          tools,
          defaultOptions,
          workflows,
          agents,
          integrationTools: integrationToolsFromBody,
          inputProcessors,
          outputProcessors,
          memory,
          scorers,
          requestContextSchema
        }
      });
      const resolved = await agentsStore.getByIdResolved(id);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created agent" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating stored agent");
    }
  }
});
var UPDATE_STORED_AGENT_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "PATCH",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: chunkQCOIKCVA_cjs.storedAgentIdPathParams,
  bodySchema: chunkQCOIKCVA_cjs.updateStoredAgentBodySchema,
  responseSchema: chunkQCOIKCVA_cjs.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,
    requestContextSchema
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const existing = await agentsStore.getById(storedAgentId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });
      }
      const integrationToolsFromBody = Array.isArray(integrationTools) ? integrationTools : void 0;
      const updatedAgent = await agentsStore.update({
        id: storedAgentId,
        authorId,
        metadata,
        name,
        description,
        instructions,
        model,
        tools,
        defaultOptions,
        workflows,
        agents,
        integrationTools: integrationToolsFromBody,
        inputProcessors,
        outputProcessors,
        memory,
        scorers,
        requestContextSchema
      });
      const configFields = {
        name,
        description,
        instructions,
        model,
        tools,
        defaultOptions,
        workflows,
        agents,
        integrationTools: integrationToolsFromBody,
        inputProcessors,
        outputProcessors,
        memory,
        scorers,
        requestContextSchema
      };
      const providedConfigFields = Object.fromEntries(Object.entries(configFields).filter(([_, v]) => v !== void 0));
      const autoVersionResult = await chunk2KMBCFTE_cjs.handleAutoVersioning(
        agentsStore,
        storedAgentId,
        existing,
        updatedAgent,
        providedConfigFields
      );
      if (!autoVersionResult) {
        throw new Error("handleAutoVersioning returned undefined");
      }
      const editor = mastra.getEditor();
      if (editor) {
        editor.agent.clearCache(storedAgentId);
      }
      const resolved = await agentsStore.getByIdResolved(storedAgentId);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated agent" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error updating stored agent");
    }
  }
});
var DELETE_STORED_AGENT_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "DELETE",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: chunkQCOIKCVA_cjs.storedAgentIdPathParams,
  responseSchema: chunkQCOIKCVA_cjs.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 chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const agentsStore = await storage.getStore("agents");
      if (!agentsStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" });
      }
      const existing = await agentsStore.getById(storedAgentId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });
      }
      await agentsStore.delete(storedAgentId);
      mastra.getEditor()?.agent.clearCache(storedAgentId);
      return { success: true, message: `Agent ${storedAgentId} deleted successfully` };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error deleting stored agent");
    }
  }
});
var PREVIEW_INSTRUCTIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/preview-instructions",
  responseType: "json",
  bodySchema: chunkQCOIKCVA_cjs.previewInstructionsBodySchema,
  responseSchema: chunkQCOIKCVA_cjs.previewInstructionsResponseSchema,
  summary: "Preview resolved instructions",
  description: "Resolves an array of instruction blocks against a request context, evaluating rules, fetching prompt block references, and rendering template variables. Returns the final concatenated instruction string.",
  tags: ["Stored Agents"],
  requiresAuth: true,
  handler: async ({ mastra, blocks, context }) => {
    try {
      const editor = mastra.getEditor();
      if (!editor) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Editor is not configured" });
      }
      const result = await editor.prompt.preview(blocks, context ?? {});
      return { result };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error previewing instructions");
    }
  }
});

exports.CREATE_STORED_AGENT_ROUTE = CREATE_STORED_AGENT_ROUTE;
exports.DELETE_STORED_AGENT_ROUTE = DELETE_STORED_AGENT_ROUTE;
exports.GET_STORED_AGENT_ROUTE = GET_STORED_AGENT_ROUTE;
exports.LIST_STORED_AGENTS_ROUTE = LIST_STORED_AGENTS_ROUTE;
exports.PREVIEW_INSTRUCTIONS_ROUTE = PREVIEW_INSTRUCTIONS_ROUTE;
exports.UPDATE_STORED_AGENT_ROUTE = UPDATE_STORED_AGENT_ROUTE;
//# sourceMappingURL=chunk-T6A5ZU57.cjs.map
//# sourceMappingURL=chunk-T6A5ZU57.cjs.map