'use strict';

var chunkEFP5PJBY_cjs = require('./chunk-EFP5PJBY.cjs');
var chunkTU7U5XUE_cjs = require('./chunk-TU7U5XUE.cjs');
var chunk5UKYK7YK_cjs = require('./chunk-5UKYK7YK.cjs');
var chunkB34S64RC_cjs = require('./chunk-B34S64RC.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 v4 = require('zod/v4');

// src/server/handlers/observability.ts
var observability_exports = {};
chunkO7I5CWRX_cjs.__export(observability_exports, {
  CREATE_FEEDBACK: () => chunkEFP5PJBY_cjs.CREATE_FEEDBACK,
  CREATE_SCORE: () => chunkEFP5PJBY_cjs.CREATE_SCORE,
  GET_ENTITY_NAMES: () => chunkEFP5PJBY_cjs.GET_ENTITY_NAMES,
  GET_ENTITY_TYPES: () => chunkEFP5PJBY_cjs.GET_ENTITY_TYPES,
  GET_ENVIRONMENTS: () => chunkEFP5PJBY_cjs.GET_ENVIRONMENTS,
  GET_FEEDBACK_AGGREGATE: () => chunkEFP5PJBY_cjs.GET_FEEDBACK_AGGREGATE,
  GET_FEEDBACK_BREAKDOWN: () => chunkEFP5PJBY_cjs.GET_FEEDBACK_BREAKDOWN,
  GET_FEEDBACK_PERCENTILES: () => chunkEFP5PJBY_cjs.GET_FEEDBACK_PERCENTILES,
  GET_FEEDBACK_TIME_SERIES: () => chunkEFP5PJBY_cjs.GET_FEEDBACK_TIME_SERIES,
  GET_METRIC_AGGREGATE: () => chunkEFP5PJBY_cjs.GET_METRIC_AGGREGATE,
  GET_METRIC_BREAKDOWN: () => chunkEFP5PJBY_cjs.GET_METRIC_BREAKDOWN,
  GET_METRIC_LABEL_KEYS: () => chunkEFP5PJBY_cjs.GET_METRIC_LABEL_KEYS,
  GET_METRIC_LABEL_VALUES: () => chunkEFP5PJBY_cjs.GET_METRIC_LABEL_VALUES,
  GET_METRIC_NAMES: () => chunkEFP5PJBY_cjs.GET_METRIC_NAMES,
  GET_METRIC_PERCENTILES: () => chunkEFP5PJBY_cjs.GET_METRIC_PERCENTILES,
  GET_METRIC_TIME_SERIES: () => chunkEFP5PJBY_cjs.GET_METRIC_TIME_SERIES,
  GET_SCORE_AGGREGATE: () => chunkEFP5PJBY_cjs.GET_SCORE_AGGREGATE,
  GET_SCORE_BREAKDOWN: () => chunkEFP5PJBY_cjs.GET_SCORE_BREAKDOWN,
  GET_SCORE_PERCENTILES: () => chunkEFP5PJBY_cjs.GET_SCORE_PERCENTILES,
  GET_SCORE_TIME_SERIES: () => chunkEFP5PJBY_cjs.GET_SCORE_TIME_SERIES,
  GET_SERVICE_NAMES: () => chunkEFP5PJBY_cjs.GET_SERVICE_NAMES,
  GET_SPAN_ROUTE: () => GET_SPAN_ROUTE,
  GET_TAGS: () => chunkEFP5PJBY_cjs.GET_TAGS,
  GET_TRACE_LIGHT_ROUTE: () => GET_TRACE_LIGHT_ROUTE,
  GET_TRACE_ROUTE: () => GET_TRACE_ROUTE,
  GET_TRACE_TRAJECTORY_ROUTE: () => GET_TRACE_TRAJECTORY_ROUTE,
  LIST_FEEDBACK: () => chunkEFP5PJBY_cjs.LIST_FEEDBACK,
  LIST_LOGS: () => chunkEFP5PJBY_cjs.LIST_LOGS,
  LIST_SCORES: () => chunkEFP5PJBY_cjs.LIST_SCORES,
  LIST_SCORES_BY_SPAN_ROUTE: () => LIST_SCORES_BY_SPAN_ROUTE,
  LIST_TRACES_ROUTE: () => LIST_TRACES_ROUTE,
  NEW_ROUTES: () => chunkEFP5PJBY_cjs.NEW_ROUTES,
  SCORE_TRACES_ROUTE: () => SCORE_TRACES_ROUTE
});
var legacyQueryParamsSchema = v4.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: v4.z.string().optional(),
  // entityType needs preprocessing to handle legacy 'workflow' value
  entityType: v4.z.preprocess((val) => val === "workflow" ? "workflow_run" : val, v4.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;
}
async function getScoresStore(mastra) {
  const storage = chunkTU7U5XUE_cjs.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 = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/observability/traces",
  responseType: "json",
  queryParamSchema: chunk5UKYK7YK_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 = chunk5UKYK7YK_cjs.pickParams(storage.tracesFilterSchema, transformedParams);
      const pagination = chunk5UKYK7YK_cjs.pickParams(storage.paginationArgsSchema, transformedParams);
      const orderBy = chunk5UKYK7YK_cjs.pickParams(storage.tracesOrderBySchema, transformedParams);
      const observabilityStore = await chunkTU7U5XUE_cjs.getObservabilityStore(mastra);
      return await observabilityStore.listTraces({ filters, pagination, orderBy });
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error listing traces");
    }
  }
});
var GET_TRACE_ROUTE = chunk5UKYK7YK_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 chunkTU7U5XUE_cjs.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 chunkB34S64RC_cjs.handleError(error, "Error getting trace");
    }
  }
});
var GET_TRACE_LIGHT_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/light",
  responseType: "json",
  pathParamSchema: storage.getTraceArgsSchema,
  responseSchema: storage.getTraceLightResponseSchema,
  summary: "Get lightweight AI trace by ID",
  description: "Returns a trace with lightweight span data (timeline fields only, excludes input/output/attributes/metadata/tags/links)",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, traceId }) => {
    try {
      const observabilityStore = await chunkTU7U5XUE_cjs.getObservabilityStore(mastra);
      const trace = await observabilityStore.getTraceLight({ traceId });
      if (!trace) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Trace with ID '${traceId}' not found` });
      }
      return trace;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting lightweight trace");
    }
  }
});
var GET_SPAN_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/spans/:spanId",
  responseType: "json",
  pathParamSchema: storage.getSpanArgsSchema,
  responseSchema: storage.getSpanResponseSchema,
  summary: "Get a single span by ID",
  description: "Returns a complete span record with all details by trace ID and span ID",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, traceId, spanId }) => {
    try {
      const observabilityStore = await chunkTU7U5XUE_cjs.getObservabilityStore(mastra);
      const span = await observabilityStore.getSpan({ traceId, spanId });
      if (!span) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Span not found` });
      }
      return span;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting span");
    }
  }
});
var GET_TRACE_TRAJECTORY_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/trajectory",
  responseType: "json",
  pathParamSchema: storage.getTraceArgsSchema,
  responseSchema: v4.z.object({
    steps: v4.z.array(v4.z.unknown()),
    totalDurationMs: v4.z.number().optional(),
    rawOutput: v4.z.unknown().optional(),
    rawWorkflowResult: v4.z.unknown().optional()
  }),
  summary: "Extract trajectory from trace",
  description: "Extracts a structured trajectory (ordered steps) from a trace by analyzing its spans",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, traceId }) => {
    try {
      const observabilityStore = await chunkTU7U5XUE_cjs.getObservabilityStore(mastra);
      const trace = await observabilityStore.getTrace({ traceId });
      if (!trace) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Trace with ID '${traceId}' not found` });
      }
      const trajectory = evals.extractTrajectoryFromTrace(trace.spans);
      return trajectory;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error extracting trajectory from trace");
    }
  }
});
var SCORE_TRACES_ROUTE = chunk5UKYK7YK_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 {
      chunkTU7U5XUE_cjs.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 chunkB34S64RC_cjs.handleError(error, "Error processing trace scoring");
    }
  }
});
var LIST_SCORES_BY_SPAN_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/:spanId/scores",
  responseType: "json",
  pathParamSchema: storage.spanIdsSchema,
  // List endpoints accept optional query params; use partial() to allow empty queries.
  queryParamSchema: chunk5UKYK7YK_cjs.wrapSchemaForQueryParams(storage.paginationArgsSchema.partial()),
  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 = chunk5UKYK7YK_cjs.pickParams(storage.paginationArgsSchema, params);
      const spanIds = chunk5UKYK7YK_cjs.pickParams(storage.spanIdsSchema, params);
      const scoresStore = await getScoresStore(mastra);
      return await scoresStore.listScoresBySpan({
        ...spanIds,
        pagination
      });
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting scores by span");
    }
  }
});

exports.GET_SPAN_ROUTE = GET_SPAN_ROUTE;
exports.GET_TRACE_LIGHT_ROUTE = GET_TRACE_LIGHT_ROUTE;
exports.GET_TRACE_ROUTE = GET_TRACE_ROUTE;
exports.GET_TRACE_TRAJECTORY_ROUTE = GET_TRACE_TRAJECTORY_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-EBKNX5RM.cjs.map
//# sourceMappingURL=chunk-EBKNX5RM.cjs.map