'use strict';

var chunkCXL3KPGO_cjs = require('./chunk-CXL3KPGO.cjs');
var chunkMCYD5LW7_cjs = require('./chunk-MCYD5LW7.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunk4LVJBXI2_cjs = require('./chunk-4LVJBXI2.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var z2 = require('zod');

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

var z2__default = /*#__PURE__*/_interopDefault(z2);

var semanticRecallSchema = z2__default.default.object({
  topK: z2__default.default.number().describe("Number of semantically similar messages to retrieve"),
  messageRange: z2__default.default.union([
    z2__default.default.number(),
    z2__default.default.object({
      before: z2__default.default.number(),
      after: z2__default.default.number()
    })
  ]).describe("Amount of surrounding context to include with each retrieved message"),
  scope: z2__default.default.enum(["thread", "resource"]).optional().describe("Scope for semantic search queries"),
  threshold: z2__default.default.number().min(0).max(1).optional().describe("Minimum similarity score threshold"),
  indexName: z2__default.default.string().optional().describe("Index name for the vector store")
});
var titleGenerationSchema = z2__default.default.union([
  z2__default.default.boolean(),
  z2__default.default.object({
    model: z2__default.default.string().describe("Model ID in format provider/model-name (ModelRouterModelId)"),
    instructions: z2__default.default.string().optional().describe("Custom instructions for title generation")
  })
]);
var serializedMemoryConfigSchema = z2__default.default.object({
  vector: z2__default.default.union([z2__default.default.string(), z2__default.default.literal(false)]).optional().describe("Vector database identifier or false to disable"),
  options: z2__default.default.object({
    readOnly: z2__default.default.boolean().optional(),
    lastMessages: z2__default.default.union([z2__default.default.number(), z2__default.default.literal(false)]).optional(),
    semanticRecall: z2__default.default.union([z2__default.default.boolean(), semanticRecallSchema]).optional(),
    generateTitle: titleGenerationSchema.optional()
  }).optional().describe("Memory behavior configuration, excluding workingMemory and threads"),
  embedder: z2__default.default.string().optional().describe('Embedding model ID in the format "provider/model" (e.g., "openai/text-embedding-3-small")'),
  embedderOptions: z2__default.default.record(z2__default.default.string(), z2__default.default.unknown()).optional().describe("Options to pass to the embedder, omitting telemetry")
}).refine(
  (data) => {
    const semanticRecall = data.options?.semanticRecall;
    const semanticRecallEnabled = semanticRecall === true || typeof semanticRecall === "object" && semanticRecall !== null;
    if (semanticRecallEnabled) {
      const hasVector = typeof data.vector === "string" && data.vector.length > 0;
      const hasEmbedder = typeof data.embedder === "string" && data.embedder.length > 0;
      return hasVector && hasEmbedder;
    }
    return true;
  },
  {
    message: "Semantic recall requires both vector and embedder to be configured",
    path: ["options", "semanticRecall"]
  }
);
var storedAgentIdPathParams = z2__default.default.object({
  storedAgentId: z2__default.default.string().describe("Unique identifier for the stored agent")
});
var storageOrderBySchema = z2__default.default.object({
  field: z2__default.default.enum(["createdAt", "updatedAt"]).optional(),
  direction: z2__default.default.enum(["ASC", "DESC"]).optional()
});
var listStoredAgentsQuerySchema = chunkMCYD5LW7_cjs.createPagePaginationSchema(100).extend({
  orderBy: storageOrderBySchema.optional(),
  authorId: z2__default.default.string().optional().describe("Filter agents by author identifier"),
  metadata: z2__default.default.record(z2__default.default.string(), z2__default.default.unknown()).optional().describe("Filter agents by metadata key-value pairs")
});
var scorerConfigSchema = z2__default.default.object({
  sampling: z2__default.default.union([
    z2__default.default.object({ type: z2__default.default.literal("none") }),
    z2__default.default.object({ type: z2__default.default.literal("ratio"), rate: z2__default.default.number().min(0).max(1) })
  ]).optional()
});
var snapshotConfigSchema = z2__default.default.object({
  name: z2__default.default.string().describe("Name of the agent"),
  description: z2__default.default.string().optional().describe("Description of the agent"),
  instructions: z2__default.default.string().describe("System instructions for the agent"),
  model: z2__default.default.object({
    provider: z2__default.default.string().describe("Model provider (e.g., openai, anthropic)"),
    name: z2__default.default.string().describe("Model name (e.g., gpt-4o, claude-3-opus)")
  }).passthrough().describe("Model configuration (provider, name, and optional params)"),
  tools: z2__default.default.array(z2__default.default.string()).optional().describe("Array of tool keys to resolve from Mastra registry"),
  defaultOptions: chunkCXL3KPGO_cjs.defaultOptionsSchema.optional().describe("Default options for generate/stream calls"),
  workflows: z2__default.default.array(z2__default.default.string()).optional().describe("Array of workflow keys to resolve from Mastra registry"),
  agents: z2__default.default.array(z2__default.default.string()).optional().describe("Array of agent keys to resolve from Mastra registry"),
  integrationTools: z2__default.default.array(z2__default.default.string()).optional().describe("Array of specific integration tool IDs (format: provider_toolkitSlug_toolSlug)"),
  inputProcessors: z2__default.default.array(z2__default.default.string()).optional().describe("Array of processor keys to resolve from Mastra registry"),
  outputProcessors: z2__default.default.array(z2__default.default.string()).optional().describe("Array of processor keys to resolve from Mastra registry"),
  memory: serializedMemoryConfigSchema.optional().describe("Memory configuration object (SerializedMemoryConfig)"),
  scorers: z2__default.default.record(z2__default.default.string(), scorerConfigSchema).optional().describe("Scorer keys with optional sampling config")
});
var agentMetadataSchema = z2__default.default.object({
  authorId: z2__default.default.string().optional().describe("Author identifier for multi-tenant filtering"),
  metadata: z2__default.default.record(z2__default.default.string(), z2__default.default.unknown()).optional().describe("Additional metadata for the agent")
});
var createStoredAgentBodySchema = z2__default.default.object({
  id: z2__default.default.string().describe("Unique identifier for the agent"),
  authorId: z2__default.default.string().optional().describe("Author identifier for multi-tenant filtering"),
  metadata: z2__default.default.record(z2__default.default.string(), z2__default.default.unknown()).optional().describe("Additional metadata for the agent")
}).merge(snapshotConfigSchema);
var updateStoredAgentBodySchema = agentMetadataSchema.partial().merge(snapshotConfigSchema.partial());
var storedAgentSchema = z2__default.default.object({
  // Thin agent record fields
  id: z2__default.default.string(),
  status: z2__default.default.string().describe("Agent status: draft or published"),
  activeVersionId: z2__default.default.string().optional(),
  authorId: z2__default.default.string().optional(),
  metadata: z2__default.default.record(z2__default.default.string(), z2__default.default.unknown()).optional(),
  createdAt: z2__default.default.coerce.date(),
  updatedAt: z2__default.default.coerce.date(),
  // Version snapshot config fields (resolved from active version)
  name: z2__default.default.string().describe("Name of the agent"),
  description: z2__default.default.string().optional().describe("Description of the agent"),
  instructions: z2__default.default.string().describe("System instructions for the agent"),
  model: z2__default.default.object({
    provider: z2__default.default.string().describe("Model provider (e.g., openai, anthropic)"),
    name: z2__default.default.string().describe("Model name (e.g., gpt-4o, claude-3-opus)")
  }).passthrough().describe("Model configuration (provider, name, and optional params)"),
  tools: z2__default.default.array(z2__default.default.string()).optional().describe("Array of tool keys to resolve from Mastra registry"),
  defaultOptions: chunkCXL3KPGO_cjs.defaultOptionsSchema.optional().describe("Default options for generate/stream calls"),
  workflows: z2__default.default.array(z2__default.default.string()).optional().describe("Array of workflow keys to resolve from Mastra registry"),
  agents: z2__default.default.array(z2__default.default.string()).optional().describe("Array of agent keys to resolve from Mastra registry"),
  integrationTools: z2__default.default.array(z2__default.default.string()).optional().describe("Array of specific integration tool IDs (format: provider_toolkitSlug_toolSlug)"),
  inputProcessors: z2__default.default.array(z2__default.default.string()).optional().describe("Array of processor keys to resolve from Mastra registry"),
  outputProcessors: z2__default.default.array(z2__default.default.string()).optional().describe("Array of processor keys to resolve from Mastra registry"),
  memory: serializedMemoryConfigSchema.optional().describe("Memory configuration object (SerializedMemoryConfig)"),
  scorers: z2__default.default.record(z2__default.default.string(), scorerConfigSchema).optional().describe("Scorer keys with optional sampling config")
});
var listStoredAgentsResponseSchema = chunkMCYD5LW7_cjs.paginationInfoSchema.extend({
  agents: z2__default.default.array(storedAgentSchema)
});
var getStoredAgentResponseSchema = storedAgentSchema;
var createStoredAgentResponseSchema = storedAgentSchema;
var updateStoredAgentResponseSchema = z2__default.default.union([
  // Thin agent record (no version config)
  z2__default.default.object({
    id: z2__default.default.string(),
    status: z2__default.default.string(),
    activeVersionId: z2__default.default.string().optional(),
    authorId: z2__default.default.string().optional(),
    metadata: z2__default.default.record(z2__default.default.string(), z2__default.default.unknown()).optional(),
    createdAt: z2__default.default.coerce.date(),
    updatedAt: z2__default.default.coerce.date()
  }),
  // Resolved agent (thin record + version config)
  storedAgentSchema
]);
var deleteStoredAgentResponseSchema = z2__default.default.object({
  success: z2__default.default.boolean(),
  message: z2__default.default.string()
});

// src/server/schemas/agent-versions.ts
var agentVersionPathParams = z2__default.default.object({
  agentId: z2__default.default.string().describe("Unique identifier for the stored agent")
});
var versionIdPathParams = z2__default.default.object({
  agentId: z2__default.default.string().describe("Unique identifier for the stored agent"),
  versionId: z2__default.default.string().describe("Unique identifier for the version (UUID)")
});
var versionOrderBySchema = z2__default.default.object({
  field: z2__default.default.enum(["versionNumber", "createdAt"]).optional(),
  direction: z2__default.default.enum(["ASC", "DESC"]).optional()
});
var listVersionsQuerySchema = chunkMCYD5LW7_cjs.createPagePaginationSchema(20).extend({
  orderBy: versionOrderBySchema.optional()
});
var compareVersionsQuerySchema = z2__default.default.object({
  from: z2__default.default.string().describe("Version ID (UUID) to compare from"),
  to: z2__default.default.string().describe("Version ID (UUID) to compare to")
});
var createVersionBodySchema = z2__default.default.object({
  changeMessage: z2__default.default.string().max(500).optional().describe("Optional message describing the changes")
});
var agentVersionSchema = z2__default.default.object({
  id: z2__default.default.string().describe("Unique identifier for the version (UUID)"),
  agentId: z2__default.default.string().describe("ID of the agent this version belongs to"),
  versionNumber: z2__default.default.number().describe("Sequential version number (1, 2, 3, ...)"),
  // Top-level config fields (from StorageAgentSnapshotType)
  name: z2__default.default.string().describe("Name of the agent"),
  description: z2__default.default.string().optional().describe("Description of the agent"),
  instructions: z2__default.default.string().describe("System instructions for the agent"),
  model: z2__default.default.record(z2__default.default.string(), z2__default.default.unknown()).describe("Model configuration (provider, name, etc.)"),
  tools: z2__default.default.array(z2__default.default.string()).optional().describe("Array of tool keys to resolve from Mastra registry"),
  defaultOptions: chunkCXL3KPGO_cjs.defaultOptionsSchema.optional().describe("Default options for generate/stream calls"),
  workflows: z2__default.default.array(z2__default.default.string()).optional().describe("Array of workflow keys to resolve from Mastra registry"),
  agents: z2__default.default.array(z2__default.default.string()).optional().describe("Array of agent keys to resolve from Mastra registry"),
  integrationTools: z2__default.default.array(z2__default.default.string()).optional().describe("Array of specific integration tool IDs (format: provider_toolkitSlug_toolSlug)"),
  inputProcessors: z2__default.default.array(z2__default.default.string()).optional().describe("Array of processor keys to resolve from Mastra registry"),
  outputProcessors: z2__default.default.array(z2__default.default.string()).optional().describe("Array of processor keys to resolve from Mastra registry"),
  memory: serializedMemoryConfigSchema.optional().describe("Memory configuration object (SerializedMemoryConfig)"),
  scorers: z2__default.default.record(z2__default.default.string(), scorerConfigSchema).optional().describe("Scorer keys with optional sampling config"),
  // Version metadata fields
  changedFields: z2__default.default.array(z2__default.default.string()).optional().describe("Array of field names that changed from the previous version"),
  changeMessage: z2__default.default.string().optional().describe("Optional message describing the changes"),
  createdAt: z2__default.default.coerce.date().describe("When this version was created")
});
var listVersionsResponseSchema = chunkMCYD5LW7_cjs.paginationInfoSchema.extend({
  versions: z2__default.default.array(agentVersionSchema)
});
var getVersionResponseSchema = agentVersionSchema;
var createVersionResponseSchema = agentVersionSchema.partial().merge(
  z2__default.default.object({
    // These fields are always present in a version response
    id: z2__default.default.string().describe("Unique identifier for the version (UUID)"),
    agentId: z2__default.default.string().describe("ID of the agent this version belongs to"),
    versionNumber: z2__default.default.number().describe("Sequential version number (1, 2, 3, ...)"),
    createdAt: z2__default.default.coerce.date().describe("When this version was created")
  })
);
var activateVersionResponseSchema = z2__default.default.object({
  success: z2__default.default.boolean(),
  message: z2__default.default.string(),
  activeVersionId: z2__default.default.string()
});
var restoreVersionResponseSchema = agentVersionSchema.describe(
  "The newly created version from the restored configuration"
);
var deleteVersionResponseSchema = z2__default.default.object({
  success: z2__default.default.boolean(),
  message: z2__default.default.string()
});
var versionDiffEntrySchema = z2__default.default.object({
  field: z2__default.default.string().describe("The field path that changed"),
  previousValue: z2__default.default.unknown().describe('The value in the "from" version'),
  currentValue: z2__default.default.unknown().describe('The value in the "to" version')
});
var compareVersionsResponseSchema = z2__default.default.object({
  diffs: z2__default.default.array(versionDiffEntrySchema).describe("List of differences between versions"),
  fromVersion: agentVersionSchema.describe("The source version"),
  toVersion: agentVersionSchema.describe("The target version")
});

// src/server/handlers/agent-versions.ts
var DEFAULT_MAX_VERSIONS_PER_AGENT = 50;
var SNAPSHOT_CONFIG_FIELDS = [
  "name",
  "description",
  "instructions",
  "model",
  "tools",
  "defaultOptions",
  "workflows",
  "agents",
  "integrationTools",
  "inputProcessors",
  "outputProcessors",
  "memory",
  "scorers"
];
function deepEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return a === b;
  if (typeof a !== typeof b) return false;
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return false;
    return a.every((item, index) => deepEqual(item, b[index]));
  }
  if (a instanceof Date && b instanceof Date) {
    return a.getTime() === b.getTime();
  }
  if (typeof a === "object" && typeof b === "object") {
    const aObj = a;
    const bObj = b;
    const aKeys = Object.keys(aObj);
    const bKeys = Object.keys(bObj);
    if (aKeys.length !== bKeys.length) return false;
    return aKeys.every((key) => Object.prototype.hasOwnProperty.call(bObj, key) && deepEqual(aObj[key], bObj[key]));
  }
  return false;
}
function generateVersionId() {
  return crypto.randomUUID();
}
function extractConfigFromVersion(version) {
  const config = {};
  for (const field of SNAPSHOT_CONFIG_FIELDS) {
    if (field in version) {
      config[field] = version[field];
    }
  }
  return config;
}
function calculateChangedFields(previous, current) {
  if (!previous) {
    return Object.keys(current);
  }
  const changedFields = [];
  const allKeys = /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(current)]);
  for (const key of allKeys) {
    if (key === "updatedAt" || key === "createdAt") {
      continue;
    }
    const prevValue = previous[key];
    const currValue = current[key];
    if (!deepEqual(prevValue, currValue)) {
      changedFields.push(key);
    }
  }
  return changedFields;
}
function computeVersionDiffs(fromConfig, toConfig) {
  const diffs = [];
  const allKeys = /* @__PURE__ */ new Set([...Object.keys(fromConfig), ...Object.keys(toConfig)]);
  for (const key of allKeys) {
    if (key === "updatedAt" || key === "createdAt") {
      continue;
    }
    const prevValue = fromConfig[key];
    const currValue = toConfig[key];
    if (!deepEqual(prevValue, currValue)) {
      diffs.push({
        field: key,
        previousValue: prevValue,
        currentValue: currValue
      });
    }
  }
  return diffs;
}
async function enforceRetentionLimit(agentsStore, agentId, activeVersionId, maxVersions = DEFAULT_MAX_VERSIONS_PER_AGENT) {
  const { total } = await agentsStore.listVersions({ agentId, perPage: 1 });
  if (total <= maxVersions) {
    return { deletedCount: 0 };
  }
  const versionsToDelete = total - maxVersions;
  const { versions: oldestVersions } = await agentsStore.listVersions({
    agentId,
    perPage: versionsToDelete + 1,
    // Get one extra in case we need to skip the active version
    orderBy: { field: "versionNumber", direction: "ASC" }
  });
  let deletedCount = 0;
  for (const version of oldestVersions) {
    if (deletedCount >= versionsToDelete) {
      break;
    }
    if (version.id === activeVersionId) {
      continue;
    }
    await agentsStore.deleteVersion(version.id);
    deletedCount++;
  }
  return { deletedCount };
}
function isVersionNumberConflictError(error) {
  if (error instanceof Error) {
    const message = error.message.toLowerCase();
    return message.includes("unique") && message.includes("constraint") || message.includes("duplicate key") || message.includes("unique_violation") || message.includes("sqlite_constraint_unique") || message.includes("versionnumber");
  }
  return false;
}
async function createVersionWithRetry(agentsStore, agentId, snapshotConfig, changedFields, options = {}) {
  const { changeMessage, maxRetries = 3 } = options;
  let lastError;
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const latestVersion = await agentsStore.getLatestVersion(agentId);
      const versionNumber = latestVersion ? latestVersion.versionNumber + 1 : 1;
      const versionId = generateVersionId();
      await agentsStore.createVersion({
        ...snapshotConfig,
        id: versionId,
        agentId,
        versionNumber,
        changedFields,
        changeMessage
      });
      return { versionId, versionNumber };
    } catch (error) {
      lastError = error;
      if (isVersionNumberConflictError(error) && attempt < maxRetries - 1) {
        await new Promise((resolve) => setTimeout(resolve, 10 * (attempt + 1)));
        continue;
      }
      throw error;
    }
  }
  throw lastError;
}
async function handleAutoVersioning(agentsStore, agentId, existingAgent, updatedAgent, configFields) {
  if (!configFields || Object.keys(configFields).length === 0) {
    return { agent: updatedAgent, versionCreated: false };
  }
  const activeVersion = existingAgent.activeVersionId ? await agentsStore.getVersion(existingAgent.activeVersionId) : null;
  const versionToCompare = activeVersion || await agentsStore.getLatestVersion(agentId);
  const previousConfig = versionToCompare ? extractConfigFromVersion(versionToCompare) : null;
  const changedFields = calculateChangedFields(previousConfig, configFields);
  if (changedFields.length === 0) {
    return { agent: updatedAgent, versionCreated: false };
  }
  const fullConfig = previousConfig ? { ...previousConfig } : {};
  for (const [key, value] of Object.entries(configFields)) {
    fullConfig[key] = value;
  }
  const { versionId } = await createVersionWithRetry(agentsStore, agentId, fullConfig, changedFields, {
    changeMessage: "Auto-saved after edit"
  });
  await agentsStore.updateAgent({
    id: agentId,
    activeVersionId: versionId
  });
  const agentWithNewVersion = {
    ...updatedAgent,
    activeVersionId: versionId
  };
  await enforceRetentionLimit(agentsStore, agentId, versionId);
  return { agent: agentWithNewVersion, versionCreated: true };
}
var LIST_AGENT_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/agents/:agentId/versions",
  responseType: "json",
  pathParamSchema: agentVersionPathParams,
  queryParamSchema: 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.getAgentById({ id: 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",
  responseType: "json",
  pathParamSchema: agentVersionPathParams,
  bodySchema: 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.getAgentById({ id: 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 = extractConfigFromVersion(activeVersion);
        }
      }
      const latestVersion = await agentsStore.getLatestVersion(agentId);
      const previousConfig = latestVersion ? extractConfigFromVersion(latestVersion) : null;
      const changedFields = calculateChangedFields(previousConfig, currentConfig);
      const { versionId } = await createVersionWithRetry(
        agentsStore,
        agentId,
        currentConfig,
        changedFields.length > 0 ? changedFields : [],
        { changeMessage }
      );
      const version = await agentsStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await enforceRetentionLimit(agentsStore, 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",
  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",
  responseType: "json",
  pathParamSchema: versionIdPathParams,
  responseSchema: 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.getAgentById({ id: 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.updateAgent({
        id: agentId,
        activeVersionId: versionId,
        status: "published"
      });
      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",
  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.getAgentById({ id: 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 = extractConfigFromVersion(versionToRestore);
      await agentsStore.updateAgent({
        id: agentId,
        ...restoredConfig
      });
      const latestVersion = await agentsStore.getLatestVersion(agentId);
      const previousConfig = latestVersion ? extractConfigFromVersion(latestVersion) : null;
      const changedFields = calculateChangedFields(previousConfig, restoredConfig);
      const { versionId: newVersionId } = await createVersionWithRetry(
        agentsStore,
        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 enforceRetentionLimit(agentsStore, agentId, agent.activeVersionId);
      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",
  responseType: "json",
  pathParamSchema: versionIdPathParams,
  responseSchema: 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.getAgentById({ id: 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);
      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",
  responseType: "json",
  pathParamSchema: agentVersionPathParams,
  queryParamSchema: 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 = extractConfigFromVersion(fromVersion);
      const toConfig = extractConfigFromVersion(toVersion);
      const diffs = 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.DEFAULT_MAX_VERSIONS_PER_AGENT = DEFAULT_MAX_VERSIONS_PER_AGENT;
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;
exports.calculateChangedFields = calculateChangedFields;
exports.createStoredAgentBodySchema = createStoredAgentBodySchema;
exports.createStoredAgentResponseSchema = createStoredAgentResponseSchema;
exports.createVersionWithRetry = createVersionWithRetry;
exports.deleteStoredAgentResponseSchema = deleteStoredAgentResponseSchema;
exports.enforceRetentionLimit = enforceRetentionLimit;
exports.generateVersionId = generateVersionId;
exports.getStoredAgentResponseSchema = getStoredAgentResponseSchema;
exports.handleAutoVersioning = handleAutoVersioning;
exports.listStoredAgentsQuerySchema = listStoredAgentsQuerySchema;
exports.listStoredAgentsResponseSchema = listStoredAgentsResponseSchema;
exports.storedAgentIdPathParams = storedAgentIdPathParams;
exports.updateStoredAgentBodySchema = updateStoredAgentBodySchema;
exports.updateStoredAgentResponseSchema = updateStoredAgentResponseSchema;
//# sourceMappingURL=chunk-Q34I6QR2.cjs.map
//# sourceMappingURL=chunk-Q34I6QR2.cjs.map