import { getAgentFromSystem } from './chunk-LP3TMC5I.js';
import { paginationInfoSchema, runIdSchema } from './chunk-HT4LP3BO.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-D5VCL56B.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import z from 'zod';

// src/server/handlers/scores.ts
var scores_exports = {};
__export(scores_exports, {
  GET_SCORER_ROUTE: () => GET_SCORER_ROUTE,
  LIST_SCORERS_ROUTE: () => LIST_SCORERS_ROUTE,
  LIST_SCORES_BY_ENTITY_ID_ROUTE: () => LIST_SCORES_BY_ENTITY_ID_ROUTE,
  LIST_SCORES_BY_RUN_ID_ROUTE: () => LIST_SCORES_BY_RUN_ID_ROUTE,
  LIST_SCORES_BY_SCORER_ID_ROUTE: () => LIST_SCORES_BY_SCORER_ID_ROUTE,
  SAVE_SCORE_ROUTE: () => SAVE_SCORE_ROUTE
});
var scoringSamplingConfigSchema = z.object({});
var mastraScorerConfigSchema = z.object({
  id: z.string(),
  name: z.string().optional(),
  description: z.string(),
  type: z.unknown().optional(),
  judge: z.unknown().optional()
});
var mastraScorerSchema = z.object({
  config: mastraScorerConfigSchema
});
var scorerEntrySchema = z.object({
  scorer: mastraScorerSchema,
  sampling: scoringSamplingConfigSchema.optional(),
  agentIds: z.array(z.string()),
  agentNames: z.array(z.string()),
  workflowIds: z.array(z.string()),
  isRegistered: z.boolean()
});
var listScorersResponseSchema = z.record(z.string(), scorerEntrySchema);
var scorerIdPathParams = z.object({
  scorerId: z.string().describe("Unique identifier for the scorer")
});
var entityPathParams = z.object({
  entityType: z.string().describe("Type of the entity (AGENT or WORKFLOW)"),
  entityId: z.string().describe("Unique identifier for the entity")
});
var listScoresByRunIdQuerySchema = z.object({
  page: z.coerce.number().optional().default(0),
  perPage: z.coerce.number().optional().default(10)
});
var listScoresByScorerIdQuerySchema = z.object({
  page: z.coerce.number().optional().default(0),
  perPage: z.coerce.number().optional().default(10),
  entityId: z.string().optional(),
  entityType: z.string().optional()
});
var listScoresByEntityIdQuerySchema = z.object({
  page: z.coerce.number().optional().default(0),
  perPage: z.coerce.number().optional().default(10)
});
var saveScoreBodySchema = z.object({
  score: z.unknown()
  // ScoreRowData - complex type
});
var scoresWithPaginationResponseSchema = z.object({
  pagination: paginationInfoSchema,
  scores: z.array(z.unknown())
  // Array of score records
});
var saveScoreResponseSchema = z.object({
  score: z.unknown()
  // ScoreRowData
});

