'use strict';

var chunkWNK6NJYP_cjs = require('./chunk-WNK6NJYP.cjs');
var chunkGFP7IMFR_cjs = require('./chunk-GFP7IMFR.cjs');
var chunk2XZ2466F_cjs = require('./chunk-2XZ2466F.cjs');
var chunkDRDVJ35H_cjs = require('./chunk-DRDVJ35H.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');

// src/server/handlers/agent-versions.ts
var SNAPSHOT_CONFIG_FIELDS = [
  "name",
  "description",
  "instructions",
  "model",
  "tools",
  "defaultOptions",
  "workflows",
  "agents",
  "integrationTools",
  "inputProcessors",
  "outputProcessors",
  "memory",
  "scorers",
  "requestContextSchema",
  "mcpClients"
];
var LIST_AGENT_VERSIONS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:agentId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: chunkWNK6NJYP_cjs.agentVersionPathParams,
  queryParamSchema: chunkGFP7IMFR_cjs.listVersionsQuerySchema,
  responseSchema: chunkWNK6NJYP_cjs.listVersionsResponseSchema,
  summary: "List agent versions",
  description: "Returns a paginated list of all versions for a stored agent",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, page, perPage, orderBy, requestContext }) => {
    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 storedAgent = await agentsStore.getById(agentId);
      let codeAgentExists = false;
      try {
        mastra.getAgentById(agentId);
        codeAgentExists = true;
      } catch {
      }
      if (!storedAgent && !codeAgentExists) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${agentId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(storedAgent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      const result = await agentsStore.listVersions({
        agentId,
        page,
        perPage,
        orderBy
      });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing agent versions");
    }
  }
});
var CREATE_AGENT_VERSION_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/:agentId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: chunkWNK6NJYP_cjs.agentVersionPathParams,
  bodySchema: chunkGFP7IMFR_cjs.createVersionBodySchema,
  responseSchema: chunkWNK6NJYP_cjs.createVersionResponseSchema,
  summary: "Create agent version",
  description: "Creates a new version snapshot of the current agent configuration",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, changeMessage, requestContext }) => {
    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.getById(agentId);
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${agentId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(agent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      let currentConfig = {};
      if (agent.activeVersionId) {
        const activeVersion = await agentsStore.getVersion(agent.activeVersionId);
        if (activeVersion) {
          currentConfig = chunk2XZ2466F_cjs.extractConfigFromVersion(
            activeVersion,
            SNAPSHOT_CONFIG_FIELDS
          );
        }
      }
      const latestVersion = await agentsStore.getLatestVersion(agentId);
      if (!agent.activeVersionId && latestVersion) {
        currentConfig = chunk2XZ2466F_cjs.extractConfigFromVersion(
          latestVersion,
          SNAPSHOT_CONFIG_FIELDS
        );
      }
      const previousConfig = latestVersion ? chunk2XZ2466F_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunk2XZ2466F_cjs.calculateChangedFields(previousConfig, currentConfig);
      const { versionId } = await chunk2XZ2466F_cjs.createVersionWithRetry(
        agentsStore,
        agentId,
        "agentId",
        currentConfig,
        changedFields,
        { changeMessage }
      );
      const version = await agentsStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunk2XZ2466F_cjs.enforceRetentionLimit(
        agentsStore,
        agentId,
        "agentId",
        agent.activeVersionId
      );
      return version;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error creating agent version");
    }
  }
});
var GET_AGENT_VERSION_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:agentId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: chunkWNK6NJYP_cjs.versionIdPathParams,
  responseSchema: chunkWNK6NJYP_cjs.getVersionResponseSchema,
  summary: "Get agent version",
  description: "Returns a specific version of an agent by its version ID",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, versionId, requestContext }) => {
    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 version = await agentsStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.agentId !== agentId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found for agent ${agentId}` });
      }
      const agent = await agentsStore.getById(agentId);
      chunkDRDVJ35H_cjs.assertStoredResourceScope(agent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      return version;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting agent version");
    }
  }
});
var ACTIVATE_AGENT_VERSION_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/:agentId/versions/:versionId/activate",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: chunkWNK6NJYP_cjs.versionIdPathParams,
  responseSchema: chunkGFP7IMFR_cjs.activateVersionResponseSchema,
  summary: "Activate agent version",
  description: "Sets a specific version as the active version for the agent",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, versionId, requestContext }) => {
    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.getById(agentId);
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${agentId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(agent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      const version = await agentsStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.agentId !== agentId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found for agent ${agentId}` });
      }
      await agentsStore.update({
        id: agentId,
        activeVersionId: versionId,
        status: "published"
      });
      mastra.getEditor()?.agent.clearCache(agentId);
      return {
        success: true,
        message: `Version ${version.versionNumber} is now active`,
        activeVersionId: versionId
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error activating agent version");
    }
  }
});
var RESTORE_AGENT_VERSION_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/:agentId/versions/:versionId/restore",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: chunkWNK6NJYP_cjs.versionIdPathParams,
  responseSchema: chunkWNK6NJYP_cjs.restoreVersionResponseSchema,
  summary: "Restore agent version",
  description: "Restores the agent configuration from a version, creating a new version",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, versionId, requestContext }) => {
    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.getById(agentId);
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${agentId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(agent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      const versionToRestore = await agentsStore.getVersion(versionId);
      if (!versionToRestore) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (versionToRestore.agentId !== agentId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found for agent ${agentId}` });
      }
      const restoredConfig = chunk2XZ2466F_cjs.extractConfigFromVersion(
        versionToRestore,
        SNAPSHOT_CONFIG_FIELDS
      );
      await agentsStore.update({
        id: agentId,
        ...restoredConfig
      });
      const latestVersion = await agentsStore.getLatestVersion(agentId);
      const previousConfig = latestVersion ? chunk2XZ2466F_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunk2XZ2466F_cjs.calculateChangedFields(previousConfig, restoredConfig);
      const { versionId: newVersionId } = await chunk2XZ2466F_cjs.createVersionWithRetry(
        agentsStore,
        agentId,
        "agentId",
        restoredConfig,
        changedFields,
        {
          changeMessage: `Restored from version ${versionToRestore.versionNumber}`
        }
      );
      const newVersion = await agentsStore.getVersion(newVersionId);
      if (!newVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunk2XZ2466F_cjs.enforceRetentionLimit(
        agentsStore,
        agentId,
        "agentId",
        agent.activeVersionId
      );
      mastra.getEditor()?.agent.clearCache(agentId);
      return newVersion;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error restoring agent version");
    }
  }
});
var DELETE_AGENT_VERSION_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "DELETE",
  path: "/stored/agents/:agentId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: chunkWNK6NJYP_cjs.versionIdPathParams,
  responseSchema: chunkGFP7IMFR_cjs.deleteVersionResponseSchema,
  summary: "Delete agent version",
  description: "Deletes a specific version (cannot delete the active version)",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, versionId, requestContext }) => {
    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.getById(agentId);
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${agentId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(agent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      const version = await agentsStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.agentId !== agentId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found for agent ${agentId}` });
      }
      if (agent.activeVersionId === versionId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Cannot delete the active version. Activate a different version first."
        });
      }
      await agentsStore.deleteVersion(versionId);
      mastra.getEditor()?.agent.clearCache(agentId);
      return {
        success: true,
        message: `Version ${version.versionNumber} deleted successfully`
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error deleting agent version");
    }
  }
});
var COMPARE_AGENT_VERSIONS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:agentId/versions/compare",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: chunkWNK6NJYP_cjs.agentVersionPathParams,
  queryParamSchema: chunkGFP7IMFR_cjs.compareVersionsQuerySchema,
  responseSchema: chunkWNK6NJYP_cjs.compareVersionsResponseSchema,
  summary: "Compare agent versions",
  description: "Compares two versions and returns the differences between them",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, from, to, requestContext }) => {
    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.getById(agentId);
      chunkDRDVJ35H_cjs.assertStoredResourceScope(agent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      const fromVersion = await agentsStore.getVersion(from);
      if (!fromVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${from} not found` });
      }
      if (fromVersion.agentId !== agentId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${from} not found for agent ${agentId}` });
      }
      const toVersion = await agentsStore.getVersion(to);
      if (!toVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${to} not found` });
      }
      if (toVersion.agentId !== agentId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${to} not found for agent ${agentId}` });
      }
      const fromConfig = chunk2XZ2466F_cjs.extractConfigFromVersion(
        fromVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const toConfig = chunk2XZ2466F_cjs.extractConfigFromVersion(
        toVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const diffs = chunk2XZ2466F_cjs.computeVersionDiffs(fromConfig, toConfig);
      return {
        diffs,
        fromVersion,
        toVersion
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error comparing agent versions");
    }
  }
});

exports.ACTIVATE_AGENT_VERSION_ROUTE = ACTIVATE_AGENT_VERSION_ROUTE;
exports.COMPARE_AGENT_VERSIONS_ROUTE = COMPARE_AGENT_VERSIONS_ROUTE;
exports.CREATE_AGENT_VERSION_ROUTE = CREATE_AGENT_VERSION_ROUTE;
exports.DELETE_AGENT_VERSION_ROUTE = DELETE_AGENT_VERSION_ROUTE;
exports.GET_AGENT_VERSION_ROUTE = GET_AGENT_VERSION_ROUTE;
exports.LIST_AGENT_VERSIONS_ROUTE = LIST_AGENT_VERSIONS_ROUTE;
exports.RESTORE_AGENT_VERSION_ROUTE = RESTORE_AGENT_VERSION_ROUTE;
//# sourceMappingURL=chunk-TZZ2AOOV.cjs.map
//# sourceMappingURL=chunk-TZZ2AOOV.cjs.map