@prefactor/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/config.d.ts +259 -0
  2. package/dist/config.d.ts.map +1 -0
  3. package/dist/config.js +110 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/index.cjs +642 -0
  6. package/dist/index.cjs.map +17 -0
  7. package/dist/index.d.ts +10 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +610 -0
  10. package/dist/index.js.map +17 -0
  11. package/dist/tracing/context.d.ts +53 -0
  12. package/dist/tracing/context.d.ts.map +1 -0
  13. package/dist/tracing/context.js +66 -0
  14. package/dist/tracing/context.js.map +1 -0
  15. package/dist/tracing/span.d.ts +68 -0
  16. package/dist/tracing/span.d.ts.map +1 -0
  17. package/dist/tracing/span.js +21 -0
  18. package/dist/tracing/span.js.map +1 -0
  19. package/dist/tracing/tracer.d.ts +100 -0
  20. package/dist/tracing/tracer.d.ts.map +1 -0
  21. package/dist/tracing/tracer.js +151 -0
  22. package/dist/tracing/tracer.js.map +1 -0
  23. package/dist/transport/base.d.ts +38 -0
  24. package/dist/transport/base.d.ts.map +1 -0
  25. package/dist/transport/base.js +2 -0
  26. package/dist/transport/base.js.map +1 -0
  27. package/dist/transport/http.d.ts +90 -0
  28. package/dist/transport/http.d.ts.map +1 -0
  29. package/dist/transport/http.js +399 -0
  30. package/dist/transport/http.js.map +1 -0
  31. package/dist/transport/stdio.d.ts +48 -0
  32. package/dist/transport/stdio.d.ts.map +1 -0
  33. package/dist/transport/stdio.js +71 -0
  34. package/dist/transport/stdio.js.map +1 -0
  35. package/dist/utils/logging.d.ts +29 -0
  36. package/dist/utils/logging.d.ts.map +1 -0
  37. package/dist/utils/logging.js +71 -0
  38. package/dist/utils/logging.js.map +1 -0
  39. package/dist/utils/serialization.d.ts +24 -0
  40. package/dist/utils/serialization.d.ts.map +1 -0
  41. package/dist/utils/serialization.js +60 -0
  42. package/dist/utils/serialization.js.map +1 -0
  43. package/package.json +36 -0
