import { toSlug } from './chunk-LII44FTI.js';
import { createPagePaginationSchema, paginationInfoSchema } from './chunk-HT4LP3BO.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-D5VCL56B.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import z from 'zod';

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

// src/server/handlers/stored-scorers.ts
var LIST_STORED_SCORERS_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new 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 handleError(error, "Error listing stored scorer definitions");
    }
  }
});
var GET_STORED_SCORER_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getByIdResolved(storedScorerId);
      if (!scorer) {
        throw new HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      return scorer;
    } catch (error) {
      return handleError(error, "Error getting stored scorer definition");
    }
  }
});
var CREATE_STORED_SCORER_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const id = providedId || toSlug(name);
      if (!id) {
        throw new 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 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 HTTPException(500, { message: "Failed to resolve created scorer definition" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error creating stored scorer definition");
    }
  }
});
var UPDATE_STORED_SCORER_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new 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 HTTPException(500, { message: "Failed to resolve updated scorer definition" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error updating stored scorer definition");
    }
  }
});
var DELETE_STORED_SCORER_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new 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 handleError(error, "Error deleting stored scorer definition");
    }
  }
});

export { CREATE_STORED_SCORER_ROUTE, DELETE_STORED_SCORER_ROUTE, GET_STORED_SCORER_ROUTE, LIST_STORED_SCORERS_ROUTE, UPDATE_STORED_SCORER_ROUTE };
//# sourceMappingURL=chunk-5VYQDYZU.js.map
//# sourceMappingURL=chunk-5VYQDYZU.js.map