'use strict';

var chunkY2BKW5ND_cjs = require('./chunk-Y2BKW5ND.cjs');
var chunk6P7P7Y5U_cjs = require('./chunk-6P7P7Y5U.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var evals = require('@mastra/core/evals');
var scoreTraces = require('@mastra/core/evals/scoreTraces');
var storage = require('@mastra/core/storage');
var zod = require('zod');

// src/server/handlers/observability.ts
var observability_exports = {};
chunkO7I5CWRX_cjs.__export(observability_exports, {
  GET_TRACE_ROUTE: () => GET_TRACE_ROUTE,
  LIST_SCORES_BY_SPAN_ROUTE: () => LIST_SCORES_BY_SPAN_ROUTE,
  LIST_TRACES_ROUTE: () => LIST_TRACES_ROUTE,
  SCORE_TRACES_ROUTE: () => SCORE_TRACES_ROUTE
});
var legacyQueryParamsSchema = zod.z.object({
  // Old: dateRange was in pagination, now it's startedAt in filters
  dateRange: storage.dateRangeSchema.optional(),
  // Old: name matched span names like "agent run: 'myAgent'"
  name: zod.z.string().optional(),
  // entityType needs preprocessing to handle legacy 'workflow' value
  entityType: zod.z.preprocess((val) => val === "workflow" ? "workflow_run" : val, zod.z.string().optional())
});
function transformLegacyParams(params) {
  const result = { ...params };
  if (result.entityType === "workflow") {
    result.entityType = "workflow_run";
  }
  if (params.dateRange && !params.startedAt) {
    result.startedAt = params.dateRange;
    delete result.dateRange;
  }
  if (typeof params.name === "string" && !params.entityId) {
    const agentMatch = params.name.match(/^agent run: '([^']+)'$/);
    const workflowMatch = params.name.match(/^workflow run: '([^']+)'$/);
    if (agentMatch) {
      result.entityId = agentMatch[1];
      result.entityType = "agent";
    } else if (workflowMatch) {
      result.entityId = workflowMatch[1];
      result.entityType = "workflow_run";
    }
    delete result.name;
  }
  return result;
}
function getStorage(mastra) {
  const storage = mastra.getStorage();
  if (!storage) {
    throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not available" });
  }
  return storage;
}
async function getObservabilityStore(mastra) {
  const storage = getStorage(mastra);
  const observability = await storage.getStore("observability");
  if (!observability) {
    throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Observability storage domain is not available" });
  }
  return observability;
}
async function getScoresStore(mastra) {
  const storage = getStorage(mastra);
  const scores = await storage.getStore("scores");
  if (!scores) {
    throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scores storage domain is not available" });
  }
  return scores;
}
var LIST_TRACES_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "GET",
  path: "/observability/traces",
  responseType: "json",
  queryParamSchema: chunk6P7P7Y5U_cjs.wrapSchemaForQueryParams(
    storage.tracesFilterSchema.extend(storage.paginationArgsSchema.shape).extend(storage.tracesOrderBySchema.shape).extend(legacyQueryParamsSchema.shape).partial()
  ),
  responseSchema: storage.listTracesResponseSchema,
  summary: "List traces",
  description: "Returns a paginated list of traces with optional filtering and sorting",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    try {
      const transformedParams = transformLegacyParams(params);
      const filters = chunk6P7P7Y5U_cjs.pickParams(storage.tracesFilterSchema, transformedParams);
      const pagination = chunk6P7P7Y5U_cjs.pickParams(storage.paginationArgsSchema, transformedParams);
      const orderBy = chunk6P7P7Y5U_cjs.pickParams(storage.tracesOrderBySchema, transformedParams);
      const observabilityStore = await getObservabilityStore(mastra);
      return await observabilityStore.listTraces({ filters, pagination, orderBy });
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error listing traces");
    }
  }
});
var GET_TRACE_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/:traceId",
  responseType: "json",
  pathParamSchema: storage.getTraceArgsSchema,
  responseSchema: storage.getTraceResponseSchema,
  summary: "Get AI trace by ID",
  description: "Returns a complete AI trace with all spans by trace ID",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, traceId }) => {
    try {
      const observabilityStore = await getObservabilityStore(mastra);
      const trace = await observabilityStore.getTrace({ traceId });
      if (!trace) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Trace with ID '${traceId}' not found` });
      }
      return trace;
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error getting trace");
    }
  }
});
var SCORE_TRACES_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "POST",
  path: "/observability/traces/score",
  responseType: "json",
  bodySchema: storage.scoreTracesRequestSchema,
  responseSchema: storage.scoreTracesResponseSchema,
  summary: "Score traces",
  description: "Scores one or more traces using a specified scorer (fire-and-forget)",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    try {
      getStorage(mastra);
      const { scorerName, targets } = params;
      const scorer = mastra.getScorerById(scorerName);
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Scorer '${scorerName}' not found` });
      }
      scoreTraces.scoreTraces({
        scorerId: scorer.config.id || scorer.config.name,
        targets,
        mastra
      }).catch((error) => {
        const logger = mastra.getLogger();
        logger?.error(`Background trace scoring failed: ${error.message}`, error);
      });
      return {
        status: "success",
        message: `Scoring started for ${targets.length} ${targets.length === 1 ? "trace" : "traces"}`,
        traceCount: targets.length
      };
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error processing trace scoring");
    }
  }
});
var LIST_SCORES_BY_SPAN_ROUTE = chunk6P7P7Y5U_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/:spanId/scores",
  responseType: "json",
  pathParamSchema: storage.spanIdsSchema,
  queryParamSchema: storage.paginationArgsSchema,
  responseSchema: evals.listScoresResponseSchema,
  summary: "List scores by span",
  description: "Returns all scores for a specific span within a trace",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    try {
      const pagination = chunk6P7P7Y5U_cjs.pickParams(storage.paginationArgsSchema, params);
      const spanIds = chunk6P7P7Y5U_cjs.pickParams(storage.spanIdsSchema, params);
      const scoresStore = await getScoresStore(mastra);
      return await scoresStore.listScoresBySpan({
        ...spanIds,
        pagination
      });
    } catch (error) {
      return chunkY2BKW5ND_cjs.handleError(error, "Error getting scores by span");
    }
  }
});

exports.GET_TRACE_ROUTE = GET_TRACE_ROUTE;
exports.LIST_SCORES_BY_SPAN_ROUTE = LIST_SCORES_BY_SPAN_ROUTE;
exports.LIST_TRACES_ROUTE = LIST_TRACES_ROUTE;
exports.SCORE_TRACES_ROUTE = SCORE_TRACES_ROUTE;
exports.observability_exports = observability_exports;
//# sourceMappingURL=chunk-ALE53JHX.cjs.map
//# sourceMappingURL=chunk-ALE53JHX.cjs.map