'use strict';

var chunkMCYD5LW7_cjs = require('./chunk-MCYD5LW7.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunkK52BGIHQ_cjs = require('./chunk-K52BGIHQ.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var error = require('@mastra/core/error');
var features = require('@mastra/core/features');
var z = require('zod');

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

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

var jsonSchemaObject = z__default.default.lazy(() => z__default.default.record(z__default.default.unknown()));
var jsonSchemaField = z__default.default.union([jsonSchemaObject, z__default.default.null()]).optional();
var datasetIdPathParams = z__default.default.object({
  datasetId: z__default.default.string().describe("Unique identifier for the dataset")
});
z__default.default.object({
  experimentId: z__default.default.string().describe("Unique identifier for the experiment")
});
z__default.default.object({
  itemId: z__default.default.string().describe("Unique identifier for the dataset item")
});
var datasetAndExperimentIdPathParams = z__default.default.object({
  datasetId: z__default.default.string().describe("Unique identifier for the dataset"),
  experimentId: z__default.default.string().describe("Unique identifier for the experiment")
});
var datasetAndItemIdPathParams = z__default.default.object({
  datasetId: z__default.default.string().describe("Unique identifier for the dataset"),
  itemId: z__default.default.string().describe("Unique identifier for the dataset item")
});
var paginationQuerySchema = z__default.default.object({
  page: z__default.default.coerce.number().optional().default(0),
  perPage: z__default.default.coerce.number().optional().default(10)
});
var listItemsQuerySchema = z__default.default.object({
  page: z__default.default.coerce.number().optional().default(0),
  perPage: z__default.default.coerce.number().optional().default(10),
  version: z__default.default.coerce.number().int().optional(),
  // Optional version filter for snapshot semantics
  search: z__default.default.string().optional()
});
var createDatasetBodySchema = z__default.default.object({
  name: z__default.default.string().describe("Name of the dataset"),
  description: z__default.default.string().optional().describe("Description of the dataset"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata"),
  inputSchema: jsonSchemaField.describe("JSON Schema for validating item input"),
  groundTruthSchema: jsonSchemaField.describe("JSON Schema for validating item groundTruth")
});
var updateDatasetBodySchema = z__default.default.object({
  name: z__default.default.string().optional().describe("Name of the dataset"),
  description: z__default.default.string().optional().describe("Description of the dataset"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata"),
  inputSchema: jsonSchemaField.describe("JSON Schema for validating item input"),
  groundTruthSchema: jsonSchemaField.describe("JSON Schema for validating item groundTruth")
});
var addItemBodySchema = z__default.default.object({
  input: z__default.default.unknown().describe("Input data for the dataset item"),
  groundTruth: z__default.default.unknown().optional().describe("Expected output for comparison"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata")
});
var updateItemBodySchema = z__default.default.object({
  input: z__default.default.unknown().optional().describe("Input data for the dataset item"),
  groundTruth: z__default.default.unknown().optional().describe("Expected output for comparison"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata")
});
var triggerExperimentBodySchema = z__default.default.object({
  targetType: z__default.default.enum(["agent", "workflow", "scorer"]).describe("Type of target to run against"),
  targetId: z__default.default.string().describe("ID of the target"),
  scorerIds: z__default.default.array(z__default.default.string()).optional().describe("IDs of scorers to apply"),
  version: z__default.default.coerce.number().int().optional().describe("Pin to specific dataset version"),
  maxConcurrency: z__default.default.number().optional().describe("Maximum concurrent executions")
});
var compareExperimentsBodySchema = z__default.default.object({
  experimentIdA: z__default.default.string().describe("ID of baseline experiment"),
  experimentIdB: z__default.default.string().describe("ID of candidate experiment")
});
var datasetResponseSchema = z__default.default.object({
  id: z__default.default.string(),
  name: z__default.default.string(),
  description: z__default.default.string().optional().nullable(),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().nullable(),
  inputSchema: z__default.default.record(z__default.default.unknown()).optional().nullable(),
  groundTruthSchema: z__default.default.record(z__default.default.unknown()).optional().nullable(),
  version: z__default.default.number().int(),
  createdAt: z__default.default.coerce.date(),
  updatedAt: z__default.default.coerce.date()
});
var datasetItemResponseSchema = z__default.default.object({
  id: z__default.default.string(),
  datasetId: z__default.default.string(),
  datasetVersion: z__default.default.number().int(),
  input: z__default.default.unknown(),
  groundTruth: z__default.default.unknown().optional(),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional(),
  createdAt: z__default.default.coerce.date(),
  updatedAt: z__default.default.coerce.date()
});
var experimentResponseSchema = z__default.default.object({
  id: z__default.default.string(),
  datasetId: z__default.default.string().nullable(),
  datasetVersion: z__default.default.number().int().nullable(),
  targetType: z__default.default.enum(["agent", "workflow", "scorer", "processor"]),
  targetId: z__default.default.string(),
  name: z__default.default.string().optional(),
  description: z__default.default.string().optional(),
  metadata: z__default.default.record(z__default.default.unknown()).optional(),
  status: z__default.default.enum(["pending", "running", "completed", "failed"]),
  totalItems: z__default.default.number(),
  succeededCount: z__default.default.number(),
  failedCount: z__default.default.number(),
  skippedCount: z__default.default.number(),
  startedAt: z__default.default.coerce.date().nullable(),
  completedAt: z__default.default.coerce.date().nullable(),
  createdAt: z__default.default.coerce.date(),
  updatedAt: z__default.default.coerce.date()
});
z__default.default.object({
  scorerId: z__default.default.string(),
  scorerName: z__default.default.string(),
  score: z__default.default.number().nullable(),
  reason: z__default.default.string().nullable(),
  error: z__default.default.string().nullable()
});
var experimentResultResponseSchema = z__default.default.object({
  id: z__default.default.string(),
  experimentId: z__default.default.string(),
  itemId: z__default.default.string(),
  itemDatasetVersion: z__default.default.number().int().nullable(),
  input: z__default.default.unknown(),
  output: z__default.default.unknown().nullable(),
  groundTruth: z__default.default.unknown().nullable(),
  error: z__default.default.object({
    message: z__default.default.string(),
    stack: z__default.default.string().optional(),
    code: z__default.default.string().optional()
  }).nullable(),
  startedAt: z__default.default.coerce.date(),
  completedAt: z__default.default.coerce.date(),
  retryCount: z__default.default.number(),
  traceId: z__default.default.string().nullable(),
  createdAt: z__default.default.coerce.date()
});
var comparisonItemSchema = z__default.default.object({
  itemId: z__default.default.string(),
  input: z__default.default.unknown().nullable(),
  groundTruth: z__default.default.unknown().nullable(),
  results: z__default.default.record(
    z__default.default.string(),
    z__default.default.object({
      output: z__default.default.unknown().nullable(),
      scores: z__default.default.record(z__default.default.string(), z__default.default.number().nullable())
    }).nullable()
  )
});
var comparisonResponseSchema = z__default.default.object({
  baselineId: z__default.default.string(),
  items: z__default.default.array(comparisonItemSchema)
});
var experimentSummaryResponseSchema = z__default.default.object({
  experimentId: z__default.default.string(),
  status: z__default.default.enum(["pending", "running", "completed", "failed"]),
  totalItems: z__default.default.number(),
  succeededCount: z__default.default.number(),
  failedCount: z__default.default.number(),
  startedAt: z__default.default.coerce.date(),
  completedAt: z__default.default.coerce.date().nullable(),
  results: z__default.default.array(
    z__default.default.object({
      itemId: z__default.default.string(),
      itemDatasetVersion: z__default.default.number().int().nullable(),
      input: z__default.default.unknown(),
      output: z__default.default.unknown().nullable(),
      groundTruth: z__default.default.unknown().nullable(),
      error: z__default.default.string().nullable(),
      startedAt: z__default.default.coerce.date(),
      completedAt: z__default.default.coerce.date(),
      retryCount: z__default.default.number(),
      scores: z__default.default.array(
        z__default.default.object({
          scorerId: z__default.default.string(),
          scorerName: z__default.default.string(),
          score: z__default.default.number().nullable(),
          reason: z__default.default.string().nullable(),
          error: z__default.default.string().nullable()
        })
      )
    })
  )
});
var listDatasetsResponseSchema = z__default.default.object({
  datasets: z__default.default.array(datasetResponseSchema),
  pagination: chunkMCYD5LW7_cjs.paginationInfoSchema
});
var listItemsResponseSchema = z__default.default.object({
  items: z__default.default.array(datasetItemResponseSchema),
  pagination: chunkMCYD5LW7_cjs.paginationInfoSchema
});
var listExperimentsResponseSchema = z__default.default.object({
  experiments: z__default.default.array(experimentResponseSchema),
  pagination: chunkMCYD5LW7_cjs.paginationInfoSchema
});
var listExperimentResultsResponseSchema = z__default.default.object({
  results: z__default.default.array(experimentResultResponseSchema),
  pagination: chunkMCYD5LW7_cjs.paginationInfoSchema
});
var datasetItemVersionPathParams = z__default.default.object({
  datasetId: z__default.default.string().describe("Unique identifier for the dataset"),
  itemId: z__default.default.string().describe("Unique identifier for the dataset item"),
  datasetVersion: z__default.default.coerce.number().int().describe("Dataset version number")
});
var itemVersionResponseSchema = z__default.default.object({
  id: z__default.default.string(),
  datasetId: z__default.default.string(),
  datasetVersion: z__default.default.number().int(),
  input: z__default.default.unknown(),
  groundTruth: z__default.default.unknown().optional(),
  metadata: z__default.default.record(z__default.default.unknown()).optional(),
  validTo: z__default.default.number().int().nullable(),
  isDeleted: z__default.default.boolean(),
  createdAt: z__default.default.coerce.date(),
  updatedAt: z__default.default.coerce.date()
});
var listItemVersionsResponseSchema = z__default.default.object({
  history: z__default.default.array(itemVersionResponseSchema)
});
var datasetVersionResponseSchema = z__default.default.object({
  id: z__default.default.string(),
  datasetId: z__default.default.string(),
  version: z__default.default.number().int(),
  createdAt: z__default.default.coerce.date()
});
var listDatasetVersionsResponseSchema = z__default.default.object({
  versions: z__default.default.array(datasetVersionResponseSchema),
  pagination: chunkMCYD5LW7_cjs.paginationInfoSchema
});
var batchInsertItemsBodySchema = z__default.default.object({
  items: z__default.default.array(
    z__default.default.object({
      input: z__default.default.unknown(),
      groundTruth: z__default.default.unknown().optional(),
      metadata: z__default.default.record(z__default.default.unknown()).optional()
    })
  )
});
var batchInsertItemsResponseSchema = z__default.default.object({
  items: z__default.default.array(datasetItemResponseSchema),
  count: z__default.default.number()
});
var batchDeleteItemsBodySchema = z__default.default.object({
  itemIds: z__default.default.array(z__default.default.string())
});
var batchDeleteItemsResponseSchema = z__default.default.object({
  success: z__default.default.boolean(),
  deletedCount: z__default.default.number()
});

// src/server/handlers/datasets.ts
function assertDatasetsAvailable() {
  if (!features.coreFeatures.has("datasets")) {
    throw new chunk64ITUOXI_cjs.HTTPException(501, { message: "Datasets require @mastra/core >= 1.4.0" });
  }
}
function isSchemaValidationError(error) {
  return error instanceof Error && error.name === "SchemaValidationError";
}
function isSchemaUpdateValidationError(error) {
  return error instanceof Error && error.name === "SchemaUpdateValidationError";
}
function getHttpStatusForMastraError(errorId) {
  switch (errorId) {
    case "DATASET_NOT_FOUND":
    case "EXPERIMENT_NOT_FOUND":
      return 404;
    default:
      return 500;
  }
}
var LIST_DATASETS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets",
  responseType: "json",
  queryParamSchema: paginationQuerySchema,
  responseSchema: listDatasetsResponseSchema,
  summary: "List all datasets",
  description: "Returns a paginated list of all datasets",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { page, perPage } = params;
      const result = await mastra.datasets.list({ page: page ?? 0, perPage: perPage ?? 10 });
      return {
        datasets: result.datasets,
        pagination: result.pagination
      };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error listing datasets");
    }
  }
});
var CREATE_DATASET_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "POST",
  path: "/datasets",
  responseType: "json",
  bodySchema: createDatasetBodySchema,
  responseSchema: datasetResponseSchema,
  summary: "Create a new dataset",
  description: "Creates a new dataset with the specified name and optional metadata",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { name, description, metadata, inputSchema, groundTruthSchema } = params;
      const ds = await mastra.datasets.create({
        name,
        description,
        metadata,
        inputSchema: inputSchema ?? void 0,
        groundTruthSchema: groundTruthSchema ?? void 0
      });
      const details = await ds.getDetails();
      return details;
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error creating dataset");
    }
  }
});
var GET_DATASET_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  responseSchema: datasetResponseSchema.nullable(),
  summary: "Get dataset by ID",
  description: "Returns details for a specific dataset",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId }) => {
    assertDatasetsAvailable();
    try {
      const ds = await mastra.datasets.get({ id: datasetId });
      return await ds.getDetails();
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error getting dataset");
    }
  }
});
var UPDATE_DATASET_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "PATCH",
  path: "/datasets/:datasetId",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  bodySchema: updateDatasetBodySchema,
  responseSchema: datasetResponseSchema,
  summary: "Update dataset",
  description: "Updates a dataset with the specified fields",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { name, description, metadata, inputSchema, groundTruthSchema } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const result = await ds.update({
        name,
        description,
        metadata,
        inputSchema: inputSchema ?? void 0,
        groundTruthSchema: groundTruthSchema ?? void 0
      });
      return result;
    } catch (error$1) {
      if (isSchemaUpdateValidationError(error$1)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: error$1.message,
          cause: { failingItems: error$1.failingItems }
        });
      }
      if (isSchemaValidationError(error$1)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: error$1.message,
          cause: { field: error$1.field, errors: error$1.errors }
        });
      }
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error updating dataset");
    }
  }
});
var DELETE_DATASET_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "DELETE",
  path: "/datasets/:datasetId",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  responseSchema: chunkMCYD5LW7_cjs.successResponseSchema,
  summary: "Delete dataset",
  description: "Deletes a dataset and all its items",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId }) => {
    assertDatasetsAvailable();
    try {
      await mastra.datasets.get({ id: datasetId });
      await mastra.datasets.delete({ id: datasetId });
      return { success: true };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error deleting dataset");
    }
  }
});
var LIST_ITEMS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/items",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  queryParamSchema: listItemsQuerySchema,
  responseSchema: listItemsResponseSchema,
  summary: "List dataset items",
  description: "Returns a paginated list of items in the dataset",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { page, perPage, version, search } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const result = await ds.listItems({
        page: page ?? 0,
        perPage: perPage ?? 10,
        version,
        search
      });
      if (Array.isArray(result)) {
        return { items: result, pagination: { total: result.length, page: 0, perPage: result.length, hasMore: false } };
      }
      return { items: result.items, pagination: result.pagination };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error listing dataset items");
    }
  }
});
var ADD_ITEM_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "POST",
  path: "/datasets/:datasetId/items",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  bodySchema: addItemBodySchema,
  responseSchema: datasetItemResponseSchema,
  summary: "Add item to dataset",
  description: "Adds a new item to the dataset (auto-increments dataset version)",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { input, groundTruth, metadata } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      return await ds.addItem({ input, groundTruth, metadata });
    } catch (error$1) {
      if (isSchemaValidationError(error$1)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: error$1.message,
          cause: { field: error$1.field, errors: error$1.errors }
        });
      }
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error adding item to dataset");
    }
  }
});
var GET_ITEM_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/items/:itemId",
  responseType: "json",
  pathParamSchema: datasetAndItemIdPathParams,
  responseSchema: datasetItemResponseSchema.nullable(),
  summary: "Get dataset item by ID",
  description: "Returns details for a specific dataset item",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, itemId }) => {
    assertDatasetsAvailable();
    try {
      const ds = await mastra.datasets.get({ id: datasetId });
      const item = await ds.getItem({ itemId });
      if (!item || item.datasetId !== datasetId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Item not found: ${itemId}` });
      }
      return item;
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error getting dataset item");
    }
  }
});
var UPDATE_ITEM_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "PATCH",
  path: "/datasets/:datasetId/items/:itemId",
  responseType: "json",
  pathParamSchema: datasetAndItemIdPathParams,
  bodySchema: updateItemBodySchema,
  responseSchema: datasetItemResponseSchema,
  summary: "Update dataset item",
  description: "Updates a dataset item (auto-increments dataset version)",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, itemId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { input, groundTruth, metadata } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const existing = await ds.getItem({ itemId });
      if (!existing || existing.datasetId !== datasetId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Item not found: ${itemId}` });
      }
      return await ds.updateItem({ itemId, input, groundTruth, metadata });
    } catch (error$1) {
      if (isSchemaValidationError(error$1)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: error$1.message,
          cause: { field: error$1.field, errors: error$1.errors }
        });
      }
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error updating dataset item");
    }
  }
});
var DELETE_ITEM_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "DELETE",
  path: "/datasets/:datasetId/items/:itemId",
  responseType: "json",
  pathParamSchema: datasetAndItemIdPathParams,
  responseSchema: chunkMCYD5LW7_cjs.successResponseSchema,
  summary: "Delete dataset item",
  description: "Deletes a dataset item",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, itemId }) => {
    assertDatasetsAvailable();
    try {
      const ds = await mastra.datasets.get({ id: datasetId });
      const existing = await ds.getItem({ itemId });
      if (!existing || existing.datasetId !== datasetId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Item not found: ${itemId}` });
      }
      await ds.deleteItem({ itemId });
      return { success: true };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error deleting dataset item");
    }
  }
});
var LIST_EXPERIMENTS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/experiments",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  queryParamSchema: paginationQuerySchema,
  responseSchema: listExperimentsResponseSchema,
  summary: "List experiments for dataset",
  description: "Returns a paginated list of experiments for the dataset",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { page, perPage } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const result = await ds.listExperiments({ page: page ?? 0, perPage: perPage ?? 10 });
      return { experiments: result.experiments, pagination: result.pagination };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error listing experiments");
    }
  }
});
var TRIGGER_EXPERIMENT_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "POST",
  path: "/datasets/:datasetId/experiments",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  bodySchema: triggerExperimentBodySchema,
  responseSchema: experimentSummaryResponseSchema,
  summary: "Trigger a new experiment",
  description: "Triggers a new experiment on the dataset against the specified target. Returns immediately with pending status; execution happens in background.",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { targetType, targetId, scorerIds, version, maxConcurrency } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const result = await ds.startExperimentAsync({
        targetType,
        targetId,
        scorers: scorerIds,
        version,
        maxConcurrency
      });
      return {
        experimentId: result.experimentId,
        status: result.status,
        totalItems: 0,
        succeededCount: 0,
        failedCount: 0,
        startedAt: /* @__PURE__ */ new Date(),
        completedAt: null,
        results: []
      };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error triggering experiment");
    }
  }
});
var GET_EXPERIMENT_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/experiments/:experimentId",
  responseType: "json",
  pathParamSchema: datasetAndExperimentIdPathParams,
  responseSchema: experimentResponseSchema.nullable(),
  summary: "Get experiment by ID",
  description: "Returns details for a specific experiment",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, experimentId }) => {
    assertDatasetsAvailable();
    try {
      const ds = await mastra.datasets.get({ id: datasetId });
      const run = await ds.getExperiment({ experimentId });
      if (!run || run.datasetId !== datasetId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Experiment not found: ${experimentId}` });
      }
      return run;
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error getting experiment");
    }
  }
});
var LIST_EXPERIMENT_RESULTS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/experiments/:experimentId/results",
  responseType: "json",
  pathParamSchema: datasetAndExperimentIdPathParams,
  queryParamSchema: paginationQuerySchema,
  responseSchema: listExperimentResultsResponseSchema,
  summary: "List experiment results",
  description: "Returns a paginated list of results for the experiment",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, experimentId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { page, perPage } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const run = await ds.getExperiment({ experimentId });
      if (!run || run.datasetId !== datasetId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Experiment not found: ${experimentId}` });
      }
      const result = await ds.listExperimentResults({ experimentId, page: page ?? 0, perPage: perPage ?? 10 });
      return {
        results: result.results.map(({ experimentId: _eid, ...rest }) => ({ experimentId, ...rest })),
        pagination: result.pagination
      };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error listing experiment results");
    }
  }
});
var COMPARE_EXPERIMENTS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "POST",
  path: "/datasets/:datasetId/compare",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  bodySchema: compareExperimentsBodySchema,
  responseSchema: comparisonResponseSchema,
  summary: "Compare two experiments",
  description: "Compares two experiments to detect score regressions",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { experimentIdA, experimentIdB } = params;
      await mastra.datasets.get({ id: datasetId });
      const result = await mastra.datasets.compareExperiments({
        experimentIds: [experimentIdA, experimentIdB],
        baselineId: experimentIdA
      });
      return result;
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error comparing experiments");
    }
  }
});
var LIST_DATASET_VERSIONS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/versions",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  queryParamSchema: paginationQuerySchema,
  responseSchema: listDatasetVersionsResponseSchema,
  summary: "List dataset versions",
  description: "Returns a paginated list of all versions for the dataset",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { page, perPage } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const result = await ds.listVersions({ page: page ?? 0, perPage: perPage ?? 10 });
      return { versions: result.versions, pagination: result.pagination };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error listing dataset versions");
    }
  }
});
var LIST_ITEM_VERSIONS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/items/:itemId/history",
  responseType: "json",
  pathParamSchema: datasetAndItemIdPathParams,
  responseSchema: listItemVersionsResponseSchema,
  summary: "Get item history",
  description: "Returns the full SCD-2 history of the item across all dataset versions",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, itemId }) => {
    assertDatasetsAvailable();
    try {
      const ds = await mastra.datasets.get({ id: datasetId });
      const rows = await ds.getItemHistory({ itemId });
      if (rows.length > 0 && rows[0]?.datasetId !== datasetId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Item not found in dataset: ${itemId}` });
      }
      return { history: rows };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error listing item history");
    }
  }
});
var GET_ITEM_VERSION_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/datasets/:datasetId/items/:itemId/versions/:datasetVersion",
  responseType: "json",
  pathParamSchema: datasetItemVersionPathParams,
  responseSchema: datasetItemResponseSchema.nullable(),
  summary: "Get item at specific dataset version",
  description: "Returns the item as it existed at a specific dataset version",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, itemId, datasetVersion }) => {
    assertDatasetsAvailable();
    try {
      const ds = await mastra.datasets.get({ id: datasetId });
      const item = await ds.getItem({ itemId, version: datasetVersion });
      if (!item) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Item ${itemId} not found at version ${datasetVersion}` });
      }
      if (item.datasetId !== datasetId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Item not found in dataset: ${itemId}` });
      }
      return item;
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error getting item version");
    }
  }
});
var BATCH_INSERT_ITEMS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "POST",
  path: "/datasets/:datasetId/items/batch",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  bodySchema: batchInsertItemsBodySchema,
  responseSchema: batchInsertItemsResponseSchema,
  summary: "Batch insert items to dataset",
  description: "Adds multiple items to the dataset in a single operation (single version entry)",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { items } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      const addedItems = await ds.addItems({ items });
      return { items: addedItems, count: addedItems.length };
    } catch (error$1) {
      if (isSchemaValidationError(error$1)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: error$1.message,
          cause: { field: error$1.field, errors: error$1.errors }
        });
      }
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error batch inserting items");
    }
  }
});
var BATCH_DELETE_ITEMS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "DELETE",
  path: "/datasets/:datasetId/items/batch",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  bodySchema: batchDeleteItemsBodySchema,
  responseSchema: batchDeleteItemsResponseSchema,
  summary: "Batch delete items from dataset",
  description: "Deletes multiple items from the dataset in a single operation (single version entry)",
  tags: ["Datasets"],
  requiresAuth: true,
  handler: async ({ mastra, datasetId, ...params }) => {
    assertDatasetsAvailable();
    try {
      const { itemIds } = params;
      const ds = await mastra.datasets.get({ id: datasetId });
      await ds.deleteItems({ itemIds });
      return { success: true, deletedCount: itemIds.length };
    } catch (error$1) {
      if (error$1 instanceof error.MastraError) {
        throw new chunk64ITUOXI_cjs.HTTPException(getHttpStatusForMastraError(error$1.id), { message: error$1.message });
      }
      return chunkSUKFO7UM_cjs.handleError(error$1, "Error bulk deleting items");
    }
  }
});

