@mastra/observability 1.24.0-alpha.5 → 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.
package/dist/index.cjs CHANGED
@@ -77,6 +77,9 @@ function routeToHandler(handler, event, logger) {
77
77
  }), handler.name, "score", logger);
78
78
  }
79
79
  break;
80
+ case "feedback_review_status":
81
+ if (handler.onFeedbackReviewStatusEvent) return catchAsyncResult(handler.onFeedbackReviewStatusEvent(event), handler.name, "feedback review status", logger);
82
+ break;
80
83
  case "feedback_replacement":
81
84
  if (handler.onFeedbackReplacementEvent) return catchAsyncResult(handler.onFeedbackReplacementEvent(event), handler.name, "feedback replacement", logger);
82
85
  break;
@@ -580,6 +583,10 @@ function cleanEvent(event, options) {
580
583
  type: "score",
581
584
  score: deepClean(event.score, options)
582
585
  };
586
+ case "feedback_review_status": return {
587
+ type: event.type,
588
+ feedback: deepClean(event.feedback, options)
589
+ };
583
590
  case "feedback_replacement": return {
584
591
  type: event.type,
585
592
  feedback: deepClean(event.feedback, options)
@@ -3451,6 +3458,34 @@ function mergeMetadata$1(parentMetadata, metadata) {
3451
3458
  }
3452
3459
  }
3453
3460
  // src/spans/base.ts
