UNPKG

@mastra/core

Version:
2,568 lines • 97.3 kB
import { $t as metricsFilterSchema, Ct as getScoreBreakdownArgsSchema, Dt as getScoreTimeSeriesArgsSchema, M as deltaInfoSchema, N as deltaLimitSchema, Tt as getScorePercentilesArgsSchema, _t as getMetricPercentilesArgsSchema, an as paginationInfoSchema, fn as requireDistinctColumnRefinement, in as paginationArgsSchema, j as deltaCursorSchema, lt as getMetricBreakdownArgsSchema, st as getMetricAggregateArgsSchema, xn as scoresFilterSchema, xt as getScoreAggregateArgsSchema, yt as getMetricTimeSeriesArgsSchema } from "./storage-Cc50aQAp.js";
import { n as TokenMetrics } from "./metrics-CYB9MY31.js";
import { z } from "zod/v4";
// src/storage/domains/observability/trace-query.ts
const TRACE_QUERY_MAX_DEPTH = 12;
const TRACE_QUERY_MAX_NODES = 100;
const TRACE_QUERY_MAX_SET_VALUES = 100;
const TRACE_QUERY_MAX_RELATED_CLAUSES = 8;
const TRACE_QUERY_MAX_LITERAL_UNITS = 1e3;
const TRACE_QUERY_MAX_STRING_BYTES = 4096;
const TRACE_QUERY_MAX_PATH_BYTES = 128;
const TRACE_QUERY_DISCOVERY_DEFAULT_LIMIT = 25;
const TRACE_QUERY_DISCOVERY_MAX_LIMIT = 100;
const TRACE_QUERY_DISCOVERY_MAX_SEARCH_LENGTH = 256;
const TRACE_QUERY_DEFAULT_TIMEOUT_MS = 15e3;
const TRACE_QUERY_MAX_TIMEOUT_MS = 3e5;
const TRACE_QUERY_NUMERIC_ORDER_FIELDS = ["timeToFirstChunkMs", "timeToFirstTokenMs"];
/**
* Fields trace and span queries can sort by. `timeToFirstChunkMs` and `timeToFirstTokenMs` are
* numbers that can be empty; empty values sort last in both directions.
*/
const TRACE_QUERY_ORDER_FIELDS = [
	"startedAt",
	"endedAt",
	...TRACE_QUERY_NUMERIC_ORDER_FIELDS
];
/** @internal Whether a decoded cursor's sort value has the kind its order field produces. */
function isTraceQuerySortValueFor(field, value) {
	return TRACE_QUERY_NUMERIC_ORDER_FIELDS.includes(field) ? value === null || typeof value === "number" : typeof value === "string";
}
/** @internal Cursor sort values: ISO timestamps, or finite numbers and `null` for numeric fields. */
const traceQuerySortValueSchema = z.union([
	z.string().datetime({ offset: true }),
	z.number(),
	z.null()
]);
/** @internal Shared with the trace-aggregate request schema so both report identical complexity issues. */
const TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE = `Predicates are limited to 100 nodes and 12 levels`;
const PREDICATE_COMPLEXITY_MESSAGE = TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE;
const PAGINATION_MODE_CONFLICT_MESSAGE = "Trace queries cannot combine keyset and page pagination";
const GROUP_PAGINATION_NOT_SUPPORTED_MESSAGE = "Grouped trace queries do not support page pagination";
function compareTraceQueryStrings(left, right) {
	if (left < right) return -1;
	if (left > right) return 1;
	return 0;
}
const hasMaxUtf8Bytes$1 = (value, maxBytes) => new TextEncoder().encode(value).length <= maxBytes;
const literalStringSchema = z.string().refine((value) => hasMaxUtf8Bytes$1(value, TRACE_QUERY_MAX_STRING_BYTES), "String literal is too large");
const collectionMemberSchema = literalStringSchema.refine((value) => value.trim().length > 0, "Collection predicates require a non-empty string value");
const timestampLiteralSchema = z.string().datetime({ offset: true });
/** Maximum Unicode code points in a token-search literal, before store tokenization. */
const TRACE_QUERY_TOKEN_SEARCH_MAX_LENGTH = 256;
const TRACE_QUERY_TOKEN_FIELDS = [
	"input",
	"output",
	"error",
	"inputPreview",
	"outputPreview",
	"errorPreview",
	"all"
];
/**
* Positive whole-token matching on indexed span content. For `all`, one underlying column
* must contain every query token; tokens cannot be satisfied across different columns.
* The planner preserves case. Tokenization and case folding belong to the supporting store.
* A literal producing no tokens matches nothing, including missing content.
* `not` and `none` ancestors are unsupported;
* positive predicates can compose through `and`, `or`, and `spans.some`.
*/
const tokenPredicateSchema = z.object({
	op: z.literal("hasAllTokens"),
	left: z.object({ path: z.enum(TRACE_QUERY_TOKEN_FIELDS) }).strict(),
	right: z.object({ literal: z.string().trim().min(1).refine((value) => Array.from(value).length <= 256, `Token search must contain at most 256 characters`).meta({ maxLength: 256 }) }).strict()
}).strict();
const textLiteralSchema = z.object({ literal: literalStringSchema }).strict();
const predicatePathSchema = z.string().min(1).refine((value) => hasMaxUtf8Bytes$1(value, 128), "Predicate path is too large");
const literalSchema = z.union([
	literalStringSchema,
	z.number(),
	z.boolean(),
	z.null()
]);
const pathRefSchema = z.object({ path: predicatePathSchema }).strict();
const literalRefSchema = z.object({ literal: literalSchema }).strict();
const pathOrLiteralSchema = z.union([pathRefSchema, literalRefSchema]);
const membershipSetSchema = z.array(literalSchema).min(1).refine((set) => set.length <= 100, "Membership set is too large").meta({ maxItems: 100 });
const traceQueryScalarPredicateSchema = z.lazy(() => z.union([
	z.object({
		op: z.enum([
			"eq",
			"ne",
			"lt",
			"lte",
			"gt",
			"gte"
		]),
		left: pathOrLiteralSchema,
		right: pathOrLiteralSchema
	}).strict(),
	z.object({
		op: z.enum(["in", "notIn"]),
		value: pathOrLiteralSchema,
		set: membershipSetSchema
	}).strict(),
	z.object({
		op: z.enum(["exists", "notExists"]),
		path: predicatePathSchema
	}).strict(),
	z.object({
		op: z.enum(["includes", "notIncludes"]),
		path: predicatePathSchema,
		value: collectionMemberSchema
	}).strict(),
	z.object({
		op: z.enum(["matches", "notMatches"]),
		left: pathRefSchema,
		right: textLiteralSchema
	}).strict(),
	tokenPredicateSchema,
	z.object({
		op: z.enum(["and", "or"]),
		args: z.array(traceQueryScalarPredicateSchema).min(1)
	}).strict(),
	z.object({
		op: z.literal("not"),
		arg: traceQueryScalarPredicateSchema
	}).strict()
]));
const traceQueryPredicateSchema = z.lazy(() => z.union([
	z.object({
		op: z.enum([
			"eq",
			"ne",
			"lt",
			"lte",
			"gt",
			"gte"
		]),
		left: pathOrLiteralSchema,
		right: pathOrLiteralSchema
	}).strict(),
	z.object({
		op: z.enum(["in", "notIn"]),
		value: pathOrLiteralSchema,
		set: membershipSetSchema
	}).strict(),
	z.object({
		op: z.enum(["exists", "notExists"]),
		path: predicatePathSchema
	}).strict(),
	z.object({
		op: z.enum(["includes", "notIncludes"]),
		path: predicatePathSchema,
		value: collectionMemberSchema
	}).strict(),
	z.object({
		op: z.enum(["matches", "notMatches"]),
		left: pathRefSchema,
		right: textLiteralSchema
	}).strict(),
	tokenPredicateSchema,
	z.object({
		op: z.enum(["and", "or"]),
		args: z.array(traceQueryPredicateSchema).min(1)
	}).strict(),
	z.object({
		op: z.literal("not"),
		arg: traceQueryPredicateSchema
	}).strict(),
	z.object({ spans: z.union([z.object({ some: traceQueryScalarPredicateSchema }).strict(), z.object({ none: traceQueryScalarPredicateSchema }).strict()]) }).strict(),
	z.object({ scores: z.union([z.object({ some: traceQueryScalarPredicateSchema }).strict(), z.object({ none: traceQueryScalarPredicateSchema }).strict()]) }).strict(),
	z.object({ feedback: z.union([z.object({ some: traceQueryScalarPredicateSchema }).strict(), z.object({ none: traceQueryScalarPredicateSchema }).strict()]) }).strict()
]));
const traceQueryTimeRangeSchema = z.object({
	from: z.string().datetime({ offset: true }),
	to: z.string().datetime({ offset: true })
}).strict();
const traceQueryPredicateScopeSchema = z.enum([
	"trace",
	"spans",
	"scores",
	"feedback"
]);
const traceQueryOperatorSchema = z.enum([
	"eq",
	"ne",
	"lt",
	"lte",
	"gt",
	"gte",
	"in",
	"notIn",
	"exists",
	"notExists",
	"includes",
	"notIncludes",
	"matches",
	"notMatches"
]);
const traceQueryValueKindSchema = z.enum([
	"string",
	"number",
	"stringOrNumber",
	"timestamp",
	"presence",
	"array"
]);
const traceQueryDiscoveryTimeRangeSchema = traceQueryTimeRangeSchema.superRefine((timeRange, context) => {
	if (new Date(timeRange.from) >= new Date(timeRange.to)) context.addIssue({
		code: "custom",
		path: [],
		message: "`from` must be earlier than `to`"
	});
});
const traceQueryDiscoverySearchSchema = z.string().trim().max(256).optional();
const traceQueryDiscoveryLimitSchema = z.number().int().min(1).max(100).default(25);
const getTraceQueryFieldsArgsSchema = z.object({
	timeRange: traceQueryDiscoveryTimeRangeSchema,
	predicateScope: traceQueryPredicateScopeSchema,
	search: traceQueryDiscoverySearchSchema,
	limit: traceQueryDiscoveryLimitSchema
}).strict();
const getTraceQueryValuesArgsSchema = z.object({
	timeRange: traceQueryDiscoveryTimeRangeSchema,
	predicateScope: traceQueryPredicateScopeSchema,
	path: predicatePathSchema.transform((path) => normalizeTraceQueryPath(path)),
	search: traceQueryDiscoverySearchSchema,
	limit: traceQueryDiscoveryLimitSchema
}).strict().superRefine((args, context) => {
	if (!isTraceQueryValueSuggestionsPath(args.predicateScope, args.path)) context.addIssue({
		code: "custom",
		path: ["path"],
		message: "Value suggestions are not available for this path"
	});
});
const traceQueryCanonicalFieldDescriptorSchema = z.object({
	path: z.string(),
	valueKind: traceQueryValueKindSchema,
	operators: z.array(traceQueryOperatorSchema),
	valueSuggestions: z.boolean()
}).strict();
const traceQueryObservedFieldDescriptorSchema = z.object({
	path: z.string().startsWith("metadata.").refine((path) => isTraceQueryMetadataPath(path), "Invalid metadata path"),
	valueKind: z.literal("string"),
	operators: z.array(z.enum([
		"eq",
		"ne",
		"in",
		"notIn",
		"exists",
		"notExists"
	])),
	valueSuggestions: z.literal(true),
	occurrences: z.number().int().nonnegative()
}).strict();
const traceAggregateDimensionDescriptorSchema = z.object({
	path: z.string(),
	valueKind: z.literal("string")
}).strict();
const traceAggregateMeasureDescriptorSchema = z.object({
	name: z.string(),
	kind: z.enum([
		"count",
		"duration",
		"error",
		"tokens",
		"cost",
		"timeToFirstToken",
		"timeToFirstChunk"
	]),
	statistic: z.enum([
		"avg",
		"min",
		"max",
		"p50",
		"p90",
		"p95",
		"p99",
		"sum",
		"count"
	]).optional(),
	unit: z.enum([
		"count",
		"milliseconds",
		"ratio",
		"tokens",
		"currency"
	]),
	approximate: z.boolean()
}).strict();
const traceAggregateDiscoverySchema = z.object({
	dimensions: z.array(traceAggregateDimensionDescriptorSchema),
	measures: z.array(traceAggregateMeasureDescriptorSchema)
}).strict().describe("What `aggregateTraces()` accepts. Present only for `predicateScope: \"trace\"` when the store supports aggregation. Every observed field is also a groupable dimension, and `countDistinct.<field>` accepts any dimension or `traceId`.");
const getTraceQueryFieldsResponseSchema = z.object({
	canonicalFields: z.array(traceQueryCanonicalFieldDescriptorSchema),
	observedFields: z.array(traceQueryObservedFieldDescriptorSchema).max(100),
	observedFieldsTruncated: z.boolean(),
	aggregate: traceAggregateDiscoverySchema.optional()
}).strict();
const getTraceQueryValuesResponseSchema = z.object({
	values: z.array(z.object({
		value: literalStringSchema,
		count: z.number().int().nonnegative()
	}).strict()).max(100),
	valuesTruncated: z.boolean()
}).strict();
const traceSelectionSchema = z.object({
	timeRange: traceQueryTimeRangeSchema,
	where: traceQueryPredicateSchema.optional()
}).strict();
const threadPredicateSchema = z.lazy(() => z.union([
	z.object({
		op: z.enum(["and", "or"]),
		args: z.array(threadPredicateSchema).min(1)
	}).strict(),
	z.object({
		op: z.literal("not"),
		arg: threadPredicateSchema
	}).strict(),
	z.object({ traces: z.union([z.object({ some: traceQueryPredicateSchema }).strict(), z.object({ none: traceQueryPredicateSchema }).strict()]) }).strict()
]));
const pageSchema = z.object({
	limit: z.number().int().min(1).max(1e3).default(100),
	after: z.string().min(1).nullable().optional()
}).strict();
const traceQueryRootSourceSchema = z.enum(["legacy", "aggregated"]);
const traceQueryRequestObjectSchema = z.object({
	rootSource: traceQueryRootSourceSchema.optional(),
	timeRange: traceQueryTimeRangeSchema,
	where: traceQueryPredicateSchema.optional(),
	/**
	* @deprecated Use `queryThreads()` instead. Grouped trace queries remain supported until the next major release.
	*/
	group: z.object({ by: z.tuple([z.literal("threadId")]) }).strict().optional(),
	orderBy: z.array(z.object({
		field: z.enum(TRACE_QUERY_ORDER_FIELDS),
		direction: z.enum(["asc", "desc"])
	}).strict()).length(1).optional(),
	page: pageSchema.optional(),
	pagination: paginationArgsSchema.optional(),
	mode: z.literal("delta").optional(),
	after: deltaCursorSchema.optional(),
	limit: deltaLimitSchema
}).strict().superRefine((request, context) => {
	if (request.rootSource === "aggregated" && request.mode === "delta") context.addIssue({
		code: "custom",
		path: ["rootSource"],
		message: "Aggregated roots do not support delta mode"
	});
	if (request.mode === "delta") {
		for (const field of [
			"page",
			"pagination",
			"group",
			"orderBy"
		]) if (request[field] !== void 0) context.addIssue({
			code: "custom",
			path: [field],
			message: `Delta trace queries do not support ${field}`
		});
	} else for (const field of ["after", "limit"]) if (request[field] !== void 0) context.addIssue({
		code: "custom",
		path: [field],
		message: `${field} requires delta mode`
	});
	if (request.page && request.pagination) context.addIssue({
		code: "custom",
		path: ["pagination"],
		message: PAGINATION_MODE_CONFLICT_MESSAGE
	});
	if (request.group && request.pagination) context.addIssue({
		code: "custom",
		path: ["pagination"],
		message: GROUP_PAGINATION_NOT_SUPPORTED_MESSAGE
	});
});
const traceQueryRequestSchema = z.preprocess((input, context) => {
	const issuePath = findPredicateComplexityIssue(input, [["where"]]);
	if (issuePath) {
		context.addIssue({
			code: "custom",
			path: issuePath,
			message: PREDICATE_COMPLEXITY_MESSAGE
		});
		return z.NEVER;
	}
	return input;
}, traceQueryRequestObjectSchema);
const queryThreadsInputObjectSchema = z.object({
	traces: traceSelectionSchema,
	where: threadPredicateSchema.optional(),
	page: pageSchema.default({ limit: 100 })
}).strict();
const queryThreadsInputSchema = z.preprocess((input, context) => {
	const issuePath = findPredicateComplexityIssue(input, [["traces", "where"], ["where"]]);
	if (issuePath) {
		context.addIssue({
			code: "custom",
			path: issuePath,
			message: PREDICATE_COMPLEXITY_MESSAGE
		});
		return z.NEVER;
	}
	return input;
}, queryThreadsInputObjectSchema);
const traceQueryTraceSchema = z.object({
	traceId: z.string(),
	rootSpanId: z.string(),
	rootKind: z.enum(["native", "external"]).optional(),
	runtimeDurationMs: z.number().nonnegative().nullable().optional(),
	errorCount: z.number().int().nonnegative().nullable().optional(),
	name: z.string(),
	entityId: z.string().nullable(),
	parentSpanId: z.string().nullable(),
	createdAt: z.string().datetime({ offset: true }),
	metadata: z.record(z.string(), z.unknown()).nullable(),
	inputPreview: z.string().nullable(),
	outputPreview: z.string().nullable(),
	errorPreview: z.string().nullable(),
	threadId: z.string().nullable(),
	resourceId: z.string().nullable(),
	startedAt: z.string().datetime({ offset: true }),
	endedAt: z.string().datetime({ offset: true }),
	entityName: z.string().nullable(),
	entityType: z.string().nullable(),
	environment: z.string().nullable(),
	status: z.enum(["success", "error"]),
	/**
	* The root span's time to first chunk; `null` when the root never streamed one.
	* Absent when the store lacks the `trace-query-time-to-first-chunk` feature.
	*/
	timeToFirstChunkMs: z.number().nullable().optional(),
	/**
	* The root span's time to first token; `null` when the root has none.
	* Absent when the store lacks the `trace-query-time-to-first-token` feature.
	*/
	timeToFirstTokenMs: z.number().nullable().optional(),
	/**
	* How the root span ended, for example `success`, `limit` or a custom string. Separate from
	* `status`, which reflects only `error`. `null` when not recorded (older SDKs or a running root),
	* which does not mean success. Absent when the store lacks the `trace-query-outcome-fields` feature.
	*/
	outcome: z.string().nullable().optional(),
	/**
	* Why the root span stopped, for example `max_steps`. `null` when not recorded.
	* Absent when the store lacks the `trace-query-outcome-fields` feature.
	*/
	stopReason: z.string().nullable().optional(),
	/**
	* Details for the root span's `stopReason`. Returned only; not filterable.
	* Absent when the store lacks the `trace-query-outcome-fields` feature.
	*/
	stopReasonContext: z.record(z.string(), z.unknown()).nullable().optional()
}).strict();
const responsePageSchema = z.object({ next: z.string().nullable() }).strict();
const traceQueryTraceResponseSchema = z.object({
	traces: z.array(traceQueryTraceSchema),
	page: responsePageSchema
}).strict();
const traceQueryPaginatedTraceResponseSchema = z.object({
	traces: z.array(traceQueryTraceSchema),
	pagination: paginationInfoSchema,
	deltaCursor: deltaCursorSchema.optional()
}).strict();
const traceQueryDeltaTraceResponseSchema = z.object({
	traces: z.array(traceQueryTraceSchema),
	delta: deltaInfoSchema,
	deltaCursor: deltaCursorSchema
}).strict();
/**
* @deprecated Use `queryThreadsResultSchema` instead. Grouped trace queries remain supported until the next major release.
*/
const traceQueryGroupResponseSchema = z.object({
	groups: z.array(z.object({ threadId: z.string() }).strict()),
	page: responsePageSchema
}).strict();
const traceQueryResponseSchema = z.union([
	traceQueryTraceResponseSchema,
	traceQueryPaginatedTraceResponseSchema,
	traceQueryDeltaTraceResponseSchema,
	traceQueryGroupResponseSchema
]);
const threadIdentitySchema = z.object({ threadId: z.string() }).strict();
const queryThreadsResultSchema = z.object({
	threads: z.array(threadIdentitySchema),
	page: responsePageSchema
}).strict();
const TRACE_QUERY_STRING_OPERATORS = [
	"eq",
	"ne",
	"in",
	"notIn",
	"exists",
	"notExists"
];
const TRACE_QUERY_ORDERED_OPERATORS = [
	...TRACE_QUERY_STRING_OPERATORS,
	"lt",
	"lte",
	"gt",
	"gte"
];
const TRACE_QUERY_PRESENCE_OPERATORS = ["exists", "notExists"];
/** Stored string collections such as `tags`. `exists` means at least one member; `notExists` means none. */
const TRACE_QUERY_ARRAY_OPERATORS = [
	"includes",
	"notIncludes",
	"exists",
	"notExists"
];
/** Human-written text such as feedback comments: exact string operators plus word matching. */
const TRACE_QUERY_TEXT_OPERATORS = [
	...TRACE_QUERY_STRING_OPERATORS,
	"matches",
	"notMatches"
];
const stringField = (valueSuggestions) => ({
	valueKind: "string",
	operators: TRACE_QUERY_STRING_OPERATORS,
	valueSuggestions
});
const orderedField = (valueKind) => ({
	valueKind,
	operators: TRACE_QUERY_ORDERED_OPERATORS,
	valueSuggestions: false
});
const presenceField = () => ({
	valueKind: "presence",
	operators: TRACE_QUERY_PRESENCE_OPERATORS,
	valueSuggestions: false
});
const arrayField = () => ({
	valueKind: "array",
	operators: TRACE_QUERY_ARRAY_OPERATORS,
	valueSuggestions: true
});
const textField = (valueSuggestions) => ({
	valueKind: "string",
	operators: TRACE_QUERY_TEXT_OPERATORS,
	valueSuggestions
});
const TRACE_QUERY_FIELD_REGISTRY = {
	trace: {
		traceId: stringField(false),
		threadId: stringField(false),
		resourceId: stringField(false),
		runId: stringField(false),
		sessionId: stringField(false),
		userId: stringField(false),
		organizationId: stringField(false),
		requestId: stringField(false),
		serviceName: stringField(false),
		experimentId: stringField(false),
		startedAt: orderedField("timestamp"),
		endedAt: orderedField("timestamp"),
		durationMs: orderedField("number"),
		timeToFirstChunkMs: orderedField("number"),
		timeToFirstTokenMs: orderedField("number"),
		entityId: stringField(false),
		entityName: stringField(true),
		entityType: stringField(true),
		name: stringField(true),
		spanType: stringField(true),
		environment: stringField(true),
		status: stringField(true),
		outcome: stringField(true),
		stopReason: stringField(true),
		tags: arrayField()
	},
	spans: {
		name: textField(true),
		spanType: stringField(true),
		model: stringField(true),
		provider: stringField(true),
		startedAt: orderedField("timestamp"),
		endedAt: orderedField("timestamp"),
		durationMs: orderedField("number"),
		timeToFirstChunkMs: orderedField("number"),
		timeToFirstTokenMs: orderedField("number"),
		status: stringField(true),
		outcome: stringField(true),
		stopReason: stringField(true),
		error: presenceField(),
		entityType: stringField(true),
		entityId: stringField(false),
		entityName: stringField(true),
		entityVersionId: stringField(false),
		parentEntityVersionId: stringField(false),
		rootEntityVersionId: stringField(false),
		runId: stringField(false),
		sessionId: stringField(false),
		userId: stringField(false),
		organizationId: stringField(false),
		requestId: stringField(false),
		serviceName: stringField(false),
		experimentId: stringField(false)
	},
	scores: {
		scorerId: stringField(true),
		scorerVersion: stringField(true),
		scoreSource: stringField(true),
		score: orderedField("number"),
		timestamp: orderedField("timestamp"),
		spanId: presenceField(),
		entityVersionId: stringField(false),
		parentEntityVersionId: stringField(false),
		rootEntityVersionId: stringField(false)
	},
	feedback: {
		feedbackType: stringField(true),
		feedbackSource: stringField(true),
		feedbackUserId: stringField(false),
		sourceId: stringField(false),
		entityVersionId: stringField(false),
		parentEntityVersionId: stringField(false),
		rootEntityVersionId: stringField(false),
		value: orderedField("stringOrNumber"),
		timestamp: orderedField("timestamp"),
		comment: textField(false)
	}
};
/** Direct span queries have a separate policy from trace queries' related span predicates. */
const SPAN_QUERY_FIELD_REGISTRY = {
	name: textField(true),
	spanType: stringField(true),
	model: stringField(true),
	provider: stringField(true),
	status: stringField(true),
	outcome: stringField(true),
	stopReason: stringField(true),
	error: presenceField(),
	startedAt: orderedField("timestamp"),
	endedAt: orderedField("timestamp"),
	durationMs: orderedField("number"),
	timeToFirstChunkMs: orderedField("number"),
	timeToFirstTokenMs: orderedField("number"),
	traceId: stringField(false),
	spanId: stringField(false),
	parentSpanId: stringField(false),
	threadId: stringField(false),
	organizationId: stringField(false),
	resourceId: stringField(false),
	runId: stringField(false),
	sessionId: stringField(false),
	userId: stringField(false),
	requestId: stringField(false),
	serviceName: stringField(true),
	experimentId: stringField(false),
	environment: stringField(true),
	executionSource: stringField(true),
	entityType: stringField(true),
	entityId: stringField(false),
	entityName: stringField(true),
	entityVersionId: stringField(false),
	parentEntityType: stringField(true),
	parentEntityId: stringField(false),
	parentEntityName: stringField(true),
	parentEntityVersionId: stringField(false),
	rootEntityType: stringField(true),
	rootEntityId: stringField(false),
	rootEntityName: stringField(true),
	rootEntityVersionId: stringField(false)
};
/** Direct thread-row predicates apply after full-history representative selection. */
const THREAD_QUERY_FIELD_REGISTRY = {
	threadId: stringField(false),
	organizationId: stringField(false),
	firstTraceId: stringField(false),
	lastTraceId: stringField(false),
	resourceId: stringField(false),
	userId: stringField(false),
	entityType: stringField(false),
	entityId: stringField(false),
	entityName: stringField(false),
	entityVersionId: stringField(false),
	runId: stringField(false),
	sessionId: stringField(false),
	requestId: stringField(false),
	serviceName: stringField(false),
	experimentId: stringField(false),
	environment: stringField(false),
	executionSource: stringField(false),
	status: {
		...stringField(false),
		operators: [
			"eq",
			"ne",
			"in",
			"notIn"
		]
	},
	startedAt: orderedField("timestamp"),
	endedAt: orderedField("timestamp"),
	traceCount: {
		...orderedField("number"),
		operators: [
			"eq",
			"ne",
			"lt",
			"lte",
			"gt",
			"gte"
		]
	},
	timeToFirstChunkMs: orderedField("number"),
	timeToFirstTokenMs: orderedField("number")
};
const METADATA_FIELD_RULE = {
	valueKind: "string",
	operators: TRACE_QUERY_STRING_OPERATORS,
	valueSuggestions: true,
	nonEmpty: true
};
var TraceQueryValidationError = class extends Error {
	issues;
	code = "TRACE_QUERY_INVALID";
	constructor(issues) {
		super("The trace query is invalid");
		this.issues = issues;
		this.name = "TraceQueryValidationError";
	}
};
var TraceQueryCursorError = class extends Error {
	code;
	constructor(code) {
		super(code === "TRACE_QUERY_CURSOR_MALFORMED" ? "The query cursor is malformed" : "The cursor does not match the query");
		this.code = code;
		this.name = "TraceQueryCursorError";
	}
};
/** A valid query uses a feature the selected storage adapter cannot execute. */
var TraceQueryUnsupportedError = class extends Error {
	code = "TRACE_QUERY_UNSUPPORTED";
	constructor(message) {
		super(message);
		this.name = "TraceQueryUnsupportedError";
	}
};
var TraceQueryExecutionError = class extends Error {
	code = "TRACE_QUERY_EXECUTION_TIMEOUT";
	constructor() {
		super("The query exceeded its execution timeout");
		this.name = "TraceQueryExecutionError";
	}
};
var TraceQueryResourceLimitError = class extends Error {
	code = "TRACE_QUERY_RESOURCE_LIMIT";
	constructor() {
		super("The query exceeded its resource limit");
		this.name = "TraceQueryResourceLimitError";
	}
};
function resolveTraceQueryTimeoutMs(timeoutMs = TRACE_QUERY_DEFAULT_TIMEOUT_MS) {
	if (!Number.isFinite(timeoutMs) || !Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 3e5) throw new RangeError(`traceQueryTimeoutMs must be an integer between 1 and ${TRACE_QUERY_MAX_TIMEOUT_MS}`);
	return timeoutMs;
}
function addPredicateComplexityIssue(path, message, state) {
	if (!state.issues.some((issue) => issue.code === "predicate_too_complex" && issue.message === message)) state.issues.push({
		code: "predicate_too_complex",
		path,
		message
	});
}
/** @internal Pre-parse complexity guard shared by the trace-query and trace-aggregate request schemas. */
function findPredicateComplexityIssue(input, rootPaths) {
	if (!input || typeof input !== "object") return void 0;
	const stack = [];
	for (let index = rootPaths.length - 1; index >= 0; index -= 1) {
		const path = rootPaths[index];
		let predicate = input;
		for (const part of path) {
			if (!predicate || typeof predicate !== "object" || !Object.hasOwn(predicate, part)) {
				predicate = void 0;
				break;
			}
			predicate = predicate[part];
		}
		if (predicate !== void 0) stack.push({
			predicate,
			path,
			depth: 1
		});
	}
	let nodes = 0;
	while (stack.length > 0) {
		const frame = stack.pop();
		nodes += 1;
		if (frame.depth > 12 || nodes > 100) return frame.path;
		if (!frame.predicate || typeof frame.predicate !== "object") continue;
		const predicate = frame.predicate;
		if ((predicate.op === "and" || predicate.op === "or") && Array.isArray(predicate.args)) {
			for (let index = predicate.args.length - 1; index >= 0; index -= 1) stack.push({
				predicate: predicate.args[index],
				path: [
					...frame.path,
					"args",
					index
				],
				depth: frame.depth + 1
			});
			continue;
		}
		if (predicate.op === "not" && Object.hasOwn(predicate, "arg")) {
			stack.push({
				predicate: predicate.arg,
				path: [...frame.path, "arg"],
				depth: frame.depth + 1
			});
			continue;
		}
		for (const collection of [
			"traces",
			"feedback",
			"scores",
			"spans"
		]) {
			const clause = predicate[collection];
			if (!clause || typeof clause !== "object") continue;
			for (const quantifier of ["none", "some"]) {
				if (!Object.hasOwn(clause, quantifier)) continue;
				stack.push({
					predicate: clause[quantifier],
					path: [
						...frame.path,
						collection,
						quantifier
					],
					depth: frame.depth + 1
				});
			}
		}
	}
}
function getTraceQueryFieldRule(scope, path) {
	if (scope === "trace" && isTraceQueryMetadataPath(path)) return METADATA_FIELD_RULE;
	const registry = TRACE_QUERY_FIELD_REGISTRY[scope];
	return Object.hasOwn(registry, path) ? registry[path] : void 0;
}
function isTraceQueryMetadataPath(path) {
	if (!path.startsWith("metadata.") || !hasMaxUtf8Bytes$1(path, 128)) return false;
	const key = path.slice(9);
	return key.length > 0 && !key.includes(".");
}
function isTraceQueryValueSuggestionsPath(scope, path) {
	return getTraceQueryFieldRule(scope, normalizeTraceQueryPath(path))?.valueSuggestions === true;
}
function getTraceQueryCanonicalFieldDescriptors(scope, search) {
	const normalizedSearch = search?.trim().toLowerCase();
	return Object.entries(TRACE_QUERY_FIELD_REGISTRY[scope]).filter(([path]) => !normalizedSearch || path.toLowerCase().includes(normalizedSearch)).map(([path, rule]) => ({
		path,
		valueKind: rule.valueKind,
		operators: [...rule.operators],
		valueSuggestions: rule.valueSuggestions
	}));
}
function createTraceQueryObservedFieldDescriptor(path, occurrences) {
	return traceQueryObservedFieldDescriptorSchema.parse({
		path,
		valueKind: "string",
		operators: [...TRACE_QUERY_STRING_OPERATORS],
		valueSuggestions: true,
		occurrences
	});
}
function parseGetTraceQueryFieldsArgs(input) {
	const result = getTraceQueryFieldsArgsSchema.safeParse(input);
	if (!result.success) throw new TraceQueryValidationError(formatTraceQuerySchemaIssues(result.error));
	return result.data;
}
function parseGetTraceQueryValuesArgs(input) {
	const result = getTraceQueryValuesArgsSchema.safeParse(input);
	if (!result.success) throw new TraceQueryValidationError(formatTraceQuerySchemaIssues(result.error));
	return result.data;
}
function planTraceQueryObservedFields(args, options = {}) {
	return {
		timeRange: {
			from: new Date(args.timeRange.from).toISOString(),
			to: new Date(args.timeRange.to).toISOString()
		},
		predicateScope: args.predicateScope,
		search: args.search,
		limit: args.limit,
		scope: normalizeTraceQueryTenantScope(options.scope)
	};
}
function planTraceQueryValues(args, options = {}) {
	return {
		...planTraceQueryObservedFields(args, options),
		path: args.path
	};
}
/**
* Drops an absent `resourceId` so the plan and cursor binding are canonical.
*
* @internal Shared with the trace-aggregate planner.
*/
function normalizeTraceQueryTenantScope(scope) {
	if (!scope) return void 0;
	return scope.resourceId === void 0 ? { organizationId: scope.organizationId } : {
		organizationId: scope.organizationId,
		resourceId: scope.resourceId
	};
}
const STRUCTURAL_ISSUE_CODES = /* @__PURE__ */ new Set([
	"invalid_type",
	"invalid_value",
	"invalid_union",
	"invalid_key",
	"invalid_element",
	"unrecognized_keys"
]);
/**
* Reports the issues of the one union branch whose shape matched and that failed only checks
* (sizes, formats, refinements). Zod did this itself until 4.6.7 made an oversized array fail its
* size check before parsing the elements, which aborts the branch, so zod now reports only the union.
*/
function narrowUnionIssue(issue) {
	if (issue.code !== "invalid_union") return [issue];
	const matching = issue.errors.map((branch) => branch.flatMap((inner) => narrowUnionIssue({
		...inner,
		path: [...issue.path, ...inner.path]
	}))).filter((branch) => branch.length > 0 && branch.every((inner) => !STRUCTURAL_ISSUE_CODES.has(inner.code)));
	return matching.length === 1 ? matching[0] : [issue];
}
function formatTraceQuerySchemaIssues(error) {
	return error.issues.flatMap(narrowUnionIssue).map((issue) => {
		const customIssueCode = issue.code === "custom" ? issue.message === PREDICATE_COMPLEXITY_MESSAGE ? "predicate_too_complex" : issue.message === PAGINATION_MODE_CONFLICT_MESSAGE ? "pagination_mode_conflict" : issue.message === GROUP_PAGINATION_NOT_SUPPORTED_MESSAGE ? "group_pagination_not_supported" : void 0 : void 0;
		return {
			code: customIssueCode ?? "invalid_request",
			path: issue.path.map((part) => typeof part === "symbol" ? String(part) : part),
			message: customIssueCode ? issue.message : "The value does not match the trace-query request contract"
		};
	});
}
function parseTraceQueryRequest(input) {
	const result = traceQueryRequestSchema.safeParse(input);
	if (!result.success) throw new TraceQueryValidationError(formatTraceQuerySchemaIssues(result.error));
	return result.data;
}
function parseQueryThreadsInput(input) {
	const result = queryThreadsInputSchema.safeParse(input);
	if (!result.success) throw new TraceQueryValidationError(formatTraceQuerySchemaIssues(result.error));
	return result.data;
}
/** @internal */
function planThreadPredicate(predicate, path, depth, state) {
	state.nodes += 1;
	if (depth > 12 || state.nodes > 100) {
		addPredicateComplexityIssue(path, PREDICATE_COMPLEXITY_MESSAGE, state);
		return;
	}
	if ("traces" in predicate) {
		state.relatedClauses += 1;
		if (state.relatedClauses > 8) addPredicateComplexityIssue(path, `Trace queries are limited to 8 related collection clauses`, state);
		const quantifier = "some" in predicate.traces ? "some" : "none";
		const planned = planPredicate("some" in predicate.traces ? predicate.traces.some : predicate.traces.none, "trace", [
			...path,
			"traces",
			quantifier
		], depth + 1, state);
		return planned ? {
			type: "relation",
			collection: "traces",
			quantifier,
			predicate: planned
		} : void 0;
	}
	if (predicate.op === "and" || predicate.op === "or") {
		const args = predicate.args.map((arg, index) => planThreadPredicate(arg, [
			...path,
			"args",
			index
		], depth + 1, state)).filter((arg) => arg !== void 0);
		return {
			type: "boolean",
			operator: predicate.op,
			args
		};
	}
	if (predicate.op === "not") {
		const arg = planThreadPredicate(predicate.arg, [...path, "arg"], depth + 1, state);
		return arg ? {
			type: "not",
			arg
		} : void 0;
	}
}
/**
* Plans a trace-scope selection predicate with a fresh complexity budget, appending any
* problems to `issues`.
*
* @internal Shared with the trace-aggregate planner so both apply identical selection
* validation.
*/
function planTraceQuerySelectionPredicate(where, issues, path = ["where"], allowTokenSearch = false) {
	return planPredicate(where, "trace", path, 1, {
		nodes: 0,
		relatedClauses: 0,
		literalUnits: 0,
		issues,
		allowTokenSearch
	});
}
/** @internal Plans a direct span-row predicate without changing related trace predicates. */
function planSpanQuerySelectionPredicate(where, issues, allowTokenSearch = false) {
	return planPredicate(where, "spanQuery", ["where"], 1, {
		nodes: 0,
		relatedClauses: 0,
		literalUnits: 0,
		issues,
		allowTokenSearch
	});
}
/** @internal Shares scalar validation without admitting related-trace predicates. */
function planThreadQuerySelectionPredicate(where, issues) {
	return planPredicate(where, "threadQuery", ["where"], 1, {
		nodes: 0,
		relatedClauses: 0,
		literalUnits: 0,
		issues,
		isThreadQuery: true
	});
}
/** @internal */
function planPredicate(predicate, context, path, depth, state, underNegation = false) {
	state.nodes += 1;
	if (depth > 12 || state.nodes > 100) {
		addPredicateComplexityIssue(path, PREDICATE_COMPLEXITY_MESSAGE, state);
		return;
	}
	if ("spans" in predicate || "scores" in predicate || "feedback" in predicate) {
		state.relatedClauses += 1;
		if (state.relatedClauses > 8) addPredicateComplexityIssue(path, `Trace queries are limited to 8 related collection clauses`, state);
		if (context !== "trace") {
			state.issues.push({
				code: "invalid_request",
				path,
				message: "Related collections cannot be nested inside related-record predicates"
			});
			return;
		}
		const collection = "spans" in predicate ? "spans" : "scores" in predicate ? "scores" : "feedback";
		const clause = "spans" in predicate ? predicate.spans : "scores" in predicate ? predicate.scores : predicate.feedback;
		const quantifier = "some" in clause ? "some" : "none";
		const planned = planPredicate("some" in clause ? clause.some : clause.none, collection, [
			...path,
			collection,
			quantifier
		], depth + 1, state, underNegation || quantifier === "none");
		return planned ? {
			type: "relation",
			collection,
			quantifier,
			predicate: planned
		} : void 0;
	}
	if (predicate.op === "and" || predicate.op === "or") {
		const args = predicate.args.map((arg, index) => planPredicate(arg, context, [
			...path,
			"args",
			index
		], depth + 1, state, underNegation)).filter((arg) => arg !== void 0);
		return {
			type: "boolean",
			operator: predicate.op,
			args
		};
	}
	if (predicate.op === "not") {
		const arg = planPredicate(predicate.arg, context, [...path, "arg"], depth + 1, state, true);
		return arg ? {
			type: "not",
			arg
		} : void 0;
	}
	if (predicate.op === "hasAllTokens") {
		if (state.isThreadQuery || underNegation) {
			state.issues.push({
				code: "operator_not_allowed",
				path: [...path, "op"],
				message: state.isThreadQuery ? "Token search is not supported in thread queries" : "Token search is not supported beneath not or none"
			});
			return;
		}
		if (!state.allowTokenSearch) {
			state.issues.push({
				code: "operator_not_allowed",
				path: [...path, "op"],
				message: "Token search requires a supporting host"
			});
			return;
		}
		if (context !== "spans" && context !== "spanQuery") {
			state.issues.push({
				code: "field_not_allowed",
				path,
				message: "Token matching is supported only on spans"
			});
			return;
		}
		state.literalUnits += 1;
		if (state.literalUnits > 1e3) addPredicateComplexityIssue([
			...path,
			"right",
			"literal"
		], `Trace queries are limited to ${TRACE_QUERY_MAX_LITERAL_UNITS} literal units`, state);
		return {
			type: "tokens",
			field: predicate.left.path,
			operator: "hasAllTokens",
			value: predicate.right.literal
		};
	}
	const rules = rulesForContext(context);
	if (predicate.op === "exists" || predicate.op === "notExists") {
		const field = normalizeTraceQueryPath(predicate.path);
		const rule = getRule(field, context, rules, [...path, "path"], state);
		if (!rule) return void 0;
		if (!rule.operators.includes(predicate.op)) addOperatorIssue(predicate.op, field, [...path, "op"], state);
		if (rule.valueKind === "array") return {
			type: "collection",
			field,
			operator: predicate.op === "exists" ? "notEmpty" : "empty"
		};
		return {
			type: "presence",
			field,
			operator: predicate.op
		};
	}
	if (predicate.op === "includes" || predicate.op === "notIncludes") {
		state.literalUnits += 1;
		if (state.literalUnits > 1e3) addPredicateComplexityIssue([...path, "value"], `Trace queries are limited to ${TRACE_QUERY_MAX_LITERAL_UNITS} literal units`, state);
		const field = normalizeTraceQueryPath(predicate.path);
		const rule = getRule(field, context, rules, [...path, "path"], state);
		if (!rule) return void 0;
		if (!rule.operators.includes(predicate.op)) addOperatorIssue(predicate.op, field, [...path, "op"], state);
		return {
			type: "collection",
			field,
			operator: predicate.op,
			value: predicate.value
		};
	}
	if (predicate.op === "matches" || predicate.op === "notMatches") {
		state.literalUnits += 1;
		if (state.literalUnits > 1e3) addPredicateComplexityIssue([
			...path,
			"right",
			"literal"
		], `Trace queries are limited to ${TRACE_QUERY_MAX_LITERAL_UNITS} literal units`, state);
		const field = normalizeTraceQueryPath(predicate.left.path);
		const rule = getRule(field, context, rules, [
			...path,
			"left",
			"path"
		], state);
		if (!rule) return void 0;
		if (!rule.operators.includes(predicate.op)) addOperatorIssue(predicate.op, field, [...path, "op"], state);
		const value = normalizeTraceQueryText(predicate.right.literal);
		if (value === "") {
			state.issues.push({
				code: "invalid_literal",
				path: [
					...path,
					"right",
					"literal"
				],
				message: "Text predicates require at least one letter or digit"
			});
			return;
		}
		return {
			type: "text",
			field,
			operator: predicate.op,
			value
		};
	}
	if (predicate.op === "in" || predicate.op === "notIn") {
		state.literalUnits += predicate.set.length;
		if (state.literalUnits > 1e3) addPredicateComplexityIssue([...path, "set"], `Trace queries are limited to ${TRACE_QUERY_MAX_LITERAL_UNITS} literal units`, state);
		if (!("path" in predicate.value)) {
			state.issues.push({
				code: "invalid_operands",
				path: [...path, "value"],
				message: "Membership predicates require an allowlisted field path"
			});
			return;
		}
		const field = normalizeTraceQueryPath(predicate.value.path);
		const rule = getRule(field, context, rules, [
			...path,
			"value",
			"path"
		], state);
		if (!rule) return void 0;
		if (!rule.operators.includes(predicate.op)) addOperatorIssue(predicate.op, field, [...path, "op"], state);
		const values = normalizeSet(predicate.set, rule);
		if (!values) {
			state.issues.push({
				code: "invalid_literal",
				path: [...path, "set"],
				message: "Membership values must be homogeneous and match the selected field type"
			});
			return;
		}
		return {
			type: "membership",
			field,
			operator: predicate.op,
			values
		};
	}
	const comparison = predicate;
	state.literalUnits += 1;
	if (state.literalUnits > 1e3) addPredicateComplexityIssue([
		...path,
		"right",
		"literal"
	], `Trace queries are limited to ${TRACE_QUERY_MAX_LITERAL_UNITS} literal units`, state);
	if (!("path" in comparison.left) || !("literal" in comparison.right)) {
		state.issues.push({
			code: "invalid_operands",
			path,
			message: "Comparison predicates require a field on the left and a literal on the right"
		});
		return;
	}
	const field = normalizeTraceQueryPath(comparison.left.path);
	const rule = getRule(field, context, rules, [
		...path,
		"left",
		"path"
	], state);
	if (!rule) return void 0;
	if (!rule.operators.includes(comparison.op)) addOperatorIssue(comparison.op, field, [...path, "op"], state);
	const value = normalizeLiteral(comparison.right.literal, rule, comparison.op);
	if (value === void 0) {
		state.issues.push({
			code: "invalid_literal",
			path: [
				...path,
				"right",
				"literal"
			],
			message: "The literal does not match the selected field type"
		});
		return;
	}
	return {
		type: "comparison",
		field,
		operator: comparison.op,
		value
	};
}
function rulesForContext(context) {
	if (context === "threadQuery") return THREAD_QUERY_FIELD_REGISTRY;
	if (context === "spanQuery") return SPAN_QUERY_FIELD_REGISTRY;
	return TRACE_QUERY_FIELD_REGISTRY[context];
}
function getRule(field, context, rules, path, state) {
	if (context === "trace" && field.startsWith("metadata.")) {
		const key = field.slice(9);
		if (key.length === 0 || key.includes(".")) {
			state.issues.push({
				code: "invalid_metadata_key",
				path,
				message: "Metadata predicates require one non-empty top-level key"
			});
			return;
		}
		return METADATA_FIELD_RULE;
	}
	if (!Object.hasOwn(rules, field)) {
		state.issues.push({
			code: "field_not_allowed",
			path,
			message: "The predicate field is not allowed here"
		});
		return;
	}
	return rules[field];
}
function addOperatorIssue(operator, field, path, state) {
	state.issues.push({
		code: "operator_not_allowed",
		path,
		message: `Operator ${operator} is not supported for field ${field}`
	});
}
/**
* Unwraps `${...}` templates and trims a caller-supplied field path.
*
* @internal Shared with the trace-aggregate planner so dimension, measure, and `having`
* paths are normalized exactly like predicate paths.
*/
function normalizeTraceQueryPath(path) {
	const unwrapped = /^\$\{([^}]+)\}$/.exec(path.trim())?.[1] ?? path;
	const normalized = unwrapped.trim();
	if (normalized.startsWith("metadata.")) {
		const prefixIndex = unwrapped.indexOf("metadata.");
		return `metadata.${unwrapped.slice(prefixIndex + 9)}`;
	}
	return normalized;
}
/**
* Lowercases text and reduces it to its words: maximal runs of Unicode letters, combining
* marks, and digits, joined by single spaces. Text is composed to NFC first, so an accent
* stored as a separate mark equals its precomposed form, and marks stay inside their word,
* so `नमस्ते` is one word. After that, `İ` folds to plain `i`: it is the only letter whose lowercase form
* is two code points, and the stores' `lower()` returns one. A Greek final `ς` becomes `σ`, since
* `toLowerCase()` picks the final form by position and the stores' `lower()` does not. `matches` succeeds when the
* normalized literal appears as a contiguous word sequence inside the normalized field
* value. Stores apply the same normalization in SQL, so `incorrect` matches
* `This answer is incorrect.` but not `This was incorrectly formatted.`
*/
function normalizeTraceQueryText(text) {
	return text.normalize("NFC").replace(/\u0130/g, "i").toLowerCase().replace(/\u03c2/g, "σ").split(/[^\p{L}\p{M}\p{N}]+/u).filter((word) => word.length > 0).join(" ");
}
function normalizeLiteral(value, rule, operator) {
	if (rule.valueKind === "number") return typeof value === "number" && Number.isFinite(value) ? value : void 0;
	if (rule.valueKind === "stringOrNumber") {
		if (operator && !TRACE_QUERY_STRING_OPERATORS.some((candidate) => candidate === operator)) return typeof value === "number" && Number.isFinite(value) ? value : void 0;
		return typeof value === "string" || typeof value === "number" && Number.isFinite(value) ? value : void 0;
	}
	if (rule.valueKind === "timestamp") {
		const timestamp = timestampLiteralSchema.safeParse(value);
		return timestamp.success ? new Date(timestamp.data).toISOString() : void 0;
	}
	if (rule.valueKind === "string" || rule.valueKind === "array") return typeof value === "string" && (!rule.nonEmpty || value.trim().length > 0) ? value : void 0;
}
function normalizeSet(values, rule) {
	const normalized = values.map((value) => normalizeLiteral(value, rule));
	if (normalized.some((value) => value === void 0)) return void 0;
	if (rule.valueKind === "stringOrNumber" && normalized.some((value) => typeof value !== typeof normalized[0])) return void 0;
	return normalized;
}
/** Whether a trusted predicate requires indexed token-search support. */
function hasTraceQueryTokenPredicate(predicate) {
	if (!predicate) return false;
	if (predicate.type === "tokens") return true;
	if (predicate.type === "boolean") return predicate.args.some(hasTraceQueryTokenPredicate);
	if (predicate.type === "not") return hasTraceQueryTokenPredicate(predicate.arg);
	if (predicate.type === "relation") return hasTraceQueryTokenPredicate(predicate.predicate);
	return false;
}
// src/storage/domains/observability/trace-aggregate.ts
/**
* Public request/response contract for `aggregateTraces()`.
*
* Zod owns grammar and shape only (fixed literals, caps, defaults, unknown-property rejection).
* Semantic checks — the groupable-dimension allowlist, `countDistinct` targets, `having` /
* `orderBy` referencing declared measures, and the bucket cap — belong to the aggregate planner.
*/
const TRACE_AGGREGATE_MAX_DIMENSIONS = 2;
const TRACE_AGGREGATE_DEFAULT_LIMIT = 100;
const TRACE_AGGREGATE_MAX_LIMIT = 1e3;
const TRACE_AGGREGATE_MAX_TIME_RANGE_DAYS = 365;
const TRACE_AGGREGATE_INTERVALS = [
	"1m",
	"5m",
	"15m",
	"1h",
	"1d"
];
const TRACE_AGGREGATE_FIXED_MEASURES = [
	"count",
	"duration.avg",
	"duration.min",
	"duration.max",
	"duration.p50",
	"duration.p90",
	"duration.p95",
	"duration.p99",
	"errorCount",
	"errorRate",
	"tokens.input.sum",
	"tokens.input.avg",
	"tokens.output.sum",
	"tokens.output.avg",
	"tokens.total.sum",
	"tokens.total.avg",
	"tokens.reasoning.sum",
	"tokens.reasoning.avg",
	"tokens.cached.sum",
	"tokens.cached.avg",
	"cost.sum",
	"cost.avg",
	"timeToFirstToken.avg",
	"timeToFirstToken.min",
	"timeToFirstToken.max",
	"timeToFirstToken.p50",
	"timeToFirstToken.p90",
	"timeToFirstToken.p95",
	"timeToFirstToken.p99",
	"timeToFirstToken.count",
	"timeToFirstChunk.avg",
	"timeToFirstChunk.min",
	"timeToFirstChunk.max",
	"timeToFirstChunk.p50",
	"timeToFirstChunk.p90",
	"timeToFirstChunk.p95",
	"timeToFirstChunk.p99",
	"timeToFirstChunk.count"
];
/** `cost.unit` value for a group whose priced rows use more than one cost unit. */
const TRACE_AGGREGATE_MIXED_COST_UNIT = "mixed";
const TRACE_AGGREGATE_COUNT_DISTINCT_PREFIX = "countDistinct.";
const hasMaxUtf8Bytes = (value, maxBytes) => new TextEncoder().encode(value).length <= maxBytes;
function isTraceAggregateCountDistinctMeasure(name) {
	return getTraceAggregateCountDistinctField(name) !== void 0;
}
/** Returns the target field of a `countDistinct.<field>` measure name, or `undefined` for any other name. */
function getTraceAggregateCountDistinctField(name) {
	if (!name.startsWith("countDistinct.")) return void 0;
	if (!hasMaxUtf8Bytes(name, 128)) return void 0;
	const field = name.slice(14);
	return field.length > 0 ? field : void 0;
}
const traceAggregateIntervalSchema = z.enum(TRACE_AGGREGATE_INTERVALS);
const traceAggregateCountDistinctMeasureSchema = z.templateLiteral([TRACE_AGGREGATE_COUNT_DISTINCT_PREFIX, z.string()]).refine((name) => isTraceAggregateCountDistinctMeasure(name), "Invalid countDistinct measure");
const traceAggregateMeasureSchema = z.union([z.enum(TRACE_AGGREGATE_FIXED_MEASURES), traceAggregateCountDistinctMeasureSchema]);
const traceAggregateDimensionSchema = z.string().min(1).refine((value) => hasMaxUtf8Bytes(value, 128), "Dimension path is too large");
const traceAggregateTimeRangeSchema = traceQueryTimeRangeSchema.superRefine((timeRange, context) => {
	const from = new Date(timeRange.from);
	const to = new Date(timeRange.to);
	if (from >= to) context.addIssue({
		code: "custom",
		path: [],
		message: "`from` must be earlier than `to`"
	});
	else if (to.getTime() - from.getTime() > 31536e6) context.addIssue({
		code: "custom",
		path: [],
		message: `The time range cannot exceed 365 days`
	});
});
const traceAggregateOrderBySchema = z.object({
	field: z.string().min(1),
	direction: z.enum(["asc", "desc"])
}).strict().default({
	field: "count",
	direction: "desc"
});
const hasDistinctValues$1 = (values) => new Set(values).size === values.length;
const traceAggregateRequestObjectSchema = z.object({
	timeRange: traceAggregateTimeRangeSchema,
	where: traceQueryPredicateSchema.optional(),
	groupBy: z.array(traceAggregateDimensionSchema).max(2).refine(hasDistinctValues$1, "Dimensions must be distinct").default([]),
	interval: traceAggregateIntervalSchema.optional(),
	measures: z.array(traceAggregateMeasureSchema).min(1).refine(hasDistinctValues$1, "Measures must be distinct"),
	having: traceQueryScalarPredicateSchema.optional(),
	orderBy: traceAggregateOrderBySchema,
	limit: z.number().int().min(1).max(TRACE_AGGREGATE_MAX_LIMIT).default(100)
}).strict();
/**
* A trace aggregate request without its time range, for callers that store a query and supply the
* range at run time (dashboard widgets). Apply `findPredicateComplexityIssue` before parsing.
*/
const traceAggregateQueryObjectSchema = traceAggregateRequestObjectSchema.omit({ timeRange: true });
const traceAggregateRequestSchema = z.preprocess((input, context) => {
	const issuePath = findPredicateComplexityIssue(input, [["where"], ["having"]]);
	if (issuePath) {
		context.addIssue({
			code: "custom",
			path: issuePath,
			message: TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE
		});
		return z.NEVER;
	}
	return input;
}, traceAggregateRequestObjectSchema);
const traceAggregateRowMeasuresSchema = z.record(traceAggregateMeasureSchema, z.number().nullable());
/** Returned on every row whenever any `cost.*` measure is requested. */
const traceAggregateRowCostSchema = z.object({
	/**
	* Covered traces ÷ usage-bearing traces; null when the group has no usage-bearing traces. A trace
	* is covered when it has priced cost and no total row failed to price.
	*/
	coverage: z.number().min(0).max(1).nullable(),
	/** The priced rows' cost unit, `'mixed'` when they use more than one, null when none are priced. */
	unit: z.string().nullable()
}).strict();
const traceAggregateRowSchema = z.object({
	dimensions: z.record(z.string(), z.string().nullable()).optional(),
	bucket: z.string().datetime({ offset: true }).optional(),
	measures: traceAggregateRowMeasuresSchema,
	cost: traceAggregateRowCostSchema.optional()
}).strict();
const traceAggregateResponseSchema = z.object({
	rows: z.array(traceAggregateRowSchema),
	truncated: z.boolean()
}).strict();
function formatTraceAggregateSchemaIssues(error) {
	return error.issues.map((issue) => {
		const predicateTooComplex = issue.code === "custom" && issue.message === "Predicates are limited to 100 nodes and 12 levels";
		return {
			code: predicateTooComplex ? "predicate_too_complex" : "invalid_request",
			path: issue.path.map((part) => typeof part === "symbol" ? String(part) : part),
			message: predicateTooComplex ? TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE : "The value does not match the trace-aggregate request contract"
		};
	});
}
function parseTraceAggregateRequest(input) {
	const result = traceAggregateRequestSchema.safeParse(input);
	if (!result.success) throw new TraceQueryValidationError(formatTraceAggregateSchemaIssues(result.error));
	return result.data;
}
// src/storage/domains/observability/trace-aggregate-registry.ts
const stringDimension$1 = () => ({ valueKind: "string" });
/**
* Trace-scope groupable dimensions for `aggregateTraces()`.
* Key order is the spec order and is the order discovery lists them in. Top-level
* `metadata.<key>` paths are also groupable; see `isTraceAggregateDimension`.
*/
const TRACE_AGGREGATE_DIMENSION_REGISTRY = {
	entityType: stringDimension$1(),
	entityName: stringDimension$1(),
	name: stringDimension$1(),
	spanType: stringDimension$1(),
	entityId: stringDimension$1(),
	environment: stringDimension$1(),
	status: stringDimension$1(),
	outcome: stringDimension$1(),
	stopReason: stringDimension$1(),
	serviceName: stringDimension$1(),
	executionSource: stringDimension$1(),
	threadId: stringDimension$1(),
	resourceId: stringDimension$1(),
	userId: stringDimension$1(),
	sessionId: stringDimension$1(),
	organizationId: stringDimension$1(),
	experimentId: stringDimension$1()
};
const TRACE_AGGREGATE_METADATA_DIMENSION_RULE = stringDimension$1();
/** Identity fields excluded from grouping: grouping by identity is not grouping. */
const TRACE_AGGREGATE_IDENTITY_FIELDS = [
	"traceId",
	"spanId",
	"runId",
	"requestId"
];
function isTraceAggregateCanonicalDimension(path) {
	return Object.hasOwn(TRACE_AGGREGATE_DIMENSION_REGISTRY, path);
}
/**
* Whether an already-normalized path may appear in `groupBy`. Callers unwrap
* `${...}` templates and trim before calling; this predicate does no normalization.
*/
function isTraceAggregateDimension(path) {
	return isTraceAggregateCanonicalDimension(path) || isTraceQueryMetadataPath(path);
}
function isTraceAggregateCountDistinctField(path) {
	return path === "traceId" || isTraceAggregateDimension(path);
}
function getTraceAggregateDimensionRule(path) {
	if (isTraceAggregateCanonicalDimension(path)) return TRACE_AGGREGATE_DIMENSION_REGISTRY[path];
	if (isTraceQueryMetadataPath(path)) return TRACE_AGGREGATE_METADATA_DIMENSION_RULE;
}
/**
* Token metric rows that carry the per-call cost. Each total row already holds the sum of its
* detail rows' costs, so cost is summed over these rows only.
*/
const TRACE_AGGREGATE_COST_METRIC_NAMES = [TokenMetrics.TOTAL_INPUT, TokenMetrics.TOTAL_OUTPUT];
/** Every token metric name a token or cost measure reads; store compilers prune metric rows to these. */
const TRACE_AGGREGATE_USAGE_METRIC_NAMES = [
	TokenMetrics.TOTAL_INPUT,
	TokenMetrics.TOTAL_OUTPUT,
	TokenMetrics.OUTPUT_REASONING,
	TokenMetrics.INPUT_CACHE_READ
];
const countMeasure = () => ({
	kind: "count",
	unit: "count",
	approximate: false
});
const durationMeasure = (statistic) => ({
	kind: "duration",
	statistic,
	unit: "milliseconds",
	approximate: statistic.startsWith("p")
});
const errorMeasure = (unit) => ({
	kind: "error",
	unit,
	approximate: false
});
const tokensMeasure = (statistic, metricNames) => ({
	kind: "tokens",
	statistic,
	unit: "tokens",
	approximate: false,
	metricNames
});
const costMeasure = (statistic) => ({
	kind: "cost",
	statistic,
	unit: "currency",
	approximate: false,
	metricNames: TRACE_AGGREGATE_COST_METRIC_NAMES
});
const timeToFirstMeasure = (kind, statistic) => ({
	kind,
	statistic,
	unit: statistic === "count" ? "count" : "milliseconds",
	approximate: statistic.startsWith("p"),
	field: kind === "timeToFirstToken" ? "timeToFirstTokenMs" : "timeToFirstChunkMs"
});
const TOTAL_TOKEN_METRIC_NAMES = [TokenMetrics.TOTAL_INPUT, TokenMetrics.TOTAL_OUTPUT];
/**
* Measures for `aggregateTraces()`: the measures computed from the trace root, followed by the
* token and cost measures, then time to first token/chunk. Time-to-first measures read the root
* span's value in `aggregateTraces()` (the value `queryTraces()` returns) and each span's own value
* in `aggregateSpans()`; they need the `aggregate-time-to-first-measures` store feature.
* `countDistinct.<field>` is a family keyed by field and is handled by
* `parseTraceAggregateMeasure` rather than listed here.
*/
const TRACE_AGGREGATE_MEASURE_REGISTRY = {
	count: countMeasure(),
	"duration.avg": durationMeasure("avg"),
	"duration.min": durationMeasure("min"),
	"duration.max": durationMeasure("max"),
	"duration.p50": durationMeasure("p50"),
	"duration.p90": durationMeasure("p90"),
	"duration.p95": durationMeasure("p95"),
	"duration.p99": durationMeasure("p99"),
	errorCount: errorMeasure("count"),
	errorRate: errorMeasure("ratio"),
	"tokens.input.sum": tokensMeasure("sum", [TokenMetrics.TOTAL_INPUT]),
	"tokens.input.avg": tokensMeasure("avg", [TokenMetrics.TOTAL_INPUT]),
	"tokens.output.sum": tokensMeasure("sum", [TokenMetrics.TOTAL_OUTPUT]),
	"tokens.output.avg": tokensMeasure("avg", [TokenMetrics.TOTAL_OUTPUT]),
	"tokens.total.sum": tokensMeasure("sum", TOTAL_TOKEN_METRIC_NAMES),
	"tokens.total.avg": tokensMeasure("avg", TOTAL_TOKEN_METRIC_NAMES),
	"tokens.reasoning.sum": tokensMeasure("sum", [TokenMetrics.OUTPUT_REASONING]),
	"tokens.reasoning.avg": tokensMeasure("avg", [TokenMetrics.OUTPUT_REASONING]),
	"tokens.cached.sum": tokensMeasure("sum", [TokenMetrics.INPUT_CACHE_READ]),
	"tokens.cached.avg": tokensMeasure("avg", [TokenMetrics.INPUT_CACHE_READ]),
	"cost.sum": costMeasure("sum"),
	"cost.avg": costMeasure("avg"),
	"timeToFirstToken.avg": timeToFirstMeasure("timeToFirstToken", "avg"),
	"timeToFirstToken.min": timeToFirstMeasure("timeToFirstToken", "min"),
	"timeToFirstToken.max": timeToFirstMeasure("timeToFirstToken", "max"),
	"timeToFirstToken.p50": timeToFirstMeasure("timeToFirstToken", "p50"),
	"timeToFirstToken.p90": timeToFirstMeasure("timeToFirstToken", "p90"),
	"timeToFirstToken.p95": timeToFirstMeasure("timeToFirstToken", "p95"),
	"timeToFirstToken.p99": timeToFirstMeasure("timeToFirstToken", "p99"),
	"timeToFirstToken.count": timeToFirstMeasure("timeToFirstToken", "count"),
	"timeToFirstChunk.avg": timeToFirstMeasure("timeToFirstChunk", "avg"),
	"timeToFirstChunk.min": timeToFirstMeasure("timeToFirstChunk", "min"),
	"timeToFirstChunk.max": timeToFirstMeasure("timeToFirstChunk", "max"),
	"timeToFirstChunk.p50": timeToFirstMeasure("timeToFirstChunk", "p50"),
	"timeToFirstChunk.p90": timeToFirstMeasure("timeToFirstChunk", "p90"),
	"timeToFirstChunk.p95": timeToFirstMeasure("timeToFirstChunk", "p95"),
	"timeToFirstChunk.p99": timeToFirstMeasure("timeToFirstChunk", "p99"),
	"timeToFirstChunk.count": timeToFirstMeasure("timeToFirstChunk", "count")
};
function isTraceAggregateCanonicalMeasure(name) {
	return Object.hasOwn(TRACE_AGGREGATE_MEASURE_REGISTRY, name);
}
function parseTraceAggregateMeasure(name) {
	if (isTraceAggregateCanonicalMeasure(name)) return {
		type: "canonical",
		measure: name,
		rule: TRACE_AGGREGATE_MEASURE_REGISTRY[name]
	};
	const field = getTraceAggregateCountDistinctField(name);
	if (field !== void 0 && isTraceAggregateCountDistinctField(field)) return {
		type: "countDistinct",
		field
	};
}
function getTraceAggregateDimensionDescriptors() {
	return Object.keys(TRACE_AGGREGATE_DIMENSION_REGISTRY).map((path) => ({
		path,
		valueKind: TRACE_AGGREGATE_DIMENSION_REGISTRY[path].valueKind
	}));
}
function getTraceAggregateMeasureDescriptors() {
	return Object.keys(TRACE_AGGREGATE_MEASURE_REGISTRY).map((name) => {
		const rule = TRACE_AGGREGATE_MEASURE_REGISTRY[name];
		return {
			name,
			kind: rule.kind,
			...rule.statistic ? { statistic: rule.statistic } : {},
			unit: rule.unit,
			approximate: rule.approximate
		};
	});
}
// src/storage/domains/observability/trace-aggregate-planner.ts
/**
* Trusted, backend-independent plan for `aggregateTraces()`.
*
* `planTraceAggregate` enforces everything the request schema leaves to the planner: the
* groupable-dimension allowlist, `countDistinct` targets, `having` / `orderBy` referencing
* requested measures or dimensions, the 365-day window, the 1000-bucket cap, and the 10,000-row
* cap. Only allowlisted identifiers and finite numeric literals reach the plan.
*/
const TRACE_AGGREGATE_MAX_BUCKETS = 1e3;
/** Upper bound on `limit × bucket count` when `interval` is present. */
const TRACE_AGGREGATE_MAX_ROWS = 1e4;
const TRACE_AGGREGATE_INTERVAL_MS = {
	"1m": 6e4,
	"5m": 3e5,
	"15m": 9e5,
	"1h": 36e5,
	"1d": 864e5
};
/**
* Number of UTC-aligned buckets a `[from, to)` range touches. A range that does not
* start on a bucket boundary touches one more bucket than `(to - from) / interval`.
*/
function countTraceAggregateBuckets(fromMs, toMs, interval) {
	const intervalMs = TRACE_AGGREGATE_INTERVAL_MS[interval];
	return Math.floor((toMs - 1) / intervalMs) - Math.floor(fromMs / intervalMs) + 1;
}
/**
* Converts a structurally valid aggregate request into the canonical plan consumed by
* observability storage adapters.
*
* @internal This is a trusted server/storage boundary, not a client-side query builder.
*/
function planTraceAggregate(request, options = {}) {
	const issues = [];
	const where = request.where ? planTraceQuerySelectionPredicate(request.where, issues, ["where"], options.allowTokenSearch) : void 0;
	return {
		result: "aggregate",
		...planAggregateGroups(request, issues, {
			isDimension: isTraceAggregateDimension,
			parseMeasure: parseTraceAggregateMeasure
		}),
		where,
		scope: normalizeTraceQueryTenantScope(options.scope)
	};
}
/** @internal Window, bucket and row caps, dimensions, measures, `having` and `orderBy` for any scope. */
function planAggregateGroups(request, issues, policy) {
	const from = new Date(request.timeRange.from);
	const to = new Date(request.timeRange.to);
	const fromMs = from.getTime();
	const toMs = to.getTime();
	if (fromMs >= toMs) issues.push({
		code: "invalid_time_range",
		path: ["timeRange"],
		message: "`from` must be earlier than `to`"
	});
	else if (toMs - fromMs > 31536e6) issues.push({
		code: "time_range_too_large",
		path: ["timeRange"],
		message: `The time range cannot exceed 365 days`
	});
	else if (request.interval) {
		const buckets = countTraceAggregateBuckets(fromMs, toMs, request.interval);
		if (buckets > 1e3) {
			const smallest = TRACE_AGGREGATE_INTERVALS.find((interval) => countTraceAggregateBuckets(fromMs, toMs, interval) <= TRACE_AGGREGATE_MAX_BUCKETS);
			issues.push({
				code: "too_many_buckets",
				path: ["interval"],
				message: `The interval produces more than ${TRACE_AGGREGATE_MAX_BUCKETS} buckets; the smallest permitted interval is ${smallest}`
			});
		} else if (request.limit * buckets > 1e4) issues.push({
			code: "too_many_rows",
			path: ["limit"],
			message: `limit × buckets cannot exceed ${TRACE_AGGREGATE_MAX_ROWS} rows; lower limit or widen interval`
		});
	}
	const dimensions = [];
	request.groupBy.forEach((raw, index) => {
		const path = ["groupBy", index];
		const dimension = normalizeTraceQueryPath(raw);
		if (!policy.isDimension(dimension)) {
			issues.push(dimension.startsWith("metadata.") && policy.isDimension("metadata.key") ? {
				code: "invalid_metadata_key",
				path,
				message: "Metadata dimensions require one non-empty top-level key"
			} : {
				code: "field_not_allowed",
				path,
				message: "The field cannot be used as a dimension"
			});
			return;
		}
		if (dimensions.includes(dimension)) {
			issues.push({
				code: "invalid_request",
				path,
				message: "Dimensions must be distinct"
			});
			return;
		}
		dimensions.push(dimension);
	});
	const measures = [];
	const measureNames = /* @__PURE__ */ new Map();
	request.measures.forEach((raw, index) => {
		const path = ["measures", index];
		const measure = planMeasure(raw, path, issues, policy);
		if (!measure) return;
		if (measureNames.has(measure.name)) {
			issues.push({
				code: "invalid_request",
				path,
				message: "Measures must be distinct"
			});
			return;
		}
		measureNames.set(measure.name, measure.name);
		measures.push(measure);
	});
	const referenceable = new Map(measureNames).set("count", "count");
	const having = request.having ? planHaving(request.having, ["having"], 1, {
		nodes: 0,
		issues,
		measureNames: referenceable
	}) : void 0;
	const orderBy = planOrderBy(request.orderBy, referenceable, dimensions, issues);
	if (issues.length > 0 || !orderBy) throw new TraceQueryValidationError(issues);
	return {
		timeRange: {
			from: from.toISOString(),
			to: to.toISOString()
		},
		dimensions,
		interval: request.interval,
		measures,
		having,
		orderBy,
		limit: request.limit
	};
}
/**
* Normalizes a measure name identically for `measures`, `having` paths, and `orderBy.field`, so
* `countDistinct.${threadId}` and `countDistinct.threadId` resolve to the same requested measure.
*/
function normalizeTraceAggregateMeasureName(raw) {
	const unwrapped = normalizeTraceQueryPath(raw);
	return unwrapped.startsWith("countDistinct.") ? `${TRACE_AGGREGATE_COUNT_DISTINCT_PREFIX}${normalizeTraceQueryPath(unwrapped.slice(14))}` : unwrapped;
}
function planMeasure(raw, path, issues, policy) {
	const name = normalizeTraceAggregateMeasureName(raw);
	const parsed = policy.parseMeasure(name);
	if (parsed?.type === "canonical") return {
		type: "canonical",
		name: parsed.measure
	};
	if (parsed?.type === "countDistinct") return {
		type: "countDistinct",
		name: `${TRACE_AGGREGATE_COUNT_DISTINCT_PREFIX}${parsed.field}`,
		field: parsed.field
	};
	const field = name.slice(14);
	issues.push(name.startsWith("countDistinct.") && field.startsWith("metadata.") && policy.isDimension("metadata.key") ? {
		code: "invalid_metadata_key",
		path,
		message: "countDistinct over metadata requires one non-empty top-level key"
	} : {
		code: "field_not_allowed",
		path,
		message: "The measure is not supported"
	});
}
function planHaving(predicate, path, depth, state) {
	state.nodes += 1;
	if (depth > 12 || state.nodes > 100) {
		if (!state.issues.some((issue) => issue.code === "predicate_too_complex")) state.issues.push({
			code: "predicate_too_complex",
			path,
			message: TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE
		});
		return;
	}
	if (predicate.op === "and" || predicate.op === "or") {
		const args = predicate.args.map((arg, index) => planHaving(arg, [
			...path,
			"args",
			index
		], depth + 1, state)).filter((arg) => arg !== void 0);
		return {
			type: "boolean",
			operator: predicate.op,
			args
		};
	}
	if (predicate.op === "not") {
		const arg = planHaving(predicate.arg, [...path, "arg"], depth + 1, state);
		return arg ? {
			type: "not",
			arg
		} : void 0;
	}
	if (predicate.op === "exists" || predicate.op === "notExists") {
		state.issues.push({
			code: "operator_not_allowed",
			path: [...path, "op"],
			message: "Presence operators are not supported in having"
		});
		return;
	}
	if (predicate.op === "includes" || predicate.op === "notIncludes") {
		state.issues.push({
			code: "operator_not_allowed",
			path: [...path, "op"],
			message: "Array containment operators are not supported in having; measures are scalar"
		});
		return;
	}
	if (predicate.op === "in" || predicate.op === "notIn") {
		if (!("path" in predicate.value)) {
			state.issues.push({
				code: "invalid_operands",
				path: [...path, "value"],
				message: "Membership predicates in having require a requested measure name"
			});
			return;
		}
		const measure = resolveHavingMeasure(predicate.value.path, [
			...path,
			"value",
			"path"
		], state);
		if (!measure) return void 0;
		const values = predicate.set.map(toFiniteNumber);
		if (values.some((value) => value === void 0)) {
			state.issues.push({
				code: "invalid_literal",
				path: [...path, "set"],
				message: "Membership values in having must be finite numbers"
			});
			return;
		}
		return {
			type: "membership",
			measure,
			operator: predicate.op,
			values
		};
	}
	if (predicate.op === "matches" || predicate.op === "notMatches" || predicate.op === "hasAllTokens") {
		state.issues.push({
			code: "operator_not_allowed",
			path: [...path, "op"],
			message: "Text operators are not supported in having; measures are numeric"
		});
		return;
	}
	const comparison = predicate;
	if (!("path" in comparison.left) || !("literal" in comparison.right)) {
		state.issues.push({
			code: "invalid_operands",
			path,
			message: "Comparison predicates in having require a measure on the left and a literal on the right"
		});
		return;
	}
	const measure = resolveHavingMeasure(comparison.left.path, [
		...path,
		"left",
		"path"
	], state);
	if (!measure) return void 0;
	const value = toFiniteNumber(comparison.right.literal);
	if (value === void 0) {
		state.issues.push({
			code: "invalid_literal",
			path: [
				...path,
				"right",
				"literal"
			],
			message: "Comparison literals in having must be finite numbers"
		});
		return;
	}
	return {
		type: "comparison",
		measure,
		operator: comparison.op,
		value
	};
}
function resolveHavingMeasure(raw, path, state) {
	const name = normalizeTraceAggregateMeasureName(raw);
	const measure = state.measureNames.get(name);
	if (measure) return measure;
	state.issues.push({
		code: "field_not_allowed",
		path,
		message: "having may only reference requested measures or count"
	});
}
function planOrderBy(orderBy, measureNames, dimensions, issues) {
	const field = normalizeTraceAggregateMeasureName(orderBy.field);
	const measure = measureNames.get(field);
	if (measure) return {
		target: "measure",
		measure,
		direction: orderBy.direction
	};
	const dimension = dimensions.find((candidate) => candidate === field);
	if (dimension) return {
		target: "dimension",
		dimension,
		direction: orderBy.direction
	};
	issues.push({
		code: "field_not_allowed",
		path: ["orderBy", "field"],
		message: "orderBy must reference a requested measure, count, or a requested dimension"
	});
}
function toFiniteNumber(value) {
	return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
// src/storage/domains/observability/span-aggregate.ts
/**
* Storage contract for `aggregateSpans()`: grouped measures over individual current spans.
*
* Shares the `aggregateTraces()` envelope (window, intervals, `having`, `orderBy`, `limit`,
* response rows) and measures. Differs in scope: `where` is the direct span field policy of
* `querySpans()` (`SPAN_QUERY_FIELD_REGISTRY`), dimensions are span fields, and usage is
* attributed per span rather than per trace. Trace-level questions ("traces containing a failing
* tool call") remain `aggregateTraces()` with `spans.some`.
*/
const stringDimension = () => ({ valueKind: "string" });
/**
* Span-scope groupable dimensions for `aggregateSpans()`, in discovery order.
*
* The trace dimensions plus the span's own `name`/`spanType`, its `entityId`, the parent and root
* entity context, and `model`/`provider`. `model` and `provider` read only their dedicated columns,
* like their filters, so spans exported before the columns were filled group under `null`. Not
* groupable: `metadata.<key>` (the span field policy has no metadata) and identity fields
* (`traceId`, `spanId`, `parentSpanId`, `runId`, `requestId`).
*/
const SPAN_AGGREGATE_DIMENSION_REGISTRY = {
	name: stringDimension(),
	spanType: stringDimension(),
	entityType: stringDimension(),
	entityId: stringDimension(),
	entityName: stringDimension(),
	parentEntityType: stringDimension(),
	parentEntityName: stringDimension(),
	rootEntityType: stringDimension(),
	rootEntityName: stringDimension(),
	environment: stringDimension(),
	status: stringDimension(),
	outcome: stringDimension(),
	stopReason: stringDimension(),
	serviceName: stringDimension(),
	executionSource: stringDimension(),
	threadId: stringDimension(),
	resourceId: stringDimension(),
	userId: stringDimension(),
	sessionId: stringDimension(),
	organizationId: stringDimension(),
	experimentId: stringDimension(),
	model: stringDimension(),
	provider: stringDimension()
};
function isSpanAggregateDimension(path) {
	return Object.hasOwn(SPAN_AGGREGATE_DIMENSION_REGISTRY, path);
}
function isSpanAggregateCountDistinctField(path) {
	return path === "traceId" || isSpanAggregateDimension(path);
}
/** Span aggregates use the trace measure registry; `countDistinct` targets are span dimensions or `traceId`. */
function parseSpanAggregateMeasure(name) {
	if (isTraceAggregateCanonicalMeasure(name)) return {
		type: "canonical",
		measure: name
	};
	const field = getTraceAggregateCountDistinctField(name);
	if (field !== void 0 && isSpanAggregateCountDistinctField(field)) return {
		type: "countDistinct",
		field
	};
}
function getSpanAggregateDimensionDescriptors() {
	return Object.keys(SPAN_AGGREGATE_DIMENSION_REGISTRY).map((path) => ({
		path,
		valueKind: SPAN_AGGREGATE_DIMENSION_REGISTRY[path].valueKind
	}));
}
function getSpanAggregateMeasureDescriptors() {
	return Object.keys(TRACE_AGGREGATE_MEASURE_REGISTRY).map((name) => {
		const rule = TRACE_AGGREGATE_MEASURE_REGISTRY[name];
		return {
			name,
			kind: rule.kind,
			...rule.statistic ? { statistic: rule.statistic } : {},
			unit: rule.unit,
			approximate: rule.approximate
		};
	});
}
const hasDistinctValues = (values) => new Set(values).size === values.length;
const spanAggregateRequestObjectSchema = z.object({
	timeRange: traceAggregateTimeRangeSchema,
	where: traceQueryScalarPredicateSchema.optional(),
	groupBy: z.array(traceAggregateDimensionSchema).max(2).refine(hasDistinctValues, "Dimensions must be distinct").default([]),
	interval: traceAggregateIntervalSchema.optional(),
	measures: z.array(traceAggregateMeasureSchema).min(1).refine(hasDistinctValues, "Measures must be distinct"),
	having: traceQueryScalarPredicateSchema.optional(),
	orderBy: traceAggregateOrderBySchema,
	limit: z.number().int().min(1).max(TRACE_AGGREGATE_MAX_LIMIT).default(100)
}).strict();
/**
* A span aggregate request without its time range, for callers that store a query and supply the
* range at run time (dashboard widgets). Apply `findPredicateComplexityIssue` before parsing.
*/
const spanAggregateQueryObjectSchema = spanAggregateRequestObjectSchema.omit({ timeRange: true });
const spanAggregateRequestSchema = z.preprocess((input, context) => {
	const issuePath = findPredicateComplexityIssue(input, [["where"], ["having"]]);
	if (issuePath) {
		context.addIssue({
			code: "custom",
			path: issuePath,
			message: TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE
		});
		return z.NEVER;
	}
	return input;
}, spanAggregateRequestObjectSchema);
/** Same row shape as trace aggregates; `cost.coverage` is per usage-bearing span. */
const spanAggregateResponseSchema = traceAggregateResponseSchema;
function parseSpanAggregateRequest(input) {
	const parsed = spanAggregateRequestSchema.safeParse(input);
	if (!parsed.success) throw new TraceQueryValidationError(formatTraceQuerySchemaIssues(parsed.error));
	return parsed.data;
}
/**
* Converts a span aggregate request into the canonical plan consumed by observability storage
* adapters. Accepts raw input; schema and planner failures throw `TraceQueryValidationError`.
*
* @internal This is a trusted server/storage boundary, not a client-side query builder.
*/
function planSpanAggregate(input, options = {}) {
	const request = parseSpanAggregateRequest(input);
	const issues = [];
	const where = request.where ? planSpanQuerySelectionPredicate(request.where, issues, options.allowTokenSearch) : void 0;
	return {
		result: "spanAggregate",
		...planAggregateGroups(request, issues, {
			isDimension: isSpanAggregateDimension,
			parseMeasure: parseSpanAggregateMeasure
		}),
		where,
		scope: normalizeTraceQueryTenantScope(options.scope)
	};
}
// src/storage/domains/studio/saved-views/filter-node.ts
/**
* Filter-bar state of the observability list pages, in the same encoding as their URLs:
* flat tokens plus nested AND/OR groups (the JSON of the `filterGroup` URL param).
*/
const filterTokenSchema = z.object({
	fieldId: z.string().min(1),
	value: z.union([z.string(), z.array(z.string())]),
	/**
	* The filter bar's operator id (`<param>.op` in the URL); omitted means the field default. Any id is
	* accepted so a page or dashboard can add operators without a schema change; the UI drops a token
	* whose operator it doesn't know.
	*/
	operatorId: z.string().min(1).optional(),
	/** Set on tokens inside a group: a group may hold several tokens on the same field. */
	id: z.string().optional()
});
const groupedFilterTokenSchema = filterTokenSchema.extend({ id: z.string().min(1) });
const filterGroupSchema = z.object({
	id: z.string().min(1),
	logic: z.enum(["and", "or"]),
	get nodes() {
		return z.array(z.union([filterGroupSchema, groupedFilterTokenSchema]));
	}
});
const filterNodeSchema = z.union([filterGroupSchema, filterTokenSchema]);
// src/storage/domains/studio/saved-views/saved-view.ts
/**
* A saved view: a named copy of an observability list page's URL state.
*
* `savedViewStateSchema` validates the whole state (used by the page that applies it).
* `savedViewStateEnvelopeSchema` checks only what storage needs (version, page, size), so a page
* can add state without a server deploy.
*/
const SAVED_VIEW_SCHEMA_VERSION = 1;
const SAVED_VIEW_PAGES = [
	"traces",
	"spans",
	"threads",
	"logs"
];
/** Max size of a saved view's state, as UTF-8 JSON. */
const SAVED_VIEW_STATE_MAX_BYTES = 16384;
const savedViewPageSchema = z.enum(SAVED_VIEW_PAGES);
const timestamp = z.string().datetime({ offset: true });
const utf8Bytes = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
const withinSizeLimit = (value) => utf8Bytes(value) <= SAVED_VIEW_STATE_MAX_BYTES;
const sizeLimitMessage = `Saved view state must be at most ${SAVED_VIEW_STATE_MAX_BYTES} bytes as JSON`;
const savedViewDateRangeSchema = z.union([z.object({ preset: z.string().min(1) }).strict(), z.object({
	from: timestamp,
	/** Omitted: the range is open-ended and runs to "now". */
	to: timestamp.optional()
}).strict().refine(({ from, to }) => to === void 0 || Date.parse(from) <= Date.parse(to), {
	message: "`from` must not be after `to`",
	path: ["to"]
})]);
const savedViewSortSchema = z.object({
	field: z.string().min(1),
	direction: z.enum(["asc", "desc"])
});
const savedViewColumnSchema = z.object({
	id: z.string().min(1),
	visible: z.boolean()
});
const savedViewStateSchema = z.object({
	schemaVersion: z.literal(1),
	page: savedViewPageSchema,
	filters: z.array(filterNodeSchema),
	dateRange: savedViewDateRangeSchema.optional(),
	sort: savedViewSortSchema.optional(),
	/** In display order. */
	columns: z.array(savedViewColumnSchema).refine((columns) => new Set(columns.map((column) => column.id)).size === columns.length, { message: "Column ids must be unique" }).optional(),
	/** Per-page extras, e.g. the traces `listMode`. */
	options: z.record(z.string(), z.unknown()).optional()
}).refine(withinSizeLimit, { message: sizeLimitMessage });
/** What a store checks before saving: a known version and page, within the size limit. */
const savedViewStateEnvelopeSchema = z.looseObject({
	schemaVersion: z.literal(1),
	page: savedViewPageSchema
}).refine(withinSizeLimit, { message: sizeLimitMessage });
// src/storage/domains/studio/dashboards/dashboard.ts
/**
* Stored definition of a custom dashboard: rows of widgets on a 12-column grid, each widget
* describing its own queries and presentation.
*
* Queries reuse the observability request schemas minus what the page supplies at run time: the
* time range always, and `interval` for time series (the renderer derives it from the range).
* The page's filters are intersected with each query's own: `where` is ANDed, and a metrics or scores
* filter field set by both must agree (arrays intersect). A contradiction yields no data.
*
* Core owns the common widget shape and the query sources. A widget's `kind` is any non-empty string
* and `options` stay opaque here: each kind validates its own options where it renders, so a new kind
* needs no core change or storage deploy. A new query source is one more entry in the `source` union.
*
* Two schemas share the same limits:
* - `dashboardDefinitionSchema` validates everything; the renderer parses with it.
* - `dashboardDefinitionEnvelopeSchema` validates only what storage needs (version, limits, unique
*   widget ids, every widget has `kind` and `views`), so new widget kinds or query fields don't
*   require the storing service to upgrade.
*/
/** Every version storage accepts; `migrateDashboardDefinition` upgrades each to the current one. */
const DASHBOARD_SCHEMA_VERSIONS = [1];
const DASHBOARD_SCHEMA_VERSION = 1;
const DASHBOARD_MAX_WIDGETS = 20;
const DASHBOARD_MAX_QUERIES_PER_VIEW = 8;
/** Limit on the UTF-8 size of the JSON-serialized definition. */
const DASHBOARD_MAX_BYTES = 65536;
const DASHBOARD_WIDGET_SPANS = [
	1,
	2,
	3,
	4,
	6,
	12
];
/** Kinds the built-in renderer ships. Not enforced: `kind` accepts any non-empty string. */
const DASHBOARD_WIDGET_KINDS = [
	"kpis",
	"table",
	"timeseries",
	"scores"
];
const DASHBOARD_SCOPES = ["org", "project"];
const DASHBOARD_DRILLDOWN_PAGES = [
	"traces",
	"spans",
	"logs",
	"threads"
];
/** Compares each value with the window of equal length right before the page's range. */
const compareSchema = z.literal("previousWindow").optional();
/** Lets options refer to a query by name instead of position. Unique within a view. */
const queryIdSchema = z.string().regex(/^[A-Za-z][\w-]*$/, "Query ids start with a letter and contain only letters, digits, _ or -").optional();
const traceAggregateDashboardQuerySchema = traceAggregateQueryObjectSchema.extend({
	source: z.literal("traceAggregate"),
	id: queryIdSchema,
	compare: compareSchema
});
const spanAggregateDashboardQuerySchema = spanAggregateQueryObjectSchema.extend({
	source: z.literal("spanAggregate"),
	id: queryIdSchema,
	compare: compareSchema
});
const metricsQueryFilters = metricsFilterSchema.omit({ timestamp: true }).strict().optional();
const scoresQueryFilters = scoresFilterSchema.omit({ timestamp: true }).strict().optional();
const metricsSource = {
	source: z.literal("metrics"),
	id: queryIdSchema,
	compare: compareSchema
};
const scoresSource = {
	source: z.literal("scores"),
	id: queryIdSchema,
	compare: compareSchema
};
const { comparePeriod: _metricComparePeriod, ...metricAggregateShape } = getMetricAggregateArgsSchema.shape;
const { comparePeriod: _scoreComparePeriod, ...scoreAggregateShape } = getScoreAggregateArgsSchema.shape;
const optionalScorerId = { scorerId: getScoreAggregateArgsSchema.shape.scorerId.optional() };
const metricsDashboardQuerySchema = z.discriminatedUnion("request", [
	z.object({
		...metricsSource,
		request: z.literal("aggregate"),
		...metricAggregateShape,
		filters: metricsQueryFilters
	}).strict().refine(requireDistinctColumnRefinement.check, requireDistinctColumnRefinement.options),
	z.object({
		...metricsSource,
		request: z.literal("breakdown"),
		...getMetricBreakdownArgsSchema.shape,
		filters: metricsQueryFilters
	}).strict().refine(requireDistinctColumnRefinement.check, requireDistinctColumnRefinement.options),
	z.object({
		...metricsSource,
		request: z.literal("timeSeries"),
		...getMetricTimeSeriesArgsSchema.shape,
		interval: getMetricTimeSeriesArgsSchema.shape.interval.optional(),
		filters: metricsQueryFilters
	}).strict().refine(requireDistinctColumnRefinement.check, requireDistinctColumnRefinement.options),
	z.object({
		...metricsSource,
		request: z.literal("percentiles"),
		...getMetricPercentilesArgsSchema.shape,
		interval: getMetricPercentilesArgsSchema.shape.interval.optional(),
		filters: metricsQueryFilters
	}).strict()
]);
const scoresDashboardQuerySchema = z.discriminatedUnion("request", [
	z.object({
		...scoresSource,
		request: z.literal("aggregate"),
		...scoreAggregateShape,
		...optionalScorerId,
		filters: scoresQueryFilters
	}).strict(),
	z.object({
		...scoresSource,
		request: z.literal("breakdown"),
		...getScoreBreakdownArgsSchema.shape,
		...optionalScorerId,
		filters: scoresQueryFilters
	}).strict(),
	z.object({
		...scoresSource,
		request: z.literal("timeSeries"),
		...getScoreTimeSeriesArgsSchema.shape,
		interval: getScoreTimeSeriesArgsSchema.shape.interval.optional(),
		...optionalScorerId,
		filters: scoresQueryFilters
	}).strict(),
	z.object({
		...scoresSource,
		request: z.literal("percentiles"),
		...getScorePercentilesArgsSchema.shape,
		interval: getScorePercentilesArgsSchema.shape.interval.optional(),
		...optionalScorerId,
		filters: scoresQueryFilters
	}).strict()
]);
const dashboardQueryUnionSchema = z.discriminatedUnion("source", [
	traceAggregateDashboardQuerySchema,
	spanAggregateDashboardQuerySchema,
	metricsDashboardQuerySchema,
	scoresDashboardQuerySchema
]);
const dashboardQuerySchema = z.preprocess((input, context) => {
	const issuePath = findPredicateComplexityIssue(input, [["where"], ["having"]]);
	if (issuePath) {
		context.addIssue({
			code: "custom",
			path: issuePath,
			message: TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE
		});
		return z.NEVER;
	}
	return input;
}, dashboardQueryUnionSchema);
const scopeSchema = z.enum(DASHBOARD_SCOPES).optional();
/** Deepest nesting of filter groups. Checked before parsing so a deep tree fails instead of overflowing the stack. */
const DASHBOARD_MAX_FILTER_DEPTH = 12;
const findFilterTooDeep = (filters) => {
	const stack = [{
		value: filters,
		path: [],
		depth: 0
	}];
	for (let next = stack.pop(); next; next = stack.pop()) {
		const { value, path, depth } = next;
		if (!Array.isArray(value)) continue;
		if (depth > 12) return path;
		value.forEach((node, index) => {
			if (node && typeof node === "object" && "nodes" in node) stack.push({
				value: node.nodes,
				path: [
					...path,
					index,
					"nodes"
				],
				depth: depth + 1
			});
		});
	}
};
const filtersSchema = z.preprocess((input, context) => {
	const path = findFilterTooDeep(input);
	if (path) {
		context.addIssue({
			code: "custom",
			path,
			message: `Filter groups nest at most 12 levels deep`
		});
		return z.NEVER;
	}
	return input;
}, z.array(filterNodeSchema)).optional();
const queriesArraySchema = (query) => z.array(query).min(1).max(8);
/** The serialized size is measured on the raw input, before defaults are applied. */
const withSizeLimit = (schema) => z.preprocess((input, context) => {
	const bytes = new TextEncoder().encode(JSON.stringify(input) ?? "").length;
	if (bytes > 65536) {
		context.addIssue({
			code: "custom",
			path: [],
			message: `Dashboard definition is ${bytes} bytes; the limit is ${DASHBOARD_MAX_BYTES}`
		});
		return z.NEVER;
	}
	return input;
}, schema);
const refineUniqueIds = (items, field, label, context) => {
	const seen = /* @__PURE__ */ new Set();
	items.forEach((item, index) => {
		if (item.id === void 0) return;
		if (seen.has(item.id)) context.addIssue({
			code: "custom",
			path: [
				field,
				index,
				"id"
			],
			message: `Duplicate ${label} id '${item.id}'`
		});
		seen.add(item.id);
	});
};
const refineWidgets = (definition, context) => {
	const seen = /* @__PURE__ */ new Set();
	let count = 0;
	definition.rows.forEach((row, rowIndex) => {
		row.widgets.forEach((widget, widgetIndex) => {
			count += 1;
			if (seen.has(widget.id)) context.addIssue({
				code: "custom",
				path: [
					"rows",
					rowIndex,
					"widgets",
					widgetIndex,
					"id"
				],
				message: `Duplicate widget id '${widget.id}'`
			});
			seen.add(widget.id);
		});
	});
	if (count > 20) context.addIssue({
		code: "custom",
		path: ["rows"],
		message: `A dashboard can have at most 20 widgets; found ${count}`
	});
};
const dashboardColumnSchema = z.object({
	/** A measure or dimension key from the view's queries. */
	id: z.string().min(1),
	label: z.string().optional(),
	/** Shown only at this scope. */
	scope: scopeSchema,
	options: z.record(z.string(), z.unknown()).optional()
}).strict();
const dashboardDrilldownTargetSchema = z.object({
	page: z.enum(DASHBOARD_DRILLDOWN_PAGES),
	/** Added to the page's range (and, for `click`, the clicked row's dimensions) when the drilldown opens. */
	filters: filtersSchema
}).strict();
const dashboardDrilldownSchema = z.object({
	/** Opened from the widget's action button. */
	action: dashboardDrilldownTargetSchema.optional(),
	/** Opened by clicking a row, bar or point. */
	click: dashboardDrilldownTargetSchema.optional()
}).strict();
const dashboardWidgetViewSchema = z.object({
	label: z.string().optional(),
	/** Overrides the widget's description. */
	description: z.string().optional(),
	queries: queriesArraySchema(dashboardQuerySchema),
	/** Table widgets only. */
	columns: z.array(dashboardColumnSchema).optional(),
	/** Validated by the widget's kind, not here. */
	options: z.record(z.string(), z.unknown()).optional(),
	/** Overrides the widget's drilldown. */
	drilldown: dashboardDrilldownSchema.optional(),
	/** Shown only at this scope. */
	scope: scopeSchema
}).strict().superRefine((view, context) => {
	refineUniqueIds(view.queries, "queries", "query", context);
	if (view.columns) refineUniqueIds(view.columns, "columns", "column", context);
});
const dashboardWidgetSchema = z.object({
	id: z.string().min(1),
	span: z.literal(DASHBOARD_WIDGET_SPANS),
	/** See `DASHBOARD_WIDGET_KINDS` for the built-in kinds. */
	kind: z.string().min(1),
	title: z.string().optional(),
	description: z.string().optional(),
	/** Two or more views render as tabs. */
	views: z.array(dashboardWidgetViewSchema).min(1),
	drilldown: dashboardDrilldownSchema.optional(),
	/** Shown only at this scope. */
	scope: scopeSchema
}).strict();
const dashboardRowSchema = z.object({ widgets: z.array(dashboardWidgetSchema) }).strict();
const dashboardDefaultsSchema = z.object({
	datePreset: z.string().min(1).optional(),
	filters: filtersSchema
}).strict();
const dashboardDefinitionSchema = withSizeLimit(z.object({
	/**
	* Adding an optional field doesn't change the version. A breaking change bumps it, adds the old
	* version to `DASHBOARD_SCHEMA_VERSIONS`, and adds an upgrade step to `migrateDashboardDefinition`.
	*/
	schemaVersion: z.literal(1),
	/** Used when the page URL doesn't set the range or filters. */
	defaults: dashboardDefaultsSchema.optional(),
	rows: z.array(dashboardRowSchema)
}).strict().superRefine(refineWidgets));
const dashboardDefinitionEnvelopeSchema = withSizeLimit(z.looseObject({
	schemaVersion: z.literal(DASHBOARD_SCHEMA_VERSIONS),
	rows: z.array(z.looseObject({ widgets: z.array(z.looseObject({
		id: z.string().min(1),
		kind: z.string().min(1),
		views: z.array(z.looseObject({ queries: queriesArraySchema(z.unknown()) })).min(1)
	})) }))
}).superRefine(refineWidgets));
/**
* Upgrades a stored definition of any known version to `DASHBOARD_SCHEMA_VERSION`. Parse the result
* with `dashboardDefinitionSchema`. Version 1 is current, so this returns its input unchanged today.
*/
function migrateDashboardDefinition(definition) {
	switch (definition.schemaVersion) {
		case 1: return definition;
	}
}
export { TRACE_AGGREGATE_MEASURE_REGISTRY as $, traceQueryTimeRangeSchema as $n, TRACE_QUERY_TOKEN_SEARCH_MAX_LENGTH as $t, filterGroupSchema as A, planTraceQuerySelectionPredicate as An, traceAggregateTimeRangeSchema as At, planSpanAggregate as B, traceQueryCanonicalFieldDescriptorSchema as Bn, TRACE_QUERY_MAX_LITERAL_UNITS as Bt, SAVED_VIEW_SCHEMA_VERSION as C, parseQueryThreadsInput as Cn, traceAggregateMeasureSchema as Ct, savedViewSortSchema as D, planThreadPredicate as Dn, traceAggregateResponseSchema as Dt, savedViewDateRangeSchema as E, planSpanQuerySelectionPredicate as En, traceAggregateRequestSchema as Et, getSpanAggregateMeasureDescriptors as F, threadIdentitySchema as Fn, TRACE_QUERY_DISCOVERY_DEFAULT_LIMIT as Ft, TRACE_AGGREGATE_MAX_BUCKETS as G, traceQueryPaginatedTraceResponseSchema as Gn, TRACE_QUERY_MAX_STRING_BYTES as Gt, spanAggregateRequestSchema as H, traceQueryGroupResponseSchema as Hn, TRACE_QUERY_MAX_PATH_BYTES as Ht, isSpanAggregateCountDistinctField as I, threadPredicateSchema as In, TRACE_QUERY_DISCOVERY_MAX_LIMIT as It, planAggregateGroups as J, traceQueryRequestSchema as Jn, TRACE_QUERY_ORDER_FIELDS as Jt, TRACE_AGGREGATE_MAX_ROWS as K, traceQueryPredicateSchema as Kn, TRACE_QUERY_MAX_TIMEOUT_MS as Kt, isSpanAggregateDimension as L, traceAggregateDimensionDescriptorSchema as Ln, TRACE_QUERY_DISCOVERY_MAX_SEARCH_LENGTH as Lt, filterTokenSchema as M, queryThreadsInputSchema as Mn, THREAD_QUERY_FIELD_REGISTRY as Mt, SPAN_AGGREGATE_DIMENSION_REGISTRY as N, queryThreadsResultSchema as Nn, TRACE_QUERY_ARRAY_OPERATORS as Nt, savedViewStateEnvelopeSchema as O, planThreadQuerySelectionPredicate as On, traceAggregateRowCostSchema as Ot, getSpanAggregateDimensionDescriptors as P, resolveTraceQueryTimeoutMs as Pn, TRACE_QUERY_DEFAULT_TIMEOUT_MS as Pt, TRACE_AGGREGATE_IDENTITY_FIELDS as Q, traceQuerySortValueSchema as Qn, TRACE_QUERY_TOKEN_FIELDS as Qt, parseSpanAggregateMeasure as R, traceAggregateDiscoverySchema as Rn, TRACE_QUERY_FIELD_REGISTRY as Rt, SAVED_VIEW_PAGES as S, parseGetTraceQueryValuesArgs as Sn, traceAggregateIntervalSchema as St, savedViewColumnSchema as T, planPredicate as Tn, traceAggregateQueryObjectSchema as Tt, spanAggregateResponseSchema as U, traceQueryObservedFieldDescriptorSchema as Un, TRACE_QUERY_MAX_RELATED_CLAUSES as Ut, spanAggregateQueryObjectSchema as V, traceQueryDeltaTraceResponseSchema as Vn, TRACE_QUERY_MAX_NODES as Vt, TRACE_AGGREGATE_INTERVAL_MS as W, traceQueryOperatorSchema as Wn, TRACE_QUERY_MAX_SET_VALUES as Wt, TRACE_AGGREGATE_COST_METRIC_NAMES as X, traceQueryRootSourceSchema as Xn, TRACE_QUERY_PRESENCE_OPERATORS as Xt, planTraceAggregate as Y, traceQueryResponseSchema as Yn, TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE as Yt, TRACE_AGGREGATE_DIMENSION_REGISTRY as Z, traceQueryScalarPredicateSchema as Zn, TRACE_QUERY_STRING_OPERATORS as Zt, dashboardQuerySchema as _, isTraceQueryValueSuggestionsPath as _n, TRACE_AGGREGATE_MIXED_COST_UNIT as _t, DASHBOARD_MAX_WIDGETS as a, compareTraceQueryStrings as an, isTraceAggregateCanonicalDimension as at, dashboardWidgetViewSchema as b, normalizeTraceQueryText as bn, parseTraceAggregateRequest as bt, DASHBOARD_SCOPES as c, formatTraceQuerySchemaIssues as cn, isTraceAggregateDimension as ct, dashboardColumnSchema as d, getTraceQueryFieldsResponseSchema as dn, TRACE_AGGREGATE_DEFAULT_LIMIT as dt, TraceQueryCursorError as en, traceQueryTraceResponseSchema as er, TRACE_AGGREGATE_METADATA_DIMENSION_RULE as et, dashboardDefaultsSchema as f, getTraceQueryValuesArgsSchema as fn, TRACE_AGGREGATE_FIXED_MEASURES as ft, dashboardDrilldownTargetSchema as g, isTraceQuerySortValueFor as gn, TRACE_AGGREGATE_MAX_TIME_RANGE_DAYS as gt, dashboardDrilldownSchema as h, isTraceQueryMetadataPath as hn, TRACE_AGGREGATE_MAX_LIMIT as ht, DASHBOARD_MAX_QUERIES_PER_VIEW as i, TraceQueryValidationError as in, getTraceAggregateMeasureDescriptors as it, filterNodeSchema as j, planTraceQueryValues as jn, SPAN_QUERY_FIELD_REGISTRY as jt, savedViewStateSchema as k, planTraceQueryObservedFields as kn, traceAggregateRowSchema as kt, DASHBOARD_WIDGET_KINDS as l, getTraceQueryCanonicalFieldDescriptors as ln, parseTraceAggregateMeasure as lt, dashboardDefinitionSchema as m, hasTraceQueryTokenPredicate as mn, TRACE_AGGREGATE_MAX_DIMENSIONS as mt, DASHBOARD_MAX_BYTES as n, TraceQueryResourceLimitError as nn, traceQueryValueKindSchema as nr, getTraceAggregateDimensionDescriptors as nt, DASHBOARD_SCHEMA_VERSION as o, createTraceQueryObservedFieldDescriptor as on, isTraceAggregateCanonicalMeasure as ot, dashboardDefinitionEnvelopeSchema as p, getTraceQueryValuesResponseSchema as pn, TRACE_AGGREGATE_INTERVALS as pt, countTraceAggregateBuckets as q, traceQueryPredicateScopeSchema as qn, TRACE_QUERY_ORDERED_OPERATORS as qt, DASHBOARD_MAX_FILTER_DEPTH as r, TraceQueryUnsupportedError as rn, traceSelectionSchema as rr, getTraceAggregateDimensionRule as rt, DASHBOARD_SCHEMA_VERSIONS as s, findPredicateComplexityIssue as sn, isTraceAggregateCountDistinctField as st, DASHBOARD_DRILLDOWN_PAGES as t, TraceQueryExecutionError as tn, traceQueryTraceSchema as tr, TRACE_AGGREGATE_USAGE_METRIC_NAMES as tt, DASHBOARD_WIDGET_SPANS as u, getTraceQueryFieldsArgsSchema as un, TRACE_AGGREGATE_COUNT_DISTINCT_PREFIX as ut, dashboardRowSchema as v, normalizeTraceQueryPath as vn, getTraceAggregateCountDistinctField as vt, SAVED_VIEW_STATE_MAX_BYTES as w, parseTraceQueryRequest as wn, traceAggregateOrderBySchema as wt, migrateDashboardDefinition as x, parseGetTraceQueryFieldsArgs as xn, traceAggregateDimensionSchema as xt, dashboardWidgetSchema as y, normalizeTraceQueryTenantScope as yn, isTraceAggregateCountDistinctMeasure as yt, parseSpanAggregateRequest as z, traceAggregateMeasureDescriptorSchema as zn, TRACE_QUERY_MAX_DEPTH as zt };

//# sourceMappingURL=dashboard-BH7sDVbr.js.map