@lelemondev/sdk 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anthropic.js +2 -2
- package/dist/anthropic.js.map +1 -1
- package/dist/anthropic.mjs +2 -2
- package/dist/anthropic.mjs.map +1 -1
- package/dist/bedrock.js +2 -2
- package/dist/bedrock.js.map +1 -1
- package/dist/bedrock.mjs +2 -2
- package/dist/bedrock.mjs.map +1 -1
- package/dist/gemini.js +2 -2
- package/dist/gemini.js.map +1 -1
- package/dist/gemini.mjs +2 -2
- package/dist/gemini.mjs.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/openai.js +2 -2
- package/dist/openai.js.map +1 -1
- package/dist/openai.mjs +2 -2
- package/dist/openai.mjs.map +1 -1
- package/dist/openrouter.js +2 -2
- package/dist/openrouter.js.map +1 -1
- package/dist/openrouter.mjs +2 -2
- package/dist/openrouter.mjs.map +1 -1
- package/package.json +1 -1
package/dist/gemini.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/logger.ts","../src/core/transport.ts","../src/core/config.ts","../src/core/capture.ts","../src/core/context.ts","../src/providers/gemini.ts","../src/gemini.ts"],"names":["debugEnabled","setDebug","enabled","isDebugEnabled","getEnvVar","PREFIX","debug","message","data","logWithPrefix","info","warn","traceCapture","provider","model","durationMs","status","traceCaptureError","err","clientWrapped","batchSend","count","endpoint","batchSuccess","batchError","requestDetails","method","url","bodySize","responseDetails","level","logFn","name","DEFAULT_BATCH_SIZE","DEFAULT_FLUSH_INTERVAL_MS","DEFAULT_REQUEST_TIMEOUT_MS","Transport","config","__publicField","trace","items","startTime","error","path","body","controller","bodyStr","timeoutId","response","errorText","text","globalConfig","globalTransport","DEFAULT_ENDPOINT","init","createTransport","getConfig","isEnabled","getTransport","flush","apiKey","globalContext","setGlobalContext","options","getGlobalContext","captureTrace","params","transport","traceContext","getTraceContext","spanId","generateId","request","sanitizeInput","sanitizeOutput","captureError","captureSpan","metadataTraceId","metadataParentSpanId","cleanMetadata","MAX_STRING_LENGTH","SENSITIVE_KEYS","input","sanitize","output","value","depth","item","sanitized","key","val","k","traceStorage","AsyncLocalStorage","registerToolCalls","toolCallIds","llmSpanId","ctx","id","getToolParentSpanId","toolCallId","clearToolCall","nameOrOptions","fn","parentContext","traceId","rootSpanId","context","result","e","sendRootSpan","rootSpan","span","parentSpanId","PROVIDER_NAME","canHandle","client","constructorName","c","wrap","geminiClient","target","prop","receiver","wrapGetGenerativeModel","originalFn","wrapGenerativeModel","modelName","wrapGenerateContent","wrapGenerateContentStream","wrapStartChat","extractInput","rawResponse","buildRawResponse","functionCallIds","extractFunctionCallIds","wrappedStream","wrapStream","stream","finalResponse","firstTokenMs","firstTokenReceived","chunk","parts","lastPart","part","extractFunctionCallIdsFromCandidates","chat","wrapChatSession","wrapSendMessage","wrapSendMessageStream","ids","index","candidates","observe"],"mappings":";AAWA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,EAAA,CAAA,CAAA,CAAA,OAAA,CAAA,EAAA,QAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAIA,EAAe,KAAA,CASZ,SAASC,CAAAA,CAASC,CAAAA,CAAwB,CAC/CF,CAAAA,CAAeE,EACj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EAK5BjG,CAAAA,CAAc,QAAQ,EACRoG,CAAAA,CAAKH,CAAM,IALvBzG,CAAAA,CAAK,8FAA8F,EAC5FyG,CAAAA,CAKX","file":"gemini.js","sourcesContent":["/**\n * Centralized Logger\n *\n * Provides consistent debug logging across the SDK.\n * Enable via: init({ debug: true }) or LELEMON_DEBUG=true\n */\n\n// ─────────────────────────────────────────────────────────────\n// State\n// ─────────────────────────────────────────────────────────────\n\nlet debugEnabled = false;\n\n// ─────────────────────────────────────────────────────────────\n// Configuration\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Enable or disable debug mode\n */\nexport function setDebug(enabled: boolean): void {\n debugEnabled = enabled;\n}\n\n/**\n * Check if debug mode is enabled\n */\nexport function isDebugEnabled(): boolean {\n // Config takes precedence, then check env var\n if (debugEnabled) return true;\n return getEnvVar('LELEMON_DEBUG') === 'true';\n}\n\n// ─────────────────────────────────────────────────────────────\n// Logging Functions\n// ─────────────────────────────────────────────────────────────\n\nconst PREFIX = '[Lelemon]';\n\n/**\n * Log debug message (only when debug enabled)\n */\nexport function debug(message: string, data?: unknown): void {\n if (!isDebugEnabled()) return;\n logWithPrefix('debug', message, data);\n}\n\n/**\n * Log info message (only when debug enabled)\n */\nexport function info(message: string, data?: unknown): void {\n if (!isDebugEnabled()) return;\n logWithPrefix('info', message, data);\n}\n\n/**\n * Log warning message (always shown)\n */\nexport function warn(message: string, data?: unknown): void {\n logWithPrefix('warn', message, data);\n}\n\n/**\n * Log error message (always shown)\n */\nexport function error(message: string, data?: unknown): void {\n logWithPrefix('error', message, data);\n}\n\n// ─────────────────────────────────────────────────────────────\n// Trace-specific logging\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Log when a trace is captured\n */\nexport function traceCapture(provider: string, model: string, durationMs: number, status: string): void {\n if (!isDebugEnabled()) return;\n console.log(\n `${PREFIX} Captured trace: provider=${provider} model=${model} duration=${durationMs}ms status=${status}`\n );\n}\n\n/**\n * Log when a trace capture fails (always visible)\n */\nexport function traceCaptureError(provider: string, err: Error): void {\n console.error(`${PREFIX} Failed to capture trace: provider=${provider} error=${err.message}`);\n}\n\n/**\n * Log when a client is wrapped\n */\nexport function clientWrapped(provider: string): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Wrapped client: provider=${provider}`);\n}\n\n/**\n * Log transport events\n */\nexport function transportEvent(event: string, details?: Record<string, unknown>): void {\n if (!isDebugEnabled()) return;\n if (details) {\n console.log(`${PREFIX} Transport: ${event}`, details);\n } else {\n console.log(`${PREFIX} Transport: ${event}`);\n }\n}\n\n/**\n * Log batch send details\n */\nexport function batchSend(count: number, endpoint: string): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Sending batch: count=${count} endpoint=${endpoint}`);\n}\n\n/**\n * Log batch send success\n */\nexport function batchSuccess(count: number, durationMs: number): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Batch sent successfully: count=${count} duration=${durationMs}ms`);\n}\n\n/**\n * Log batch send failure (always visible - errors should never be silent)\n */\nexport function batchError(count: number, err: unknown): void {\n const message = err instanceof Error ? err.message : String(err);\n console.error(`${PREFIX} Batch send failed: count=${count} error=${message}`);\n}\n\n/**\n * Log request details (for deep debugging)\n */\nexport function requestDetails(method: string, url: string, bodySize: number): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Request: ${method} ${url} (${bodySize} bytes)`);\n}\n\n/**\n * Log response details\n */\nexport function responseDetails(status: number, durationMs: number): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Response: status=${status} duration=${durationMs}ms`);\n}\n\n// ─────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────\n\nfunction logWithPrefix(level: 'debug' | 'info' | 'warn' | 'error', message: string, data?: unknown): void {\n const logFn = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log;\n\n if (data !== undefined) {\n logFn(`${PREFIX} ${message}`, data);\n } else {\n logFn(`${PREFIX} ${message}`);\n }\n}\n\nfunction getEnvVar(name: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[name];\n }\n return undefined;\n}\n","/**\n * Transport Layer\n *\n * Handles batched HTTP requests to the Lelemon API.\n * Features:\n * - Queue-based batching\n * - Auto-flush on batch size or interval\n * - Request timeout protection\n * - Graceful error handling\n */\n\nimport type { CreateTraceRequest } from './types';\nimport { batchSend, batchSuccess, batchError, requestDetails, responseDetails, transportEvent } from './logger';\n\n// ─────────────────────────────────────────────────────────────\n// Configuration\n// ─────────────────────────────────────────────────────────────\n\ninterface TransportConfig {\n apiKey: string;\n endpoint: string;\n debug: boolean;\n disabled: boolean;\n batchSize?: number;\n flushIntervalMs?: number;\n requestTimeoutMs?: number;\n}\n\nconst DEFAULT_BATCH_SIZE = 10;\nconst DEFAULT_FLUSH_INTERVAL_MS = 1000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10000;\n\n// ─────────────────────────────────────────────────────────────\n// Transport Class\n// ─────────────────────────────────────────────────────────────\n\nexport class Transport {\n private readonly config: Required<TransportConfig>;\n private queue: CreateTraceRequest[] = [];\n private flushPromise: Promise<void> | null = null;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(config: TransportConfig) {\n this.config = {\n apiKey: config.apiKey,\n endpoint: config.endpoint,\n debug: config.debug,\n disabled: config.disabled,\n batchSize: config.batchSize ?? DEFAULT_BATCH_SIZE,\n flushIntervalMs: config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n requestTimeoutMs: config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n };\n }\n\n /**\n * Check if transport is enabled\n */\n isEnabled(): boolean {\n return !this.config.disabled && !!this.config.apiKey;\n }\n\n /**\n * Enqueue a trace for sending\n * Fire-and-forget - never blocks\n */\n enqueue(trace: CreateTraceRequest): void {\n if (this.config.disabled) return;\n\n this.queue.push(trace);\n\n if (this.queue.length >= this.config.batchSize) {\n this.flush();\n } else {\n this.scheduleFlush();\n }\n }\n\n /**\n * Flush all pending traces\n * Safe to call multiple times\n */\n async flush(): Promise<void> {\n if (this.flushPromise) {\n return this.flushPromise;\n }\n\n if (this.queue.length === 0) {\n return;\n }\n\n this.cancelScheduledFlush();\n\n const items = this.queue;\n this.queue = [];\n\n this.flushPromise = this.sendBatch(items).finally(() => {\n this.flushPromise = null;\n });\n\n return this.flushPromise;\n }\n\n /**\n * Get pending count (for debugging)\n */\n getPendingCount(): number {\n return this.queue.length;\n }\n\n // ─────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────\n\n private scheduleFlush(): void {\n if (this.flushTimer !== null) return;\n\n this.flushTimer = setTimeout(() => {\n this.flushTimer = null;\n this.flush();\n }, this.config.flushIntervalMs);\n }\n\n private cancelScheduledFlush(): void {\n if (this.flushTimer !== null) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n }\n\n private async sendBatch(items: CreateTraceRequest[]): Promise<void> {\n if (items.length === 0) return;\n\n const startTime = Date.now();\n batchSend(items.length, `${this.config.endpoint}/api/v1/ingest`);\n\n try {\n await this.request('POST', '/api/v1/ingest', { events: items });\n batchSuccess(items.length, Date.now() - startTime);\n } catch (error) {\n batchError(items.length, error);\n // Don't rethrow - observability should never crash the app\n }\n }\n\n private async request(method: string, path: string, body?: unknown): Promise<unknown> {\n const url = `${this.config.endpoint}${path}`;\n const controller = new AbortController();\n const bodyStr = body ? JSON.stringify(body) : undefined;\n\n requestDetails(method, url, bodyStr?.length ?? 0);\n\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, this.config.requestTimeoutMs);\n\n const startTime = Date.now();\n\n try {\n const response = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n },\n body: bodyStr,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n responseDetails(response.status, Date.now() - startTime);\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'Unknown error');\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const text = await response.text();\n return text ? JSON.parse(text) : {};\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`);\n }\n\n throw error;\n }\n }\n}\n","/**\n * Global Configuration\n *\n * Manages SDK configuration and transport instance.\n */\n\nimport type { LelemonConfig } from './types';\nimport { Transport } from './transport';\nimport { setDebug, info, warn, debug } from './logger';\n\n// ─────────────────────────────────────────────────────────────\n// Global State\n// ─────────────────────────────────────────────────────────────\n\nlet globalConfig: LelemonConfig = {};\nlet globalTransport: Transport | null = null;\nlet initialized = false;\n\n// ─────────────────────────────────────────────────────────────\n// Configuration\n// ─────────────────────────────────────────────────────────────\n\nconst DEFAULT_ENDPOINT = 'https://www.lelemon.dev';\n\n/**\n * Initialize the SDK\n * Call once at app startup\n */\nexport function init(config: LelemonConfig = {}): void {\n globalConfig = config;\n\n // Configure debug mode\n if (config.debug) {\n setDebug(true);\n }\n\n info('Initializing SDK', {\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n debug: config.debug ?? false,\n disabled: config.disabled ?? false,\n });\n\n globalTransport = createTransport(config);\n initialized = true;\n\n // Log status after transport is created\n if (globalTransport.isEnabled()) {\n info('SDK initialized - tracing enabled');\n } else {\n debug('SDK initialized - tracing disabled (no API key or explicitly disabled)');\n }\n}\n\n/**\n * Get current config\n */\nexport function getConfig(): LelemonConfig {\n return globalConfig;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isInitialized(): boolean {\n return initialized;\n}\n\n/**\n * Check if SDK is enabled\n */\nexport function isEnabled(): boolean {\n return getTransport().isEnabled();\n}\n\n// ─────────────────────────────────────────────────────────────\n// Transport\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Get or create transport instance\n */\nexport function getTransport(): Transport {\n if (!globalTransport) {\n globalTransport = createTransport(globalConfig);\n }\n return globalTransport;\n}\n\n/**\n * Flush all pending traces\n */\nexport async function flush(): Promise<void> {\n if (globalTransport) {\n await globalTransport.flush();\n }\n}\n\n/**\n * Create transport instance\n */\nfunction createTransport(config: LelemonConfig): Transport {\n const apiKey = config.apiKey ?? getEnvVar('LELEMON_API_KEY');\n\n if (!apiKey && !config.disabled) {\n warn('No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled.');\n }\n\n return new Transport({\n apiKey: apiKey ?? '',\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n debug: config.debug ?? false,\n disabled: config.disabled ?? !apiKey,\n batchSize: config.batchSize,\n flushIntervalMs: config.flushIntervalMs,\n requestTimeoutMs: config.requestTimeoutMs,\n });\n}\n\n/**\n * Get environment variable (works in Node and edge)\n */\nfunction getEnvVar(name: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[name];\n }\n return undefined;\n}\n","/**\n * Capture Module\n *\n * Handles trace capture and batching.\n * Called by providers to record LLM calls.\n */\n\nimport type { ProviderName, CreateTraceRequest, ObserveOptions, CaptureSpanOptions, SpanType } from './types';\nimport { getTransport } from './config';\nimport { traceCapture, traceCaptureError, debug } from './logger';\nimport { getTraceContext, generateId } from './context';\n\n// ─────────────────────────────────────────────────────────────\n// Global context (set via observe options)\n// ─────────────────────────────────────────────────────────────\n\nlet globalContext: ObserveOptions = {};\n\nexport function setGlobalContext(options: ObserveOptions): void {\n globalContext = options;\n debug('Global context updated', options);\n}\n\nexport function getGlobalContext(): ObserveOptions {\n return globalContext;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Capture Functions\n// ─────────────────────────────────────────────────────────────\n\nexport interface CaptureTraceParams {\n provider: ProviderName;\n model: string;\n input: unknown;\n output: unknown;\n inputTokens: number;\n outputTokens: number;\n durationMs: number;\n status: 'success' | 'error';\n streaming: boolean;\n metadata?: Record<string, unknown>;\n // Extended fields (Phase 7.1)\n stopReason?: string;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n firstTokenMs?: number;\n thinking?: string;\n}\n\nexport interface CaptureErrorParams {\n provider: ProviderName;\n model: string;\n input: unknown;\n error: Error;\n durationMs: number;\n streaming: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Capture a successful trace (LLM call)\n * Fire-and-forget - never throws\n * @returns The span ID, for linking tool calls to this LLM span\n */\nexport function captureTrace(params: CaptureTraceParams): string | undefined {\n try {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping trace capture');\n return undefined;\n }\n\n const globalContext = getGlobalContext();\n const traceContext = getTraceContext();\n const spanId = generateId();\n\n const request: CreateTraceRequest = {\n provider: params.provider,\n model: params.model,\n input: sanitizeInput(params.input),\n output: sanitizeOutput(params.output),\n inputTokens: params.inputTokens,\n outputTokens: params.outputTokens,\n durationMs: params.durationMs,\n status: params.status,\n streaming: params.streaming,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n // Hierarchy fields (Phase 7.2) - use trace context if available\n traceId: traceContext?.traceId,\n spanId,\n parentSpanId: traceContext?.currentSpanId,\n metadata: {\n ...globalContext.metadata,\n ...params.metadata,\n // Include trace name for debugging\n ...(traceContext ? { _traceName: traceContext.name } : {}),\n },\n tags: globalContext.tags,\n // Extended fields (Phase 7.1)\n stopReason: params.stopReason,\n cacheReadTokens: params.cacheReadTokens,\n cacheWriteTokens: params.cacheWriteTokens,\n reasoningTokens: params.reasoningTokens,\n firstTokenMs: params.firstTokenMs,\n thinking: params.thinking,\n };\n\n traceCapture(params.provider, params.model, params.durationMs, params.status);\n transport.enqueue(request);\n\n return spanId;\n } catch (err) {\n traceCaptureError(params.provider, err instanceof Error ? err : new Error(String(err)));\n return undefined;\n }\n}\n\n/**\n * Capture an error trace\n * Fire-and-forget - never throws\n */\nexport function captureError(params: CaptureErrorParams): void {\n try {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping error capture');\n return;\n }\n\n const globalContext = getGlobalContext();\n const traceContext = getTraceContext();\n\n const request: CreateTraceRequest = {\n provider: params.provider,\n model: params.model,\n input: sanitizeInput(params.input),\n output: null,\n inputTokens: 0,\n outputTokens: 0,\n durationMs: params.durationMs,\n status: 'error',\n errorMessage: params.error.message,\n errorStack: params.error.stack,\n streaming: params.streaming,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n // Hierarchy fields (Phase 7.2)\n traceId: traceContext?.traceId,\n spanId: generateId(),\n parentSpanId: traceContext?.currentSpanId,\n metadata: {\n ...globalContext.metadata,\n ...params.metadata,\n ...(traceContext ? { _traceName: traceContext.name } : {}),\n },\n tags: globalContext.tags,\n };\n\n traceCapture(params.provider, params.model, params.durationMs, 'error');\n debug('Error details', { message: params.error.message, stack: params.error.stack });\n transport.enqueue(request);\n } catch (err) {\n traceCaptureError(params.provider, err instanceof Error ? err : new Error(String(err)));\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Manual Span Capture\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Manually capture a span (tool call, retrieval, custom)\n * Use this when auto-detection doesn't cover your use case\n *\n * @example\n * // Capture a tool call\n * captureSpan({\n * type: 'tool',\n * name: 'get_weather',\n * input: { location: 'San Francisco' },\n * output: { temperature: 72, conditions: 'sunny' },\n * durationMs: 150,\n * });\n *\n * @example\n * // Capture a retrieval/RAG operation\n * captureSpan({\n * type: 'retrieval',\n * name: 'vector_search',\n * input: { query: 'user question', k: 5 },\n * output: { documents: [...] },\n * durationMs: 50,\n * });\n */\nexport function captureSpan(options: CaptureSpanOptions): void {\n try {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping span capture');\n return;\n }\n\n const globalContext = getGlobalContext();\n const traceContext = getTraceContext();\n\n // Extract trace context from metadata if passed from span() in context.ts\n const metadataTraceId = (options.metadata as Record<string, unknown>)?._traceId as string | undefined;\n const metadataParentSpanId = (options.metadata as Record<string, unknown>)?._parentSpanId as string | undefined;\n\n // Clean up internal metadata keys\n const cleanMetadata = { ...globalContext.metadata, ...options.metadata };\n delete (cleanMetadata as Record<string, unknown>)._traceId;\n delete (cleanMetadata as Record<string, unknown>)._parentSpanId;\n\n const request: CreateTraceRequest = {\n spanType: options.type,\n name: options.name,\n provider: 'unknown', // Manual spans don't have a provider\n model: options.name, // Use name as model for compatibility\n input: sanitizeInput(options.input),\n output: sanitizeOutput(options.output),\n inputTokens: 0,\n outputTokens: 0,\n durationMs: options.durationMs,\n status: options.status || 'success',\n errorMessage: options.errorMessage,\n streaming: false,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n // Hierarchy fields (Phase 7.2)\n traceId: metadataTraceId ?? traceContext?.traceId,\n spanId: generateId(),\n parentSpanId: metadataParentSpanId ?? traceContext?.currentSpanId,\n toolCallId: options.toolCallId,\n metadata: cleanMetadata,\n tags: globalContext.tags,\n };\n\n debug(`Span captured: ${options.type}/${options.name}`, { durationMs: options.durationMs });\n transport.enqueue(request);\n } catch (err) {\n traceCaptureError('unknown', err instanceof Error ? err : new Error(String(err)));\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Sanitization (security)\n// ─────────────────────────────────────────────────────────────\n\nconst MAX_STRING_LENGTH = 100_000; // 100KB per field\nconst SENSITIVE_KEYS = ['api_key', 'apikey', 'password', 'secret', 'token', 'authorization'];\n\n/**\n * Sanitize input before sending\n * - Truncates large strings\n * - Removes sensitive data\n */\nfunction sanitizeInput(input: unknown): unknown {\n return sanitize(input, 0);\n}\n\n/**\n * Sanitize output before sending\n */\nfunction sanitizeOutput(output: unknown): unknown {\n return sanitize(output, 0);\n}\n\nfunction sanitize(value: unknown, depth: number): unknown {\n // Prevent infinite recursion\n if (depth > 10) return '[max depth exceeded]';\n\n if (value === null || value === undefined) return value;\n\n if (typeof value === 'string') {\n return value.length > MAX_STRING_LENGTH\n ? value.slice(0, MAX_STRING_LENGTH) + '...[truncated]'\n : value;\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => sanitize(item, depth + 1));\n }\n\n if (typeof value === 'object') {\n const sanitized: Record<string, unknown> = {};\n\n for (const [key, val] of Object.entries(value)) {\n // Redact sensitive keys\n if (SENSITIVE_KEYS.some((k) => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]';\n } else {\n sanitized[key] = sanitize(val, depth + 1);\n }\n }\n\n return sanitized;\n }\n\n // Functions, symbols, etc.\n return String(value);\n}\n","/**\n * Trace Context Module\n *\n * Provides AsyncLocalStorage-based context for grouping spans under a parent trace.\n * Supports hierarchical tracing where:\n * - trace() creates a root \"agent\" span\n * - LLM calls become children of the root\n * - Tool calls become children of the LLM that triggered them (via toolCallId linking)\n *\n * @example\n * ```typescript\n * import { trace, span } from '@lelemondev/sdk';\n *\n * await trace({ name: 'sales-agent', input: userMessage }, async () => {\n * const response = await client.send(new ConverseCommand({...}));\n * // Tools automatically linked to their parent LLM via toolCallId\n * return response;\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { getTransport } from './config';\nimport { getGlobalContext } from './capture';\nimport { debug } from './logger';\nimport type { CreateTraceRequest, SpanType } from './types';\n\n// ─────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────\n\nexport interface TraceContext {\n /** Unique trace ID (shared by all spans in this trace) */\n traceId: string;\n /** Root span ID (the agent/workflow span) */\n rootSpanId: string;\n /** Current span ID (for nesting - LLM calls become children of this) */\n currentSpanId: string;\n /** Parent span ID (for nested trace() calls) */\n parentSpanId?: string;\n /** Trace name */\n name: string;\n /** Start time in ms */\n startTime: number;\n /** Input data */\n input?: unknown;\n /** Trace metadata */\n metadata?: Record<string, unknown>;\n /** Trace tags */\n tags?: string[];\n /** Map of toolCallId → llmSpanId for linking tool spans to their parent LLM */\n pendingToolCalls: Map<string, string>;\n}\n\nexport interface TraceOptions {\n /** Name for the trace (e.g., 'sales-agent', 'rag-query') */\n name: string;\n /** Input data for the trace */\n input?: unknown;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n /** Tags for filtering */\n tags?: string[];\n}\n\nexport interface SpanOptions {\n /** Span type */\n type: 'retrieval' | 'embedding' | 'tool' | 'guardrail' | 'rerank' | 'custom';\n /** Span name (e.g., 'pinecone-search', 'cohere-rerank') */\n name: string;\n /** Input data */\n input?: unknown;\n /** Output data */\n output?: unknown;\n /** Duration in milliseconds (optional, will be set automatically if not provided) */\n durationMs?: number;\n /** Status */\n status?: 'success' | 'error';\n /** Error message if status is 'error' */\n errorMessage?: string;\n /** Tool call ID (links this tool span to the LLM that requested it) */\n toolCallId?: string;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n}\n\n// ─────────────────────────────────────────────────────────────\n// AsyncLocalStorage for trace context\n// ─────────────────────────────────────────────────────────────\n\nconst traceStorage = new AsyncLocalStorage<TraceContext>();\n\n// ─────────────────────────────────────────────────────────────\n// ID Generation\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Generate a unique trace/span ID\n * Uses crypto.randomUUID if available, falls back to timestamp-based ID\n */\nexport function generateId(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n // Fallback for older Node.js versions\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Context API\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Get the current trace context, if any\n */\nexport function getTraceContext(): TraceContext | undefined {\n return traceStorage.getStore();\n}\n\n/**\n * Check if we're inside a trace() block\n */\nexport function hasTraceContext(): boolean {\n return traceStorage.getStore() !== undefined;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Tool Call Linking\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Register tool calls from an LLM response.\n * When the LLM returns with tool_use, call this to link subsequent tool spans.\n * @param toolCallIds - Array of tool call IDs from the LLM response\n * @param llmSpanId - The span ID of the LLM call that requested these tools\n */\nexport function registerToolCalls(toolCallIds: string[], llmSpanId: string): void {\n const ctx = getTraceContext();\n if (!ctx) return;\n\n for (const id of toolCallIds) {\n ctx.pendingToolCalls.set(id, llmSpanId);\n debug(`Registered tool call ${id} → LLM span ${llmSpanId}`);\n }\n}\n\n/**\n * Get the correct parent span ID for a tool span.\n * If toolCallId matches a pending tool call, returns the LLM span that requested it.\n * Otherwise falls back to the current span ID.\n */\nexport function getToolParentSpanId(toolCallId?: string): string | undefined {\n const ctx = getTraceContext();\n if (!ctx) return undefined;\n\n if (toolCallId && ctx.pendingToolCalls.has(toolCallId)) {\n return ctx.pendingToolCalls.get(toolCallId);\n }\n\n return ctx.currentSpanId;\n}\n\n/**\n * Clear a tool call from the pending map after it's been processed.\n */\nexport function clearToolCall(toolCallId: string): void {\n const ctx = getTraceContext();\n if (ctx) {\n ctx.pendingToolCalls.delete(toolCallId);\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// trace() - Main API for grouping spans\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Execute a function within a trace context.\n * Creates a root \"agent\" span that contains all LLM calls and tool executions.\n * The result of the function becomes the output of the root span.\n *\n * @example Simple usage (just name)\n * ```typescript\n * await trace('sales-agent', async () => {\n * await client.send(new ConverseCommand({...}));\n * return finalResponse;\n * });\n * ```\n *\n * @example With options\n * ```typescript\n * await trace({ name: 'rag-query', input: question, tags: ['production'] }, async () => {\n * const docs = await search(question);\n * span({ type: 'retrieval', name: 'pinecone', output: { count: docs.length } });\n * return client.send(new ConverseCommand({...}));\n * });\n * ```\n */\nexport async function trace<T>(\n nameOrOptions: string | TraceOptions,\n fn: () => Promise<T>\n): Promise<T> {\n // Normalize options\n const options: TraceOptions =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n\n const parentContext = getTraceContext();\n const traceId = parentContext?.traceId ?? generateId();\n const rootSpanId = generateId();\n\n const context: TraceContext = {\n traceId,\n rootSpanId,\n currentSpanId: rootSpanId,\n parentSpanId: parentContext?.currentSpanId,\n name: options.name,\n startTime: Date.now(),\n input: options.input,\n metadata: options.metadata,\n tags: options.tags,\n pendingToolCalls: new Map(),\n };\n\n // Run the function within the trace context\n return traceStorage.run(context, async () => {\n let result: T | undefined;\n let error: Error | undefined;\n\n try {\n result = await fn();\n return result;\n } catch (e) {\n error = e instanceof Error ? e : new Error(String(e));\n throw e;\n } finally {\n // Send the root span with the final result\n sendRootSpan(context, error ? undefined : result, error);\n }\n });\n}\n\n/**\n * Send the root \"agent\" span when the trace completes.\n * This span represents the entire agent execution with input/output.\n */\nfunction sendRootSpan(context: TraceContext, result?: unknown, error?: Error): void {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping root span');\n return;\n }\n\n const globalContext = getGlobalContext();\n const durationMs = Date.now() - context.startTime;\n\n // Sanitize result if it's a string (common case for agent responses)\n const output = error ? null : result;\n\n const rootSpan: CreateTraceRequest = {\n spanType: 'agent' as SpanType,\n name: context.name,\n provider: 'agent',\n model: context.name,\n traceId: context.traceId,\n spanId: context.rootSpanId,\n parentSpanId: context.parentSpanId,\n input: context.input,\n output,\n inputTokens: 0, // Will be aggregated from children\n outputTokens: 0,\n durationMs,\n status: error ? 'error' : 'success',\n errorMessage: error?.message,\n streaming: false,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n metadata: {\n ...globalContext.metadata,\n ...context.metadata,\n },\n tags: context.tags ?? globalContext.tags,\n };\n\n debug(`Sending root span: ${context.name}`, { durationMs, hasError: !!error });\n transport.enqueue(rootSpan);\n}\n\n// ─────────────────────────────────────────────────────────────\n// span() - Manual span capture for non-LLM operations\n// ─────────────────────────────────────────────────────────────\n\n// Import directly - circular dependency is handled by module system\nimport { captureSpan as captureSpanImport } from './capture';\n\n/**\n * Manually capture a span for non-LLM operations (retrieval, embedding, tool, etc.)\n * Must be called within a trace() block.\n *\n * @example Tool with toolCallId (links to parent LLM)\n * ```typescript\n * span({\n * type: 'tool',\n * name: 'query_database',\n * toolCallId: 'tooluse_abc123', // Links to LLM that requested this\n * input: { sql: 'SELECT ...' },\n * output: { rows: [...] },\n * durationMs: 15,\n * });\n * ```\n *\n * @example Retrieval without toolCallId\n * ```typescript\n * span({\n * type: 'retrieval',\n * name: 'pinecone-search',\n * input: { topK: 5 },\n * output: { count: 10 },\n * durationMs: 50,\n * });\n * ```\n */\nexport function span(options: SpanOptions): void {\n const context = getTraceContext();\n\n if (!context) {\n // Warn but don't throw - fire-and-forget principle\n if (process.env.NODE_ENV !== 'production') {\n console.warn('[Lelemon] span() called outside of trace() - span will not be captured');\n }\n return;\n }\n\n // Determine parent: if toolCallId provided and registered, use the LLM span\n const parentSpanId = getToolParentSpanId(options.toolCallId);\n\n captureSpanImport({\n type: options.type,\n name: options.name,\n input: options.input,\n output: options.output,\n durationMs: options.durationMs ?? 0,\n status: options.status ?? 'success',\n errorMessage: options.errorMessage,\n toolCallId: options.toolCallId,\n metadata: {\n ...options.metadata,\n _traceId: context.traceId,\n _parentSpanId: parentSpanId,\n },\n });\n\n // Clear the tool call after processing\n if (options.toolCallId) {\n clearToolCall(options.toolCallId);\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Internal helpers (exported for capture.ts)\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Run a function with a specific trace context (for internal use)\n */\nexport function runWithContext<T>(context: TraceContext, fn: () => T): T {\n return traceStorage.run(context, fn);\n}\n","/**\n * Google Gemini Provider Wrapper\n *\n * Wraps @google/generative-ai to automatically capture LLM calls.\n * SDK thin: only captures timing and raw response.\n * Server smart: extracts tokens, output, tools, etc.\n */\n\nimport type { ProviderName } from '../core/types';\nimport { captureTrace, captureError } from '../core/capture';\nimport { registerToolCalls } from '../core/context';\n\n// ─────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────\n\ninterface GeminiClient {\n getGenerativeModel: (config: ModelConfig) => GenerativeModel;\n}\n\ninterface ModelConfig {\n model: string;\n [key: string]: unknown;\n}\n\ninterface GenerativeModel {\n generateContent: (request: GenerateContentRequest | string) => Promise<GenerateContentResult>;\n generateContentStream: (request: GenerateContentRequest | string) => Promise<StreamGenerateContentResult>;\n startChat: (config?: ChatConfig) => ChatSession;\n model: string;\n}\n\ninterface GenerateContentRequest {\n contents?: Content[];\n [key: string]: unknown;\n}\n\ninterface Content {\n role?: string;\n parts: Part[];\n}\n\ninterface Part {\n text?: string;\n functionCall?: { name: string; args: unknown };\n [key: string]: unknown;\n}\n\ninterface GenerateContentResult {\n response: GenerateContentResponse;\n}\n\ninterface StreamGenerateContentResult {\n stream: AsyncIterable<GenerateContentStreamChunk>;\n response: Promise<GenerateContentResponse>;\n}\n\ninterface GenerateContentResponse {\n text: () => string;\n candidates?: Candidate[];\n usageMetadata?: UsageMetadata;\n}\n\ninterface GenerateContentStreamChunk {\n text: () => string;\n candidates?: Candidate[];\n usageMetadata?: UsageMetadata;\n}\n\ninterface Candidate {\n content?: Content;\n finishReason?: string;\n}\n\ninterface UsageMetadata {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n cachedContentTokenCount?: number;\n thoughtsTokenCount?: number;\n}\n\ninterface ChatConfig {\n [key: string]: unknown;\n}\n\ninterface ChatSession {\n sendMessage: (request: string | Part[]) => Promise<GenerateContentResult>;\n sendMessageStream: (request: string | Part[]) => Promise<StreamGenerateContentResult>;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Provider Implementation\n// ─────────────────────────────────────────────────────────────\n\nexport const PROVIDER_NAME: ProviderName = 'gemini';\n\nexport function canHandle(client: unknown): boolean {\n if (!client || typeof client !== 'object') return false;\n const constructorName = client.constructor?.name;\n if (constructorName === 'GoogleGenerativeAI') return true;\n if (constructorName === 'GoogleGenAI') return true;\n const c = client as Record<string, unknown>;\n if (typeof c.getGenerativeModel === 'function') return true;\n if (c.models && typeof (c.models as Record<string, unknown>).generate === 'function') {\n return true;\n }\n return false;\n}\n\nexport function wrap(client: unknown): unknown {\n const geminiClient = client as GeminiClient;\n return new Proxy(geminiClient, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === 'getGenerativeModel' && typeof value === 'function') {\n return wrapGetGenerativeModel(value.bind(target));\n }\n return value;\n },\n });\n}\n\nfunction wrapGetGenerativeModel(\n originalFn: (config: ModelConfig) => GenerativeModel\n): (config: ModelConfig) => GenerativeModel {\n return function wrappedGetGenerativeModel(config: ModelConfig): GenerativeModel {\n const model = originalFn(config);\n return wrapGenerativeModel(model, config.model);\n };\n}\n\nfunction wrapGenerativeModel(model: GenerativeModel, modelName: string): GenerativeModel {\n return new Proxy(model, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === 'generateContent' && typeof value === 'function') {\n return wrapGenerateContent(value.bind(target), modelName);\n }\n if (prop === 'generateContentStream' && typeof value === 'function') {\n return wrapGenerateContentStream(value.bind(target), modelName);\n }\n if (prop === 'startChat' && typeof value === 'function') {\n return wrapStartChat(value.bind(target), modelName);\n }\n return value;\n },\n });\n}\n\n// ─────────────────────────────────────────────────────────────\n// generateContent\n// ─────────────────────────────────────────────────────────────\n\nfunction wrapGenerateContent(\n originalFn: (request: GenerateContentRequest | string) => Promise<GenerateContentResult>,\n modelName: string\n) {\n return async function wrappedGenerateContent(\n request: GenerateContentRequest | string\n ): Promise<GenerateContentResult> {\n const startTime = Date.now();\n const input = extractInput(request);\n\n try {\n const result = await originalFn(request);\n const durationMs = Date.now() - startTime;\n\n // Build raw response from Gemini's response object\n const rawResponse = buildRawResponse(result.response);\n\n const spanId = captureTrace({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n rawResponse, // Server extracts everything\n durationMs,\n status: 'success',\n streaming: false,\n });\n\n // Register function calls for hierarchy\n if (spanId) {\n const functionCallIds = extractFunctionCallIds(result.response);\n if (functionCallIds.length > 0) {\n registerToolCalls(functionCallIds, spanId);\n }\n }\n\n return result;\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: false,\n });\n throw error;\n }\n };\n}\n\n// ─────────────────────────────────────────────────────────────\n// generateContentStream\n// ─────────────────────────────────────────────────────────────\n\nfunction wrapGenerateContentStream(\n originalFn: (request: GenerateContentRequest | string) => Promise<StreamGenerateContentResult>,\n modelName: string\n) {\n return async function wrappedGenerateContentStream(\n request: GenerateContentRequest | string\n ): Promise<StreamGenerateContentResult> {\n const startTime = Date.now();\n const input = extractInput(request);\n\n try {\n const result = await originalFn(request);\n const wrappedStream = wrapStream(result.stream, modelName, input, startTime);\n return {\n ...result,\n stream: wrappedStream,\n };\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: true,\n });\n throw error;\n }\n };\n}\n\nasync function* wrapStream(\n stream: AsyncIterable<GenerateContentStreamChunk>,\n modelName: string,\n input: unknown,\n startTime: number\n): AsyncIterable<GenerateContentStreamChunk> {\n // Accumulate to build final response\n const finalResponse: {\n candidates: Candidate[];\n usageMetadata?: UsageMetadata;\n } = { candidates: [{ content: { parts: [] } }] };\n let error: Error | null = null;\n let firstTokenMs: number | undefined;\n let firstTokenReceived = false;\n\n try {\n for await (const chunk of stream) {\n // Accumulate text\n try {\n const text = chunk.text();\n if (text) {\n if (!firstTokenReceived) {\n firstTokenReceived = true;\n firstTokenMs = Date.now() - startTime;\n }\n // Add text part to accumulated response\n const parts = finalResponse.candidates[0].content?.parts || [];\n const lastPart = parts[parts.length - 1];\n if (lastPart?.text !== undefined) {\n lastPart.text += text;\n } else {\n parts.push({ text });\n }\n }\n } catch {\n // text() may throw if no text content\n }\n\n // Extract candidates for function calls\n if (chunk.candidates?.[0]?.content?.parts) {\n for (const part of chunk.candidates[0].content.parts) {\n if (part.functionCall) {\n finalResponse.candidates[0].content?.parts?.push(part);\n }\n }\n }\n\n // Capture usage and finish reason from last chunk\n if (chunk.usageMetadata) {\n finalResponse.usageMetadata = chunk.usageMetadata;\n }\n if (chunk.candidates?.[0]?.finishReason) {\n finalResponse.candidates[0].finishReason = chunk.candidates[0].finishReason;\n }\n\n yield chunk;\n }\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err));\n throw err;\n } finally {\n const durationMs = Date.now() - startTime;\n\n if (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error,\n durationMs,\n streaming: true,\n });\n } else {\n const spanId = captureTrace({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n rawResponse: finalResponse,\n durationMs,\n status: 'success',\n streaming: true,\n firstTokenMs,\n });\n\n if (spanId) {\n const functionCallIds = extractFunctionCallIdsFromCandidates(finalResponse.candidates);\n if (functionCallIds.length > 0) {\n registerToolCalls(functionCallIds, spanId);\n }\n }\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Chat\n// ─────────────────────────────────────────────────────────────\n\nfunction wrapStartChat(\n originalFn: (config?: ChatConfig) => ChatSession,\n modelName: string\n): (config?: ChatConfig) => ChatSession {\n return function wrappedStartChat(config?: ChatConfig): ChatSession {\n const chat = originalFn(config);\n return wrapChatSession(chat, modelName);\n };\n}\n\nfunction wrapChatSession(chat: ChatSession, modelName: string): ChatSession {\n return new Proxy(chat, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === 'sendMessage' && typeof value === 'function') {\n return wrapSendMessage(value.bind(target), modelName);\n }\n if (prop === 'sendMessageStream' && typeof value === 'function') {\n return wrapSendMessageStream(value.bind(target), modelName);\n }\n return value;\n },\n });\n}\n\nfunction wrapSendMessage(\n originalFn: (request: string | Part[]) => Promise<GenerateContentResult>,\n modelName: string\n) {\n return async function wrappedSendMessage(\n request: string | Part[]\n ): Promise<GenerateContentResult> {\n const startTime = Date.now();\n const input = request;\n\n try {\n const result = await originalFn(request);\n const durationMs = Date.now() - startTime;\n const rawResponse = buildRawResponse(result.response);\n\n const spanId = captureTrace({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n rawResponse,\n durationMs,\n status: 'success',\n streaming: false,\n });\n\n if (spanId) {\n const functionCallIds = extractFunctionCallIds(result.response);\n if (functionCallIds.length > 0) {\n registerToolCalls(functionCallIds, spanId);\n }\n }\n\n return result;\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: false,\n });\n throw error;\n }\n };\n}\n\nfunction wrapSendMessageStream(\n originalFn: (request: string | Part[]) => Promise<StreamGenerateContentResult>,\n modelName: string\n) {\n return async function wrappedSendMessageStream(\n request: string | Part[]\n ): Promise<StreamGenerateContentResult> {\n const startTime = Date.now();\n const input = request;\n\n try {\n const result = await originalFn(request);\n const wrappedStream = wrapStream(result.stream, modelName, input, startTime);\n return {\n ...result,\n stream: wrappedStream,\n };\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: true,\n });\n throw error;\n }\n };\n}\n\n// ─────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────\n\nfunction extractInput(request: GenerateContentRequest | string): unknown {\n if (typeof request === 'string') return request;\n if (request.contents) return request.contents;\n return request;\n}\n\nfunction buildRawResponse(response: GenerateContentResponse): unknown {\n // Build a serializable response object\n return {\n candidates: response.candidates,\n usageMetadata: response.usageMetadata,\n };\n}\n\nfunction extractFunctionCallIds(response: GenerateContentResponse): string[] {\n const ids: string[] = [];\n const parts = response.candidates?.[0]?.content?.parts;\n if (parts) {\n parts.forEach((part, index) => {\n if (part.functionCall?.name) {\n ids.push(`gemini-fc-${part.functionCall.name}-${index}`);\n }\n });\n }\n return ids;\n}\n\nfunction extractFunctionCallIdsFromCandidates(candidates: Candidate[]): string[] {\n const ids: string[] = [];\n const parts = candidates?.[0]?.content?.parts;\n if (parts) {\n parts.forEach((part, index) => {\n if (part.functionCall?.name) {\n ids.push(`gemini-fc-${part.functionCall.name}-${index}`);\n }\n });\n }\n return ids;\n}\n","/**\n * Google Gemini Provider Entry Point\n *\n * @example\n * ```typescript\n * import { init, observe, flush } from '@lelemondev/sdk/gemini';\n * import { GoogleGenerativeAI } from '@google/generative-ai';\n *\n * init({ apiKey: process.env.LELEMON_API_KEY });\n * const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);\n * const model = observe(genAI.getGenerativeModel({ model: 'gemini-pro' }));\n *\n * await model.generateContent('Hello!');\n * await flush();\n * ```\n */\n\n// Re-export core\nexport { init, flush, isEnabled } from './core/config';\nexport { trace, span, getTraceContext } from './core/context';\nexport { captureSpan } from './core/capture';\n\n// Re-export types\nexport type {\n LelemonConfig,\n ObserveOptions,\n SpanType,\n CaptureSpanOptions,\n} from './core/types';\nexport type { TraceContext, TraceOptions, SpanOptions } from './core/context';\n\n// Provider-specific observe\nimport * as gemini from './providers/gemini';\nimport { setGlobalContext } from './core/capture';\nimport { getConfig } from './core/config';\nimport type { ObserveOptions } from './core/types';\nimport { clientWrapped, warn, debug } from './core/logger';\n\n/**\n * Wrap a Gemini model with automatic tracing\n */\nexport function observe<T>(client: T, options?: ObserveOptions): T {\n if (options) {\n setGlobalContext(options);\n }\n\n const config = getConfig();\n if (config.disabled) {\n debug('Tracing disabled, returning unwrapped client');\n return client;\n }\n\n if (!gemini.canHandle(client)) {\n warn('Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK.');\n return client;\n }\n\n clientWrapped('gemini');\n return gemini.wrap(client) as T;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/logger.ts","../src/core/transport.ts","../src/core/config.ts","../src/core/capture.ts","../src/core/context.ts","../src/providers/gemini.ts","../src/gemini.ts"],"names":["debugEnabled","setDebug","enabled","isDebugEnabled","getEnvVar","PREFIX","debug","message","data","logWithPrefix","info","warn","traceCapture","provider","model","durationMs","status","traceCaptureError","err","clientWrapped","batchSend","count","endpoint","batchSuccess","batchError","requestDetails","method","url","bodySize","responseDetails","level","logFn","name","DEFAULT_BATCH_SIZE","DEFAULT_FLUSH_INTERVAL_MS","DEFAULT_REQUEST_TIMEOUT_MS","Transport","config","__publicField","trace","items","startTime","error","path","body","controller","bodyStr","timeoutId","response","errorText","text","globalConfig","globalTransport","DEFAULT_ENDPOINT","init","createTransport","getConfig","isEnabled","getTransport","flush","apiKey","globalContext","setGlobalContext","options","getGlobalContext","captureTrace","params","transport","traceContext","getTraceContext","spanId","generateId","request","sanitizeInput","sanitize","captureError","captureSpan","metadataTraceId","metadataParentSpanId","cleanMetadata","MAX_STRING_LENGTH","SENSITIVE_KEYS","input","value","depth","item","sanitized","key","val","k","traceStorage","AsyncLocalStorage","registerToolCalls","toolCallIds","llmSpanId","ctx","id","getToolParentSpanId","toolCallId","clearToolCall","nameOrOptions","fn","parentContext","traceId","rootSpanId","context","result","e","sendRootSpan","output","rootSpan","span","parentSpanId","PROVIDER_NAME","canHandle","client","constructorName","c","wrap","geminiClient","target","prop","receiver","wrapGetGenerativeModel","originalFn","wrapGenerativeModel","modelName","wrapGenerateContent","wrapGenerateContentStream","wrapStartChat","extractInput","rawResponse","buildRawResponse","functionCallIds","extractFunctionCallIds","wrappedStream","wrapStream","stream","finalResponse","firstTokenMs","firstTokenReceived","chunk","parts","lastPart","part","extractFunctionCallIdsFromCandidates","chat","wrapChatSession","wrapSendMessage","wrapSendMessageStream","ids","index","candidates","observe"],"mappings":";AAWA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,EAAA,CAAA,CAAA,CAAA,OAAA,CAAA,EAAA,QAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA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ging across the SDK.\n * Enable via: init({ debug: true }) or LELEMON_DEBUG=true\n */\n\n// ─────────────────────────────────────────────────────────────\n// State\n// ─────────────────────────────────────────────────────────────\n\nlet debugEnabled = false;\n\n// ─────────────────────────────────────────────────────────────\n// Configuration\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Enable or disable debug mode\n */\nexport function setDebug(enabled: boolean): void {\n debugEnabled = enabled;\n}\n\n/**\n * Check if debug mode is enabled\n */\nexport function isDebugEnabled(): boolean {\n // Config takes precedence, then check env var\n if (debugEnabled) return true;\n return getEnvVar('LELEMON_DEBUG') === 'true';\n}\n\n// ─────────────────────────────────────────────────────────────\n// Logging Functions\n// ─────────────────────────────────────────────────────────────\n\nconst PREFIX = '[Lelemon]';\n\n/**\n * Log debug message (only when debug enabled)\n */\nexport function debug(message: string, data?: unknown): void {\n if (!isDebugEnabled()) return;\n logWithPrefix('debug', message, data);\n}\n\n/**\n * Log info message (only when debug enabled)\n */\nexport function info(message: string, data?: unknown): void {\n if (!isDebugEnabled()) return;\n logWithPrefix('info', message, data);\n}\n\n/**\n * Log warning message (always shown)\n */\nexport function warn(message: string, data?: unknown): void {\n logWithPrefix('warn', message, data);\n}\n\n/**\n * Log error message (always shown)\n */\nexport function error(message: string, data?: unknown): void {\n logWithPrefix('error', message, data);\n}\n\n// ─────────────────────────────────────────────────────────────\n// Trace-specific logging\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Log when a trace is captured\n */\nexport function traceCapture(provider: string, model: string, durationMs: number, status: string): void {\n if (!isDebugEnabled()) return;\n console.log(\n `${PREFIX} Captured trace: provider=${provider} model=${model} duration=${durationMs}ms status=${status}`\n );\n}\n\n/**\n * Log when a trace capture fails (always visible)\n */\nexport function traceCaptureError(provider: string, err: Error): void {\n console.error(`${PREFIX} Failed to capture trace: provider=${provider} error=${err.message}`);\n}\n\n/**\n * Log when a client is wrapped\n */\nexport function clientWrapped(provider: string): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Wrapped client: provider=${provider}`);\n}\n\n/**\n * Log transport events\n */\nexport function transportEvent(event: string, details?: Record<string, unknown>): void {\n if (!isDebugEnabled()) return;\n if (details) {\n console.log(`${PREFIX} Transport: ${event}`, details);\n } else {\n console.log(`${PREFIX} Transport: ${event}`);\n }\n}\n\n/**\n * Log batch send details\n */\nexport function batchSend(count: number, endpoint: string): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Sending batch: count=${count} endpoint=${endpoint}`);\n}\n\n/**\n * Log batch send success\n */\nexport function batchSuccess(count: number, durationMs: number): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Batch sent successfully: count=${count} duration=${durationMs}ms`);\n}\n\n/**\n * Log batch send failure (always visible - errors should never be silent)\n */\nexport function batchError(count: number, err: unknown): void {\n const message = err instanceof Error ? err.message : String(err);\n console.error(`${PREFIX} Batch send failed: count=${count} error=${message}`);\n}\n\n/**\n * Log request details (for deep debugging)\n */\nexport function requestDetails(method: string, url: string, bodySize: number): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Request: ${method} ${url} (${bodySize} bytes)`);\n}\n\n/**\n * Log response details\n */\nexport function responseDetails(status: number, durationMs: number): void {\n if (!isDebugEnabled()) return;\n console.log(`${PREFIX} Response: status=${status} duration=${durationMs}ms`);\n}\n\n// ─────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────\n\nfunction logWithPrefix(level: 'debug' | 'info' | 'warn' | 'error', message: string, data?: unknown): void {\n const logFn = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log;\n\n if (data !== undefined) {\n logFn(`${PREFIX} ${message}`, data);\n } else {\n logFn(`${PREFIX} ${message}`);\n }\n}\n\nfunction getEnvVar(name: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[name];\n }\n return undefined;\n}\n","/**\n * Transport Layer\n *\n * Handles batched HTTP requests to the Lelemon API.\n * Features:\n * - Queue-based batching\n * - Auto-flush on batch size or interval\n * - Request timeout protection\n * - Graceful error handling\n */\n\nimport type { CreateTraceRequest } from './types';\nimport { batchSend, batchSuccess, batchError, requestDetails, responseDetails, transportEvent } from './logger';\n\n// ─────────────────────────────────────────────────────────────\n// Configuration\n// ─────────────────────────────────────────────────────────────\n\ninterface TransportConfig {\n apiKey: string;\n endpoint: string;\n debug: boolean;\n disabled: boolean;\n batchSize?: number;\n flushIntervalMs?: number;\n requestTimeoutMs?: number;\n}\n\nconst DEFAULT_BATCH_SIZE = 10;\nconst DEFAULT_FLUSH_INTERVAL_MS = 1000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10000;\n\n// ─────────────────────────────────────────────────────────────\n// Transport Class\n// ─────────────────────────────────────────────────────────────\n\nexport class Transport {\n private readonly config: Required<TransportConfig>;\n private queue: CreateTraceRequest[] = [];\n private flushPromise: Promise<void> | null = null;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(config: TransportConfig) {\n this.config = {\n apiKey: config.apiKey,\n endpoint: config.endpoint,\n debug: config.debug,\n disabled: config.disabled,\n batchSize: config.batchSize ?? DEFAULT_BATCH_SIZE,\n flushIntervalMs: config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n requestTimeoutMs: config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n };\n }\n\n /**\n * Check if transport is enabled\n */\n isEnabled(): boolean {\n return !this.config.disabled && !!this.config.apiKey;\n }\n\n /**\n * Enqueue a trace for sending\n * Fire-and-forget - never blocks\n */\n enqueue(trace: CreateTraceRequest): void {\n if (this.config.disabled) return;\n\n this.queue.push(trace);\n\n if (this.queue.length >= this.config.batchSize) {\n this.flush();\n } else {\n this.scheduleFlush();\n }\n }\n\n /**\n * Flush all pending traces\n * Safe to call multiple times\n */\n async flush(): Promise<void> {\n if (this.flushPromise) {\n return this.flushPromise;\n }\n\n if (this.queue.length === 0) {\n return;\n }\n\n this.cancelScheduledFlush();\n\n const items = this.queue;\n this.queue = [];\n\n this.flushPromise = this.sendBatch(items).finally(() => {\n this.flushPromise = null;\n });\n\n return this.flushPromise;\n }\n\n /**\n * Get pending count (for debugging)\n */\n getPendingCount(): number {\n return this.queue.length;\n }\n\n // ─────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────\n\n private scheduleFlush(): void {\n if (this.flushTimer !== null) return;\n\n this.flushTimer = setTimeout(() => {\n this.flushTimer = null;\n this.flush();\n }, this.config.flushIntervalMs);\n }\n\n private cancelScheduledFlush(): void {\n if (this.flushTimer !== null) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n }\n\n private async sendBatch(items: CreateTraceRequest[]): Promise<void> {\n if (items.length === 0) return;\n\n const startTime = Date.now();\n batchSend(items.length, `${this.config.endpoint}/api/v1/ingest`);\n\n try {\n await this.request('POST', '/api/v1/ingest', { events: items });\n batchSuccess(items.length, Date.now() - startTime);\n } catch (error) {\n batchError(items.length, error);\n // Don't rethrow - observability should never crash the app\n }\n }\n\n private async request(method: string, path: string, body?: unknown): Promise<unknown> {\n const url = `${this.config.endpoint}${path}`;\n const controller = new AbortController();\n const bodyStr = body ? JSON.stringify(body) : undefined;\n\n requestDetails(method, url, bodyStr?.length ?? 0);\n\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, this.config.requestTimeoutMs);\n\n const startTime = Date.now();\n\n try {\n const response = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n },\n body: bodyStr,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n responseDetails(response.status, Date.now() - startTime);\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'Unknown error');\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const text = await response.text();\n return text ? JSON.parse(text) : {};\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`);\n }\n\n throw error;\n }\n }\n}\n","/**\n * Global Configuration\n *\n * Manages SDK configuration and transport instance.\n */\n\nimport type { LelemonConfig } from './types';\nimport { Transport } from './transport';\nimport { setDebug, info, warn, debug } from './logger';\n\n// ─────────────────────────────────────────────────────────────\n// Global State\n// ─────────────────────────────────────────────────────────────\n\nlet globalConfig: LelemonConfig = {};\nlet globalTransport: Transport | null = null;\nlet initialized = false;\n\n// ─────────────────────────────────────────────────────────────\n// Configuration\n// ─────────────────────────────────────────────────────────────\n\nconst DEFAULT_ENDPOINT = 'https://www.lelemon.dev';\n\n/**\n * Initialize the SDK\n * Call once at app startup\n */\nexport function init(config: LelemonConfig = {}): void {\n globalConfig = config;\n\n // Configure debug mode\n if (config.debug) {\n setDebug(true);\n }\n\n info('Initializing SDK', {\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n debug: config.debug ?? false,\n disabled: config.disabled ?? false,\n });\n\n globalTransport = createTransport(config);\n initialized = true;\n\n // Log status after transport is created\n if (globalTransport.isEnabled()) {\n info('SDK initialized - tracing enabled');\n } else {\n debug('SDK initialized - tracing disabled (no API key or explicitly disabled)');\n }\n}\n\n/**\n * Get current config\n */\nexport function getConfig(): LelemonConfig {\n return globalConfig;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isInitialized(): boolean {\n return initialized;\n}\n\n/**\n * Check if SDK is enabled\n */\nexport function isEnabled(): boolean {\n return getTransport().isEnabled();\n}\n\n// ─────────────────────────────────────────────────────────────\n// Transport\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Get or create transport instance\n */\nexport function getTransport(): Transport {\n if (!globalTransport) {\n globalTransport = createTransport(globalConfig);\n }\n return globalTransport;\n}\n\n/**\n * Flush all pending traces\n */\nexport async function flush(): Promise<void> {\n if (globalTransport) {\n await globalTransport.flush();\n }\n}\n\n/**\n * Create transport instance\n */\nfunction createTransport(config: LelemonConfig): Transport {\n const apiKey = config.apiKey ?? getEnvVar('LELEMON_API_KEY');\n\n if (!apiKey && !config.disabled) {\n warn('No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled.');\n }\n\n return new Transport({\n apiKey: apiKey ?? '',\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n debug: config.debug ?? false,\n disabled: config.disabled ?? !apiKey,\n batchSize: config.batchSize,\n flushIntervalMs: config.flushIntervalMs,\n requestTimeoutMs: config.requestTimeoutMs,\n });\n}\n\n/**\n * Get environment variable (works in Node and edge)\n */\nfunction getEnvVar(name: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[name];\n }\n return undefined;\n}\n","/**\n * Capture Module\n *\n * Handles trace capture and batching.\n * Called by providers to record LLM calls.\n */\n\nimport type { ProviderName, CreateTraceRequest, ObserveOptions, CaptureSpanOptions, SpanType } from './types';\nimport { getTransport } from './config';\nimport { traceCapture, traceCaptureError, debug } from './logger';\nimport { getTraceContext, generateId } from './context';\n\n// ─────────────────────────────────────────────────────────────\n// Global context (set via observe options)\n// ─────────────────────────────────────────────────────────────\n\nlet globalContext: ObserveOptions = {};\n\nexport function setGlobalContext(options: ObserveOptions): void {\n globalContext = options;\n debug('Global context updated', options);\n}\n\nexport function getGlobalContext(): ObserveOptions {\n return globalContext;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Capture Functions\n// ─────────────────────────────────────────────────────────────\n\nexport interface CaptureTraceParams {\n provider: ProviderName;\n model: string;\n input: unknown;\n durationMs: number;\n status: 'success' | 'error';\n streaming: boolean;\n metadata?: Record<string, unknown>;\n\n // Raw response (server extracts tokens, output, tools, etc.)\n rawResponse?: unknown;\n\n // Timing\n firstTokenMs?: number;\n\n // Manual span type\n spanType?: SpanType;\n name?: string;\n}\n\nexport interface CaptureErrorParams {\n provider: ProviderName;\n model: string;\n input: unknown;\n error: Error;\n durationMs: number;\n streaming: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Capture a successful trace (LLM call)\n * Fire-and-forget - never throws\n * @returns The span ID, for linking tool calls to this LLM span\n */\nexport function captureTrace(params: CaptureTraceParams): string | undefined {\n try {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping trace capture');\n return undefined;\n }\n\n const globalContext = getGlobalContext();\n const traceContext = getTraceContext();\n const spanId = generateId();\n\n const request: CreateTraceRequest = {\n provider: params.provider,\n model: params.model,\n input: sanitizeInput(params.input),\n rawResponse: params.rawResponse ? sanitize(params.rawResponse, 0) : undefined,\n durationMs: params.durationMs,\n status: params.status,\n streaming: params.streaming,\n firstTokenMs: params.firstTokenMs,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n // Hierarchy fields\n traceId: traceContext?.traceId,\n spanId,\n parentSpanId: traceContext?.currentSpanId,\n metadata: {\n ...globalContext.metadata,\n ...params.metadata,\n ...(traceContext ? { _traceName: traceContext.name } : {}),\n },\n tags: globalContext.tags,\n // Manual span fields\n spanType: params.spanType,\n name: params.name,\n };\n\n traceCapture(params.provider, params.model, params.durationMs, params.status);\n transport.enqueue(request);\n\n return spanId;\n } catch (err) {\n traceCaptureError(params.provider, err instanceof Error ? err : new Error(String(err)));\n return undefined;\n }\n}\n\n/**\n * Capture an error trace\n * Fire-and-forget - never throws\n */\nexport function captureError(params: CaptureErrorParams): void {\n try {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping error capture');\n return;\n }\n\n const globalContext = getGlobalContext();\n const traceContext = getTraceContext();\n\n const request: CreateTraceRequest = {\n provider: params.provider,\n model: params.model,\n input: sanitizeInput(params.input),\n durationMs: params.durationMs,\n status: 'error',\n errorMessage: params.error.message,\n streaming: params.streaming,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n traceId: traceContext?.traceId,\n spanId: generateId(),\n parentSpanId: traceContext?.currentSpanId,\n metadata: {\n ...globalContext.metadata,\n ...params.metadata,\n ...(traceContext ? { _traceName: traceContext.name } : {}),\n },\n tags: globalContext.tags,\n };\n\n traceCapture(params.provider, params.model, params.durationMs, 'error');\n debug('Error details', { message: params.error.message, stack: params.error.stack });\n transport.enqueue(request);\n } catch (err) {\n traceCaptureError(params.provider, err instanceof Error ? err : new Error(String(err)));\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Manual Span Capture\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Manually capture a span (tool call, retrieval, custom)\n * Use this when auto-detection doesn't cover your use case\n *\n * @example\n * // Capture a tool call\n * captureSpan({\n * type: 'tool',\n * name: 'get_weather',\n * input: { location: 'San Francisco' },\n * output: { temperature: 72, conditions: 'sunny' },\n * durationMs: 150,\n * });\n *\n * @example\n * // Capture a retrieval/RAG operation\n * captureSpan({\n * type: 'retrieval',\n * name: 'vector_search',\n * input: { query: 'user question', k: 5 },\n * output: { documents: [...] },\n * durationMs: 50,\n * });\n */\nexport function captureSpan(options: CaptureSpanOptions): void {\n try {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping span capture');\n return;\n }\n\n const globalContext = getGlobalContext();\n const traceContext = getTraceContext();\n\n // Extract trace context from metadata if passed from span() in context.ts\n const metadataTraceId = (options.metadata as Record<string, unknown>)?._traceId as string | undefined;\n const metadataParentSpanId = (options.metadata as Record<string, unknown>)?._parentSpanId as string | undefined;\n\n // Clean up internal metadata keys\n const cleanMetadata = { ...globalContext.metadata, ...options.metadata };\n delete (cleanMetadata as Record<string, unknown>)._traceId;\n delete (cleanMetadata as Record<string, unknown>)._parentSpanId;\n\n const request: CreateTraceRequest = {\n spanType: options.type,\n name: options.name,\n provider: 'unknown',\n model: options.name,\n input: sanitizeInput(options.input),\n // Manual spans use output directly (not rawResponse)\n output: sanitize(options.output, 0),\n durationMs: options.durationMs,\n status: options.status || 'success',\n errorMessage: options.errorMessage,\n streaming: false,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n traceId: metadataTraceId ?? traceContext?.traceId,\n spanId: generateId(),\n parentSpanId: metadataParentSpanId ?? traceContext?.currentSpanId,\n toolCallId: options.toolCallId,\n metadata: cleanMetadata,\n tags: globalContext.tags,\n };\n\n debug(`Span captured: ${options.type}/${options.name}`, { durationMs: options.durationMs });\n transport.enqueue(request);\n } catch (err) {\n traceCaptureError('unknown', err instanceof Error ? err : new Error(String(err)));\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Sanitization (security)\n// ─────────────────────────────────────────────────────────────\n\nconst MAX_STRING_LENGTH = 100_000; // 100KB per field\nconst SENSITIVE_KEYS = ['api_key', 'apikey', 'password', 'secret', 'token', 'authorization'];\n\n/**\n * Sanitize input before sending\n * - Truncates large strings\n * - Removes sensitive data\n */\nfunction sanitizeInput(input: unknown): unknown {\n return sanitize(input, 0);\n}\n\n/**\n * Sanitize output before sending\n */\nfunction sanitizeOutput(output: unknown): unknown {\n return sanitize(output, 0);\n}\n\nfunction sanitize(value: unknown, depth: number): unknown {\n // Prevent infinite recursion\n if (depth > 10) return '[max depth exceeded]';\n\n if (value === null || value === undefined) return value;\n\n if (typeof value === 'string') {\n return value.length > MAX_STRING_LENGTH\n ? value.slice(0, MAX_STRING_LENGTH) + '...[truncated]'\n : value;\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => sanitize(item, depth + 1));\n }\n\n if (typeof value === 'object') {\n const sanitized: Record<string, unknown> = {};\n\n for (const [key, val] of Object.entries(value)) {\n // Redact sensitive keys\n if (SENSITIVE_KEYS.some((k) => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]';\n } else {\n sanitized[key] = sanitize(val, depth + 1);\n }\n }\n\n return sanitized;\n }\n\n // Functions, symbols, etc.\n return String(value);\n}\n","/**\n * Trace Context Module\n *\n * Provides AsyncLocalStorage-based context for grouping spans under a parent trace.\n * Supports hierarchical tracing where:\n * - trace() creates a root \"agent\" span\n * - LLM calls become children of the root\n * - Tool calls become children of the LLM that triggered them (via toolCallId linking)\n *\n * @example\n * ```typescript\n * import { trace, span } from '@lelemondev/sdk';\n *\n * await trace({ name: 'sales-agent', input: userMessage }, async () => {\n * const response = await client.send(new ConverseCommand({...}));\n * // Tools automatically linked to their parent LLM via toolCallId\n * return response;\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { getTransport } from './config';\nimport { getGlobalContext } from './capture';\nimport { debug } from './logger';\nimport type { CreateTraceRequest, SpanType } from './types';\n\n// ─────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────\n\nexport interface TraceContext {\n /** Unique trace ID (shared by all spans in this trace) */\n traceId: string;\n /** Root span ID (the agent/workflow span) */\n rootSpanId: string;\n /** Current span ID (for nesting - LLM calls become children of this) */\n currentSpanId: string;\n /** Parent span ID (for nested trace() calls) */\n parentSpanId?: string;\n /** Trace name */\n name: string;\n /** Start time in ms */\n startTime: number;\n /** Input data */\n input?: unknown;\n /** Trace metadata */\n metadata?: Record<string, unknown>;\n /** Trace tags */\n tags?: string[];\n /** Map of toolCallId → llmSpanId for linking tool spans to their parent LLM */\n pendingToolCalls: Map<string, string>;\n}\n\nexport interface TraceOptions {\n /** Name for the trace (e.g., 'sales-agent', 'rag-query') */\n name: string;\n /** Input data for the trace */\n input?: unknown;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n /** Tags for filtering */\n tags?: string[];\n}\n\nexport interface SpanOptions {\n /** Span type */\n type: 'retrieval' | 'embedding' | 'tool' | 'guardrail' | 'rerank' | 'custom';\n /** Span name (e.g., 'pinecone-search', 'cohere-rerank') */\n name: string;\n /** Input data */\n input?: unknown;\n /** Output data */\n output?: unknown;\n /** Duration in milliseconds (optional, will be set automatically if not provided) */\n durationMs?: number;\n /** Status */\n status?: 'success' | 'error';\n /** Error message if status is 'error' */\n errorMessage?: string;\n /** Tool call ID (links this tool span to the LLM that requested it) */\n toolCallId?: string;\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n}\n\n// ─────────────────────────────────────────────────────────────\n// AsyncLocalStorage for trace context\n// ─────────────────────────────────────────────────────────────\n\nconst traceStorage = new AsyncLocalStorage<TraceContext>();\n\n// ─────────────────────────────────────────────────────────────\n// ID Generation\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Generate a unique trace/span ID\n * Uses crypto.randomUUID if available, falls back to timestamp-based ID\n */\nexport function generateId(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n // Fallback for older Node.js versions\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Context API\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Get the current trace context, if any\n */\nexport function getTraceContext(): TraceContext | undefined {\n return traceStorage.getStore();\n}\n\n/**\n * Check if we're inside a trace() block\n */\nexport function hasTraceContext(): boolean {\n return traceStorage.getStore() !== undefined;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Tool Call Linking\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Register tool calls from an LLM response.\n * When the LLM returns with tool_use, call this to link subsequent tool spans.\n * @param toolCallIds - Array of tool call IDs from the LLM response\n * @param llmSpanId - The span ID of the LLM call that requested these tools\n */\nexport function registerToolCalls(toolCallIds: string[], llmSpanId: string): void {\n const ctx = getTraceContext();\n if (!ctx) return;\n\n for (const id of toolCallIds) {\n ctx.pendingToolCalls.set(id, llmSpanId);\n debug(`Registered tool call ${id} → LLM span ${llmSpanId}`);\n }\n}\n\n/**\n * Get the correct parent span ID for a tool span.\n * If toolCallId matches a pending tool call, returns the LLM span that requested it.\n * Otherwise falls back to the current span ID.\n */\nexport function getToolParentSpanId(toolCallId?: string): string | undefined {\n const ctx = getTraceContext();\n if (!ctx) return undefined;\n\n if (toolCallId && ctx.pendingToolCalls.has(toolCallId)) {\n return ctx.pendingToolCalls.get(toolCallId);\n }\n\n return ctx.currentSpanId;\n}\n\n/**\n * Clear a tool call from the pending map after it's been processed.\n */\nexport function clearToolCall(toolCallId: string): void {\n const ctx = getTraceContext();\n if (ctx) {\n ctx.pendingToolCalls.delete(toolCallId);\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// trace() - Main API for grouping spans\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Execute a function within a trace context.\n * Creates a root \"agent\" span that contains all LLM calls and tool executions.\n * The result of the function becomes the output of the root span.\n *\n * @example Simple usage (just name)\n * ```typescript\n * await trace('sales-agent', async () => {\n * await client.send(new ConverseCommand({...}));\n * return finalResponse;\n * });\n * ```\n *\n * @example With options\n * ```typescript\n * await trace({ name: 'rag-query', input: question, tags: ['production'] }, async () => {\n * const docs = await search(question);\n * span({ type: 'retrieval', name: 'pinecone', output: { count: docs.length } });\n * return client.send(new ConverseCommand({...}));\n * });\n * ```\n */\nexport async function trace<T>(\n nameOrOptions: string | TraceOptions,\n fn: () => Promise<T>\n): Promise<T> {\n // Normalize options\n const options: TraceOptions =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n\n const parentContext = getTraceContext();\n const traceId = parentContext?.traceId ?? generateId();\n const rootSpanId = generateId();\n\n const context: TraceContext = {\n traceId,\n rootSpanId,\n currentSpanId: rootSpanId,\n parentSpanId: parentContext?.currentSpanId,\n name: options.name,\n startTime: Date.now(),\n input: options.input,\n metadata: options.metadata,\n tags: options.tags,\n pendingToolCalls: new Map(),\n };\n\n // Run the function within the trace context\n return traceStorage.run(context, async () => {\n let result: T | undefined;\n let error: Error | undefined;\n\n try {\n result = await fn();\n return result;\n } catch (e) {\n error = e instanceof Error ? e : new Error(String(e));\n throw e;\n } finally {\n // Send the root span with the final result\n sendRootSpan(context, error ? undefined : result, error);\n }\n });\n}\n\n/**\n * Send the root \"agent\" span when the trace completes.\n * This span represents the entire agent execution with input/output.\n */\nfunction sendRootSpan(context: TraceContext, result?: unknown, error?: Error): void {\n const transport = getTransport();\n if (!transport.isEnabled()) {\n debug('Transport disabled, skipping root span');\n return;\n }\n\n const globalContext = getGlobalContext();\n const durationMs = Date.now() - context.startTime;\n\n // Sanitize result if it's a string (common case for agent responses)\n const output = error ? null : result;\n\n const rootSpan: CreateTraceRequest = {\n spanType: 'agent' as SpanType,\n name: context.name,\n provider: 'agent',\n model: context.name,\n traceId: context.traceId,\n spanId: context.rootSpanId,\n parentSpanId: context.parentSpanId,\n input: context.input,\n output,\n inputTokens: 0, // Will be aggregated from children\n outputTokens: 0,\n durationMs,\n status: error ? 'error' : 'success',\n errorMessage: error?.message,\n streaming: false,\n sessionId: globalContext.sessionId,\n userId: globalContext.userId,\n metadata: {\n ...globalContext.metadata,\n ...context.metadata,\n },\n tags: context.tags ?? globalContext.tags,\n };\n\n debug(`Sending root span: ${context.name}`, { durationMs, hasError: !!error });\n transport.enqueue(rootSpan);\n}\n\n// ─────────────────────────────────────────────────────────────\n// span() - Manual span capture for non-LLM operations\n// ─────────────────────────────────────────────────────────────\n\n// Import directly - circular dependency is handled by module system\nimport { captureSpan as captureSpanImport } from './capture';\n\n/**\n * Manually capture a span for non-LLM operations (retrieval, embedding, tool, etc.)\n * Must be called within a trace() block.\n *\n * @example Tool with toolCallId (links to parent LLM)\n * ```typescript\n * span({\n * type: 'tool',\n * name: 'query_database',\n * toolCallId: 'tooluse_abc123', // Links to LLM that requested this\n * input: { sql: 'SELECT ...' },\n * output: { rows: [...] },\n * durationMs: 15,\n * });\n * ```\n *\n * @example Retrieval without toolCallId\n * ```typescript\n * span({\n * type: 'retrieval',\n * name: 'pinecone-search',\n * input: { topK: 5 },\n * output: { count: 10 },\n * durationMs: 50,\n * });\n * ```\n */\nexport function span(options: SpanOptions): void {\n const context = getTraceContext();\n\n if (!context) {\n // Warn but don't throw - fire-and-forget principle\n if (process.env.NODE_ENV !== 'production') {\n console.warn('[Lelemon] span() called outside of trace() - span will not be captured');\n }\n return;\n }\n\n // Determine parent: if toolCallId provided and registered, use the LLM span\n const parentSpanId = getToolParentSpanId(options.toolCallId);\n\n captureSpanImport({\n type: options.type,\n name: options.name,\n input: options.input,\n output: options.output,\n durationMs: options.durationMs ?? 0,\n status: options.status ?? 'success',\n errorMessage: options.errorMessage,\n toolCallId: options.toolCallId,\n metadata: {\n ...options.metadata,\n _traceId: context.traceId,\n _parentSpanId: parentSpanId,\n },\n });\n\n // Clear the tool call after processing\n if (options.toolCallId) {\n clearToolCall(options.toolCallId);\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Internal helpers (exported for capture.ts)\n// ─────────────────────────────────────────────────────────────\n\n/**\n * Run a function with a specific trace context (for internal use)\n */\nexport function runWithContext<T>(context: TraceContext, fn: () => T): T {\n return traceStorage.run(context, fn);\n}\n","/**\n * Google Gemini Provider Wrapper\n *\n * Wraps @google/generative-ai to automatically capture LLM calls.\n * SDK thin: only captures timing and raw response.\n * Server smart: extracts tokens, output, tools, etc.\n */\n\nimport type { ProviderName } from '../core/types';\nimport { captureTrace, captureError } from '../core/capture';\nimport { registerToolCalls } from '../core/context';\n\n// ─────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────\n\ninterface GeminiClient {\n getGenerativeModel: (config: ModelConfig) => GenerativeModel;\n}\n\ninterface ModelConfig {\n model: string;\n [key: string]: unknown;\n}\n\ninterface GenerativeModel {\n generateContent: (request: GenerateContentRequest | string) => Promise<GenerateContentResult>;\n generateContentStream: (request: GenerateContentRequest | string) => Promise<StreamGenerateContentResult>;\n startChat: (config?: ChatConfig) => ChatSession;\n model: string;\n}\n\ninterface GenerateContentRequest {\n contents?: Content[];\n [key: string]: unknown;\n}\n\ninterface Content {\n role?: string;\n parts: Part[];\n}\n\ninterface Part {\n text?: string;\n functionCall?: { name: string; args: unknown };\n [key: string]: unknown;\n}\n\ninterface GenerateContentResult {\n response: GenerateContentResponse;\n}\n\ninterface StreamGenerateContentResult {\n stream: AsyncIterable<GenerateContentStreamChunk>;\n response: Promise<GenerateContentResponse>;\n}\n\ninterface GenerateContentResponse {\n text: () => string;\n candidates?: Candidate[];\n usageMetadata?: UsageMetadata;\n}\n\ninterface GenerateContentStreamChunk {\n text: () => string;\n candidates?: Candidate[];\n usageMetadata?: UsageMetadata;\n}\n\ninterface Candidate {\n content?: Content;\n finishReason?: string;\n}\n\ninterface UsageMetadata {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n cachedContentTokenCount?: number;\n thoughtsTokenCount?: number;\n}\n\ninterface ChatConfig {\n [key: string]: unknown;\n}\n\ninterface ChatSession {\n sendMessage: (request: string | Part[]) => Promise<GenerateContentResult>;\n sendMessageStream: (request: string | Part[]) => Promise<StreamGenerateContentResult>;\n}\n\n// ─────────────────────────────────────────────────────────────\n// Provider Implementation\n// ─────────────────────────────────────────────────────────────\n\nexport const PROVIDER_NAME: ProviderName = 'gemini';\n\nexport function canHandle(client: unknown): boolean {\n if (!client || typeof client !== 'object') return false;\n const constructorName = client.constructor?.name;\n if (constructorName === 'GoogleGenerativeAI') return true;\n if (constructorName === 'GoogleGenAI') return true;\n const c = client as Record<string, unknown>;\n if (typeof c.getGenerativeModel === 'function') return true;\n if (c.models && typeof (c.models as Record<string, unknown>).generate === 'function') {\n return true;\n }\n return false;\n}\n\nexport function wrap(client: unknown): unknown {\n const geminiClient = client as GeminiClient;\n return new Proxy(geminiClient, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === 'getGenerativeModel' && typeof value === 'function') {\n return wrapGetGenerativeModel(value.bind(target));\n }\n return value;\n },\n });\n}\n\nfunction wrapGetGenerativeModel(\n originalFn: (config: ModelConfig) => GenerativeModel\n): (config: ModelConfig) => GenerativeModel {\n return function wrappedGetGenerativeModel(config: ModelConfig): GenerativeModel {\n const model = originalFn(config);\n return wrapGenerativeModel(model, config.model);\n };\n}\n\nfunction wrapGenerativeModel(model: GenerativeModel, modelName: string): GenerativeModel {\n return new Proxy(model, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === 'generateContent' && typeof value === 'function') {\n return wrapGenerateContent(value.bind(target), modelName);\n }\n if (prop === 'generateContentStream' && typeof value === 'function') {\n return wrapGenerateContentStream(value.bind(target), modelName);\n }\n if (prop === 'startChat' && typeof value === 'function') {\n return wrapStartChat(value.bind(target), modelName);\n }\n return value;\n },\n });\n}\n\n// ─────────────────────────────────────────────────────────────\n// generateContent\n// ─────────────────────────────────────────────────────────────\n\nfunction wrapGenerateContent(\n originalFn: (request: GenerateContentRequest | string) => Promise<GenerateContentResult>,\n modelName: string\n) {\n return async function wrappedGenerateContent(\n request: GenerateContentRequest | string\n ): Promise<GenerateContentResult> {\n const startTime = Date.now();\n const input = extractInput(request);\n\n try {\n const result = await originalFn(request);\n const durationMs = Date.now() - startTime;\n\n // Build raw response from Gemini's response object\n const rawResponse = buildRawResponse(result.response);\n\n const spanId = captureTrace({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n rawResponse, // Server extracts everything\n durationMs,\n status: 'success',\n streaming: false,\n });\n\n // Register function calls for hierarchy\n if (spanId) {\n const functionCallIds = extractFunctionCallIds(result.response);\n if (functionCallIds.length > 0) {\n registerToolCalls(functionCallIds, spanId);\n }\n }\n\n return result;\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: false,\n });\n throw error;\n }\n };\n}\n\n// ─────────────────────────────────────────────────────────────\n// generateContentStream\n// ─────────────────────────────────────────────────────────────\n\nfunction wrapGenerateContentStream(\n originalFn: (request: GenerateContentRequest | string) => Promise<StreamGenerateContentResult>,\n modelName: string\n) {\n return async function wrappedGenerateContentStream(\n request: GenerateContentRequest | string\n ): Promise<StreamGenerateContentResult> {\n const startTime = Date.now();\n const input = extractInput(request);\n\n try {\n const result = await originalFn(request);\n const wrappedStream = wrapStream(result.stream, modelName, input, startTime);\n return {\n ...result,\n stream: wrappedStream,\n };\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: true,\n });\n throw error;\n }\n };\n}\n\nasync function* wrapStream(\n stream: AsyncIterable<GenerateContentStreamChunk>,\n modelName: string,\n input: unknown,\n startTime: number\n): AsyncIterable<GenerateContentStreamChunk> {\n // Accumulate to build final response\n const finalResponse: {\n candidates: Candidate[];\n usageMetadata?: UsageMetadata;\n } = { candidates: [{ content: { parts: [] } }] };\n let error: Error | null = null;\n let firstTokenMs: number | undefined;\n let firstTokenReceived = false;\n\n try {\n for await (const chunk of stream) {\n // Accumulate text\n try {\n const text = chunk.text();\n if (text) {\n if (!firstTokenReceived) {\n firstTokenReceived = true;\n firstTokenMs = Date.now() - startTime;\n }\n // Add text part to accumulated response\n const parts = finalResponse.candidates[0].content?.parts || [];\n const lastPart = parts[parts.length - 1];\n if (lastPart?.text !== undefined) {\n lastPart.text += text;\n } else {\n parts.push({ text });\n }\n }\n } catch {\n // text() may throw if no text content\n }\n\n // Extract candidates for function calls\n if (chunk.candidates?.[0]?.content?.parts) {\n for (const part of chunk.candidates[0].content.parts) {\n if (part.functionCall) {\n finalResponse.candidates[0].content?.parts?.push(part);\n }\n }\n }\n\n // Capture usage and finish reason from last chunk\n if (chunk.usageMetadata) {\n finalResponse.usageMetadata = chunk.usageMetadata;\n }\n if (chunk.candidates?.[0]?.finishReason) {\n finalResponse.candidates[0].finishReason = chunk.candidates[0].finishReason;\n }\n\n yield chunk;\n }\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err));\n throw err;\n } finally {\n const durationMs = Date.now() - startTime;\n\n if (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error,\n durationMs,\n streaming: true,\n });\n } else {\n const spanId = captureTrace({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n rawResponse: finalResponse,\n durationMs,\n status: 'success',\n streaming: true,\n firstTokenMs,\n });\n\n if (spanId) {\n const functionCallIds = extractFunctionCallIdsFromCandidates(finalResponse.candidates);\n if (functionCallIds.length > 0) {\n registerToolCalls(functionCallIds, spanId);\n }\n }\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────\n// Chat\n// ─────────────────────────────────────────────────────────────\n\nfunction wrapStartChat(\n originalFn: (config?: ChatConfig) => ChatSession,\n modelName: string\n): (config?: ChatConfig) => ChatSession {\n return function wrappedStartChat(config?: ChatConfig): ChatSession {\n const chat = originalFn(config);\n return wrapChatSession(chat, modelName);\n };\n}\n\nfunction wrapChatSession(chat: ChatSession, modelName: string): ChatSession {\n return new Proxy(chat, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === 'sendMessage' && typeof value === 'function') {\n return wrapSendMessage(value.bind(target), modelName);\n }\n if (prop === 'sendMessageStream' && typeof value === 'function') {\n return wrapSendMessageStream(value.bind(target), modelName);\n }\n return value;\n },\n });\n}\n\nfunction wrapSendMessage(\n originalFn: (request: string | Part[]) => Promise<GenerateContentResult>,\n modelName: string\n) {\n return async function wrappedSendMessage(\n request: string | Part[]\n ): Promise<GenerateContentResult> {\n const startTime = Date.now();\n const input = request;\n\n try {\n const result = await originalFn(request);\n const durationMs = Date.now() - startTime;\n const rawResponse = buildRawResponse(result.response);\n\n const spanId = captureTrace({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n rawResponse,\n durationMs,\n status: 'success',\n streaming: false,\n });\n\n if (spanId) {\n const functionCallIds = extractFunctionCallIds(result.response);\n if (functionCallIds.length > 0) {\n registerToolCalls(functionCallIds, spanId);\n }\n }\n\n return result;\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: false,\n });\n throw error;\n }\n };\n}\n\nfunction wrapSendMessageStream(\n originalFn: (request: string | Part[]) => Promise<StreamGenerateContentResult>,\n modelName: string\n) {\n return async function wrappedSendMessageStream(\n request: string | Part[]\n ): Promise<StreamGenerateContentResult> {\n const startTime = Date.now();\n const input = request;\n\n try {\n const result = await originalFn(request);\n const wrappedStream = wrapStream(result.stream, modelName, input, startTime);\n return {\n ...result,\n stream: wrappedStream,\n };\n } catch (error) {\n captureError({\n provider: PROVIDER_NAME,\n model: modelName,\n input,\n error: error instanceof Error ? error : new Error(String(error)),\n durationMs: Date.now() - startTime,\n streaming: true,\n });\n throw error;\n }\n };\n}\n\n// ─────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────\n\nfunction extractInput(request: GenerateContentRequest | string): unknown {\n if (typeof request === 'string') return request;\n if (request.contents) return request.contents;\n return request;\n}\n\nfunction buildRawResponse(response: GenerateContentResponse): unknown {\n // Build a serializable response object\n return {\n candidates: response.candidates,\n usageMetadata: response.usageMetadata,\n };\n}\n\nfunction extractFunctionCallIds(response: GenerateContentResponse): string[] {\n const ids: string[] = [];\n const parts = response.candidates?.[0]?.content?.parts;\n if (parts) {\n parts.forEach((part, index) => {\n if (part.functionCall?.name) {\n ids.push(`gemini-fc-${part.functionCall.name}-${index}`);\n }\n });\n }\n return ids;\n}\n\nfunction extractFunctionCallIdsFromCandidates(candidates: Candidate[]): string[] {\n const ids: string[] = [];\n const parts = candidates?.[0]?.content?.parts;\n if (parts) {\n parts.forEach((part, index) => {\n if (part.functionCall?.name) {\n ids.push(`gemini-fc-${part.functionCall.name}-${index}`);\n }\n });\n }\n return ids;\n}\n","/**\n * Google Gemini Provider Entry Point\n *\n * @example\n * ```typescript\n * import { init, observe, flush } from '@lelemondev/sdk/gemini';\n * import { GoogleGenerativeAI } from '@google/generative-ai';\n *\n * init({ apiKey: process.env.LELEMON_API_KEY });\n * const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);\n * const model = observe(genAI.getGenerativeModel({ model: 'gemini-pro' }));\n *\n * await model.generateContent('Hello!');\n * await flush();\n * ```\n */\n\n// Re-export core\nexport { init, flush, isEnabled } from './core/config';\nexport { trace, span, getTraceContext } from './core/context';\nexport { captureSpan } from './core/capture';\n\n// Re-export types\nexport type {\n LelemonConfig,\n ObserveOptions,\n SpanType,\n CaptureSpanOptions,\n} from './core/types';\nexport type { TraceContext, TraceOptions, SpanOptions } from './core/context';\n\n// Provider-specific observe\nimport * as gemini from './providers/gemini';\nimport { setGlobalContext } from './core/capture';\nimport { getConfig } from './core/config';\nimport type { ObserveOptions } from './core/types';\nimport { clientWrapped, warn, debug } from './core/logger';\n\n/**\n * Wrap a Gemini model with automatic tracing\n */\nexport function observe<T>(client: T, options?: ObserveOptions): T {\n if (options) {\n setGlobalContext(options);\n }\n\n const config = getConfig();\n if (config.disabled) {\n debug('Tracing disabled, returning unwrapped client');\n return client;\n }\n\n if (!gemini.canHandle(client)) {\n warn('Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK.');\n return client;\n }\n\n clientWrapped('gemini');\n return gemini.wrap(client) as T;\n}\n"]}
|
package/dist/gemini.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import {AsyncLocalStorage}from'async_hooks';/* @lelemondev/sdk - LLM Observability */
|
|
2
|
-
var re=Object.defineProperty;var oe=(e,t,n)=>t in e?re(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var w=(e,t,n)=>oe(e,typeof t!="symbol"?t+"":t,n);var O=false;function _(e){O=e;}function g(){return O?true:se("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function l(e,t){g()&&P("debug",e,t);}function R(e,t){g()&&P("info",e,t);}function k(e,t){P("warn",e,t);}function G(e,t,n,r){g()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function I(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function A(e){g()&&console.log(`${p} Wrapped client: provider=${e}`);}function L(e,t){g()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function U(e,t){g()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function z(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function K(e,t,n){g()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function F(e,t){g()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function P(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function se(e){if(typeof process<"u"&&process.env)return process.env[e]}var ae=10,ie=1e3,ue=1e4,v=class{constructor(t){w(this,"config");w(this,"queue",[]);w(this,"flushPromise",null);w(this,"flushTimer",null);this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??ae,flushIntervalMs:t.flushIntervalMs??ie,requestTimeoutMs:t.requestTimeoutMs??ue};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();L(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),U(t.length,Date.now()-n);}catch(r){z(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,s=new AbortController,a=r?JSON.stringify(r):void 0;K(t,o,a?.length??0);let c=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),u=Date.now();try{let i=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:s.signal});if(clearTimeout(c),F(i.status,Date.now()-u),!i.ok){let y=await i.text().catch(()=>"Unknown error");throw new Error(`HTTP ${i.status}: ${y}`)}let d=await i.text();return d?JSON.parse(d):{}}catch(i){throw clearTimeout(c),i instanceof Error&&i.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):i}}};var $={},C=null,N="https://www.lelemon.dev";function de(e={}){$=e,e.debug&&_(true),R("Initializing SDK",{endpoint:e.endpoint??N,debug:e.debug??false,disabled:e.disabled??false}),C=B(e),C.isEnabled()?R("SDK initialized - tracing enabled"):l("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function W(){return $}function le(){return h().isEnabled()}function h(){return C||(C=B($)),C}async function pe(){C&&await C.flush();}function B(e){let t=e.apiKey??fe("LELEMON_API_KEY");return !t&&!e.disabled&&k("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new v({apiKey:t??"",endpoint:e.endpoint??N,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function fe(e){if(typeof process<"u"&&process.env)return process.env[e]}var V={};function j(e){V=e,l("Global context updated",e);}function S(){return V}function x(e){try{let t=h();if(!t.isEnabled()){l("Transport disabled, skipping trace capture");return}let n=S(),r=f(),o=b(),s={provider:e.provider,model:e.model,input:D(e.input),output:Y(e.output),inputTokens:e.inputTokens,outputTokens:e.outputTokens,durationMs:e.durationMs,status:e.status,streaming:e.streaming,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{}},tags:n.tags,stopReason:e.stopReason,cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,reasoningTokens:e.reasoningTokens,firstTokenMs:e.firstTokenMs,thinking:e.thinking};return G(e.provider,e.model,e.durationMs,e.status),t.enqueue(s),o}catch(t){I(e.provider,t instanceof Error?t:new Error(String(t)));return}}function T(e){try{let t=h();if(!t.isEnabled()){l("Transport disabled, skipping error capture");return}let n=S(),r=f(),o={provider:e.provider,model:e.model,input:D(e.input),output:null,inputTokens:0,outputTokens:0,durationMs:e.durationMs,status:"error",errorMessage:e.error.message,errorStack:e.error.stack,streaming:e.streaming,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:b(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{}},tags:n.tags};G(e.provider,e.model,e.durationMs,"error"),l("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(o);}catch(t){I(e.provider,t instanceof Error?t:new Error(String(t)));}}function q(e){try{let t=h();if(!t.isEnabled()){l("Transport disabled, skipping span capture");return}let n=S(),r=f(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,a={...n.metadata,...e.metadata};delete a._traceId,delete a._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:D(e.input),output:Y(e.output),inputTokens:0,outputTokens:0,durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:n.sessionId,userId:n.userId,traceId:o??r?.traceId,spanId:b(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:a,tags:n.tags};l(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(c);}catch(t){I("unknown",t instanceof Error?t:new Error(String(t)));}}var H=1e5,ge=["api_key","apikey","password","secret","token","authorization"];function D(e){return M(e,0)}function Y(e){return M(e,0)}function M(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string")return e.length>H?e.slice(0,H)+"...[truncated]":e;if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>M(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))ge.some(s=>r.toLowerCase().includes(s))?n[r]="[REDACTED]":n[r]=M(o,t+1);return n}return String(e)}var J=new AsyncLocalStorage;function b(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function f(){return J.getStore()}function E(e,t){let n=f();if(n)for(let r of e)n.pendingToolCalls.set(r,t),l(`Registered tool call ${r} \u2192 LLM span ${t}`);}function Ce(e){let t=f();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function he(e){let t=f();t&&t.pendingToolCalls.delete(e);}async function Te(e,t){let n=typeof e=="string"?{name:e}:e,r=f(),o=r?.traceId??b(),s=b(),a={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,pendingToolCalls:new Map};return J.run(a,async()=>{let c,u;try{return c=await t(),c}catch(i){throw u=i instanceof Error?i:new Error(String(i)),i}finally{be(a,u?void 0:c,u);}})}function be(e,t,n){let r=h();if(!r.isEnabled()){l("Transport disabled, skipping root span");return}let o=S(),s=Date.now()-e.startTime,a=n?null:t,c={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:a,inputTokens:0,outputTokens:0,durationMs:s,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:o.sessionId,userId:o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};l(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!n}),r.enqueue(c);}function we(e){let t=f();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=Ce(e.toolCallId);q({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n}}),e.toolCallId&&he(e.toolCallId);}var m="gemini";function X(e){if(!e||typeof e!="object")return false;let t=e.constructor?.name;if(t==="GoogleGenerativeAI"||t==="GoogleGenAI")return true;let n=e;return !!(typeof n.getGenerativeModel=="function"||n.models&&typeof n.models.generate=="function")}function Q(e){let t=e;return new Proxy(t,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="getGenerativeModel"&&typeof s=="function"?Se(s.bind(n)):s}})}function Se(e){return function(n){let r=e(n);return ye(r,n.model)}}function ye(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="generateContent"&&typeof s=="function"?ke(s.bind(n),t):r==="generateContentStream"&&typeof s=="function"?Ie(s.bind(n),t):r==="startChat"&&typeof s=="function"?ve(s.bind(n),t):s}})}function ke(e,t){return async function(r){let o=Date.now(),s=ee(r);try{let a=await e(r),c=Date.now()-o,u=te(a.response),i=x({provider:m,model:t,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=ne(a.response);d.length>0&&E(d,i);}return a}catch(a){throw T({provider:m,model:t,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function Ie(e,t){return async function(r){let o=Date.now(),s=ee(r);try{let a=await e(r),c=Z(a.stream,t,s,o);return {...a,stream:c}}catch(a){throw T({provider:m,model:t,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}async function*Z(e,t,n,r){let o={candidates:[{content:{parts:[]}}]},s=null,a,c=false;try{for await(let u of e){try{let i=u.text();if(i){c||(c=!0,a=Date.now()-r);let d=o.candidates[0].content?.parts||[],y=d[d.length-1];y?.text!==void 0?y.text+=i:d.push({text:i});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let i of u.candidates[0].content.parts)i.functionCall&&o.candidates[0].content?.parts?.push(i);u.usageMetadata&&(o.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw s=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(s)T({provider:m,model:t,input:n,error:s,durationMs:u,streaming:true});else {let i=x({provider:m,model:t,input:n,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:a});if(i){let d=Re(o.candidates);d.length>0&&E(d,i);}}}}function ve(e,t){return function(r){let o=e(r);return Me(o,t)}}function Me(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return r==="sendMessage"&&typeof s=="function"?xe(s.bind(n),t):r==="sendMessageStream"&&typeof s=="function"?Ee(s.bind(n),t):s}})}function xe(e,t){return async function(r){let o=Date.now(),s=r;try{let a=await e(r),c=Date.now()-o,u=te(a.response),i=x({provider:m,model:t,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=ne(a.response);d.length>0&&E(d,i);}return a}catch(a){throw T({provider:m,model:t,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function Ee(e,t){return async function(r){let o=Date.now(),s=r;try{let a=await e(r),c=Z(a.stream,t,s,o);return {...a,stream:c}}catch(a){throw T({provider:m,model:t,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}function ee(e){return typeof e=="string"?e:e.contents?e.contents:e}function te(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function ne(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function Re(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function tt(e,t){return t&&j(t),W().disabled?(l("Tracing disabled, returning unwrapped client"),e):X(e)?(A("gemini"),Q(e)):(k("Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK."),e)}
|
|
3
|
-
export{q as captureSpan,
|
|
2
|
+
var ne=Object.defineProperty;var re=(e,t,n)=>t in e?ne(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var T=(e,t,n)=>re(e,typeof t!="symbol"?t+"":t,n);var O=false;function _(e){O=e;}function g(){return O?true:oe("LELEMON_DEBUG")==="true"}var p="[Lelemon]";function l(e,t){g()&&P("debug",e,t);}function R(e,t){g()&&P("info",e,t);}function v(e,t){P("warn",e,t);}function G(e,t,n,r){g()&&console.log(`${p} Captured trace: provider=${e} model=${t} duration=${n}ms status=${r}`);}function M(e,t){console.error(`${p} Failed to capture trace: provider=${e} error=${t.message}`);}function A(e){g()&&console.log(`${p} Wrapped client: provider=${e}`);}function L(e,t){g()&&console.log(`${p} Sending batch: count=${e} endpoint=${t}`);}function U(e,t){g()&&console.log(`${p} Batch sent successfully: count=${e} duration=${t}ms`);}function z(e,t){let n=t instanceof Error?t.message:String(t);console.error(`${p} Batch send failed: count=${e} error=${n}`);}function K(e,t,n){g()&&console.log(`${p} Request: ${e} ${t} (${n} bytes)`);}function F(e,t){g()&&console.log(`${p} Response: status=${e} duration=${t}ms`);}function P(e,t,n){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`${p} ${t}`,n):r(`${p} ${t}`);}function oe(e){if(typeof process<"u"&&process.env)return process.env[e]}var ae=10,se=1e3,ie=1e4,x=class{constructor(t){T(this,"config");T(this,"queue",[]);T(this,"flushPromise",null);T(this,"flushTimer",null);this.config={apiKey:t.apiKey,endpoint:t.endpoint,debug:t.debug,disabled:t.disabled,batchSize:t.batchSize??ae,flushIntervalMs:t.flushIntervalMs??se,requestTimeoutMs:t.requestTimeoutMs??ie};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(t){this.config.disabled||(this.queue.push(t),this.queue.length>=this.config.batchSize?this.flush():this.scheduleFlush());}async flush(){if(this.flushPromise)return this.flushPromise;if(this.queue.length===0)return;this.cancelScheduledFlush();let t=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(t).finally(()=>{this.flushPromise=null;}),this.flushPromise}getPendingCount(){return this.queue.length}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},this.config.flushIntervalMs));}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null);}async sendBatch(t){if(t.length===0)return;let n=Date.now();L(t.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:t}),U(t.length,Date.now()-n);}catch(r){z(t.length,r);}}async request(t,n,r){let o=`${this.config.endpoint}${n}`,a=new AbortController,s=r?JSON.stringify(r):void 0;K(t,o,s?.length??0);let c=setTimeout(()=>{a.abort();},this.config.requestTimeoutMs),u=Date.now();try{let i=await fetch(o,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:s,signal:a.signal});if(clearTimeout(c),F(i.status,Date.now()-u),!i.ok){let I=await i.text().catch(()=>"Unknown error");throw new Error(`HTTP ${i.status}: ${I}`)}let d=await i.text();return d?JSON.parse(d):{}}catch(i){throw clearTimeout(c),i instanceof Error&&i.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):i}}};var $={},C=null,N="https://www.lelemon.dev";function ce(e={}){$=e,e.debug&&_(true),R("Initializing SDK",{endpoint:e.endpoint??N,debug:e.debug??false,disabled:e.disabled??false}),C=H(e),C.isEnabled()?R("SDK initialized - tracing enabled"):l("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function B(){return $}function de(){return h().isEnabled()}function h(){return C||(C=H($)),C}async function le(){C&&await C.flush();}function H(e){let t=e.apiKey??pe("LELEMON_API_KEY");return !t&&!e.disabled&&v("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new x({apiKey:t??"",endpoint:e.endpoint??N,debug:e.debug??false,disabled:e.disabled??!t,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function pe(e){if(typeof process<"u"&&process.env)return process.env[e]}var W={};function j(e){W=e,l("Global context updated",e);}function y(){return W}function E(e){try{let t=h();if(!t.isEnabled()){l("Transport disabled, skipping trace capture");return}let n=y(),r=f(),o=b(),a={provider:e.provider,model:e.model,input:D(e.input),rawResponse:e.rawResponse?S(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{}},tags:n.tags,spanType:e.spanType,name:e.name};return G(e.provider,e.model,e.durationMs,e.status),t.enqueue(a),o}catch(t){M(e.provider,t instanceof Error?t:new Error(String(t)));return}}function w(e){try{let t=h();if(!t.isEnabled()){l("Transport disabled, skipping error capture");return}let n=y(),r=f(),o={provider:e.provider,model:e.model,input:D(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:n.sessionId,userId:n.userId,traceId:r?.traceId,spanId:b(),parentSpanId:r?.currentSpanId,metadata:{...n.metadata,...e.metadata,...r?{_traceName:r.name}:{}},tags:n.tags};G(e.provider,e.model,e.durationMs,"error"),l("Error details",{message:e.error.message,stack:e.error.stack}),t.enqueue(o);}catch(t){M(e.provider,t instanceof Error?t:new Error(String(t)));}}function q(e){try{let t=h();if(!t.isEnabled()){l("Transport disabled, skipping span capture");return}let n=y(),r=f(),o=e.metadata?._traceId,a=e.metadata?._parentSpanId,s={...n.metadata,...e.metadata};delete s._traceId,delete s._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:D(e.input),output:S(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:n.sessionId,userId:n.userId,traceId:o??r?.traceId,spanId:b(),parentSpanId:a??r?.currentSpanId,toolCallId:e.toolCallId,metadata:s,tags:n.tags};l(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),t.enqueue(c);}catch(t){M("unknown",t instanceof Error?t:new Error(String(t)));}}var V=1e5,fe=["api_key","apikey","password","secret","token","authorization"];function D(e){return S(e,0)}function S(e,t){if(t>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string")return e.length>V?e.slice(0,V)+"...[truncated]":e;if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(n=>S(n,t+1));if(typeof e=="object"){let n={};for(let[r,o]of Object.entries(e))fe.some(a=>r.toLowerCase().includes(a))?n[r]="[REDACTED]":n[r]=S(o,t+1);return n}return String(e)}var Y=new AsyncLocalStorage;function b(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function f(){return Y.getStore()}function k(e,t){let n=f();if(n)for(let r of e)n.pendingToolCalls.set(r,t),l(`Registered tool call ${r} \u2192 LLM span ${t}`);}function me(e){let t=f();if(t)return e&&t.pendingToolCalls.has(e)?t.pendingToolCalls.get(e):t.currentSpanId}function Ce(e){let t=f();t&&t.pendingToolCalls.delete(e);}async function he(e,t){let n=typeof e=="string"?{name:e}:e,r=f(),o=r?.traceId??b(),a=b(),s={traceId:o,rootSpanId:a,currentSpanId:a,parentSpanId:r?.currentSpanId,name:n.name,startTime:Date.now(),input:n.input,metadata:n.metadata,tags:n.tags,pendingToolCalls:new Map};return Y.run(s,async()=>{let c,u;try{return c=await t(),c}catch(i){throw u=i instanceof Error?i:new Error(String(i)),i}finally{we(s,u?void 0:c,u);}})}function we(e,t,n){let r=h();if(!r.isEnabled()){l("Transport disabled, skipping root span");return}let o=y(),a=Date.now()-e.startTime,s=n?null:t,c={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:s,inputTokens:0,outputTokens:0,durationMs:a,status:n?"error":"success",errorMessage:n?.message,streaming:false,sessionId:o.sessionId,userId:o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};l(`Sending root span: ${e.name}`,{durationMs:a,hasError:!!n}),r.enqueue(c);}function be(e){let t=f();if(!t){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let n=me(e.toolCallId);q({type:e.type,name:e.name,input:e.input,output:e.output,durationMs:e.durationMs??0,status:e.status??"success",errorMessage:e.errorMessage,toolCallId:e.toolCallId,metadata:{...e.metadata,_traceId:t.traceId,_parentSpanId:n}}),e.toolCallId&&Ce(e.toolCallId);}var m="gemini";function J(e){if(!e||typeof e!="object")return false;let t=e.constructor?.name;if(t==="GoogleGenerativeAI"||t==="GoogleGenAI")return true;let n=e;return !!(typeof n.getGenerativeModel=="function"||n.models&&typeof n.models.generate=="function")}function X(e){let t=e;return new Proxy(t,{get(n,r,o){let a=Reflect.get(n,r,o);return r==="getGenerativeModel"&&typeof a=="function"?Te(a.bind(n)):a}})}function Te(e){return function(n){let r=e(n);return Se(r,n.model)}}function Se(e,t){return new Proxy(e,{get(n,r,o){let a=Reflect.get(n,r,o);return r==="generateContent"&&typeof a=="function"?ye(a.bind(n),t):r==="generateContentStream"&&typeof a=="function"?Ie(a.bind(n),t):r==="startChat"&&typeof a=="function"?ve(a.bind(n),t):a}})}function ye(e,t){return async function(r){let o=Date.now(),a=Z(r);try{let s=await e(r),c=Date.now()-o,u=ee(s.response),i=E({provider:m,model:t,input:a,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=te(s.response);d.length>0&&k(d,i);}return s}catch(s){throw w({provider:m,model:t,input:a,error:s instanceof Error?s:new Error(String(s)),durationMs:Date.now()-o,streaming:false}),s}}}function Ie(e,t){return async function(r){let o=Date.now(),a=Z(r);try{let s=await e(r),c=Q(s.stream,t,a,o);return {...s,stream:c}}catch(s){throw w({provider:m,model:t,input:a,error:s instanceof Error?s:new Error(String(s)),durationMs:Date.now()-o,streaming:true}),s}}}async function*Q(e,t,n,r){let o={candidates:[{content:{parts:[]}}]},a=null,s,c=false;try{for await(let u of e){try{let i=u.text();if(i){c||(c=!0,s=Date.now()-r);let d=o.candidates[0].content?.parts||[],I=d[d.length-1];I?.text!==void 0?I.text+=i:d.push({text:i});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let i of u.candidates[0].content.parts)i.functionCall&&o.candidates[0].content?.parts?.push(i);u.usageMetadata&&(o.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=u.candidates[0].finishReason),yield u;}}catch(u){throw a=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-r;if(a)w({provider:m,model:t,input:n,error:a,durationMs:u,streaming:true});else {let i=E({provider:m,model:t,input:n,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:s});if(i){let d=ke(o.candidates);d.length>0&&k(d,i);}}}}function ve(e,t){return function(r){let o=e(r);return Me(o,t)}}function Me(e,t){return new Proxy(e,{get(n,r,o){let a=Reflect.get(n,r,o);return r==="sendMessage"&&typeof a=="function"?xe(a.bind(n),t):r==="sendMessageStream"&&typeof a=="function"?Ee(a.bind(n),t):a}})}function xe(e,t){return async function(r){let o=Date.now(),a=r;try{let s=await e(r),c=Date.now()-o,u=ee(s.response),i=E({provider:m,model:t,input:a,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=te(s.response);d.length>0&&k(d,i);}return s}catch(s){throw w({provider:m,model:t,input:a,error:s instanceof Error?s:new Error(String(s)),durationMs:Date.now()-o,streaming:false}),s}}}function Ee(e,t){return async function(r){let o=Date.now(),a=r;try{let s=await e(r),c=Q(s.stream,t,a,o);return {...s,stream:c}}catch(s){throw w({provider:m,model:t,input:a,error:s instanceof Error?s:new Error(String(s)),durationMs:Date.now()-o,streaming:true}),s}}}function Z(e){return typeof e=="string"?e:e.contents?e.contents:e}function ee(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function te(e){let t=[],n=e.candidates?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function ke(e){let t=[],n=e?.[0]?.content?.parts;return n&&n.forEach((r,o)=>{r.functionCall?.name&&t.push(`gemini-fc-${r.functionCall.name}-${o}`);}),t}function et(e,t){return t&&j(t),B().disabled?(l("Tracing disabled, returning unwrapped client"),e):J(e)?(A("gemini"),X(e)):(v("Client is not a Gemini model. Use @lelemondev/sdk/gemini only with Google Generative AI SDK."),e)}
|
|
3
|
+
export{q as captureSpan,le as flush,f as getTraceContext,ce as init,de as isEnabled,et as observe,be as span,he as trace};//# sourceMappingURL=gemini.mjs.map
|
|
4
4
|
//# sourceMappingURL=gemini.mjs.map
|