@mastra/core
Version: 1,474 lines • 56 kB
JavaScript
import { t as EntityType } from "./storage-Cc50aQAp.js";
import { a as getOrCreateSpan } from "./utils-DU_pU5SK.js";
import { z } from "zod/v4";
// src/observability/types/outcome.ts
/** An individual execution's result, reported by its runtime (OBS-724). */
const SPAN_OUTCOMES = [
"success",
"error",
"abort",
"interrupted",
"suspend",
"limit",
"blocked",
"unknown"
];
/** Exhaustive reason registry shared by runtime validation and storage consumers. */
const SPAN_STOP_REASONS = {
max_steps: true,
max_tokens: true,
timeout: true,
runtime_error: true,
model_error: true,
caller_cancelled: true,
signal_received: true,
observer_failed: true,
context_window_exceeded: true,
guardrail: true,
content_filter: true,
approval_required: true,
stop_condition: true,
iteration_hook: true,
delegation_bail: true,
authentication: true,
authorization: true
};
// src/observability/outcome-schema.ts
const label = z.string().max(128).optional();
const reason = z.enum(Object.keys(SPAN_STOP_REASONS));
const failure = {
provider: label,
errorCode: label,
retryable: z.boolean().optional()
};
const cause = {
causeOutcome: z.enum(SPAN_OUTCOMES).optional(),
causeStopReason: reason.optional()
};
const contexts = {
max_steps: z.strictObject({
maxSteps: z.number().optional(),
completedSteps: z.number().optional()
}),
max_tokens: z.strictObject({ maxTokens: z.number().optional() }),
timeout: z.strictObject({
timeoutMs: z.number().optional(),
timeoutType: z.enum([
"step",
"total",
"firstChunk"
]).optional()
}),
runtime_error: z.strictObject(failure),
model_error: z.strictObject(failure),
caller_cancelled: z.strictObject({}),
observer_failed: z.strictObject({
observerSpanId: label,
...cause
}),
context_window_exceeded: z.strictObject({
provider: label,
errorCode: label,
contextWindow: z.number().optional()
}),
guardrail: z.strictObject({ processorId: label }),
content_filter: z.strictObject({ provider: label }),
approval_required: z.strictObject({
toolCallId: label,
toolName: label
}),
signal_received: z.strictObject({
signalId: label,
signalType: z.enum([
"user",
"state",
"reactive",
"notification"
]).optional()
}),
stop_condition: z.strictObject({}),
iteration_hook: z.strictObject({ feedbackCompleted: z.boolean().optional() }),
delegation_bail: z.strictObject(cause),
authentication: z.strictObject(failure),
authorization: z.strictObject(failure)
};
/** @internal Allowlist tooltip facts for framework producers, including untyped runtime inputs. */
function compactStopReasonContext(stopReason, context) {
if (!stopReason || !Object.hasOwn(contexts, stopReason) || !context || typeof context !== "object") return null;
try {
const result = {};
for (const [key, schema] of Object.entries(contexts[stopReason].shape)) {
const value = context[key];
const parsed = schema.safeParse(value);
if (parsed.success && parsed.data !== void 0) result[key] = parsed.data;
}
return Object.keys(result).length ? result : null;
} catch {
return null;
}
}
function termination(stopReason) {
return z.object({
outcome: z.enum(SPAN_OUTCOMES),
stopReason: z.literal(stopReason),
stopReasonContext: contexts[stopReason].nullish()
});
}
z.union([...Object.keys(SPAN_STOP_REASONS).map(termination), z.object({
outcome: z.enum(SPAN_OUTCOMES),
stopReason: z.null().optional(),
stopReasonContext: z.null().optional()
})]);
// src/observability/execution-outcome.ts
/** Read a provider's structured code without inferring a cause from diagnostic text. */
function providerFailureCode(value) {
if (typeof value.code === "string") return value.code;
let data = value.data;
if (data == null && typeof value.responseBody === "string") try {
data = JSON.parse(value.responseBody);
} catch {
return;
}
if (!data || typeof data !== "object") return void 0;
const record = data;
const error = record.error && typeof record.error === "object" ? record.error : record;
return typeof error.code === "string" ? error.code : void 0;
}
/** @internal Classify explicit failure facts, including wrapped/serialized causes. Never match error-message text. */
function executionFailureTermination(error, layer = "runtime_error") {
try {
const termination = classifyExecutionFailure(error, layer);
return {
...termination,
stopReasonContext: compactStopReasonContext(termination.stopReason, termination.stopReasonContext)
};
} catch {
return {
outcome: "error",
stopReason: layer
};
}
}
function classifyExecutionFailure(error, layer) {
const seen = /* @__PURE__ */ new Set();
let current = error;
let failure;
let modelFailure = layer === "model_error";
while (current && typeof current === "object" && !seen.has(current)) {
seen.add(current);
const value = current;
if (value.status === "failed" && value.error && typeof value.error === "object") {
current = value.error;
continue;
}
if (value.name === "TripWire" && (value.processorId === void 0 || typeof value.processorId === "string") && value.options && typeof value.options === "object" && typeof value.message === "string") {
const options = value.options;
return tripwireTermination({
processorId: value.processorId,
reason: value.message,
...options
});
}
failure = value;
if (value.name === "MastraTimeoutError" && typeof value.timeoutMs === "number") return {
outcome: "limit",
stopReason: "timeout",
stopReasonContext: {
timeoutMs: value.timeoutMs,
...value.timeoutType === "step" || value.timeoutType === "total" || value.timeoutType === "firstChunk" ? { timeoutType: value.timeoutType } : {}
}
};
if (value.name === "FGADeniedError") return {
outcome: "blocked",
stopReason: "authorization"
};
const apiError = value[Symbol.for("vercel.ai.error.AI_APICallError")] === true || value.name === "AI_APICallError";
if (apiError) modelFailure = true;
if (apiError && (value.statusCode === 401 || value.statusCode === 403)) return {
outcome: "blocked",
stopReason: value.statusCode === 401 ? "authentication" : "authorization",
stopReasonContext: {
errorCode: String(value.statusCode),
provider: typeof value.provider === "string" ? value.provider : void 0
}
};
if (apiError) {
const errorCode = providerFailureCode(value);
if (errorCode === "content_filter") return {
outcome: "blocked",
stopReason: "content_filter",
stopReasonContext: { provider: typeof value.provider === "string" ? value.provider : void 0 }
};
if (errorCode === "context_length_exceeded" || errorCode === "context_window_exceeded") return {
outcome: "limit",
stopReason: "context_window_exceeded",
stopReasonContext: { errorCode }
};
}
current = value.cause;
}
return {
outcome: "error",
stopReason: modelFailure ? "model_error" : "runtime_error",
stopReasonContext: {
provider: typeof failure?.provider === "string" ? failure.provider : void 0,
errorCode: typeof failure?.code === "string" ? failure.code : typeof failure?.id === "string" ? failure.id : void 0,
retryable: typeof failure?.isRetryable === "boolean" ? failure.isRetryable : void 0
}
};
}
/** Link to the observer's diagnostics without copying its payload into the interrupted span. */
function tripwireTermination(tripwire) {
try {
const metadata = tripwire?.metadata;
const observer = metadata && typeof metadata === "object" && "observerFailure" in metadata ? metadata.observerFailure : void 0;
if (observer && typeof observer === "object" && "cause" in observer && observer.cause && typeof observer.cause === "object") {
const cause = observer.cause;
if (SPAN_OUTCOMES.includes(cause.outcome) && cause.outcome !== "success" && cause.outcome !== "suspend") return {
outcome: "interrupted",
stopReason: "observer_failed",
stopReasonContext: compactStopReasonContext("observer_failed", {
observerSpanId: "observerSpanId" in observer ? observer.observerSpanId : void 0,
causeOutcome: cause.outcome,
causeStopReason: typeof cause.stopReason === "string" && Object.hasOwn(SPAN_STOP_REASONS, cause.stopReason) ? cause.stopReason : void 0
})
};
}
return {
outcome: "blocked",
stopReason: "guardrail",
stopReasonContext: compactStopReasonContext("guardrail", { processorId: tripwire?.processorId })
};
} catch {
return {
outcome: "blocked",
stopReason: "guardrail"
};
}
}
// src/loop/shared/execution-outcome.ts
/**
* @internal
* Classify a settled agent loop using its runtime stop boundary. A provider
* finish reason refines the result; it cannot establish successful execution
* without a continuation decision. Call only after finish-time work succeeds.
*/
function agentLoopTermination(input) {
const { stopCause, finishReason, maxSteps, tripwire } = input;
if (tripwire || finishReason === "tripwire") return tripwireTermination(tripwire);
if (finishReason === "suspended") {
const suspension = input.suspension;
if (suspension?.approvalRequired) return {
outcome: "suspend",
stopReason: "approval_required",
stopReasonContext: compactStopReasonContext("approval_required", {
toolCallId: suspension.toolCallId,
toolName: suspension.toolName
})
};
return {
outcome: "suspend",
stopReason: null,
stopReasonContext: null
};
}
if (finishReason === "length") return {
outcome: "limit",
stopReason: "max_tokens"
};
if (finishReason === "content-filter") return {
outcome: "blocked",
stopReason: "content_filter"
};
if (finishReason === "abort" || finishReason === "aborted") return {
outcome: "abort",
stopReason: "caller_cancelled"
};
if (finishReason === "error") return {
outcome: "error",
stopReason: "model_error"
};
switch (stopCause) {
case "max_steps": return {
outcome: "limit",
stopReason: "max_steps",
stopReasonContext: { maxSteps }
};
case "stop_condition": return {
outcome: "success",
stopReason: "stop_condition"
};
case "iteration_hook":
case "feedback_complete": return {
outcome: "success",
stopReason: "iteration_hook",
stopReasonContext: { feedbackCompleted: stopCause === "feedback_complete" }
};
case "delegation":
if (input.delegationFailure) return {
outcome: "interrupted",
stopReason: "delegation_bail",
stopReasonContext: {
causeOutcome: input.delegationFailure.outcome,
causeStopReason: input.delegationFailure.stopReason ?? void 0
}
};
return {
outcome: "success",
stopReason: "delegation_bail"
};
case "model_finished": if (finishReason === "stop" || finishReason === "tool-calls") return {
outcome: "success",
stopReason: null,
stopReasonContext: null
};
}
return {
outcome: "unknown",
stopReason: null,
stopReasonContext: null
};
}
// src/observability/no-op.ts
const noOpCounter = { add() {} };
const noOpGauge = { set() {} };
const noOpHistogram = { record() {} };
/**
* No-op tracing context used when observability is not configured.
*/
const noOpTracingContext = { currentSpan: void 0 };
/**
* No-op logger context that silently discards all log calls.
* Used when observability is not configured.
*/
const noOpLoggerContext = {
debug() {},
info() {},
warn() {},
error() {},
fatal() {}
};
/**
* No-op metrics context that silently discards all metric operations.
* Used when observability is not configured.
*/
const noOpMetricsContext = {
emit() {},
counter() {
return noOpCounter;
},
gauge() {
return noOpGauge;
},
histogram() {
return noOpHistogram;
}
};
/** No-op observability entrypoint that silently discards all operations. */
var NoOpObservability = class {
setMastraContext(_options) {}
setLogger(_options) {}
getSelectedInstance(_options) {}
async getRecordedTrace(_args) {
return null;
}
async addScore(_args) {}
async addFeedback(_args) {}
registerInstance(_name, _instance, _isDefault = false) {}
getInstance(_name) {}
getDefaultInstance() {}
listInstances() {
return /* @__PURE__ */ new Map();
}
unregisterInstance(_name) {
return false;
}
hasInstance(_name) {
return false;
}
setConfigSelector(_selector) {}
clear() {}
async flush() {}
async shutdown() {}
};
// src/observability/context-factory.ts
/**
* Derives a LoggerContext from the current span's ObservabilityInstance.
* Falls back to no-op when there is no span or the instance doesn't support logging.
*/
function deriveLoggerContext(tracing) {
const span = tracing.currentSpan;
return span?.observabilityInstance?.getLoggerContext?.(span) ?? noOpLoggerContext;
}
/**
* Derives a MetricsContext from the current span's ObservabilityInstance.
* Falls back to no-op when there is no span or the instance doesn't support metrics.
*/
function deriveMetricsContext(tracing) {
const span = tracing.currentSpan;
return span?.observabilityInstance?.getMetricsContext?.(span) ?? noOpMetricsContext;
}
/**
* Creates an observability context with real or no-op implementations for
* tracing, logging, and metrics.
*
* When a TracingContext with a current span is provided, the logger and metrics
* contexts are derived from the span's ObservabilityInstance so that log entries
* and metric data points are automatically correlated to the active trace.
*
* @param tracingContext - TracingContext with current span, or undefined for no-op
* @returns ObservabilityContext with all three signals (tracing, logger, metrics)
*/
function createObservabilityContext(tracingContext) {
const tracing = tracingContext ?? noOpTracingContext;
return {
tracing,
loggerVNext: deriveLoggerContext(tracing),
metrics: deriveMetricsContext(tracing),
tracingContext: tracing
};
}
/**
* Resolves a partial observability context (from execute params) into a
* complete ObservabilityContext with no-op defaults for any missing fields.
*
* Explicitly provided logger/metrics contexts are preserved (e.g. when set
* upstream). When missing, they are derived from the tracing context's span,
* following the same derivation logic as createObservabilityContext().
*
* @param partial - Partial context from ExecuteFunctionParams
* @returns Complete ObservabilityContext
*/
function resolveObservabilityContext(partial) {
const tracing = partial.tracing ?? partial.tracingContext ?? noOpTracingContext;
return {
tracing,
loggerVNext: partial.loggerVNext ?? deriveLoggerContext(tracing),
metrics: partial.metrics ?? deriveMetricsContext(tracing),
tracingContext: tracing
};
}
// src/observability/context.ts
const AGENT_GETTERS = ["getAgent", "getAgentById"];
const AGENT_METHODS_TO_WRAP = [
"generate",
"stream",
"generateLegacy",
"streamLegacy"
];
const WORKFLOW_GETTERS = ["getWorkflow", "getWorkflowById"];
const WORKFLOW_METHODS_TO_WRAP = [
"execute",
"createRun",
"createRun"
];
/**
* Maps a tracing proxy back to the instance it wraps. `wrapMastra` returns a
* Proxy that forwards property reads but is a distinct object identity from its
* target, so identity-sensitive lookups keyed on the Mastra instance would treat
* the proxy as a different Mastra. Cycles are impossible: a proxy's recorded
* target always existed before the proxy was created.
*/
const tracingProxyTargets = /* @__PURE__ */ new WeakMap();
/**
* Helper function to detect NoOp spans to avoid unnecessary wrapping
*/
function isNoOpSpan(span) {
return span.constructor.name === "NoOpSpan" || span.__isNoOp === true;
}
/**
* Checks to see if a passed object is an actual instance of Mastra
* (for the purposes of wrapping it for Tracing)
*/
function isMastra(mastra) {
const hasAgentGetters = AGENT_GETTERS.every((method) => typeof mastra?.[method] === "function");
const hasWorkflowGetters = WORKFLOW_GETTERS.every((method) => typeof mastra?.[method] === "function");
return hasAgentGetters && hasWorkflowGetters;
}
/**
* Creates a tracing-aware Mastra proxy that automatically injects
* tracing context into agent and workflow method calls
*/
function wrapMastra(mastra, tracingContext) {
if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) return mastra;
if (!isMastra(mastra)) return mastra;
try {
const proxy = new Proxy(mastra, { get(target, prop) {
try {
if (AGENT_GETTERS.includes(prop)) return (...args) => {
return wrapAgent(target[prop](...args), tracingContext);
};
if (WORKFLOW_GETTERS.includes(prop)) return (...args) => {
return wrapWorkflow(target[prop](...args), tracingContext);
};
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
} catch (error) {
console.warn("Tracing: Failed to wrap method, falling back to original", error);
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
}
} });
tracingProxyTargets.set(proxy, mastra);
return proxy;
} catch (error) {
console.warn("Tracing: Failed to create proxy, using original Mastra instance", error);
return mastra;
}
}
/**
* Resolve a tracing proxy back to the underlying instance. Returns the argument
* unchanged when it is not a proxy this module created. Transitive: a tool
* executed inside a traced workflow step receives an already-wrapped mastra and
* `tools/tool-builder/builder.ts` wraps it again, so nesting is real.
*/
function unwrapMastraTracingProxy(mastra) {
let current = mastra;
let target = tracingProxyTargets.get(current);
while (target) {
current = target;
target = tracingProxyTargets.get(current);
}
return current;
}
/**
* Creates a tracing-aware Agent proxy that automatically injects
* tracing context into generation method calls
*/
function wrapAgent(agent, tracingContext) {
if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) return agent;
try {
return new Proxy(agent, { get(target, prop) {
try {
if (AGENT_METHODS_TO_WRAP.includes(prop)) return (input, options = {}) => {
return target[prop](input, {
...options,
...createObservabilityContext(tracingContext)
});
};
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
} catch (error) {
console.warn("Tracing: Failed to wrap agent method, falling back to original", error);
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
}
} });
} catch (error) {
console.warn("Tracing: Failed to create agent proxy, using original instance", error);
return agent;
}
}
/**
* Creates a tracing-aware Workflow proxy that automatically injects
* tracing context into execution method calls
*/
function wrapWorkflow(workflow, tracingContext) {
if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) return workflow;
try {
return new Proxy(workflow, { get(target, prop) {
try {
if (WORKFLOW_METHODS_TO_WRAP.includes(prop)) {
if (prop === "createRun" || prop === "createRun") return async (options = {}) => {
const run = await target[prop](options);
return run ? wrapRun(run, tracingContext) : run;
};
return (input, options = {}) => {
return target[prop](input, {
...options,
...createObservabilityContext(tracingContext)
});
};
}
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
} catch (error) {
console.warn("Tracing: Failed to wrap workflow method, falling back to original", error);
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
}
} });
} catch (error) {
console.warn("Tracing: Failed to create workflow proxy, using original instance", error);
return workflow;
}
}
/**
* Creates a tracing-aware Run proxy that automatically injects
* tracing context into start method calls
*/
function wrapRun(run, tracingContext) {
if (!tracingContext.currentSpan || isNoOpSpan(tracingContext.currentSpan)) return run;
try {
return new Proxy(run, { get(target, prop) {
try {
if (prop === "start") return (startOptions = {}) => {
return target.start({
...startOptions,
...createObservabilityContext(startOptions.tracingContext ?? tracingContext)
});
};
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
} catch (error) {
console.warn("Tracing: Failed to wrap run method, falling back to original", error);
const value = target[prop];
return typeof value === "function" ? value.bind(target) : value;
}
} });
} catch (error) {
console.warn("Tracing: Failed to create run proxy, using original instance", error);
return run;
}
}
// src/observability/types/core.ts
/**
* Sampling strategy types
*/
let SamplingStrategyType = /* @__PURE__ */ function(SamplingStrategyType) {
SamplingStrategyType["ALWAYS"] = "always";
SamplingStrategyType["NEVER"] = "never";
SamplingStrategyType["RATIO"] = "ratio";
SamplingStrategyType["CUSTOM"] = "custom";
return SamplingStrategyType;
}({});
// src/observability/w3c.ts
/**
* W3C Trace Context `traceparent` parsing and formatting.
* @see https://www.w3.org/TR/trace-context/#traceparent-header
*/
const TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
/** Parses a W3C `traceparent`. Values that aren't strings, are malformed, or use all-zero IDs yield `null`. */
function parseTraceparent(value) {
if (typeof value !== "string") return null;
const match = TRACEPARENT_RE.exec(value.trim());
if (!match) return null;
const [, version, traceId, spanId, flags] = match;
if (version === "ff" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return null;
return {
version,
traceId,
spanId,
flags
};
}
/** Formats a W3C `traceparent` for a span. */
function formatTraceparent(traceId, spanId, sampled) {
return `00-${traceId}-${spanId}-${sampled ? "01" : "00"}`;
}
// src/observability/processor-span-record.ts
/** Phase names as they are shown to a reader. */
const PROCESSOR_PHASE_LABELS = {
input: "Input",
inputStep: "Input step",
llmRequest: "LLM request",
llmResponse: "LLM response",
outputStream: "Output stream",
outputResult: "Output result",
outputStep: "Output step",
toolResult: "Tool result",
requestError: "Request error"
};
/**
* The phase a processor span recorded, or `undefined` when it recorded none.
*
* Read from `attributes` rather than `spanType`, so a processor that retyped
* its span (`Processor.spanType`) still describes its payloads — the runner
* writes the same shapes either way. Spans stored before the attribute existed,
* and spans a newer version wrote with a phase this one does not know, return
* `undefined` and fall back to JSON.
*/
function describeProcessorPhase(span) {
const phase = span.attributes?.processorPhase;
return typeof phase === "string" && Object.hasOwn(PROCESSOR_PHASE_LABELS, phase) ? phase : void 0;
}
/**
* Tags a processor payload with the phase that recorded it.
*
* The payload itself is not validated, matching what `isSpanRecordOfType` and
* the other `describeSpan*` helpers already do: the typed view trusts that the
* producer for a phase wrote the shape core declares. Renderers guard each
* field they read, so a partially populated span shows what it has rather than
* losing the whole view to one unexpected value.
*/
function describeProcessorPayload(span, data) {
const phase = describeProcessorPhase(span);
if (!phase || Object.keys(data).length === 0) return void 0;
return {
phase,
phaseLabel: PROCESSOR_PHASE_LABELS[phase],
data
};
}
/** The `input` a processor span recorded, tagged by the phase that produced it. */
function describeProcessorInput(span, data) {
return describeProcessorPayload(span, data);
}
/** The `output` a processor span recorded, tagged by the phase that produced it. */
function describeProcessorOutput(span, data) {
return describeProcessorPayload(span, data);
}
/** Attribute keys `describeProcessorPipeline` accounts for. */
const PROCESSOR_PIPELINE_KEYS = [
"processorPhase",
"processorExecutor",
"processorIndex",
"hookDurationMs",
"messageListMutations",
"tripwireAbort"
];
/**
* Describes the runner-owned attributes of a processor span for rendering.
* Returns `undefined` when the span recorded no phase, so a legacy or
* non-processor span falls back to its raw attributes.
*/
function describeProcessorPipeline(span) {
const phase = describeProcessorPhase(span);
if (!phase) return void 0;
const attributes = span.attributes ?? {};
const mutations = Array.isArray(attributes.messageListMutations) ? attributes.messageListMutations : void 0;
const tripwireAbort = typeof attributes.tripwireAbort === "object" && attributes.tripwireAbort !== null ? attributes.tripwireAbort : void 0;
const presented = new Set(PROCESSOR_PIPELINE_KEYS);
if (attributes.messageListMutations !== void 0 && !mutations) presented.delete("messageListMutations");
if (attributes.tripwireAbort !== void 0 && !tripwireAbort) presented.delete("tripwireAbort");
const rest = {};
for (const [key, value] of Object.entries(attributes)) if (!presented.has(key)) rest[key] = value;
return {
phase,
phaseLabel: PROCESSOR_PHASE_LABELS[phase],
executor: attributes.processorExecutor,
processorIndex: attributes.processorIndex,
hookDurationMs: attributes.hookDurationMs,
messageListMutations: mutations,
tripwireAbort,
...Object.keys(rest).length > 0 ? { rest } : {}
};
}
// src/observability/span-record.ts
/**
* Narrows a stored span record to one or more span types, typing its
* `attributes`, `input` and `output` for that type.
*
* The check is on `spanType` only. Payloads are not validated: the typed view
* trusts that the producer for that span type wrote the shape core declares,
* the same trust `SpanTypeMap` already places in `attributes`.
*
* This module uses only the `SpanType` enum and browser-safe payload helpers
* at runtime, without pulling in the rest of the observability utilities.
*
* @example
* if (isSpanRecordOfType(span, SpanType.MODEL_GENERATION)) {
* span.attributes?.usage; // UsageStats | undefined
* }
*/
function isSpanRecordOfType(span, type) {
return Array.isArray(type) ? type.includes(span.spanType) : span.spanType === type;
}
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
const isInterrupted = (value) => value.status === "suspended" || value.status === "aborted" || value.status === "interrupted";
/** Span types whose `input` is a message list when it is an array. */
const MESSAGE_LIST_INPUT_SPANS = [
"agent_run",
"model_step",
"model_inference"
];
/**
* Describes a stored span's `input` for rendering: the value tagged by what it
* holds. Returns `undefined` when the span recorded no input.
*
* - `text`: a plain string, such as the prompt passed to an agent
* - `messages`: a message list, unwrapped from the `{ messages }` envelope
* model generation spans and legacy agent spans record
* - `agent-run-resume`: the resume data of a resumed agent run, whatever shape it has
* - `processor`: a processor payload, tagged with the pipeline phase that recorded it
* - `json`: anything else, such as tool arguments or workflow step data
*/
function describeSpanInput(span) {
const input = span.input;
if (input == null) return void 0;
if (span.spanType === "agent_run" && span.metadata?.resumed === true) return {
type: "agent-run-resume",
value: isRecord(input) ? input : { resumeData: input }
};
if (describeProcessorPhase(span)) {
const processor = isRecord(input) ? describeProcessorInput(span, input) : void 0;
return processor ? {
type: "processor",
value: processor
} : {
type: "json",
value: input
};
}
if (typeof input === "string") return {
type: "text",
value: input
};
if (Array.isArray(input)) return MESSAGE_LIST_INPUT_SPANS.includes(span.spanType) ? {
type: "messages",
value: input
} : {
type: "json",
value: input
};
if (!isRecord(input)) return {
type: "json",
value: input
};
const isAgentRun = span.spanType === "agent_run";
if ((isAgentRun || span.spanType === "model_generation") && "messages" in input) {
const { messages } = input;
if (typeof messages === "string") return {
type: "text",
value: messages
};
if (Array.isArray(messages)) return {
type: "messages",
value: messages
};
if (isRecord(messages)) return {
type: "messages",
value: [messages]
};
}
if (isAgentRun) {
if (typeof input.role === "string") return {
type: "messages",
value: [input]
};
if ("toolCallId" in input || "toolName" in input || "resumeData" in input) return {
type: "agent-run-resume",
value: input
};
}
return {
type: "json",
value: input
};
}
/**
* Describes a stored span's `output` for rendering: the value tagged by what it
* holds. Returns `undefined` when the span recorded no output.
*
* - `interrupted`: the run suspended or was aborted before the span's result existed
* - `agent-run-result`, `model-generation-result`, `model-step-result`: the
* result of the span type that recorded it
* - `processor`: a processor payload, tagged with the pipeline phase that recorded it
* - `text`: a plain string
* - `json`: anything else, such as a tool result or workflow step output
*/
function describeSpanOutput(span) {
const output = span.output;
if (output == null) return void 0;
if (describeProcessorPhase(span)) {
const processor = isRecord(output) ? describeProcessorOutput(span, output) : void 0;
return processor ? {
type: "processor",
value: processor
} : {
type: "json",
value: output
};
}
if (typeof output === "string") return {
type: "text",
value: output
};
if (!isRecord(output)) return {
type: "json",
value: output
};
switch (span.spanType) {
case "agent_run": return isInterrupted(output) ? {
type: "interrupted",
value: output
} : {
type: "agent-run-result",
value: output
};
case "model_generation": return isInterrupted(output) ? {
type: "interrupted",
value: output
} : {
type: "model-generation-result",
value: output
};
case "model_step": return isInterrupted(output) ? {
type: "interrupted",
value: output
} : {
type: "model-step-result",
value: output
};
case "model_inference": return {
type: "model-step-result",
value: output
};
default: return {
type: "json",
value: output
};
}
}
const isSpanErrorInfo = (value) => isRecord(value) && typeof value.message === "string";
/** The error a stored span recorded, typed, or `undefined` when the span succeeded. */
function describeSpanError(span) {
return isSpanErrorInfo(span.error) ? span.error : void 0;
}
// src/observability/rag-ingestion.ts
/**
* RAG ingestion helpers.
*
* Provides a thin wrapper around `getOrCreateSpan` for starting a
* `RAG_INGESTION` root span without reaching into observability internals.
*
* Two surfaces:
* - `startRagIngestion(...)` — manual: returns `{ span, observabilityContext }`,
* caller is responsible for `.end()` / `.error()`.
* - `withRagIngestion(opts, fn)` — scoped: runs `fn(observabilityContext)`,
* automatically attaches the return value as the span's `output` and
* routes thrown errors to `span.error(...)`.
*
* ## Observability data
*
* Mastra emits raw span data (start/end timestamps, attributes, input,
* output) — exporters and downstream consumers do their own aggregation.
* The shapes below are designed to make the common derivations cheap:
*
* - **Duration**: every span has start/end, so per-operation latency
* falls out for free.
* - **Embedding cost**: `RAG_EMBEDDING` spans (and only `RAG_EMBEDDING`
* spans) expose `attributes.usage` using the same `UsageStats` shape as
* `MODEL_GENERATION`, so any existing LLM cost-extraction pipeline that
* parses `usage.inputTokens` handles embeddings uniformly. Cost
* dimensions are `{model, provider, mode}` (mode is `'ingest'` or
* `'query'`). Token counts are deliberately NOT duplicated on the
* `RAG_INGESTION` root — aggregating at the root would double-count
* when summing child spans. Mirrors how `AGENT_RUN` does not carry
* aggregated `MODEL_GENERATION` usage.
* - **Vector store throughput**: `RAG_VECTOR_OPERATION` spans carry
* `{operation, store, indexName}` as attributes; result counts live on
* `output` (e.g. `output.returned`, `output.vectorCount`).
* - **Ingestion roll-ups**: `RAG_INGESTION` (root) carries
* `{vectorStore, indexName, embeddingModel, embeddingProvider}` as
* attributes and aggregate `usage` summed across child embed calls.
*/
/**
* Start a `RAG_INGESTION` root span. Caller is responsible for closing it
* via `result.span?.end(...)` or `result.span?.error(...)`.
*
* Prefer `withRagIngestion` for the common try/catch/end flow.
*
* @example
* ```ts
* const { span, observabilityContext } = startRagIngestion({
* mastra,
* name: 'docs ingestion',
* attributes: { vectorStore: 'pgvector', indexName: 'docs' },
* });
* try {
* const chunks = await doc.chunk({ observabilityContext });
* // ...
* span?.end({ output: { chunkCount: chunks.length } });
* } catch (err) {
* span?.error({ error: err as Error });
* throw err;
* }
* ```
*/
function startRagIngestion(options) {
const span = getOrCreateSpan({
...options,
entityType: EntityType.RAG_INGESTION,
type: "rag_ingestion"
});
return {
span,
observabilityContext: createObservabilityContext(span ? { currentSpan: span } : void 0)
};
}
/**
* Run an async function inside a `RAG_INGESTION` root span.
*
* The callback receives an `ObservabilityContext` to thread into chunk,
* embed, and vector-store calls. The return value is attached to the span
* as `output`. Thrown errors are recorded via `span.error(...)` and
* re-thrown.
*
* @example
* ```ts
* await withRagIngestion(
* {
* mastra,
* name: 'docs ingestion',
* attributes: { vectorStore: 'pgvector', indexName: 'docs' },
* },
* async (observabilityContext) => {
* const chunks = await doc.chunk({ observabilityContext });
* const { embeddings } = await embed(chunks, { observabilityContext });
* await vectorStore.upsert({
* indexName: 'docs',
* vectors: embeddings,
* observabilityContext,
* });
* return { chunkCount: chunks.length };
* },
* );
* ```
*/
async function withRagIngestion(options, fn) {
const { span, observabilityContext } = startRagIngestion(options);
try {
const result = await fn(observabilityContext);
span?.end({ output: result });
return result;
} catch (err) {
span?.error({
error: err,
endSpan: true
});
throw err;
}
}
// src/observability/span-previews.ts
/** Maximum preview length, before the trailing `…`, including supplied previews. */
const PREVIEW_MAX_LENGTH = 100;
function truncatePreview(text, maxLength = 100) {
const trimmed = text.trim();
if (!trimmed) return null;
if (trimmed.length <= maxLength) return trimmed;
const end = maxLength > 0 && /[\uD800-\uDBFF]/.test(trimmed[maxLength - 1]) ? maxLength - 1 : maxLength;
return `${trimmed.slice(0, end)}…`;
}
const record$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
const text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
const limit = (value) => truncatePreview(value) ?? "";
/** Only serialize enough JSON for a preview. Never walk an entire embedding, message history,
* or tool result just to return 100 characters. Cycles/deep values remain readable. */
function jsonPreview(value) {
let result = "";
let visited = 0;
const ancestors = /* @__PURE__ */ new Set();
const append = (part) => {
result += part.slice(0, 101 - result.length);
};
const visit = (item, depth) => {
if (result.length > 100) return;
if (++visited > 128) {
append("\"[More values]\"");
return;
}
if (typeof item === "string") append(JSON.stringify(item.slice(0, 101)));
else if (typeof item === "bigint") append(JSON.stringify(String(item)));
else if (item === null || typeof item !== "object") append(JSON.stringify(item) ?? "null");
else if (item instanceof Date) append(JSON.stringify(item));
else if (ancestors.has(item) || depth >= 8) append(JSON.stringify(ancestors.has(item) ? "[Circular]" : "[Nested value]"));
else {
ancestors.add(item);
if (Array.isArray(item)) {
append("[");
for (let i = 0; i < item.length && result.length <= 100; i++) {
if (i) append(",");
visit(item[i], depth + 1);
}
append("]");
} else {
append("{");
let first = true;
let keys = 0;
for (const key in item) {
if (result.length > 100) break;
if (!Object.hasOwn(item, key)) continue;
if (++keys > 128) {
if (!first) append(",");
append("\"…\":\"[More fields]\"");
break;
}
const field = item[key];
if (field === void 0 || typeof field === "function" || typeof field === "symbol") continue;
if (!first) append(",");
first = false;
append(JSON.stringify(key.slice(0, 101)));
append(":");
visit(field, depth + 1);
}
append("}");
}
ancestors.delete(item);
}
};
visit(value, 0);
return limit(result);
}
function generic(value) {
if (value == null) return "";
if (typeof value === "string") return limit(value);
const data = record$1(value);
if (data?.__isCreatedSignal === true) return signalPreview(data);
const content = text(data?.text) ?? text(data?.message);
return content ? limit(content) : jsonPreview(value);
}
/** Created signals are caller input, rather than messages with a role. */
function signalPreview(signal) {
const content = messageContent(signal.contents);
if (signal.type === "user" || signal.type === "user-message") return content;
const tagName = text(signal.tagName);
const skillName = text(record$1(signal.attributes)?.name);
const label = tagName === "skill" && skillName ? `Skill ${skillName}` : tagName ?? text(signal.type) ?? "signal";
return limit(content ? `${label}: ${content}` : label);
}
/** Content parts are deliberately shallow: never serialize binary data or an entire tool result. */
function messageContent(value) {
if (typeof value === "string") return limit(value);
const container = record$1(value);
if (container) return messageContent(container.parts ?? container.content);
if (!Array.isArray(value)) return "";
const parts = [];
const hasAnswer = value.some((item) => record$1(item)?.type === "text" && text(record$1(item)?.text));
let length = 0;
for (const item of value) {
const part = record$1(item);
if (hasAnswer && part?.type === "reasoning") continue;
let content = typeof item === "string" ? limit(item) : text(part?.text);
if (!content && part) {
const type = text(part.type);
if (type === "step-start") continue;
if (type === "reasoning") content = text(part.reasoning);
else if (type === "tool-invocation" || type === "dynamic-tool" || type?.startsWith("tool-") && type !== "tool-call" && type !== "tool-result") {
const invocation = record$1(part.toolInvocation) ?? part;
const name = text(invocation.toolName) ?? (type?.startsWith("tool-") ? type.slice(5) : void 0) ?? "unknown";
const state = text(invocation.state);
content = `[${state === "result" || state === "output-available" ? "tool-result" : state === "output-error" ? "tool-error" : state === "output-denied" ? "tool-denied" : state?.startsWith("approval-") ? "tool-approval" : "tool-call"}: ${name}]`;
} else if (type === "tool-call" || type === "tool-result") content = `[${type}: ${text(part.toolName) ?? "unknown"}]`;
else if (type === "image" || type === "image_url" || type === "input_image") content = "[image]";
else if (type === "audio" || type === "input_audio") content = "[audio]";
else if (type === "file" || type === "resource" || type === "resource_link") content = `[${type}]`;
else if (type) content = `[${type}]`;
}
if (content) {
parts.push(limit(content));
length += content.length + 1;
if (length > 100) break;
}
}
return limit(parts.join(" "));
}
function messages(value, preferUser, label = false) {
if (typeof value === "string") return limit(value);
const data = record$1(value);
if (data && "messages" in data) return messages(data.messages, preferUser, label);
const list = Array.isArray(value) ? value : data?.role ? [data] : void 0;
if (!list) return void 0;
let latest;
for (let i = list.length - 1; i >= 0; i--) {
const item = list[i];
const message = record$1(item);
const role = typeof item === "string" ? "user" : text(message?.role);
if (!role || role === "system" || role === "developer") continue;
const body = record$1(message?.content) ?? message;
let content = typeof item === "string" ? limit(item) : messageContent(message?.parts ?? message?.content);
if (!content && Array.isArray(body?.toolInvocations)) content = messageContent(body.toolInvocations.map((toolInvocation) => ({
type: "tool-invocation",
toolInvocation
})));
if (!content && Array.isArray(body?.experimental_attachments) && body.experimental_attachments.length) content = "[attachment]";
content ||= text(body?.reasoning) ?? "";
if (!content) continue;
const preview = label ? `${role[0].toUpperCase()}${role.slice(1)}: ${content}` : content;
latest ??= preview;
const signalType = record$1(record$1(record$1(message?.content)?.metadata)?.signal)?.type;
if (!preferUser || role === "user" || role === "signal" && (signalType === "user" || signalType === "user-message")) return preview;
}
return latest ?? "";
}
function toolCalls(value) {
if (!Array.isArray(value) || !value.length) return void 0;
return `Tool calls: ${value.slice(0, 4).map((call) => {
const data = record$1(call);
return text(data?.toolName) ?? text(data?.name) ?? text(record$1(data?.function)?.name) ?? "unknown";
}).join(", ")}${value.length > 4 ? ` (+${value.length - 4})` : ""}`;
}
const modelWriter = (span, direction) => {
const value = span[direction];
const data = record$1(value);
if (direction === "input") {
if (span.type === "agent_run" && data && (span.metadata?.resumed === true || "resumeData" in data || "toolCallId" in data || "toolName" in data)) return `Resume${text(data.toolName) ? ` ${data.toolName}` : ""}: ${generic(data.resumeData ?? value)}`;
if (span.type === "agent_run" && span.metadata?.resumed === true && value != null) return `Resume: ${generic(value)}`;
const step = span.type === "model_step" || span.type === "model_inference";
return messages(value, !step, step);
}
if (!data) return void 0;
if ([
"suspended",
"aborted",
"interrupted"
].includes(String(data.status))) {
const status = String(data.status);
return `${status[0].toUpperCase()}${status.slice(1)}${text(data.reason) ? `: ${data.reason}` : ""}${text(data.toolName) ? ` (${data.toolName})` : ""}`;
}
const tripwire = record$1(data.tripwire);
if (tripwire) return `Tripwire${text(tripwire.reason) ? `: ${tripwire.reason}` : ""}`;
if (data.object != null) return jsonPreview(data.object);
const calls = toolCalls(data.toolCalls);
if (text(data.text)) return `${data.text}${calls ? ` — ${calls}` : ""}`;
if (calls) return calls;
if (Array.isArray(data.files) && data.files.length) return `${data.files.length} generated file(s)`;
if (text(data.reasoningText)) return `Reasoning: ${data.reasoningText}`;
};
const processorWriter = (span, direction) => {
const data = record$1(span[direction]);
if (!data) return void 0;
const phase = record$1(span.attributes)?.processorPhase;
if (phase === "outputStream") return text(data.accumulatedText) ?? (typeof data.totalChunks === "number" ? `${data.totalChunks} chunks` : void 0);
if (direction === "input") {
if (phase === "requestError" && text(data.error)) return `Request error: ${data.error}`;
if (phase === "toolResult" && text(data.toolName)) return `Tool result: ${data.toolName}`;
return messages(data.messages ?? data.prompt, phase === "input" || phase === "inputStep") ?? text(data.text);
}
const changes = [];
if (record$1(data.model)) changes.push(`Model: ${generic(data.model)}`);
for (const key of [
"messages",
"systemMessages",
"tools",
"activeTools",
"toolChoice"
]) if (Object.hasOwn(data, key)) changes.push(`${key} replaced`);
if (changes.length) return changes.join("; ");
if (Object.keys(data).length === 0) return "No recorded changes";
};
const processorPhases = /* @__PURE__ */ new Set([
"input",
"inputStep",
"outputStream",
"outputResult",
"outputStep",
"toolResult",
"llmRequest",
"llmResponse",
"requestError"
]);
const writers = {
["agent_run"]: modelWriter,
["model_generation"]: modelWriter,
["model_step"]: modelWriter,
["model_inference"]: modelWriter,
["model_chunk"]: (span, direction) => {
if (direction !== "output") return void 0;
const data = record$1(span.output);
if (!data) return void 0;
if (text(data.text) ?? text(data.delta)) return text(data.text) ?? text(data.delta);
if (text(data.toolName)) return `${data.toolName}: ${generic(data.toolInput ?? data.args ?? data.input ?? data.result)}`;
if (record$1(span.attributes)?.chunkType === "file") return "[file]";
},
["mcp_tool_call"]: mcpWriter,
["mcp_server_request"]: mcpWriter,
["scorer_run"]: (span, direction) => {
const data = record$1(span[direction]);
if (!data) return void 0;
if (direction === "input" && data.output != null) return `Response: ${generic(data.output)}`;
if (direction === "output" && typeof data.score === "number") return `Score: ${data.score}${text(data.reason) ? ` — ${data.reason}` : ""}`;
},
["classifier_evaluation"]: (span, direction) => {
const data = record$1(span[direction]);
return data && (direction === "input" ? data.questions : data.answers) != null ? generic(direction === "input" ? data.questions : data.answers) : void 0;
},
["rag_embedding"]: (span, direction) => {
const value = span[direction];
if (direction === "input" && Array.isArray(value)) return `${value.length} texts: ${generic(value[0])}`;
const data = record$1(value);
if (direction === "output" && typeof data?.dimensions === "number") return `${data.dimensions} dimensions`;
},
["rag_vector_operation"]: returnedWriter,
["rag_action"]: (span, direction) => {
const data = record$1(span[direction]);
if (direction === "input" && record$1(span.attributes)?.action === "rerank" && data?.query != null) return generic(data.query);
return returnedWriter(span, direction);
},
["graph_action"]: returnedWriter
};
function returnedWriter(span, direction) {
const data = record$1(span[direction]);
return direction === "output" && typeof data?.returned === "number" ? `${data.returned} results` : void 0;
}
function mcpWriter(span, direction) {
if (direction !== "output") return void 0;
const data = record$1(span.output);
if (data?.structuredContent != null) return jsonPreview(data.structuredContent);
if (Array.isArray(data?.content)) return messageContent(data.content) || void 0;
}
function errorPreview(value) {
if (typeof value === "string") return limit(value);
const data = record$1(value);
if (!data) return "";
const field = (key) => {
try {
return text(data[key]);
} catch {
return;
}
};
const message = field("message");
const name = field("name");
if (message) return limit(name && name !== "Error" && !message.startsWith(`${name}:`) ? `${name}: ${message}` : message);
return limit(name ?? field("id") ?? field("domain") ?? field("category") ?? "");
}
/** Readable previews of a processed/redacted span. Explicit strings, including
* empty strings, take precedence. Does not mutate the span or retain snapshots. */
function buildSpanPreviews(span) {
const preview = (direction) => {
try {
const upstream = span[direction === "input" ? "inputPreview" : "outputPreview"];
if (typeof upstream === "string") return limit(upstream);
if (span[direction] == null) return "";
const phase = record$1(span.attributes)?.processorPhase;
const writer = typeof phase === "string" && processorPhases.has(phase) ? processorWriter : writers[span.type];
return limit(writer?.(span, direction) ?? generic(span[direction]));
} catch {
try {
return generic(span[direction]);
} catch {
return "";
}
}
};
let error = "";
try {
error = typeof span.errorPreview === "string" ? limit(span.errorPreview) : errorPreview(span.errorInfo);
} catch {}
return {
inputPreview: preview("input"),
outputPreview: preview("output"),
errorPreview: error
};
}
// src/observability/usage.ts
const usageCountKeys = [
"inputTokens",
"outputTokens",
"totalTokens",
"reasoningTokens",
"cachedInputTokens",
"cacheCreationInputTokens",
"cacheCreationInputTokens5m",
"cacheCreationInputTokens1h"
];
function isUsageIncomplete(usage) {
return usage?.inputTokens === void 0 || usage.outputTokens === void 0 || usage.totalTokens === void 0;
}
/**
* Usage left after removing what earlier generations of the same run already reported.
* A resumed run reports cumulative usage, but its suspended legs already recorded part of it.
*/
function subtractReportedUsage(usage, reported) {
if (!usage || !reported) return usage;
const remaining = { ...usage };
for (const key of usageCountKeys) {
const value = usage[key];
if (value !== void 0) remaining[key] = Math.max(0, value - (reported[key] ?? 0));
}
return remaining;
}
function calculateObservedUsage(steps) {
const usage = {
inputTokens: void 0,
outputTokens: void 0,
totalTokens: void 0
};
for (const step of steps) for (const key of usageCountKeys) {
const value = step.usage?.[key];
if (value !== void 0) usage[key] = (usage[key] ?? 0) + value;
}
if (usage.inputTokens !== void 0 && usage.outputTokens !== void 0) usage.totalTokens = usage.inputTokens + usage.outputTokens;
return usage;
}
function isV3RawUsage(raw) {
return typeof raw === "object" && raw !== null && "inputTokens" in raw;
}
/**
* Null-safe check: returns true if value is a number (including 0).
*/
function isDefined(value) {
return value != null;
}
/**
* Extracts and normalizes token usage from AI SDK response, including
* provider-specific cache tokens from providerMetadata.
*
* Cache token extraction priority (highest to lowest):
* 1. AI SDK aggregated inputTokenDetails (properly summed across all steps in multi-step runs)
* 2. Mastra-aggregated top-level usage fields (usage.cachedInputTokens, usage.cacheCreationInputTokens) -
* summed across steps by RunOutput, so they are correct for multi-step runs.
* 3. Provider-specific providerMetadata (accurate for single-step, LAST STEP ONLY in multi-step).
*
* Handles:
* - OpenAI: cachedInputTokens in usage object
* - Anthropic: cacheCreationInputTokens, cacheReadInputTokens in providerMetadata.anthropic
* - Google/Gemini: cachedContentTokenCount, thoughtsTokenCount in providerMetadata.google.usageMetadata
* - OpenRouter: Uses OpenAI-compatible structure (cache tokens in usage)
*
* Kept in sync with `observability/mastra/src/usage.ts` (duplicated so exporters do not need a newer core).
* Change both copies together; the parity test in @mastra/observability fails if they drift.
*
* @param usage - The LanguageModelV2Usage from AI SDK response
* @param providerMetadata - Optional provider-specific metadata
* @returns UsageStats with inputDetails and outputDetails
*/
function extractUsageMetrics(usage, providerMetadata) {
if (!usage) return {};
const inputDetails = {};
const outputDetails = {};
let inputTokens = usage.inputTokens;
const outputTokens = usage.outputTokens;
const aiSdkDetails = usage.inputTokenDetails;
if (isDefined(aiSdkDetails?.cacheReadTokens)) inputDetails.cacheRead = aiSdkDetails.cacheReadTokens;
if (isDefined(aiSdkDetails?.cacheWriteTokens)) inputDetails.cacheWrite = aiSdkDetails.cacheWriteTokens;
if (!isDefined(inputDetails.cacheRead) && isDefined(usage.cachedInputTokens)) inputDetails.cacheRead = usage.cachedInputTokens;
if (isDefined(usage.cacheCreationInputTokens5m)) inputDetails.cacheWrite5m = usage.cacheCreationInputTokens5m;
if (isDefined(usage.cacheCreationInputTokens1h)) inputDetails.cacheWrite1h = usage.cacheCreationInputTokens1h;
if (!isDefined(inputDetails.cacheWrite) && isDefined(usage.cacheCreationInputTokens)) inputDetails.cacheWrite = usage.cacheCreationInputTokens;
const anthropic = providerMetadata?.anthropic;
const cacheCreation = anthropic?.cacheCreation ?? anthropic?.usage?.cache_creation ?? usage.raw?.cache_creation;
const cacheWrite5m = cacheCreation?.ephemeral_5m_input_tokens ?? cacheCreation?.ephemeral5mInputTokens;
const cacheWrite1h = cacheCreation?.ephemeral_1h_input_tokens ?? cacheCreation?.ephemeral1hInputTokens;
if (!isDefined(inputDetails.cacheWrite5m) && isDefined(cacheWrite5m)) inputDetails.cacheWrite5m = cacheWrite5m;
if (!isDefined(inputDetails.cacheWrite1h) && isDefined(cacheWrite1h)) inputDetails.cacheWrite1h = cacheWrite1h;
if (!isDefined(inputDetails.cacheWrite) && (isDefined(inputDetails.cacheWrite5m) || isDefined(inputDetails.cacheWrite1h))) inputDetails.cacheWrite = (inputDetails.cacheWrite5m ?? 0) + (inputDetails.cacheWrite1h ?? 0);
if (isDefined(usage.reasoningTokens)) outputDetails.reasoning = usage.reasoningTokens;
if (anthropic) {
const rawV3InputUsage = isV3RawUsage(usage.raw) ? usage.raw.inputTokens : void 0;
const hasV3CachedTotals = rawV3InputUsage?.total !== void 0 && (rawV3InputUsage.cacheRead !== void 0 || rawV3InputUsage.cacheWrite !== void 0);
if (!isDefined(inputDetails.cacheRead) && isDefined(anthropic.cacheReadInputTokens)) inputDetails.cacheRead = anthropic.cacheReadInputTokens;
if (!isDefined(inputDetails.cacheWrite) && isDefined(anthropic.cacheCreationInputTokens)) inputDetails.cacheWrite = anthropic.cacheCreationInputTokens;
if (!(hasV3CachedTotals || isDefined(usage.cachedInputTokens) && usage.cachedInputTokens > 0 || isDefined(usage.cacheCreationInputTokens) && usage.cacheCreationInputTokens > 0) && (isDefined(inputDetails.cacheRead) || isDefined(inputDetails.cacheWrite))) inputTokens = (usage.inputTokens ?? 0) + (inputDetails.cacheRead ?? 0) + (inputDetails.cacheWrite ?? 0);
}
const google = providerMetadata?.google;
if (google?.usageMetadata) {
if (!isDefined(inputDetails.cacheRead) && isDefined(google.usageMetadata.cachedContentTokenCount)) inputDetails.cacheRead = google.usageMetadata.cachedContentTokenCount;
if (isDefined(google.usageMetadata.thoughtsTokenCount)) outputDetails.reasoning = google.usageMetadata.thoughtsTokenCount;
}
if (isDefined(inputTokens)) inputDetails.text = Math.max(0, inputTokens - sumDefinedValues(inputDetails, [
"cacheRead",
"cacheWrite",
"audio",
"image"
]));
if (isDefined(outputTokens)) outputDetails.text = Math.max(0, outputTokens - sumDefinedValues(outputDetails, [
"reasoning",
"audio",
"image"
]));
const result = {
inputTokens,
outputTokens
};
if (Object.keys(inputDetails).length > 0) result.inputDetails = inputDetails;
if (Object.keys(outputDetails).length > 0) result.outputDetails = outputDetails;
return result;
}
function sumDefinedValues(obj, keys) {
return keys.reduce((sum, key) => sum + (obj[key] ?? 0), 0);
}
export { compactStopReasonContext as A, NoOpObservability as C, agentLoopTermination as D, noOpTracingContext as E, SPAN_STOP_REASONS as M, executionFailureTermination as O, resolveObservabilityContext as S, noOpMetricsContext as T, parseTraceparent as _, PREVIEW_MAX_LENGTH as a, wrapMastra as b, startRagIngestion as c, describeSpanInput as d, describeSpanOutput as f, formatTraceparent as g, describeProcessorPipeline as h, subtractReportedUsage as i, SPAN_OUTCOMES as j, tripwireTermination as k, withRagIngestion as l, describeProcessorPhase as m, extractUsageMetrics as n, buildSpanPreviews as o, isSpanRecordOfType as p, isUsageIncomplete as r, truncatePreview as s, calculateObservedUsage as t, describeSpanError as u, SamplingStrategyType as v, noOpLoggerContext as w, createObservabilityContext as x, unwrapMastraTracingProxy as y };
//# sourceMappingURL=observability-D3dpuDDk.js.map