@mastra/observability 1.24.0-alpha.4 → 1.24.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/bus/observability-bus.d.ts +2 -1
  2. package/dist/bus/observability-bus.d.ts.map +1 -1
  3. package/dist/bus/route-event.d.ts.map +1 -1
  4. package/dist/default.d.ts +5 -1
  5. package/dist/default.d.ts.map +1 -1
  6. package/dist/docs/SKILL.md +1 -1
  7. package/dist/docs/assets/SOURCE_MAP.json +63 -53
  8. package/dist/docs/references/docs-observability-feedback.md +5 -7
  9. package/dist/docs/references/reference-observability-feedback.md +57 -14
  10. package/dist/docs/references/reference-observability-tracing-exporters-langfuse.md +24 -1
  11. package/dist/docs/references/reference-observability-tracing-exporters-mastra-platform-exporter.md +19 -16
  12. package/dist/exporters/default.d.ts +6 -7
  13. package/dist/exporters/default.d.ts.map +1 -1
  14. package/dist/exporters/event-buffer.d.ts +5 -2
  15. package/dist/exporters/event-buffer.d.ts.map +1 -1
  16. package/dist/exporters/keyed-queue.d.ts +6 -0
  17. package/dist/exporters/keyed-queue.d.ts.map +1 -0
  18. package/dist/exporters/mastra-platform.d.ts +8 -1
  19. package/dist/exporters/mastra-platform.d.ts.map +1 -1
  20. package/dist/exporters/mastra-storage.d.ts +6 -7
  21. package/dist/exporters/mastra-storage.d.ts.map +1 -1
  22. package/dist/exporters/platform-resolved-record.d.ts +3 -0
  23. package/dist/exporters/platform-resolved-record.d.ts.map +1 -0
  24. package/dist/exporters/storage-annotation.d.ts +12 -0
  25. package/dist/exporters/storage-annotation.d.ts.map +1 -0
  26. package/dist/exporters/storage-byte-tracker.d.ts +2 -3
  27. package/dist/exporters/storage-byte-tracker.d.ts.map +1 -1
  28. package/dist/index.cjs +994 -708
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.js +993 -709
  31. package/dist/index.js.map +1 -1
  32. package/dist/instances/base.d.ts +2 -1
  33. package/dist/instances/base.d.ts.map +1 -1
  34. package/dist/recorded.d.ts +4 -12
  35. package/dist/recorded.d.ts.map +1 -1
  36. package/dist/spans/base.d.ts +9 -0
  37. package/dist/spans/base.d.ts.map +1 -1
  38. package/dist/spans/default.d.ts.map +1 -1
  39. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -52,6 +52,12 @@ function routeToHandler(handler, event, logger) {
52
52
  }), handler.name, "score", logger);
53
53
  }
54
54
  break;
55
+ case "feedback_review_status":
56
+ if (handler.onFeedbackReviewStatusEvent) return catchAsyncResult(handler.onFeedbackReviewStatusEvent(event), handler.name, "feedback review status", logger);
57
+ break;
58
+ case "feedback_replacement":
59
+ if (handler.onFeedbackReplacementEvent) return catchAsyncResult(handler.onFeedbackReplacementEvent(event), handler.name, "feedback replacement", logger);
60
+ break;
55
61
  case "feedback": if (handler.onFeedbackEvent) return catchAsyncResult(handler.onFeedbackEvent(event), handler.name, "feedback", logger);
56
62
  }
