UNPKG

@mastra/core

Version:
503 lines (502 loc) • 19 kB
const require_storage = require("./storage-CfG0I2aF.cjs"); // src/observability/types/tracing.ts /** * AI-specific span types with their associated metadata */ let SpanType = /* @__PURE__ */ function(SpanType) { /** Agent run - root span for agent processes */ SpanType["AGENT_RUN"] = "agent_run"; /** Scorer execution */ SpanType["SCORER_RUN"] = "scorer_run"; /** Classifier evaluation */ SpanType["CLASSIFIER_EVALUATION"] = "classifier_evaluation"; /** Individual scorer pipeline step */ SpanType["SCORER_STEP"] = "scorer_step"; /** Generic span for custom operations */ SpanType["GENERIC"] = "generic"; /** Model generation with model calls, token usage, prompts, completions */ SpanType["MODEL_GENERATION"] = "model_generation"; /** Single model execution step within a generation (one API call) */ SpanType["MODEL_STEP"] = "model_step"; /** Model provider call within a step - wraps only the inference, excluding processors and tool executions */ SpanType["MODEL_INFERENCE"] = "model_inference"; /** Individual model streaming chunk/event */ SpanType["MODEL_CHUNK"] = "model_chunk"; /** MCP (Model Context Protocol) tool execution */ SpanType["MCP_TOOL_CALL"] = "mcp_tool_call"; /** A request served by a Mastra MCPServer (the server side of an MCP edge) */ SpanType["MCP_SERVER_REQUEST"] = "mcp_server_request"; /** Input or Output Processor execution */ SpanType["PROCESSOR_RUN"] = "processor_run"; /** Function/tool execution with inputs, outputs, errors */ SpanType["TOOL_CALL"] = "tool_call"; /** * Client-side tool execution marker. The server creates this span * when the model emits a client tool call, injects its W3C carrier * into the outgoing tool-call chunk, then ends the span once tool * args are available. Child spans/logs from inside the client tool's * execute function flow back as OTLP/JSON via the ClientObservabilityProxy * interface in @mastra/observability and parent themselves under this * span via parentSpanId reference. */ SpanType["CLIENT_TOOL_CALL"] = "client_tool_call"; /** * Provider-executed (server-side) tool span. Reconstructed from * tool-call and tool-result stream chunks for tools the model * provider executes (e.g. Anthropic code execution, server-side * web search). Created on the tool-result chunk under the model * step that delivered it, with the start time backdated to the * tool-call chunk. */ SpanType["PROVIDER_TOOL_CALL"] = "provider_tool_call"; /** Workflow run - root span for workflow processes */ SpanType["WORKFLOW_RUN"] = "workflow_run"; /** Workflow step execution with step status, data flow */ SpanType["WORKFLOW_STEP"] = "workflow_step"; /** Workflow conditional execution with condition evaluation */ SpanType["WORKFLOW_CONDITIONAL"] = "workflow_conditional"; /** Individual condition evaluation within conditional */ SpanType["WORKFLOW_CONDITIONAL_EVAL"] = "workflow_conditional_eval"; /** Workflow parallel execution */ SpanType["WORKFLOW_PARALLEL"] = "workflow_parallel"; /** Workflow loop execution */ SpanType["WORKFLOW_LOOP"] = "workflow_loop"; /** Workflow sleep operation */ SpanType["WORKFLOW_SLEEP"] = "workflow_sleep"; /** Workflow wait for event operation */ SpanType["WORKFLOW_WAIT_EVENT"] = "workflow_wait_event"; /** Memory operation (recall, save, delete, update working memory) */ SpanType["MEMORY_OPERATION"] = "memory_operation"; /** Workspace action (filesystem, sandbox, search, skill, mount operations) */ SpanType["WORKSPACE_ACTION"] = "workspace_action"; /** RAG ingestion - root span for an ingestion pipeline run (load → chunk → extract → embed → upsert) */ SpanType["RAG_INGESTION"] = "rag_ingestion"; /** Embedding call (used by both RAG ingestion and query) */ SpanType["RAG_EMBEDDING"] = "rag_embedding"; /** Vector store I/O (query / upsert / delete / fetch) */ SpanType["RAG_VECTOR_OPERATION"] = "rag_vector_operation"; /** RAG-specific actions: chunk, extract_metadata, rerank */ SpanType["RAG_ACTION"] = "rag_action"; /** Graph operations (build / traverse) - not RAG-specific */ SpanType["GRAPH_ACTION"] = "graph_action"; /** Inline data mapping between pipeline stages (e.g. a tool's `toModelOutput` transform) */ SpanType["MAPPING"] = "mapping"; /** Dynamic agent skills resolver run */ /** * @deprecated Use {@link SpanType.SKILL_ACTION} with `operation: 'resolve'`. * No longer emitted; retained so existing exporters and stored traces keep * resolving the value. */ SpanType["SKILL_RESOLUTION"] = "skill_resolution"; /** Any skill lifecycle operation: resolve, inject, activate, search, read */ SpanType["SKILL_ACTION"] = "skill_action"; /** * An agent state signal emitted onto the model context (point-in-time event, * not a duration). */ SpanType["AGENT_SIGNAL"] = "agent_signal"; return SpanType; }({}); /** * Bitwise options to set different types of spans as internal in * a workflow or agent execution. */ let InternalSpans = /* @__PURE__ */ function(InternalSpans) { /** No spans are marked internal */ InternalSpans[InternalSpans["NONE"] = 0] = "NONE"; /** Workflow spans are marked internal */ InternalSpans[InternalSpans["WORKFLOW"] = 1] = "WORKFLOW"; /** Agent spans are marked internal */ InternalSpans[InternalSpans["AGENT"] = 2] = "AGENT"; /** Tool spans are marked internal */ InternalSpans[InternalSpans["TOOL"] = 4] = "TOOL"; /** Model spans are marked internal */ InternalSpans[InternalSpans["MODEL"] = 8] = "MODEL"; /** All spans are marked internal */ InternalSpans[InternalSpans["ALL"] = 15] = "ALL"; return InternalSpans; }({}); /** * Tracing event types */ let TracingEventType = /* @__PURE__ */ function(TracingEventType) { TracingEventType["SPAN_STARTED"] = "span_started"; TracingEventType["SPAN_UPDATED"] = "span_updated"; TracingEventType["SPAN_ENDED"] = "span_ended"; return TracingEventType; }({}); // src/observability/utils.ts /** * Browser-safe observability utilities. * * Functions that depend on AsyncLocalStorage (getCurrentSpan, executeWithContext, * executeWithContextSync) are in context-storage.ts and should only be imported * by server-side code. */ const entityTypeValues = new Set(Object.values(require_storage.EntityType)); let currentSpanResolver; function setCurrentSpanResolver(resolver) { currentSpanResolver = resolver; } function resolveCurrentSpan() { return currentSpanResolver?.(); } /** Generate a unique id for an observability signal (log, metric, score, feedback). */ function generateSignalId() { return crypto.randomUUID(); } /** * Compute the names of tools the model can call on a single inference step, * applying `activeTools` filtering when present. Used to populate the * `availableTools` attribute on MODEL_INFERENCE spans so observers see the * post-processor tool set, which can differ per-step from the AGENT_RUN view. * * `activeTools` is treated by presence, not truthiness: an explicit empty * array means "no tools enabled for this step" and is honored as such. * Returns `[]` (not `undefined`) when `tools` is provided but empty, so a * tool-less agent still reports a definitive empty list to observers. * * @deprecated No longer used. `availableTools` is now derived from the tool * definitions serialized for the MODEL_INFERENCE `tools` attribute, which * also apply `toolChoice` and drop names that are not registered tools. */ function getStepAvailableToolNames(tools, activeTools) { if (activeTools !== void 0) return [...activeTools]; if (tools) return Object.keys(tools); } let executeWithContextImpl; let executeWithContextSyncImpl; function setExecuteWithContext(impl) { executeWithContextImpl = impl; } function setExecuteWithContextSync(impl) { executeWithContextSyncImpl = impl; } /** * Execute an async function within a span's tracing context. * Falls back to direct execution if no context-storage implementation is registered or no span exists. */ async function executeWithContext(params) { if (executeWithContextImpl) return executeWithContextImpl(params); const { span, fn } = params; if (span?.executeInContext) return span.executeInContext(fn); return fn(); } /** * Execute a sync function within a span's tracing context. * Falls back to direct execution if no context-storage implementation is registered or no span exists. */ function executeWithContextSync(params) { if (executeWithContextSyncImpl) return executeWithContextSyncImpl(params); const { span, fn } = params; if (span?.executeInContextSync) return span.executeInContextSync(fn); return fn(); } /** * Resolve the spanId an observability signal should reference for a span. * * Signals (logs, metrics, and a suspending run's resume link) must name a span * that actually reached exporters. An internal or excluded span is never * stored, so referencing its raw id leaves the signal pointing at nothing: * log/metric span lookups 404, and a resumed run's exported children inherit a * dangling parentSpanId and land as orphans. `undefined` is a valid answer — it * omits the reference rather than pointing it at a span that does not exist. * * `getExportedSpanId` is optional on the `Span` interface, so the typeof guard * separates "this implementation predates the method" (keep the old behavior of * referencing the span's own id) from "the method ran and found nothing * exportable" (undefined). Without it the two collapse and custom span * implementations silently lose correlation. */ function resolveExportedSpanId(span) { if (!span) return void 0; return typeof span.getExportedSpanId === "function" ? span.getExportedSpanId() : span.id; } const NO_OP_TRACE_ID = "no-op-trace"; const NO_OP_SPAN_ID = "no-op"; /** * The lineage a suspending run saves so that its resume continues it (see `resumeFrom`). * Takes the run's live span, or its exported span when another process persisted it. * An unsampled run saves nothing: its no-op span has no real trace for a resume to join. */ function getResumeTracingContext(span) { if (!span) return void 0; const live = "exportSpan" in span; if (live ? !span.isValid : span.id === NO_OP_SPAN_ID) return void 0; const exported = live ? span.exportSpan(span.observabilityInstance?.getConfig?.().includeInternalSpans) : span; return { traceId: span.traceId, spanId: live ? resolveExportedSpanId(span) : span.id, parentSpanId: exported?.parentSpanId, resumedFromSpanId: exported && (exported.resumedFromSpanId ?? exported.id), externalParentSpanId: exported?.externalParentSpanId }; } /** * The context a suspending workflow run saves: its lineage plus the trace's sampling decision and * state, so a resume continues the trace as it was instead of deciding again. An unsampled run * saves only that decision, since its no-op span has no trace for a resume to join. Agent runs * save `getResumeTracingContext` alone and decide on resume. */ function getWorkflowResumeTracingContext(span) { if (!span) return void 0; const lineage = getResumeTracingContext(span); if (!lineage) return { sampled: false }; const traceState = "exportSpan" in span ? span.traceState : span.traceState; if (!traceState) return { ...lineage, sampled: true }; const { nestedUnderParent: _nested, ...ownTraceState } = traceState; return { ...lineage, sampled: true, traceState: ownTraceState }; } function resumeInSavedTrace(saved, targetTraceId) { if (!saved?.traceId || saved.traceId === NO_OP_TRACE_ID) return void 0; if ((targetTraceId ?? saved.traceId) !== saved.traceId) return void 0; return { traceId: saved.traceId, parentSpanId: saved.spanId, resumedFromSpanId: saved.resumedFromSpanId ?? saved.spanId, externalParentSpanId: saved.externalParentSpanId }; } /** * Creates or gets a child span from existing tracing context or starts a new trace. * This helper consolidates the common pattern of creating spans that can either be: * 1. Children of an existing span (when tracingContext.currentSpan exists) * 2. New root spans (when no current span exists) * * @param options - Configuration object for span creation * @returns The created Span or undefined if tracing is disabled */ function getOrCreateSpan(options) { const { type, attributes, tracingContext, requestContext, tracingOptions, resumeFrom, resumedFromSpanId, samplingDecision, ...rest } = options; const metadata = { ...rest.metadata ?? {}, ...Object.fromEntries(Object.entries(tracingOptions?.metadata ?? {}).filter(([, value]) => value !== void 0)) }; const resumed = resumeInSavedTrace(resumeFrom, tracingContext?.currentSpan?.traceId ?? tracingOptions?.traceId); const staysUnsampled = resumeFrom?.sampled === false && !tracingOptions?.traceId; const saved = resumeFrom && (resumed || staysUnsampled) ? resumeFrom : void 0; if (tracingContext?.currentSpan) return tracingContext.currentSpan.createChildSpan({ type, attributes, ...rest, metadata, requestContext, resumedFromSpanId: resumed?.resumedFromSpanId }); const instance = options.mastra?.observability?.getSelectedInstance({ requestContext }); const savedState = saved?.traceState; const rootTracingOptions = resumed || savedState ? { ...tracingOptions, ...resumed ? { traceId: resumed.traceId } : {}, ...savedState ? { hideInput: tracingOptions?.hideInput ?? savedState.hideInput, hideOutput: tracingOptions?.hideOutput ?? savedState.hideOutput, requestContextKeys: tracingOptions?.requestContextKeys ?? savedState.requestContextKeys } : {} } : tracingOptions; return instance?.startSpan({ type, attributes, ...rest, metadata, requestContext, tracingOptions: rootTracingOptions, traceId: rootTracingOptions?.traceId, samplingDecision: samplingDecision ?? saved?.sampled, parentSpanId: resumed ? resumed.parentSpanId : resumedFromSpanId, resumedFromSpanId: resumed?.resumedFromSpanId, externalParentSpanId: tracingOptions?.parentSpanId ?? resumed?.externalParentSpanId, customSamplerOptions: { requestContext, metadata } }); } /** * Builds `tracingOptions` that attach the next run as a child of a previous * run, for example an LLM judge under the run it scores. Pass the previous * run's result (or its `traceId` and `spanId`). When that run was not traced, * the given options are returned unchanged. */ function nestUnderRun(run, tracingOptions) { if (!run.traceId || !run.spanId) return tracingOptions; return { ...tracingOptions, traceId: run.traceId, parentSpanId: run.spanId, nestUnderParent: true }; } /** * Returns the top-most non-internal span that would appear in exported tracing output. * * Public API results should use this span for trace/span correlation because internal Mastra * workflow spans are omitted from external exporters. */ function getRootExportSpan(span) { if (!span?.isValid) return; let current = span; let rootExportSpan = span.isInternal ? void 0 : span; while (current?.parent) { current = current.parent; if (!current.isInternal) rootExportSpan = current; } return rootExportSpan; } /** * Resolves the best available entity type for a span-like record. * * Prefers an explicit `entityType` when present and valid, then falls back to the * span type for common observability entities. */ function getEntityTypeForSpan(span) { if (span.entityType && entityTypeValues.has(span.entityType)) return span.entityType; switch (span.spanType) { case "agent_run": return require_storage.EntityType.AGENT; case "rag_ingestion": return require_storage.EntityType.RAG_INGESTION; case "scorer_run": case "scorer_step": return require_storage.EntityType.SCORER; case "workflow_run": return require_storage.EntityType.WORKFLOW_RUN; case "workflow_step": return require_storage.EntityType.WORKFLOW_STEP; case "tool_call": case "mcp_tool_call": case "provider_tool_call": return require_storage.EntityType.TOOL; case "mcp_server_request": return require_storage.EntityType.MCP_SERVER; case "processor_run": return require_storage.EntityType.OUTPUT_PROCESSOR; case "classifier_evaluation": return require_storage.EntityType.CLASSIFIER; default: return; } } /** * Time to first chunk in milliseconds for any span whose attributes carry * `completionStartTime`, measured from that span's own start. Undefined when * the span never saw a chunk. */ function getTimeToFirstChunkMs(span) { const completionStartTime = span.attributes?.completionStartTime; if (!completionStartTime) return void 0; const ms = new Date(completionStartTime).getTime() - new Date(span.startTime).getTime(); return Number.isNaN(ms) ? void 0 : Math.max(0, ms); } Object.defineProperty(exports, "InternalSpans", { enumerable: true, get: function() { return InternalSpans; } }); Object.defineProperty(exports, "SpanType", { enumerable: true, get: function() { return SpanType; } }); Object.defineProperty(exports, "TracingEventType", { enumerable: true, get: function() { return TracingEventType; } }); Object.defineProperty(exports, "executeWithContext", { enumerable: true, get: function() { return executeWithContext; } }); Object.defineProperty(exports, "executeWithContextSync", { enumerable: true, get: function() { return executeWithContextSync; } }); Object.defineProperty(exports, "generateSignalId", { enumerable: true, get: function() { return generateSignalId; } }); Object.defineProperty(exports, "getEntityTypeForSpan", { enumerable: true, get: function() { return getEntityTypeForSpan; } }); Object.defineProperty(exports, "getOrCreateSpan", { enumerable: true, get: function() { return getOrCreateSpan; } }); Object.defineProperty(exports, "getResumeTracingContext", { enumerable: true, get: function() { return getResumeTracingContext; } }); Object.defineProperty(exports, "getRootExportSpan", { enumerable: true, get: function() { return getRootExportSpan; } }); Object.defineProperty(exports, "getStepAvailableToolNames", { enumerable: true, get: function() { return getStepAvailableToolNames; } }); Object.defineProperty(exports, "getTimeToFirstChunkMs", { enumerable: true, get: function() { return getTimeToFirstChunkMs; } }); Object.defineProperty(exports, "getWorkflowResumeTracingContext", { enumerable: true, get: function() { return getWorkflowResumeTracingContext; } }); Object.defineProperty(exports, "nestUnderRun", { enumerable: true, get: function() { return nestUnderRun; } }); Object.defineProperty(exports, "resolveCurrentSpan", { enumerable: true, get: function() { return resolveCurrentSpan; } }); Object.defineProperty(exports, "resolveExportedSpanId", { enumerable: true, get: function() { return resolveExportedSpanId; } }); Object.defineProperty(exports, "setCurrentSpanResolver", { enumerable: true, get: function() { return setCurrentSpanResolver; } }); Object.defineProperty(exports, "setExecuteWithContext", { enumerable: true, get: function() { return setExecuteWithContext; } }); Object.defineProperty(exports, "setExecuteWithContextSync", { enumerable: true, get: function() { return setExecuteWithContextSync; } }); //# sourceMappingURL=utils-D-eNsgDM.cjs.map