'use strict';

var chunk46D4LXPJ_cjs = require('./chunk-46D4LXPJ.cjs');
var chunkQOW24SR2_cjs = require('./chunk-QOW24SR2.cjs');
var chunkZNP74O27_cjs = require('./chunk-ZNP74O27.cjs');
var chunk42NUNMRC_cjs = require('./chunk-42NUNMRC.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.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: () => chunk46D4LXPJ_cjs.CREATE_FEEDBACK,
  CREATE_SCORE: () => chunk46D4LXPJ_cjs.CREATE_SCORE,
  GET_BRANCH_ROUTE: () => GET_BRANCH_ROUTE,
  GET_ENTITY_NAMES: () => chunk46D4LXPJ_cjs.GET_ENTITY_NAMES,
  GET_ENTITY_TYPES: () => chunk46D4LXPJ_cjs.GET_ENTITY_TYPES,
  GET_ENVIRONMENTS: () => chunk46D4LXPJ_cjs.GET_ENVIRONMENTS,
  GET_FEEDBACK_AGGREGATE: () => chunk46D4LXPJ_cjs.GET_FEEDBACK_AGGREGATE,
  GET_FEEDBACK_BREAKDOWN: () => chunk46D4LXPJ_cjs.GET_FEEDBACK_BREAKDOWN,
  GET_FEEDBACK_PERCENTILES: () => chunk46D4LXPJ_cjs.GET_FEEDBACK_PERCENTILES,
  GET_FEEDBACK_TIME_SERIES: () => chunk46D4LXPJ_cjs.GET_FEEDBACK_TIME_SERIES,
  GET_METRIC_AGGREGATE: () => chunk46D4LXPJ_cjs.GET_METRIC_AGGREGATE,
  GET_METRIC_BREAKDOWN: () => chunk46D4LXPJ_cjs.GET_METRIC_BREAKDOWN,
  GET_METRIC_LABEL_KEYS: () => chunk46D4LXPJ_cjs.GET_METRIC_LABEL_KEYS,
  GET_METRIC_LABEL_VALUES: () => chunk46D4LXPJ_cjs.GET_METRIC_LABEL_VALUES,
  GET_METRIC_NAMES: () => chunk46D4LXPJ_cjs.GET_METRIC_NAMES,
  GET_METRIC_PERCENTILES: () => chunk46D4LXPJ_cjs.GET_METRIC_PERCENTILES,
  GET_METRIC_TIME_SERIES: () => chunk46D4LXPJ_cjs.GET_METRIC_TIME_SERIES,
  GET_SCORE: () => chunk46D4LXPJ_cjs.GET_SCORE,
  GET_SCORE_AGGREGATE: () => chunk46D4LXPJ_cjs.GET_SCORE_AGGREGATE,
  GET_SCORE_BREAKDOWN: () => chunk46D4LXPJ_cjs.GET_SCORE_BREAKDOWN,
  GET_SCORE_PERCENTILES: () => chunk46D4LXPJ_cjs.GET_SCORE_PERCENTILES,
  GET_SCORE_TIME_SERIES: () => chunk46D4LXPJ_cjs.GET_SCORE_TIME_SERIES,
  GET_SERVICE_NAMES: () => chunk46D4LXPJ_cjs.GET_SERVICE_NAMES,
  GET_SPAN_ROUTE: () => GET_SPAN_ROUTE,
  GET_TAGS: () => chunk46D4LXPJ_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_BRANCHES_ROUTE: () => LIST_BRANCHES_ROUTE,
  LIST_FEEDBACK: () => chunk46D4LXPJ_cjs.LIST_FEEDBACK,
  LIST_LOGS: () => chunk46D4LXPJ_cjs.LIST_LOGS,
  LIST_METRICS: () => chunk46D4LXPJ_cjs.LIST_METRICS,
  LIST_SCORES: () => chunk46D4LXPJ_cjs.LIST_SCORES,
  LIST_SCORES_BY_SPAN_ROUTE: () => LIST_SCORES_BY_SPAN_ROUTE,
  LIST_TRACES_LIGHT_ROUTE: () => LIST_TRACES_LIGHT_ROUTE,
  LIST_TRACES_ROUTE: () => LIST_TRACES_ROUTE,
  NEW_ROUTES: () => chunk46D4LXPJ_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 = chunkQOW24SR2_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 listTracesQueryParamSchema = chunkN54Q3AQR_cjs.wrapSchemaForQueryParams(
  storage.tracesFilterSchema.extend(chunkZNP74O27_cjs.paginationArgsSchema.shape).extend(storage.tracesOrderBySchema.shape).extend(legacyQueryParamsSchema.shape).partial()
);
var LIST_TRACES_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/observability/traces",
  responseType: "json",
  queryParamSchema: chunkQOW24SR2_cjs.createObservabilityListQuerySchema(
    storage.tracesFilterSchema.extend({
      ...legacyQueryParamsSchema.shape,
      entityType: v4.z.preprocess(
        (value) => value === "workflow" ? "workflow_run" : value,
        storage.tracesFilterSchema.shape.entityType
      )
    }),
    storage.tracesOrderBySchema
  ),
  responseSchema: storage.listTracesResponseSchema,
  summary: "List traces",
  description: "Returns a paginated list of traces with optional filtering and sorting. In delta mode, returns only newly listed traces matching the filters.",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, mode, after, limit, ...params }) => {
    try {
      const transformedParams = transformLegacyParams(params);
      const filters = chunkN54Q3AQR_cjs.pickParams(storage.tracesFilterSchema, transformedParams);
      const observabilityStore = await chunkQOW24SR2_cjs.getObservabilityStore(mastra);
      if (mode === "delta") {
        chunkQOW24SR2_cjs.assertObservabilityDeltaSupported(observabilityStore, chunkQOW24SR2_cjs.OBSERVABILITY_LIST_ENDPOINTS.traces);
        return await observabilityStore.listTraces({
          mode,
          filters,
          after: typeof after === "string" ? after : void 0,
          limit
        });
      }
      const pagination = chunkN54Q3AQR_cjs.pickParams(chunkZNP74O27_cjs.paginationArgsSchema, transformedParams);
      const orderBy = chunkN54Q3AQR_cjs.pickParams(storage.tracesOrderBySchema, transformedParams);
      return await observabilityStore.listTraces({ filters, pagination, orderBy });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing traces");
    }
  }
});
var LIST_TRACES_LIGHT_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/light",
  responseType: "json",
  queryParamSchema: listTracesQueryParamSchema,
  responseSchema: chunk42NUNMRC_cjs.listTracesLightResponseSchema,
  summary: "List lightweight traces",
  description: "Returns a paginated list of lightweight traces with optional filtering and sorting",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, ...params }) => {
    try {
      const transformedParams = transformLegacyParams(params);
      const filters = chunkN54Q3AQR_cjs.pickParams(storage.tracesFilterSchema, transformedParams);
      const pagination = chunkN54Q3AQR_cjs.pickParams(chunkZNP74O27_cjs.paginationArgsSchema, transformedParams);
      const orderBy = chunkN54Q3AQR_cjs.pickParams(storage.tracesOrderBySchema, transformedParams);
      const observabilityStore = await chunkQOW24SR2_cjs.getObservabilityStore(mastra);
      const store = observabilityStore;
      if (typeof store.listTracesLight !== "function") {
        return await observabilityStore.listTraces({ filters, pagination, orderBy });
      }
      return await observabilityStore.listTracesLight({ filters, pagination, orderBy });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing lightweight traces");
    }
  }
});
var LIST_BRANCHES_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/observability/branches",
  responseType: "json",
  queryParamSchema: chunkQOW24SR2_cjs.createObservabilityListQuerySchema(chunk42NUNMRC_cjs.branchesFilterSchema, chunk42NUNMRC_cjs.branchesOrderBySchema),
  responseSchema: chunk42NUNMRC_cjs.listBranchesResponseSchema,
  summary: "List trace branches",
  description: "Returns a paginated list of branch-anchor spans (e.g., AGENT_RUN, WORKFLOW_RUN, TOOL_CALL) across all traces. Unlike listTraces (one row per root-rooted trace), each row here is a single anchor span -- including ones nested under a different root entity. In delta mode, returns only newly listed branch rows matching the filters.",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, mode, after, limit, ...params }) => {
    try {
      const filters = chunkN54Q3AQR_cjs.pickParams(chunk42NUNMRC_cjs.branchesFilterSchema, params);
      const observabilityStore = await chunkQOW24SR2_cjs.getObservabilityStore(mastra);
      if (mode === "delta") {
        chunkQOW24SR2_cjs.assertObservabilityDeltaSupported(observabilityStore, chunkQOW24SR2_cjs.OBSERVABILITY_LIST_ENDPOINTS.branches);
        return await observabilityStore.listBranches({
          mode,
          filters,
          after: typeof after === "string" ? after : void 0,
          limit
        });
      }
      const pagination = chunkN54Q3AQR_cjs.pickParams(chunkZNP74O27_cjs.paginationArgsSchema, params);
      const orderBy = chunkN54Q3AQR_cjs.pickParams(chunk42NUNMRC_cjs.branchesOrderBySchema, params);
      return await observabilityStore.listBranches({ filters, pagination, orderBy });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing branches");
    }
  }
});
var GET_BRANCH_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/branches/:spanId",
  responseType: "json",
  pathParamSchema: chunk42NUNMRC_cjs.getBranchArgsSchema.pick({ traceId: true, spanId: true }),
  queryParamSchema: chunkN54Q3AQR_cjs.wrapSchemaForQueryParams(chunk42NUNMRC_cjs.getBranchArgsSchema.pick({ depth: true })),
  responseSchema: chunk42NUNMRC_cjs.getBranchResponseSchema,
  summary: "Get trace branch by span ID",
  description: "Returns the subtree of spans rooted at the given span. The optional `depth` query param bounds descendant levels below the anchor (0 = anchor only; omitted = full subtree).",
  tags: ["Observability"],
  requiresAuth: true,
  handler: async ({ mastra, traceId, spanId, depth }) => {
    try {
      const observabilityStore = await chunkQOW24SR2_cjs.getObservabilityStore(mastra);
      const branch = await observabilityStore.getBranch({ traceId, spanId, depth });
      if (!branch) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Branch not found for span '${spanId}' in trace '${traceId}'` });
      }
      return branch;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting branch");
    }
  }
});
var GET_TRACE_ROUTE = chunkN54Q3AQR_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 chunkQOW24SR2_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 chunkZ7LCIYK7_cjs.handleError(error, "Error getting trace");
    }
  }
});
var GET_TRACE_LIGHT_ROUTE = chunkN54Q3AQR_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 chunkQOW24SR2_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 chunkZ7LCIYK7_cjs.handleError(error, "Error getting lightweight trace");
    }
  }
});
var GET_SPAN_ROUTE = chunkN54Q3AQR_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 chunkQOW24SR2_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 chunkZ7LCIYK7_cjs.handleError(error, "Error getting span");
    }
  }
});
var GET_TRACE_TRAJECTORY_ROUTE = chunkN54Q3AQR_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 chunkQOW24SR2_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 chunkZ7LCIYK7_cjs.handleError(error, "Error extracting trajectory from trace");
    }
  }
});
var SCORE_TRACES_ROUTE = chunkN54Q3AQR_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 {
      chunkQOW24SR2_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 chunkZ7LCIYK7_cjs.handleError(error, "Error processing trace scoring");
    }
  }
});
var LIST_SCORES_BY_SPAN_ROUTE = chunkN54Q3AQR_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: chunkN54Q3AQR_cjs.wrapSchemaForQueryParams(chunkZNP74O27_cjs.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 = chunkN54Q3AQR_cjs.pickParams(chunkZNP74O27_cjs.paginationArgsSchema, params);
      const spanIds = chunkN54Q3AQR_cjs.pickParams(storage.spanIdsSchema, params);
      const scoresStore = await getScoresStore(mastra);
      return await scoresStore.listScoresBySpan({
        ...spanIds,
        pagination
      });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting scores by span");
    }
  }
});

exports.GET_BRANCH_ROUTE = GET_BRANCH_ROUTE;
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_BRANCHES_ROUTE = LIST_BRANCHES_ROUTE;
exports.LIST_SCORES_BY_SPAN_ROUTE = LIST_SCORES_BY_SPAN_ROUTE;
exports.LIST_TRACES_LIGHT_ROUTE = LIST_TRACES_LIGHT_ROUTE;
exports.LIST_TRACES_ROUTE = LIST_TRACES_ROUTE;
exports.SCORE_TRACES_ROUTE = SCORE_TRACES_ROUTE;
exports.observability_exports = observability_exports;
//# sourceMappingURL=chunk-U52CKL4A.cjs.map
//# sourceMappingURL=chunk-U52CKL4A.cjs.map