57
63
  } catch (err) {
@@ -552,6 +558,14 @@ function cleanEvent(event, options) {
552
558
  type: "score",
553
559
  score: deepClean(event.score, options)
554
560
  };
561
+ case "feedback_review_status": return {
562
+ type: event.type,
563
+ feedback: deepClean(event.feedback, options)
564
+ };
565
+ case "feedback_replacement": return {
566
+ type: event.type,
567
+ feedback: deepClean(event.feedback, options)
568
+ };
555
569
  case "feedback": return {
556
570
  type: "feedback",
557
571
  feedback: deepClean(event.feedback, options)
@@ -644,10 +658,10 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
644
658
  * emit() is synchronous — async handler promises are tracked internally
645
659
  * and can be drained via flush().
646
660
  */
647
- emit(event) {
661
+ emit(event, shouldHandle) {
648
662
  const cleaned = cleanEvent(event, this.deepCleanOptions);
649
- for (const exporter of this.exporters) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
650
- if (this.bridge) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
663
+ for (const exporter of this.exporters) if (!shouldHandle || shouldHandle(exporter)) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
664
+ if (this.bridge && (!shouldHandle || shouldHandle(this.bridge))) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
651
665
  super.emit(cleaned);
652
666
  }
653
667
  /**
@@ -3419,6 +3433,34 @@ function mergeMetadata$1(parentMetadata, metadata) {
3419
3433
  }
3420
3434
  }
3421
3435
  // src/spans/base.ts
3436
+ /** Replaces error text exported from traces that hide input or output. */
3437
+ const REDACTED_ERROR_MESSAGE = "[REDACTED]";
3438
+ /**
3439
+ * The error as exported from a trace that hides input or output: keeps what
3440
+ * identifies the error (id, name, domain, category, stack frames) and drops
3441
+ * text and free-form details, which can quote the hidden data.
3442
+ */
3443
+ function redactErrorInfo(errorInfo, stackMessage) {
3444
+ if (!errorInfo) return errorInfo;
3445
+ const { id, name, domain, category, stack } = errorInfo;
3446
+ return {
3447
+ ...id !== void 0 ? { id } : {},
3448
+ ...name !== void 0 ? { name } : {},
3449
+ ...domain !== void 0 ? { domain } : {},
3450
+ ...category !== void 0 ? { category } : {},
3451
+ message: REDACTED_ERROR_MESSAGE,
3452
+ ...stack !== void 0 ? { stack: redactStackHeader(stack, stackMessage ?? errorInfo.message, errorInfo.name) } : {}
3453
+ };
3454
+ }
3455
+ /** Preserve stack frames only when they follow the complete captured message. */
3456
+ function redactStackHeader(stack, message, name = "Error") {
3457
+ const redactedHeader = `${name}: ${REDACTED_ERROR_MESSAGE}`;
3458
+ const separator = `: ${message}`;
3459
+ const separatorIndex = stack.indexOf(separator);
3460
+ if (separatorIndex <= 0 || stack.slice(0, separatorIndex).includes("\n")) return redactedHeader;
3461
+ const suffix = stack.slice(separatorIndex + separator.length);
3462
+ return suffix === "" || suffix.startsWith("\n") ? `${redactedHeader}${suffix}` : redactedHeader;
3463
+ }
3422
3464
  const LINEAGE_KEYS = [
3423
3465
  "parentEntityType",
3424
3466
  "parentEntityId",
@@ -3548,6 +3590,7 @@ var BaseSpan = class BaseSpan {
3548
3590
  stopReason;
3549
3591
  stopReasonContext;
3550
3592
  errorInfo;
3593
+ errorStackMessage;
3551
3594
  metadata;
3552
3595
  requestContext;
3553
3596
  tags;
@@ -3935,7 +3978,7 @@ var BaseSpan = class BaseSpan {
3935
3978
  endTime: this.endTime,
3936
3979
  input: hideInput ? void 0 : this.input,
3937
3980
  output: hideOutput ? void 0 : this.output,
3938
- errorInfo: this.errorInfo,
3981
+ errorInfo: hideInput || hideOutput ? redactErrorInfo(this.errorInfo, this.errorStackMessage) : this.errorInfo,
3939
3982
  ...this.outcome !== void 0 ? { outcome: this.outcome } : {},
3940
3983
  ...this.stopReason !== void 0 ? { stopReason: this.stopReason } : {},
3941
3984
  ...this.stopReasonContext !== void 0 ? { stopReasonContext: this.stopReasonContext } : {},
@@ -4087,6 +4130,8 @@ var DefaultSpan = class extends BaseSpan {
4087
4130
  };
4088
4131
  if (!this.isExcluded) {
4089
4132
  const apiDetails = apiCallErrorDetails(error);
4133
+ const stackError = error instanceof MastraError && error.cause instanceof Error && error.cause.stack ? error.cause : error;
4134
+ this.errorStackMessage = stackError.message;
4090
4135
  this.errorInfo = deepClean(error instanceof MastraError ? {
4091
4136
  id: error.id,
4092
4137
  details: apiDetails ? {
@@ -4097,7 +4142,7 @@ var DefaultSpan = class extends BaseSpan {
4097
4142
  domain: error.domain,
4098
4143
  message: error.message,
4099
4144
  name: error.name,
4100
- stack: error.cause instanceof Error && error.cause.stack || error.stack
4145
+ stack: stackError.stack
4101
4146
  } : {
4102
4147
  message: error.message,
4103
4148
  name: error.name,
@@ -4599,175 +4644,555 @@ var EventBuffer = class {
4599
4644
  });
4600
4645
  }
4601
4646
  };
4602
- // src/exporters/default.ts
4603
- /**
4604
- * Resolves the final tracing storage strategy based on config and observability store hints
4605
- */
4606
- function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
4607
- const observabilityStrategy = observabilityStorage.observabilityStrategy;
4608
- if (config.strategy && config.strategy !== "auto") {
4609
- if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
4610
- logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
4611
- userStrategy: config.strategy,
4612
- storageAdapter: storageName,
4613
- supportedStrategies: observabilityStrategy.supported,
4614
- fallbackStrategy: observabilityStrategy.preferred
4615
- });
4616
- }
4617
- return observabilityStrategy.preferred;
4618
- }
4619
- const FLUSH_SUCCEEDED$1 = { failed: false };
4620
- /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
4621
- const MAX_FLUSH_ROUNDS$1 = 3;
4622
- /**
4623
- * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
4624
- * This class is preserved unchanged so existing integrations (including code
4625
- * that matches on the `mastra-default-observability-exporter` exporter name)
4626
- * keep working. It will be removed in a future major version.
4627
- *
4628
- * Default storage-backed exporter. Buffers observability events and flushes them
4629
- * in batches to the configured ObservabilityStorage backend with retry support.
4630
- */
4631
- var DefaultExporter = class extends BaseExporter {
4632
- name = "mastra-default-observability-exporter";
4633
- #config;
4634
- #isInitializing = false;
4635
- #initPromises = /* @__PURE__ */ new Set();
4636
- #eventBuffer;
4637
- #storage;
4638
- #observabilityStorage;
4639
- #resolvedStrategy;
4640
- #flushTimer;
4641
- /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
4642
- #inFlightFlushes = /* @__PURE__ */ new Set();
4643
- #emitDropEvent;
4644
- #unsupportedSignals = /* @__PURE__ */ new Set();
4645
- constructor(config = {}) {
4646
- super(config);
4647
- this.#config = {
4648
- ...config,
4649
- maxBatchSize: config.maxBatchSize ?? 1e3,
4650
- maxBufferSize: config.maxBufferSize ?? 1e4,
4651
- maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
4652
- maxRetries: config.maxRetries ?? 4,
4653
- retryDelayMs: config.retryDelayMs ?? 500,
4654
- strategy: config.strategy ?? "auto"
4647
+ // src/exporters/keyed-queue.ts
4648
+ /** Keep writes to one record ordered without blocking unrelated records. */
4649
+ var KeyedQueue = class {
4650
+ pending = /* @__PURE__ */ new Map();
4651
+ enqueue(key, write) {
4652
+ const current = (this.pending.get(key) ?? Promise.resolve()).catch(() => {}).then(write);
4653
+ this.pending.set(key, current);
4654
+ const cleanup = () => {
4655
+ if (this.pending.get(key) === current) this.pending.delete(key);
4655
4656
  };
4656
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
4657
- }
4658
- /**
4659
- * Initialize the exporter (called after all dependencies are ready)
4660
- */
4661
- async init(options) {
4662
- try {
4663
- this.#isInitializing = true;
4664
- this.#emitDropEvent = options.emitDropEvent;
4665
- this.#storage = options.mastra?.getStorage();
4666
- if (!this.#storage) {
4667
- this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
4668
- return;
4669
- }
4670
- this.#observabilityStorage = await this.#storage.getStore("observability");
4671
- if (!this.#observabilityStorage) {
4672
- this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
4673
- return;
4674
- }
4675
- if (!this.#resolvedStrategy) {
4676
- this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
4677
- this.logger.debug("tracing storage exporter initialized", {
4678
- strategy: this.#resolvedStrategy,
4679
- source: this.#config.strategy !== "auto" ? "user" : "auto",
4680
- storageAdapter: this.#storage.constructor.name,
4681
- maxBatchSize: this.#config.maxBatchSize,
4682
- maxBatchWaitMs: this.#config.maxBatchWaitMs
4683
- });
4684
- }
4685
- if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
4686
- } finally {
4687
- this.#isInitializing = false;
4688
- /**
4689
- * Assumes caller waits until export of a parent span is completed before calling
4690
- * export for child spans , order is not relevant for resolve
4691
- */
4692
- this.#initPromises.forEach((resolve) => {
4693
- resolve();
4694
- });
4695
- this.#initPromises.clear();
4696
- }
4657
+ current.then(cleanup, cleanup);
4658
+ return current;
4697
4659
  }
4698
- /**
4699
- * Checks if buffer should be flushed based on size or time triggers
4700
- */
4701
- shouldFlush() {
4702
- if (this.#resolvedStrategy === "realtime") return true;
4703
- if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
4704
- if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
4705
- if (this.#eventBuffer.totalSize > 0) {
4706
- if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
4660
+ };
4661
+ // src/recorded.ts
4662
+ function nullToUndefined(value) {
4663
+ return value ?? void 0;
4664
+ }
4665
+ function mergeMetadata(base, extra) {
4666
+ if (!base && !extra) return void 0;
4667
+ return {
4668
+ ...base ?? {},
4669
+ ...extra ?? {}
4670
+ };
4671
+ }
4672
+ function normalizeErrorInfo(error) {
4673
+ if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
4674
+ return {
4675
+ message: error.message,
4676
+ id: "id" in error && typeof error.id === "string" ? error.id : void 0,
4677
+ name: "name" in error && typeof error.name === "string" ? error.name : void 0,
4678
+ stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
4679
+ domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
4680
+ category: "category" in error && typeof error.category === "string" ? error.category : void 0,
4681
+ details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
4682
+ };
4683
+ }
4684
+ function buildCorrelationContext(span, rootSpan, parent) {
4685
+ return {
4686
+ tags: rootSpan.tags ?? void 0,
4687
+ entityType: nullToUndefined(span.entityType),
4688
+ entityId: nullToUndefined(span.entityId),
4689
+ entityName: nullToUndefined(span.entityName),
4690
+ parentEntityType: parent?.entityType ?? void 0,
4691
+ parentEntityId: parent?.entityId ?? void 0,
4692
+ parentEntityName: parent?.entityName ?? void 0,
4693
+ rootEntityType: nullToUndefined(rootSpan.entityType),
4694
+ rootEntityId: nullToUndefined(rootSpan.entityId),
4695
+ rootEntityName: nullToUndefined(rootSpan.entityName),
4696
+ userId: nullToUndefined(span.userId),
4697
+ organizationId: nullToUndefined(span.organizationId),
4698
+ resourceId: nullToUndefined(span.resourceId),
4699
+ runId: nullToUndefined(span.runId),
4700
+ sessionId: nullToUndefined(span.sessionId),
4701
+ threadId: nullToUndefined(span.threadId),
4702
+ requestId: nullToUndefined(span.requestId),
4703
+ environment: nullToUndefined(span.environment),
4704
+ source: nullToUndefined(span.source),
4705
+ serviceName: nullToUndefined(span.serviceName),
4706
+ experimentId: nullToUndefined(span.experimentId)
4707
+ };
4708
+ }
4709
+ function buildScoreEvent(args) {
4710
+ const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
4711
+ return {
4712
+ type: "score",
4713
+ score: {
4714
+ scoreId: generateSignalId(),
4715
+ timestamp: /* @__PURE__ */ new Date(),
4716
+ traceId,
4717
+ spanId,
4718
+ scorerId: score.scorerId,
4719
+ scorerName: score.scorerName,
4720
+ scorerVersion: score.scorerVersion,
4721
+ source: score.source,
4722
+ scoreSource: score.scoreSource,
4723
+ score: score.score,
4724
+ reason: score.reason,
4725
+ experimentId: score.experimentId,
4726
+ scoreTraceId: score.scoreTraceId,
4727
+ targetEntityType: score.targetEntityType,
4728
+ correlationContext,
4729
+ metadata: mergeMetadata(inheritedMetadata, score.metadata)
4707
4730
  }
4708
- return false;
4709
- }
4710
- /**
4711
- * Schedules a flush using setTimeout
4712
- */
4713
- scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
4714
- if (this.#flushTimer) clearTimeout(this.#flushTimer);
4715
- this.#flushTimer = setTimeout(() => {
4716
- this.#flushTimer = void 0;
4717
- this.trackFlushBuffer().catch((error) => {
4718
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
4719
- });
4720
- }, delayMs);
4721
- }
4722
- retryDelay(retryAttempt) {
4723
- return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
4724
- }
4725
- retryAttempt(events) {
4726
- return events.reduce((earliestAttempt, event) => {
4727
- if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
4728
- return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
4729
- }, void 0);
4730
- }
4731
- logStorageFailure(signal, events, retryAttempt, error) {
4732
- this.logger.warn("Failed to persist observability events", {
4733
- signal,
4734
- eventCount: events.length,
4735
- retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
4736
- maxRetries: this.#config.maxRetries,
4737
- ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
4738
- error: error instanceof Error ? error.message : String(error)
4739
- });
4740
- }
4741
- /**
4742
- * Checks flush triggers and schedules/triggers flush as needed.
4743
- * Called after adding any event to the buffer.
4744
- * Returns the flush promise when flushing so callers can await it.
4745
- */
4746
- async handleBatchedFlush() {
4747
- if (this.shouldFlush()) await this.trackFlushBuffer();
4748
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
4749
- }
4750
- sanitizeDropError(error) {
4751
- if (error instanceof MastraError) return {
4752
- id: error.id,
4753
- domain: String(error.domain),
4754
- message: error.message
4755
- };
4756
- if (error instanceof Error) return { message: error.message };
4757
- return { message: String(error) };
4758
- }
4759
- emitDrop(signal, reason, count, error) {
4760
- if (count === 0) return;
4761
- const dropEvent = {
4762
- type: "drop",
4763
- signal,
4764
- reason,
4765
- count,
4731
+ };
4732
+ }
4733
+ function buildFeedbackEvent(args) {
4734
+ const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
4735
+ return {
4736
+ type: "feedback",
4737
+ feedback: {
4738
+ feedbackId: generateSignalId(),
4766
4739
  timestamp: /* @__PURE__ */ new Date(),
4767
- exporterName: this.name,
4768
- ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
4769
- ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
4770
- };
4740
+ traceId,
4741
+ spanId,
4742
+ source: feedback.source,
4743
+ feedbackSource: feedback.feedbackSource,
4744
+ feedbackType: feedback.feedbackType,
4745
+ value: feedback.value,
4746
+ userId: feedback.userId,
4747
+ feedbackUserId: feedback.feedbackUserId,
4748
+ comment: feedback.comment,
4749
+ sourceId: feedback.sourceId,
4750
+ experimentId: feedback.experimentId,
4751
+ correlationContext,
4752
+ metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
4753
+ }
4754
+ };
4755
+ }
4756
+ function findSpanById(spans, spanId) {
4757
+ if (!spanId) return void 0;
4758
+ return spans.find((span) => span.spanId === spanId);
4759
+ }
4760
+ /** Resolve a storage exporter's copy without changing the event identity or other destinations' payloads. */
4761
+ function resolveRecordedEventFromTrace(trace, event) {
4762
+ const record = event.type === "score" ? event.score : event.feedback;
4763
+ const spans = trace.spans.filter((span) => span.traceId === record.traceId);
4764
+ const span = record.spanId ? findSpanById(spans, record.spanId) : spans.find((span) => !span.parentSpanId);
4765
+ if (!span) return null;
4766
+ const byId = new Map(spans.map((span) => [span.spanId, span]));
4767
+ let root = span;
4768
+ const visited = /* @__PURE__ */ new Set();
4769
+ while (root.parentSpanId) {
4770
+ if (visited.has(root.spanId)) return null;
4771
+ visited.add(root.spanId);
4772
+ const parent = byId.get(root.parentSpanId);
4773
+ if (!parent) return null;
4774
+ root = parent;
4775
+ }
4776
+ const context = {
4777
+ correlationContext: buildCorrelationContext(span, root, span.parentSpanId ? byId.get(span.parentSpanId) : void 0),
4778
+ metadata: mergeMetadata(span.metadata, record.metadata)
4779
+ };
4780
+ return event.type === "score" ? {
4781
+ type: "score",
4782
+ score: {
4783
+ ...event.score,
4784
+ ...context
4785
+ }
4786
+ } : event.type === "feedback_replacement" ? {
4787
+ type: "feedback_replacement",
4788
+ feedback: {
4789
+ ...event.feedback,
4790
+ ...context
4791
+ }
4792
+ } : {
4793
+ type: "feedback",
4794
+ feedback: {
4795
+ ...event.feedback,
4796
+ ...context
4797
+ }
4798
+ };
4799
+ }
4800
+ var RecordedSpanImpl = class {
4801
+ id;
4802
+ traceId;
4803
+ name;
4804
+ type;
4805
+ entityType;
4806
+ entityId;
4807
+ entityName;
4808
+ startTime;
4809
+ endTime;
4810
+ attributes;
4811
+ metadata;
4812
+ tags;
4813
+ input;
4814
+ output;
4815
+ errorInfo;
4816
+ requestContext;
4817
+ isEvent;
4818
+ isRootSpan;
4819
+ parentSpanId;
4820
+ parent;
4821
+ children = [];
4822
+ #raw;
4823
+ #rootSpan;
4824
+ #emitRecordedEvent;
4825
+ #canEmitRecordedEvent;
4826
+ #debugRecordedAnnotationUnavailable;
4827
+ constructor(args) {
4828
+ const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
4829
+ this.#raw = raw;
4830
+ this.#rootSpan = rootSpan;
4831
+ this.#emitRecordedEvent = emitRecordedEvent;
4832
+ this.#canEmitRecordedEvent = canEmitRecordedEvent;
4833
+ this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
4834
+ this.id = raw.spanId;
4835
+ this.traceId = raw.traceId;
4836
+ this.name = raw.name;
4837
+ this.type = raw.spanType;
4838
+ this.entityType = raw.entityType ?? void 0;
4839
+ this.entityId = raw.entityId ?? void 0;
4840
+ this.entityName = raw.entityName ?? void 0;
4841
+ this.startTime = raw.startedAt;
4842
+ this.endTime = raw.endedAt ?? void 0;
4843
+ this.attributes = raw.attributes ?? void 0;
4844
+ this.metadata = raw.metadata ?? void 0;
4845
+ this.tags = raw.tags ?? void 0;
4846
+ this.input = raw.input ?? void 0;
4847
+ this.output = raw.output ?? void 0;
4848
+ this.errorInfo = normalizeErrorInfo(raw.error);
4849
+ this.requestContext = raw.requestContext ?? void 0;
4850
+ this.isEvent = raw.isEvent;
4851
+ this.isRootSpan = !raw.parentSpanId;
4852
+ this.parentSpanId = raw.parentSpanId ?? void 0;
4853
+ }
4854
+ async addScore(score) {
4855
+ if (!this.#canEmitRecordedEvent()) {
4856
+ this.#debugRecordedAnnotationUnavailable({
4857
+ kind: "score",
4858
+ traceId: this.traceId,
4859
+ spanId: this.id
4860
+ });
4861
+ return;
4862
+ }
4863
+ await this.#emitRecordedEvent(buildScoreEvent({
4864
+ traceId: this.#raw.traceId,
4865
+ spanId: this.id,
4866
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4867
+ score,
4868
+ inheritedMetadata: this.#raw.metadata
4869
+ }));
4870
+ }
4871
+ async addFeedback(feedback) {
4872
+ if (!this.#canEmitRecordedEvent()) {
4873
+ this.#debugRecordedAnnotationUnavailable({
4874
+ kind: "feedback",
4875
+ traceId: this.traceId,
4876
+ spanId: this.id
4877
+ });
4878
+ return;
4879
+ }
4880
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4881
+ traceId: this.#raw.traceId,
4882
+ spanId: this.id,
4883
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4884
+ feedback,
4885
+ inheritedMetadata: this.#raw.metadata
4886
+ }));
4887
+ }
4888
+ };
4889
+ var RecordedTraceImpl = class {
4890
+ traceId;
4891
+ rootSpan;
4892
+ spans;
4893
+ #rootRecord;
4894
+ #emitRecordedEvent;
4895
+ #spanMap;
4896
+ #canEmitRecordedEvent;
4897
+ #debugRecordedAnnotationUnavailable;
4898
+ constructor(args) {
4899
+ this.traceId = args.traceId;
4900
+ this.rootSpan = args.rootSpan;
4901
+ this.#rootRecord = args.rootRecord;
4902
+ this.spans = args.spans;
4903
+ this.#emitRecordedEvent = args.emitRecordedEvent;
4904
+ this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
4905
+ this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
4906
+ this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
4907
+ }
4908
+ getSpan(spanId) {
4909
+ return this.#spanMap.get(spanId) ?? null;
4910
+ }
4911
+ async addScore(score) {
4912
+ if (!this.#canEmitRecordedEvent()) {
4913
+ this.#debugRecordedAnnotationUnavailable({
4914
+ kind: "score",
4915
+ traceId: this.traceId
4916
+ });
4917
+ return;
4918
+ }
4919
+ await this.#emitRecordedEvent(buildScoreEvent({
4920
+ traceId: this.#rootRecord.traceId,
4921
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4922
+ score,
4923
+ inheritedMetadata: this.#rootRecord.metadata
4924
+ }));
4925
+ }
4926
+ async addFeedback(feedback) {
4927
+ if (!this.#canEmitRecordedEvent()) {
4928
+ this.#debugRecordedAnnotationUnavailable({
4929
+ kind: "feedback",
4930
+ traceId: this.traceId
4931
+ });
4932
+ return;
4933
+ }
4934
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4935
+ traceId: this.#rootRecord.traceId,
4936
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4937
+ feedback,
4938
+ inheritedMetadata: this.#rootRecord.metadata
4939
+ }));
4940
+ }
4941
+ };
4942
+ function findRootSpan(spans) {
4943
+ const spanIds = new Set(spans.map((span) => span.spanId));
4944
+ return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
4945
+ }
4946
+ function hydrateRecordedTrace(args) {
4947
+ const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
4948
+ const rootSpan = findRootSpan(trace.spans);
4949
+ if (!rootSpan) return null;
4950
+ const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
4951
+ raw,
4952
+ rootSpan,
4953
+ emitRecordedEvent,
4954
+ canEmitRecordedEvent,
4955
+ debugRecordedAnnotationUnavailable
4956
+ }));
4957
+ const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
4958
+ for (const span of recordedSpans) {
4959
+ if (!span.parentSpanId) continue;
4960
+ const parent = spanMap.get(span.parentSpanId);
4961
+ if (!parent) continue;
4962
+ span.parent = parent;
4963
+ parent.children.push(span);
4964
+ }
4965
+ const hydratedRootSpan = spanMap.get(rootSpan.spanId);
4966
+ if (!hydratedRootSpan) return null;
4967
+ return new RecordedTraceImpl({
4968
+ traceId: trace.traceId,
4969
+ rootSpan: hydratedRootSpan,
4970
+ rootRecord: rootSpan,
4971
+ spans: recordedSpans,
4972
+ emitRecordedEvent,
4973
+ canEmitRecordedEvent,
4974
+ debugRecordedAnnotationUnavailable
4975
+ });
4976
+ }
4977
+ // src/exporters/storage-annotation.ts
4978
+ const LOOKUP_DELAYS_MS = [
4979
+ 0,
4980
+ 100,
4981
+ 250,
4982
+ 500,
4983
+ 1e3,
4984
+ 2e3,
4985
+ 2e3
4986
+ ];
4987
+ /** Older stores may inherit a method that throws instead of omitting the hook. */
4988
+ async function updateStorageFeedbackReviewStatus(storage, feedback, logger) {
4989
+ if (typeof storage.updateFeedbackReviewStatus === "function") try {
4990
+ await storage.updateFeedbackReviewStatus(feedback);
4991
+ return;
4992
+ } catch (error) {
4993
+ if (typeof error !== "object" || error === null || !("id" in error) || error.id !== "OBSERVABILITY_STORAGE_UPDATE_FEEDBACK_REVIEW_STATUS_NOT_IMPLEMENTED") throw error;
4994
+ }
4995
+ logger.warn("Storage exporter skipped feedback review update: upgrade the storage adapter and @mastra/core");
4996
+ }
4997
+ /**
4998
+ * Resolve attached-storage context within a bounded retry window, including failed reads.
4999
+ * Exhaustion returns null for missing anchors or throws the last read error for the exporter to report.
5000
+ * Other destinations receive the original event independently.
5001
+ */
5002
+ async function resolveStorageAnnotation(event, storage, flushSpans) {
5003
+ const record = event.type === "score" ? event.score : event.feedback;
5004
+ if (record.correlationContext !== void 0) return event;
5005
+ if (!record.traceId) return null;
5006
+ let lastReadFailure;
5007
+ for (const delay of LOOKUP_DELAYS_MS) {
5008
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
5009
+ let trace;
5010
+ try {
5011
+ trace = await storage.getTrace({ traceId: record.traceId });
5012
+ lastReadFailure = void 0;
5013
+ } catch (error) {
5014
+ lastReadFailure = { error };
5015
+ }
5016
+ if (trace) {
5017
+ const resolved = resolveRecordedEventFromTrace(trace, event);
5018
+ if (resolved) return resolved;
5019
+ }
5020
+ if (delay === 0) await flushSpans();
5021
+ }
5022
+ if (lastReadFailure) throw lastReadFailure.error;
5023
+ return null;
5024
+ }
5025
+ // src/exporters/default.ts
5026
+ /**
5027
+ * Resolves the final tracing storage strategy based on config and observability store hints
5028
+ */
5029
+ function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
5030
+ const observabilityStrategy = observabilityStorage.observabilityStrategy;
5031
+ if (config.strategy && config.strategy !== "auto") {
5032
+ if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
5033
+ logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
5034
+ userStrategy: config.strategy,
5035
+ storageAdapter: storageName,
5036
+ supportedStrategies: observabilityStrategy.supported,
5037
+ fallbackStrategy: observabilityStrategy.preferred
5038
+ });
5039
+ }
5040
+ return observabilityStrategy.preferred;
5041
+ }
5042
+ const FLUSH_SUCCEEDED$1 = { failed: false };
5043
+ /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
5044
+ const MAX_FLUSH_ROUNDS$1 = 3;
5045
+ /**
5046
+ * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
5047
+ * This class is preserved unchanged so existing integrations (including code
5048
+ * that matches on the `mastra-default-observability-exporter` exporter name)
5049
+ * keep working. It will be removed in a future major version.
5050
+ *
5051
+ * Default storage-backed exporter. Buffers observability events and flushes them
5052
+ * in batches to the configured ObservabilityStorage backend with retry support.
5053
+ */
5054
+ var DefaultExporter = class extends BaseExporter {
5055
+ name = "mastra-default-observability-exporter";
5056
+ #config;
5057
+ #isInitializing = false;
5058
+ #initPromises = /* @__PURE__ */ new Set();
5059
+ #eventBuffer;
5060
+ #storage;
5061
+ #observabilityStorage;
5062
+ #resolvedStrategy;
5063
+ #flushTimer;
5064
+ /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5065
+ #inFlightFlushes = /* @__PURE__ */ new Set();
5066
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5067
+ #feedbackWrites = new KeyedQueue();
5068
+ #emitDropEvent;
5069
+ #unsupportedSignals = /* @__PURE__ */ new Set();
5070
+ constructor(config = {}) {
5071
+ super(config);
5072
+ this.#config = {
5073
+ ...config,
5074
+ maxBatchSize: config.maxBatchSize ?? 1e3,
5075
+ maxBufferSize: config.maxBufferSize ?? 1e4,
5076
+ maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
5077
+ maxRetries: config.maxRetries ?? 4,
5078
+ retryDelayMs: config.retryDelayMs ?? 500,
5079
+ strategy: config.strategy ?? "auto"
5080
+ };
5081
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5082
+ }
5083
+ /**
5084
+ * Initialize the exporter (called after all dependencies are ready)
5085
+ */
5086
+ async init(options) {
5087
+ try {
5088
+ this.#isInitializing = true;
5089
+ this.#emitDropEvent = options.emitDropEvent;
5090
+ this.#storage = options.mastra?.getStorage();
5091
+ if (!this.#storage) {
5092
+ this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
5093
+ return;
5094
+ }
5095
+ this.#observabilityStorage = await this.#storage.getStore("observability");
5096
+ if (!this.#observabilityStorage) {
5097
+ this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
5098
+ return;
5099
+ }
5100
+ if (!this.#resolvedStrategy) {
5101
+ this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
5102
+ this.logger.debug("tracing storage exporter initialized", {
5103
+ strategy: this.#resolvedStrategy,
5104
+ source: this.#config.strategy !== "auto" ? "user" : "auto",
5105
+ storageAdapter: this.#storage.constructor.name,
5106
+ maxBatchSize: this.#config.maxBatchSize,
5107
+ maxBatchWaitMs: this.#config.maxBatchWaitMs
5108
+ });
5109
+ }
5110
+ if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
5111
+ } finally {
5112
+ this.#isInitializing = false;
5113
+ /**
5114
+ * Assumes caller waits until export of a parent span is completed before calling
5115
+ * export for child spans , order is not relevant for resolve
5116
+ */
5117
+ this.#initPromises.forEach((resolve) => {
5118
+ resolve();
5119
+ });
5120
+ this.#initPromises.clear();
5121
+ }
5122
+ }
5123
+ /**
5124
+ * Checks if buffer should be flushed based on size or time triggers
5125
+ */
5126
+ shouldFlush() {
5127
+ if (this.#resolvedStrategy === "realtime") return true;
5128
+ if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5129
+ if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
5130
+ if (this.#eventBuffer.totalSize > 0) {
5131
+ if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
5132
+ }
5133
+ return false;
5134
+ }
5135
+ /**
5136
+ * Schedules a flush using setTimeout
5137
+ */
5138
+ scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
5139
+ if (this.#flushTimer) clearTimeout(this.#flushTimer);
5140
+ this.#flushTimer = setTimeout(() => {
5141
+ this.#flushTimer = void 0;
5142
+ this.trackFlushBuffer().catch((error) => {
5143
+ this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5144
+ });
5145
+ }, delayMs);
5146
+ }
5147
+ retryDelay(retryAttempt) {
5148
+ return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5149
+ }
5150
+ retryAttempt(events) {
5151
+ return events.reduce((earliestAttempt, event) => {
5152
+ if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
5153
+ return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
5154
+ }, void 0);
5155
+ }
5156
+ logStorageFailure(signal, events, retryAttempt, error) {
5157
+ this.logger.warn("Failed to persist observability events", {
5158
+ signal,
5159
+ eventCount: events.length,
5160
+ retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
5161
+ maxRetries: this.#config.maxRetries,
5162
+ ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
5163
+ error: error instanceof Error ? error.message : String(error)
5164
+ });
5165
+ }
5166
+ /**
5167
+ * Checks flush triggers and schedules/triggers flush as needed.
5168
+ * Called after adding any event to the buffer.
5169
+ * Returns the flush promise when flushing so callers can await it.
5170
+ */
5171
+ async handleBatchedFlush() {
5172
+ if (this.shouldFlush()) await this.trackFlushBuffer();
5173
+ else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5174
+ }
5175
+ sanitizeDropError(error) {
5176
+ if (error instanceof MastraError) return {
5177
+ id: error.id,
5178
+ domain: String(error.domain),
5179
+ message: error.message
5180
+ };
5181
+ if (error instanceof Error) return { message: error.message };
5182
+ return { message: String(error) };
5183
+ }
5184
+ emitDrop(signal, reason, count, error) {
5185
+ if (count === 0) return;
5186
+ const dropEvent = {
5187
+ type: "drop",
5188
+ signal,
5189
+ reason,
5190
+ count,
5191
+ timestamp: /* @__PURE__ */ new Date(),
5192
+ exporterName: this.name,
5193
+ ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
5194
+ ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
5195
+ };
4771
5196
  this.#emitDropEvent?.(dropEvent);
4772
5197
  }
