UNPKG

@mastra/core

Version:

Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

1,369 lines (1,364 loc) • 247 kB
'use strict'; var chunkN6ERFPTM_cjs = require('./chunk-N6ERFPTM.cjs'); var chunkNVYQFL3H_cjs = require('./chunk-NVYQFL3H.cjs'); var chunkYOXBFIMG_cjs = require('./chunk-YOXBFIMG.cjs'); var chunkMM77B7S3_cjs = require('./chunk-MM77B7S3.cjs'); var chunkJZ6HQF5G_cjs = require('./chunk-JZ6HQF5G.cjs'); var chunkFYN37C2K_cjs = require('./chunk-FYN37C2K.cjs'); var chunkRKHARY3D_cjs = require('./chunk-RKHARY3D.cjs'); var chunk2RQFCM6V_cjs = require('./chunk-2RQFCM6V.cjs'); var chunk3VBF5IP7_cjs = require('./chunk-3VBF5IP7.cjs'); var chunkXD7CRAEV_cjs = require('./chunk-XD7CRAEV.cjs'); var chunk6E6FPM76_cjs = require('./chunk-6E6FPM76.cjs'); var chunkG3JYQ2UI_cjs = require('./chunk-G3JYQ2UI.cjs'); var chunkFCQNDFEW_cjs = require('./chunk-FCQNDFEW.cjs'); var chunkRQ4MB5TM_cjs = require('./chunk-RQ4MB5TM.cjs'); var chunk4U7ZLI36_cjs = require('./chunk-4U7ZLI36.cjs'); var jsonToZod = require('@mastra/schema-compat/json-to-zod'); var v4 = require('zod/v4'); var crypto$1 = require('crypto'); var path = require('path'); var fs = require('fs'); // src/storage/domains/observability/base.ts var ObservabilityStorage = class _ObservabilityStorage extends chunk3VBF5IP7_cjs.StorageDomain { constructor() { super({ component: "STORAGE", name: "OBSERVABILITY" }); } async dangerouslyClearAll() { } /** * Provides hints for tracing strategy selection by the MastraStorageExporter. * Storage adapters can override this to specify their preferred and supported strategies. */ get observabilityStrategy() { return { preferred: "batch-with-updates", // Default for most SQL stores supported: ["realtime", "batch-with-updates", "insert-only"] }; } /** * Provides hints for tracing strategy selection by the MastraStorageExporter. * Storage adapters can override this to specify their preferred and supported strategies. * @deprecated Use {@link observabilityStrategy} instead. * @see {@link observabilityStrategy} for the replacement property. */ get tracingStrategy() { return this.observabilityStrategy; } /** * Reports the tracing strategy currently in effect for this attached observability store. * * Single-strategy stores can rely on the default implementation. Multi-strategy stores * should override this getter only when they can determine the actual configured mode * from storage-owned configuration, not exporter state. */ get runtimeTracingStrategy() { const supportedStrategies = this.observabilityStrategy.supported; return supportedStrategies.length === 1 ? supportedStrategies[0] : void 0; } /** * Optional feature list for observability storage APIs. * Stores that implement delta polling should override this and opt in explicitly. * Older stores and older package versions will simply omit it, which keeps page mode working. */ getFeatures() { return void 0; } /** * Creates a single Span record in the storage provider. */ async createSpan(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_CREATE_SPAN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support creating spans" }); } /** * Updates a single Span with partial data. Primarily used for realtime trace creation. * * @deprecated This method only works with stores that support span updates, * It will be removed in the future. Instead try to add all data to a span before * ending it. */ async updateSpan(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_UPDATE_SPAN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support updating spans" }); } /** * Retrieves a single span. */ async getSpan(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SPAN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support getting spans" }); } /** * Retrieves a single root span. */ async getRootSpan(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_ROOT_SPAN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support getting root spans" }); } /** * Retrieves a single trace with all its associated spans. */ async getTrace(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_TRACE_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support getting traces" }); } /** * Retrieves the structural skeleton of a trace -- parent/child links, span * type, timing, and status -- with heavy fields (input, output, attributes, * metadata, tags, links) excluded. Intended for waterfall/timeline rendering * where the full payload would be wasteful. * * Default implementation forwards to {@link getTraceLight} (the legacy * override surface). Backends should override either method -- the response * shape is identical, and the unimplemented one delegates to the * implemented one. The cycle guard is what makes that safe. */ async getStructure(args) { if (this.getTraceLight === _ObservabilityStorage.prototype.getTraceLight) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_STRUCTURE_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support getting trace structure" }); } return this.getTraceLight(args); } /** * @deprecated Use {@link getStructure} instead. Default implementation * forwards to {@link getStructure} so backends that only override the * canonical name still work for legacy callers. */ async getTraceLight(args) { if (this.getStructure === _ObservabilityStorage.prototype.getStructure) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_TRACE_LIGHT_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support getting lightweight traces" }); } return this.getStructure(args); } /** * Retrieves the subtree of spans rooted at a given span, optionally bounded * to `depth` levels of descendants. * * Default implementation prefers a two-step path: fetch the lightweight * structure to determine which spans belong to the branch, then batch-fetch * only those with full data. This avoids pulling the entire trace when the * branch is a small slice of a large trace. Backends that don't yet * implement {@link getStructure} or {@link getSpans} fall back to fetching * the full trace and walking it in memory. */ async getBranch(args) { const parsed = chunkXD7CRAEV_cjs.getBranchArgsSchema.parse(args); try { const skeleton = await this.getStructure({ traceId: parsed.traceId }); if (!skeleton) return null; const branchSpanIds = chunkXD7CRAEV_cjs.extractBranchSpans(skeleton.spans, parsed.spanId, parsed.depth).map((s) => s.spanId); if (branchSpanIds.length === 0) return null; const { spans: spans2 } = await this.getSpans({ traceId: parsed.traceId, spanIds: branchSpanIds }); if (spans2.length === 0) return null; spans2.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime()); return { traceId: parsed.traceId, spans: spans2 }; } catch (error) { const isFallbackTrigger = error instanceof chunk4U7ZLI36_cjs.MastraError && (error.id === "OBSERVABILITY_STORAGE_GET_STRUCTURE_NOT_IMPLEMENTED" || error.id === "OBSERVABILITY_STORAGE_GET_TRACE_LIGHT_NOT_IMPLEMENTED" || error.id === "OBSERVABILITY_STORAGE_GET_SPANS_NOT_IMPLEMENTED"); if (!isFallbackTrigger) throw error; } const trace = await this.getTrace({ traceId: parsed.traceId }); if (!trace) return null; const spans = chunkXD7CRAEV_cjs.extractBranchSpans(trace.spans, parsed.spanId, parsed.depth); if (spans.length === 0) return null; return { traceId: parsed.traceId, spans }; } /** * Batch-fetches spans by spanId within a single trace. Used by the * optimized {@link getBranch} path to fetch only the spans that belong to * the requested branch (after walking the lightweight structure to identify * them) instead of pulling the entire trace. */ async getSpans(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SPANS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch-fetching spans" }); } /** * Retrieves a list of traces with optional filtering. */ async listTraces(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_LIST_TRACES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support listing traces" }); } /** * Retrieves a lightweight list of traces with optional filtering. */ async listTracesLight(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_LIST_TRACES_LIGHT_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support listing lightweight traces" }); } /** * Lists trace branches across all traces. Unlike {@link listTraces} (which * returns one row per root-rooted trace), each row here is a single branch * anchor span, including ones nested under a different root entity -- useful * for "show me every run of agent X" regardless of caller. Pairs with * {@link getBranch} to expand a single branch into its subtree. */ async listBranches(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_LIST_BRANCHES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support listing trace branches" }); } /** * Creates multiple Spans in a single batch. */ async batchCreateSpans(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_BATCH_CREATE_SPAN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch creating spans" }); } /** * Updates multiple Spans in a single batch. */ async batchUpdateSpans(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_BATCH_UPDATE_SPANS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch updating spans" }); } /** * Deletes multiple traces and all their associated spans in a single batch operation. */ async batchDeleteTraces(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_BATCH_DELETE_TRACES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch deleting traces" }); } // ============================================================================ // Logs // ============================================================================ /** * Creates multiple log records in a single batch. */ async batchCreateLogs(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_BATCH_CREATE_LOGS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch creating logs" }); } /** * Retrieves a list of logs with optional filtering. */ async listLogs(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_LIST_LOGS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support listing logs" }); } // ============================================================================ // Metrics // ============================================================================ /** * Creates multiple metric observations in a single batch. */ async batchCreateMetrics(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_BATCH_CREATE_METRICS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch creating metrics" }); } async listMetrics(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_LIST_METRICS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support listing metrics" }); } async getMetricAggregate(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_METRIC_AGGREGATE_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support metric aggregation" }); } async getMetricBreakdown(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_METRIC_BREAKDOWN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support metric breakdown" }); } async getMetricTimeSeries(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_METRIC_TIME_SERIES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support metric time series" }); } async getMetricPercentiles(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_METRIC_PERCENTILES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support metric percentiles" }); } // ============================================================================ // Discovery / Metadata Methods // ============================================================================ async getMetricNames(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_METRIC_NAMES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support metric name discovery" }); } async getMetricLabelKeys(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_METRIC_LABEL_KEYS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support metric label key discovery" }); } async getMetricLabelValues(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_LABEL_VALUES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support label value discovery" }); } async getEntityTypes(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_ENTITY_TYPES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support entity type discovery" }); } async getEntityNames(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_ENTITY_NAMES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support entity name discovery" }); } async getServiceNames(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SERVICE_NAMES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support service name discovery" }); } async getEnvironments(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_ENVIRONMENTS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support environment discovery" }); } async getTags(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_TAGS_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support tag discovery" }); } // ============================================================================ // Scores // ============================================================================ /** * Creates a single score record. */ async createScore(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_CREATE_SCORE_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support creating scores" }); } /** * Creates multiple score observations in a single batch. */ async batchCreateScores(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_BATCH_CREATE_SCORES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch creating scores" }); } /** * Retrieves a list of scores with optional filtering. */ async listScores(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_LIST_SCORES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support listing scores" }); } /** * Retrieves a single score by its score ID. */ async getScoreById(_scoreId) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SCORE_BY_ID_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support getting scores by ID" }); } async getScoreAggregate(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SCORE_AGGREGATE_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support score aggregation" }); } async getScoreBreakdown(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SCORE_BREAKDOWN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support score breakdown" }); } async getScoreTimeSeries(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SCORE_TIME_SERIES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support score time series" }); } async getScorePercentiles(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_SCORE_PERCENTILES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support score percentiles" }); } // ============================================================================ // Feedback // ============================================================================ /** * Creates a single feedback record. */ async createFeedback(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_CREATE_FEEDBACK_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support creating feedback" }); } /** * Creates multiple feedback observations in a single batch. */ async batchCreateFeedback(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_BATCH_CREATE_FEEDBACK_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support batch creating feedback" }); } /** * Retrieves a list of feedback with optional filtering. */ async listFeedback(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_LIST_FEEDBACK_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support listing feedback" }); } async getFeedbackAggregate(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_FEEDBACK_AGGREGATE_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support feedback aggregation" }); } async getFeedbackBreakdown(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_FEEDBACK_BREAKDOWN_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support feedback breakdown" }); } async getFeedbackTimeSeries(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_FEEDBACK_TIME_SERIES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support feedback time series" }); } async getFeedbackPercentiles(_args) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_STORAGE_GET_FEEDBACK_PERCENTILES_NOT_IMPLEMENTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support feedback percentiles" }); } }; // src/storage/utils.ts function safelyParseJSON(input) { if (input && typeof input === "object") return input; if (input == null) return {}; if (typeof input === "string") { try { return JSON.parse(input); } catch { return input; } } return {}; } function transformRow(row, tableName, options = {}) { const { preferredTimestampFields = {}, convertTimestamps = false, nullValuePattern, fieldMappings = {} } = options; const tableSchema = chunkXD7CRAEV_cjs.TABLE_SCHEMAS[tableName]; const result = {}; for (const [key, columnSchema] of Object.entries(tableSchema)) { const sourceKey = fieldMappings[key] ?? key; let value = row[sourceKey]; if (preferredTimestampFields[key]) { value = row[preferredTimestampFields[key]] ?? value; } if (value === void 0 || value === null) { continue; } if (nullValuePattern && value === nullValuePattern) { continue; } if (columnSchema.type === "jsonb") { if (typeof value === "string") { result[key] = safelyParseJSON(value); } else if (typeof value === "object") { result[key] = value; } else { result[key] = value; } } else if (columnSchema.type === "timestamp" && convertTimestamps && typeof value === "string") { result[key] = new Date(value); } else { result[key] = value; } } return result; } function transformScoreRow(row, options = {}) { return transformRow(row, chunkXD7CRAEV_cjs.TABLE_SCORERS, options); } function toUpperSnakeCase(str) { return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, ""); } function createStoreErrorId(type, store, operation, status) { const normalizedStore = toUpperSnakeCase(store); const normalizedOperation = toUpperSnakeCase(operation); const normalizedStatus = toUpperSnakeCase(status); const typePrefix = type === "storage" ? "STORAGE" : "VECTOR"; return `MASTRA_${typePrefix}_${normalizedStore}_${normalizedOperation}_${normalizedStatus}`; } function createStorageErrorId(store, operation, status) { return createStoreErrorId("storage", store, operation, status); } function createVectorErrorId(store, operation, status) { return createStoreErrorId("vector", store, operation, status); } function getSqlType(type) { switch (type) { case "text": return "TEXT"; case "timestamp": return "TIMESTAMP"; case "float": return "FLOAT"; case "integer": return "INTEGER"; case "bigint": return "BIGINT"; case "jsonb": return "JSONB"; case "boolean": return "BOOLEAN"; default: return "TEXT"; } } function getDefaultValue(type) { switch (type) { case "text": case "uuid": return "DEFAULT ''"; case "timestamp": return "DEFAULT '1970-01-01 00:00:00'"; case "integer": case "bigint": case "float": return "DEFAULT 0"; case "jsonb": return "DEFAULT '{}'"; case "boolean": return "DEFAULT FALSE"; default: return "DEFAULT ''"; } } function ensureDate(date) { if (!date) return void 0; return date instanceof Date ? date : new Date(date); } function serializeDate(date) { if (!date) return void 0; const dateObj = ensureDate(date); return dateObj?.toISOString(); } function filterByDateRange(items, getCreatedAt, dateRange) { if (!dateRange) return items; let result = items; if (dateRange.start) { const startTime = ensureDate(dateRange.start).getTime(); result = result.filter((item) => { const itemTime = getCreatedAt(item).getTime(); return dateRange.startExclusive ? itemTime > startTime : itemTime >= startTime; }); } if (dateRange.end) { const endTime = ensureDate(dateRange.end).getTime(); result = result.filter((item) => { const itemTime = getCreatedAt(item).getTime(); return dateRange.endExclusive ? itemTime < endTime : itemTime <= endTime; }); } return result; } function jsonValueEquals(a, b) { if (a === void 0 || b === void 0) { return a === b; } if (a === null || b === null) { return a === b; } if (typeof a !== typeof b) { return false; } if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } if (a instanceof Date || b instanceof Date) { return false; } if (typeof a === "object") { if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; return a.every((val, i) => jsonValueEquals(val, b[i])); } if (Array.isArray(a) || Array.isArray(b)) { return false; } const aKeys = Object.keys(a); const bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) return false; return aKeys.every( (key) => jsonValueEquals(a[key], b[key]) ); } return a === b; } // src/storage/domains/observability/inmemory.ts var OBSERVABILITY_DELTA_POLLING_FEATURE = "observability-delta-polling"; var ObservabilityInMemory = class extends ObservabilityStorage { db; constructor({ db }) { super(); this.db = db; } getFeatures() { if (!this.deltaPollingFeatureEnabled()) { return void 0; } return ["delta-polling"]; } async dangerouslyClearAll() { this.db.traces.clear(); this.db.metricRecords.length = 0; this.db.logRecords.length = 0; this.db.scoreRecords.length = 0; this.db.feedbackRecords.length = 0; this.db.observabilityNextCursorId = 1; this.db.traceCursorIds.clear(); this.db.branchCursorIds.clear(); this.db.metricCursorIds.clear(); this.db.logCursorIds.clear(); this.db.scoreCursorIds.clear(); this.db.feedbackCursorIds.clear(); } deltaPollingFeatureEnabled() { return chunk6E6FPM76_cjs.coreFeatures.has(OBSERVABILITY_DELTA_POLLING_FEATURE); } assertDeltaPollingEnabled() { if (this.deltaPollingFeatureEnabled()) { return; } throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_DELTA_POLLING_NOT_SUPPORTED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "This storage provider does not support observability delta polling" }); } allocateObservabilityCursorId() { const cursorId = this.db.observabilityNextCursorId; this.db.observabilityNextCursorId += 1; return cursorId; } /** * Upserts a record into an append-only collection keyed by an id field. * * If an existing record with the same id is found, it is replaced in place * (preserving its cursor id so delta polling does not re-emit it). Otherwise * the record is appended and a fresh cursor id is allocated. */ upsertByIdField(records, cursorIds, record, idField) { const id = record[idField]; if (id == null) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_MISSING_RECORD_ID", domain: "STORAGE" /* STORAGE */, category: "USER" /* USER */, text: `Observability record is missing required id field '${String(idField)}'` }); } const existingIndex = records.findIndex((existing) => existing[idField] === id); if (existingIndex !== -1) { const previous = records[existingIndex]; const cursorId = cursorIds.get(previous); cursorIds.delete(previous); records[existingIndex] = record; if (cursorId !== void 0) { cursorIds.set(record, cursorId); } return; } records.push(record); cursorIds.set(record, this.allocateObservabilityCursorId()); } encodeDeltaCursor(cursorId) { return (cursorId ?? 0).toString(); } decodeDeltaCursor(cursor) { if (!/^\d+$/.test(cursor)) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_INVALID_DELTA_CURSOR", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "USER" /* USER */, text: "Invalid observability delta cursor" }); } const cursorId = Number.parseInt(cursor, 10); if (!Number.isInteger(cursorId) || cursorId < 0) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_INVALID_DELTA_CURSOR", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "USER" /* USER */, text: "Invalid observability delta cursor" }); } return cursorId; } pageDeltaCursor(cursorId) { if (!this.deltaPollingFeatureEnabled()) { return {}; } return { deltaCursor: this.encodeDeltaCursor(cursorId) }; } maxMatchingCursorId(rows, cursorIds, matches) { let maxCursorId = null; for (const row of rows) { const cursorId = cursorIds.get(row); if (cursorId === void 0 || !matches(row)) { continue; } if (maxCursorId === null || cursorId > maxCursorId) { maxCursorId = cursorId; } } return maxCursorId; } createBranchCursorKey(traceId, spanId) { return `${traceId}\0${spanId}`; } maybeRegisterTraceCursor(traceEntry) { const rootSpan = traceEntry.rootSpan; if (!rootSpan) { return; } if (!this.db.traceCursorIds.has(rootSpan.traceId)) { this.db.traceCursorIds.set(rootSpan.traceId, this.allocateObservabilityCursorId()); } } maybeRegisterBranchCursor(span) { if (!chunkXD7CRAEV_cjs.BRANCH_SPAN_TYPE_SET.has(span.spanType)) { return; } const key = this.createBranchCursorKey(span.traceId, span.spanId); if (!this.db.branchCursorIds.has(key)) { this.db.branchCursorIds.set(key, this.allocateObservabilityCursorId()); } } buildDeltaResponse(rows, limit, fallbackCursorId) { const visibleRows = rows.slice(0, limit); const hasMore = rows.length > limit; return { rows: visibleRows.map((entry) => entry.row), delta: { limit, hasMore }, deltaCursor: visibleRows.length > 0 ? this.encodeDeltaCursor(visibleRows[visibleRows.length - 1].cursorId) : this.encodeDeltaCursor(fallbackCursorId) }; } listAppendOnlyDelta(rows, cursorIds, matches, after, limit) { const currentCursorId = this.maxMatchingCursorId(rows, cursorIds, matches); const streamCursorId = this.maxMatchingCursorId(rows, cursorIds, () => true); const fallbackCursorId = currentCursorId ?? streamCursorId; if (after === void 0) { return { rows: [], delta: { limit, hasMore: false }, deltaCursor: this.encodeDeltaCursor(fallbackCursorId) }; } const afterCursorId = this.decodeDeltaCursor(after); const matchingRows = rows.flatMap((row) => { const cursorId = cursorIds.get(row); if (cursorId === void 0 || cursorId <= afterCursorId || !matches(row)) { return []; } return [{ cursorId, row }]; }).sort((a, b) => a.cursorId - b.cursorId).slice(0, limit + 1); return this.buildDeltaResponse(matchingRows, limit, fallbackCursorId); } getTraceCursorId(traceId, filters) { const cursorId = this.db.traceCursorIds.get(traceId); const traceEntry = this.db.traces.get(traceId); if (cursorId === void 0 || !traceEntry?.rootSpan || !this.traceMatchesFilters(traceEntry, filters)) { return null; } return cursorId; } getMaxTraceCursorId(filters) { let maxCursorId = null; for (const traceId of this.db.traceCursorIds.keys()) { const cursorId = this.getTraceCursorId(traceId, filters); if (cursorId === null) { continue; } if (maxCursorId === null || cursorId > maxCursorId) { maxCursorId = cursorId; } } return maxCursorId; } getMaxTraceStreamCursorId() { let maxCursorId = null; for (const cursorId of this.db.traceCursorIds.values()) { if (maxCursorId === null || cursorId > maxCursorId) { maxCursorId = cursorId; } } return maxCursorId; } getBranchCursorId(key, filters) { const cursorId = this.db.branchCursorIds.get(key); if (cursorId === void 0) { return null; } const [traceId, spanId] = key.split("\0"); if (!traceId || !spanId) { return null; } const traceEntry = this.db.traces.get(traceId); const span = traceEntry?.spans[spanId]; if (!span || !this.spanMatchesBranchFilters(span, filters)) { return null; } return cursorId; } getMaxBranchCursorId(filters) { let maxCursorId = null; for (const key of this.db.branchCursorIds.keys()) { const cursorId = this.getBranchCursorId(key, filters); if (cursorId === null) { continue; } if (maxCursorId === null || cursorId > maxCursorId) { maxCursorId = cursorId; } } return maxCursorId; } getMaxBranchStreamCursorId() { let maxCursorId = null; for (const cursorId of this.db.branchCursorIds.values()) { if (maxCursorId === null || cursorId > maxCursorId) { maxCursorId = cursorId; } } return maxCursorId; } async createSpan(args) { const { span } = args; this.validateCreateSpan(span); const now = /* @__PURE__ */ new Date(); const record = { ...span, createdAt: now, updatedAt: now }; this.upsertSpanToTrace(record); } async batchCreateSpans(args) { const now = /* @__PURE__ */ new Date(); for (const span of args.records) { this.validateCreateSpan(span); const record = { ...span, createdAt: now, updatedAt: now }; this.upsertSpanToTrace(record); } } validateCreateSpan(record) { if (!record.spanId) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_SPAN_ID_REQUIRED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "Span ID is required for creating a span" }); } if (!record.traceId) { throw new chunk4U7ZLI36_cjs.MastraError({ id: "OBSERVABILITY_TRACE_ID_REQUIRED", domain: "MASTRA_OBSERVABILITY" /* MASTRA_OBSERVABILITY */, category: "SYSTEM" /* SYSTEM */, text: "Trace ID is required for creating a span" }); } } /** * Inserts or updates a span in the trace and recomputes trace-level properties */ upsertSpanToTrace(span) { const { traceId, spanId } = span; let traceEntry = this.db.traces.get(traceId); if (!traceEntry) { traceEntry = { spans: {}, rootSpan: null, status: "running" /* RUNNING */, hasChildError: false }; this.db.traces.set(traceId, traceEntry); } traceEntry.spans[spanId] = span; if (span.parentSpanId == null) { traceEntry.rootSpan = span; } this.recomputeTraceProperties(traceEntry); this.maybeRegisterTraceCursor(traceEntry); this.maybeRegisterBranchCursor(span); } /** * Recomputes derived trace properties from all spans */ recomputeTraceProperties(traceEntry) { const spans = Object.values(traceEntry.spans); if (spans.length === 0) return; traceEntry.hasChildError = spans.some((s) => s.error != null); const rootSpan = traceEntry.rootSpan; if (rootSpan) { if (rootSpan.error != null) { traceEntry.status = "error" /* ERROR */; } else if (rootSpan.endedAt == null) { traceEntry.status = "running" /* RUNNING */; } else { traceEntry.status = "success" /* SUCCESS */; } } else { traceEntry.status = "running" /* RUNNING */; } } async getSpan(args) { const { traceId, spanId } = args; const traceEntry = this.db.traces.get(traceId); if (!traceEntry) { return null; } const span = traceEntry.spans[spanId]; if (!span) { return null; } return { span }; } async getSpans(args) { const { traceId, spanIds } = args; const traceEntry = this.db.traces.get(traceId); if (!traceEntry) { return { traceId, spans: [] }; } const spans = []; for (const spanId of spanIds) { const span = traceEntry.spans[spanId]; if (span) spans.push(span); } return { traceId, spans }; } async getRootSpan(args) { const { traceId } = args; const traceEntry = this.db.traces.get(traceId); if (!traceEntry || !traceEntry.rootSpan) { return null; } return { span: traceEntry.rootSpan }; } async getTrace(args) { const { traceId } = args; const traceEntry = this.db.traces.get(traceId); if (!traceEntry) { return null; } const spans = Object.values(traceEntry.spans); if (spans.length === 0) { return null; } spans.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime()); return { traceId, spans }; } async getTraceLight(args) { const { traceId } = args; const traceEntry = this.db.traces.get(traceId); if (!traceEntry) { return null; } const spans = Object.values(traceEntry.spans); if (spans.length === 0) { return null; } spans.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime()); return { traceId, spans: spans.map( (span) => ({ traceId: span.traceId, spanId: span.spanId, parentSpanId: span.parentSpanId, name: span.name, spanType: span.spanType, isEvent: span.isEvent, startedAt: span.startedAt, endedAt: span.endedAt, error: span.error, entityType: span.entityType, entityId: span.entityId, entityName: span.entityName, createdAt: span.createdAt, updatedAt: span.updatedAt }) ) }; } getMatchingRootSpans(args) { const { filters, pagination, orderBy } = chunkXD7CRAEV_cjs.listTracesArgsSchema.parse(args); const matchingRootSpans = []; for (const [, traceEntry] of this.db.traces) { if (!traceEntry.rootSpan) continue; if (this.traceMatchesFilters(traceEntry, filters)) { matchingRootSpans.push(traceEntry.rootSpan); } } const { field: sortField, direction: sortDirection } = orderBy; matchingRootSpans.sort((a, b) => { if (sortField === "endedAt") { const aVal = a.endedAt; const bVal = b.endedAt; if (aVal == null && bVal == null) return 0; if (aVal == null) return sortDirection === "DESC" ? -1 : 1; if (bVal == null) return sortDirection === "DESC" ? 1 : -1; const diff = aVal.getTime() - bVal.getTime(); return sortDirection === "DESC" ? -diff : diff; } else { const diff = a.startedAt.getTime() - b.startedAt.getTime(); return sortDirection === "DESC" ? -diff : diff; } }); const total = matchingRootSpans.length; const { page, perPage } = pagination; const start = page * perPage; const end = start + perPage; const paged = matchingRootSpans.slice(start, end); return { paged, total, page, perPage, hasMore: end < total }; } async listTraces(args) { const { mode, filters, after, limit } = chunkXD7CRAEV_cjs.listTracesArgsSchema.parse(args); if (mode === "delta") { this.assertDeltaPollingEnabled(); const currentCursorId = this.getMaxTraceCursorId(filters); const fallbackCursorId = currentCursorId ?? this.getMaxTraceStreamCursorId(); if (after === void 0) { return { spans: [], delta: { limit, hasMore: false }, deltaCursor: this.encodeDeltaCursor(fallbackCursorId) }; } const afterCursorId = this.decodeDeltaCursor(after); const matchingRootSpans = Array.from(this.db.traceCursorIds.entries()).flatMap(([traceId, cursorId]) => { if (cursorId <= afterCursorId) { return []; } const traceEntry = this.db.traces.get(traceId); if (!traceEntry?.rootSpan || !this.traceMatchesFilters(traceEntry, filters)) { return []; } return [{ cursorId, row: traceEntry.rootSpan }]; }).sort((a, b) => a.cursorId - b.cursorId).slice(0, limit + 1); const deltaResponse = this.buildDeltaResponse(matchingRootSpans, limit, fallbackCursorId); return { spans: chunkXD7CRAEV_cjs.toTraceSpans(deltaResponse.rows), delta: deltaResponse.delta, deltaCursor: deltaResponse.deltaCursor }; } const { paged, total, page, perPage, hasMore } = this.getMatchingRootSpans(args); return { spans: chunkXD7CRAEV_cjs.toTraceSpans(paged), pagination: { total, page, perPage, hasMore }, ...this.pageDeltaCursor(this.getMaxTraceCursorId(filters) ?? this.getMaxTraceStreamCursorId()) }; } async listTracesLight(args) { const { paged, total, page, perPage, hasMore } = this.getMatchingRootSpans(args); return { spans: paged.map((span) => ({ traceId: span.traceId, spanId: span.spanId, parentSpanId: span.parentSpanId, name: span.name, spanType: span.spanType, isEvent: span.isEvent, startedAt: span.startedAt, endedAt: span.endedAt, error: span.error, entityType: span.entityType, entityId: span.entityId, entityName: span.entityName, createdAt: span.createdAt, updatedAt: span.updatedAt })), pagination: { total, page, perPage, hasMore } }; } /** * Check if a trace matches all provided filters */ traceMatchesFilters(traceEntry, filters) { if (!filters) return true; const rootSpan = traceEntry.rootSpan; if (!rootSpan) return false; if (filters.startedAt) { if (filters.startedAt.start && rootSpan.startedAt < filters.startedAt.start) { return false; } if (filters.startedAt.end && rootSpan.startedAt > filters.startedAt.end) { return false; } } if (filters.endedAt) { if (rootSpan.endedAt == null) { return false; } if (filters.endedAt.start && rootSpan.endedAt < filters.endedAt.start) { return false; } if (filters.endedAt.end && rootSpan.endedAt > filters.endedAt.end) { return false; } } if (filters.spanType !== void 0 && rootSpan.spanType !== filters.spanType) { return false; } if (filters.entityType !== void 0 && rootSpan.entityType !== filters.entityType) { return false; } if (filters.entityId !== void 0 && rootSpan.entityId !== filters.entityId) { return false; } if (filters.entityName !== void 0 && rootSpan.entityName !== filters.entityName) { return false; } if (filters.entityVersionId !== void 0 && rootSpan.entityVersionId !== filters.entityVersionId) { return false; } if (filters.experimentId !== void 0 && rootSpan.experimentId !== filters.experimentId) { return false; } if (filters.userId !== void 0 && rootSpan.userId !== filters.userId) { return false; } if (filters.organizationId !== void 0 && rootSpan.organizationId !== filters.organizationId) { return false; } if (filters.resourceId !== void 0 && rootSpan.resourceId !== filters.resourceId) { return false; } if (filters.runId !== void 0 && rootSpan.runId !== filters.runId) { return false; } if (filters.sessionId !== void 0 && rootSpan.sessionId !== filters.sessionId) { return false; } if (filters.threadId !== void 0 && rootSpan.threadId !== filters.threadId) { return false; } if (filters.requestId !== void 0 && rootSpan.requestId !== filters.requestId) { return false; } if (filters.environment !== void 0 && rootSpan.environment !== filters.environment) { return false; } if (filters.source !== void 0 && rootSpan.source !== filters.source) { return false; } if (filters.serviceName !== void 0 && rootSpan.serviceName !== filters.serviceName) { return false; } if (filters.scope != null && rootSpan.scope != null) { for (const [key, value] of Object.entries(filters.scope)) { if (!jsonValueEquals(rootSpan.scope[key], value)) { return false; } } } else if (filters.scope != null && rootSpan.scope == null) { return false; } if (filters.metadata != null && rootSpan.metadata != null) { for (const [key, value] of Object.entries(filters.metadata)) { if (!jsonValueEquals(rootSpan.metadata[key], value)) { return false; } } } else if (filters.metadata != null && rootSpan.metadata == null) { return false; } if (filters.tags != null && filters.tags.length > 0) { if (rootSpan.tags == null) { return false; } for (const tag of filters.tags) { if (!rootSpan.tags.includes(tag)) { return false; } } } if (filters.status !== void 0 && traceEntry.status !== filters.status) { return false; } if (filters.hasChildError !== void 0 && traceEntry.hasChildError !== filters.hasChildError) { return false; } return true; } async listBranches(args) { const { mode, filters, pagination, orderBy, after, limit } = chunkXD7CRAEV_cjs.listBranchesArgsSchema.parse(args); if (mode === "delta") { this.assertDeltaPollingEnabled(); const currentCursorId = this.getMaxBranchCursorId(filters); const fallbackCursorId = currentCursorId ?? this.getMaxBranchStreamCursorId(); if (after === void 0) { return { branches: [], delta: { limit, hasMore: false }, deltaCursor: this.encodeDeltaCursor(fallbackCursorId) }; } const afterCursorId = this.decodeDeltaCursor(after); const matches2 = Array.from(this.db.branchCursorIds.entries()).flatMap(([key, cursorId]) => { if (cursorId <= afterCursorId) { return [];