import { paginationInfoSchema, successResponseSchema } from './chunk-HT4LP3BO.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-OQ5GQJAS.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { MastraError } from '@mastra/core/error';
import { coreFeatures } from '@mastra/core/features';
import z from 'zod';

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

// src/server/handlers/datasets.ts
function assertDatasetsAvailable() {
  if (!coreFeatures.has("datasets")) {
    throw new 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 = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error listing datasets");
    }
  }
});
var CREATE_DATASET_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error creating dataset");
    }
  }
});
var GET_DATASET_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error getting dataset");
    }
  }
});
var UPDATE_DATASET_ROUTE = 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) {
      if (isSchemaUpdateValidationError(error)) {
        throw new HTTPException(400, {
          message: error.message,
          cause: { failingItems: error.failingItems }
        });
      }
      if (isSchemaValidationError(error)) {
        throw new HTTPException(400, {
          message: error.message,
          cause: { field: error.field, errors: error.errors }
        });
      }
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error updating dataset");
    }
  }
});
var DELETE_DATASET_ROUTE = createRoute({
  method: "DELETE",
  path: "/datasets/:datasetId",
  responseType: "json",
  pathParamSchema: datasetIdPathParams,
  responseSchema: 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error deleting dataset");
    }
  }
});
var LIST_ITEMS_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error listing dataset items");
    }
  }
});
var ADD_ITEM_ROUTE = 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) {
      if (isSchemaValidationError(error)) {
        throw new HTTPException(400, {
          message: error.message,
          cause: { field: error.field, errors: error.errors }
        });
      }
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error adding item to dataset");
    }
  }
});
var GET_ITEM_ROUTE = 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 HTTPException(404, { message: `Item not found: ${itemId}` });
      }
      return item;
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error getting dataset item");
    }
  }
});
var UPDATE_ITEM_ROUTE = 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 HTTPException(404, { message: `Item not found: ${itemId}` });
      }
      return await ds.updateItem({ itemId, input, groundTruth, metadata });
    } catch (error) {
      if (isSchemaValidationError(error)) {
        throw new HTTPException(400, {
          message: error.message,
          cause: { field: error.field, errors: error.errors }
        });
      }
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error updating dataset item");
    }
  }
});
var DELETE_ITEM_ROUTE = createRoute({
  method: "DELETE",
  path: "/datasets/:datasetId/items/:itemId",
  responseType: "json",
  pathParamSchema: datasetAndItemIdPathParams,
  responseSchema: 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 HTTPException(404, { message: `Item not found: ${itemId}` });
      }
      await ds.deleteItem({ itemId });
      return { success: true };
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error deleting dataset item");
    }
  }
});
var LIST_EXPERIMENTS_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error listing experiments");
    }
  }
});
var TRIGGER_EXPERIMENT_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error triggering experiment");
    }
  }
});
var GET_EXPERIMENT_ROUTE = 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 HTTPException(404, { message: `Experiment not found: ${experimentId}` });
      }
      return run;
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error getting experiment");
    }
  }
});
var LIST_EXPERIMENT_RESULTS_ROUTE = 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 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error listing experiment results");
    }
  }
});
var COMPARE_EXPERIMENTS_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error comparing experiments");
    }
  }
});
var LIST_DATASET_VERSIONS_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error listing dataset versions");
    }
  }
});
var LIST_ITEM_VERSIONS_ROUTE = 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 HTTPException(404, { message: `Item not found in dataset: ${itemId}` });
      }
      return { history: rows };
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error listing item history");
    }
  }
});
var GET_ITEM_VERSION_ROUTE = 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 HTTPException(404, { message: `Item ${itemId} not found at version ${datasetVersion}` });
      }
      if (item.datasetId !== datasetId) {
        throw new HTTPException(404, { message: `Item not found in dataset: ${itemId}` });
      }
      return item;
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error getting item version");
    }
  }
});
var BATCH_INSERT_ITEMS_ROUTE = 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) {
      if (isSchemaValidationError(error)) {
        throw new HTTPException(400, {
          message: error.message,
          cause: { field: error.field, errors: error.errors }
        });
      }
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error batch inserting items");
    }
  }
});
var BATCH_DELETE_ITEMS_ROUTE = 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) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id), { message: error.message });
      }
      return handleError(error, "Error bulk deleting items");
    }
  }
});

export { ADD_ITEM_ROUTE, BATCH_DELETE_ITEMS_ROUTE, BATCH_INSERT_ITEMS_ROUTE, COMPARE_EXPERIMENTS_ROUTE, CREATE_DATASET_ROUTE, DELETE_DATASET_ROUTE, DELETE_ITEM_ROUTE, GET_DATASET_ROUTE, GET_EXPERIMENT_ROUTE, GET_ITEM_ROUTE, GET_ITEM_VERSION_ROUTE, LIST_DATASETS_ROUTE, LIST_DATASET_VERSIONS_ROUTE, LIST_EXPERIMENTS_ROUTE, LIST_EXPERIMENT_RESULTS_ROUTE, LIST_ITEMS_ROUTE, LIST_ITEM_VERSIONS_ROUTE, TRIGGER_EXPERIMENT_ROUTE, UPDATE_DATASET_ROUTE, UPDATE_ITEM_ROUTE };
//# sourceMappingURL=chunk-KHA3D2IU.js.map
//# sourceMappingURL=chunk-KHA3D2IU.js.map