4773
5198
  /**
@@ -4912,7 +5337,10 @@ var DefaultExporter = class extends BaseExporter {
4912
5337
  case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
4913
5338
  }
4914
5339
  const flushResults = await Promise.all([
4915
- this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => buildFeedbackRecord(f)) })),
5340
+ this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
5341
+ feedbacks: events.map((f) => buildFeedbackRecord(f)),
5342
+ onConflict: "ignore"
5343
+ })),
4916
5344
  this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
4917
5345
  this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
4918
5346
  this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
@@ -4989,22 +5417,55 @@ var DefaultExporter = class extends BaseExporter {
4989
5417
  this.#eventBuffer.addEvent(event);
4990
5418
  await this.handleBatchedFlush();
4991
5419
  }
4992
- /**
4993
- * Handle score events — buffer for batch flush.
4994
- */
4995
- async onScoreEvent(event) {
4996
- await this.waitForInit();
4997
- if (!this.#observabilityStorage) return;
4998
- this.#eventBuffer.addEvent(event);
4999
- await this.handleBatchedFlush();
5420
+ onScoreEvent(event) {
5421
+ return this.enqueueAnnotation(event);
5000
5422
  }
5001
- /**
5002
- * Handle feedback events — buffer for batch flush.
5003
- */
5004
- async onFeedbackEvent(event) {
5423
+ onFeedbackReviewStatusEvent(event) {
5424
+ return this.enqueueAnnotation(event);
5425
+ }
5426
+ onFeedbackReplacementEvent(event) {
5427
+ return this.enqueueAnnotation(event);
5428
+ }
5429
+ onFeedbackEvent(event) {
5430
+ return this.enqueueAnnotation(event);
5431
+ }
5432
+ enqueueAnnotation(event) {
5433
+ const feedbackId = event.type === "score" ? void 0 : event.feedback.feedbackId;
5434
+ const pending = feedbackId ? this.#feedbackWrites.enqueue(feedbackId, () => this.storeAnnotation(event)) : this.storeAnnotation(event);
5435
+ this.#pendingAnnotations.add(pending);
5436
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
5437
+ return pending;
5438
+ }
5439
+ async storeAnnotation(event) {
5005
5440
  await this.waitForInit();
5006
5441
  if (!this.#observabilityStorage) return;
5007
- this.#eventBuffer.addEvent(event);
5442
+ if (event.type === "feedback_review_status") {
5443
+ await this.flushBufferedEvents();
5444
+ await updateStorageFeedbackReviewStatus(this.#observabilityStorage, event.feedback, this.logger);
5445
+ return;
5446
+ }
5447
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
5448
+ await Promise.allSettled([...this.#inFlightFlushes]);
5449
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5450
+ });
5451
+ if (!resolved) {
5452
+ const record = event.type === "score" ? event.score : event.feedback;
5453
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
5454
+ eventType: event.type,
5455
+ traceId: record.traceId,
5456
+ spanId: record.spanId
5457
+ });
5458
+ return;
5459
+ }
5460
+ if (resolved.type === "feedback_replacement") {
5461
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
5462
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
5463
+ return;
5464
+ }
5465
+ await this.#observabilityStorage.replaceFeedback({ feedback: buildFeedbackRecord(resolved) });
5466
+ return;
5467
+ }
5468
+ this.#eventBuffer.addEvent(resolved);
5008
5469
  await this.handleBatchedFlush();
5009
5470
  }
5010
5471
  /**
@@ -5013,6 +5474,10 @@ var DefaultExporter = class extends BaseExporter {
5013
5474
  * are exported before the runtime instance is terminated.
5014
5475
  */
5015
5476
  async flush() {
5477
+ await Promise.allSettled([...this.#pendingAnnotations]);
5478
+ await this.flushBufferedEvents();
5479
+ }
5480
+ async flushBufferedEvents() {
5016
5481
  for (let round = 0; round < MAX_FLUSH_ROUNDS$1; round++) {
5017
5482
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5018
5483
  if (this.#eventBuffer.totalSize > 0) {
@@ -5162,6 +5627,8 @@ var MastraStorageExporter = class extends BaseExporter {
5162
5627
  #flushTimer;
5163
5628
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5164
5629
  #inFlightFlushes = /* @__PURE__ */ new Set();
5630
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5631
+ #feedbackWrites = new KeyedQueue();
5165
5632
  #emitDropEvent;
5166
5633
  #unsupportedSignals = /* @__PURE__ */ new Set();
5167
5634
  constructor(config = {}) {
@@ -5532,7 +5999,10 @@ var MastraStorageExporter = class extends BaseExporter {
5532
5999
  case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5533
6000
  }
5534
6001
  const createTasks = [
5535
- () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => buildFeedbackRecord(f)) })),
6002
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
6003
+ feedbacks: events.map((f) => buildFeedbackRecord(f)),
6004
+ onConflict: "ignore"
6005
+ })),
5536
6006
  () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
5537
6007
  () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
5538
6008
  () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
@@ -5613,22 +6083,55 @@ var MastraStorageExporter = class extends BaseExporter {
5613
6083
  this.#eventBuffer.addEvent(event);
5614
6084
  await this.handleBatchedFlush();
5615
6085
  }
5616
- /**
5617
- * Handle score events — buffer for batch flush.
5618
- */
5619
- async onScoreEvent(event) {
5620
- await this.ensureInitialized();
5621
- if (!this.#observabilityStorage) return;
5622
- this.#eventBuffer.addEvent(event);
5623
- await this.handleBatchedFlush();
6086
+ onScoreEvent(event) {
6087
+ return this.enqueueAnnotation(event);
5624
6088
  }
5625
- /**
5626
- * Handle feedback events — buffer for batch flush.
5627
- */
5628
- async onFeedbackEvent(event) {
6089
+ onFeedbackReviewStatusEvent(event) {
6090
+ return this.enqueueAnnotation(event);
6091
+ }
6092
+ onFeedbackReplacementEvent(event) {
6093
+ return this.enqueueAnnotation(event);
6094
+ }
6095
+ onFeedbackEvent(event) {
6096
+ return this.enqueueAnnotation(event);
6097
+ }
6098
+ enqueueAnnotation(event) {
6099
+ const feedbackId = event.type === "score" ? void 0 : event.feedback.feedbackId;
6100
+ const pending = feedbackId ? this.#feedbackWrites.enqueue(feedbackId, () => this.storeAnnotation(event)) : this.storeAnnotation(event);
6101
+ this.#pendingAnnotations.add(pending);
6102
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
6103
+ return pending;
6104
+ }
6105
+ async storeAnnotation(event) {
5629
6106
  await this.ensureInitialized();
5630
6107
  if (!this.#observabilityStorage) return;
5631
- this.#eventBuffer.addEvent(event);
6108
+ if (event.type === "feedback_review_status") {
6109
+ await this.flushBufferedEvents();
6110
+ await updateStorageFeedbackReviewStatus(this.#observabilityStorage, event.feedback, this.logger);
6111
+ return;
6112
+ }
6113
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
6114
+ await Promise.allSettled([...this.#inFlightFlushes]);
6115
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
6116
+ });
6117
+ if (!resolved) {
6118
+ const record = event.type === "score" ? event.score : event.feedback;
6119
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
6120
+ eventType: event.type,
6121
+ traceId: record.traceId,
6122
+ spanId: record.spanId
6123
+ });
6124
+ return;
6125
+ }
6126
+ if (resolved.type === "feedback_replacement") {
6127
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
6128
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
6129
+ return;
6130
+ }
6131
+ await this.#observabilityStorage.replaceFeedback({ feedback: buildFeedbackRecord(resolved) });
6132
+ return;
6133
+ }
6134
+ this.#eventBuffer.addEvent(resolved);
5632
6135
  await this.handleBatchedFlush();
5633
6136
  }
5634
6137
  /**
@@ -5637,6 +6140,10 @@ var MastraStorageExporter = class extends BaseExporter {
5637
6140
  * are exported before the runtime instance is terminated.
5638
6141
  */
5639
6142
  async flush() {
6143
+ await Promise.allSettled([...this.#pendingAnnotations]);
6144
+ await this.flushBufferedEvents();
6145
+ }
6146
+ async flushBufferedEvents() {
5640
6147
  if (this.#byteTracker) {
5641
6148
  if (!this.#observabilityStorage) return;
5642
6149
  this.#byteDrainers++;
@@ -6063,8 +6570,9 @@ var BaseObservabilityInstance = class extends MastraBase {
6063
6570
  * Internal hook used by RecordedTrace/RecordedSpan hydration to route
6064
6571
  * non-tracing annotation events back through the normal exporter pipeline.
6065
6572
  */
6066
- __emitRecordedEvent(event) {
6067
- this.emitObservabilityEvent(event);
6573
+ __emitRecordedEvent(event, shouldHandle) {
6574
+ if (shouldHandle) this.observabilityBus.emit(event, shouldHandle);
6575
+ else this.emitObservabilityEvent(event);
6068
6576
  }
6069
6577
  /**
6070
6578
  * Internal hook used by the client observability proxy (`client/`)
@@ -8647,6 +9155,41 @@ var PlatformByteBatcher = class {
8647
9155
  };
8648
9156
  }
8649
9157
  };
9158
+ // src/exporters/platform-resolved-record.ts
9159
+ /** Deliver one feedback or score record whose span context must be resolved by Platform. */
9160
+ async function publishResolvedRecord(url, body, headers, method = "POST") {
9161
+ const deadline = AbortSignal.timeout(3e4);
9162
+ for (let attempt = 0; attempt < 6; attempt++) {
9163
+ const response = await fetch(url, {
9164
+ method,
9165
+ headers,
9166
+ body,
9167
+ signal: deadline
9168
+ });
9169
+ if (response.ok) {
9170
+ await response.body?.cancel();
9171
+ return;
9172
+ }
9173
+ const error = await response.json().catch(() => null);
9174
+ const code = error?.code ?? error?.error?.code;
9175
+ if (!(method === "PATCH" ? response.status === 404 && code === "FEEDBACK_NOT_FOUND" || response.status === 503 && code === "FEEDBACK_LOOKUP_UNAVAILABLE" : response.status === 404 && (code === "TRACE_NOT_FOUND" || code === "SPAN_NOT_FOUND") || response.status === 503 && code === "ANCHOR_LOOKUP_UNAVAILABLE") || attempt === 5) throw new Error(`Platform record delivery failed: HTTP ${response.status}${code ? ` (${code})` : ""}`);
9176
+ const retryAfter = response.headers.get("retry-after");
9177
+ const retryAfterMs = retryAfter ? /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now() : 0;
9178
+ const delay = Math.max(Math.min(500 * 2 ** attempt, 4e3), Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
9179
+ await new Promise((resolve, reject) => {
9180
+ deadline.throwIfAborted();
9181
+ const timer = setTimeout(() => {
9182
+ deadline.removeEventListener("abort", abort);
9183
+ resolve();
9184
+ }, Math.min(delay, 3e4));
9185
+ function abort() {
9186
+ clearTimeout(timer);
9187
+ reject(deadline.reason);
9188
+ }
9189
+ deadline.addEventListener("abort", abort, { once: true });
9190
+ });
9191
+ }
9192
+ }
8650
9193
  // src/exporters/mastra-platform.ts
8651
9194
  const SIGNAL_PUBLISH_SUFFIXES = {
8652
9195
  traces: "/spans/publish",
@@ -8766,6 +9309,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8766
9309
  buffer;
8767
9310
  flushTimer = null;
8768
9311
  inFlightFlushes = /* @__PURE__ */ new Set();
9312
+ pendingRecords = /* @__PURE__ */ new Set();
9313
+ feedbackUpdates = new KeyedQueue();
8769
9314
  quotaPaused = false;
8770
9315
  quotaProbeTimer = null;
8771
9316
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
@@ -8802,6 +9347,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8802
9347
  maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
8803
9348
  maxRetries: config.maxRetries ?? 3,
8804
9349
  accessToken: accessToken || "",
9350
+ projectId,
8805
9351
  tracesEndpoint,
8806
9352
  logsEndpoint: resolveConfiguredSignalEndpoint("logs", config.logsEndpoint),
8807
9353
  metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config.metricsEndpoint),
@@ -8843,17 +9389,73 @@ var MastraPlatformExporter = class extends BaseExporter {
8843
9389
  await this.handleBufferedEvent();
8844
9390
  }
8845
9391
  async onScoreEvent(event) {
8846
- if (this.isDisabled) return;
9392
+ if (this.isDisabled || this.shuttingDown) return;
9393
+ if (event.score.correlationContext == null) {
9394
+ this.enqueueResolvedRecord("score", event.score);
9395
+ return;
9396
+ }
8847
9397
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8848
9398
  this.addScoreToBuffer(event);
8849
9399
  await this.handleBufferedEvent();
8850
9400
  }
8851
9401
  async onFeedbackEvent(event) {
8852
- if (this.isDisabled) return;
9402
+ if (this.isDisabled || this.shuttingDown) return;
9403
+ if (event.feedback.correlationContext == null) {
9404
+ this.enqueueResolvedRecord("feedback", event.feedback);
9405
+ return;
9406
+ }
8853
9407
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8854
9408
  this.addFeedbackToBuffer(event);
8855
9409
  await this.handleBufferedEvent();
8856
9410
  }
9411
+ onFeedbackReplacementEvent(event) {
9412
+ if (this.isDisabled || this.shuttingDown) return;
9413
+ if (!event.feedback.feedbackId?.trim()) {
9414
+ this.logger.warn("Dropping feedback replacement: feedbackId is required");
9415
+ return;
9416
+ }
9417
+ this.enqueueResolvedRecord("feedback", event.feedback, event.feedback.feedbackId);
9418
+ }
9419
+ onFeedbackReviewStatusEvent(event) {
9420
+ if (this.isDisabled || this.shuttingDown) return;
9421
+ const { feedbackId, reviewStatus } = event.feedback;
9422
+ if (!feedbackId?.trim() || !["needs-review", "reviewed"].includes(reviewStatus)) {
9423
+ this.logger.warn("Dropping feedback review update: feedbackId and reviewStatus are required");
9424
+ return;
9425
+ }
9426
+ const url = new URL(`/api/observability/feedback/${encodeURIComponent(feedbackId)}/review-status`, this.platformConfig.feedbackEndpoint);
9427
+ this.enqueueInteractiveWrite("feedback", url, JSON.stringify({ reviewStatus }), "PATCH", feedbackId);
9428
+ }
9429
+ enqueueResolvedRecord(kind, record, replacementId) {
9430
+ if (!record.traceId?.trim()) {
9431
+ this.logger.warn(`Dropping ${kind}: context resolution requires traceId`);
9432
+ return;
9433
+ }
9434
+ let body;
9435
+ try {
9436
+ body = JSON.stringify({ [kind]: record });
9437
+ } catch (error) {
9438
+ this.logger.warn(`Dropping unserializable ${kind}`, { error });
9439
+ return;
9440
+ }
9441
+ const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9442
+ const url = new URL(`/api/observability/${kind === "score" ? "scores" : "feedback"}`, collectorEndpoint);
9443
+ if (replacementId !== void 0) url.pathname += `/${encodeURIComponent(replacementId)}`;
9444
+ this.enqueueInteractiveWrite(kind, url, body, replacementId !== void 0 ? "PUT" : "POST", replacementId);
9445
+ }
9446
+ enqueueInteractiveWrite(kind, url, body, method, feedbackId) {
9447
+ const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9448
+ const projectId = new URL(collectorEndpoint).pathname.match(/\/projects\/([^/]+)\/ai\//)?.[1] ?? this.platformConfig.projectId;
9449
+ const headers = {
9450
+ Authorization: `Bearer ${this.platformConfig.accessToken}`,
9451
+ "Content-Type": "application/json",
9452
+ ...projectId ? { "X-Mastra-Project-Id": projectId } : {}
9453
+ };
9454
+ this.flushBatches().catch((error) => this.logger.warn("Failed to flush buffered telemetry", { error }));
9455
+ const send = () => publishResolvedRecord(url, body, headers, method);
9456
+ const pending = (feedbackId !== void 0 ? this.feedbackUpdates.enqueue(feedbackId, send) : send()).catch((error) => this.logger.warn(`Dropping ${kind} after Platform delivery failed`, { error })).finally(() => this.pendingRecords.delete(pending));
9457
+ this.pendingRecords.add(pending);
9458
+ }
8857
9459
  addToBuffer(event) {
8858
9460
  if (this.byteBatcher) {
8859
9461
  this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
@@ -9194,6 +9796,13 @@ var MastraPlatformExporter = class extends BaseExporter {
9194
9796
  * are exported before the runtime instance is terminated.
9195
9797
  */
9196
9798
  async flush() {
9799
+ if (this.isDisabled) return;
9800
+ do {
9801
+ await this.flushBatches();
9802
+ await Promise.allSettled([...this.pendingRecords]);
9803
+ } while (this.pendingRecords.size > 0 || this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0 || (this.byteBatcher?.getStats().pendingBytes ?? 0) > 0);
9804
+ }
9805
+ async flushBatches() {
9197
9806
  if (this.isDisabled) return;
9198
9807
  if (this.byteBatcher) {
9199
9808
  await this.byteBatcher.flush();
@@ -10151,458 +10760,154 @@ var TestExporter = class extends BaseExporter {
10151
10760
  /**
10152
10761
  * Check if a value is an __or__ marker object
10153
10762
  */
10154
- #isOrMarker(value) {
10155
- return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10156
- }
10157
- /**
10158
- * Check if a value is an __any__ marker object
10159
- */
10160
- #isAnyMarker(value) {
10161
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10162
- if (!("__any__" in value)) return false;
10163
- const constraint = value.__any__;
10164
- return constraint === true || [
10165
- "string",
10166
- "number",
10167
- "boolean",
10168
- "object",
10169
- "array"
10170
- ].includes(constraint);
10171
- }
10172
- /**
10173
- * Check if a key should be skipped during comparison (metadata keys like __structure__)
10174
- */
10175
- #isMetadataKey(key) {
10176
- return key.startsWith("__") && key.endsWith("__");
10177
- }
10178
- /**
10179
- * Custom JSON replacer to handle Date objects and other special types
10180
- */
10181
- #jsonReplacer = (_key, value) => {
10182
- if (value instanceof Date) return value.toISOString();
10183
- return value;
10184
- };
10185
- /**
10186
- * Get all stored debug logs (internal exporter logging, not signal logs)
10187
- */
10188
- getLogs() {
10189
- return [...this.#debugLogs];
10190
- }
10191
- /**
10192
- * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10193
- */
10194
- dumpLogs() {
10195
- console.error("\n=== TestExporter Logs ===");
10196
- this.#debugLogs.forEach((log) => {
10197
- console.error(log);
10198
- });
10199
- console.error("=== End Logs ===\n");
10200
- }
10201
- /**
10202
- * Validate final state - useful for test assertions
10203
- *
10204
- * @returns Object with validation results
10205
- */
10206
- validateFinalState() {
10207
- const traceIds = this.getTraceIds();
10208
- const incompleteSpans = this.getIncompleteSpans();
10209
- const singleTraceId = traceIds.length === 1;
10210
- const allSpansComplete = incompleteSpans.length === 0;
10211
- return {
10212
- valid: singleTraceId && allSpansComplete,
10213
- singleTraceId,
10214
- allSpansComplete,
10215
- traceIds,
10216
- incompleteSpans
10217
- };
10763
+ #isOrMarker(value) {
10764
+ return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10218
10765
  }
10219
10766
  /**
10220
- * Clear all collected events and state across all signals
10767
+ * Check if a value is an __any__ marker object
10221
10768
  */
10222
- clearEvents() {
10223
- this.#tracingEvents = [];
10224
- this.#spanStates.clear();
10225
- this.#logEvents = [];
10226
- this.#metricEvents = [];
10227
- this.#scoreEvents = [];
10228
- this.#feedbackEvents = [];
10229
- this.#debugLogs = [];
10769
+ #isAnyMarker(value) {
10770
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10771
+ if (!("__any__" in value)) return false;
10772
+ const constraint = value.__any__;
10773
+ return constraint === true || [
10774
+ "string",
10775
+ "number",
10776
+ "boolean",
10777
+ "object",
10778
+ "array"
10779
+ ].includes(constraint);
10230
10780
  }
10231
10781
  /**
10232
- * Alias for clearEvents (compatibility with TestExporter)
10782
+ * Check if a key should be skipped during comparison (metadata keys like __structure__)
10233
10783
  */
10234
- reset() {
10235
- this.clearEvents();
10784
+ #isMetadataKey(key) {
10785
+ return key.startsWith("__") && key.endsWith("__");
10236
10786
  }
10237
10787
  /**
10238
- * Get internal metrics about the exporter's own activity.
10788
+ * Custom JSON replacer to handle Date objects and other special types
10239
10789
  */
10240
- getInternalMetrics() {
10241
- const json = this.toJSON({
10242
- includeEvents: false,
10243
- includeStats: false
10244
- });
10245
- return {
10246
- startedAt: this.#internalMetrics.startedAt,
10247
- lastEventAt: this.#internalMetrics.lastEventAt,
10248
- totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10249
- bySignal: { ...this.#internalMetrics.bySignal },
10250
- flushCount: this.#internalMetrics.flushCount,
10251
- estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10252
- };
10253
- }
10790
+ #jsonReplacer = (_key, value) => {
10791
+ if (value instanceof Date) return value.toISOString();
10792
+ return value;
10793
+ };
10254
10794
  /**
10255
- * Flush buffered data and log internal metrics summary.
10795
+ * Get all stored debug logs (internal exporter logging, not signal logs)
10256
10796
  */
10257
- async flush() {
10258
- this.#internalMetrics.flushCount++;
10259
- if (this.#config.logMetricsOnFlush) {
10260
- const metrics = this.getInternalMetrics();
10261
- const uptimeMs = Date.now() - metrics.startedAt.getTime();
10262
- const summary = [
10263
- `[TestExporter] flush #${metrics.flushCount} summary:`,
10264
- ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10265
- ` total events received: ${metrics.totalEventsReceived}`,
10266
- ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10267
- ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10268
- ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10269
- ].join("\n");
10270
- this.logger.info(summary);
10271
- }
10272
- }
10273
- async shutdown() {
10274
- await this.flush();
10275
- this.logger.info("TestExporter shutdown");
10797
+ getLogs() {
10798
+ return [...this.#debugLogs];
10276
10799
  }
10277
10800
  /**
10278
- * Extract unique spans from a list of events
10801
+ * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10279
10802
  */
10280
- #getUniqueSpansFromEvents(events) {
10281
- const spanMap = /* @__PURE__ */ new Map();
10282
- for (const event of events) {
10283
- const span = event.exportedSpan;
10284
- if (event.type === TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10285
- }
10286
- return Array.from(spanMap.values());
10287
- }
10288
- };
10289
- /**
10290
- * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10291
- */
10292
- const JsonExporter = TestExporter;
10293
- // src/instances/default.ts
10294
- var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10295
- constructor(config) {
10296
- super(config);
10297
- }
10298
- createSpan(options) {
10299
- return new DefaultSpan(options, this);
10300
- }
10301
- };
10302
- // src/recorded.ts
10303
- function nullToUndefined(value) {
10304
- return value ?? void 0;
10305
- }
10306
- function mergeMetadata(base, extra) {
10307
- if (!base && !extra) return void 0;
10308
- return {
10309
- ...base ?? {},
10310
- ...extra ?? {}
10311
- };
10312
- }
10313
- function normalizeErrorInfo(error) {
10314
- if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
10315
- return {
10316
- message: error.message,
10317
- id: "id" in error && typeof error.id === "string" ? error.id : void 0,
10318
- name: "name" in error && typeof error.name === "string" ? error.name : void 0,
10319
- stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
10320
- domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
10321
- category: "category" in error && typeof error.category === "string" ? error.category : void 0,
10322
- details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
10323
- };
10324
- }
10325
- function buildCorrelationContext(span, rootSpan, parent) {
10326
- return {
10327
- tags: rootSpan.tags ?? void 0,
10328
- entityType: nullToUndefined(span.entityType),
10329
- entityId: nullToUndefined(span.entityId),
10330
- entityName: nullToUndefined(span.entityName),
10331
- parentEntityType: parent?.entityType ?? void 0,
10332
- parentEntityId: parent?.entityId ?? void 0,
10333
- parentEntityName: parent?.entityName ?? void 0,
10334
- rootEntityType: nullToUndefined(rootSpan.entityType),
10335
- rootEntityId: nullToUndefined(rootSpan.entityId),
10336
- rootEntityName: nullToUndefined(rootSpan.entityName),
10337
- userId: nullToUndefined(span.userId),
10338
- organizationId: nullToUndefined(span.organizationId),
10339
- resourceId: nullToUndefined(span.resourceId),
10340
- runId: nullToUndefined(span.runId),
10341
- sessionId: nullToUndefined(span.sessionId),
10342
- threadId: nullToUndefined(span.threadId),
10343
- requestId: nullToUndefined(span.requestId),
10344
- environment: nullToUndefined(span.environment),
10345
- source: nullToUndefined(span.source),
10346
- serviceName: nullToUndefined(span.serviceName),
10347
- experimentId: nullToUndefined(span.experimentId)
10348
- };
10349
- }
10350
- function buildScoreEvent(args) {
10351
- const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
10352
- return {
10353
- type: "score",
10354
- score: {
10355
- scoreId: generateSignalId(),
10356
- timestamp: /* @__PURE__ */ new Date(),
10357
- traceId,
10358
- spanId,
10359
- scorerId: score.scorerId,
10360
- scorerName: score.scorerName,
10361
- scorerVersion: score.scorerVersion,
10362
- source: score.source,
10363
- scoreSource: score.scoreSource,
10364
- score: score.score,
10365
- reason: score.reason,
10366
- experimentId: score.experimentId,
10367
- scoreTraceId: score.scoreTraceId,
10368
- targetEntityType: score.targetEntityType,
10369
- correlationContext,
10370
- metadata: mergeMetadata(inheritedMetadata, score.metadata)
10371
- }
10372
- };
10373
- }
10374
- function buildFeedbackEvent(args) {
10375
- const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
10376
- return {
10377
- type: "feedback",
10378
- feedback: {
10379
- feedbackId: generateSignalId(),
10380
- timestamp: /* @__PURE__ */ new Date(),
10381
- traceId,
10382
- spanId,
10383
- source: feedback.source,
10384
- feedbackSource: feedback.feedbackSource,
10385
- feedbackType: feedback.feedbackType,
10386
- value: feedback.value,
10387
- userId: feedback.userId,
10388
- feedbackUserId: feedback.feedbackUserId,
10389
- comment: feedback.comment,
10390
- sourceId: feedback.sourceId,
10391
- experimentId: feedback.experimentId,
10392
- correlationContext,
10393
- metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
10394
- }
10395
- };
10396
- }
10397
- function findSpanById(spans, spanId) {
10398
- if (!spanId) return void 0;
10399
- return spans.find((span) => span.spanId === spanId);
10400
- }
10401
- function buildRecordedScoreEventFromTrace(args) {
10402
- const rootSpan = findRootSpan(args.trace.spans);
10403
- if (!rootSpan) return null;
10404
- const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
10405
- if (!span) return null;
10406
- const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
10407
- return buildScoreEvent({
10408
- traceId: span.traceId,
10409
- spanId: args.spanId,
10410
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10411
- score: args.score,
10412
- inheritedMetadata: span.metadata
10413
- });
10414
- }
10415
- function buildRecordedFeedbackEventFromTrace(args) {
10416
- const rootSpan = findRootSpan(args.trace.spans);
10417
- if (!rootSpan) return null;
10418
- const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
10419
- if (!span) return null;
10420
- const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
10421
- return buildFeedbackEvent({
10422
- traceId: span.traceId,
10423
- spanId: args.spanId,
10424
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10425
- feedback: args.feedback,
10426
- inheritedMetadata: span.metadata
10427
- });
10428
- }
10429
- var RecordedSpanImpl = class {
10430
- id;
10431
- traceId;
10432
- name;
10433
- type;
10434
- entityType;
10435
- entityId;
10436
- entityName;
10437
- startTime;
10438
- endTime;
10439
- attributes;
10440
- metadata;
10441
- tags;
10442
- input;
10443
- output;
10444
- errorInfo;
10445
- requestContext;
10446
- isEvent;
10447
- isRootSpan;
10448
- parentSpanId;
10449
- parent;
10450
- children = [];
10451
- #raw;
10452
- #rootSpan;
10453
- #emitRecordedEvent;
10454
- #canEmitRecordedEvent;
10455
- #debugRecordedAnnotationUnavailable;
10456
- constructor(args) {
10457
- const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
10458
- this.#raw = raw;
10459
- this.#rootSpan = rootSpan;
10460
- this.#emitRecordedEvent = emitRecordedEvent;
10461
- this.#canEmitRecordedEvent = canEmitRecordedEvent;
10462
- this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
10463
- this.id = raw.spanId;
10464
- this.traceId = raw.traceId;
10465
- this.name = raw.name;
10466
- this.type = raw.spanType;
10467
- this.entityType = raw.entityType ?? void 0;
10468
- this.entityId = raw.entityId ?? void 0;
10469
- this.entityName = raw.entityName ?? void 0;
10470
- this.startTime = raw.startedAt;
10471
- this.endTime = raw.endedAt ?? void 0;
10472
- this.attributes = raw.attributes ?? void 0;
10473
- this.metadata = raw.metadata ?? void 0;
10474
- this.tags = raw.tags ?? void 0;
10475
- this.input = raw.input ?? void 0;
10476
- this.output = raw.output ?? void 0;
10477
- this.errorInfo = normalizeErrorInfo(raw.error);
10478
- this.requestContext = raw.requestContext ?? void 0;
10479
- this.isEvent = raw.isEvent;
10480
- this.isRootSpan = !raw.parentSpanId;
10481
- this.parentSpanId = raw.parentSpanId ?? void 0;
10803
+ dumpLogs() {
10804
+ console.error("\n=== TestExporter Logs ===");
10805
+ this.#debugLogs.forEach((log) => {
10806
+ console.error(log);
10807
+ });
10808
+ console.error("=== End Logs ===\n");
10482
10809
  }
10483
- async addScore(score) {
10484
- if (!this.#canEmitRecordedEvent()) {
10485
- this.#debugRecordedAnnotationUnavailable({
10486
- kind: "score",
10487
- traceId: this.traceId,
10488
- spanId: this.id
10489
- });
10490
- return;
10491
- }
10492
- await this.#emitRecordedEvent(buildScoreEvent({
10493
- traceId: this.#raw.traceId,
10494
- spanId: this.id,
10495
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10496
- score,
10497
- inheritedMetadata: this.#raw.metadata
10498
- }));
10810
+ /**
10811
+ * Validate final state - useful for test assertions
10812
+ *
10813
+ * @returns Object with validation results
10814
+ */
10815
+ validateFinalState() {
10816
+ const traceIds = this.getTraceIds();
10817
+ const incompleteSpans = this.getIncompleteSpans();
10818
+ const singleTraceId = traceIds.length === 1;
10819
+ const allSpansComplete = incompleteSpans.length === 0;
10820
+ return {
10821
+ valid: singleTraceId && allSpansComplete,
10822
+ singleTraceId,
10823
+ allSpansComplete,
10824
+ traceIds,
10825
+ incompleteSpans
10826
+ };
10499
10827
  }
10500
- async addFeedback(feedback) {
10501
- if (!this.#canEmitRecordedEvent()) {
10502
- this.#debugRecordedAnnotationUnavailable({
10503
- kind: "feedback",
10504
- traceId: this.traceId,
10505
- spanId: this.id
10506
- });
10507
- return;
10508
- }
10509
- await this.#emitRecordedEvent(buildFeedbackEvent({
10510
- traceId: this.#raw.traceId,
10511
- spanId: this.id,
10512
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10513
- feedback,
10514
- inheritedMetadata: this.#raw.metadata
10515
- }));
10828
+ /**
10829
+ * Clear all collected events and state across all signals
10830
+ */
10831
+ clearEvents() {
10832
+ this.#tracingEvents = [];
10833
+ this.#spanStates.clear();
10834
+ this.#logEvents = [];
10835
+ this.#metricEvents = [];
10836
+ this.#scoreEvents = [];
10837
+ this.#feedbackEvents = [];
10838
+ this.#debugLogs = [];
10516
10839
  }
10517
- };
10518
- var RecordedTraceImpl = class {
10519
- traceId;
10520
- rootSpan;
10521
- spans;
10522
- #rootRecord;
10523
- #emitRecordedEvent;
10524
- #spanMap;
10525
- #canEmitRecordedEvent;
10526
- #debugRecordedAnnotationUnavailable;
10527
- constructor(args) {
10528
- this.traceId = args.traceId;
10529
- this.rootSpan = args.rootSpan;
10530
- this.#rootRecord = args.rootRecord;
10531
- this.spans = args.spans;
10532
- this.#emitRecordedEvent = args.emitRecordedEvent;
10533
- this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
10534
- this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
10535
- this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
10840
+ /**
10841
+ * Alias for clearEvents (compatibility with TestExporter)
10842
+ */
10843
+ reset() {
10844
+ this.clearEvents();
10536
10845
  }
10537
- getSpan(spanId) {
10538
- return this.#spanMap.get(spanId) ?? null;
10846
+ /**
10847
+ * Get internal metrics about the exporter's own activity.
10848
+ */
10849
+ getInternalMetrics() {
10850
+ const json = this.toJSON({
10851
+ includeEvents: false,
10852
+ includeStats: false
10853
+ });
10854
+ return {
10855
+ startedAt: this.#internalMetrics.startedAt,
10856
+ lastEventAt: this.#internalMetrics.lastEventAt,
10857
+ totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10858
+ bySignal: { ...this.#internalMetrics.bySignal },
10859
+ flushCount: this.#internalMetrics.flushCount,
10860
+ estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10861
+ };
10539
10862
  }
10540
- async addScore(score) {
10541
- if (!this.#canEmitRecordedEvent()) {
10542
- this.#debugRecordedAnnotationUnavailable({
10543
- kind: "score",
10544
- traceId: this.traceId
10545
- });
10546
- return;
10863
+ /**
10864
+ * Flush buffered data and log internal metrics summary.
10865
+ */
10866
+ async flush() {
10867
+ this.#internalMetrics.flushCount++;
10868
+ if (this.#config.logMetricsOnFlush) {
10869
+ const metrics = this.getInternalMetrics();
10870
+ const uptimeMs = Date.now() - metrics.startedAt.getTime();
10871
+ const summary = [
10872
+ `[TestExporter] flush #${metrics.flushCount} summary:`,
10873
+ ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10874
+ ` total events received: ${metrics.totalEventsReceived}`,
10875
+ ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10876
+ ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10877
+ ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10878
+ ].join("\n");
10879
+ this.logger.info(summary);
10547
10880
  }
10548
- await this.#emitRecordedEvent(buildScoreEvent({
10549
- traceId: this.#rootRecord.traceId,
10550
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10551
- score,
10552
- inheritedMetadata: this.#rootRecord.metadata
10553
- }));
10554
10881
  }
10555
- async addFeedback(feedback) {
10556
- if (!this.#canEmitRecordedEvent()) {
10557
- this.#debugRecordedAnnotationUnavailable({
10558
- kind: "feedback",
10559
- traceId: this.traceId
10560
- });
10561
- return;
10882
+ async shutdown() {
10883
+ await this.flush();
10884
+ this.logger.info("TestExporter shutdown");
10885
+ }
10886
+ /**
10887
+ * Extract unique spans from a list of events
10888
+ */
10889
+ #getUniqueSpansFromEvents(events) {
10890
+ const spanMap = /* @__PURE__ */ new Map();
10891
+ for (const event of events) {
10892
+ const span = event.exportedSpan;
10893
+ if (event.type === TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10562
10894
  }
10563
- await this.#emitRecordedEvent(buildFeedbackEvent({
10564
- traceId: this.#rootRecord.traceId,
10565
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10566
- feedback,
10567
- inheritedMetadata: this.#rootRecord.metadata
10568
- }));
10895
+ return Array.from(spanMap.values());
10569
10896
  }
10570
10897
  };
10571
- function findRootSpan(spans) {
10572
- const spanIds = new Set(spans.map((span) => span.spanId));
10573
- return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
10574
- }
10575
- function hydrateRecordedTrace(args) {
10576
- const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
10577
- const rootSpan = findRootSpan(trace.spans);
10578
- if (!rootSpan) return null;
10579
- const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
10580
- raw,
10581
- rootSpan,
10582
- emitRecordedEvent,
10583
- canEmitRecordedEvent,
10584
- debugRecordedAnnotationUnavailable
10585
- }));
10586
- const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
10587
- for (const span of recordedSpans) {
10588
- if (!span.parentSpanId) continue;
10589
- const parent = spanMap.get(span.parentSpanId);
10590
- if (!parent) continue;
10591
- span.parent = parent;
10592
- parent.children.push(span);
10898
+ /**
10899
+ * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10900
+ */
10901
+ const JsonExporter = TestExporter;
10902
+ // src/instances/default.ts
10903
+ var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10904
+ constructor(config) {
10905
+ super(config);
10593
10906
  }
10594
- const hydratedRootSpan = spanMap.get(rootSpan.spanId);
10595
- if (!hydratedRootSpan) return null;
10596
- return new RecordedTraceImpl({
10597
- traceId: trace.traceId,
10598
- rootSpan: hydratedRootSpan,
10599
- rootRecord: rootSpan,
10600
- spans: recordedSpans,
10601
- emitRecordedEvent,
10602
- canEmitRecordedEvent,
10603
- debugRecordedAnnotationUnavailable
10604
- });
10605
- }
10907
+ createSpan(options) {
10908
+ return new DefaultSpan(options, this);
10909
+ }
10910
+ };
10606
10911
  // src/registry.ts