@@ -0,0 +1,17 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/config.ts", "../src/tracing/context.ts", "../src/tracing/span.ts", "../src/tracing/tracer.ts", "../src/utils/logging.ts", "../src/transport/http.ts", "../src/utils/serialization.ts", "../src/transport/stdio.ts"],
4
+ "sourcesContent": [
5
+ "import { z } from 'zod';\n\n/**\n * Configuration schema for HTTP transport\n */\nexport const HttpTransportConfigSchema = z.object({\n /** API endpoint URL */\n apiUrl: z.string().url(),\n\n /** Authentication token */\n apiToken: z.string().min(1),\n\n /** Optional agent identifier */\n agentId: z.string().optional(),\n\n /** Optional agent version */\n agentVersion: z.string().optional(),\n\n /** Optional agent name */\n agentName: z.string().optional(),\n\n /** Optional agent description */\n agentDescription: z.string().optional(),\n\n /** Optional agent schema for validation (full schema object) */\n agentSchema: z.record(z.unknown()).optional(),\n\n /** Optional agent schema version identifier (string) */\n agentSchemaVersion: z.string().optional(),\n\n /** Skip schema validation */\n skipSchema: z.boolean().default(false),\n\n /** Request timeout in milliseconds */\n requestTimeout: z.number().positive().default(30000),\n\n /** Connection timeout in milliseconds */\n connectTimeout: z.number().positive().default(10000),\n\n /** Maximum number of retry attempts */\n maxRetries: z.number().int().nonnegative().default(3),\n\n /** Initial delay between retries in milliseconds */\n initialRetryDelay: z.number().positive().default(1000),\n\n /** Maximum delay between retries in milliseconds */\n maxRetryDelay: z.number().positive().default(60000),\n\n /** Multiplier for exponential backoff */\n retryMultiplier: z.number().positive().default(2.0),\n});\n\nexport type HttpTransportConfig = z.infer<typeof HttpTransportConfigSchema>;\n\n/**\n * Partial HTTP config schema for user input (before defaults are applied)\n */\nexport const PartialHttpConfigSchema = z.object({\n apiUrl: z.string().url(),\n apiToken: z.string().min(1),\n agentId: z.string().optional(),\n agentVersion: z.string().optional(),\n agentName: z.string().optional(),\n agentDescription: z.string().optional(),\n agentSchema: z.record(z.unknown()).optional(),\n agentSchemaVersion: z.string().optional(),\n skipSchema: z.boolean().optional(),\n requestTimeout: z.number().positive().optional(),\n connectTimeout: z.number().positive().optional(),\n maxRetries: z.number().int().nonnegative().optional(),\n initialRetryDelay: z.number().positive().optional(),\n maxRetryDelay: z.number().positive().optional(),\n retryMultiplier: z.number().positive().optional(),\n});\n\nexport type PartialHttpConfig = z.infer<typeof PartialHttpConfigSchema>;\n\n/**\n * Main SDK configuration schema\n */\nexport const ConfigSchema = z.object({\n /** Transport type to use for span emission */\n transportType: z.enum(['stdio', 'http']).default('stdio'),\n\n /** Sampling rate (0.0 to 1.0) */\n sampleRate: z.number().min(0).max(1).default(1.0),\n\n /** Whether to capture span inputs */\n captureInputs: z.boolean().default(true),\n\n /** Whether to capture span outputs */\n captureOutputs: z.boolean().default(true),\n\n /** Maximum length for input strings */\n maxInputLength: z.number().int().positive().default(10000),\n\n /** Maximum length for output strings */\n maxOutputLength: z.number().int().positive().default(10000),\n\n /** HTTP transport configuration (required if transportType is 'http') */\n httpConfig: PartialHttpConfigSchema.optional(),\n});\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/**\n * Creates a validated configuration object by merging provided options with\n * environment variables and defaults.\n *\n * @param options - Partial configuration options\n * @returns Validated configuration object\n * @throws {z.ZodError} If configuration is invalid\n *\n * @example\n * ```typescript\n * const config = createConfig({\n * transportType: 'http',\n * httpConfig: {\n * apiUrl: 'https://api.prefactor.ai',\n * apiToken: process.env.PREFACTOR_API_TOKEN!,\n * }\n * });\n * ```\n */\nexport function createConfig(options?: Partial<Config>): Config {\n const config = {\n transportType:\n options?.transportType ??\n (process.env.PREFACTOR_TRANSPORT as 'stdio' | 'http' | undefined) ??\n 'stdio',\n sampleRate: options?.sampleRate ?? parseFloat(process.env.PREFACTOR_SAMPLE_RATE ?? '1.0'),\n captureInputs: options?.captureInputs ?? process.env.PREFACTOR_CAPTURE_INPUTS !== 'false',\n captureOutputs: options?.captureOutputs ?? process.env.PREFACTOR_CAPTURE_OUTPUTS !== 'false',\n maxInputLength:\n options?.maxInputLength ?? parseInt(process.env.PREFACTOR_MAX_INPUT_LENGTH ?? '10000', 10),\n maxOutputLength:\n options?.maxOutputLength ?? parseInt(process.env.PREFACTOR_MAX_OUTPUT_LENGTH ?? '10000', 10),\n httpConfig: options?.httpConfig,\n };\n\n // Validate and return\n return ConfigSchema.parse(config);\n}\n",
6
+ "import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Span } from './span.js';\n\n/**\n * Storage for the current span in async context\n */\nconst spanStorage = new AsyncLocalStorage<Span>();\n\n/**\n * SpanContext manages the current span in async execution contexts.\n * This enables automatic parent-child span relationships without manual tracking.\n *\n * Uses Node.js AsyncLocalStorage which provides async-safe context propagation.\n *\n * @example\n * ```typescript\n * const span = tracer.startSpan({ name: 'parent', ... });\n *\n * await SpanContext.runAsync(span, async () => {\n * // Inside this function, getCurrent() returns the parent span\n * const parent = SpanContext.getCurrent();\n *\n * const child = tracer.startSpan({\n * name: 'child',\n * parentSpanId: parent?.spanId,\n * traceId: parent?.traceId,\n * });\n * // ...\n * });\n * ```\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: Intentional API design for namespacing context operations\nexport class SpanContext {\n /**\n * Get the current span from the async context\n *\n * @returns The current span, or undefined if no span is active\n */\n static getCurrent(): Span | undefined {\n return spanStorage.getStore();\n }\n\n /**\n * Run a synchronous function with the given span as the current context\n *\n * @param span - The span to set as current\n * @param fn - The function to execute\n * @returns The return value of the function\n */\n static run<T>(span: Span, fn: () => T): T {\n return spanStorage.run(span, fn);\n }\n\n /**\n * Run an asynchronous function with the given span as the current context\n *\n * @param span - The span to set as current\n * @param fn - The async function to execute\n * @returns A promise resolving to the return value of the function\n */\n static async runAsync<T>(span: Span, fn: () => Promise<T>): Promise<T> {\n return spanStorage.run(span, fn);\n }\n\n /**\n * Clear the current context (primarily for testing)\n */\n static clear(): void {\n spanStorage.disable();\n }\n}\n",
7
+ "/**\n * Types of spans that can be traced\n */\nexport enum SpanType {\n AGENT = 'agent',\n LLM = 'llm',\n TOOL = 'tool',\n CHAIN = 'chain',\n RETRIEVER = 'retriever',\n}\n\n/**\n * Status of a span\n */\nexport enum SpanStatus {\n RUNNING = 'running',\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\n/**\n * Token usage information for LLM calls\n */\nexport interface TokenUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n}\n\n/**\n * Error information captured when a span fails\n */\nexport interface ErrorInfo {\n errorType: string;\n message: string;\n stacktrace: string;\n}\n\n/**\n * A span represents a single operation in a trace\n */\nexport interface Span {\n /** Unique identifier for this span */\n spanId: string;\n\n /** ID of the parent span, or null if this is a root span */\n parentSpanId: string | null;\n\n /** Trace ID shared by all spans in a single trace */\n traceId: string;\n\n /** Human-readable name for this span */\n name: string;\n\n /** Type of operation this span represents */\n spanType: SpanType;\n\n /** Start time in milliseconds since Unix epoch */\n startTime: number;\n\n /** End time in milliseconds since Unix epoch, or null if still running */\n endTime: number | null;\n\n /** Current status of the span */\n status: SpanStatus;\n\n /** Input data for this operation */\n inputs: Record<string, unknown>;\n\n /** Output data from this operation, or null if not completed */\n outputs: Record<string, unknown> | null;\n\n /** Token usage for LLM calls, or null if not applicable */\n tokenUsage: TokenUsage | null;\n\n /** Error information if the span failed, or null if successful */\n error: ErrorInfo | null;\n\n /** Additional metadata about this span */\n metadata: Record<string, unknown>;\n\n /** Tags for categorizing and filtering spans */\n tags: string[];\n}\n",
8
+ "import { generate, generatePartition, type Partition } from '@prefactor/pfid';\nimport type { Transport } from '../transport/base.js';\nimport type { Span, SpanType, TokenUsage } from './span.js';\nimport { SpanStatus } from './span.js';\n\n/**\n * Options for starting a new span\n */\nexport interface StartSpanOptions {\n /** Name of the span */\n name: string;\n\n /** Type of operation this span represents */\n spanType: SpanType;\n\n /** Input data for this operation */\n inputs: Record<string, unknown>;\n\n /** ID of the parent span (optional) */\n parentSpanId?: string;\n\n /** Trace ID to use (optional, will generate if not provided) */\n traceId?: string;\n\n /** Additional metadata (optional) */\n metadata?: Record<string, unknown>;\n\n /** Tags for categorizing the span (optional) */\n tags?: string[];\n}\n\n/**\n * Options for ending a span\n */\nexport interface EndSpanOptions {\n /** Output data from the operation */\n outputs?: Record<string, unknown>;\n\n /** Error that occurred (if any) */\n error?: Error;\n\n /** Token usage information (for LLM calls) */\n tokenUsage?: TokenUsage;\n}\n\n/**\n * Tracer manages the lifecycle of spans.\n *\n * The tracer is responsible for:\n * - Creating spans with unique IDs\n * - Managing span lifecycle (start/end)\n * - Delegating to the transport layer for span emission\n * - Handling agent instance lifecycle\n *\n * @example\n * ```typescript\n * const tracer = new Tracer(transport);\n *\n * const span = tracer.startSpan({\n * name: 'llm-call',\n * spanType: SpanType.LLM,\n * inputs: { prompt: 'Hello' }\n * });\n *\n * try {\n * // ... do work ...\n * tracer.endSpan(span, { outputs: { response: 'Hi!' } });\n * } catch (error) {\n * tracer.endSpan(span, { error });\n * }\n * ```\n */\nexport class Tracer {\n private partition: Partition;\n\n /**\n * Initialize the tracer.\n *\n * @param transport - The transport to use for emitting spans\n * @param partition - The partition for ID generation. If not provided, a random partition will be generated.\n */\n constructor(\n private transport: Transport,\n partition?: Partition\n ) {\n this.partition = partition ?? generatePartition();\n }\n\n /**\n * Start a new span\n *\n * @param options - Span configuration options\n * @returns The created span\n */\n startSpan(options: StartSpanOptions): Span {\n const spanId = generate(this.partition);\n const traceId = options.traceId ?? generate(this.partition);\n\n const span: Span = {\n spanId,\n parentSpanId: options.parentSpanId ?? null,\n traceId,\n name: options.name,\n spanType: options.spanType,\n startTime: Date.now(),\n endTime: null,\n status: SpanStatus.RUNNING,\n inputs: options.inputs,\n outputs: null,\n tokenUsage: null,\n error: null,\n metadata: options.metadata ?? {},\n tags: options.tags ?? [],\n };\n\n // AGENT spans are emitted immediately for real-time tracking\n // They will be finished later with finishSpan()\n if (options.spanType === 'agent') {\n try {\n this.transport.emit(span);\n } catch (error) {\n console.error('Failed to emit agent span:', error);\n }\n }\n\n return span;\n }\n\n /**\n * End a span and emit it to the transport\n *\n * @param span - The span to end\n * @param options - End span options (outputs, error, token usage)\n */\n endSpan(span: Span, options?: EndSpanOptions): void {\n span.endTime = Date.now();\n span.outputs = options?.outputs ?? null;\n span.tokenUsage = options?.tokenUsage ?? null;\n\n if (options?.error) {\n span.status = SpanStatus.ERROR;\n span.error = {\n errorType: options.error.constructor.name,\n message: options.error.message,\n stacktrace: options.error.stack ?? '',\n };\n } else {\n span.status = SpanStatus.SUCCESS;\n }\n\n try {\n // AGENT spans use finishSpan API (they were already emitted on start)\n // Other span types are emitted here\n if (span.spanType === 'agent') {\n this.transport.finishSpan(span.spanId, span.endTime);\n } else {\n this.transport.emit(span);\n }\n } catch (error) {\n console.error('Failed to emit/finish span:', error);\n }\n }\n\n /**\n * Signal the start of an agent instance execution\n */\n startAgentInstance(): void {\n try {\n this.transport.startAgentInstance();\n } catch (error) {\n console.error('Failed to start agent instance:', error);\n }\n }\n\n /**\n * Signal the completion of an agent instance execution\n */\n finishAgentInstance(): void {\n try {\n this.transport.finishAgentInstance();\n } catch (error) {\n console.error('Failed to finish agent instance:', error);\n }\n }\n\n /**\n * Close the tracer and flush any pending spans\n *\n * @returns Promise that resolves when the tracer is closed\n */\n async close(): Promise<void> {\n try {\n await this.transport.close();\n } catch (error) {\n console.error('Failed to close transport:', error);\n }\n }\n}\n",
9
+ "/**\n * Log levels for the SDK\n */\nenum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n}\n\n/**\n * Logger class for the Prefactor SDK\n */\nclass Logger {\n private static level: LogLevel = LogLevel.INFO;\n\n constructor(private namespace: string) {}\n\n debug(message: string, ...args: unknown[]): void {\n if (Logger.level <= LogLevel.DEBUG) {\n console.debug(`[prefactor:${this.namespace}] ${message}`, ...args);\n }\n }\n\n info(message: string, ...args: unknown[]): void {\n if (Logger.level <= LogLevel.INFO) {\n console.info(`[prefactor:${this.namespace}] ${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: unknown[]): void {\n if (Logger.level <= LogLevel.WARN) {\n console.warn(`[prefactor:${this.namespace}] ${message}`, ...args);\n }\n }\n\n error(message: string, ...args: unknown[]): void {\n if (Logger.level <= LogLevel.ERROR) {\n console.error(`[prefactor:${this.namespace}] ${message}`, ...args);\n }\n }\n\n /**\n * Set the global log level\n */\n static setLevel(level: 'debug' | 'info' | 'warn' | 'error'): void {\n const levelMap = {\n debug: LogLevel.DEBUG,\n info: LogLevel.INFO,\n warn: LogLevel.WARN,\n error: LogLevel.ERROR,\n };\n Logger.level = levelMap[level];\n }\n}\n\n/**\n * Get a logger instance for a specific namespace\n *\n * @param namespace - The namespace for this logger\n * @returns Logger instance\n */\nexport function getLogger(namespace: string): Logger {\n return new Logger(namespace);\n}\n\n/**\n * Configure logging based on environment variables\n */\nexport function configureLogging(): void {\n const level = process.env.PREFACTOR_LOG_LEVEL?.toLowerCase() as\n | 'debug'\n | 'info'\n | 'warn'\n | 'error'\n | undefined;\n\n if (level) {\n Logger.setLevel(level);\n }\n}\n",
10
+ "import type { HttpTransportConfig } from '../config.js';\nimport type { Span } from '../tracing/span.js';\nimport { getLogger } from '../utils/logging.js';\nimport type { Transport } from './base.js';\n\nconst logger = getLogger('http-transport');\n\n/**\n * Queue item types for background processing\n */\ninterface QueueItem {\n type: 'span' | 'finish_span' | 'start_agent' | 'finish_agent';\n data: unknown;\n}\n\n/**\n * HTTP transport sends spans to a remote API endpoint.\n *\n * Features:\n * - Queue-based async processing\n * - Exponential backoff retry logic\n * - Span ID mapping (SDK ID → backend ID)\n * - Agent instance lifecycle management\n * - Graceful shutdown with timeout\n *\n * @example\n * ```typescript\n * const transport = new HttpTransport({\n * apiUrl: 'https://api.prefactor.ai',\n * apiToken: process.env.PREFACTOR_API_TOKEN!,\n * });\n * ```\n */\nexport class HttpTransport implements Transport {\n private queue: QueueItem[] = [];\n private processing = false;\n private closed = false;\n private agentInstanceId: string | null = null;\n private spanIdMap = new Map<string, string>();\n\n constructor(private config: HttpTransportConfig) {\n this.startProcessing();\n }\n\n /**\n * Emit a span (adds to queue for async processing)\n *\n * @param span - The span to emit\n */\n emit(span: Span): void {\n if (this.closed) {\n return;\n }\n this.queue.push({ type: 'span', data: span });\n }\n\n /**\n * Finish a previously emitted span (for AGENT spans)\n *\n * @param spanId - ID of the span to finish\n * @param endTime - End time in milliseconds since Unix epoch\n */\n finishSpan(spanId: string, endTime: number): void {\n if (this.closed) {\n return;\n }\n const timestamp = new Date(endTime).toISOString();\n this.queue.push({ type: 'finish_span', data: { spanId, timestamp } });\n }\n\n /**\n * Signal the start of an agent instance execution\n */\n startAgentInstance(): void {\n if (this.closed) {\n return;\n }\n this.queue.push({ type: 'start_agent', data: null });\n }\n\n /**\n * Signal the completion of an agent instance execution\n */\n finishAgentInstance(): void {\n if (this.closed) {\n return;\n }\n this.queue.push({ type: 'finish_agent', data: null });\n }\n\n /**\n * Start background queue processing\n */\n private async startProcessing(): Promise<void> {\n this.processing = true;\n\n while (!this.closed || this.queue.length > 0) {\n if (this.queue.length === 0) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n continue;\n }\n\n const item = this.queue.shift();\n if (!item) continue;\n\n try {\n // Ensure agent is registered before processing spans\n if (!this.agentInstanceId && item.type !== 'start_agent') {\n await this.ensureAgentRegistered();\n }\n\n switch (item.type) {\n case 'span':\n await this.sendSpan(item.data as Span);\n break;\n case 'finish_span':\n await this.finishSpanHttp(item.data as { spanId: string; timestamp: string });\n break;\n case 'start_agent':\n await this.startAgentInstanceHttp();\n break;\n case 'finish_agent':\n await this.finishAgentInstanceHttp();\n break;\n }\n } catch (error) {\n logger.error('Error processing queue item:', error);\n }\n }\n\n this.processing = false;\n }\n\n /**\n * Send a span to the API\n */\n private async sendSpan(span: Span, retry = 0): Promise<void> {\n const url = `${this.config.apiUrl}/api/v1/agent_spans`;\n const payload = this.transformSpanToApiFormat(span);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.config.apiToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.config.requestTimeout),\n });\n\n if (response.ok) {\n const data = (await response.json()) as { details?: { id?: string } };\n const backendSpanId = data?.details?.id;\n if (backendSpanId) {\n this.spanIdMap.set(span.spanId, backendSpanId);\n }\n return;\n }\n\n // Retry on server errors or rate limiting\n if ((response.status >= 500 || response.status === 429) && retry < this.config.maxRetries) {\n const delay = Math.min(\n this.config.initialRetryDelay * this.config.retryMultiplier ** retry,\n this.config.maxRetryDelay\n );\n logger.debug(`Retrying span send after ${delay}ms (attempt ${retry + 1})`);\n await new Promise((resolve) => setTimeout(resolve, delay));\n return this.sendSpan(span, retry + 1);\n }\n\n logger.error(`Failed to send span: ${response.status} ${response.statusText}`);\n } catch (error) {\n logger.error('Error sending span:', error);\n\n // Retry on network errors\n if (retry < this.config.maxRetries) {\n const delay = Math.min(\n this.config.initialRetryDelay * this.config.retryMultiplier ** retry,\n this.config.maxRetryDelay\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n return this.sendSpan(span, retry + 1);\n }\n }\n }\n\n /**\n * Transform span to backend API format with nested details/payload structure\n */\n private transformSpanToApiFormat(span: Span): Record<string, unknown> {\n const startedAt = new Date(span.startTime).toISOString();\n const finishedAt = span.endTime ? new Date(span.endTime).toISOString() : null;\n\n // Build payload with span data\n const payload: Record<string, unknown> = {\n span_id: span.spanId,\n trace_id: span.traceId,\n name: span.name,\n status: span.status,\n inputs: span.inputs,\n outputs: span.outputs,\n metadata: span.metadata,\n tags: span.tags,\n token_usage: null,\n error: null,\n };\n\n // Add optional token_usage\n if (span.tokenUsage) {\n payload.token_usage = {\n prompt_tokens: span.tokenUsage.promptTokens,\n completion_tokens: span.tokenUsage.completionTokens,\n total_tokens: span.tokenUsage.totalTokens,\n };\n }\n\n // Add optional error\n if (span.error) {\n payload.error = {\n error_type: span.error.errorType,\n message: span.error.message,\n stacktrace: span.error.stacktrace,\n };\n }\n\n // Resolve parent span ID to backend ID\n const parentSpanId = span.parentSpanId ? (this.spanIdMap.get(span.parentSpanId) ?? null) : null;\n\n return {\n details: {\n agent_instance_id: this.agentInstanceId,\n schema_name: span.spanType,\n payload,\n parent_span_id: parentSpanId,\n started_at: startedAt,\n finished_at: finishedAt,\n },\n };\n }\n\n /**\n * Get default schema (v1.0.0) with span schemas for all supported types\n */\n private getDefaultSchema(): Record<string, unknown> {\n return {\n external_identifier: '1.0.0',\n span_schemas: {\n agent: {\n type: 'object',\n properties: { type: { type: 'string', const: 'agent' } },\n },\n llm: {\n type: 'object',\n properties: { type: { type: 'string', const: 'llm' } },\n },\n tool: {\n type: 'object',\n properties: { type: { type: 'string', const: 'tool' } },\n },\n chain: {\n type: 'object',\n properties: { type: { type: 'string', const: 'chain' } },\n },\n retriever: {\n type: 'object',\n properties: { type: { type: 'string', const: 'retriever' } },\n },\n },\n };\n }\n\n /**\n * Ensure an agent instance is registered\n */\n private async ensureAgentRegistered(): Promise<void> {\n if (this.agentInstanceId) {\n return;\n }\n\n const url = `${this.config.apiUrl}/api/v1/agent_instance/register`;\n const payload: Record<string, unknown> = {};\n\n if (this.config.agentId) payload.agent_id = this.config.agentId;\n if (this.config.agentVersion) {\n payload.agent_version = {\n external_identifier: this.config.agentVersion,\n name: this.config.agentName || 'Agent',\n description: this.config.agentDescription || '',\n };\n }\n\n // Schema handling - four modes:\n // 1. skipSchema=true: No schema in payload (pre-registered on backend)\n // 2. agentSchema provided: Use full custom schema object\n // 3. agentSchemaVersion provided: Use version identifier only\n // 4. None of above: Use default v1.0.0 schema\n if (this.config.skipSchema) {\n logger.debug('Skipping schema in registration (skipSchema=true)');\n // Do not add agent_schema_version key\n } else if (this.config.agentSchema) {\n logger.debug('Using custom agent schema');\n payload.agent_schema_version = this.config.agentSchema;\n } else if (this.config.agentSchemaVersion) {\n logger.debug(`Using schema version: ${this.config.agentSchemaVersion}`);\n payload.agent_schema_version = {\n external_identifier: this.config.agentSchemaVersion,\n };\n } else {\n logger.debug('Using default hardcoded schema (v1.0.0)');\n payload.agent_schema_version = this.getDefaultSchema();\n }\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.config.apiToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.config.requestTimeout),\n });\n\n if (response.ok) {\n const data = (await response.json()) as { details?: { id?: string } };\n this.agentInstanceId = data?.details?.id ?? null;\n logger.debug(`Registered agent instance: ${this.agentInstanceId}`);\n } else {\n logger.error(`Failed to register agent: ${response.status} ${response.statusText}`);\n }\n } catch (error) {\n logger.error('Error registering agent:', error);\n }\n }\n\n /**\n * Start agent instance execution\n */\n private async startAgentInstanceHttp(): Promise<void> {\n await this.ensureAgentRegistered();\n\n if (!this.agentInstanceId) {\n logger.error('Cannot start agent instance: not registered');\n return;\n }\n\n const url = `${this.config.apiUrl}/api/v1/agent_instance/${this.agentInstanceId}/start`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.config.apiToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({}),\n signal: AbortSignal.timeout(this.config.requestTimeout),\n });\n\n if (!response.ok) {\n logger.error(`Failed to start agent instance: ${response.status} ${response.statusText}`);\n }\n } catch (error) {\n logger.error('Error starting agent instance:', error);\n }\n }\n\n /**\n * Finish agent instance execution\n */\n private async finishAgentInstanceHttp(): Promise<void> {\n if (!this.agentInstanceId) {\n logger.error('Cannot finish agent instance: not registered');\n return;\n }\n\n const url = `${this.config.apiUrl}/api/v1/agent_instance/${this.agentInstanceId}/finish`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.config.apiToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({}),\n signal: AbortSignal.timeout(this.config.requestTimeout),\n });\n\n if (!response.ok) {\n logger.error(`Failed to finish agent instance: ${response.status} ${response.statusText}`);\n }\n } catch (error) {\n logger.error('Error finishing agent instance:', error);\n }\n }\n\n /**\n * Finish a span via HTTP\n */\n private async finishSpanHttp(data: { spanId: string; timestamp: string }): Promise<void> {\n const backendSpanId = this.spanIdMap.get(data.spanId);\n if (!backendSpanId) {\n logger.warn(`Cannot finish span ${data.spanId}: backend ID not found`);\n return;\n }\n\n const url = `${this.config.apiUrl}/api/v1/agent_spans/${backendSpanId}/finish`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.config.apiToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ timestamp: data.timestamp }),\n signal: AbortSignal.timeout(this.config.requestTimeout),\n });\n\n if (!response.ok) {\n logger.error(`Failed to finish span: ${response.status} ${response.statusText}`);\n }\n } catch (error) {\n logger.error('Error finishing span:', error);\n }\n }\n\n /**\n * Close the transport and wait for queue to drain\n *\n * @returns Promise that resolves when transport is closed\n */\n async close(): Promise<void> {\n this.closed = true;\n\n // Wait for queue to drain (with timeout)\n const timeout = 10000;\n const start = Date.now();\n while (this.processing && Date.now() - start < timeout) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n if (this.processing) {\n logger.warn('Transport closed with pending queue items');\n }\n }\n}\n",
11
+ "/**\n * Truncate a string to a maximum length, adding an ellipsis if truncated\n *\n * @param value - The string to truncate\n * @param maxLength - Maximum length\n * @returns Truncated string\n */\nexport function truncateString(value: string, maxLength: number): string {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}... [truncated]`;\n}\n\n/**\n * Serialize a value for JSON output, handling non-serializable types and\n * truncating long strings\n *\n * @param value - Value to serialize\n * @param maxLength - Maximum length for strings (null for no truncation)\n * @returns Serialized value\n *\n * @example\n * ```typescript\n * const serialized = serializeValue({ message: 'Hello'.repeat(1000) }, 100);\n * // Result: { message: 'HelloHelloHello... [truncated]' }\n * ```\n */\nexport function serializeValue(value: unknown, maxLength: number | null = 10000): unknown {\n // Handle primitives that don't need serialization\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === 'boolean' || typeof value === 'number') {\n return value;\n }\n\n // Handle strings with truncation\n if (typeof value === 'string') {\n return maxLength !== null ? truncateString(value, maxLength) : value;\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n return value.map((item) => serializeValue(item, maxLength));\n }\n\n // Handle objects\n if (typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = serializeValue(val, maxLength);\n }\n return result;\n }\n\n // Handle other types by converting to string\n try {\n return String(value);\n } catch {\n return `<${typeof value} object>`;\n }\n}\n",
12
+ "import type { Span } from '../tracing/span.js';\nimport { serializeValue } from '../utils/serialization.js';\nimport type { Transport } from './base.js';\n\n/**\n * STDIO transport emits spans as newline-delimited JSON to stdout.\n *\n * This is the default transport and requires no configuration.\n * It's useful for local development and for piping span data to other tools.\n *\n * Features:\n * - Newline-delimited JSON output\n * - Promise-based write locking for ordering\n * - Graceful error handling\n *\n * @example\n * ```typescript\n * const transport = new StdioTransport();\n * const tracer = new Tracer(transport);\n * ```\n */\nexport class StdioTransport implements Transport {\n private closed = false;\n private writeLock = Promise.resolve();\n\n /**\n * Emit a span to stdout as JSON\n *\n * @param span - The span to emit\n */\n emit(span: Span): void {\n if (this.closed) {\n return;\n }\n\n // Queue write to maintain ordering\n this.writeLock = this.writeLock.then(async () => {\n try {\n const serialized = serializeValue(span);\n const json = JSON.stringify(serialized);\n await Bun.write(Bun.stdout, `${json}\\n`);\n } catch (error) {\n console.error('Failed to emit span to stdout:', error);\n }\n });\n }\n\n /**\n * No-op for stdio transport (not applicable)\n */\n finishSpan(): void {\n // No-op for stdio transport\n }\n\n /**\n * No-op for stdio transport (not applicable)\n */\n startAgentInstance(): void {\n // No-op for stdio transport\n }\n\n /**\n * No-op for stdio transport (not applicable)\n */\n finishAgentInstance(): void {\n // No-op for stdio transport\n }\n\n /**\n * Close the transport and wait for pending writes to complete\n *\n * @returns Promise that resolves when all writes are complete\n */\n async close(): Promise<void> {\n this.closed = true;\n await this.writeLock;\n }\n}\n"
13
+ ],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IAAI,CAAC,MAAkB;AAAA,IACrB,IAAI,KAAK,QAAQ;AAAA,MACf;AAAA,IACF;AAAA,IAGA,KAAK,YAAY,KAAK,UAAU,KAAK,YAAY;AAAA,MAC/C,IAAI;AAAA,QACF,MAAM,aAAa,eAAe,IAAI;AAAA,QACtC,MAAM,OAAO,KAAK,UAAU,UAAU;AAAA,QACtC,MAAM,IAAI,MAAM,IAAI,QAAQ,GAAG;AAAA,CAAQ;AAAA,QACvC,OAAO,OAAO;AAAA,QACd,QAAQ,MAAM,kCAAkC,KAAK;AAAA;AAAA,KAExD;AAAA;AAAA,EAMH,UAAU,GAAS;AAAA,EAOnB,kBAAkB,GAAS;AAAA,EAO3B,mBAAmB,GAAS;AAAA,OAStB,MAAK,GAAkB;AAAA,IAC3B,KAAK,SAAS;AAAA,IACd,MAAM,KAAK;AAAA;AAEf;",
15
+ "debugId": "48E67D6DE4160D4864756E2164756E21",
16
+ "names": []
17
+ }
@@ -0,0 +1,53 @@
1
+ import type { Span } from './span.js';
2
+ /**
3
+ * SpanContext manages the current span in async execution contexts.
4
+ * This enables automatic parent-child span relationships without manual tracking.
5
+ *
6
+ * Uses Node.js AsyncLocalStorage which provides async-safe context propagation.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const span = tracer.startSpan({ name: 'parent', ... });
11
+ *
12
+ * await SpanContext.runAsync(span, async () => {
13
+ * // Inside this function, getCurrent() returns the parent span
14
+ * const parent = SpanContext.getCurrent();
15
+ *
16
+ * const child = tracer.startSpan({
17
+ * name: 'child',
18
+ * parentSpanId: parent?.spanId,
19
+ * traceId: parent?.traceId,
20
+ * });
21
+ * // ...
22
+ * });
23
+ * ```
24
+ */
25
+ export declare class SpanContext {
26
+ /**
27
+ * Get the current span from the async context
28
+ *
29
+ * @returns The current span, or undefined if no span is active
30
+ */
31
+ static getCurrent(): Span | undefined;
32
+ /**
33
+ * Run a synchronous function with the given span as the current context
34
+ *
35
+ * @param span - The span to set as current
36
+ * @param fn - The function to execute
37
+ * @returns The return value of the function
38
+ */
39
+ static run<T>(span: Span, fn: () => T): T;
40
+ /**
41
+ * Run an asynchronous function with the given span as the current context
42
+ *
43
+ * @param span - The span to set as current
44
+ * @param fn - The async function to execute
45
+ * @returns A promise resolving to the return value of the function
46
+ */
47
+ static runAsync<T>(span: Span, fn: () => Promise<T>): Promise<T>;
48
+ /**
49
+ * Clear the current context (primarily for testing)
50
+ */
51
+ static clear(): void;
52
+ }
53
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/tracing/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAOtC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,qBAAa,WAAW;IACtB;;;;OAIG;IACH,MAAM,CAAC,UAAU,IAAI,IAAI,GAAG,SAAS;IAIrC;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC;IAIzC;;;;;;OAMG;WACU,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAItE;;OAEG;IACH,MAAM,CAAC,KAAK,IAAI,IAAI;CAGrB"}
@@ -0,0 +1,66 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ /**
3
+ * Storage for the current span in async context
4
+ */
5
+ const spanStorage = new AsyncLocalStorage();
6
+ /**
7
+ * SpanContext manages the current span in async execution contexts.
8
+ * This enables automatic parent-child span relationships without manual tracking.
9
+ *
10
+ * Uses Node.js AsyncLocalStorage which provides async-safe context propagation.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const span = tracer.startSpan({ name: 'parent', ... });
15
+ *
16
+ * await SpanContext.runAsync(span, async () => {
17
+ * // Inside this function, getCurrent() returns the parent span
18
+ * const parent = SpanContext.getCurrent();
19
+ *
20
+ * const child = tracer.startSpan({
21
+ * name: 'child',
22
+ * parentSpanId: parent?.spanId,
23
+ * traceId: parent?.traceId,
24
+ * });
25
+ * // ...
26
+ * });
27
+ * ```
28
+ */
29
+ // biome-ignore lint/complexity/noStaticOnlyClass: Intentional API design for namespacing context operations
30
+ export class SpanContext {
31
+ /**
32
+ * Get the current span from the async context
33
+ *
34
+ * @returns The current span, or undefined if no span is active
35
+ */
36
+ static getCurrent() {
37
+ return spanStorage.getStore();
38
+ }
39
+ /**
40
+ * Run a synchronous function with the given span as the current context
41
+ *
42
+ * @param span - The span to set as current
43
+ * @param fn - The function to execute
44
+ * @returns The return value of the function
45
+ */
46
+ static run(span, fn) {
47
+ return spanStorage.run(span, fn);
48
+ }
49
+ /**
50
+ * Run an asynchronous function with the given span as the current context
51
+ *
52
+ * @param span - The span to set as current
53
+ * @param fn - The async function to execute
54
+ * @returns A promise resolving to the return value of the function
55
+ */
56
+ static async runAsync(span, fn) {
57
+ return spanStorage.run(span, fn);
58
+ }
59
+ /**
60
+ * Clear the current context (primarily for testing)
61
+ */
62
+ static clear() {
63
+ spanStorage.disable();
64
+ }
65
+ }
66
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/tracing/context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD;;GAEG;AACH,MAAM,WAAW,GAAG,IAAI,iBAAiB,EAAQ,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,4GAA4G;AAC5G,MAAM,OAAO,WAAW;IACtB;;;;OAIG;IACH,MAAM,CAAC,UAAU;QACf,OAAO,WAAW,CAAC,QAAQ,EAAE,CAAC;IAChC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAI,IAAU,EAAE,EAAW;QACnC,OAAO,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACnC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAI,IAAU,EAAE,EAAoB;QACvD,OAAO,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACnC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,KAAK;QACV,WAAW,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACF"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Types of spans that can be traced
3
+ */
4
+ export declare enum SpanType {
5
+ AGENT = "agent",
6
+ LLM = "llm",
7
+ TOOL = "tool",
8
+ CHAIN = "chain",
9
+ RETRIEVER = "retriever"
10
+ }
11
+ /**
12
+ * Status of a span
13
+ */
14
+ export declare enum SpanStatus {
15
+ RUNNING = "running",
16
+ SUCCESS = "success",
17
+ ERROR = "error"
18
+ }
19
+ /**
20
+ * Token usage information for LLM calls
21
+ */
22
+ export interface TokenUsage {
23
+ promptTokens: number;
24
+ completionTokens: number;
25
+ totalTokens: number;
26
+ }
27
+ /**
28
+ * Error information captured when a span fails
29
+ */
30
+ export interface ErrorInfo {
31
+ errorType: string;
32
+ message: string;
33
+ stacktrace: string;
34
+ }
35
+ /**
36
+ * A span represents a single operation in a trace
37
+ */
38
+ export interface Span {
39
+ /** Unique identifier for this span */
40
+ spanId: string;
41
+ /** ID of the parent span, or null if this is a root span */
42
+ parentSpanId: string | null;
43
+ /** Trace ID shared by all spans in a single trace */
44
+ traceId: string;
45
+ /** Human-readable name for this span */
46
+ name: string;
47
+ /** Type of operation this span represents */
48
+ spanType: SpanType;
49
+ /** Start time in milliseconds since Unix epoch */
50
+ startTime: number;
51
+ /** End time in milliseconds since Unix epoch, or null if still running */
52
+ endTime: number | null;
53
+ /** Current status of the span */
54
+ status: SpanStatus;
55
+ /** Input data for this operation */
56
+ inputs: Record<string, unknown>;
57
+ /** Output data from this operation, or null if not completed */
58
+ outputs: Record<string, unknown> | null;
59
+ /** Token usage for LLM calls, or null if not applicable */
60
+ tokenUsage: TokenUsage | null;
61
+ /** Error information if the span failed, or null if successful */
62
+ error: ErrorInfo | null;
63
+ /** Additional metadata about this span */
64
+ metadata: Record<string, unknown>;
65
+ /** Tags for categorizing and filtering spans */
66
+ tags: string[];
67
+ }
68
+ //# sourceMappingURL=span.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"span.d.ts","sourceRoot":"","sources":["../../src/tracing/span.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,QAAQ;IAClB,KAAK,UAAU;IACf,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,KAAK,UAAU;IACf,SAAS,cAAc;CACxB;AAED;;GAEG;AACH,oBAAY,UAAU;IACpB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,IAAI;IACnB,sCAAsC;IACtC,MAAM,EAAE,MAAM,CAAC;IAEf,4DAA4D;IAC5D,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAE5B,qDAAqD;IACrD,OAAO,EAAE,MAAM,CAAC;IAEhB,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IAEb,6CAA6C;IAC7C,QAAQ,EAAE,QAAQ,CAAC;IAEnB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAElB,0EAA0E;IAC1E,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvB,iCAAiC;IACjC,MAAM,EAAE,UAAU,CAAC;IAEnB,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEhC,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAExC,2DAA2D;IAC3D,UAAU,EAAE,UAAU,GAAG,IAAI,CAAC;IAE9B,kEAAkE;IAClE,KAAK,EAAE,SAAS,GAAG,IAAI,CAAC;IAExB,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAElC,gDAAgD;IAChD,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Types of spans that can be traced
3
+ */
4
+ export var SpanType;
5
+ (function (SpanType) {
6
+ SpanType["AGENT"] = "agent";
7
+ SpanType["LLM"] = "llm";
8
+ SpanType["TOOL"] = "tool";
9
+ SpanType["CHAIN"] = "chain";
10
+ SpanType["RETRIEVER"] = "retriever";
11
+ })(SpanType || (SpanType = {}));
12
+ /**
13
+ * Status of a span
14
+ */
15
+ export var SpanStatus;
16
+ (function (SpanStatus) {
17
+ SpanStatus["RUNNING"] = "running";
18
+ SpanStatus["SUCCESS"] = "success";
19
+ SpanStatus["ERROR"] = "error";
20
+ })(SpanStatus || (SpanStatus = {}));
21
+ //# sourceMappingURL=span.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"span.js","sourceRoot":"","sources":["../../src/tracing/span.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAN,IAAY,QAMX;AAND,WAAY,QAAQ;IAClB,2BAAe,CAAA;IACf,uBAAW,CAAA;IACX,yBAAa,CAAA;IACb,2BAAe,CAAA;IACf,mCAAuB,CAAA;AACzB,CAAC,EANW,QAAQ,KAAR,QAAQ,QAMnB;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,UAIX;AAJD,WAAY,UAAU;IACpB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,6BAAe,CAAA;AACjB,CAAC,EAJW,UAAU,KAAV,UAAU,QAIrB"}
@@ -0,0 +1,100 @@
1
+ import { type Partition } from '@prefactor/pfid';
2
+ import type { Transport } from '../transport/base.js';
3
+ import type { Span, SpanType, TokenUsage } from './span.js';
4
+ /**
5
+ * Options for starting a new span
6
+ */
7
+ export interface StartSpanOptions {
8
+ /** Name of the span */
9
+ name: string;
10
+ /** Type of operation this span represents */
11
+ spanType: SpanType;
12
+ /** Input data for this operation */
13
+ inputs: Record<string, unknown>;
14
+ /** ID of the parent span (optional) */
15
+ parentSpanId?: string;
16
+ /** Trace ID to use (optional, will generate if not provided) */
17
+ traceId?: string;
18
+ /** Additional metadata (optional) */
19
+ metadata?: Record<string, unknown>;
20
+ /** Tags for categorizing the span (optional) */
21
+ tags?: string[];
22
+ }
23
+ /**
24
+ * Options for ending a span
25
+ */
26
+ export interface EndSpanOptions {
27
+ /** Output data from the operation */
28
+ outputs?: Record<string, unknown>;
29
+ /** Error that occurred (if any) */
30
+ error?: Error;
31
+ /** Token usage information (for LLM calls) */
32
+ tokenUsage?: TokenUsage;
33
+ }
34
+ /**
35
+ * Tracer manages the lifecycle of spans.
36
+ *
37
+ * The tracer is responsible for:
38
+ * - Creating spans with unique IDs
39
+ * - Managing span lifecycle (start/end)
40
+ * - Delegating to the transport layer for span emission
41
+ * - Handling agent instance lifecycle
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const tracer = new Tracer(transport);
46
+ *
47
+ * const span = tracer.startSpan({
48
+ * name: 'llm-call',
49
+ * spanType: SpanType.LLM,
50
+ * inputs: { prompt: 'Hello' }
51
+ * });
52
+ *
53
+ * try {
54
+ * // ... do work ...
55
+ * tracer.endSpan(span, { outputs: { response: 'Hi!' } });
56
+ * } catch (error) {
57
+ * tracer.endSpan(span, { error });
58
+ * }
59
+ * ```
60
+ */
61
+ export declare class Tracer {
62
+ private transport;
63
+ private partition;
64
+ /**
65
+ * Initialize the tracer.
66
+ *
67
+ * @param transport - The transport to use for emitting spans
68
+ * @param partition - The partition for ID generation. If not provided, a random partition will be generated.
69
+ */
70
+ constructor(transport: Transport, partition?: Partition);
71
+ /**
72
+ * Start a new span
73
+ *
74
+ * @param options - Span configuration options
75
+ * @returns The created span
76
+ */
77
+ startSpan(options: StartSpanOptions): Span;
78
+ /**
79
+ * End a span and emit it to the transport
80
+ *
81
+ * @param span - The span to end
82
+ * @param options - End span options (outputs, error, token usage)
83
+ */
84
+ endSpan(span: Span, options?: EndSpanOptions): void;
85
+ /**
86
+ * Signal the start of an agent instance execution
87
+ */
88
+ startAgentInstance(): void;
89
+ /**
90
+ * Signal the completion of an agent instance execution
91
+ */
92
+ finishAgentInstance(): void;
93
+ /**
94
+ * Close the tracer and flush any pending spans
95
+ *
96
+ * @returns Promise that resolves when the tracer is closed
97
+ */
98
+ close(): Promise<void>;
99
+ }
100
+ //# sourceMappingURL=tracer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../../src/tracing/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAG5D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,uBAAuB;IACvB,IAAI,EAAE,MAAM,CAAC;IAEb,6CAA6C;IAC7C,QAAQ,EAAE,QAAQ,CAAC;IAEnB,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEhC,uCAAuC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,qCAAqC;IACrC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEnC,gDAAgD;IAChD,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,qCAAqC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAElC,mCAAmC;IACnC,KAAK,CAAC,EAAE,KAAK,CAAC;IAEd,8CAA8C;IAC9C,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,MAAM;IAUf,OAAO,CAAC,SAAS;IATnB,OAAO,CAAC,SAAS,CAAY;IAE7B;;;;;OAKG;gBAEO,SAAS,EAAE,SAAS,EAC5B,SAAS,CAAC,EAAE,SAAS;IAKvB;;;;;OAKG;IACH,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI;IAkC1C;;;;;OAKG;IACH,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,IAAI;IA6BnD;;OAEG;IACH,kBAAkB,IAAI,IAAI;IAQ1B;;OAEG;IACH,mBAAmB,IAAI,IAAI;IAQ3B;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAO7B"}
@@ -0,0 +1,151 @@
1
+ import { generate, generatePartition } from '@prefactor/pfid';
2
+ import { SpanStatus } from './span.js';
3
+ /**
4
+ * Tracer manages the lifecycle of spans.
5
+ *
6
+ * The tracer is responsible for:
7
+ * - Creating spans with unique IDs
8
+ * - Managing span lifecycle (start/end)
9
+ * - Delegating to the transport layer for span emission
10
+ * - Handling agent instance lifecycle
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const tracer = new Tracer(transport);
15
+ *
16
+ * const span = tracer.startSpan({
17
+ * name: 'llm-call',
18
+ * spanType: SpanType.LLM,
19
+ * inputs: { prompt: 'Hello' }
20
+ * });
21
+ *
22
+ * try {
23
+ * // ... do work ...
24
+ * tracer.endSpan(span, { outputs: { response: 'Hi!' } });
25
+ * } catch (error) {
26
+ * tracer.endSpan(span, { error });
27
+ * }
28
+ * ```
29
+ */
30
+ export class Tracer {
31
+ transport;
32
+ partition;
33
+ /**
34
+ * Initialize the tracer.
35
+ *
36
+ * @param transport - The transport to use for emitting spans
37
+ * @param partition - The partition for ID generation. If not provided, a random partition will be generated.
38
+ */
39
+ constructor(transport, partition) {
40
+ this.transport = transport;
41
+ this.partition = partition ?? generatePartition();
42
+ }
43
+ /**
44
+ * Start a new span
45
+ *
46
+ * @param options - Span configuration options
47
+ * @returns The created span
48
+ */
49
+ startSpan(options) {
50
+ const spanId = generate(this.partition);
51
+ const traceId = options.traceId ?? generate(this.partition);
52
+ const span = {
53
+ spanId,
54
+ parentSpanId: options.parentSpanId ?? null,
55
+ traceId,
56
+ name: options.name,
57
+ spanType: options.spanType,
58
+ startTime: Date.now(),
59
+ endTime: null,
60
+ status: SpanStatus.RUNNING,
61
+ inputs: options.inputs,
62
+ outputs: null,
63
+ tokenUsage: null,
64
+ error: null,
65
+ metadata: options.metadata ?? {},
66
+ tags: options.tags ?? [],
67
+ };
68
+ // AGENT spans are emitted immediately for real-time tracking
69
+ // They will be finished later with finishSpan()
70
+ if (options.spanType === 'agent') {
71
+ try {
72
+ this.transport.emit(span);
73
+ }
74
+ catch (error) {
75
+ console.error('Failed to emit agent span:', error);
76
+ }
77
+ }
78
+ return span;
79
+ }
80
+ /**
81
+ * End a span and emit it to the transport
82
+ *
83
+ * @param span - The span to end
84
+ * @param options - End span options (outputs, error, token usage)
85
+ */
86
+ endSpan(span, options) {
87
+ span.endTime = Date.now();
88
+ span.outputs = options?.outputs ?? null;
89
+ span.tokenUsage = options?.tokenUsage ?? null;
90
+ if (options?.error) {
91
+ span.status = SpanStatus.ERROR;
92
+ span.error = {
93
+ errorType: options.error.constructor.name,
94
+ message: options.error.message,
95
+ stacktrace: options.error.stack ?? '',
96
+ };
97
+ }
98
+ else {
99
+ span.status = SpanStatus.SUCCESS;
100
+ }
101
+ try {
102
+ // AGENT spans use finishSpan API (they were already emitted on start)
103
+ // Other span types are emitted here
104
+ if (span.spanType === 'agent') {
105
+ this.transport.finishSpan(span.spanId, span.endTime);
106
+ }
107
+ else {
108
+ this.transport.emit(span);
109
+ }
110
+ }
111
+ catch (error) {
112
+ console.error('Failed to emit/finish span:', error);
113
+ }
114
+ }
115
+ /**
116
+ * Signal the start of an agent instance execution
117
+ */
118
+ startAgentInstance() {
119
+ try {
120
+ this.transport.startAgentInstance();
121
+ }
122
+ catch (error) {
123
+ console.error('Failed to start agent instance:', error);
124
+ }
125
+ }
126
+ /**
127
+ * Signal the completion of an agent instance execution
128
+ */
129
+ finishAgentInstance() {
130
+ try {
131
+ this.transport.finishAgentInstance();
132
+ }
133
+ catch (error) {
134
+ console.error('Failed to finish agent instance:', error);
135
+ }
136
+ }
137
+ /**
138
+ * Close the tracer and flush any pending spans
139
+ *
140
+ * @returns Promise that resolves when the tracer is closed
141
+ */
142
+ async close() {
143
+ try {
144
+ await this.transport.close();
145
+ }
146
+ catch (error) {
147
+ console.error('Failed to close transport:', error);
148
+ }
149
+ }
150
+ }
151
+ //# sourceMappingURL=tracer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../src/tracing/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAkB,MAAM,iBAAiB,CAAC;AAG9E,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AA0CvC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,OAAO,MAAM;IAUP;IATF,SAAS,CAAY;IAE7B;;;;;OAKG;IACH,YACU,SAAoB,EAC5B,SAAqB;QADb,cAAS,GAAT,SAAS,CAAW;QAG5B,IAAI,CAAC,SAAS,GAAG,SAAS,IAAI,iBAAiB,EAAE,CAAC;IACpD,C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AAK,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK;QACT,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,38 @@
1
+ import type { Span } from '../tracing/span.js';
2
+ /**
3
+ * Transport interface for emitting spans to different backends
4
+ *
5
+ * Transports are responsible for sending span data to a destination
6
+ * (e.g., stdout, HTTP API). They implement the strategy pattern to allow
7
+ * pluggable backends.
8
+ */
9
+ export interface Transport {
10
+ /**
11
+ * Emit a span to the transport destination
12
+ *
13
+ * @param span - The span to emit
14
+ */
15
+ emit(span: Span): void;
16
+ /**
17
+ * Finish a previously emitted span (for long-running spans like AGENT spans)
18
+ *
19
+ * @param spanId - ID of the span to finish
20
+ * @param endTime - End time in milliseconds since Unix epoch
21
+ */
22
+ finishSpan(spanId: string, endTime: number): void;
23
+ /**
24
+ * Signal the start of an agent instance execution
25
+ */
26
+ startAgentInstance(): void;
27
+ /**
28
+ * Signal the completion of an agent instance execution
29
+ */
30
+ finishAgentInstance(): void;
31
+ /**
32
+ * Close the transport and flush any pending data
33
+ *
34
+ * @returns Promise that resolves when the transport is fully closed
35
+ */
36
+ close(): void | Promise<void>;
37
+ }
38
+ //# sourceMappingURL=base.d.ts.map