import { handleAutoVersioning } from './chunk-33QPJPK4.js';
import { toSlug } from './chunk-2E5ZB7FH.js';
import { listStoredAgentsResponseSchema, listStoredAgentsQuerySchema, getStoredAgentResponseSchema, storedAgentIdPathParams, createStoredAgentResponseSchema, createStoredAgentBodySchema, updateStoredAgentResponseSchema, updateStoredAgentBodySchema, deleteStoredAgentResponseSchema, previewInstructionsResponseSchema, previewInstructionsBodySchema } from './chunk-VKTJMAUK.js';
import { statusQuerySchema } from './chunk-USZD5AX2.js';
import { handleError } from './chunk-NA7LKQPZ.js';
import { createRoute } from './chunk-OLKVMPNB.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';

// 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 = 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, status, 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.listResolved({
        page,
        perPage,
        orderBy,
        status,
        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,
  queryParamSchema: statusQuerySchema,
  responseSchema: 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 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.getByIdResolved(storedAgentId, { status });
      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: 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 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 id = providedId || toSlug(name);
      if (!id) {
        throw new 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 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 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,
    mcpClients,
    inputProcessors,
    outputProcessors,
    memory,
    scorers,
    skills,
    workspace,
    requestContextSchema,
    // Version metadata
    changeMessage
  }) => {
    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.getById(storedAgentId);
      if (!existing) {
        throw new 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 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 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.getById(storedAgentId);
      if (!existing) {
        throw new 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 handleError(error, "Error deleting stored agent");
    }
  }
});
var PREVIEW_INSTRUCTIONS_ROUTE = createRoute({
  method: "POST",
  path: "/stored/agents/preview-instructions",
  responseType: "json",
  bodySchema: previewInstructionsBodySchema,
  responseSchema: 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 HTTPException(500, { message: "Editor is not configured" });
      }
      const result = await editor.prompt.preview(blocks, context ?? {});
      return { result };
    } catch (error) {
      return handleError(error, "Error previewing instructions");
    }
  }
});

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