10607
10912
  /**
10608
10913
  * Registry for Observability instances.
@@ -10909,23 +11214,6 @@ function isInstance(obj) {
10909
11214
  return obj instanceof BaseObservabilityInstance;
10910
11215
  }
10911
11216
  /**
10912
- * Delays (ms) between attempts to rehydrate a trace from storage when an
10913
- * annotation (score/feedback) targets a span that has not been flushed by
10914
- * the configured exporters yet. Exporters buffer and flush asynchronously:
10915
- * by default they flush at 1000 spans or after a 5000ms wait
10916
- * (`maxBatchWaitMs`), so an annotation emitted right after a span ends can
10917
- * race the flush and be silently dropped. The schedule below sums to
10918
- * ~5.85s, covering the default flush interval with margin.
10919
- */
10920
- const RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS = [
10921
- 100,
10922
- 250,
10923
- 500,
10924
- 1e3,
10925
- 2e3,
10926
- 2e3
10927
- ];
10928
- /**
10929
11217
  * Manages observability instances and selects their configurations for Mastra operations.
10930
11218
  * Configure instances and exporters to collect and export telemetry.
10931
11219
  *
@@ -10952,6 +11240,7 @@ var Observability = class extends MastraBase {
10952
11240
  #registry = new ObservabilityRegistry();
10953
11241
  #mastra;
10954
11242
  #clientObservabilityProxy;
11243
+ #pendingPersistedEvents = /* @__PURE__ */ new Set();
10955
11244
  constructor(config) {
10956
11245
  super({
10957
11246
  component: RegisteredLogger.OBSERVABILITY,
@@ -11092,50 +11381,57 @@ var Observability = class extends MastraBase {
11092
11381
  async addScore(args) {
11093
11382
  const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11094
11383
  const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11095
- if (args.correlationContext) {
11096
- await this.#emitRecordedEvent(buildScoreEvent({
11097
- ...targetTraceId ? { traceId: targetTraceId } : {},
11098
- ...targetSpanId ? { spanId: targetSpanId } : {},
11099
- correlationContext: args.correlationContext,
11100
- score: args.score
11101
- }));
11102
- return;
11103
- }
11104
- if (!args.traceId) return;
11105
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedScoreEventFromTrace({
11106
- trace,
11107
- spanId: args.spanId,
11108
- score: args.score
11384
+ if (!targetTraceId && !args.correlationContext) return;
11385
+ await this.#emitRecordedEvent(buildScoreEvent({
11386
+ ...args,
11387
+ traceId: targetTraceId,
11388
+ spanId: targetSpanId
11109
11389
  }));
11110
- if (!event) {
11111
- this.logger?.warn(`Score event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11112
- return;
11113
- }
11114
- await this.#emitRecordedEvent(event);
11115
11390
  }
11116
11391
  async addFeedback(args) {
11117
- const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11118
- const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11119
- if (args.correlationContext) {
11120
- await this.#emitRecordedEvent(buildFeedbackEvent({
11121
- ...targetTraceId ? { traceId: targetTraceId } : {},
11122
- ...targetSpanId ? { spanId: targetSpanId } : {},
11123
- correlationContext: args.correlationContext,
11124
- feedback: args.feedback
11125
- }));
11126
- return;
11127
- }
11128
- if (!args.traceId) return;
11129
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedFeedbackEventFromTrace({
11130
- trace,
11131
- spanId: args.spanId,
11132
- feedback: args.feedback
11392
+ const traceId = args.traceId ?? args.correlationContext?.traceId;
11393
+ const spanId = args.spanId ?? args.correlationContext?.spanId;
11394
+ if (!traceId && !args.correlationContext) return;
11395
+ await this.#emitRecordedEvent(buildFeedbackEvent({
11396
+ ...args,
11397
+ traceId,
11398
+ spanId
11133
11399
  }));
11134
- if (!event) {
11135
- this.logger?.warn(`Feedback event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11136
- return;
11137
- }
11138
- await this.#emitRecordedEvent(event);
11400
+ }
11401
+ async replaceFeedback(args) {
11402
+ if (!args.traceId?.trim() || !args.feedback.feedbackId?.trim() || !Number.isFinite(args.feedback.timestamp?.getTime())) throw new Error("Feedback replacement requires traceId, feedbackId, and the original timestamp");
11403
+ await this.#emitRecordedEvent({
11404
+ type: "feedback_replacement",
11405
+ feedback: {
11406
+ ...args.feedback,
11407
+ traceId: args.traceId,
11408
+ spanId: args.spanId,
11409
+ correlationContext: args.correlationContext
11410
+ }
11411
+ });
11412
+ }
11413
+ async updateFeedbackReviewStatus(args) {
11414
+ if (!args.feedbackId?.trim() || !["needs-review", "reviewed"].includes(args.reviewStatus)) throw new Error("Feedback review update requires feedbackId and a valid reviewStatus");
11415
+ await this.#emitRecordedEvent({
11416
+ type: "feedback_review_status",
11417
+ feedback: {
11418
+ feedbackId: args.feedbackId,
11419
+ reviewStatus: args.reviewStatus
11420
+ }
11421
+ });
11422
+ }
11423
+ /** @internal Queue an HTTP-created record; flush/shutdown await delivery without holding the HTTP response open. */
11424
+ async __exportPersistedEvent(event) {
11425
+ const storageExporters = new Set(this.#getRecordedTraceInstance()?.getExporters().filter(isMastraBuiltInStorageExporter));
11426
+ const pending = this.#emitRecordedEvent(event, (handler) => !storageExporters.has(handler));
11427
+ this.#pendingPersistedEvents.add(pending);
11428
+ pending.then(() => this.#pendingPersistedEvents.delete(pending), (error) => {
11429
+ this.#pendingPersistedEvents.delete(pending);
11430
+ this.logger.error("Failed to notify exporters of persisted feedback/score", {
11431
+ error,
11432
+ eventType: event.type
11433
+ });
11434
+ });
11139
11435
  }
