UNPKG

autotel

Version:
1,289 lines (1,280 loc) 44.3 kB
'use strict'; var chunk7EQ4G4SI_cjs = require('./chunk-7EQ4G4SI.cjs'); var chunkAC5GNZKB_cjs = require('./chunk-AC5GNZKB.cjs'); var chunkM3LFHHTN_cjs = require('./chunk-M3LFHHTN.cjs'); var chunk2ZKEORFN_cjs = require('./chunk-2ZKEORFN.cjs'); var chunkESMHTKLJ_cjs = require('./chunk-ESMHTKLJ.cjs'); var chunkT4B5LB6E_cjs = require('./chunk-T4B5LB6E.cjs'); var chunkZ6HRSM2Y_cjs = require('./chunk-Z6HRSM2Y.cjs'); var chunk4P6ZOARG_cjs = require('./chunk-4P6ZOARG.cjs'); var chunkINJD3G4K_cjs = require('./chunk-INJD3G4K.cjs'); var chunkTC5ZPWM4_cjs = require('./chunk-TC5ZPWM4.cjs'); require('./chunk-YTXEZ4SD.cjs'); var chunkWJH6IYU2_cjs = require('./chunk-WJH6IYU2.cjs'); var chunkVG2ABKJX_cjs = require('./chunk-VG2ABKJX.cjs'); var chunkFGNDN2FD_cjs = require('./chunk-FGNDN2FD.cjs'); var chunkOPPXYVEZ_cjs = require('./chunk-OPPXYVEZ.cjs'); var chunkGBFTC7Q7_cjs = require('./chunk-GBFTC7Q7.cjs'); require('./chunk-NZ72VDNY.cjs'); require('./chunk-UY3UYPBZ.cjs'); var chunkVQTCQKHQ_cjs = require('./chunk-VQTCQKHQ.cjs'); var chunkZ7PW3KHL_cjs = require('./chunk-Z7PW3KHL.cjs'); var chunkR7QYGZUP_cjs = require('./chunk-R7QYGZUP.cjs'); require('./chunk-QWW3E3JM.cjs'); require('./chunk-CEAQK2QY.cjs'); var chunkZNMBW67B_cjs = require('./chunk-ZNMBW67B.cjs'); var chunkIOYFAFHJ_cjs = require('./chunk-IOYFAFHJ.cjs'); var chunkNEIB3TLD_cjs = require('./chunk-NEIB3TLD.cjs'); require('./chunk-CU6IDACR.cjs'); var chunk6S5RUKU3_cjs = require('./chunk-6S5RUKU3.cjs'); require('./chunk-NVAI5CCN.cjs'); var chunkVH77IPJN_cjs = require('./chunk-VH77IPJN.cjs'); require('./chunk-FU6R566Y.cjs'); require('./chunk-ESLWRGAG.cjs'); var chunkYREV3LGG_cjs = require('./chunk-YREV3LGG.cjs'); var api = require('@opentelemetry/api'); var crypto$1 = require('crypto'); var async_hooks = require('async_hooks'); var sdkMetrics = require('@opentelemetry/sdk-metrics'); var otelMethods = { // Class methods on TraceAPI — bind to the singleton. setGlobalTracerProvider: api.trace.setGlobalTracerProvider.bind(api.trace), getTracerProvider: api.trace.getTracerProvider.bind(api.trace), getTracer: api.trace.getTracer.bind(api.trace), disable: api.trace.disable.bind(api.trace), // Instance fields on TraceAPI — already standalone, copy by reference. wrapSpanContext: api.trace.wrapSpanContext, isSpanContextValid: api.trace.isSpanContextValid, deleteSpan: api.trace.deleteSpan, getSpan: api.trace.getSpan, getActiveSpan: api.trace.getActiveSpan, getSpanContext: api.trace.getSpanContext, setSpan: api.trace.setSpan, setSpanContext: api.trace.setSpanContext }; var trace2 = Object.assign( chunkFGNDN2FD_cjs.trace, otelMethods ); function defineEvent(name, schema, options = {}) { const jsonSchema = options.toJsonSchema?.(schema); const schemaMetadata = jsonSchema ? { source: "zod", jsonSchema, hash: hashSchema(jsonSchema) } : void 0; return { name, schemaMetadata, track(payload) { const parsed = schema.safeParse(payload); if (!parsed.success) { throw new Error( `Invalid payload for event "${name}". Schema validation failed.` ); } chunkZ7PW3KHL_cjs.track( name, parsed.data, schemaMetadata ? { schema: schemaMetadata } : void 0 ); } }; } function hashSchema(schema) { return crypto$1.createHash("sha256").update(stableStringify(schema)).digest("hex"); } function stableStringify(value) { if (value === null || value === void 0 || typeof value !== "object") { return JSON.stringify(value); } if (Array.isArray(value)) { return "[" + value.map((v) => stableStringify(v)).join(",") + "]"; } const obj = value; const body = Object.keys(obj).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(","); return "{" + body + "}"; } // src/shutdown.ts async function flush(options) { const timeout = options?.timeout ?? 2e3; const forShutdown = options?.forShutdown ?? false; const doFlush = async () => { const eventsQueue = chunkZ7PW3KHL_cjs.getEventQueue(); if (eventsQueue) { if (forShutdown) { await eventsQueue.shutdown(); } else { await eventsQueue.flush(); } } const sdk = chunkR7QYGZUP_cjs.getSdk(); if (sdk) { try { const sdkAny = sdk; if (typeof sdkAny.getTracerProvider === "function") { const tracerProvider = sdkAny.getTracerProvider(); if (tracerProvider && typeof tracerProvider.forceFlush === "function") { await tracerProvider.forceFlush(); } } } catch { } } }; let timeoutHandle; try { await Promise.race([ doFlush().finally(() => { if (timeoutHandle) { clearTimeout(timeoutHandle); } }), new Promise((_, reject) => { timeoutHandle = setTimeout( () => reject(new Error("Flush timeout")), timeout ); timeoutHandle.unref(); }) ]); } catch (error) { if (timeoutHandle) { clearTimeout(timeoutHandle); } const logger = chunkR7QYGZUP_cjs.getLogger(); logger.error( { err: error instanceof Error ? error : new Error(String(error)) }, "[autotel] Flush error" ); throw error; } } async function shutdown() { const logger = chunkR7QYGZUP_cjs.getLogger(); let shutdownError = null; try { await flush({ forShutdown: true }); } catch (error) { const err = error instanceof Error ? error : new Error(String(error)); shutdownError = err; logger.error( { err }, "[autotel] Flush failed during shutdown, continuing cleanup" ); } try { const sdk = chunkR7QYGZUP_cjs.getSdk(); if (sdk) { await sdk.shutdown(); } } catch (error) { const err = error instanceof Error ? error : new Error(String(error)); const isConnectionRefused = typeof error === "object" && error !== null && "code" in error && error.code === "ECONNREFUSED"; if (!isConnectionRefused) { if (!shutdownError) { shutdownError = err; } logger.error({ err }, "[autotel] SDK shutdown failed"); } } finally { await chunkR7QYGZUP_cjs._closeEmbeddedDevtools(); const eventsQueue = chunkZ7PW3KHL_cjs.getEventQueue(); if (eventsQueue && typeof eventsQueue.cleanup === "function") { eventsQueue.cleanup(); } chunkGBFTC7Q7_cjs.resetEvents(); chunkTC5ZPWM4_cjs.resetMetrics(); chunkZ7PW3KHL_cjs.resetEventQueue(); } if (shutdownError) { throw shutdownError; } } function registerShutdownHooks() { if (typeof process === "undefined") return; const signals = ["SIGTERM", "SIGINT"]; let shuttingDown = false; for (const signal of signals) { process.on(signal, async () => { if (shuttingDown) return; shuttingDown = true; if (process.env.NODE_ENV !== "test") { chunkR7QYGZUP_cjs.getLogger().info( {}, `[autotel] Received ${signal}, flushing telemetry...` ); } try { await shutdown(); } catch (error) { chunkR7QYGZUP_cjs.getLogger().error( { err: error instanceof Error ? error : void 0 }, "[autotel] Error during shutdown" ); } finally { process.exit(0); } }); } } registerShutdownHooks(); var POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when available."; function warnPostEmit(method, detail) { console.warn( `[autotel] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}` ); } function mergeInto(target, source) { for (const key in source) { const sourceVal = source[key]; if (sourceVal === void 0) continue; const targetVal = target[key]; if (sourceVal !== null && typeof sourceVal === "object" && !Array.isArray(sourceVal) && targetVal !== null && typeof targetVal === "object" && !Array.isArray(targetVal)) { mergeInto( targetVal, sourceVal ); } else if (Array.isArray(targetVal) && Array.isArray(sourceVal)) { target[key] = [...targetVal, ...sourceVal]; } else { target[key] = sourceVal; } } } var requestContextStore = new async_hooks.AsyncLocalStorage(); function runWithRequestContext(ctx2, fn) { return requestContextStore.run(ctx2, fn); } function resolveContext(ctx2) { if (ctx2) return ctx2; const stored = requestContextStore.getStore(); if (stored) return stored; const span2 = api.trace.getActiveSpan(); if (!span2) { throw new Error( "[autotel] getRequestLogger() requires an active span or runWithRequestContext(). Wrap your handler with trace() or use runWithRequestContext()." ); } return chunkZ7PW3KHL_cjs.createTraceContext(span2); } function getRequestLogger(ctx2, options) { const activeContext = resolveContext(ctx2); let contextState = {}; let emitted = false; let lastSnapshot = null; const addLogEvent = (level, message, fields) => { const attrs2 = fields ? chunkZ7PW3KHL_cjs.flattenToAttributes(fields) : void 0; chunk4P6ZOARG_cjs.emitCorrelatedEvent(activeContext, `log.${level}`, { message, ...attrs2 ?? {} }); }; const sealCheck = (method, keys) => { if (emitted) { warnPostEmit( method, `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.` ); } }; return { set(fields) { sealCheck("log.set()", Object.keys(fields)); if (emitted) return; mergeInto(contextState, fields); activeContext.setAttributes(chunkZ7PW3KHL_cjs.flattenToAttributes(fields)); }, info(message, fields) { const keys = fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"]; sealCheck("log.info()", keys); if (emitted) return; addLogEvent("info", message, fields); if (fields) { mergeInto(contextState, fields); activeContext.setAttributes(chunkZ7PW3KHL_cjs.flattenToAttributes(fields)); } }, warn(message, fields) { const keys = fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"]; sealCheck("log.warn()", keys); if (emitted) return; addLogEvent("warn", message, fields); activeContext.setAttribute("autotel.log.level", "warn"); if (fields) { mergeInto(contextState, fields); activeContext.setAttributes(chunkZ7PW3KHL_cjs.flattenToAttributes(fields)); } }, error(error, fields) { const keys = fields ? [...Object.keys(fields), "error"] : ["error"]; sealCheck("log.error()", keys); if (emitted) return; const err = typeof error === "string" ? new Error(error) : error; chunkZ7PW3KHL_cjs.recordStructuredError(activeContext, err); addLogEvent("error", err.message, fields); if (fields) { mergeInto(contextState, fields); activeContext.setAttributes(chunkZ7PW3KHL_cjs.flattenToAttributes(fields)); } activeContext.setAttribute("autotel.log.level", "error"); }, getContext() { return { ...contextState }; }, emitNow(overrides) { if (emitted) { warnPostEmit("log.emitNow()", "Ignoring duplicate emit."); return lastSnapshot; } const mergedContext = { ...contextState, ...overrides ?? {} }; const flattened = chunkZ7PW3KHL_cjs.flattenToAttributes(mergedContext); activeContext.setAttributes(flattened); const snapshot = { timestamp: (/* @__PURE__ */ new Date()).toISOString(), traceId: activeContext.traceId, spanId: activeContext.spanId, correlationId: activeContext.correlationId, context: mergedContext }; chunk4P6ZOARG_cjs.emitCorrelatedEvent(activeContext, "log.emit.manual", { ...flattened }); if (options?.onEmit) { Promise.resolve(options.onEmit(snapshot)).catch((error) => { console.warn("[autotel] request logger onEmit failed:", error); }); } emitted = true; lastSnapshot = snapshot; return snapshot; }, fork(label, fn, forkOptions) { const parentRequestId = activeContext.correlationId; if (typeof parentRequestId !== "string" || parentRequestId.length === 0) { throw new Error( "[autotel] log.fork() requires the parent logger to have a correlationId. Ensure the request was created by autotel middleware." ); } const tracer = api.trace.getTracer("autotel.request-logger"); const lifecycle = forkOptions?.lifecycle; void tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => { const childContext = { ...chunkZ7PW3KHL_cjs.createTraceContext(childSpan), correlationId: crypto.randomUUID() }; requestContextStore.run(childContext, () => { const childLog = getRequestLogger(childContext); childLog.set({ operation: label, _parentCorrelationId: parentRequestId }); lifecycle?.onChildEnter?.(childLog); void Promise.resolve().then(() => fn()).then(() => { childLog.emitNow(); }).catch((err) => { const error = err instanceof Error ? err : new Error(String(err)); childLog.error(error); childLog.emitNow(); }).finally(() => { try { lifecycle?.onChildExit?.(childLog); } catch (hookError) { console.warn( "[autotel] fork onChildExit hook threw:", hookError ); } childSpan.end(); }); }); }); } }; } // src/error-catalog.ts var catalogCodeKey = /* @__PURE__ */ Symbol.for("autotel.catalog.code"); function readCatalogCode(error) { if (error === null || typeof error !== "object") return void 0; return error[catalogCodeKey]; } function isCatalogError(error) { return readCatalogCode(error) !== void 0; } function getCatalogCode(error) { return readCatalogCode(error); } function defineErrorCatalog(namespace, entries) { const catalog = {}; for (const [key, entry] of Object.entries(entries)) { const code = entry.code ?? `${namespace}.${key}`; const usesParams = typeof entry.message === "function" || typeof entry.why === "function"; const builder = ((paramsOrOptions, maybeOptions) => { const params = usesParams ? paramsOrOptions : void 0; const options = usesParams ? maybeOptions : paramsOrOptions; const message = typeof entry.message === "function" ? entry.message(params) : entry.message; const why = typeof entry.why === "function" ? entry.why(params) : entry.why; const error = chunkZ7PW3KHL_cjs.createStructuredError({ message, name: entry.name ?? key, code, ...entry.status === void 0 ? {} : { status: entry.status }, ...why === void 0 ? {} : { why }, ...entry.fix === void 0 ? {} : { fix: entry.fix }, ...entry.link === void 0 ? {} : { link: entry.link }, ...options?.cause === void 0 ? {} : { cause: options.cause }, ...options?.details === void 0 ? {} : { details: options.details }, ...options?.internal === void 0 ? {} : { internal: options.internal } }); Object.defineProperty(error, catalogCodeKey, { value: code, enumerable: false, writable: false, configurable: true }); return error; }); Object.defineProperty(builder, "code", { value: code, enumerable: true }); Object.defineProperty(builder, "match", { value: (error) => readCatalogCode(error) === code, enumerable: false }); catalog[key] = builder; } return Object.freeze(catalog); } function defineAuditCatalog(namespace, entries) { const catalog = {}; for (const [key, entry] of Object.entries(entries)) { const action = entry.action ?? `${namespace}.${key}`; const severity = entry.severity ?? "info"; const descriptor = ((params) => { const message = typeof entry.message === "function" ? entry.message(params) : entry.message; return Object.freeze({ action, severity, ...message === void 0 ? {} : { message } }); }); Object.defineProperty(descriptor, "action", { value: action, enumerable: true }); Object.defineProperty(descriptor, "severity", { value: severity, enumerable: true }); catalog[key] = descriptor; } return Object.freeze(catalog); } // src/drain-toolkit.ts var DEFAULT_TIMEOUT_MS = 5e3; var DEFAULT_RETRIES = 2; function delay(ms) { return new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.(); }); } async function postWithRetry(options) { const { name, request: request2, timeoutMs, retries } = options; const attempts = Math.max(1, retries); let lastError; for (let attempt = 1; attempt <= attempts; attempt++) { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), timeoutMs); timeout.unref?.(); try { const response = await fetch(request2.url, { method: "POST", headers: request2.headers, body: request2.body, signal: controller.signal }); if (!response.ok) { throw new Error( `[autotel/${name}] HTTP ${response.status} draining ${request2.url}` ); } return; } catch (error) { lastError = error; if (attempt < attempts) { await delay(100 * attempt); } } finally { clearTimeout(timeout); } } throw lastError; } function defineDrain(options) { return async (ctx2) => { const contexts = Array.isArray(ctx2) ? ctx2 : [ctx2]; if (contexts.length === 0) return; const config = await options.resolve(); if (!config) return; const payloads = options.transform ? options.transform(contexts) : contexts; if (payloads.length === 0) return; try { await options.send(payloads, config); } catch (error) { console.error(`[autotel/${options.name}] drain failed:`, error); } }; } function defineHttpDrain(options) { return defineDrain({ name: options.name, resolve: options.resolve, transform: options.transform, send: async (payloads, config) => { const request2 = options.encode(payloads, config); if (!request2) return; const timeoutMs = options.resolveTimeoutMs?.(config) ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS; const retries = options.resolveRetries?.(config) ?? options.retries ?? DEFAULT_RETRIES; await postWithRetry({ name: options.name, request: request2, timeoutMs, retries }); } }); } // src/enricher-toolkit.ts function isPlainObject(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function mergeInto2(target, source) { for (const key in source) { const sourceVal = source[key]; if (sourceVal === void 0) continue; const targetVal = target[key]; if (isPlainObject(sourceVal) && isPlainObject(targetVal)) { mergeInto2(targetVal, sourceVal); } else { target[key] = sourceVal; } } } function defineEnricher(def, options = {}) { return (ctx2) => { let computed; try { computed = def.compute(ctx2); } catch (error) { console.error(`[autotel/${def.name}] enrich failed:`, error); return; } if (!computed) return; if (options.overwrite || !isPlainObject(ctx2.event[def.field])) { ctx2.event[def.field] = computed; return; } mergeInto2( ctx2.event[def.field], computed ); }; } var GEN_AI_DURATION_BUCKETS_SECONDS = Object.freeze( [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 60, 120, 300] ); var GEN_AI_TOKEN_USAGE_BUCKETS = Object.freeze([ 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304 ]); var GEN_AI_COST_USD_BUCKETS = Object.freeze([ 1e-5, 1e-4, 1e-3, 5e-3, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50 ]); function llmHistogramAdvice(kind) { const boundaries = kind === "duration" ? GEN_AI_DURATION_BUCKETS_SECONDS : kind === "tokens" ? GEN_AI_TOKEN_USAGE_BUCKETS : GEN_AI_COST_USD_BUCKETS; return { advice: { explicitBucketBoundaries: [...boundaries] } }; } function genAiMetricViews(extra = []) { const defaults = [ { instrumentName: "gen_ai.client.operation.duration", kind: "duration" }, { instrumentName: "gen_ai.client.token.usage", kind: "tokens" }, // Autotel-emitted cost metric. No-op if you don't emit it. { instrumentName: "gen_ai.client.cost.usd", kind: "cost" } ]; return [...defaults, ...extra].map( ({ instrumentName, kind }) => ({ instrumentName, aggregation: { type: sdkMetrics.AggregationType.EXPLICIT_BUCKET_HISTOGRAM, options: { boundaries: kind === "duration" ? [...GEN_AI_DURATION_BUCKETS_SECONDS] : kind === "tokens" ? [...GEN_AI_TOKEN_USAGE_BUCKETS] : [...GEN_AI_COST_USD_BUCKETS] } } }) ); } // src/gen-ai-events.ts function recordPromptSent(ctx2, event = {}) { chunk4P6ZOARG_cjs.emitCorrelatedEvent(ctx2, "gen_ai.prompt.sent", buildPromptSentAttrs(event)); } function recordResponseReceived(ctx2, event = {}) { chunk4P6ZOARG_cjs.emitCorrelatedEvent( ctx2, "gen_ai.response.received", buildResponseAttrs(event) ); } function recordRetry(ctx2, event) { chunk4P6ZOARG_cjs.emitCorrelatedEvent(ctx2, "gen_ai.retry", buildRetryAttrs(event)); } function recordToolCall(ctx2, event) { chunk4P6ZOARG_cjs.emitCorrelatedEvent(ctx2, "gen_ai.tool.call", buildToolCallAttrs(event)); } function recordStreamFirstToken(ctx2, event = {}) { chunk4P6ZOARG_cjs.emitCorrelatedEvent( ctx2, "gen_ai.stream.first_token", buildStreamFirstTokenAttrs(event) ); } function buildPromptSentAttrs(event) { const attrs2 = {}; if (event.model) attrs2["gen_ai.request.model"] = event.model; if (event.promptTokens !== void 0) attrs2["gen_ai.usage.input_tokens"] = event.promptTokens; if (event.messageCount !== void 0) attrs2["gen_ai.request.message_count"] = event.messageCount; if (event.operation) attrs2["gen_ai.operation.name"] = event.operation; return attrs2; } function buildResponseAttrs(event) { const attrs2 = {}; if (event.model) attrs2["gen_ai.response.model"] = event.model; if (event.promptTokens !== void 0) attrs2["gen_ai.usage.input_tokens"] = event.promptTokens; if (event.completionTokens !== void 0) attrs2["gen_ai.usage.output_tokens"] = event.completionTokens; if (event.totalTokens !== void 0) attrs2["gen_ai.usage.total_tokens"] = event.totalTokens; if (event.finishReasons && event.finishReasons.length > 0) { attrs2["gen_ai.response.finish_reasons"] = event.finishReasons.join(","); } return attrs2; } function buildRetryAttrs(event) { const attrs2 = { "retry.attempt": event.attempt }; if (event.reason) attrs2["retry.reason"] = event.reason; if (event.delayMs !== void 0) attrs2["retry.delay_ms"] = event.delayMs; if (event.statusCode !== void 0) attrs2["http.response.status_code"] = event.statusCode; return attrs2; } function buildToolCallAttrs(event) { const attrs2 = { "gen_ai.tool.name": event.toolName }; if (event.toolCallId) attrs2["gen_ai.tool.call.id"] = event.toolCallId; if (event.arguments) attrs2["gen_ai.tool.arguments"] = event.arguments; return attrs2; } function buildStreamFirstTokenAttrs(event) { const attrs2 = {}; if (event.tokensSoFar !== void 0) attrs2["gen_ai.stream.tokens_so_far"] = event.tokensSoFar; return attrs2; } // src/gen-ai-cost.ts var GEN_AI_COST_ATTRIBUTE = "gen_ai.usage.cost.usd"; var MODEL_PRICING = { // OpenAI "gpt-4o": { inputPer1M: 2.5, outputPer1M: 10 }, "gpt-4o-mini": { inputPer1M: 0.15, outputPer1M: 0.6 }, "gpt-4.1": { inputPer1M: 2, outputPer1M: 8 }, "gpt-4.1-mini": { inputPer1M: 0.4, outputPer1M: 1.6 }, "gpt-4.1-nano": { inputPer1M: 0.1, outputPer1M: 0.4 }, "o3-mini": { inputPer1M: 1.1, outputPer1M: 4.4 }, // Anthropic Claude "claude-opus-4": { inputPer1M: 15, outputPer1M: 75 }, "claude-sonnet-4": { inputPer1M: 3, outputPer1M: 15 }, "claude-3-5-sonnet": { inputPer1M: 3, outputPer1M: 15 }, "claude-3-5-haiku": { inputPer1M: 0.8, outputPer1M: 4 }, "claude-3-opus": { inputPer1M: 15, outputPer1M: 75 }, "claude-3-haiku": { inputPer1M: 0.25, outputPer1M: 1.25 }, // Google Gemini "gemini-1.5-pro": { inputPer1M: 1.25, outputPer1M: 5 }, "gemini-1.5-flash": { inputPer1M: 0.075, outputPer1M: 0.3 }, "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4 } }; function resolvePricing(table, model) { const exact = table[model]; if (exact) return exact; let best; let bestLength = 0; for (const key of Object.keys(table)) { if (model.startsWith(key) && key.length > bestLength) { best = table[key]; bestLength = key.length; } } return best; } function round(value) { return Math.round(value * 1e6) / 1e6; } function estimateLLMCost(model, usage, options) { const table = options?.pricing ? { ...MODEL_PRICING, ...options.pricing } : MODEL_PRICING; const price = resolvePricing(table, model); if (!price) return void 0; const cachedInput = usage.cachedInputTokens ?? 0; const billedInput = Math.max(0, (usage.inputTokens ?? 0) - cachedInput); const output = usage.outputTokens ?? 0; const cachedRate = price.cachedInputPer1M ?? price.inputPer1M; const cost = billedInput / 1e6 * price.inputPer1M + cachedInput / 1e6 * cachedRate + output / 1e6 * price.outputPer1M; return round(cost); } function recordLLMCost(ctx2, model, usage, options) { const cost = estimateLLMCost(model, usage, options); if (cost !== void 0) { ctx2.setAttribute(GEN_AI_COST_ATTRIBUTE, cost); } return cost; } Object.defineProperty(exports, "createDrainPipeline", { enumerable: true, get: function () { return chunk7EQ4G4SI_cjs.createDrainPipeline; } }); Object.defineProperty(exports, "getCurrentWorkflowContext", { enumerable: true, get: function () { return chunkAC5GNZKB_cjs.getCurrentWorkflowContext; } }); Object.defineProperty(exports, "isInWorkflow", { enumerable: true, get: function () { return chunkAC5GNZKB_cjs.isInWorkflow; } }); Object.defineProperty(exports, "traceStep", { enumerable: true, get: function () { return chunkAC5GNZKB_cjs.traceStep; } }); Object.defineProperty(exports, "traceWorkflow", { enumerable: true, get: function () { return chunkAC5GNZKB_cjs.traceWorkflow; } }); Object.defineProperty(exports, "attrs", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.attrs; } }); Object.defineProperty(exports, "autoRedactPII", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.autoRedactPII; } }); Object.defineProperty(exports, "dbClient", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.dbClient; } }); Object.defineProperty(exports, "httpClient", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.httpClient; } }); Object.defineProperty(exports, "httpServer", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.httpServer; } }); Object.defineProperty(exports, "identify", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.identify; } }); Object.defineProperty(exports, "mergeAttrs", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.mergeAttrs; } }); Object.defineProperty(exports, "mergeServiceResource", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.mergeServiceResource; } }); Object.defineProperty(exports, "request", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.request; } }); Object.defineProperty(exports, "safeSetAttributes", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.safeSetAttributes; } }); Object.defineProperty(exports, "setDevice", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.setDevice; } }); Object.defineProperty(exports, "setError", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.setError; } }); Object.defineProperty(exports, "setException", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.setException; } }); Object.defineProperty(exports, "setSession", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.setSession; } }); Object.defineProperty(exports, "setUser", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.setUser; } }); Object.defineProperty(exports, "validateAttribute", { enumerable: true, get: function () { return chunkM3LFHHTN_cjs.validateAttribute; } }); Object.defineProperty(exports, "httpRequestHeaderAttribute", { enumerable: true, get: function () { return chunk2ZKEORFN_cjs.httpRequestHeaderAttribute; } }); Object.defineProperty(exports, "httpResponseHeaderAttribute", { enumerable: true, get: function () { return chunk2ZKEORFN_cjs.httpResponseHeaderAttribute; } }); Object.defineProperty(exports, "HTTPAttributes", { enumerable: true, get: function () { return chunkESMHTKLJ_cjs.HTTPAttributes; } }); Object.defineProperty(exports, "ServiceAttributes", { enumerable: true, get: function () { return chunkESMHTKLJ_cjs.ServiceAttributes; } }); Object.defineProperty(exports, "URLAttributes", { enumerable: true, get: function () { return chunkESMHTKLJ_cjs.URLAttributes; } }); Object.defineProperty(exports, "parseError", { enumerable: true, get: function () { return chunkT4B5LB6E_cjs.parseError; } }); Object.defineProperty(exports, "traceConsumer", { enumerable: true, get: function () { return chunkZ6HRSM2Y_cjs.traceConsumer; } }); Object.defineProperty(exports, "traceProducer", { enumerable: true, get: function () { return chunkZ6HRSM2Y_cjs.traceProducer; } }); Object.defineProperty(exports, "BusinessBaggage", { enumerable: true, get: function () { return chunkINJD3G4K_cjs.BusinessBaggage; } }); Object.defineProperty(exports, "createSafeBaggageSchema", { enumerable: true, get: function () { return chunkINJD3G4K_cjs.createSafeBaggageSchema; } }); Object.defineProperty(exports, "Metric", { enumerable: true, get: function () { return chunkTC5ZPWM4_cjs.Metric; } }); Object.defineProperty(exports, "getMetrics", { enumerable: true, get: function () { return chunkTC5ZPWM4_cjs.getMetrics; } }); Object.defineProperty(exports, "resetMetrics", { enumerable: true, get: function () { return chunkTC5ZPWM4_cjs.resetMetrics; } }); Object.defineProperty(exports, "createCounter", { enumerable: true, get: function () { return chunkWJH6IYU2_cjs.createCounter; } }); Object.defineProperty(exports, "createHistogram", { enumerable: true, get: function () { return chunkWJH6IYU2_cjs.createHistogram; } }); Object.defineProperty(exports, "createObservableGauge", { enumerable: true, get: function () { return chunkWJH6IYU2_cjs.createObservableGauge; } }); Object.defineProperty(exports, "createUpDownCounter", { enumerable: true, get: function () { return chunkWJH6IYU2_cjs.createUpDownCounter; } }); Object.defineProperty(exports, "getMeter", { enumerable: true, get: function () { return chunkWJH6IYU2_cjs.getMeter; } }); Object.defineProperty(exports, "traceDB", { enumerable: true, get: function () { return chunkVG2ABKJX_cjs.traceDB; } }); Object.defineProperty(exports, "traceHTTP", { enumerable: true, get: function () { return chunkVG2ABKJX_cjs.traceHTTP; } }); Object.defineProperty(exports, "traceLLM", { enumerable: true, get: function () { return chunkVG2ABKJX_cjs.traceLLM; } }); Object.defineProperty(exports, "traceMessaging", { enumerable: true, get: function () { return chunkVG2ABKJX_cjs.traceMessaging; } }); Object.defineProperty(exports, "ctx", { enumerable: true, get: function () { return chunkFGNDN2FD_cjs.ctx; } }); Object.defineProperty(exports, "instrument", { enumerable: true, get: function () { return chunkFGNDN2FD_cjs.instrument; } }); Object.defineProperty(exports, "markAsImmediate", { enumerable: true, get: function () { return chunkFGNDN2FD_cjs.markAsImmediate; } }); Object.defineProperty(exports, "span", { enumerable: true, get: function () { return chunkFGNDN2FD_cjs.span; } }); Object.defineProperty(exports, "withBaggage", { enumerable: true, get: function () { return chunkFGNDN2FD_cjs.withBaggage; } }); Object.defineProperty(exports, "withNewContext", { enumerable: true, get: function () { return chunkFGNDN2FD_cjs.withNewContext; } }); Object.defineProperty(exports, "withTracing", { enumerable: true, get: function () { return chunkFGNDN2FD_cjs.withTracing; } }); Object.defineProperty(exports, "createDeterministicTraceId", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.createDeterministicTraceId; } }); Object.defineProperty(exports, "enrichWithTraceContext", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.enrichWithTraceContext; } }); Object.defineProperty(exports, "finalizeSpan", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.finalizeSpan; } }); Object.defineProperty(exports, "flattenMetadata", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.flattenMetadata; } }); Object.defineProperty(exports, "getActiveContext", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.getActiveContext; } }); Object.defineProperty(exports, "getActiveSpan", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.getActiveSpan; } }); Object.defineProperty(exports, "getTraceContext", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.getTraceContext; } }); Object.defineProperty(exports, "getTracer", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.getTracer; } }); Object.defineProperty(exports, "isTracing", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.isTracing; } }); Object.defineProperty(exports, "resolveTraceUrl", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.resolveTraceUrl; } }); Object.defineProperty(exports, "runWithSpan", { enumerable: true, get: function () { return chunkOPPXYVEZ_cjs.runWithSpan; } }); Object.defineProperty(exports, "Event", { enumerable: true, get: function () { return chunkGBFTC7Q7_cjs.Event; } }); Object.defineProperty(exports, "getEvents", { enumerable: true, get: function () { return chunkGBFTC7Q7_cjs.getEvents; } }); Object.defineProperty(exports, "resetEvents", { enumerable: true, get: function () { return chunkGBFTC7Q7_cjs.resetEvents; } }); Object.defineProperty(exports, "getOperationContext", { enumerable: true, get: function () { return chunkVQTCQKHQ_cjs.getOperationContext; } }); Object.defineProperty(exports, "runInOperationContext", { enumerable: true, get: function () { return chunkVQTCQKHQ_cjs.runInOperationContext; } }); Object.defineProperty(exports, "CORRELATION_ID_BAGGAGE_KEY", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.CORRELATION_ID_BAGGAGE_KEY; } }); Object.defineProperty(exports, "createStructuredError", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.createStructuredError; } }); Object.defineProperty(exports, "defineBaggageSchema", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.defineBaggageSchema; } }); Object.defineProperty(exports, "flattenToAttributes", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.flattenToAttributes; } }); Object.defineProperty(exports, "generateCorrelationId", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.generateCorrelationId; } }); Object.defineProperty(exports, "getCorrelationId", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.getCorrelationId; } }); Object.defineProperty(exports, "getEventQueue", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.getEventQueue; } }); Object.defineProperty(exports, "getOrCreateCorrelationId", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.getOrCreateCorrelationId; } }); Object.defineProperty(exports, "getStructuredErrorAttributes", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.getStructuredErrorAttributes; } }); Object.defineProperty(exports, "recordStructuredError", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.recordStructuredError; } }); Object.defineProperty(exports, "runWithCorrelationId", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.runWithCorrelationId; } }); Object.defineProperty(exports, "setCorrelationId", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.setCorrelationId; } }); Object.defineProperty(exports, "setCorrelationIdInBaggage", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.setCorrelationIdInBaggage; } }); Object.defineProperty(exports, "structuredErrorToJSON", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.structuredErrorToJSON; } }); Object.defineProperty(exports, "toAttributeValue", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.toAttributeValue; } }); Object.defineProperty(exports, "track", { enumerable: true, get: function () { return chunkZ7PW3KHL_cjs.track; } }); Object.defineProperty(exports, "BaggageSpanProcessor", { enumerable: true, get: function () { return chunkR7QYGZUP_cjs.BaggageSpanProcessor; } }); Object.defineProperty(exports, "createStringRedactor", { enumerable: true, get: function () { return chunkR7QYGZUP_cjs.createStringRedactor; } }); Object.defineProperty(exports, "init", { enumerable: true, get: function () { return chunkR7QYGZUP_cjs.init; } }); Object.defineProperty(exports, "isInitialized", { enumerable: true, get: function () { return chunkR7QYGZUP_cjs.isInitialized; } }); Object.defineProperty(exports, "isLoggerLocked", { enumerable: true, get: function () { return chunkR7QYGZUP_cjs.isLoggerLocked; } }); Object.defineProperty(exports, "lockLogger", { enumerable: true, get: function () { return chunkR7QYGZUP_cjs.lockLogger; } }); Object.defineProperty(exports, "FilteringSpanProcessor", { enumerable: true, get: function () { return chunkZNMBW67B_cjs.FilteringSpanProcessor; } }); Object.defineProperty(exports, "NORMALIZER_PATTERNS", { enumerable: true, get: function () { return chunkIOYFAFHJ_cjs.NORMALIZER_PATTERNS; } }); Object.defineProperty(exports, "NORMALIZER_PRESETS", { enumerable: true, get: function () { return chunkIOYFAFHJ_cjs.NORMALIZER_PRESETS; } }); Object.defineProperty(exports, "SpanNameNormalizingProcessor", { enumerable: true, get: function () { return chunkIOYFAFHJ_cjs.SpanNameNormalizingProcessor; } }); Object.defineProperty(exports, "AttributeRedactingProcessor", { enumerable: true, get: function () { return chunkNEIB3TLD_cjs.AttributeRedactingProcessor; } }); Object.defineProperty(exports, "REDACTOR_PATTERNS", { enumerable: true, get: function () { return chunkNEIB3TLD_cjs.REDACTOR_PATTERNS; } }); Object.defineProperty(exports, "REDACTOR_PRESETS", { enumerable: true, get: function () { return chunkNEIB3TLD_cjs.REDACTOR_PRESETS; } }); Object.defineProperty(exports, "builtinPatterns", { enumerable: true, get: function () { return chunkNEIB3TLD_cjs.builtinPatterns; } }); Object.defineProperty(exports, "createAttributeRedactor", { enumerable: true, get: function () { return chunkNEIB3TLD_cjs.createAttributeRedactor; } }); Object.defineProperty(exports, "createRedactedSpan", { enumerable: true, get: function () { return chunkNEIB3TLD_cjs.createRedactedSpan; } }); Object.defineProperty(exports, "normalizeAttributeRedactorConfig", { enumerable: true, get: function () { return chunkNEIB3TLD_cjs.normalizeAttributeRedactorConfig; } }); Object.defineProperty(exports, "formatDuration", { enumerable: true, get: function () { return chunk6S5RUKU3_cjs.formatDuration; } }); Object.defineProperty(exports, "AUTOTEL_SAMPLING_TAIL_EVALUATED", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.AUTOTEL_SAMPLING_TAIL_EVALUATED; } }); Object.defineProperty(exports, "AUTOTEL_SAMPLING_TAIL_KEEP", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.AUTOTEL_SAMPLING_TAIL_KEEP; } }); Object.defineProperty(exports, "AdaptiveSampler", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.AdaptiveSampler; } }); Object.defineProperty(exports, "AlwaysSampler", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.AlwaysSampler; } }); Object.defineProperty(exports, "NeverSampler", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.NeverSampler; } }); Object.defineProperty(exports, "RandomSampler", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.RandomSampler; } }); Object.defineProperty(exports, "UserIdSampler", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.UserIdSampler; } }); Object.defineProperty(exports, "createLinkFromHeaders", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.createLinkFromHeaders; } }); Object.defineProperty(exports, "extractLinksFromBatch", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.extractLinksFromBatch; } }); Object.defineProperty(exports, "resolveSamplingPreset", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.resolveSamplingPreset; } }); Object.defineProperty(exports, "samplingPresets", { enumerable: true, get: function () { return chunkVH77IPJN_cjs.samplingPresets; } }); Object.defineProperty(exports, "getAutotelTracer", { enumerable: true, get: function () { return chunkYREV3LGG_cjs.getAutotelTracer; } }); Object.defineProperty(exports, "getAutotelTracerProvider", { enumerable: true, get: function () { return chunkYREV3LGG_cjs.getAutotelTracerProvider; } }); Object.defineProperty(exports, "setAutotelTracerProvider", { enumerable: true, get: function () { return chunkYREV3LGG_cjs.setAutotelTracerProvider; } }); Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function () { return api.ROOT_CONTEXT; } }); Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return api.SpanKind; } }); Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return api.SpanStatusCode; } }); Object.defineProperty(exports, "context", { enumerable: true, get: function () { return api.context; } }); Object.defineProperty(exports, "otelTrace", { enumerable: true, get: function () { return api.trace; } }); Object.defineProperty(exports, "propagation", { enumerable: true, get: function () { return api.propagation; } }); exports.GEN_AI_COST_ATTRIBUTE = GEN_AI_COST_ATTRIBUTE; exports.GEN_AI_COST_USD_BUCKETS = GEN_AI_COST_USD_BUCKETS; exports.GEN_AI_DURATION_BUCKETS_SECONDS = GEN_AI_DURATION_BUCKETS_SECONDS; exports.GEN_AI_TOKEN_USAGE_BUCKETS = GEN_AI_TOKEN_USAGE_BUCKETS; exports.MODEL_PRICING = MODEL_PRICING; exports.defineAuditCatalog = defineAuditCatalog; exports.defineDrain = defineDrain; exports.defineEnricher = defineEnricher; exports.defineErrorCatalog = defineErrorCatalog; exports.defineEvent = defineEvent; exports.defineHttpDrain = defineHttpDrain; exports.estimateLLMCost = estimateLLMCost; exports.flush = flush; exports.genAiMetricViews = genAiMetricViews; exports.getCatalogCode = getCatalogCode; exports.getRequestLogger = getRequestLogger; exports.isCatalogError = isCatalogError; exports.llmHistogramAdvice = llmHistogramAdvice; exports.recordLLMCost = recordLLMCost; exports.recordPromptSent = recordPromptSent; exports.recordResponseReceived = recordResponseReceived; exports.recordRetry = recordRetry; exports.recordStreamFirstToken = recordStreamFirstToken; exports.recordToolCall = recordToolCall; exports.runWithRequestContext = runWithRequestContext; exports.shutdown = shutdown; exports.trace = trace2; //# sourceMappingURL=index.cjs.map //# sourceMappingURL=index.cjs.map