'use strict';

var chunk2XZ2466F_cjs = require('./chunk-2XZ2466F.cjs');
var chunkEFX5WYRT_cjs = require('./chunk-EFX5WYRT.cjs');
var chunkUSD6C4ZL_cjs = require('./chunk-USD6C4ZL.cjs');
var chunkZYXDUS6Q_cjs = require('./chunk-ZYXDUS6Q.cjs');
var chunkY2BKW5ND_cjs = require('./chunk-Y2BKW5ND.cjs');
var chunk6P7P7Y5U_cjs = require('./chunk-6P7P7Y5U.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');

// src/server/handlers/stored-agents.ts
var AGENT_SNAPSHOT_CONFIG_FIELDS = [
  "name",
  "description",
  "instructions",
  "model",
  "tools",
  "defaultOptions",
  "workflows",
  "agents",
  "integrationTools",
  "inputProcessors",
  "outputProcessors",
  "memory",
  "scorers",
  "requestContextSchema",
  "mcpClients",
  "skills",
  "workspace"
];
var LIST_STORED_AGENTS_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "GET",
  path: "/stored/agents",
  responseType: "json",
  queryParamSchema: chunkUSD6C4ZL_cjs.listStoredAgentsQuerySchema,
  responseSchema: chunkUSD6C4ZL_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, status, 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,
        status,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error listing stored agents");
    }
  }
});
var GET_STORED_AGENT_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: chunkUSD6C4ZL_cjs.storedAgentIdPathParams,
  queryParamSchema: chunkZYXDUS6Q_cjs.statusQuerySchema,
  responseSchema: chunkUSD6C4ZL_cjs.getStoredAgentResponseSchema,
  summary: "Get stored agent by ID",
  description: "Returns a specific agent from storage by its unique identifier. Use ?status=draft to resolve with the latest (draft) version, or ?status=published (default) for the active published version.",
  tags: ["Stored Agents"],
  requiresAuth: true,
  handler: async ({ mastra, storedAgentId, status }) => {
    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, { status });
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` });
      }
      return agent;
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error getting stored agent");
    }
  }
});
var CREATE_STORED_AGENT_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "POST",
  path: "/stored/agents",
  responseType: "json",
  bodySchema: chunkUSD6C4ZL_cjs.createStoredAgentBodySchema,
  responseSchema: chunkUSD6C4ZL_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,
    mcpClients,
    inputProcessors,
    outputProcessors,
    memory,
    scorers,
    skills,
    workspace,
    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 || chunkEFX5WYRT_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` });
      }
      await agentsStore.create({
        agent: {
          id,
          authorId,
          metadata,
          name,
          description,
          instructions,
          model,
          tools,
          defaultOptions,
          workflows,
          agents,
          integrationTools,
          mcpClients,
          inputProcessors,
          outputProcessors,
          memory,
          scorers,
          skills,
          workspace,
          requestContextSchema
        }
      });
      const resolved = await agentsStore.getByIdResolved(id, { status: "draft" });
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created agent" });
      }
      return resolved;
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error creating stored agent");
    }
  }
});
var UPDATE_STORED_AGENT_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "PATCH",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: chunkUSD6C4ZL_cjs.storedAgentIdPathParams,
  bodySchema: chunkUSD6C4ZL_cjs.updateStoredAgentBodySchema,
  responseSchema: chunkUSD6C4ZL_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,
    mcpClients,
    inputProcessors,
    outputProcessors,
    memory,
    scorers,
    skills,
    workspace,
    requestContextSchema,
    // Version metadata
    changeMessage
  }) => {
    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 updatedAgent = await agentsStore.update({
        id: storedAgentId,
        authorId,
        metadata,
        name,
        description,
        instructions,
        model,
        tools,
        defaultOptions,
        workflows,
        agents,
        integrationTools,
        mcpClients,
        inputProcessors,
        outputProcessors,
        memory,
        scorers,
        skills,
        workspace,
        requestContextSchema
      });
      const configFields = {
        name,
        description,
        instructions,
        model,
        tools,
        defaultOptions,
        workflows,
        agents,
        integrationTools,
        mcpClients,
        inputProcessors,
        outputProcessors,
        memory,
        scorers,
        skills,
        workspace,
        requestContextSchema
      };
      const providedConfigFields = Object.fromEntries(Object.entries(configFields).filter(([_, v]) => v !== void 0));
      const autoVersionResult = await chunk2XZ2466F_cjs.handleAutoVersioning(
        agentsStore,
        storedAgentId,
        "agentId",
        AGENT_SNAPSHOT_CONFIG_FIELDS,
        existing,
        updatedAgent,
        providedConfigFields,
        changeMessage ? { changeMessage } : void 0
      );
      if (!autoVersionResult) {
        throw new Error("handleAutoVersioning returned undefined");
      }
      const editor = mastra.getEditor();
      if (editor) {
        editor.agent.clearCache(storedAgentId);
      }
      const resolved = await agentsStore.getByIdResolved(storedAgentId, { status: "draft" });
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated agent" });
      }
      return resolved;
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error updating stored agent");
    }
  }
});
var DELETE_STORED_AGENT_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "DELETE",
  path: "/stored/agents/:storedAgentId",
  responseType: "json",
  pathParamSchema: chunkUSD6C4ZL_cjs.storedAgentIdPathParams,
  responseSchema: chunkUSD6C4ZL_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 chunkY2BKW5ND_cjs.handleError(error, "Error deleting stored agent");
    }
  }
});
var PREVIEW_INSTRUCTIONS_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/preview-instructions",
  responseType: "json",
  bodySchema: chunkUSD6C4ZL_cjs.previewInstructionsBodySchema,
  responseSchema: chunkUSD6C4ZL_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 chunkY2BKW5ND_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-TSMZEPL3.cjs.map
//# sourceMappingURL=chunk-TSMZEPL3.cjs.map