11140
11436
  /** Register a named observability instance, optionally marking it as default. */
11141
11437
  registerInstance(name, instance, isDefault = false) {
@@ -11172,12 +11468,18 @@ var Observability = class extends MastraBase {
11172
11468
  }
11173
11469
  /** Flush all registered instances without shutting down. */
11174
11470
  async flush() {
11471
+ await this.#drainPersistedEvents();
11175
11472
  await this.#registry.flush();
11176
11473
  }
11177
11474
  /** Shut down all registered instances, flushing any pending data. */
11178
11475
  async shutdown() {
11476
+ await this.#drainPersistedEvents();
11179
11477
  await this.#registry.shutdown();
11180
11478
  }
11479
+ /** Let custom handlers finish filling exporter buffers before the instance lifecycle drains them. */
11480
+ async #drainPersistedEvents() {
11481
+ while (this.#pendingPersistedEvents.size > 0) await Promise.allSettled([...this.#pendingPersistedEvents]);
11482
+ }
11181
11483
  /**
11182
11484
  * Returns the proxy responsible for client observability (W3C trace
11183
11485
  * context injection + OTLP/JSON payload reception for spans/logs
@@ -11199,40 +11501,22 @@ var Observability = class extends MastraBase {
11199
11501
  if (!storage) return null;
11200
11502
  return await storage.getStore("observability") ?? null;
11201
11503
  }
11202
- /**
11203
- * Build a recorded score/feedback event from storage, retrying briefly to
11204
- * ride out the async exporter flush: annotations emitted right after a
11205
- * span ends can otherwise race the flush and be silently dropped.
11206
- */
11207
- async #buildRecordedEventWithRetry(traceId, build) {
11208
- for (const delayMs of [0, ...RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS]) {
11209
- if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
11210
- const trace = await this.#getStoredTrace(traceId);
11211
- const event = trace ? build(trace) : null;
11212
- if (event) return event;
11213
- }
11214
- return null;
11215
- }
11216
- async #getStoredTrace(traceId) {
11217
- const observabilityStorage = await this.#getObservabilityStorage();
11218
- if (!observabilityStorage) return null;
11219
- return observabilityStorage.getTrace({ traceId });
11220
- }
11221
11504
  #getRecordedTraceInstance() {
