'use strict';

var chunkPWHXCQ22_cjs = require('./chunk-PWHXCQ22.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 chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var z = require('zod');

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

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

// src/server/handlers/scores.ts
var scores_exports = {};
chunkO7I5CWRX_cjs.__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__default.default.object({});
var mastraScorerConfigSchema = z__default.default.object({
  id: z__default.default.string(),
  name: z__default.default.string().optional(),
  description: z__default.default.string(),
  type: z__default.default.unknown().optional(),
  judge: z__default.default.unknown().optional()
});
var mastraScorerSchema = z__default.default.object({
  config: mastraScorerConfigSchema
});
var scorerEntrySchema = z__default.default.object({
  scorer: mastraScorerSchema,
  sampling: scoringSamplingConfigSchema.optional(),
  agentIds: z__default.default.array(z__default.default.string()),
  agentNames: z__default.default.array(z__default.default.string()),
  workflowIds: z__default.default.array(z__default.default.string()),
  isRegistered: z__default.default.boolean()
});
var listScorersResponseSchema = z__default.default.record(z__default.default.string(), scorerEntrySchema);
var scorerIdPathParams = z__default.default.object({
  scorerId: z__default.default.string().describe("Unique identifier for the scorer")
});
var entityPathParams = z__default.default.object({
  entityType: z__default.default.string().describe("Type of the entity (AGENT or WORKFLOW)"),
  entityId: z__default.default.string().describe("Unique identifier for the entity")
});
var listScoresByRunIdQuerySchema = z__default.default.object({
  page: z__default.default.coerce.number().optional().default(0),
  perPage: z__default.default.coerce.number().optional().default(10)
});
var listScoresByScorerIdQuerySchema = z__default.default.object({
  page: z__default.default.coerce.number().optional().default(0),
  perPage: z__default.default.coerce.number().optional().default(10),
  entityId: z__default.default.string().optional(),
  entityType: z__default.default.string().optional()
});
var listScoresByEntityIdQuerySchema = z__default.default.object({
  page: z__default.default.coerce.number().optional().default(0),
  perPage: z__default.default.coerce.number().optional().default(10)
});
var saveScoreBodySchema = z__default.default.object({
  score: z__default.default.unknown()
  // ScoreRowData - complex type
});
var scoresWithPaginationResponseSchema = z__default.default.object({
  pagination: chunkMCYD5LW7_cjs.paginationInfoSchema,
  scores: z__default.default.array(z__default.default.unknown())
  // Array of score records
});
var saveScoreResponseSchema = z__default.default.object({
  score: z__default.default.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 = chunkK52BGIHQ_cjs.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 = chunkK52BGIHQ_cjs.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 = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/scores/run/:runId",
  responseType: "json",
  pathParamSchema: chunkMCYD5LW7_cjs.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 chunkSUKFO7UM_cjs.handleError(error, "Error getting scores by run id");
    }
  }
});
var LIST_SCORES_BY_SCORER_ID_ROUTE = chunkK52BGIHQ_cjs.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 chunkSUKFO7UM_cjs.handleError(error, "Error getting scores by scorer id");
    }
  }
});
var LIST_SCORES_BY_ENTITY_ID_ROUTE = chunkK52BGIHQ_cjs.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 chunkPWHXCQ22_cjs.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 chunkSUKFO7UM_cjs.handleError(error, "Error getting scores by entity id");
    }
  }
});
var SAVE_SCORE_ROUTE = chunkK52BGIHQ_cjs.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 chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage not configured" });
      }
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error saving score");
    }
  }
});

exports.GET_SCORER_ROUTE = GET_SCORER_ROUTE;
exports.LIST_SCORERS_ROUTE = LIST_SCORERS_ROUTE;
exports.LIST_SCORES_BY_ENTITY_ID_ROUTE = LIST_SCORES_BY_ENTITY_ID_ROUTE;
exports.LIST_SCORES_BY_RUN_ID_ROUTE = LIST_SCORES_BY_RUN_ID_ROUTE;
exports.LIST_SCORES_BY_SCORER_ID_ROUTE = LIST_SCORES_BY_SCORER_ID_ROUTE;
exports.SAVE_SCORE_ROUTE = SAVE_SCORE_ROUTE;
exports.scores_exports = scores_exports;
//# sourceMappingURL=chunk-W55S54WH.cjs.map
//# sourceMappingURL=chunk-W55S54WH.cjs.map