import { NEW_ROUTES, LIST_SCORES, LIST_METRICS, LIST_LOGS, LIST_FEEDBACK, GET_TAGS, GET_SERVICE_NAMES, GET_SCORE_TIME_SERIES, GET_SCORE_PERCENTILES, GET_SCORE_BREAKDOWN, GET_SCORE_AGGREGATE, GET_SCORE, GET_METRIC_TIME_SERIES, GET_METRIC_PERCENTILES, GET_METRIC_NAMES, GET_METRIC_LABEL_VALUES, GET_METRIC_LABEL_KEYS, GET_METRIC_BREAKDOWN, GET_METRIC_AGGREGATE, GET_FEEDBACK_TIME_SERIES, GET_FEEDBACK_PERCENTILES, GET_FEEDBACK_BREAKDOWN, GET_FEEDBACK_AGGREGATE, GET_ENVIRONMENTS, GET_ENTITY_TYPES, GET_ENTITY_NAMES, CREATE_SCORE, CREATE_FEEDBACK } from './chunk-Z354XOPM.js';
import { getObservabilityStore, assertObservabilityDeltaSupported, OBSERVABILITY_LIST_ENDPOINTS, createObservabilityListQuerySchema, getStorage } from './chunk-2D3SDIRD.js';
import { paginationArgsSchema } from './chunk-YRLCLLKR.js';
import { listTracesLightResponseSchema, listBranchesResponseSchema, branchesFilterSchema, branchesOrderBySchema, getBranchResponseSchema, getBranchArgsSchema } from './chunk-5HICERRG.js';
import { handleError } from './chunk-7ZWJX3AN.js';
import { wrapSchemaForQueryParams, createRoute, pickParams } from './chunk-PIKPS6Q6.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { extractTrajectoryFromTrace, listScoresResponseSchema } from '@mastra/core/evals';
import { scoreTraces } from '@mastra/core/evals/scoreTraces';
import { dateRangeSchema, tracesFilterSchema, tracesOrderBySchema, listTracesResponseSchema, getTraceResponseSchema, getTraceArgsSchema, getTraceLightResponseSchema, getSpanResponseSchema, getSpanArgsSchema, scoreTracesResponseSchema, scoreTracesRequestSchema, spanIdsSchema } from '@mastra/core/storage';
import { z } from 'zod/v4';