11222
11505
  return this.getDefaultInstance() ?? Array.from(this.listInstances().values())[0];
11223
11506
  }
11224
- async #emitRecordedEvent(event) {
11507
+ /** Dispatch independently; the standard bus tracks delivery, while custom instances return handler promises. */
11508
+ async #emitRecordedEvent(event, shouldHandle) {
11225
11509
  const instance = this.#getRecordedTraceInstance();
11226
11510
  if (!instance) {
11227
11511
  this.logger?.debug(event.type === "score" ? "Score event was dropped because no observability instance is registered" : "Feedback event was dropped because no observability instance is registered", { eventType: event.type });
11228
11512
  return;
11229
11513
  }
11230
11514
  if (instance instanceof BaseObservabilityInstance) {
11231
- instance.__emitRecordedEvent(event);
11515
+ instance.__emitRecordedEvent(event, shouldHandle);
11232
11516
  return;
11233
11517
  }
11234
11518
  const bridge = instance.getBridge();
11235
- const handlerResults = [...instance.getExporters().map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
11519
+ const handlerResults = [...instance.getExporters().filter((exporter) => !shouldHandle || shouldHandle(exporter)).map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge && (!shouldHandle || shouldHandle(bridge)) ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
11236
11520
  if (handlerResults.length > 0) await Promise.allSettled(handlerResults);
11237
11521
  }
11238
11522
  };
