/** * OpenTelemetry tracing and local execution trace management. * * This module provides tracing capabilities using OpenTelemetry, * enabling trace data to be sent to OTLP endpoints. * * Uses a fully stateful approach via OpenTelemetry's context propagation. * Parent-child relationships are established automatically through * context.active(). Use context.with() to set a span as active before * creating child spans. * * Lightweight in-memory LocalTrace trees are always collected regardless * of OTel configuration and surfaced via AgentResult.traces. * * @example * ```typescript * const tracer = new Tracer() * const parentSpan = tracer.startAgentSpan({ ... }) * * context.with(trace.setSpan(context.active(), parentSpan), async () => { * const modelSpan = tracer.startModelInvokeSpan({ messages }) * tracer.endModelInvokeSpan(modelSpan) * }) * * tracer.endAgentSpan(parentSpan) * ``` */ import type { Span, AttributeValue, SpanContext } from '@opentelemetry/api'; import type { EndAgentSpanOptions, EndModelSpanOptions, EndToolCallSpanOptions, EndAgentLoopSpanOptions, StartAgentSpanOptions, StartModelInvokeSpanOptions, StartToolCallSpanOptions, StartAgentLoopSpanOptions, StartMultiAgentSpanOptions, EndMultiAgentSpanOptions, StartNodeSpanOptions, EndNodeSpanOptions, StartMemorySearchSpanOptions, EndMemorySearchSpanOptions, StartMemoryAddSpanOptions, EndMemoryAddSpanOptions, StartMemoryInjectSpanOptions, EndMemoryInjectSpanOptions, StartMemoryExtractSpanOptions, EndMemoryExtractSpanOptions } from './types.js'; import type { Message } from '../types/messages.js'; import type { JSONSerializable } from '../types/json.js'; /** * JSON-serializable representation of LocalTrace. */ interface AgentTraceData { id: string; name: string; parentId: string | null; startTime: number; endTime: number | null; duration: number; children: AgentTraceData[]; metadata: Record; message: Message | null; } /** * Execution trace for performance analysis. * Tracks timing and hierarchy of operations within the agent loop. * Fields default to null for JSON serialization compatibility. */ export declare class AgentTrace implements JSONSerializable { /** Unique identifier (UUID) for this trace. */ readonly id: string; /** Human-readable display name (e.g., "Cycle 1", "Tool: calc", "stream_messages"). */ readonly name: string; /** ID of the parent trace, if this trace is nested. Null for root traces. */ readonly parentId: string | null; /** Start time in milliseconds since epoch. */ readonly startTime: number; /** End time in milliseconds since epoch. Null until trace is ended. */ endTime: number | null; /** Duration in milliseconds (endTime - startTime). */ duration: number; /** Child traces nested under this trace. */ readonly children: AgentTrace[]; /** Additional metadata for this trace (e.g., cycleId, toolUseId, toolName). */ readonly metadata: Record; /** Message associated with this trace (e.g., model output). Null if not applicable. */ message: Message | null; /** * @param name - Display name for this trace * @param options - Optional configuration for parent and startTime */ constructor(name: string, options?: { parent?: AgentTrace; startTime?: number; }); /** * @param endTime - Optional end time in milliseconds since epoch */ end(endTime?: number): void; toJSON(): AgentTraceData; } /** * Manages both OpenTelemetry spans and local execution traces for agent operations. * * OTel spans are exported to external observability backends (Jaeger, X-Ray, etc.) * when configured via setupTracer(). Local traces are lightweight, in-memory timing * trees that are always collected regardless of OTel configuration and returned * in AgentResult.traces for programmatic access. * * */ export declare class Tracer { /** * OpenTelemetry tracer instance obtained from the global API. */ private readonly _tracer; /** * Whether to use latest experimental semantic conventions. * * Enabled via `OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental`. * Changes attribute names (e.g., `gen_ai.system` → `gen_ai.provider.name`) and * event formats (single `gen_ai.client.inference.operation.details` event vs * separate per-message events). Enable when your observability backend supports * newer GenAI conventions. * * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/ */ private readonly _useLatestConventions; /** * Whether to include full tool JSON schemas in span attributes. * * Enabled via `OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_tool_definitions`. * Useful for debugging tool configuration issues. Disabled by default to * reduce span payload size and observability costs. * * Can be combined with other options: * `OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental,gen_ai_tool_definitions` */ private readonly _includeToolDefinitions; /** * Custom attributes to include on all spans created by this tracer. */ private readonly _traceAttributes; /** Root span for the current agent invocation. */ private _agentSpan; /** Span for the current agent loop cycle, used to parent model and tool spans. */ private _loopSpan; /** Root span for the current multi-agent orchestration, used to parent node spans. */ private _multiAgentSpan; /** * Whether Langfuse is configured as the OTLP endpoint. * Detected from OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, * or LANGFUSE_BASE_URL environment variables. */ private readonly _isLangfuse; /** In-memory execution trace state, collected independently of OTEL. */ private readonly _traceState; /** * Initialize the tracer with OpenTelemetry configuration. * Reads OTEL_SEMCONV_STABILITY_OPT_IN to determine convention version. * Gets tracer from the global API to ensure ground truth - works correctly * whether the user or Strands initialized the tracer provider. * * @param traceAttributes - Optional custom attributes to include on all spans */ constructor(traceAttributes?: Record); /** * All local execution traces collected by this tracer. */ get localTraces(): AgentTrace[]; /** * Start an agent invocation span. * Returns the span which should be ended with endAgentSpan. * Parents to the current active span from context.active(). * * @param options - Options for starting the agent span */ startAgentSpan(options: StartAgentSpanOptions): Span | null; /** * End an agent invocation span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the span including response, error, and usage data */ endAgentSpan(span: Span | null, options?: EndAgentSpanOptions): void; /** * Start a model invocation span. * Parents to the current active span from context.active(). * * @param options - Options for starting the model invocation span */ startModelInvokeSpan(options: StartModelInvokeSpanOptions): Span | null; /** * End a model invocation span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the span including usage, metrics, error, and output */ endModelInvokeSpan(span: Span | null, options?: EndModelSpanOptions): void; /** * Start a tool call span. * Parents to the current active span from context.active(). * * @param options - Options for starting the tool call span */ startToolCallSpan(options: StartToolCallSpanOptions): Span | null; /** * End a tool call span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the tool call span */ endToolCallSpan(span: Span | null, options?: EndToolCallSpanOptions): void; /** * Start a multi-agent orchestration span. * Parents to the current active span from context.active(). * * @param options - Options for starting the multi-agent span * @returns The span, or null if span creation failed */ startMultiAgentSpan(options: StartMultiAgentSpanOptions): Span | null; /** * End a multi-agent orchestration span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the span including duration and error */ endMultiAgentSpan(span: Span | null, options?: EndMultiAgentSpanOptions): void; /** * Start a node execution span. * Parents to the current active span from context.active(). * * @param options - Options for starting the node span * @returns The span, or null if span creation failed */ startNodeSpan(options: StartNodeSpanOptions): Span | null; /** * End a node execution span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the span including status, duration, and error */ endNodeSpan(span: Span | null, options?: EndNodeSpanOptions): void; /** * Start a memory search span. * * The query is recorded verbatim as a span event, consistent with how model and tool spans * record their inputs. Memory payloads may contain user PII; suppress span content at the * exporter or processor when that is a concern. Parents to the current active span. * * @param options - Options for starting the memory search span */ startMemorySearchSpan(options: StartMemorySearchSpanOptions): Span | null; /** * End a memory search span with the retrieved entries. * * Per-store failures are logged and skipped by the manager, so a non-zero `storeFailureCount` * still ends the span OK; only `error` marks it as failed. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the memory search span */ endMemorySearchSpan(span: Span | null, options?: EndMemorySearchSpanOptions): void; /** * Start a memory add span. * * The content is recorded verbatim as a span event, consistent with how model and tool spans * record their inputs. Memory payloads may contain user PII; suppress span content at the * exporter or processor when that is a concern. * * @param options - Options for starting the memory add span */ startMemoryAddSpan(options: StartMemoryAddSpanOptions): Span | null; /** * End a memory add span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the memory add span */ endMemoryAddSpan(span: Span | null, options?: EndMemoryAddSpanOptions): void; /** * Start a memory context injection span. * * @param options - Options for starting the memory injection span */ startMemoryInjectSpan(options?: StartMemoryInjectSpanOptions): Span | null; /** * End a memory injection span. * * Injection fails open, so a format failure ends the span OK with a flag rather than an error * status (the agent did not fail). * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the memory injection span */ endMemoryInjectSpan(span: Span | null, options: EndMemoryInjectSpanOptions): void; /** * Start a memory extraction span as a trace root. * * Extraction runs detached from the agent invocation that scheduled it (the agent span has * typically ended by the time the save runs), so the span is a trace root, optionally linked * back to the agent span for causality. * * @param options - Options for starting the memory extraction span */ startMemoryExtractSpan(options: StartMemoryExtractSpanOptions): Span | null; /** * End a memory extraction span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the memory extraction span */ endMemoryExtractSpan(span: Span | null, options?: EndMemoryExtractSpanOptions): void; /** * Capture the current active span's context for linking, if one is recording. * * Used to associate a detached extraction span with the agent run that scheduled it: the * context is captured synchronously while the agent span is live, then attached as a link. * * @returns The active span's context, or undefined when no recording span with a valid context is active * @internal */ currentSpanContext(): SpanContext | undefined; /** * Runs a callback with the given span set as the active OpenTelemetry context. * Downstream code (e.g., MCP clients) can read the span from context.active() * for distributed trace propagation. No-ops if span is null. * * @param span - The span to set as active, or null if span creation failed * @param fn - The callback to run within the span's context * @returns The return value of the callback */ withSpanContext(span: Span | null, fn: () => T): T; /** * Start an agent loop cycle span. * Parents to the current active span from context.active(). * * @param options - Options for starting the agent loop span */ startAgentLoopSpan(options: StartAgentLoopSpanOptions): Span | null; /** * End an agent loop cycle span. * * @param span - The span to end, or null if span creation failed * @param options - Options for ending the agent loop span */ endAgentLoopSpan(span: Span | null, options?: EndAgentLoopSpanOptions): void; /** * Create a span parented to the current active context. */ private _startSpan; /** * End a span with the given attributes and optional error. */ private _endSpan; /** * Add an event to a span. */ private _addEvent; /** * Get common attributes based on semantic convention version. * The attribute name changed between OTEL semconv versions: * - Stable: 'gen_ai.system' * - Latest experimental: 'gen_ai.provider.name' */ private _getCommonAttributes; /** * Add message events to a span. * Uses different event formats based on semantic convention version: * - Latest: Single 'gen_ai.client.inference.operation.details' event with all messages * - Stable: Separate events per message (gen_ai.user.message, gen_ai.assistant.message, etc.) */ private _addEventMessages; /** * Get the event name for a message based on its type. */ private _getEventNameForMessage; /** * Set usage attributes on an attributes object. * Sets both legacy (prompt_tokens/completion_tokens) and new (input_tokens/output_tokens) * attribute names for compatibility with different OTEL backends. */ private _setUsageAttributes; /** * Set metrics attributes on an attributes object. */ private _setMetricsAttributes; /** * Add response event to a span. */ private _addResponseEvent; /** * Add output event to a span for model invocation. */ private _addOutputEvent; /** * Parse the OTEL_SEMCONV_STABILITY_OPT_IN environment variable. */ private static _parseSemconvOptIn; /** * Detect whether Langfuse is configured as the OTLP endpoint. * Checks OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, * and LANGFUSE_BASE_URL environment variables. */ private static _detectLangfuse; /** * Emit system prompt as a span event per OTel GenAI semantic conventions. * In stable mode, emits a `gen_ai.system.message` event. * In latest experimental mode, emits `gen_ai.system_instructions` on the * `gen_ai.client.inference.operation.details` event. * * @param span - The span to add the event to * @param systemPrompt - The system prompt provided to the model */ private _addSystemPromptEvent; /** * Map a system prompt to OTEL parts format (latest conventions). * Handles both string prompts and SystemContentBlock arrays. */ private static _mapSystemPromptToOtelParts; /** * Map content blocks to OTEL parts format (latest conventions). * Converts SDK content block types to OTEL semantic convention format. */ private static _mapContentBlocksToOtelParts; /** * Map content blocks to stable format (older conventions). * Simplifies content blocks to a minimal structure for legacy OTEL backends. */ private static _mapContentBlocksToStableFormat; } export {}; //# sourceMappingURL=tracer.d.ts.map