3461
+ /** Replaces error text exported from traces that hide input or output. */
3462
+ const REDACTED_ERROR_MESSAGE = "[REDACTED]";
3463
+ /**
3464
+ * The error as exported from a trace that hides input or output: keeps what
3465
+ * identifies the error (id, name, domain, category, stack frames) and drops
3466
+ * text and free-form details, which can quote the hidden data.
3467
+ */
3468
+ function redactErrorInfo(errorInfo, stackMessage) {
3469
+ if (!errorInfo) return errorInfo;
3470
+ const { id, name, domain, category, stack } = errorInfo;
3471
+ return {
3472
+ ...id !== void 0 ? { id } : {},
3473
+ ...name !== void 0 ? { name } : {},
3474
+ ...domain !== void 0 ? { domain } : {},
3475
+ ...category !== void 0 ? { category } : {},
3476
+ message: REDACTED_ERROR_MESSAGE,
3477
+ ...stack !== void 0 ? { stack: redactStackHeader(stack, stackMessage ?? errorInfo.message, errorInfo.name) } : {}
3478
+ };
3479
+ }
3480
+ /** Preserve stack frames only when they follow the complete captured message. */
3481
+ function redactStackHeader(stack, message, name = "Error") {
3482
+ const redactedHeader = `${name}: ${REDACTED_ERROR_MESSAGE}`;
3483
+ const separator = `: ${message}`;
3484
+ const separatorIndex = stack.indexOf(separator);
3485
+ if (separatorIndex <= 0 || stack.slice(0, separatorIndex).includes("\n")) return redactedHeader;
3486
+ const suffix = stack.slice(separatorIndex + separator.length);
3487
+ return suffix === "" || suffix.startsWith("\n") ? `${redactedHeader}${suffix}` : redactedHeader;
3488
+ }
3454
3489
  const LINEAGE_KEYS = [
3455
3490
  "parentEntityType",
3456
3491
  "parentEntityId",
@@ -3580,6 +3615,7 @@ var BaseSpan = class BaseSpan {
3580
3615
  stopReason;
3581
3616
  stopReasonContext;
3582
3617
  errorInfo;
3618
+ errorStackMessage;
3583
3619
  metadata;
3584
3620
  requestContext;
3585
3621
  tags;
@@ -3967,7 +4003,7 @@ var BaseSpan = class BaseSpan {
3967
4003
  endTime: this.endTime,
3968
4004
  input: hideInput ? void 0 : this.input,
3969
4005
  output: hideOutput ? void 0 : this.output,
3970
- errorInfo: this.errorInfo,
4006
+ errorInfo: hideInput || hideOutput ? redactErrorInfo(this.errorInfo, this.errorStackMessage) : this.errorInfo,
3971
4007
  ...this.outcome !== void 0 ? { outcome: this.outcome } : {},
3972
4008
  ...this.stopReason !== void 0 ? { stopReason: this.stopReason } : {},
3973
4009
  ...this.stopReasonContext !== void 0 ? { stopReasonContext: this.stopReasonContext } : {},
@@ -4119,6 +4155,8 @@ var DefaultSpan = class extends BaseSpan {
4119
4155
  };
4120
4156
  if (!this.isExcluded) {
4121
4157
  const apiDetails = apiCallErrorDetails(error);
4158
+ const stackError = error instanceof _mastra_core_error.MastraError && error.cause instanceof Error && error.cause.stack ? error.cause : error;
4159
+ this.errorStackMessage = stackError.message;
4122
4160
  this.errorInfo = deepClean(error instanceof _mastra_core_error.MastraError ? {
4123
4161
  id: error.id,
4124
4162
  details: apiDetails ? {
@@ -4129,7 +4167,7 @@ var DefaultSpan = class extends BaseSpan {
4129
4167
  domain: error.domain,
4130
4168
  message: error.message,
4131
4169
  name: error.name,
4132
- stack: error.cause instanceof Error && error.cause.stack || error.stack
4170
+ stack: stackError.stack
4133
4171
  } : {
4134
4172
  message: error.message,
4135
4173
  name: error.name,
@@ -4631,6 +4669,20 @@ var EventBuffer = class {
4631
4669
  });
4632
4670
  }
4633
4671
  };
4672
+ // src/exporters/keyed-queue.ts
4673
+ /** Keep writes to one record ordered without blocking unrelated records. */
4674
+ var KeyedQueue = class {
4675
+ pending = /* @__PURE__ */ new Map();
4676
+ enqueue(key, write) {
4677
+ const current = (this.pending.get(key) ?? Promise.resolve()).catch(() => {}).then(write);
4678
+ this.pending.set(key, current);
4679
+ const cleanup = () => {
4680
+ if (this.pending.get(key) === current) this.pending.delete(key);
4681
+ };
4682
+ current.then(cleanup, cleanup);
4683
+ return current;
4684
+ }
4685
+ };
4634
4686
  // src/recorded.ts
4635
4687
  function nullToUndefined(value) {
4636
4688
  return value ?? void 0;
@@ -4957,6 +5009,16 @@ const LOOKUP_DELAYS_MS = [
4957
5009
  2e3,
4958
5010
  2e3
4959
5011
  ];
5012
+ /** Older stores may inherit a method that throws instead of omitting the hook. */
5013
+ async function updateStorageFeedbackReviewStatus(storage, feedback, logger) {
5014
+ if (typeof storage.updateFeedbackReviewStatus === "function") try {
5015
+ await storage.updateFeedbackReviewStatus(feedback);
5016
+ return;
5017
+ } catch (error) {
5018
+ if (typeof error !== "object" || error === null || !("id" in error) || error.id !== "OBSERVABILITY_STORAGE_UPDATE_FEEDBACK_REVIEW_STATUS_NOT_IMPLEMENTED") throw error;
5019
+ }
5020
+ logger.warn("Storage exporter skipped feedback review update: upgrade the storage adapter and @mastra/core");
5021
+ }
4960
5022
  /**
4961
5023
  * Resolve attached-storage context within a bounded retry window, including failed reads.
4962
5024
  * Exhaustion returns null for missing anchors or throws the last read error for the exporter to report.
@@ -5027,6 +5089,7 @@ var DefaultExporter = class extends BaseExporter {
5027
5089
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5028
5090
  #inFlightFlushes = /* @__PURE__ */ new Set();
5029
5091
  #pendingAnnotations = /* @__PURE__ */ new Set();
5092
+ #feedbackWrites = new KeyedQueue();
5030
5093
  #emitDropEvent;
5031
5094
  #unsupportedSignals = /* @__PURE__ */ new Set();
5032
5095
  constructor(config = {}) {
@@ -5382,6 +5445,9 @@ var DefaultExporter = class extends BaseExporter {
5382
5445
  onScoreEvent(event) {
5383
5446
  return this.enqueueAnnotation(event);
5384
5447
  }
5448
+ onFeedbackReviewStatusEvent(event) {
5449
+ return this.enqueueAnnotation(event);
5450
+ }
5385
5451
  onFeedbackReplacementEvent(event) {
5386
5452
  return this.enqueueAnnotation(event);
5387
5453
  }
@@ -5389,7 +5455,8 @@ var DefaultExporter = class extends BaseExporter {
5389
5455
  return this.enqueueAnnotation(event);
5390
5456
  }
5391
5457
  enqueueAnnotation(event) {
5392
- const pending = this.storeAnnotation(event);
5458
+ const feedbackId = event.type === "score" ? void 0 : event.feedback.feedbackId;
5459
+ const pending = feedbackId ? this.#feedbackWrites.enqueue(feedbackId, () => this.storeAnnotation(event)) : this.storeAnnotation(event);
5393
5460
  this.#pendingAnnotations.add(pending);
5394
5461
  pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
5395
5462
  return pending;
@@ -5397,6 +5464,11 @@ var DefaultExporter = class extends BaseExporter {
5397
5464
  async storeAnnotation(event) {
5398
5465
  await this.waitForInit();
5399
5466
  if (!this.#observabilityStorage) return;
5467
+ if (event.type === "feedback_review_status") {
5468
+ await this.flushBufferedEvents();
5469
+ await updateStorageFeedbackReviewStatus(this.#observabilityStorage, event.feedback, this.logger);
5470
+ return;
5471
+ }
5400
5472
  const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
5401
5473
  await Promise.allSettled([...this.#inFlightFlushes]);
5402
5474
  if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
@@ -5428,6 +5500,9 @@ var DefaultExporter = class extends BaseExporter {
5428
5500
  */
5429
5501
  async flush() {
5430
5502
  await Promise.allSettled([...this.#pendingAnnotations]);
5503
+ await this.flushBufferedEvents();
5504
+ }
5505
+ async flushBufferedEvents() {
5431
5506
  for (let round = 0; round < MAX_FLUSH_ROUNDS$1; round++) {
5432
5507
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5433
5508
  if (this.#eventBuffer.totalSize > 0) {
@@ -5578,6 +5653,7 @@ var MastraStorageExporter = class extends BaseExporter {
5578
5653
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5579
5654
  #inFlightFlushes = /* @__PURE__ */ new Set();
5580
5655
  #pendingAnnotations = /* @__PURE__ */ new Set();
5656
+ #feedbackWrites = new KeyedQueue();
5581
5657
  #emitDropEvent;
5582
5658
  #unsupportedSignals = /* @__PURE__ */ new Set();
5583
5659
  constructor(config = {}) {
@@ -6035,6 +6111,9 @@ var MastraStorageExporter = class extends BaseExporter {
6035
6111
  onScoreEvent(event) {
6036
6112
  return this.enqueueAnnotation(event);
6037
6113
  }
6114
+ onFeedbackReviewStatusEvent(event) {
6115
+ return this.enqueueAnnotation(event);
6116
+ }
6038
6117
  onFeedbackReplacementEvent(event) {
6039
6118
  return this.enqueueAnnotation(event);
6040
6119
  }
@@ -6042,7 +6121,8 @@ var MastraStorageExporter = class extends BaseExporter {
6042
6121
  return this.enqueueAnnotation(event);
6043
6122
  }
6044
6123
  enqueueAnnotation(event) {
6045
- const pending = this.storeAnnotation(event);
6124
+ const feedbackId = event.type === "score" ? void 0 : event.feedback.feedbackId;
6125
+ const pending = feedbackId ? this.#feedbackWrites.enqueue(feedbackId, () => this.storeAnnotation(event)) : this.storeAnnotation(event);
6046
6126
  this.#pendingAnnotations.add(pending);
6047
6127
  pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
6048
6128
  return pending;
@@ -6050,6 +6130,11 @@ var MastraStorageExporter = class extends BaseExporter {
6050
6130
  async storeAnnotation(event) {
6051
6131
  await this.ensureInitialized();
6052
6132
  if (!this.#observabilityStorage) return;
6133
+ if (event.type === "feedback_review_status") {
6134
+ await this.flushBufferedEvents();
6135
+ await updateStorageFeedbackReviewStatus(this.#observabilityStorage, event.feedback, this.logger);
6136
+ return;
6137
+ }
6053
6138
  const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
6054
6139
  await Promise.allSettled([...this.#inFlightFlushes]);
6055
6140
  if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
@@ -6081,6 +6166,9 @@ var MastraStorageExporter = class extends BaseExporter {
6081
6166
  */
6082
6167
  async flush() {
6083
6168
  await Promise.allSettled([...this.#pendingAnnotations]);
6169
+ await this.flushBufferedEvents();
6170
+ }
6171
+ async flushBufferedEvents() {
6084
6172
  if (this.#byteTracker) {
6085
6173
  if (!this.#observabilityStorage) return;
6086
6174
  this.#byteDrainers++;
@@ -9109,7 +9197,7 @@ async function publishResolvedRecord(url, body, headers, method = "POST") {
9109
9197
  }
9110
9198
  const error = await response.json().catch(() => null);
9111
9199
  const code = error?.code ?? error?.error?.code;
9112
- if (!(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})` : ""}`);
9200
+ 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})` : ""}`);
9113
9201
  const retryAfter = response.headers.get("retry-after");
9114
9202
  const retryAfterMs = retryAfter ? /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now() : 0;
9115
9203
  const delay = Math.max(Math.min(500 * 2 ** attempt, 4e3), Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
@@ -9247,6 +9335,7 @@ var MastraPlatformExporter = class extends BaseExporter {
9247
9335
  flushTimer = null;
9248
9336
  inFlightFlushes = /* @__PURE__ */ new Set();
9249
9337
  pendingRecords = /* @__PURE__ */ new Set();
9338
+ feedbackUpdates = new KeyedQueue();
9250
9339
  quotaPaused = false;
9251
9340
  quotaProbeTimer = null;
9252
9341
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
@@ -9352,6 +9441,16 @@ var MastraPlatformExporter = class extends BaseExporter {
9352
9441
  }
9353
9442
  this.enqueueResolvedRecord("feedback", event.feedback, event.feedback.feedbackId);
9354
9443
  }
9444
+ onFeedbackReviewStatusEvent(event) {
9445
+ if (this.isDisabled || this.shuttingDown) return;
9446
+ const { feedbackId, reviewStatus } = event.feedback;
9447
+ if (!feedbackId?.trim() || !["needs-review", "reviewed"].includes(reviewStatus)) {
9448
+ this.logger.warn("Dropping feedback review update: feedbackId and reviewStatus are required");
9449
+ return;
9450
+ }
9451
+ const url = new URL(`/api/observability/feedback/${encodeURIComponent(feedbackId)}/review-status`, this.platformConfig.feedbackEndpoint);
9452
+ this.enqueueInteractiveWrite("feedback", url, JSON.stringify({ reviewStatus }), "PATCH", feedbackId);
9453
+ }
9355
9454
  enqueueResolvedRecord(kind, record, replacementId) {
9356
9455
  if (!record.traceId?.trim()) {
9357
9456
  this.logger.warn(`Dropping ${kind}: context resolution requires traceId`);
@@ -9367,6 +9466,10 @@ var MastraPlatformExporter = class extends BaseExporter {
9367
9466
  const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9368
9467
  const url = new URL(`/api/observability/${kind === "score" ? "scores" : "feedback"}`, collectorEndpoint);
9369
9468
  if (replacementId !== void 0) url.pathname += `/${encodeURIComponent(replacementId)}`;
9469
+ this.enqueueInteractiveWrite(kind, url, body, replacementId !== void 0 ? "PUT" : "POST", replacementId);
9470
+ }
9471
+ enqueueInteractiveWrite(kind, url, body, method, feedbackId) {
9472
+ const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9370
9473
  const projectId = new URL(collectorEndpoint).pathname.match(/\/projects\/([^/]+)\/ai\//)?.[1] ?? this.platformConfig.projectId;
9371
9474
  const headers = {
9372
9475
  Authorization: `Bearer ${this.platformConfig.accessToken}`,
@@ -9374,7 +9477,8 @@ var MastraPlatformExporter = class extends BaseExporter {
9374
9477
  ...projectId ? { "X-Mastra-Project-Id": projectId } : {}
9375
9478
  };
9376
9479
  this.flushBatches().catch((error) => this.logger.warn("Failed to flush buffered telemetry", { error }));
9377
- const pending = publishResolvedRecord(url, body, headers, replacementId !== void 0 ? "PUT" : "POST").catch((error) => this.logger.warn(`Dropping ${kind} after Platform delivery failed`, { error })).finally(() => this.pendingRecords.delete(pending));
9480
+ const send = () => publishResolvedRecord(url, body, headers, method);
9481
+ 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));
9378
9482
  this.pendingRecords.add(pending);
9379
9483
  }
9380
9484
  addToBuffer(event) {
@@ -11331,6 +11435,16 @@ var Observability = class extends _mastra_core_base.MastraBase {
11331
11435
  }
11332
11436
  });
11333
11437
  }
11438
+ async updateFeedbackReviewStatus(args) {
11439
+ if (!args.feedbackId?.trim() || !["needs-review", "reviewed"].includes(args.reviewStatus)) throw new Error("Feedback review update requires feedbackId and a valid reviewStatus");
11440
+ await this.#emitRecordedEvent({
11441
+ type: "feedback_review_status",
11442
+ feedback: {
11443
+ feedbackId: args.feedbackId,
11444
+ reviewStatus: args.reviewStatus
11445
+ }
11446
+ });
11447
+ }
11334
11448
  /** @internal Queue an HTTP-created record; flush/shutdown await delivery without holding the HTTP response open. */
11335
11449
  async __exportPersistedEvent(event) {
11336
11450
  const storageExporters = new Set(this.#getRecordedTraceInstance()?.getExporters().filter(isMastraBuiltInStorageExporter));
@@ -11514,6 +11628,7 @@ exports.OBSERVABILITY_CAPABILITIES_HEADER = OBSERVABILITY_CAPABILITIES_HEADER;
11514
11628
  exports.Observability = Observability;
11515
11629
  exports.ObservabilityBus = ObservabilityBus;
11516
11630
  exports.QUOTA_PAUSE_CAPABILITY = QUOTA_PAUSE_CAPABILITY;
11631
+ exports.REDACTED_ERROR_MESSAGE = REDACTED_ERROR_MESSAGE;
11517
11632
  exports.SamplingStrategyType = SamplingStrategyType;
11518
11633
  exports.SensitiveDataFilter = SensitiveDataFilter;
11519
11634
  exports.TestExporter = TestExporter;
@@ -11540,6 +11655,7 @@ exports.otlpSeverityToLogLevel = otlpSeverityToLogLevel;
11540
11655
  exports.parseBaggage = parseBaggage;
11541
11656
  exports.parseTraceparent = parseTraceparent;
11542
11657
  exports.reconstructSerializedMap = reconstructSerializedMap;
11658
+ exports.redactErrorInfo = redactErrorInfo;
11543
11659
  exports.routeToHandler = routeToHandler;
11544
11660
  exports.samplingStrategySchema = samplingStrategySchema;
11545
11661
  exports.serializationOptionsSchema = serializationOptionsSchema;