@@ -11296,6 +11580,6 @@ const observabilityFeatures = /* @__PURE__ */ new Set(["model-inference-span", "
11296
11580
  function buildTracingOptions(...updaters) {
11297
11581
  return updaters.reduce((opts, updater) => updater(opts), {});
11298
11582
  }
11299
- export { BaseExporter, BaseObservabilityEventBus, BaseObservabilityInstance, BaseSpan, CardinalityFilter, CloudExporter, ConsoleExporter, DEFAULT_DEEP_CLEAN_OPTIONS, DEFAULT_LIMITS, DefaultExporter, DefaultObservabilityInstance, DefaultSpan, JsonExporter, LoggerContextImpl, MastraPlatformExporter, MastraStorageExporter, MetricsContextImpl, ModelSpanTracker, NoOpSpan, OBSERVABILITY_CAPABILITIES_HEADER, Observability, ObservabilityBus, QUOTA_PAUSE_CAPABILITY, SamplingStrategyType, SensitiveDataFilter, TestExporter, TraceData, TrackingExporter, buildExportedLog, buildExportedSpan, buildTracingOptions, chainFormatters, createClientObservabilityProxy, decodeResourceLogs, decodeResourceSpans, deepClean, formatBaggage, formatTraceparent, getExternalParentId, isSerializedMap, mergeSerializationOptions, observabilityConfigValueSchema, observabilityFeatures, observabilityInstanceConfigSchema, observabilityRegistryConfigSchema, otlpSeverityToLogLevel, parseBaggage, parseTraceparent, reconstructSerializedMap, routeToHandler, samplingStrategySchema, serializationOptionsSchema, truncateString };
11583
+ export { BaseExporter, BaseObservabilityEventBus, BaseObservabilityInstance, BaseSpan, CardinalityFilter, CloudExporter, ConsoleExporter, DEFAULT_DEEP_CLEAN_OPTIONS, DEFAULT_LIMITS, DefaultExporter, DefaultObservabilityInstance, DefaultSpan, JsonExporter, LoggerContextImpl, MastraPlatformExporter, MastraStorageExporter, MetricsContextImpl, ModelSpanTracker, NoOpSpan, OBSERVABILITY_CAPABILITIES_HEADER, Observability, ObservabilityBus, QUOTA_PAUSE_CAPABILITY, REDACTED_ERROR_MESSAGE, SamplingStrategyType, SensitiveDataFilter, TestExporter, TraceData, TrackingExporter, buildExportedLog, buildExportedSpan, buildTracingOptions, chainFormatters, createClientObservabilityProxy, decodeResourceLogs, decodeResourceSpans, deepClean, formatBaggage, formatTraceparent, getExternalParentId, isSerializedMap, mergeSerializationOptions, observabilityConfigValueSchema, observabilityFeatures, observabilityInstanceConfigSchema, observabilityRegistryConfigSchema, otlpSeverityToLogLevel, parseBaggage, parseTraceparent, reconstructSerializedMap, redactErrorInfo, routeToHandler, samplingStrategySchema, serializationOptionsSchema, truncateString };
11300
11584
 
11301
11585
  //# sourceMappingURL=index.js.map