exports.ADD_ITEM_ROUTE = ADD_ITEM_ROUTE;
exports.BATCH_DELETE_ITEMS_ROUTE = BATCH_DELETE_ITEMS_ROUTE;
exports.BATCH_INSERT_ITEMS_ROUTE = BATCH_INSERT_ITEMS_ROUTE;
exports.COMPARE_EXPERIMENTS_ROUTE = COMPARE_EXPERIMENTS_ROUTE;
exports.CREATE_DATASET_ROUTE = CREATE_DATASET_ROUTE;
exports.DELETE_DATASET_ROUTE = DELETE_DATASET_ROUTE;
exports.DELETE_ITEM_ROUTE = DELETE_ITEM_ROUTE;
exports.GET_DATASET_ROUTE = GET_DATASET_ROUTE;
exports.GET_EXPERIMENT_ROUTE = GET_EXPERIMENT_ROUTE;
exports.GET_ITEM_ROUTE = GET_ITEM_ROUTE;
exports.GET_ITEM_VERSION_ROUTE = GET_ITEM_VERSION_ROUTE;
exports.LIST_DATASETS_ROUTE = LIST_DATASETS_ROUTE;
exports.LIST_DATASET_VERSIONS_ROUTE = LIST_DATASET_VERSIONS_ROUTE;
exports.LIST_EXPERIMENTS_ROUTE = LIST_EXPERIMENTS_ROUTE;
exports.LIST_EXPERIMENT_RESULTS_ROUTE = LIST_EXPERIMENT_RESULTS_ROUTE;
exports.LIST_ITEMS_ROUTE = LIST_ITEMS_ROUTE;
exports.LIST_ITEM_VERSIONS_ROUTE = LIST_ITEM_VERSIONS_ROUTE;
exports.TRIGGER_EXPERIMENT_ROUTE = TRIGGER_EXPERIMENT_ROUTE;
exports.UPDATE_DATASET_ROUTE = UPDATE_DATASET_ROUTE;
exports.UPDATE_ITEM_ROUTE = UPDATE_ITEM_ROUTE;
//# sourceMappingURL=chunk-VJKU25DB.cjs.map
//# sourceMappingURL=chunk-VJKU25DB.cjs.map