import { handleError } from './chunk-NA7LKQPZ.js';
import { createRoute, wrapSchemaForQueryParams, pickParams } from './chunk-OLKVMPNB.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { listScoresResponseSchema } from '@mastra/core/evals';
import { scoreTraces } from '@mastra/core/evals/scoreTraces';
import { dateRangeSchema, listTracesResponseSchema, tracesFilterSchema, paginationArgsSchema, tracesOrderBySchema, getTraceResponseSchema, getTraceArgsSchema, scoreTracesResponseSchema, scoreTracesRequestSchema, spanIdsSchema } from '@mastra/core/storage';
import { z } from 'zod';

// src/server/handlers/observability.ts
var observability_exports = {};
__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 = 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;
}
function getStorage(mastra) {
  const storage = mastra.getStorage();
  if (!storage) {
    throw new 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 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 HTTPException(500, { message: "Scores storage domain is not available" });
  }
  return scores;
}
var LIST_TRACES_ROUTE = createRoute({
  method: "GET",
  path: "/observability/traces",
  responseType: "json",
  queryParamSchema: wrapSchemaForQueryParams(
    tracesFilterSchema.extend(paginationArgsSchema.shape).extend(tracesOrderBySchema.shape).extend(legacyQueryParamsSchema.shape).partial()
  ),
  responseSchema: 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 = pickParams(tracesFilterSchema, transformedParams);
      const pagination = pickParams(paginationArgsSchema, transformedParams);
      const orderBy = pickParams(tracesOrderBySchema, transformedParams);
      const observabilityStore = await getObservabilityStore(mastra);
      return await observabilityStore.listTraces({ filters, pagination, orderBy });
    } catch (error) {
      return handleError(error, "Error listing traces");
    }
  }
});
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 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,
  queryParamSchema: paginationArgsSchema,
  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_TRACE_ROUTE, LIST_SCORES_BY_SPAN_ROUTE, LIST_TRACES_ROUTE, SCORE_TRACES_ROUTE, observability_exports };
//# sourceMappingURL=chunk-ONORVWSC.js.map
//# sourceMappingURL=chunk-ONORVWSC.js.map