// src/server/handlers/observability.ts
var observability_exports = {};
__export(observability_exports, {
  CREATE_FEEDBACK: () => CREATE_FEEDBACK,
  CREATE_SCORE: () => CREATE_SCORE,
  GET_BRANCH_ROUTE: () => GET_BRANCH_ROUTE,
  GET_ENTITY_NAMES: () => GET_ENTITY_NAMES,
  GET_ENTITY_TYPES: () => GET_ENTITY_TYPES,
  GET_ENVIRONMENTS: () => GET_ENVIRONMENTS,
  GET_FEEDBACK_AGGREGATE: () => GET_FEEDBACK_AGGREGATE,
  GET_FEEDBACK_BREAKDOWN: () => GET_FEEDBACK_BREAKDOWN,
  GET_FEEDBACK_PERCENTILES: () => GET_FEEDBACK_PERCENTILES,
  GET_FEEDBACK_TIME_SERIES: () => GET_FEEDBACK_TIME_SERIES,
  GET_METRIC_AGGREGATE: () => GET_METRIC_AGGREGATE,
  GET_METRIC_BREAKDOWN: () => GET_METRIC_BREAKDOWN,
  GET_METRIC_LABEL_KEYS: () => GET_METRIC_LABEL_KEYS,
  GET_METRIC_LABEL_VALUES: () => GET_METRIC_LABEL_VALUES,
  GET_METRIC_NAMES: () => GET_METRIC_NAMES,
  GET_METRIC_PERCENTILES: () => GET_METRIC_PERCENTILES,
  GET_METRIC_TIME_SERIES: () => GET_METRIC_TIME_SERIES,
  GET_SCORE: () => GET_SCORE,
  GET_SCORE_AGGREGATE: () => GET_SCORE_AGGREGATE,
  GET_SCORE_BREAKDOWN: () => GET_SCORE_BREAKDOWN,
  GET_SCORE_PERCENTILES: () => GET_SCORE_PERCENTILES,
  GET_SCORE_TIME_SERIES: () => GET_SCORE_TIME_SERIES,
  GET_SERVICE_NAMES: () => GET_SERVICE_NAMES,
  GET_SPAN_ROUTE: () => GET_SPAN_ROUTE,
  GET_TAGS: () => 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: () => LIST_FEEDBACK,
  LIST_LOGS: () => LIST_LOGS,
  LIST_METRICS: () => LIST_METRICS,
  LIST_SCORES: () => 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: () => NEW_ROUTES,
  SCORE_TRACES_ROUTE: () => SCORE_TRACES_ROUTE
});
var legacyQueryParamsSchema = z.object({
  // Old: dateRange was in pagination, now it's startedAt in filters
  dateRange: dateRangeSchema.optional(),
  // Old: name matched span names like "agent run: 'myAgent'"
  name: z.string().optional(),
  // entityType needs preprocessing to handle legacy 'workflow' value
  entityType: z.preprocess((val) => val === "workflow" ? "workflow_run" : val, 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 = getStorage(mastra);
  const scores = await storage.getStore("scores");
  if (!scores) {
    throw new HTTPException(500, { message: "Scores storage domain is not available" });
  }
  return scores;
}
var listTracesQueryParamSchema = wrapSchemaForQueryParams(
  tracesFilterSchema.extend(paginationArgsSchema.shape).extend(tracesOrderBySchema.shape).extend(legacyQueryParamsSchema.shape).partial()
);
var LIST_TRACES_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces",
  responseType: "json",
  queryParamSchema: createObservabilityListQuerySchema(
    tracesFilterSchema.extend({
      ...legacyQueryParamsSchema.shape,
      entityType: z.preprocess(
        (value) => value === "workflow" ? "workflow_run" : value,
        tracesFilterSchema.shape.entityType
      )
    }),
    tracesOrderBySchema
  ),
  responseSchema: 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 = pickParams(tracesFilterSchema, transformedParams);
      const observabilityStore = await getObservabilityStore(mastra);
      if (mode === "delta") {
        assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.traces);
        return await observabilityStore.listTraces({
          mode,
          filters,
          after: typeof after === "string" ? after : void 0,
          limit
        });
      }
      const pagination = pickParams(paginationArgsSchema, transformedParams);
      const orderBy = pickParams(tracesOrderBySchema, transformedParams);
      return await observabilityStore.listTraces({ filters, pagination, orderBy });
    } catch (error) {
      return handleError(error, "Error listing traces");
    }
  }
});
var LIST_TRACES_LIGHT_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces/light",
  responseType: "json",
  queryParamSchema: listTracesQueryParamSchema,
  responseSchema: 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 = pickParams(tracesFilterSchema, transformedParams);
      const pagination = pickParams(paginationArgsSchema, transformedParams);
      const orderBy = pickParams(tracesOrderBySchema, transformedParams);
      const observabilityStore = await 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 handleError(error, "Error listing lightweight traces");
    }
  }
});
var LIST_BRANCHES_ROUTE = createRoute({
  method: "GET",
  path: "/observability/branches",
  responseType: "json",
  queryParamSchema: createObservabilityListQuerySchema(branchesFilterSchema, branchesOrderBySchema),
  responseSchema: 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 = pickParams(branchesFilterSchema, params);
      const observabilityStore = await getObservabilityStore(mastra);
      if (mode === "delta") {
        assertObservabilityDeltaSupported(observabilityStore, OBSERVABILITY_LIST_ENDPOINTS.branches);
        return await observabilityStore.listBranches({
          mode,
          filters,
          after: typeof after === "string" ? after : void 0,
          limit
        });
      }
      const pagination = pickParams(paginationArgsSchema, params);
      const orderBy = pickParams(branchesOrderBySchema, params);
      return await observabilityStore.listBranches({ filters, pagination, orderBy });
    } catch (error) {
      return handleError(error, "Error listing branches");
    }
  }
});
var GET_BRANCH_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/branches/:spanId",
  responseType: "json",
  pathParamSchema: getBranchArgsSchema.pick({ traceId: true, spanId: true }),
  queryParamSchema: wrapSchemaForQueryParams(getBranchArgsSchema.pick({ depth: true })),
  responseSchema: 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 getObservabilityStore(mastra);
      const branch = await observabilityStore.getBranch({ traceId, spanId, depth });
      if (!branch) {
        throw new HTTPException(404, { message: `Branch not found for span '${spanId}' in trace '${traceId}'` });
      }
      return branch;
    } catch (error) {
      return handleError(error, "Error getting branch");
    }
  }
});
var GET_TRACE_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces/:traceId",
  responseType: "json",
  pathParamSchema: getTraceArgsSchema,
  responseSchema: 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 HTTPException(404, { message: `Trace with ID '${traceId}' not found` });
      }
      return trace;
    } catch (error) {
      return handleError(error, "Error getting trace");
    }
  }
});
var GET_TRACE_LIGHT_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/light",
  responseType: "json",
  pathParamSchema: getTraceArgsSchema,
  responseSchema: 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 getObservabilityStore(mastra);
      const trace = await observabilityStore.getTraceLight({ traceId });
      if (!trace) {
        throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });
      }
      return trace;
    } catch (error) {
      return handleError(error, "Error getting lightweight trace");
    }
  }
});
var GET_SPAN_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/spans/:spanId",
  responseType: "json",
  pathParamSchema: getSpanArgsSchema,
  responseSchema: 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 getObservabilityStore(mastra);
      const span = await observabilityStore.getSpan({ traceId, spanId });
      if (!span) {
        throw new HTTPException(404, { message: `Span not found` });
      }
      return span;
    } catch (error) {
      return handleError(error, "Error getting span");
    }
  }
});
var GET_TRACE_TRAJECTORY_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/trajectory",
  responseType: "json",
  pathParamSchema: getTraceArgsSchema,
  responseSchema: z.object({
    steps: z.array(z.unknown()),
    totalDurationMs: z.number().optional(),
    rawOutput: z.unknown().optional(),
    rawWorkflowResult: 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 getObservabilityStore(mastra);
      const trace = await observabilityStore.getTrace({ traceId });
      if (!trace) {
        throw new HTTPException(404, { message: `Trace with ID '${traceId}' not found` });
      }
      const trajectory = extractTrajectoryFromTrace(trace.spans);
      return trajectory;
    } catch (error) {
      return handleError(error, "Error extracting trajectory from trace");
    }
  }
});
var SCORE_TRACES_ROUTE = createRoute({
  method: "POST",
  path: "/observability/traces/score",
  responseType: "json",
  bodySchema: scoreTracesRequestSchema,
  responseSchema: 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 HTTPException(404, { message: `Scorer '${scorerName}' not found` });
      }
      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 handleError(error, "Error processing trace scoring");
    }
  }
});
var LIST_SCORES_BY_SPAN_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces/:traceId/:spanId/scores",
  responseType: "json",
  pathParamSchema: spanIdsSchema,
  // List endpoints accept optional query params; use partial() to allow empty queries.
  queryParamSchema: wrapSchemaForQueryParams(paginationArgsSchema.partial()),
  responseSchema: 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 = pickParams(paginationArgsSchema, params);
      const spanIds = pickParams(spanIdsSchema, params);
      const scoresStore = await getScoresStore(mastra);
      return await scoresStore.listScoresBySpan({
        ...spanIds,
        pagination
      });
    } catch (error) {
      return handleError(error, "Error getting scores by span");
    }
  }
});

export { GET_BRANCH_ROUTE, GET_SPAN_ROUTE, GET_TRACE_LIGHT_ROUTE, GET_TRACE_ROUTE, GET_TRACE_TRAJECTORY_ROUTE, LIST_BRANCHES_ROUTE, LIST_SCORES_BY_SPAN_ROUTE, LIST_TRACES_LIGHT_ROUTE, LIST_TRACES_ROUTE, SCORE_TRACES_ROUTE, observability_exports };
//# sourceMappingURL=chunk-LLVTDE4P.js.map
//# sourceMappingURL=chunk-LLVTDE4P.js.map