'use strict';

var chunk2BIE3CHY_cjs = require('./chunk-2BIE3CHY.cjs');
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 z = require('zod');

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

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

var storedScorerIdPathParams = z__default.default.object({
  storedScorerId: z__default.default.string().describe("Unique identifier for the stored scorer definition")
});
var storageOrderBySchema = z__default.default.object({
  field: z__default.default.enum(["createdAt", "updatedAt"]).optional(),
  direction: z__default.default.enum(["ASC", "DESC"]).optional()
});
var listStoredScorersQuerySchema = chunkMCYD5LW7_cjs.createPagePaginationSchema(100).extend({
  orderBy: storageOrderBySchema.optional(),
  authorId: z__default.default.string().optional().describe("Filter scorers by author identifier"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Filter scorers by metadata key-value pairs")
});
var samplingConfigSchema = z__default.default.union([
  z__default.default.object({ type: z__default.default.literal("none") }),
  z__default.default.object({ type: z__default.default.literal("ratio"), rate: z__default.default.number().min(0).max(1) })
]);
var modelConfigSchema = z__default.default.object({
  provider: z__default.default.string().describe("Model provider (e.g., openai, anthropic)"),
  name: z__default.default.string().describe("Model name (e.g., gpt-4o, claude-3-opus)")
}).passthrough().describe("Model configuration");
var scorerTypeEnum = z__default.default.enum([
  "llm-judge",
  "answer-relevancy",
  "answer-similarity",
  "bias",
  "context-precision",
  "context-relevance",
  "faithfulness",
  "hallucination",
  "noise-sensitivity",
  "prompt-alignment",
  "tool-call-accuracy",
  "toxicity"
]).describe("Scorer type: llm-judge for custom, or a preset type name");
var snapshotConfigSchema = z__default.default.object({
  name: z__default.default.string().describe("Name of the scorer"),
  description: z__default.default.string().optional().describe("Description of the scorer"),
  type: scorerTypeEnum,
  model: modelConfigSchema.optional().describe("Model configuration for LLM judge"),
  instructions: z__default.default.string().optional().describe("System instructions for the judge LLM (used when type is llm-judge)"),
  scoreRange: z__default.default.object({
    min: z__default.default.number().optional().describe("Minimum score value (default: 0)"),
    max: z__default.default.number().optional().describe("Maximum score value (default: 1)")
  }).optional().describe("Score range configuration (used when type is llm-judge)"),
  presetConfig: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Serializable config options for preset scorers"),
  defaultSampling: samplingConfigSchema.optional().describe("Default sampling configuration")
});
var createStoredScorerBodySchema = z__default.default.object({
  id: z__default.default.string().optional().describe("Unique identifier. If not provided, derived from name."),
  authorId: z__default.default.string().optional().describe("Author identifier for multi-tenant filtering"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata for the scorer")
}).merge(snapshotConfigSchema);
var updateStoredScorerBodySchema = z__default.default.object({
  authorId: z__default.default.string().optional(),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional()
}).partial().merge(snapshotConfigSchema.partial());
var storedScorerSchema = z__default.default.object({
  id: z__default.default.string(),
  status: z__default.default.string().describe("Scorer status: draft, published, or archived"),
  activeVersionId: z__default.default.string().optional(),
  authorId: z__default.default.string().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(),
  name: z__default.default.string().describe("Name of the scorer"),
  description: z__default.default.string().optional().describe("Description of the scorer"),
  type: scorerTypeEnum,
  model: modelConfigSchema.optional(),
  instructions: z__default.default.string().optional().describe("System instructions for the judge LLM"),
  scoreRange: z__default.default.object({
    min: z__default.default.number().optional(),
    max: z__default.default.number().optional()
  }).optional(),
  presetConfig: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional(),
  defaultSampling: samplingConfigSchema.optional()
});
var listStoredScorersResponseSchema = chunkMCYD5LW7_cjs.paginationInfoSchema.extend({
  scorerDefinitions: z__default.default.array(storedScorerSchema)
});
var getStoredScorerResponseSchema = storedScorerSchema;
var createStoredScorerResponseSchema = storedScorerSchema;
var updateStoredScorerResponseSchema = z__default.default.union([
  z__default.default.object({
    id: z__default.default.string(),
    status: z__default.default.string(),
    activeVersionId: z__default.default.string().optional(),
    authorId: z__default.default.string().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()
  }),
  storedScorerSchema
]);
var deleteStoredScorerResponseSchema = z__default.default.object({
  success: z__default.default.boolean(),
  message: z__default.default.string()
});

// src/server/handlers/stored-scorers.ts
var LIST_STORED_SCORERS_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/stored/scorers",
  responseType: "json",
  queryParamSchema: listStoredScorersQuerySchema,
  responseSchema: listStoredScorersResponseSchema,
  summary: "List stored scorer definitions",
  description: "Returns a paginated list of all scorer definitions stored in the database",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({ mastra, page, perPage, orderBy, authorId, metadata }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const result = await scorerStore.listResolved({
        page,
        perPage,
        orderBy,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing stored scorer definitions");
    }
  }
});
var GET_STORED_SCORER_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: storedScorerIdPathParams,
  responseSchema: getStoredScorerResponseSchema,
  summary: "Get stored scorer definition by ID",
  description: "Returns a specific scorer definition from storage by its unique identifier (resolved with active version config)",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({ mastra, storedScorerId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getByIdResolved(storedScorerId);
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      return scorer;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting stored scorer definition");
    }
  }
});
var CREATE_STORED_SCORER_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "POST",
  path: "/stored/scorers",
  responseType: "json",
  bodySchema: createStoredScorerBodySchema,
  responseSchema: createStoredScorerResponseSchema,
  summary: "Create stored scorer definition",
  description: "Creates a new scorer definition in storage with the provided configuration",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({
    mastra,
    id: providedId,
    authorId,
    metadata,
    name,
    description,
    type,
    model,
    instructions,
    scoreRange,
    presetConfig,
    defaultSampling
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const id = providedId || chunk2BIE3CHY_cjs.toSlug(name);
      if (!id) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Could not derive scorer definition ID from name. Please provide an explicit id."
        });
      }
      const existing = await scorerStore.getById(id);
      if (existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(409, { message: `Scorer definition with id ${id} already exists` });
      }
      await scorerStore.create({
        scorerDefinition: {
          id,
          authorId,
          metadata,
          name,
          description,
          type,
          model,
          instructions,
          scoreRange,
          presetConfig,
          defaultSampling
        }
      });
      const resolved = await scorerStore.getByIdResolved(id);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created scorer definition" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating stored scorer definition");
    }
  }
});
var UPDATE_STORED_SCORER_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "PATCH",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: storedScorerIdPathParams,
  bodySchema: updateStoredScorerBodySchema,
  responseSchema: updateStoredScorerResponseSchema,
  summary: "Update stored scorer definition",
  description: "Updates an existing scorer definition in storage with the provided fields",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({
    mastra,
    storedScorerId,
    // Metadata-level fields
    authorId,
    metadata,
    // Config fields (snapshot-level)
    name,
    description,
    type,
    model,
    instructions,
    scoreRange,
    presetConfig,
    defaultSampling
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      await scorerStore.update({
        id: storedScorerId,
        authorId,
        metadata,
        name,
        description,
        type,
        model,
        instructions,
        scoreRange,
        presetConfig,
        defaultSampling
      });
      const editor = mastra.getEditor();
      if (editor) {
        editor.scorer.clearCache(storedScorerId);
      }
      const resolved = await scorerStore.getByIdResolved(storedScorerId);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated scorer definition" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error updating stored scorer definition");
    }
  }
});
var DELETE_STORED_SCORER_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "DELETE",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: storedScorerIdPathParams,
  responseSchema: deleteStoredScorerResponseSchema,
  summary: "Delete stored scorer definition",
  description: "Deletes a scorer definition from storage by its unique identifier",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({ mastra, storedScorerId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      await scorerStore.delete(storedScorerId);
      mastra.getEditor()?.scorer.clearCache(storedScorerId);
      return { success: true, message: `Scorer definition ${storedScorerId} deleted successfully` };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error deleting stored scorer definition");
    }
  }
});

exports.CREATE_STORED_SCORER_ROUTE = CREATE_STORED_SCORER_ROUTE;
exports.DELETE_STORED_SCORER_ROUTE = DELETE_STORED_SCORER_ROUTE;
exports.GET_STORED_SCORER_ROUTE = GET_STORED_SCORER_ROUTE;
exports.LIST_STORED_SCORERS_ROUTE = LIST_STORED_SCORERS_ROUTE;
exports.UPDATE_STORED_SCORER_ROUTE = UPDATE_STORED_SCORER_ROUTE;
//# sourceMappingURL=chunk-WM6WHAM6.cjs.map
//# sourceMappingURL=chunk-WM6WHAM6.cjs.map