'use strict';

var chunkKD3YOO6V_cjs = require('./chunk-KD3YOO6V.cjs');
var chunkAWQJBTJ4_cjs = require('./chunk-AWQJBTJ4.cjs');
var chunkDAKDYSX2_cjs = require('./chunk-DAKDYSX2.cjs');
var chunkCXL3KPGO_cjs = require('./chunk-CXL3KPGO.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunk4LVJBXI2_cjs = require('./chunk-4LVJBXI2.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var z = require('zod');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var z__default = /*#__PURE__*/_interopDefault(z);

var mcpClientToolsConfigSchema = z__default.default.object({
  tools: z__default.default.record(z__default.default.string(), chunkDAKDYSX2_cjs.toolConfigSchema).optional()
});
var agentVersionPathParams = z__default.default.object({
  agentId: z__default.default.string().describe("Unique identifier for the stored agent")
});
var versionIdPathParams = z__default.default.object({
  agentId: z__default.default.string().describe("Unique identifier for the stored agent"),
  versionId: z__default.default.string().describe("Unique identifier for the version (UUID)")
});
var agentVersionSchema = z__default.default.object({
  id: z__default.default.string().describe("Unique identifier for the version (UUID)"),
  agentId: z__default.default.string().describe("ID of the agent this version belongs to"),
  versionNumber: z__default.default.number().describe("Sequential version number (1, 2, 3, ...)"),
  // Top-level config fields (from StorageAgentSnapshotType)
  name: z__default.default.string().describe("Name of the agent"),
  description: z__default.default.string().optional().describe("Description of the agent"),
  instructions: chunkDAKDYSX2_cjs.instructionsSchema,
  model: chunkDAKDYSX2_cjs.conditionalFieldSchema(chunkDAKDYSX2_cjs.modelConfigSchema).describe(
    "Model configuration \u2014 static value or array of conditional variants"
  ),
  tools: chunkDAKDYSX2_cjs.conditionalFieldSchema(chunkDAKDYSX2_cjs.toolsConfigSchema).optional().describe("Tool keys mapped to per-tool config \u2014 static or conditional"),
  defaultOptions: chunkDAKDYSX2_cjs.conditionalFieldSchema(chunkCXL3KPGO_cjs.defaultOptionsSchema).optional().describe("Default options for generate/stream calls \u2014 static or conditional"),
  workflows: chunkDAKDYSX2_cjs.conditionalFieldSchema(z__default.default.record(z__default.default.string(), chunkDAKDYSX2_cjs.toolConfigSchema)).optional().describe("Workflow keys with optional per-workflow config \u2014 static or conditional"),
  agents: chunkDAKDYSX2_cjs.conditionalFieldSchema(z__default.default.record(z__default.default.string(), chunkDAKDYSX2_cjs.toolConfigSchema)).optional().describe("Agent keys with optional per-agent config \u2014 static or conditional"),
  integrationTools: chunkDAKDYSX2_cjs.conditionalFieldSchema(z__default.default.record(z__default.default.string(), mcpClientToolsConfigSchema)).optional().describe("Map of tool provider IDs to their tool configurations \u2014 static or conditional"),
  mcpClients: chunkDAKDYSX2_cjs.conditionalFieldSchema(z__default.default.record(z__default.default.string(), mcpClientToolsConfigSchema)).optional().describe("Map of stored MCP client IDs to their tool configurations \u2014 static or conditional"),
  inputProcessors: chunkDAKDYSX2_cjs.conditionalFieldSchema(z__default.default.array(z__default.default.string())).optional().describe("Array of processor keys \u2014 static or conditional"),
  outputProcessors: chunkDAKDYSX2_cjs.conditionalFieldSchema(z__default.default.array(z__default.default.string())).optional().describe("Array of processor keys \u2014 static or conditional"),
  memory: chunkDAKDYSX2_cjs.conditionalFieldSchema(chunkDAKDYSX2_cjs.serializedMemoryConfigSchema).optional().describe("Memory configuration \u2014 static or conditional"),
  scorers: chunkDAKDYSX2_cjs.conditionalFieldSchema(z__default.default.record(z__default.default.string(), chunkDAKDYSX2_cjs.scorerConfigSchema)).optional().describe("Scorer keys with optional sampling config \u2014 static or conditional"),
  requestContextSchema: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("JSON Schema defining valid request context variables"),
  // Version metadata fields
  changedFields: z__default.default.array(z__default.default.string()).optional().describe("Array of field names that changed from the previous version"),
  changeMessage: z__default.default.string().optional().describe("Optional message describing the changes"),
  createdAt: z__default.default.coerce.date().describe("When this version was created")
});
var listVersionsResponseSchema = chunkKD3YOO6V_cjs.createListVersionsResponseSchema(agentVersionSchema);
var getVersionResponseSchema = agentVersionSchema;
var createVersionResponseSchema = agentVersionSchema.partial().merge(
  z__default.default.object({
    // These fields are always present in a version response
    id: z__default.default.string().describe("Unique identifier for the version (UUID)"),
    agentId: z__default.default.string().describe("ID of the agent this version belongs to"),
    versionNumber: z__default.default.number().describe("Sequential version number (1, 2, 3, ...)"),
    createdAt: z__default.default.coerce.date().describe("When this version was created")
  })
);
var restoreVersionResponseSchema = agentVersionSchema.describe(
  "The newly created version from the restored configuration"
);
var compareVersionsResponseSchema = chunkKD3YOO6V_cjs.createCompareVersionsResponseSchema(agentVersionSchema);

// 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 = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:agentId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: agentVersionPathParams,
  queryParamSchema: chunkKD3YOO6V_cjs.listVersionsQuerySchema,
  responseSchema: 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 }) => {
    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` });
      }
      const result = await agentsStore.listVersions({
        agentId,
        page,
        perPage,
        orderBy
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing agent versions");
    }
  }
});
var CREATE_AGENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/:agentId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: agentVersionPathParams,
  bodySchema: chunkKD3YOO6V_cjs.createVersionBodySchema,
  responseSchema: createVersionResponseSchema,
  summary: "Create agent version",
  description: "Creates a new version snapshot of the current agent configuration",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, 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 agent = await agentsStore.getById(agentId);
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${agentId} not found` });
      }
      let currentConfig = {};
      if (agent.activeVersionId) {
        const activeVersion = await agentsStore.getVersion(agent.activeVersionId);
        if (activeVersion) {
          currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
            activeVersion,
            SNAPSHOT_CONFIG_FIELDS
          );
        }
      }
      const latestVersion = await agentsStore.getLatestVersion(agentId);
      if (!agent.activeVersionId && latestVersion) {
        currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
          latestVersion,
          SNAPSHOT_CONFIG_FIELDS
        );
      }
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, currentConfig);
      const { versionId } = await chunkAWQJBTJ4_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 chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        agentsStore,
        agentId,
        "agentId",
        agent.activeVersionId
      );
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating agent version");
    }
  }
});
var GET_AGENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:agentId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: versionIdPathParams,
  responseSchema: 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 }) => {
    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}` });
      }
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting agent version");
    }
  }
});
var ACTIVATE_AGENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/:agentId/versions/:versionId/activate",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: versionIdPathParams,
  responseSchema: chunkKD3YOO6V_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 }) => {
    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` });
      }
      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 chunkSUKFO7UM_cjs.handleError(error, "Error activating agent version");
    }
  }
});
var RESTORE_AGENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/agents/:agentId/versions/:versionId/restore",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: versionIdPathParams,
  responseSchema: 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 }) => {
    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` });
      }
      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 = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        versionToRestore,
        SNAPSHOT_CONFIG_FIELDS
      );
      await agentsStore.update({
        id: agentId,
        ...restoredConfig
      });
      const latestVersion = await agentsStore.getLatestVersion(agentId);
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, restoredConfig);
      const { versionId: newVersionId } = await chunkAWQJBTJ4_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 chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        agentsStore,
        agentId,
        "agentId",
        agent.activeVersionId
      );
      mastra.getEditor()?.agent.clearCache(agentId);
      return newVersion;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error restoring agent version");
    }
  }
});
var DELETE_AGENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "DELETE",
  path: "/stored/agents/:agentId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: versionIdPathParams,
  responseSchema: chunkKD3YOO6V_cjs.deleteVersionResponseSchema,
  summary: "Delete agent version",
  description: "Deletes a specific version (cannot delete the active version)",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, versionId }) => {
    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` });
      }
      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 chunkSUKFO7UM_cjs.handleError(error, "Error deleting agent version");
    }
  }
});
var COMPARE_AGENT_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:agentId/versions/compare",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: agentVersionPathParams,
  queryParamSchema: chunkKD3YOO6V_cjs.compareVersionsQuerySchema,
  responseSchema: compareVersionsResponseSchema,
  summary: "Compare agent versions",
  description: "Compares two versions and returns the differences between them",
  tags: ["Agent Versions"],
  handler: async ({ mastra, agentId, from, to }) => {
    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 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 = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        fromVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const toConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        toVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const diffs = chunkAWQJBTJ4_cjs.computeVersionDiffs(fromConfig, toConfig);
      return {
        diffs,
        fromVersion,
        toVersion
      };
    } catch (error) {
      return chunkSUKFO7UM_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-6M4TAONR.cjs.map
//# sourceMappingURL=chunk-6M4TAONR.cjs.map