// src/server/handlers/scores.ts
async function listScorersFromSystem({
  mastra,
  requestContext
}) {
  const agents = mastra.listAgents();
  const workflows = mastra.listWorkflows();
  const scorersMap = /* @__PURE__ */ new Map();
  const processAgentScorers = async (agent) => {
    const scorers = await agent.listScorers({
      requestContext
    }) || {};
    if (Object.keys(scorers).length > 0) {
      for (const [_scorerId, scorer] of Object.entries(scorers)) {
        const scorerId = scorer.scorer.id;
        if (scorersMap.has(scorerId)) {
          scorersMap.get(scorerId)?.agentIds.push(agent.id);
          scorersMap.get(scorerId)?.agentNames.push(agent.name);
        } else {
          scorersMap.set(scorerId, {
            workflowIds: [],
            ...scorer,
            agentNames: [agent.name],
            agentIds: [agent.id],
            isRegistered: false
          });
        }
      }
    }
  };
  for (const [_, agent] of Object.entries(agents)) {
    await processAgentScorers(agent);
  }
  try {
    const editor = mastra.getEditor();
    const storedAgentsResult = await editor?.agent.list();
    if (storedAgentsResult?.agents) {
      for (const storedAgentConfig of storedAgentsResult.agents) {
        try {
          const agent = await editor?.agent.getById(storedAgentConfig.id);
          if (agent) {
            await processAgentScorers(agent);
          }
        } catch {
        }
      }
    }
  } catch {
  }
  try {
    const editor = mastra.getEditor();
    const storedScorersResult = await editor?.scorer.list();
    if (storedScorersResult?.scorerDefinitions) {
      for (const storedScorerConfig of storedScorersResult.scorerDefinitions) {
        try {
          await editor?.scorer.getById(storedScorerConfig.id);
        } catch {
        }
      }
    }
  } catch {
  }
  for (const [workflowId, workflow] of Object.entries(workflows)) {
    const scorers = await workflow.listScorers({
      requestContext
    }) || {};
    if (Object.keys(scorers).length > 0) {
      for (const [_scorerId, scorer] of Object.entries(scorers)) {
        const scorerName = scorer.scorer.name;
        if (scorersMap.has(scorerName)) {
          scorersMap.get(scorerName)?.workflowIds.push(workflowId);
        } else {
          scorersMap.set(scorerName, {
            agentIds: [],
            agentNames: [],
            ...scorer,
            workflowIds: [workflowId],
            isRegistered: false
          });
        }
      }
    }
  }
  const registeredScorers = await mastra.listScorers();
  for (const [_scorerId, scorer] of Object.entries(registeredScorers || {})) {
    const scorerId = scorer.id;
    if (scorersMap.has(scorerId)) {
      scorersMap.get(scorerId).isRegistered = true;
    } else {
      scorersMap.set(scorerId, {
        scorer,
        agentIds: [],
        agentNames: [],
        workflowIds: [],
        isRegistered: true
      });
    }
  }
  return Object.fromEntries(scorersMap.entries());
}
function getTraceDetails(traceIdWithSpanId) {
  if (!traceIdWithSpanId) {
    return {};
  }
  const [traceId, spanId] = traceIdWithSpanId.split("-");
  return {
    ...traceId ? { traceId } : {},
    ...spanId ? { spanId } : {}
  };
}
var LIST_SCORERS_ROUTE = createRoute({
  method: "GET",
  path: "/scores/scorers",
  responseType: "json",
  responseSchema: listScorersResponseSchema,
  summary: "List all scorers",
  description: "Returns a list of all registered scorers with their configuration and associated agents and workflows",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, requestContext }) => {
    const scorers = await listScorersFromSystem({
      mastra,
      requestContext
    });
    return scorers;
  }
});
var GET_SCORER_ROUTE = createRoute({
  method: "GET",
  path: "/scores/scorers/:scorerId",
  responseType: "json",
  pathParamSchema: scorerIdPathParams,
  responseSchema: scorerEntrySchema.nullable(),
  summary: "Get scorer by ID",
  description: "Returns details for a specific scorer including its configuration and associations",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, scorerId, requestContext }) => {
    const scorers = await listScorersFromSystem({
      mastra,
      requestContext
    });
    const scorer = scorers[scorerId];
    if (!scorer) {
      return null;
    }
    return scorer;
  }
});
var LIST_SCORES_BY_RUN_ID_ROUTE = createRoute({
  method: "GET",
  path: "/scores/run/:runId",
  responseType: "json",
  pathParamSchema: runIdSchema,
  queryParamSchema: listScoresByRunIdQuerySchema,
  responseSchema: scoresWithPaginationResponseSchema,
  summary: "List scores by run ID",
  description: "Returns all scores for a specific execution run",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, runId, ...params }) => {
    try {
      const { page, perPage } = params;
      const pagination = {
        page: page ?? 0,
        perPage: perPage ?? 10
      };
      const scores = await mastra.getStorage()?.getStore("scores");
      const scoreResults = await scores?.listScoresByRunId?.({
        runId,
        pagination
      }) || { pagination: { total: 0, page: 0, perPage: 0, hasMore: false }, scores: [] };
      return {
        pagination: scoreResults.pagination,
        scores: scoreResults.scores.map((score) => ({ ...score, ...getTraceDetails(score.traceId) }))
      };
    } catch (error) {
      return handleError(error, "Error getting scores by run id");
    }
  }
});
var LIST_SCORES_BY_SCORER_ID_ROUTE = createRoute({
  method: "GET",
  path: "/scores/scorer/:scorerId",
  responseType: "json",
  pathParamSchema: scorerIdPathParams,
  queryParamSchema: listScoresByScorerIdQuerySchema,
  responseSchema: scoresWithPaginationResponseSchema,
  summary: "List scores by scorer ID",
  description: "Returns all scores generated by a specific scorer",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, scorerId, ...params }) => {
    try {
      const { page, perPage, entityId, entityType } = params;
      const filters = Object.fromEntries(Object.entries({ entityId, entityType }).filter(([_, v]) => v !== void 0));
      const scores = await mastra.getStorage()?.getStore("scores");
      const scoreResults = await scores?.listScoresByScorerId?.({
        scorerId,
        pagination: { page: page ?? 0, perPage: perPage ?? 10 },
        ...filters
      }) || { pagination: { total: 0, page: 0, perPage: 0, hasMore: false }, scores: [] };
      return {
        pagination: scoreResults.pagination,
        scores: scoreResults.scores.map((score) => ({ ...score, ...getTraceDetails(score.traceId) }))
      };
    } catch (error) {
      return handleError(error, "Error getting scores by scorer id");
    }
  }
});
var LIST_SCORES_BY_ENTITY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/scores/entity/:entityType/:entityId",
  responseType: "json",
  pathParamSchema: entityPathParams,
  queryParamSchema: listScoresByEntityIdQuerySchema,
  responseSchema: scoresWithPaginationResponseSchema,
  summary: "List scores by entity ID",
  description: "Returns all scores for a specific entity (agent or workflow)",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, entityId, entityType, ...params }) => {
    try {
      const { page, perPage } = params;
      let entityIdToUse = entityId;
      if (entityType === "AGENT") {
        const agent = await getAgentFromSystem({ mastra, agentId: entityId });
        entityIdToUse = agent.id;
      } else if (entityType === "WORKFLOW") {
        const workflow = mastra.getWorkflowById(entityId);
        entityIdToUse = workflow.id;
      }
      const pagination = {
        page: page ?? 0,
        perPage: perPage ?? 10
      };
      const scoresStore = await mastra.getStorage()?.getStore("scores");
      const scoreResults = await scoresStore?.listScoresByEntityId?.({
        entityId: entityIdToUse,
        entityType,
        pagination
      }) || { pagination: { total: 0, page: 0, perPage: 0, hasMore: false }, scores: [] };
      return {
        pagination: scoreResults.pagination,
        scores: scoreResults.scores.map((score) => ({ ...score, ...getTraceDetails(score.traceId) }))
      };
    } catch (error) {
      return handleError(error, "Error getting scores by entity id");
    }
  }
});
var SAVE_SCORE_ROUTE = createRoute({
  method: "POST",
  path: "/scores",
  responseType: "json",
  bodySchema: saveScoreBodySchema,
  responseSchema: saveScoreResponseSchema,
  summary: "Save score",
  description: "Saves a new score record to storage",
  tags: ["Scoring"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    try {
      const { score } = params;
      const scoresStore = await mastra.getStorage()?.getStore("scores");
      const result = await scoresStore?.saveScore?.(score);
      if (!result) {
        throw new HTTPException(500, { message: "Storage not configured" });
      }
      return result;
    } catch (error) {
      return handleError(error, "Error saving score");
    }
  }
});

export { GET_SCORER_ROUTE, LIST_SCORERS_ROUTE, LIST_SCORES_BY_ENTITY_ID_ROUTE, LIST_SCORES_BY_RUN_ID_ROUTE, LIST_SCORES_BY_SCORER_ID_ROUTE, SAVE_SCORE_ROUTE, scores_exports };
//# sourceMappingURL=chunk-HF4Q3ZXB.js.map
//# sourceMappingURL=chunk-HF4Q3ZXB.js.map