@lelemondev/sdk 0.9.9 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  'use strict';var async_hooks=require('async_hooks');/* @lelemondev/sdk - LLM Observability */
2
- var Le=Object.defineProperty;var Ke=(e,n,t)=>n in e?Le(e,n,{enumerable:true,configurable:true,writable:true,value:t}):e[n]=t;var Z=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Je=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var A=(e,n,t)=>Ke(e,typeof n!="symbol"?n+"":n,t);var ae=Je((kt,We)=>{We.exports={name:"@lelemondev/sdk",version:"0.9.9",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/generative-ai":"^0.24.1","@types/node":"^20.0.0","@vitest/coverage-v8":"^2.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.15",typescript:"^5.9.3",vitest:"^2.0.0"}};});var Q=false;function ee(e){Q=e;}function I(){return Q?true:Fe("LELEMON_DEBUG")==="true"}var b="[Lelemon]";function w(e,n){I()&&J("debug",e,n);}function L(e,n){I()&&J("info",e,n);}function G(e,n){J("warn",e,n);}function K(e,n,t,r){I()&&console.log(`${b} Captured trace: provider=${e} model=${n} duration=${t}ms status=${r}`);}function B(e,n){console.error(`${b} Failed to capture trace: provider=${e} error=${n.message}`);}function _(e){I()&&console.log(`${b} Wrapped client: provider=${e}`);}function ne(e,n){I()&&console.log(`${b} Sending batch: count=${e} endpoint=${n}`);}function te(e,n){I()&&console.log(`${b} Batch sent successfully: count=${e} duration=${n}ms`);}function re(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${b} Batch send failed: count=${e} error=${t}`);}function oe(e,n,t){I()&&console.log(`${b} Request: ${e} ${n} (${t} bytes)`);}function se(e,n){I()&&console.log(`${b} Response: status=${e} duration=${n}ms`);}function J(e,n,t){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?r(`${b} ${n}`,t):r(`${b} ${n}`);}function Fe(e){if(typeof process<"u"&&process.env)return process.env[e]}var ze=10,Ve=1e3,He=1e4,j=class{constructor(n){A(this,"config");A(this,"queue",[]);A(this,"flushPromise",null);A(this,"flushTimer",null);this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??ze,flushIntervalMs:n.flushIntervalMs??Ve,requestTimeoutMs:n.requestTimeoutMs??He};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),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 n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).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(n){if(n.length===0)return;let t=Date.now();ne(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),te(n.length,Date.now()-t);}catch(r){re(n.length,r);}}async request(n,t,r){let o=`${this.config.endpoint}${t}`,s=new AbortController,a=r?JSON.stringify(r):void 0;oe(n,o,a?.length??0);let u=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),c=Date.now();try{let i=await fetch(o,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:s.signal});if(clearTimeout(u),se(i.status,Date.now()-c),!i.ok){let l=await i.text().catch(()=>"Unknown error");throw new Error(`HTTP ${i.status}: ${l}`)}let d=await i.text();return d?JSON.parse(d):{}}catch(i){throw clearTimeout(u),i instanceof Error&&i.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):i}}};var Ye="@lelemondev/sdk",Xe="nodejs";function Ze(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function Qe(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function en(){try{if(typeof Z<"u")return ae().version??"unknown"}catch{}return "unknown"}var E=null;function ue(e){if(!E){let t=Ze(),r=Qe();E={"telemetry.sdk.name":Ye,"telemetry.sdk.version":en(),"telemetry.sdk.language":Xe},t&&(E["process.runtime.name"]=t.name,E["process.runtime.version"]=t.version),r&&(E["os.type"]=r);}let n={...E};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var z={},T=null,F=null,ce="https://api.lelemon.dev";function tn(e={}){z=e,e.debug&&ee(true),F=ue(e.service),L("Initializing SDK",{endpoint:e.endpoint??ce,debug:e.debug??false,disabled:e.disabled??false,telemetry:F}),T=le(e),T.isEnabled()?L("SDK initialized - tracing enabled"):w("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function U(){return z}function N(){return F}function rn(){return R().isEnabled()}function R(){return T||(T=le(z)),T}async function on(){T&&await T.flush();}function le(e){let n=e.apiKey??sn("LELEMON_API_KEY");return !n&&!e.disabled&&G("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new j({apiKey:n??"",endpoint:e.endpoint??ce,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function sn(e){if(typeof process<"u"&&process.env)return process.env[e]}var V=Symbol.for("@lelemondev/sdk:globalContext");function fe(){let e=globalThis;return e[V]||(e[V]={context:{}}),e[V]}function me(e){fe().context=e,w("Global context updated",e);}function D(){return fe().context}function m(e){try{let n=R();if(!n.isEnabled()){w("Transport disabled, skipping trace capture");return}let t=D(),r=C(),o=M(),s=N(),a={provider:e.provider,model:e.model,input:W(e.input),rawResponse:e.rawResponse?P(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:t.tags,spanType:e.spanType,name:e.name};return K(e.provider,e.model,e.durationMs,e.status),n.enqueue(a),o}catch(n){B(e.provider,n instanceof Error?n:new Error(String(n)));return}}function f(e){try{let n=R();if(!n.isEnabled()){w("Transport disabled, skipping error capture");return}let t=D(),r=C(),o=N(),s={provider:e.provider,model:e.model,input:W(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:M(),parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:t.tags};K(e.provider,e.model,e.durationMs,"error"),w("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(s);}catch(n){B(e.provider,n instanceof Error?n:new Error(String(n)));}}function H(e){try{let n=R();if(!n.isEnabled()){w("Transport disabled, skipping span capture");return}let t=D(),r=C(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,a=N(),u={...t.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete u._traceId,delete u._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:W(e.input),output:P(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:o??r?.traceId,spanId:M(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:u,tags:t.tags};w(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(c);}catch(n){B("unknown",n instanceof Error?n:new Error(String(n)));}}var de=1e5,an=["api_key","apikey","password","secret","authorization"],un=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],cn=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],pe={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function ge(){return U().redaction??{}}function ln(e){let n=e.toLowerCase();return cn.includes(n)?false:!!(an.some(r=>n.includes(r))||un.some(r=>n.includes(r))||(ge().keys??[]).some(r=>n.includes(r.toLowerCase())))}function dn(e){let n=ge(),t=e;for(let r of n.patterns??[])r.lastIndex=0,t=t.replace(r,"[REDACTED]");return n.emails&&(t=t.replace(pe.emails,"[EMAIL]")),n.phones&&(t=t.replace(pe.phones,"[PHONE]")),t}function W(e){return P(e,0)}function P(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=dn(e);return t.length>de&&(t=t.slice(0,de)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>P(t,n+1));if(typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))ln(r)?t[r]="[REDACTED]":t[r]=P(o,n+1);return t}return String(e)}var Y=Symbol.for("@lelemondev/sdk:traceStorage");function fn(){let e=globalThis;return e[Y]||(e[Y]=new async_hooks.AsyncLocalStorage),e[Y]}var we=fn();function M(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function C(){return we.getStore()}function k(e,n){let t=C();if(t)for(let r of e)t.pendingToolCalls.set(r,n),w(`Registered tool call ${r} \u2192 LLM span ${n}`);}function mn(e){let n=C();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function gn(e){let n=C();n&&n.pendingToolCalls.delete(e);}async function wn(e,n){let t=typeof e=="string"?{name:e}:e,r=C(),o=r?.traceId??M(),s=M(),a={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,pendingToolCalls:new Map};return we.run(a,async()=>{let u,c;try{return u=await n(),u}catch(i){throw c=i instanceof Error?i:new Error(String(i)),i}finally{hn(a,c?void 0:u,c);}})}var kn=["text","content","message","output","response","result","answer"];function yn(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let o=e;return n in o?o[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let o of kn)if(o in r&&typeof r[o]=="string")return r[o];return e}function hn(e,n,t){let r=R();if(!r.isEnabled()){w("Transport disabled, skipping root span");return}let o=D(),s=Date.now()-e.startTime,a=t?null:yn(n,e.outputKey,e.outputTransform),u={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:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId??o.sessionId,userId:e.userId??o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};w(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),r.enqueue(u);}function bn(e){let n=C();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=mn(e.toolCallId);H({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:n.traceId,_parentSpanId:t}}),e.toolCallId&&gn(e.toolCallId);}var h="openai";function ke(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function ye(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&he(a))return Cn(a,o,r);let u=Date.now()-r,c=a,i=m({provider:h,model:o.model||c.model||"unknown",input:o.messages,rawResponse:a,durationMs:u,status:"success",streaming:!1});if(i){let d=Ie(c);d.length>0&&k(d,i);}return a}catch(a){let u=Date.now()-r;throw f({provider:h,model:o.model||"unknown",input:o.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}function he(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Cn(e,n,t){let r={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,s,a=false,u=new Map;try{for await(let c of e){let i=c,d=i?.choices?.[0]?.delta?.content;d&&(a||(a=!0,s=Date.now()-t),r.choices[0].message.content+=d);let l=i?.choices?.[0]?.delta?.tool_calls;if(l)for(let g of l){u.has(g.index)||u.set(g.index,{id:"",function:{name:"",arguments:""}});let $=u.get(g.index);g.id&&($.id=g.id),g.function?.name&&($.function.name=g.function.name),g.function?.arguments&&($.function.arguments+=g.function.arguments);}let p=i?.choices?.[0]?.finish_reason;p&&(r.choices[0].finish_reason=p),i?.usage&&(r.usage=i.usage),yield c;}}catch(c){throw o=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-t;if(u.size>0&&(r.choices[0].message.tool_calls=Array.from(u.entries()).sort((i,d)=>i[0]-d[0]).map(([,i])=>i)),o)f({provider:h,model:n.model||"unknown",input:n.messages,error:o,durationMs:c,streaming:true});else {let i=m({provider:h,model:n.model||"unknown",input:n.messages,rawResponse:r,durationMs:c,status:"success",streaming:true,firstTokenMs:s});if(i){let d=Ie(r);d.length>0&&k(d,i);}}}}function be(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&he(a))return vn(a,o,r);let u=Date.now()-r;return m({provider:h,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},rawResponse:a,durationMs:u,status:"success",streaming:!1}),a}catch(a){let u=Date.now()-r;throw f({provider:h,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}async function*vn(e,n,t){let r=[],o=null,s=null;try{for await(let a of e){r.push(a);let u=a;u.type==="response.done"&&u.response&&(o=u.response),yield a;}}catch(a){throw s=a instanceof Error?a:new Error(String(a)),a}finally{let a=Date.now()-t;s?f({provider:h,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:s,durationMs:a,streaming:true}):m({provider:h,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:o||{streamEvents:r},durationMs:a,status:"success",streaming:true});}}function Ce(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),a=Date.now()-r;return m({provider:h,model:o.model||"unknown",input:o.prompt,rawResponse:s,durationMs:a,status:"success",streaming:!1}),s}catch(s){let a=Date.now()-r;throw f({provider:h,model:o.model||"unknown",input:o.prompt,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function ve(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),a=Date.now()-r;return m({provider:h,model:o.model||"unknown",input:o.input,rawResponse:s,durationMs:a,status:"success",streaming:!1,spanType:"embedding"}),s}catch(s){let a=Date.now()-r;throw f({provider:h,model:o.model||"unknown",input:o.input,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function Ie(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let r of t)r.id&&n.push(r.id);return n}var x="anthropic";function Se(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="Anthropic")return true;let t=e;return !!(t.messages&&typeof t.messages=="object")}function Te(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&Sn(a))return Rn(a,o,r);let u=Date.now()-r,c=a,i=m({provider:x,model:o.model||c.model||"unknown",input:{system:o.system,messages:o.messages},rawResponse:a,durationMs:u,status:"success",streaming:!1});if(i&&c.content){let d=X(c.content);d.length>0&&k(d,i);}return a}catch(a){let u=Date.now()-r;throw f({provider:x,model:o.model||"unknown",input:{system:o.system,messages:o.messages},error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}function Re(e){return function(...t){let r=Date.now(),o=t[0]||{};try{let s=e(...t);return s&&typeof s=="object"?Tn(s,o,r):s}catch(s){let a=Date.now()-r;throw f({provider:x,model:o.model||"unknown",input:{system:o.system,messages:o.messages},error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:true}),s}}}function Sn(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}function Tn(e,n,t){let r=e;if(!r[Symbol.asyncIterator])return e;let o={content:[],usage:{input_tokens:0,output_tokens:0}},s=false,a,u=false,c=null,i=[],d=async function*(){try{for await(let l of r){if(l.type==="message_start"&&l.message&&(o.model=l.message.model,o.id=l.message.id,o.role=l.message.role,l.message.usage&&(o.usage={...l.message.usage})),l.type==="content_block_start"&&l.content_block&&(c=l.index??i.length,i[c]={...l.content_block},l.content_block.type==="text"&&(i[c].text=""),l.content_block.type==="thinking"&&(i[c].thinking="")),l.type==="content_block_delta"&&l.delta&&c!==null){let p=i[c];p&&(l.delta.text&&(u||(u=!0,a=Date.now()-t),p.type==="thinking"?p.thinking=(p.thinking||"")+l.delta.text:p.type==="text"&&(p.text=(p.text||"")+l.delta.text)),l.delta.partial_json&&p.type==="tool_use"&&(p._inputJson=(p._inputJson||"")+l.delta.partial_json));}if(l.type==="content_block_stop"&&c!==null){let p=i[c];if(p&&p.type==="tool_use"){let g=p._inputJson;if(g){try{p.input=JSON.parse(g);}catch{}delete p._inputJson;}}c=null;}l.type==="message_delta"&&(l.usage?.output_tokens&&(o.usage.output_tokens=l.usage.output_tokens),l.delta?.stop_reason&&(o.stop_reason=l.delta.stop_reason)),yield l;}}catch(l){if(!s){s=true;let p=Date.now()-t;f({provider:x,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:l instanceof Error?l:new Error(String(l)),durationMs:p,streaming:true});}throw l}finally{if(!s){s=true;let l=Date.now()-t;o.content=i.filter(Boolean);let p=m({provider:x,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:o,durationMs:l,status:"success",streaming:true,firstTokenMs:a});if(p&&o.content){let g=X(o.content);g.length>0&&k(g,p);}}}};return new Proxy(e,{get(l,p,g){return p===Symbol.asyncIterator?()=>d()[Symbol.asyncIterator]():Reflect.get(l,p,g)}})}async function*Rn(e,n,t){let r={content:[],usage:{input_tokens:0,output_tokens:0}},o=null,s,a=false,u=null,c=[];try{for await(let i of e){if(i.type==="message_start"&&i.message&&(r.model=i.message.model,r.id=i.message.id,r.role=i.message.role,i.message.usage&&(r.usage={...i.message.usage})),i.type==="content_block_start"&&i.content_block&&(u=i.index??c.length,c[u]={...i.content_block},i.content_block.type==="text"&&(c[u].text=""),i.content_block.type==="thinking"&&(c[u].thinking="")),i.type==="content_block_delta"&&i.delta&&u!==null){let d=c[u];d&&(i.delta.text&&(a||(a=!0,s=Date.now()-t),d.type==="thinking"?d.thinking=(d.thinking||"")+i.delta.text:d.type==="text"&&(d.text=(d.text||"")+i.delta.text)),i.delta.partial_json&&d.type==="tool_use"&&(d._inputJson=(d._inputJson||"")+i.delta.partial_json));}if(i.type==="content_block_stop"&&u!==null){let d=c[u];if(d&&d.type==="tool_use"){let l=d._inputJson;if(l){try{d.input=JSON.parse(l);}catch{}delete d._inputJson;}}u=null;}i.type==="message_delta"&&(i.usage?.output_tokens&&(r.usage.output_tokens=i.usage.output_tokens),i.delta?.stop_reason&&(r.stop_reason=i.delta.stop_reason)),yield i;}}catch(i){throw o=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t;if(r.content=c.filter(Boolean),o)f({provider:x,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:o,durationMs:i,streaming:true});else {let d=m({provider:x,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:r,durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(d&&r.content){let l=X(r.content);l.length>0&&k(l,d);}}}}function X(e){let n=[];for(let t of e)t.type==="tool_use"&&t.id&&n.push(t.id);return n}var v="bedrock";function xe(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="BedrockRuntimeClient")return true;let t=e;return typeof t.send!="function"||!t.config||typeof t.config!="object"?false:"region"in t.config}function _e(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="send"&&typeof s=="function"?_n(s.bind(t)):s}})}function _n(e){return async function(t){switch(t.constructor?.name||""){case "ConverseCommand":return En(e,t);case "ConverseStreamCommand":return Mn(e,t);case "InvokeModelCommand":return Pn(e,t);case "InvokeModelWithResponseStreamCommand":return Dn(e,t);default:return e(t)}}}async function En(e,n){let t=Date.now(),r=n.input;try{let o=await e(n),s=Date.now()-t,a=m({provider:v,model:r.modelId||"unknown",input:{system:r.system,messages:r.messages},rawResponse:Ee(o),durationMs:s,status:"success",streaming:!1});if(a){let u=Me(o);u.length>0&&k(u,a);}return o}catch(o){throw f({provider:v,model:r.modelId||"unknown",input:{system:r.system,messages:r.messages},error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:false}),o}}async function Mn(e,n){let t=Date.now(),r=n.input;try{let o=await e(n);return o.stream?{...o,stream:An(o.stream,r,t)}:o}catch(o){throw f({provider:v,model:r.modelId||"unknown",input:{system:r.system,messages:r.messages},error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:true}),o}}async function*An(e,n,t){let r={output:{message:{role:"assistant",content:[]}},usage:{inputTokens:0,outputTokens:0}},o=null,s,a=false,u=new Map,c=new Map;try{for await(let i of e){if(i.contentBlockStart){let d=i.contentBlockStart.contentBlockIndex;if(i.contentBlockStart.start?.toolUse){let l=i.contentBlockStart.start.toolUse;u.set(d,{toolUse:{toolUseId:l.toolUseId,name:l.name,input:{}}}),c.set(d,"");}else u.set(d,{text:""});}if(i.contentBlockDelta){let d=i.contentBlockDelta.contentBlockIndex,l=u.get(d);if(l&&i.contentBlockDelta.delta?.text&&(a||(a=!0,s=Date.now()-t),l.text=(l.text||"")+i.contentBlockDelta.delta.text),l?.toolUse&&i.contentBlockDelta.delta?.toolUse?.input){let p=c.get(d)||"";c.set(d,p+i.contentBlockDelta.delta.toolUse.input);}}if(i.contentBlockStop){let d=i.contentBlockStop.contentBlockIndex,l=u.get(d),p=c.get(d);if(l?.toolUse&&p)try{l.toolUse.input=JSON.parse(p);}catch{}}i.messageStop?.stopReason&&(r.stopReason=i.messageStop.stopReason),i.metadata?.usage&&(r.usage={inputTokens:i.metadata.usage.inputTokens||0,outputTokens:i.metadata.usage.outputTokens||0}),yield i;}}catch(i){throw o=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t,d=Array.from(u.entries()).sort((l,p)=>l[0]-p[0]).map(([,l])=>l);if(r.output.message.content=d,o)f({provider:v,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},error:o,durationMs:i,streaming:true});else {let l=m({provider:v,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},rawResponse:Ee(r),durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(l){let p=Me(r);p.length>0&&k(p,l);}}}}async function Pn(e,n){let t=Date.now(),r=n.input;try{let o=await e(n),s=Date.now()-t,a=Gn(o.body);return m({provider:v,model:r.modelId||"unknown",input:O(r.body),rawResponse:a,durationMs:s,status:"success",streaming:!1}),o}catch(o){throw f({provider:v,model:r.modelId||"unknown",input:O(r.body),error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:false}),o}}async function Dn(e,n){let t=Date.now(),r=n.input;try{let o=await e(n);return o.body?{...o,body:On(o.body,r,t)}:o}catch(o){throw f({provider:v,model:r.modelId||"unknown",input:O(r.body),error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:true}),o}}async function*On(e,n,t){let r=[],o=null;try{for await(let s of e){if(s.chunk?.bytes){let a=Bn(s.chunk.bytes);a&&r.push(a);}yield s;}}catch(s){throw o=s instanceof Error?s:new Error(String(s)),s}finally{let s=Date.now()-t;o?f({provider:v,model:n.modelId||"unknown",input:O(n.body),error:o,durationMs:s,streaming:true}):m({provider:v,model:n.modelId||"unknown",input:O(n.body),rawResponse:{streamEvents:r},durationMs:s,status:"success",streaming:true});}}function Ee(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function Me(e){let n=[],t=e.output?.message?.content;if(Array.isArray(t))for(let r of t)r.toolUse?.toolUseId&&n.push(r.toolUse.toolUseId);return n}function O(e){try{let n=typeof e=="string"?e:new TextDecoder().decode(e);return JSON.parse(n)}catch{return e}}function Gn(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}function Bn(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}var S="gemini";function Ae(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let t=e;return typeof t.generateContent=="function"&&typeof t.generateContentStream=="function"&&typeof t.model=="string"}function Pe(e){if(!e||typeof e!="object")return false;let n=e.constructor?.name;if(n==="GoogleGenerativeAI"||n==="GoogleGenAI")return true;let t=e;return !!(typeof t.getGenerativeModel=="function"||t.models&&typeof t.models.generate=="function"||Ae(e))}function De(e){if(Ae(e)){let t=e;return Oe(t,t.model)}let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="getGenerativeModel"&&typeof s=="function"?Un(s.bind(t)):s}})}function Un(e){return function(t){let r=e(t);return Oe(r,t.model)}}function Oe(e,n){return new Proxy(e,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="generateContent"&&typeof s=="function"?Nn(s.bind(t),n):r==="generateContentStream"&&typeof s=="function"?qn(s.bind(t),n):r==="startChat"&&typeof s=="function"?$n(s.bind(t),n):s}})}function Nn(e,n){return async function(r){let o=Date.now(),s=Be(r);try{let a=await e(r),u=Date.now()-o,c=je(a.response),i=m({provider:S,model:n,input:s,rawResponse:c,durationMs:u,status:"success",streaming:!1});if(i){let d=Ue(a.response);d.length>0&&k(d,i);}return a}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function qn(e,n){return async function(r){let o=Date.now(),s=Be(r);try{let a=await e(r),u=Ge(a.stream,n,s,o);return {...a,stream:u}}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}async function*Ge(e,n,t,r){let o={candidates:[{content:{parts:[]}}]},s=null,a,u=false;try{for await(let c of e){try{let i=c.text();if(i){u||(u=!0,a=Date.now()-r);let d=o.candidates[0].content?.parts||[],l=d[d.length-1];l?.text!==void 0?l.text+=i:d.push({text:i});}}catch{}if(c.candidates?.[0]?.content?.parts)for(let i of c.candidates[0].content.parts)i.functionCall&&o.candidates[0].content?.parts?.push(i);c.usageMetadata&&(o.usageMetadata=c.usageMetadata),c.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=c.candidates[0].finishReason),yield c;}}catch(c){throw s=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-r;if(s)f({provider:S,model:n,input:t,error:s,durationMs:c,streaming:true});else {let i=m({provider:S,model:n,input:t,rawResponse:o,durationMs:c,status:"success",streaming:true,firstTokenMs:a});if(i){let d=Fn(o.candidates);d.length>0&&k(d,i);}}}}function $n(e,n){return function(r){let o=e(r);return Ln(o,n)}}function Ln(e,n){return new Proxy(e,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="sendMessage"&&typeof s=="function"?Kn(s.bind(t),n):r==="sendMessageStream"&&typeof s=="function"?Jn(s.bind(t),n):s}})}function Kn(e,n){return async function(r){let o=Date.now(),s=r;try{let a=await e(r),u=Date.now()-o,c=je(a.response),i=m({provider:S,model:n,input:s,rawResponse:c,durationMs:u,status:"success",streaming:!1});if(i){let d=Ue(a.response);d.length>0&&k(d,i);}return a}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function Jn(e,n){return async function(r){let o=Date.now(),s=r;try{let a=await e(r),u=Ge(a.stream,n,s,o);return {...a,stream:u}}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}function Be(e){return typeof e=="string"?e:e.contents?e.contents:e}function je(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function Ue(e){let n=[],t=e.candidates?.[0]?.content?.parts;return t&&t.forEach((r,o)=>{r.functionCall?.name&&n.push(`gemini-fc-${r.functionCall.name}-${o}`);}),n}function Fn(e){let n=[],t=e?.[0]?.content?.parts;return t&&t.forEach((r,o)=>{r.functionCall?.name&&n.push(`gemini-fc-${r.functionCall.name}-${o}`);}),n}var Vn="openrouter.ai",q="openrouter";function Ne(e){if(!e||typeof e!="object")return false;let n=e;return n.chat?.completions?.create?(n.baseURL||"").includes(Vn):false}function qe(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="chat"&&s&&typeof s=="object"?Hn(s):s}})}function Hn(e){return e&&new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="completions"&&o&&typeof o=="object"?Wn(o):o}})}function Wn(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?Yn(o.bind(n)):o}})}function Yn(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&Xn(a))return Zn(a,o,r);let u=Date.now()-r,c=a;return m({provider:q,model:o.model||c.model||"unknown",input:o.messages,rawResponse:a,durationMs:u,status:"success",streaming:!1}),a}catch(a){let u=Date.now()-r;throw f({provider:q,model:o.model||"unknown",input:o.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}function Xn(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Zn(e,n,t){let r={choices:[{message:{content:"",role:"assistant"},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,s,a=false;try{for await(let u of e){let c=u;!r.id&&c.id&&(r.id=c.id);let i=c.choices?.[0]?.delta?.content;i&&(a||(a=!0,s=Date.now()-t),r.choices[0].message.content+=i);let d=c.choices?.[0]?.finish_reason;d&&(r.choices[0].finish_reason=d),c.usage&&(r.usage=c.usage),yield u;}}catch(u){throw o=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-t;o?f({provider:q,model:n.model||"unknown",input:n.messages,error:o,durationMs:u,streaming:true}):m({provider:q,model:n.model||"unknown",input:n.messages,rawResponse:r,durationMs:u,status:"success",streaming:true,firstTokenMs:s});}}function $e(e,n){return n&&me(n),U().disabled?(w("Tracing disabled, returning unwrapped client"),e):Ne(e)?(_("openrouter"),qe(e)):ke(e)?(_("openai"),et(e)):Se(e)?(_("anthropic"),at(e)):xe(e)?(_("bedrock"),_e(e)):Pe(e)?(_("gemini"),De(e)):(G("Unknown client type. Tracing not enabled. Supported: OpenAI, OpenRouter, Anthropic, Bedrock, Gemini"),e)}function et(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="chat"&&s&&typeof s=="object"?nt(s):r==="responses"&&s&&typeof s=="object"?rt(s):r==="completions"&&s&&typeof s=="object"?ot(s):r==="embeddings"&&s&&typeof s=="object"?st(s):s}})}function nt(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="completions"&&o&&typeof o=="object"?tt(o):o}})}function tt(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?ye(o.bind(n)):o}})}function rt(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?be(o.bind(n)):o}})}function ot(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?Ce(o.bind(n)):o}})}function st(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?ve(o.bind(n)):o}})}function at(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="messages"&&s&&typeof s=="object"?it(s):s}})}function it(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?Te(o.bind(n)):t==="stream"&&typeof o=="function"?Re(o.bind(n)):o}})}function ut(e){return function(t,r){return $e(t,{...e,...r})}}
3
- exports.captureSpan=H;exports.createObserve=ut;exports.flush=on;exports.getTraceContext=C;exports.init=tn;exports.isEnabled=rn;exports.observe=$e;exports.span=bn;exports.trace=wn;//# sourceMappingURL=index.js.map
2
+ var Z=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var He=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var ae=He((_t,Qe)=>{Qe.exports={name:"@lelemondev/sdk",version:"0.10.0",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],"google-genai":["./dist/google-genai.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@anthropic-ai/sdk":"^0.82.0","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",vite:"^6.0.0",typedoc:"^0.28.18",typescript:"^6.0.0",vitest:"^4.0.0"}};});var Q=false;function ee(e){Q=e;}function I(){return Q?true:We("LELEMON_DEBUG")==="true"}var C="[Lelemon]";function k(e,n){I()&&J("debug",e,n);}function L(e,n){I()&&J("info",e,n);}function O(e,n){J("warn",e,n);}function K(e,n,t,o){I()&&console.log(`${C} Captured trace: provider=${e} model=${n} duration=${t}ms status=${o}`);}function N(e,n){console.error(`${C} Failed to capture trace: provider=${e} error=${n.message}`);}function T(e){I()&&console.log(`${C} Wrapped client: provider=${e}`);}function ne(e,n){I()&&console.log(`${C} Sending batch: count=${e} endpoint=${n}`);}function te(e,n){I()&&console.log(`${C} Batch sent successfully: count=${e} duration=${n}ms`);}function re(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${C} Batch send failed: count=${e} error=${t}`);}function oe(e,n,t){I()&&console.log(`${C} Request: ${e} ${n} (${t} bytes)`);}function se(e,n){I()&&console.log(`${C} Response: status=${e} duration=${n}ms`);}function J(e,n,t){let o=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?o(`${C} ${n}`,t):o(`${C} ${n}`);}function We(e){if(typeof process<"u"&&process.env)return process.env[e]}var Ye=10,Xe=1e3,Ze=1e4,j=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(n){this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??Ye,flushIntervalMs:n.flushIntervalMs??Xe,requestTimeoutMs:n.requestTimeoutMs??Ze};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),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 n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).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(n){if(n.length===0)return;let t=Date.now();ne(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),te(n.length,Date.now()-t);}catch(o){re(n.length,o);}}async request(n,t,o){let r=`${this.config.endpoint}${t}`,s=new AbortController,a=o?JSON.stringify(o):void 0;oe(n,r,a?.length??0);let c=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),u=Date.now();try{let i=await fetch(r,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:s.signal});if(clearTimeout(c),se(i.status,Date.now()-u),!i.ok){let l=await i.text().catch(()=>"Unknown error");throw new Error(`HTTP ${i.status}: ${l}`)}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 en="@lelemondev/sdk",nn="nodejs";function tn(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function rn(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function on(){try{if(typeof Z<"u")return ae().version??"unknown"}catch{}return "unknown"}var _=null;function ue(e){if(!_){let t=tn(),o=rn();_={"telemetry.sdk.name":en,"telemetry.sdk.version":on(),"telemetry.sdk.language":nn},t&&(_["process.runtime.name"]=t.name,_["process.runtime.version"]=t.version),o&&(_["os.type"]=o);}let n={..._};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var z={},x=null,F=null,ce="https://api.lelemon.dev";function an(e={}){z=e,e.debug&&ee(true),F=ue(e.service),L("Initializing SDK",{endpoint:e.endpoint??ce,debug:e.debug??false,disabled:e.disabled??false,telemetry:F}),x=de(e),x.isEnabled()?L("SDK initialized - tracing enabled"):k("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function B(){return z}function U(){return F}function un(){return M().isEnabled()}function M(){return x||(x=de(z)),x}async function cn(){x&&await x.flush();}function de(e){let n=e.apiKey??dn("LELEMON_API_KEY");return !n&&!e.disabled&&O("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new j({apiKey:n??"",endpoint:e.endpoint??ce,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function dn(e){if(typeof process<"u"&&process.env)return process.env[e]}var V=Symbol.for("@lelemondev/sdk:globalContext");function fe(){let e=globalThis;return e[V]||(e[V]={context:{}}),e[V]}function me(e){fe().context=e,k("Global context updated",e);}function D(){return fe().context}function m(e){try{let n=M();if(!n.isEnabled()){k("Transport disabled, skipping trace capture");return}let t=D(),o=b(),r=P(),s=U(),a={provider:e.provider,model:e.model,input:W(e.input),rawResponse:e.rawResponse?A(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:o?.sessionId??t.sessionId,userId:o?.userId??t.userId,traceId:o?.traceId,spanId:r,parentSpanId:o?.currentSpanId,metadata:{...t.metadata,...e.metadata,...o?{_traceName:o.name}:{},...s?{_telemetry:s}:{}},tags:t.tags,spanType:e.spanType,name:e.name};return K(e.provider,e.model,e.durationMs,e.status),n.enqueue(a),r}catch(n){N(e.provider,n instanceof Error?n:new Error(String(n)));return}}function f(e){try{let n=M();if(!n.isEnabled()){k("Transport disabled, skipping error capture");return}let t=D(),o=b(),r=U(),s={provider:e.provider,model:e.model,input:W(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:o?.sessionId??t.sessionId,userId:o?.userId??t.userId,traceId:o?.traceId,spanId:P(),parentSpanId:o?.currentSpanId,metadata:{...t.metadata,...e.metadata,...o?{_traceName:o.name}:{},...r?{_telemetry:r}:{}},tags:t.tags};K(e.provider,e.model,e.durationMs,"error"),k("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(s);}catch(n){N(e.provider,n instanceof Error?n:new Error(String(n)));}}function H(e){try{let n=M();if(!n.isEnabled()){k("Transport disabled, skipping span capture");return}let t=D(),o=b(),r=e.metadata?._traceId,s=e.metadata?._parentSpanId,a=U(),c={...t.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete c._traceId,delete c._parentSpanId;let u={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:W(e.input),output:A(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:o?.sessionId??t.sessionId,userId:o?.userId??t.userId,traceId:r??o?.traceId,spanId:P(),parentSpanId:s??o?.currentSpanId,toolCallId:e.toolCallId,metadata:c,tags:t.tags};k(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(u);}catch(n){N("unknown",n instanceof Error?n:new Error(String(n)));}}var le=1e5,ln=["api_key","apikey","password","secret","authorization"],pn=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],fn=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],pe={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function ge(){return B().redaction??{}}function mn(e){let n=e.toLowerCase();return fn.includes(n)?false:!!(ln.some(o=>n.includes(o))||pn.some(o=>n.includes(o))||(ge().keys??[]).some(o=>n.includes(o.toLowerCase())))}function gn(e){let n=ge(),t=e;for(let o of n.patterns??[])o.lastIndex=0,t=t.replace(o,"[REDACTED]");return n.emails&&(t=t.replace(pe.emails,"[EMAIL]")),n.phones&&(t=t.replace(pe.phones,"[PHONE]")),t}function W(e){return A(e,0)}function A(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=gn(e);return t.length>le&&(t=t.slice(0,le)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>A(t,n+1));if(typeof e=="object"){let t={};for(let[o,r]of Object.entries(e))mn(o)?t[o]="[REDACTED]":t[o]=A(r,n+1);return t}return String(e)}var Y=Symbol.for("@lelemondev/sdk:traceStorage");function kn(){let e=globalThis;return e[Y]||(e[Y]=new async_hooks.AsyncLocalStorage),e[Y]}var we=kn();function P(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function b(){return we.getStore()}function g(e,n){let t=b();if(t)for(let o of e)t.pendingToolCalls.set(o,n),k(`Registered tool call ${o} \u2192 LLM span ${n}`);}function yn(e){let n=b();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function hn(e){let n=b();n&&n.pendingToolCalls.delete(e);}async function Cn(e,n){let t=typeof e=="string"?{name:e}:e,o=b(),r=o?.traceId??P(),s=P(),a={traceId:r,rootSpanId:s,currentSpanId:s,parentSpanId:o?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,pendingToolCalls:new Map};return we.run(a,async()=>{let c,u;try{return c=await n(),c}catch(i){throw u=i instanceof Error?i:new Error(String(i)),i}finally{In(a,u?void 0:c,u);}})}var bn=["text","content","message","output","response","result","answer"];function vn(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let r=e;return n in r?r[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let o=e;for(let r of bn)if(r in o&&typeof o[r]=="string")return o[r];return e}function In(e,n,t){let o=M();if(!o.isEnabled()){k("Transport disabled, skipping root span");return}let r=D(),s=Date.now()-e.startTime,a=t?null:vn(n,e.outputKey,e.outputTransform),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:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId??r.sessionId,userId:e.userId??r.userId,metadata:{...r.metadata,...e.metadata},tags:e.tags??r.tags};k(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),o.enqueue(c);}function Sn(e){let n=b();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=yn(e.toolCallId);H({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:n.traceId,_parentSpanId:t}}),e.toolCallId&&hn(e.toolCallId);}var h="openai";function ke(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function ye(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&he(a))return Rn(a,r,o);let c=Date.now()-o,u=a,i=m({provider:h,model:r.model||u.model||"unknown",input:r.messages,rawResponse:a,durationMs:c,status:"success",streaming:!1});if(i){let d=Ie(u);d.length>0&&g(d,i);}return a}catch(a){let c=Date.now()-o;throw f({provider:h,model:r.model||"unknown",input:r.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}function he(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Rn(e,n,t){let o={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},r=null,s,a=false,c=new Map;try{for await(let u of e){let i=u,d=i?.choices?.[0]?.delta?.content;d&&(a||(a=!0,s=Date.now()-t),o.choices[0].message.content+=d);let l=i?.choices?.[0]?.delta?.tool_calls;if(l)for(let w of l){c.has(w.index)||c.set(w.index,{id:"",function:{name:"",arguments:""}});let $=c.get(w.index);w.id&&($.id=w.id),w.function?.name&&($.function.name=w.function.name),w.function?.arguments&&($.function.arguments+=w.function.arguments);}let p=i?.choices?.[0]?.finish_reason;p&&(o.choices[0].finish_reason=p),i?.usage&&(o.usage=i.usage),yield u;}}catch(u){throw r=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-t;if(c.size>0&&(o.choices[0].message.tool_calls=Array.from(c.entries()).sort((i,d)=>i[0]-d[0]).map(([,i])=>i)),r)f({provider:h,model:n.model||"unknown",input:n.messages,error:r,durationMs:u,streaming:true});else {let i=m({provider:h,model:n.model||"unknown",input:n.messages,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:s});if(i){let d=Ie(o);d.length>0&&g(d,i);}}}}function Ce(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&he(a))return Tn(a,r,o);let c=Date.now()-o;return m({provider:h,model:r.model||"unknown",input:{instructions:r.instructions,input:r.input},rawResponse:a,durationMs:c,status:"success",streaming:!1}),a}catch(a){let c=Date.now()-o;throw f({provider:h,model:r.model||"unknown",input:{instructions:r.instructions,input:r.input},error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}async function*Tn(e,n,t){let o=[],r=null,s=null;try{for await(let a of e){o.push(a);let c=a;c.type==="response.done"&&c.response&&(r=c.response),yield a;}}catch(a){throw s=a instanceof Error?a:new Error(String(a)),a}finally{let a=Date.now()-t;s?f({provider:h,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:s,durationMs:a,streaming:true}):m({provider:h,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:r||{streamEvents:o},durationMs:a,status:"success",streaming:true});}}function be(e){return async function(...t){let o=Date.now(),r=t[0]||{};try{let s=await e(...t),a=Date.now()-o;return m({provider:h,model:r.model||"unknown",input:r.prompt,rawResponse:s,durationMs:a,status:"success",streaming:!1}),s}catch(s){let a=Date.now()-o;throw f({provider:h,model:r.model||"unknown",input:r.prompt,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function ve(e){return async function(...t){let o=Date.now(),r=t[0]||{};try{let s=await e(...t),a=Date.now()-o;return m({provider:h,model:r.model||"unknown",input:r.input,rawResponse:s,durationMs:a,status:"success",streaming:!1,spanType:"embedding"}),s}catch(s){let a=Date.now()-o;throw f({provider:h,model:r.model||"unknown",input:r.input,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function Ie(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let o of t)o.id&&n.push(o.id);return n}var E="anthropic";function Se(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="Anthropic")return true;let t=e;return !!(t.messages&&typeof t.messages=="object")}function Re(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&Mn(a))return _n(a,r,o);let c=Date.now()-o,u=a,i=m({provider:E,model:r.model||u.model||"unknown",input:{system:r.system,messages:r.messages},rawResponse:a,durationMs:c,status:"success",streaming:!1});if(i&&u.content){let d=X(u.content);d.length>0&&g(d,i);}return a}catch(a){let c=Date.now()-o;throw f({provider:E,model:r.model||"unknown",input:{system:r.system,messages:r.messages},error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}function Te(e){return function(...t){let o=Date.now(),r=t[0]||{};try{let s=e(...t);return s&&typeof s=="object"?En(s,r,o):s}catch(s){let a=Date.now()-o;throw f({provider:E,model:r.model||"unknown",input:{system:r.system,messages:r.messages},error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:true}),s}}}function Mn(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}function En(e,n,t){let o=e;if(!o[Symbol.asyncIterator])return e;let r={content:[],usage:{input_tokens:0,output_tokens:0}},s=false,a,c=false,u=null,i=[],d=async function*(){try{for await(let l of o){if(l.type==="message_start"&&l.message&&(r.model=l.message.model,r.id=l.message.id,r.role=l.message.role,l.message.usage&&(r.usage={...l.message.usage})),l.type==="content_block_start"&&l.content_block&&(u=l.index??i.length,i[u]={...l.content_block},l.content_block.type==="text"&&(i[u].text=""),l.content_block.type==="thinking"&&(i[u].thinking="")),l.type==="content_block_delta"&&l.delta&&u!==null){let p=i[u];p&&(l.delta.text&&(c||(c=!0,a=Date.now()-t),p.type==="thinking"?p.thinking=(p.thinking||"")+l.delta.text:p.type==="text"&&(p.text=(p.text||"")+l.delta.text)),l.delta.partial_json&&p.type==="tool_use"&&(p._inputJson=(p._inputJson||"")+l.delta.partial_json));}if(l.type==="content_block_stop"&&u!==null){let p=i[u];if(p&&p.type==="tool_use"){let w=p._inputJson;if(w){try{p.input=JSON.parse(w);}catch{}delete p._inputJson;}}u=null;}l.type==="message_delta"&&(l.usage?.output_tokens&&(r.usage.output_tokens=l.usage.output_tokens),l.delta?.stop_reason&&(r.stop_reason=l.delta.stop_reason)),yield l;}}catch(l){if(!s){s=true;let p=Date.now()-t;f({provider:E,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:l instanceof Error?l:new Error(String(l)),durationMs:p,streaming:true});}throw l}finally{if(!s){s=true;let l=Date.now()-t;r.content=i.filter(Boolean);let p=m({provider:E,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:r,durationMs:l,status:"success",streaming:true,firstTokenMs:a});if(p&&r.content){let w=X(r.content);w.length>0&&g(w,p);}}}};return new Proxy(e,{get(l,p,w){return p===Symbol.asyncIterator?()=>d()[Symbol.asyncIterator]():Reflect.get(l,p,w)}})}async function*_n(e,n,t){let o={content:[],usage:{input_tokens:0,output_tokens:0}},r=null,s,a=false,c=null,u=[];try{for await(let i of e){if(i.type==="message_start"&&i.message&&(o.model=i.message.model,o.id=i.message.id,o.role=i.message.role,i.message.usage&&(o.usage={...i.message.usage})),i.type==="content_block_start"&&i.content_block&&(c=i.index??u.length,u[c]={...i.content_block},i.content_block.type==="text"&&(u[c].text=""),i.content_block.type==="thinking"&&(u[c].thinking="")),i.type==="content_block_delta"&&i.delta&&c!==null){let d=u[c];d&&(i.delta.text&&(a||(a=!0,s=Date.now()-t),d.type==="thinking"?d.thinking=(d.thinking||"")+i.delta.text:d.type==="text"&&(d.text=(d.text||"")+i.delta.text)),i.delta.partial_json&&d.type==="tool_use"&&(d._inputJson=(d._inputJson||"")+i.delta.partial_json));}if(i.type==="content_block_stop"&&c!==null){let d=u[c];if(d&&d.type==="tool_use"){let l=d._inputJson;if(l){try{d.input=JSON.parse(l);}catch{}delete d._inputJson;}}c=null;}i.type==="message_delta"&&(i.usage?.output_tokens&&(o.usage.output_tokens=i.usage.output_tokens),i.delta?.stop_reason&&(o.stop_reason=i.delta.stop_reason)),yield i;}}catch(i){throw r=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t;if(o.content=u.filter(Boolean),r)f({provider:E,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:r,durationMs:i,streaming:true});else {let d=m({provider:E,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:o,durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(d&&o.content){let l=X(o.content);l.length>0&&g(l,d);}}}}function X(e){let n=[];for(let t of e)t.type==="tool_use"&&t.id&&n.push(t.id);return n}var v="bedrock";function xe(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="BedrockRuntimeClient")return true;let t=e;return typeof t.send!="function"||!t.config||typeof t.config!="object"?false:"region"in t.config}function Me(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="send"&&typeof s=="function"?An(s.bind(t)):s}})}function An(e){return async function(t){switch(t.constructor?.name||""){case "ConverseCommand":return Dn(e,t);case "ConverseStreamCommand":return Gn(e,t);case "InvokeModelCommand":return Nn(e,t);case "InvokeModelWithResponseStreamCommand":return jn(e,t);default:return e(t)}}}async function Dn(e,n){let t=Date.now(),o=n.input;try{let r=await e(n),s=Date.now()-t,a=m({provider:v,model:o.modelId||"unknown",input:{system:o.system,messages:o.messages},rawResponse:Ee(r),durationMs:s,status:"success",streaming:!1});if(a){let c=_e(r);c.length>0&&g(c,a);}return r}catch(r){throw f({provider:v,model:o.modelId||"unknown",input:{system:o.system,messages:o.messages},error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:false}),r}}async function Gn(e,n){let t=Date.now(),o=n.input;try{let r=await e(n);return r.stream?{...r,stream:On(r.stream,o,t)}:r}catch(r){throw f({provider:v,model:o.modelId||"unknown",input:{system:o.system,messages:o.messages},error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:true}),r}}async function*On(e,n,t){let o={output:{message:{role:"assistant",content:[]}},usage:{inputTokens:0,outputTokens:0}},r=null,s,a=false,c=new Map,u=new Map;try{for await(let i of e){if(i.contentBlockStart){let d=i.contentBlockStart.contentBlockIndex;if(i.contentBlockStart.start?.toolUse){let l=i.contentBlockStart.start.toolUse;c.set(d,{toolUse:{toolUseId:l.toolUseId,name:l.name,input:{}}}),u.set(d,"");}else c.set(d,{text:""});}if(i.contentBlockDelta){let d=i.contentBlockDelta.contentBlockIndex,l=c.get(d);if(l&&i.contentBlockDelta.delta?.text&&(a||(a=!0,s=Date.now()-t),l.text=(l.text||"")+i.contentBlockDelta.delta.text),l?.toolUse&&i.contentBlockDelta.delta?.toolUse?.input){let p=u.get(d)||"";u.set(d,p+i.contentBlockDelta.delta.toolUse.input);}}if(i.contentBlockStop){let d=i.contentBlockStop.contentBlockIndex,l=c.get(d),p=u.get(d);if(l?.toolUse&&p)try{l.toolUse.input=JSON.parse(p);}catch{}}i.messageStop?.stopReason&&(o.stopReason=i.messageStop.stopReason),i.metadata?.usage&&(o.usage={inputTokens:i.metadata.usage.inputTokens||0,outputTokens:i.metadata.usage.outputTokens||0}),yield i;}}catch(i){throw r=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t,d=Array.from(c.entries()).sort((l,p)=>l[0]-p[0]).map(([,l])=>l);if(o.output.message.content=d,r)f({provider:v,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},error:r,durationMs:i,streaming:true});else {let l=m({provider:v,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},rawResponse:Ee(o),durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(l){let p=_e(o);p.length>0&&g(p,l);}}}}async function Nn(e,n){let t=Date.now(),o=n.input;try{let r=await e(n),s=Date.now()-t,a=Un(r.body);return m({provider:v,model:o.modelId||"unknown",input:G(o.body),rawResponse:a,durationMs:s,status:"success",streaming:!1}),r}catch(r){throw f({provider:v,model:o.modelId||"unknown",input:G(o.body),error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:false}),r}}async function jn(e,n){let t=Date.now(),o=n.input;try{let r=await e(n);return r.body?{...r,body:Bn(r.body,o,t)}:r}catch(r){throw f({provider:v,model:o.modelId||"unknown",input:G(o.body),error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:true}),r}}async function*Bn(e,n,t){let o=[],r=null;try{for await(let s of e){if(s.chunk?.bytes){let a=qn(s.chunk.bytes);a&&o.push(a);}yield s;}}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{let s=Date.now()-t;r?f({provider:v,model:n.modelId||"unknown",input:G(n.body),error:r,durationMs:s,streaming:true}):m({provider:v,model:n.modelId||"unknown",input:G(n.body),rawResponse:{streamEvents:o},durationMs:s,status:"success",streaming:true});}}function Ee(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function _e(e){let n=[],t=e.output?.message?.content;if(Array.isArray(t))for(let o of t)o.toolUse?.toolUseId&&n.push(o.toolUse.toolUseId);return n}function G(e){try{let n=typeof e=="string"?e:new TextDecoder().decode(e);return JSON.parse(n)}catch{return e}}function Un(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}function qn(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}var S="gemini";function Pe(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GoogleGenAI")return true;let t=e;return !!(t.models&&typeof t.models=="object"&&typeof t.models.generateContent=="function"&&t.chats&&typeof t.chats=="object")}function Ae(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="models"&&s&&typeof s=="object"?Ln(s):o==="chats"&&s&&typeof s=="object"?Fn(s):s}})}function Ln(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="generateContent"&&typeof r=="function"?Kn(r.bind(n)):t==="generateContentStream"&&typeof r=="function"?Jn(r.bind(n)):r}})}function Kn(e){return async function(t){let o=Date.now(),r=t.model,s=Ge(t);try{let a=await e(t),c=Date.now()-o,u=Oe(a),i=m({provider:S,model:r,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Ne(a);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:S,model:r,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function Jn(e){return async function(t){let o=Date.now(),r=t.model,s=Ge(t);try{let a=await e(t);return De(a,r,s,o)}catch(a){throw f({provider:S,model:r,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}async function*De(e,n,t,o){let r={candidates:[{content:{parts:[]}}]},s=null,a,c=false;try{for await(let u of e){let i=u.text;if(i){c||(c=!0,a=Date.now()-o);let d=r.candidates[0].content?.parts||[],l=d[d.length-1];l?.text!==void 0?l.text+=i:d.push({text:i});}if(u.candidates?.[0]?.content?.parts)for(let d of u.candidates[0].content.parts)d.functionCall&&r.candidates[0].content?.parts?.push(d);u.usageMetadata&&(r.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(r.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()-o;if(s)f({provider:S,model:n,input:t,error:s,durationMs:u,streaming:true});else {let i=m({provider:S,model:n,input:t,rawResponse:r,durationMs:u,status:"success",streaming:true,firstTokenMs:a});if(i){let d=Yn(r.candidates);d.length>0&&g(d,i);}}}}function Fn(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?zn(r.bind(n)):r}})}function zn(e){return function(t){let o=e(t);return Vn(o,t.model)}}function Vn(e,n){return new Proxy(e,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="sendMessage"&&typeof s=="function"?Hn(s.bind(t),n):o==="sendMessageStream"&&typeof s=="function"?Wn(s.bind(t),n):s}})}function Hn(e,n){return async function(o){let r=Date.now(),s=o.message;try{let a=await e(o),c=Date.now()-r,u=Oe(a),i=m({provider:S,model:n,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Ne(a);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:false}),a}}}function Wn(e,n){return async function(o){let r=Date.now(),s=o.message;try{let a=await e(o);return De(a,n,s,r)}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:true}),a}}}function Ge(e){return e.contents}function Oe(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata,modelVersion:e.modelVersion}}function Ne(e){let n=[],t=e.candidates?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}function Yn(e){let n=[],t=e?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}var R="gemini";function je(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let t=e;return typeof t.generateContent=="function"&&typeof t.generateContentStream=="function"&&typeof t.model=="string"}function Be(e){return !e||typeof e!="object"?false:!!(e.constructor?.name==="GoogleGenerativeAI"||typeof e.getGenerativeModel=="function"||je(e))}function Ue(e){if(je(e)){let t=e;return qe(t,t.model)}let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="getGenerativeModel"&&typeof s=="function"?Zn(s.bind(t)):s}})}function Zn(e){return function(t){let o=e(t);return qe(o,t.model)}}function qe(e,n){return new Proxy(e,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="generateContent"&&typeof s=="function"?Qn(s.bind(t),n):o==="generateContentStream"&&typeof s=="function"?et(s.bind(t),n):o==="startChat"&&typeof s=="function"?nt(s.bind(t),n):s}})}function Qn(e,n){return async function(o){let r=Date.now(),s=Le(o);try{let a=await e(o),c=Date.now()-r,u=Ke(a.response),i=m({provider:R,model:n,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Je(a.response);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:R,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:false}),a}}}function et(e,n){return async function(o){let r=Date.now(),s=Le(o);try{let a=await e(o),c=$e(a.stream,n,s,r);return {...a,stream:c}}catch(a){throw f({provider:R,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:true}),a}}}async function*$e(e,n,t,o){let r={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()-o);let d=r.candidates[0].content?.parts||[],l=d[d.length-1];l?.text!==void 0?l.text+=i:d.push({text:i});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let i of u.candidates[0].content.parts)i.functionCall&&r.candidates[0].content?.parts?.push(i);u.usageMetadata&&(r.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(r.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()-o;if(s)f({provider:R,model:n,input:t,error:s,durationMs:u,streaming:true});else {let i=m({provider:R,model:n,input:t,rawResponse:r,durationMs:u,status:"success",streaming:true,firstTokenMs:a});if(i){let d=st(r.candidates);d.length>0&&g(d,i);}}}}function nt(e,n){return function(o){let r=e(o);return tt(r,n)}}function tt(e,n){return new Proxy(e,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="sendMessage"&&typeof s=="function"?rt(s.bind(t),n):o==="sendMessageStream"&&typeof s=="function"?ot(s.bind(t),n):s}})}function rt(e,n){return async function(o){let r=Date.now(),s=o;try{let a=await e(o),c=Date.now()-r,u=Ke(a.response),i=m({provider:R,model:n,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Je(a.response);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:R,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:false}),a}}}function ot(e,n){return async function(o){let r=Date.now(),s=o;try{let a=await e(o),c=$e(a.stream,n,s,r);return {...a,stream:c}}catch(a){throw f({provider:R,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:true}),a}}}function Le(e){return typeof e=="string"?e:e.contents?e.contents:e}function Ke(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function Je(e){let n=[],t=e.candidates?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}function st(e){let n=[],t=e?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}var it="openrouter.ai",q="openrouter";function Fe(e){if(!e||typeof e!="object")return false;let n=e;return n.chat?.completions?.create?(n.baseURL||"").includes(it):false}function ze(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="chat"&&s&&typeof s=="object"?ut(s):s}})}function ut(e){return e&&new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="completions"&&r&&typeof r=="object"?ct(r):r}})}function ct(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?dt(r.bind(n)):r}})}function dt(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&lt(a))return pt(a,r,o);let c=Date.now()-o,u=a;return m({provider:q,model:r.model||u.model||"unknown",input:r.messages,rawResponse:a,durationMs:c,status:"success",streaming:!1}),a}catch(a){let c=Date.now()-o;throw f({provider:q,model:r.model||"unknown",input:r.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}function lt(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*pt(e,n,t){let o={choices:[{message:{content:"",role:"assistant"},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},r=null,s,a=false;try{for await(let c of e){let u=c;!o.id&&u.id&&(o.id=u.id);let i=u.choices?.[0]?.delta?.content;i&&(a||(a=!0,s=Date.now()-t),o.choices[0].message.content+=i);let d=u.choices?.[0]?.finish_reason;d&&(o.choices[0].finish_reason=d),u.usage&&(o.usage=u.usage),yield c;}}catch(c){throw r=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-t;r?f({provider:q,model:n.model||"unknown",input:n.messages,error:r,durationMs:c,streaming:true}):m({provider:q,model:n.model||"unknown",input:n.messages,rawResponse:o,durationMs:c,status:"success",streaming:true,firstTokenMs:s});}}function Ve(e,n){return n&&me(n),B().disabled?(k("Tracing disabled, returning unwrapped client"),e):Fe(e)?(T("openrouter"),ze(e)):ke(e)?(T("openai"),mt(e)):Se(e)?(T("anthropic"),Ct(e)):xe(e)?(T("bedrock"),Me(e)):Pe(e)?(T("gemini"),Ae(e)):Be(e)?(T("gemini"),Ue(e)):(O("Unknown client type. Tracing not enabled. Supported: OpenAI, OpenRouter, Anthropic, Bedrock, Gemini"),e)}function mt(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="chat"&&s&&typeof s=="object"?gt(s):o==="responses"&&s&&typeof s=="object"?kt(s):o==="completions"&&s&&typeof s=="object"?yt(s):o==="embeddings"&&s&&typeof s=="object"?ht(s):s}})}function gt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="completions"&&r&&typeof r=="object"?wt(r):r}})}function wt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?ye(r.bind(n)):r}})}function kt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?Ce(r.bind(n)):r}})}function yt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?be(r.bind(n)):r}})}function ht(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?ve(r.bind(n)):r}})}function Ct(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="messages"&&s&&typeof s=="object"?bt(s):s}})}function bt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?Re(r.bind(n)):t==="stream"&&typeof r=="function"?Te(r.bind(n)):r}})}function vt(e){return function(t,o){return Ve(t,{...e,...o})}}
3
+ exports.captureSpan=H;exports.createObserve=vt;exports.flush=cn;exports.getTraceContext=b;exports.init=an;exports.isEnabled=un;exports.observe=Ve;exports.span=Sn;exports.trace=Cn;//# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  import {AsyncLocalStorage}from'async_hooks';/* @lelemondev/sdk - LLM Observability */
2
- var $e=Object.defineProperty;var Le=(e,n,t)=>n in e?$e(e,n,{enumerable:true,configurable:true,writable:true,value:t}):e[n]=t;var X=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ke=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var M=(e,n,t)=>Le(e,typeof n!="symbol"?n+"":n,t);var se=Ke((mt,He)=>{He.exports={name:"@lelemondev/sdk",version:"0.9.9",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/generative-ai":"^0.24.1","@types/node":"^20.0.0","@vitest/coverage-v8":"^2.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.15",typescript:"^5.9.3",vitest:"^2.0.0"}};});var Z=false;function Q(e){Z=e;}function v(){return Z?true:Je("LELEMON_DEBUG")==="true"}var h="[Lelemon]";function w(e,n){v()&&K("debug",e,n);}function $(e,n){v()&&K("info",e,n);}function O(e,n){K("warn",e,n);}function L(e,n,t,r){v()&&console.log(`${h} Captured trace: provider=${e} model=${n} duration=${t}ms status=${r}`);}function G(e,n){console.error(`${h} Failed to capture trace: provider=${e} error=${n.message}`);}function x(e){v()&&console.log(`${h} Wrapped client: provider=${e}`);}function ee(e,n){v()&&console.log(`${h} Sending batch: count=${e} endpoint=${n}`);}function ne(e,n){v()&&console.log(`${h} Batch sent successfully: count=${e} duration=${n}ms`);}function te(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${h} Batch send failed: count=${e} error=${t}`);}function re(e,n,t){v()&&console.log(`${h} Request: ${e} ${n} (${t} bytes)`);}function oe(e,n){v()&&console.log(`${h} Response: status=${e} duration=${n}ms`);}function K(e,n,t){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?r(`${h} ${n}`,t):r(`${h} ${n}`);}function Je(e){if(typeof process<"u"&&process.env)return process.env[e]}var Fe=10,ze=1e3,Ve=1e4,B=class{constructor(n){M(this,"config");M(this,"queue",[]);M(this,"flushPromise",null);M(this,"flushTimer",null);this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??Fe,flushIntervalMs:n.flushIntervalMs??ze,requestTimeoutMs:n.requestTimeoutMs??Ve};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),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 n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).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(n){if(n.length===0)return;let t=Date.now();ee(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),ne(n.length,Date.now()-t);}catch(r){te(n.length,r);}}async request(n,t,r){let o=`${this.config.endpoint}${t}`,s=new AbortController,a=r?JSON.stringify(r):void 0;re(n,o,a?.length??0);let u=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),c=Date.now();try{let i=await fetch(o,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:s.signal});if(clearTimeout(u),oe(i.status,Date.now()-c),!i.ok){let l=await i.text().catch(()=>"Unknown error");throw new Error(`HTTP ${i.status}: ${l}`)}let d=await i.text();return d?JSON.parse(d):{}}catch(i){throw clearTimeout(u),i instanceof Error&&i.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):i}}};var We="@lelemondev/sdk",Ye="nodejs";function Xe(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function Ze(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function Qe(){try{if(typeof X<"u")return se().version??"unknown"}catch{}return "unknown"}var _=null;function ie(e){if(!_){let t=Xe(),r=Ze();_={"telemetry.sdk.name":We,"telemetry.sdk.version":Qe(),"telemetry.sdk.language":Ye},t&&(_["process.runtime.name"]=t.name,_["process.runtime.version"]=t.version),r&&(_["os.type"]=r);}let n={..._};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var F={},S=null,J=null,ue="https://api.lelemon.dev";function nn(e={}){F=e,e.debug&&Q(true),J=ie(e.service),$("Initializing SDK",{endpoint:e.endpoint??ue,debug:e.debug??false,disabled:e.disabled??false,telemetry:J}),S=ce(e),S.isEnabled()?$("SDK initialized - tracing enabled"):w("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function j(){return F}function U(){return J}function tn(){return T().isEnabled()}function T(){return S||(S=ce(F)),S}async function rn(){S&&await S.flush();}function ce(e){let n=e.apiKey??on("LELEMON_API_KEY");return !n&&!e.disabled&&O("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new B({apiKey:n??"",endpoint:e.endpoint??ue,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function on(e){if(typeof process<"u"&&process.env)return process.env[e]}var z=Symbol.for("@lelemondev/sdk:globalContext");function pe(){let e=globalThis;return e[z]||(e[z]={context:{}}),e[z]}function fe(e){pe().context=e,w("Global context updated",e);}function P(){return pe().context}function m(e){try{let n=T();if(!n.isEnabled()){w("Transport disabled, skipping trace capture");return}let t=P(),r=b(),o=E(),s=U(),a={provider:e.provider,model:e.model,input:H(e.input),rawResponse:e.rawResponse?A(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:t.tags,spanType:e.spanType,name:e.name};return L(e.provider,e.model,e.durationMs,e.status),n.enqueue(a),o}catch(n){G(e.provider,n instanceof Error?n:new Error(String(n)));return}}function f(e){try{let n=T();if(!n.isEnabled()){w("Transport disabled, skipping error capture");return}let t=P(),r=b(),o=U(),s={provider:e.provider,model:e.model,input:H(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:E(),parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:t.tags};L(e.provider,e.model,e.durationMs,"error"),w("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(s);}catch(n){G(e.provider,n instanceof Error?n:new Error(String(n)));}}function V(e){try{let n=T();if(!n.isEnabled()){w("Transport disabled, skipping span capture");return}let t=P(),r=b(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,a=U(),u={...t.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete u._traceId,delete u._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:H(e.input),output:A(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:o??r?.traceId,spanId:E(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:u,tags:t.tags};w(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(c);}catch(n){G("unknown",n instanceof Error?n:new Error(String(n)));}}var le=1e5,sn=["api_key","apikey","password","secret","authorization"],an=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],un=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],de={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function me(){return j().redaction??{}}function cn(e){let n=e.toLowerCase();return un.includes(n)?false:!!(sn.some(r=>n.includes(r))||an.some(r=>n.includes(r))||(me().keys??[]).some(r=>n.includes(r.toLowerCase())))}function ln(e){let n=me(),t=e;for(let r of n.patterns??[])r.lastIndex=0,t=t.replace(r,"[REDACTED]");return n.emails&&(t=t.replace(de.emails,"[EMAIL]")),n.phones&&(t=t.replace(de.phones,"[PHONE]")),t}function H(e){return A(e,0)}function A(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=ln(e);return t.length>le&&(t=t.slice(0,le)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>A(t,n+1));if(typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))cn(r)?t[r]="[REDACTED]":t[r]=A(o,n+1);return t}return String(e)}var W=Symbol.for("@lelemondev/sdk:traceStorage");function pn(){let e=globalThis;return e[W]||(e[W]=new AsyncLocalStorage),e[W]}var ge=pn();function E(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function b(){return ge.getStore()}function k(e,n){let t=b();if(t)for(let r of e)t.pendingToolCalls.set(r,n),w(`Registered tool call ${r} \u2192 LLM span ${n}`);}function fn(e){let n=b();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function mn(e){let n=b();n&&n.pendingToolCalls.delete(e);}async function gn(e,n){let t=typeof e=="string"?{name:e}:e,r=b(),o=r?.traceId??E(),s=E(),a={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,pendingToolCalls:new Map};return ge.run(a,async()=>{let u,c;try{return u=await n(),u}catch(i){throw c=i instanceof Error?i:new Error(String(i)),i}finally{yn(a,c?void 0:u,c);}})}var wn=["text","content","message","output","response","result","answer"];function kn(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let o=e;return n in o?o[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let o of wn)if(o in r&&typeof r[o]=="string")return r[o];return e}function yn(e,n,t){let r=T();if(!r.isEnabled()){w("Transport disabled, skipping root span");return}let o=P(),s=Date.now()-e.startTime,a=t?null:kn(n,e.outputKey,e.outputTransform),u={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:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId??o.sessionId,userId:e.userId??o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};w(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),r.enqueue(u);}function hn(e){let n=b();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=fn(e.toolCallId);V({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:n.traceId,_parentSpanId:t}}),e.toolCallId&&mn(e.toolCallId);}var y="openai";function we(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function ke(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&ye(a))return bn(a,o,r);let u=Date.now()-r,c=a,i=m({provider:y,model:o.model||c.model||"unknown",input:o.messages,rawResponse:a,durationMs:u,status:"success",streaming:!1});if(i){let d=ve(c);d.length>0&&k(d,i);}return a}catch(a){let u=Date.now()-r;throw f({provider:y,model:o.model||"unknown",input:o.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}function ye(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*bn(e,n,t){let r={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,s,a=false,u=new Map;try{for await(let c of e){let i=c,d=i?.choices?.[0]?.delta?.content;d&&(a||(a=!0,s=Date.now()-t),r.choices[0].message.content+=d);let l=i?.choices?.[0]?.delta?.tool_calls;if(l)for(let g of l){u.has(g.index)||u.set(g.index,{id:"",function:{name:"",arguments:""}});let q=u.get(g.index);g.id&&(q.id=g.id),g.function?.name&&(q.function.name=g.function.name),g.function?.arguments&&(q.function.arguments+=g.function.arguments);}let p=i?.choices?.[0]?.finish_reason;p&&(r.choices[0].finish_reason=p),i?.usage&&(r.usage=i.usage),yield c;}}catch(c){throw o=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-t;if(u.size>0&&(r.choices[0].message.tool_calls=Array.from(u.entries()).sort((i,d)=>i[0]-d[0]).map(([,i])=>i)),o)f({provider:y,model:n.model||"unknown",input:n.messages,error:o,durationMs:c,streaming:true});else {let i=m({provider:y,model:n.model||"unknown",input:n.messages,rawResponse:r,durationMs:c,status:"success",streaming:true,firstTokenMs:s});if(i){let d=ve(r);d.length>0&&k(d,i);}}}}function he(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&ye(a))return Cn(a,o,r);let u=Date.now()-r;return m({provider:y,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},rawResponse:a,durationMs:u,status:"success",streaming:!1}),a}catch(a){let u=Date.now()-r;throw f({provider:y,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}async function*Cn(e,n,t){let r=[],o=null,s=null;try{for await(let a of e){r.push(a);let u=a;u.type==="response.done"&&u.response&&(o=u.response),yield a;}}catch(a){throw s=a instanceof Error?a:new Error(String(a)),a}finally{let a=Date.now()-t;s?f({provider:y,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:s,durationMs:a,streaming:true}):m({provider:y,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:o||{streamEvents:r},durationMs:a,status:"success",streaming:true});}}function be(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),a=Date.now()-r;return m({provider:y,model:o.model||"unknown",input:o.prompt,rawResponse:s,durationMs:a,status:"success",streaming:!1}),s}catch(s){let a=Date.now()-r;throw f({provider:y,model:o.model||"unknown",input:o.prompt,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function Ce(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),a=Date.now()-r;return m({provider:y,model:o.model||"unknown",input:o.input,rawResponse:s,durationMs:a,status:"success",streaming:!1,spanType:"embedding"}),s}catch(s){let a=Date.now()-r;throw f({provider:y,model:o.model||"unknown",input:o.input,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function ve(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let r of t)r.id&&n.push(r.id);return n}var R="anthropic";function Ie(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="Anthropic")return true;let t=e;return !!(t.messages&&typeof t.messages=="object")}function Se(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&In(a))return Tn(a,o,r);let u=Date.now()-r,c=a,i=m({provider:R,model:o.model||c.model||"unknown",input:{system:o.system,messages:o.messages},rawResponse:a,durationMs:u,status:"success",streaming:!1});if(i&&c.content){let d=Y(c.content);d.length>0&&k(d,i);}return a}catch(a){let u=Date.now()-r;throw f({provider:R,model:o.model||"unknown",input:{system:o.system,messages:o.messages},error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}function Te(e){return function(...t){let r=Date.now(),o=t[0]||{};try{let s=e(...t);return s&&typeof s=="object"?Sn(s,o,r):s}catch(s){let a=Date.now()-r;throw f({provider:R,model:o.model||"unknown",input:{system:o.system,messages:o.messages},error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:true}),s}}}function In(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}function Sn(e,n,t){let r=e;if(!r[Symbol.asyncIterator])return e;let o={content:[],usage:{input_tokens:0,output_tokens:0}},s=false,a,u=false,c=null,i=[],d=async function*(){try{for await(let l of r){if(l.type==="message_start"&&l.message&&(o.model=l.message.model,o.id=l.message.id,o.role=l.message.role,l.message.usage&&(o.usage={...l.message.usage})),l.type==="content_block_start"&&l.content_block&&(c=l.index??i.length,i[c]={...l.content_block},l.content_block.type==="text"&&(i[c].text=""),l.content_block.type==="thinking"&&(i[c].thinking="")),l.type==="content_block_delta"&&l.delta&&c!==null){let p=i[c];p&&(l.delta.text&&(u||(u=!0,a=Date.now()-t),p.type==="thinking"?p.thinking=(p.thinking||"")+l.delta.text:p.type==="text"&&(p.text=(p.text||"")+l.delta.text)),l.delta.partial_json&&p.type==="tool_use"&&(p._inputJson=(p._inputJson||"")+l.delta.partial_json));}if(l.type==="content_block_stop"&&c!==null){let p=i[c];if(p&&p.type==="tool_use"){let g=p._inputJson;if(g){try{p.input=JSON.parse(g);}catch{}delete p._inputJson;}}c=null;}l.type==="message_delta"&&(l.usage?.output_tokens&&(o.usage.output_tokens=l.usage.output_tokens),l.delta?.stop_reason&&(o.stop_reason=l.delta.stop_reason)),yield l;}}catch(l){if(!s){s=true;let p=Date.now()-t;f({provider:R,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:l instanceof Error?l:new Error(String(l)),durationMs:p,streaming:true});}throw l}finally{if(!s){s=true;let l=Date.now()-t;o.content=i.filter(Boolean);let p=m({provider:R,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:o,durationMs:l,status:"success",streaming:true,firstTokenMs:a});if(p&&o.content){let g=Y(o.content);g.length>0&&k(g,p);}}}};return new Proxy(e,{get(l,p,g){return p===Symbol.asyncIterator?()=>d()[Symbol.asyncIterator]():Reflect.get(l,p,g)}})}async function*Tn(e,n,t){let r={content:[],usage:{input_tokens:0,output_tokens:0}},o=null,s,a=false,u=null,c=[];try{for await(let i of e){if(i.type==="message_start"&&i.message&&(r.model=i.message.model,r.id=i.message.id,r.role=i.message.role,i.message.usage&&(r.usage={...i.message.usage})),i.type==="content_block_start"&&i.content_block&&(u=i.index??c.length,c[u]={...i.content_block},i.content_block.type==="text"&&(c[u].text=""),i.content_block.type==="thinking"&&(c[u].thinking="")),i.type==="content_block_delta"&&i.delta&&u!==null){let d=c[u];d&&(i.delta.text&&(a||(a=!0,s=Date.now()-t),d.type==="thinking"?d.thinking=(d.thinking||"")+i.delta.text:d.type==="text"&&(d.text=(d.text||"")+i.delta.text)),i.delta.partial_json&&d.type==="tool_use"&&(d._inputJson=(d._inputJson||"")+i.delta.partial_json));}if(i.type==="content_block_stop"&&u!==null){let d=c[u];if(d&&d.type==="tool_use"){let l=d._inputJson;if(l){try{d.input=JSON.parse(l);}catch{}delete d._inputJson;}}u=null;}i.type==="message_delta"&&(i.usage?.output_tokens&&(r.usage.output_tokens=i.usage.output_tokens),i.delta?.stop_reason&&(r.stop_reason=i.delta.stop_reason)),yield i;}}catch(i){throw o=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t;if(r.content=c.filter(Boolean),o)f({provider:R,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:o,durationMs:i,streaming:true});else {let d=m({provider:R,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:r,durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(d&&r.content){let l=Y(r.content);l.length>0&&k(l,d);}}}}function Y(e){let n=[];for(let t of e)t.type==="tool_use"&&t.id&&n.push(t.id);return n}var C="bedrock";function Re(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="BedrockRuntimeClient")return true;let t=e;return typeof t.send!="function"||!t.config||typeof t.config!="object"?false:"region"in t.config}function xe(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="send"&&typeof s=="function"?xn(s.bind(t)):s}})}function xn(e){return async function(t){switch(t.constructor?.name||""){case "ConverseCommand":return _n(e,t);case "ConverseStreamCommand":return En(e,t);case "InvokeModelCommand":return An(e,t);case "InvokeModelWithResponseStreamCommand":return Pn(e,t);default:return e(t)}}}async function _n(e,n){let t=Date.now(),r=n.input;try{let o=await e(n),s=Date.now()-t,a=m({provider:C,model:r.modelId||"unknown",input:{system:r.system,messages:r.messages},rawResponse:_e(o),durationMs:s,status:"success",streaming:!1});if(a){let u=Ee(o);u.length>0&&k(u,a);}return o}catch(o){throw f({provider:C,model:r.modelId||"unknown",input:{system:r.system,messages:r.messages},error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:false}),o}}async function En(e,n){let t=Date.now(),r=n.input;try{let o=await e(n);return o.stream?{...o,stream:Mn(o.stream,r,t)}:o}catch(o){throw f({provider:C,model:r.modelId||"unknown",input:{system:r.system,messages:r.messages},error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:true}),o}}async function*Mn(e,n,t){let r={output:{message:{role:"assistant",content:[]}},usage:{inputTokens:0,outputTokens:0}},o=null,s,a=false,u=new Map,c=new Map;try{for await(let i of e){if(i.contentBlockStart){let d=i.contentBlockStart.contentBlockIndex;if(i.contentBlockStart.start?.toolUse){let l=i.contentBlockStart.start.toolUse;u.set(d,{toolUse:{toolUseId:l.toolUseId,name:l.name,input:{}}}),c.set(d,"");}else u.set(d,{text:""});}if(i.contentBlockDelta){let d=i.contentBlockDelta.contentBlockIndex,l=u.get(d);if(l&&i.contentBlockDelta.delta?.text&&(a||(a=!0,s=Date.now()-t),l.text=(l.text||"")+i.contentBlockDelta.delta.text),l?.toolUse&&i.contentBlockDelta.delta?.toolUse?.input){let p=c.get(d)||"";c.set(d,p+i.contentBlockDelta.delta.toolUse.input);}}if(i.contentBlockStop){let d=i.contentBlockStop.contentBlockIndex,l=u.get(d),p=c.get(d);if(l?.toolUse&&p)try{l.toolUse.input=JSON.parse(p);}catch{}}i.messageStop?.stopReason&&(r.stopReason=i.messageStop.stopReason),i.metadata?.usage&&(r.usage={inputTokens:i.metadata.usage.inputTokens||0,outputTokens:i.metadata.usage.outputTokens||0}),yield i;}}catch(i){throw o=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t,d=Array.from(u.entries()).sort((l,p)=>l[0]-p[0]).map(([,l])=>l);if(r.output.message.content=d,o)f({provider:C,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},error:o,durationMs:i,streaming:true});else {let l=m({provider:C,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},rawResponse:_e(r),durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(l){let p=Ee(r);p.length>0&&k(p,l);}}}}async function An(e,n){let t=Date.now(),r=n.input;try{let o=await e(n),s=Date.now()-t,a=On(o.body);return m({provider:C,model:r.modelId||"unknown",input:D(r.body),rawResponse:a,durationMs:s,status:"success",streaming:!1}),o}catch(o){throw f({provider:C,model:r.modelId||"unknown",input:D(r.body),error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:false}),o}}async function Pn(e,n){let t=Date.now(),r=n.input;try{let o=await e(n);return o.body?{...o,body:Dn(o.body,r,t)}:o}catch(o){throw f({provider:C,model:r.modelId||"unknown",input:D(r.body),error:o instanceof Error?o:new Error(String(o)),durationMs:Date.now()-t,streaming:true}),o}}async function*Dn(e,n,t){let r=[],o=null;try{for await(let s of e){if(s.chunk?.bytes){let a=Gn(s.chunk.bytes);a&&r.push(a);}yield s;}}catch(s){throw o=s instanceof Error?s:new Error(String(s)),s}finally{let s=Date.now()-t;o?f({provider:C,model:n.modelId||"unknown",input:D(n.body),error:o,durationMs:s,streaming:true}):m({provider:C,model:n.modelId||"unknown",input:D(n.body),rawResponse:{streamEvents:r},durationMs:s,status:"success",streaming:true});}}function _e(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function Ee(e){let n=[],t=e.output?.message?.content;if(Array.isArray(t))for(let r of t)r.toolUse?.toolUseId&&n.push(r.toolUse.toolUseId);return n}function D(e){try{let n=typeof e=="string"?e:new TextDecoder().decode(e);return JSON.parse(n)}catch{return e}}function On(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}function Gn(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}var I="gemini";function Me(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let t=e;return typeof t.generateContent=="function"&&typeof t.generateContentStream=="function"&&typeof t.model=="string"}function Ae(e){if(!e||typeof e!="object")return false;let n=e.constructor?.name;if(n==="GoogleGenerativeAI"||n==="GoogleGenAI")return true;let t=e;return !!(typeof t.getGenerativeModel=="function"||t.models&&typeof t.models.generate=="function"||Me(e))}function Pe(e){if(Me(e)){let t=e;return De(t,t.model)}let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="getGenerativeModel"&&typeof s=="function"?jn(s.bind(t)):s}})}function jn(e){return function(t){let r=e(t);return De(r,t.model)}}function De(e,n){return new Proxy(e,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="generateContent"&&typeof s=="function"?Un(s.bind(t),n):r==="generateContentStream"&&typeof s=="function"?Nn(s.bind(t),n):r==="startChat"&&typeof s=="function"?qn(s.bind(t),n):s}})}function Un(e,n){return async function(r){let o=Date.now(),s=Ge(r);try{let a=await e(r),u=Date.now()-o,c=Be(a.response),i=m({provider:I,model:n,input:s,rawResponse:c,durationMs:u,status:"success",streaming:!1});if(i){let d=je(a.response);d.length>0&&k(d,i);}return a}catch(a){throw f({provider:I,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function Nn(e,n){return async function(r){let o=Date.now(),s=Ge(r);try{let a=await e(r),u=Oe(a.stream,n,s,o);return {...a,stream:u}}catch(a){throw f({provider:I,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}async function*Oe(e,n,t,r){let o={candidates:[{content:{parts:[]}}]},s=null,a,u=false;try{for await(let c of e){try{let i=c.text();if(i){u||(u=!0,a=Date.now()-r);let d=o.candidates[0].content?.parts||[],l=d[d.length-1];l?.text!==void 0?l.text+=i:d.push({text:i});}}catch{}if(c.candidates?.[0]?.content?.parts)for(let i of c.candidates[0].content.parts)i.functionCall&&o.candidates[0].content?.parts?.push(i);c.usageMetadata&&(o.usageMetadata=c.usageMetadata),c.candidates?.[0]?.finishReason&&(o.candidates[0].finishReason=c.candidates[0].finishReason),yield c;}}catch(c){throw s=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-r;if(s)f({provider:I,model:n,input:t,error:s,durationMs:c,streaming:true});else {let i=m({provider:I,model:n,input:t,rawResponse:o,durationMs:c,status:"success",streaming:true,firstTokenMs:a});if(i){let d=Jn(o.candidates);d.length>0&&k(d,i);}}}}function qn(e,n){return function(r){let o=e(r);return $n(o,n)}}function $n(e,n){return new Proxy(e,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="sendMessage"&&typeof s=="function"?Ln(s.bind(t),n):r==="sendMessageStream"&&typeof s=="function"?Kn(s.bind(t),n):s}})}function Ln(e,n){return async function(r){let o=Date.now(),s=r;try{let a=await e(r),u=Date.now()-o,c=Be(a.response),i=m({provider:I,model:n,input:s,rawResponse:c,durationMs:u,status:"success",streaming:!1});if(i){let d=je(a.response);d.length>0&&k(d,i);}return a}catch(a){throw f({provider:I,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function Kn(e,n){return async function(r){let o=Date.now(),s=r;try{let a=await e(r),u=Oe(a.stream,n,s,o);return {...a,stream:u}}catch(a){throw f({provider:I,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}function Ge(e){return typeof e=="string"?e:e.contents?e.contents:e}function Be(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function je(e){let n=[],t=e.candidates?.[0]?.content?.parts;return t&&t.forEach((r,o)=>{r.functionCall?.name&&n.push(`gemini-fc-${r.functionCall.name}-${o}`);}),n}function Jn(e){let n=[],t=e?.[0]?.content?.parts;return t&&t.forEach((r,o)=>{r.functionCall?.name&&n.push(`gemini-fc-${r.functionCall.name}-${o}`);}),n}var zn="openrouter.ai",N="openrouter";function Ue(e){if(!e||typeof e!="object")return false;let n=e;return n.chat?.completions?.create?(n.baseURL||"").includes(zn):false}function Ne(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="chat"&&s&&typeof s=="object"?Vn(s):s}})}function Vn(e){return e&&new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="completions"&&o&&typeof o=="object"?Hn(o):o}})}function Hn(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?Wn(o.bind(n)):o}})}function Wn(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let a=await e(...t);if(s&&Yn(a))return Xn(a,o,r);let u=Date.now()-r,c=a;return m({provider:N,model:o.model||c.model||"unknown",input:o.messages,rawResponse:a,durationMs:u,status:"success",streaming:!1}),a}catch(a){let u=Date.now()-r;throw f({provider:N,model:o.model||"unknown",input:o.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:u,streaming:s}),a}}}function Yn(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Xn(e,n,t){let r={choices:[{message:{content:"",role:"assistant"},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,s,a=false;try{for await(let u of e){let c=u;!r.id&&c.id&&(r.id=c.id);let i=c.choices?.[0]?.delta?.content;i&&(a||(a=!0,s=Date.now()-t),r.choices[0].message.content+=i);let d=c.choices?.[0]?.finish_reason;d&&(r.choices[0].finish_reason=d),c.usage&&(r.usage=c.usage),yield u;}}catch(u){throw o=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-t;o?f({provider:N,model:n.model||"unknown",input:n.messages,error:o,durationMs:u,streaming:true}):m({provider:N,model:n.model||"unknown",input:n.messages,rawResponse:r,durationMs:u,status:"success",streaming:true,firstTokenMs:s});}}function qe(e,n){return n&&fe(n),j().disabled?(w("Tracing disabled, returning unwrapped client"),e):Ue(e)?(x("openrouter"),Ne(e)):we(e)?(x("openai"),Qn(e)):Ie(e)?(x("anthropic"),st(e)):Re(e)?(x("bedrock"),xe(e)):Ae(e)?(x("gemini"),Pe(e)):(O("Unknown client type. Tracing not enabled. Supported: OpenAI, OpenRouter, Anthropic, Bedrock, Gemini"),e)}function Qn(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="chat"&&s&&typeof s=="object"?et(s):r==="responses"&&s&&typeof s=="object"?tt(s):r==="completions"&&s&&typeof s=="object"?rt(s):r==="embeddings"&&s&&typeof s=="object"?ot(s):s}})}function et(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="completions"&&o&&typeof o=="object"?nt(o):o}})}function nt(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?ke(o.bind(n)):o}})}function tt(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?he(o.bind(n)):o}})}function rt(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?be(o.bind(n)):o}})}function ot(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?Ce(o.bind(n)):o}})}function st(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="messages"&&s&&typeof s=="object"?at(s):s}})}function at(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?Se(o.bind(n)):t==="stream"&&typeof o=="function"?Te(o.bind(n)):o}})}function it(e){return function(t,r){return qe(t,{...e,...r})}}
3
- export{V as captureSpan,it as createObserve,rn as flush,b as getTraceContext,nn as init,tn as isEnabled,qe as observe,hn as span,gn as trace};//# sourceMappingURL=index.mjs.map
2
+ var X=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ve=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var se=Ve((xt,Ze)=>{Ze.exports={name:"@lelemondev/sdk",version:"0.10.0",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],"google-genai":["./dist/google-genai.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@anthropic-ai/sdk":"^0.82.0","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",vite:"^6.0.0",typedoc:"^0.28.18",typescript:"^6.0.0",vitest:"^4.0.0"}};});var Z=false;function Q(e){Z=e;}function v(){return Z?true:He("LELEMON_DEBUG")==="true"}var h="[Lelemon]";function k(e,n){v()&&K("debug",e,n);}function $(e,n){v()&&K("info",e,n);}function G(e,n){K("warn",e,n);}function L(e,n,t,o){v()&&console.log(`${h} Captured trace: provider=${e} model=${n} duration=${t}ms status=${o}`);}function O(e,n){console.error(`${h} Failed to capture trace: provider=${e} error=${n.message}`);}function R(e){v()&&console.log(`${h} Wrapped client: provider=${e}`);}function ee(e,n){v()&&console.log(`${h} Sending batch: count=${e} endpoint=${n}`);}function ne(e,n){v()&&console.log(`${h} Batch sent successfully: count=${e} duration=${n}ms`);}function te(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${h} Batch send failed: count=${e} error=${t}`);}function re(e,n,t){v()&&console.log(`${h} Request: ${e} ${n} (${t} bytes)`);}function oe(e,n){v()&&console.log(`${h} Response: status=${e} duration=${n}ms`);}function K(e,n,t){let o=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?o(`${h} ${n}`,t):o(`${h} ${n}`);}function He(e){if(typeof process<"u"&&process.env)return process.env[e]}var We=10,Ye=1e3,Xe=1e4,N=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(n){this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??We,flushIntervalMs:n.flushIntervalMs??Ye,requestTimeoutMs:n.requestTimeoutMs??Xe};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),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 n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).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(n){if(n.length===0)return;let t=Date.now();ee(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),ne(n.length,Date.now()-t);}catch(o){te(n.length,o);}}async request(n,t,o){let r=`${this.config.endpoint}${t}`,s=new AbortController,a=o?JSON.stringify(o):void 0;re(n,r,a?.length??0);let c=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),u=Date.now();try{let i=await fetch(r,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a,signal:s.signal});if(clearTimeout(c),oe(i.status,Date.now()-u),!i.ok){let l=await i.text().catch(()=>"Unknown error");throw new Error(`HTTP ${i.status}: ${l}`)}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 Qe="@lelemondev/sdk",en="nodejs";function nn(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function tn(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function rn(){try{if(typeof X<"u")return se().version??"unknown"}catch{}return "unknown"}var E=null;function ie(e){if(!E){let t=nn(),o=tn();E={"telemetry.sdk.name":Qe,"telemetry.sdk.version":rn(),"telemetry.sdk.language":en},t&&(E["process.runtime.name"]=t.name,E["process.runtime.version"]=t.version),o&&(E["os.type"]=o);}let n={...E};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var F={},T=null,J=null,ue="https://api.lelemon.dev";function sn(e={}){F=e,e.debug&&Q(true),J=ie(e.service),$("Initializing SDK",{endpoint:e.endpoint??ue,debug:e.debug??false,disabled:e.disabled??false,telemetry:J}),T=ce(e),T.isEnabled()?$("SDK initialized - tracing enabled"):k("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function j(){return F}function B(){return J}function an(){return x().isEnabled()}function x(){return T||(T=ce(F)),T}async function un(){T&&await T.flush();}function ce(e){let n=e.apiKey??cn("LELEMON_API_KEY");return !n&&!e.disabled&&G("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new N({apiKey:n??"",endpoint:e.endpoint??ue,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function cn(e){if(typeof process<"u"&&process.env)return process.env[e]}var z=Symbol.for("@lelemondev/sdk:globalContext");function pe(){let e=globalThis;return e[z]||(e[z]={context:{}}),e[z]}function fe(e){pe().context=e,k("Global context updated",e);}function A(){return pe().context}function m(e){try{let n=x();if(!n.isEnabled()){k("Transport disabled, skipping trace capture");return}let t=A(),o=C(),r=_(),s=B(),a={provider:e.provider,model:e.model,input:H(e.input),rawResponse:e.rawResponse?P(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:o?.sessionId??t.sessionId,userId:o?.userId??t.userId,traceId:o?.traceId,spanId:r,parentSpanId:o?.currentSpanId,metadata:{...t.metadata,...e.metadata,...o?{_traceName:o.name}:{},...s?{_telemetry:s}:{}},tags:t.tags,spanType:e.spanType,name:e.name};return L(e.provider,e.model,e.durationMs,e.status),n.enqueue(a),r}catch(n){O(e.provider,n instanceof Error?n:new Error(String(n)));return}}function f(e){try{let n=x();if(!n.isEnabled()){k("Transport disabled, skipping error capture");return}let t=A(),o=C(),r=B(),s={provider:e.provider,model:e.model,input:H(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:o?.sessionId??t.sessionId,userId:o?.userId??t.userId,traceId:o?.traceId,spanId:_(),parentSpanId:o?.currentSpanId,metadata:{...t.metadata,...e.metadata,...o?{_traceName:o.name}:{},...r?{_telemetry:r}:{}},tags:t.tags};L(e.provider,e.model,e.durationMs,"error"),k("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(s);}catch(n){O(e.provider,n instanceof Error?n:new Error(String(n)));}}function V(e){try{let n=x();if(!n.isEnabled()){k("Transport disabled, skipping span capture");return}let t=A(),o=C(),r=e.metadata?._traceId,s=e.metadata?._parentSpanId,a=B(),c={...t.metadata,...e.metadata,...a?{_telemetry:a}:{}};delete c._traceId,delete c._parentSpanId;let u={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:H(e.input),output:P(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:o?.sessionId??t.sessionId,userId:o?.userId??t.userId,traceId:r??o?.traceId,spanId:_(),parentSpanId:s??o?.currentSpanId,toolCallId:e.toolCallId,metadata:c,tags:t.tags};k(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(u);}catch(n){O("unknown",n instanceof Error?n:new Error(String(n)));}}var de=1e5,dn=["api_key","apikey","password","secret","authorization"],ln=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],pn=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],le={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function me(){return j().redaction??{}}function fn(e){let n=e.toLowerCase();return pn.includes(n)?false:!!(dn.some(o=>n.includes(o))||ln.some(o=>n.includes(o))||(me().keys??[]).some(o=>n.includes(o.toLowerCase())))}function mn(e){let n=me(),t=e;for(let o of n.patterns??[])o.lastIndex=0,t=t.replace(o,"[REDACTED]");return n.emails&&(t=t.replace(le.emails,"[EMAIL]")),n.phones&&(t=t.replace(le.phones,"[PHONE]")),t}function H(e){return P(e,0)}function P(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=mn(e);return t.length>de&&(t=t.slice(0,de)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>P(t,n+1));if(typeof e=="object"){let t={};for(let[o,r]of Object.entries(e))fn(o)?t[o]="[REDACTED]":t[o]=P(r,n+1);return t}return String(e)}var W=Symbol.for("@lelemondev/sdk:traceStorage");function wn(){let e=globalThis;return e[W]||(e[W]=new AsyncLocalStorage),e[W]}var ge=wn();function _(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function C(){return ge.getStore()}function g(e,n){let t=C();if(t)for(let o of e)t.pendingToolCalls.set(o,n),k(`Registered tool call ${o} \u2192 LLM span ${n}`);}function kn(e){let n=C();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function yn(e){let n=C();n&&n.pendingToolCalls.delete(e);}async function hn(e,n){let t=typeof e=="string"?{name:e}:e,o=C(),r=o?.traceId??_(),s=_(),a={traceId:r,rootSpanId:s,currentSpanId:s,parentSpanId:o?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,pendingToolCalls:new Map};return ge.run(a,async()=>{let c,u;try{return c=await n(),c}catch(i){throw u=i instanceof Error?i:new Error(String(i)),i}finally{vn(a,u?void 0:c,u);}})}var Cn=["text","content","message","output","response","result","answer"];function bn(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let r=e;return n in r?r[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let o=e;for(let r of Cn)if(r in o&&typeof o[r]=="string")return o[r];return e}function vn(e,n,t){let o=x();if(!o.isEnabled()){k("Transport disabled, skipping root span");return}let r=A(),s=Date.now()-e.startTime,a=t?null:bn(n,e.outputKey,e.outputTransform),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:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId??r.sessionId,userId:e.userId??r.userId,metadata:{...r.metadata,...e.metadata},tags:e.tags??r.tags};k(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),o.enqueue(c);}function In(e){let n=C();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=kn(e.toolCallId);V({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:n.traceId,_parentSpanId:t}}),e.toolCallId&&yn(e.toolCallId);}var y="openai";function we(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function ke(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&ye(a))return Sn(a,r,o);let c=Date.now()-o,u=a,i=m({provider:y,model:r.model||u.model||"unknown",input:r.messages,rawResponse:a,durationMs:c,status:"success",streaming:!1});if(i){let d=ve(u);d.length>0&&g(d,i);}return a}catch(a){let c=Date.now()-o;throw f({provider:y,model:r.model||"unknown",input:r.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}function ye(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Sn(e,n,t){let o={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},r=null,s,a=false,c=new Map;try{for await(let u of e){let i=u,d=i?.choices?.[0]?.delta?.content;d&&(a||(a=!0,s=Date.now()-t),o.choices[0].message.content+=d);let l=i?.choices?.[0]?.delta?.tool_calls;if(l)for(let w of l){c.has(w.index)||c.set(w.index,{id:"",function:{name:"",arguments:""}});let q=c.get(w.index);w.id&&(q.id=w.id),w.function?.name&&(q.function.name=w.function.name),w.function?.arguments&&(q.function.arguments+=w.function.arguments);}let p=i?.choices?.[0]?.finish_reason;p&&(o.choices[0].finish_reason=p),i?.usage&&(o.usage=i.usage),yield u;}}catch(u){throw r=u instanceof Error?u:new Error(String(u)),u}finally{let u=Date.now()-t;if(c.size>0&&(o.choices[0].message.tool_calls=Array.from(c.entries()).sort((i,d)=>i[0]-d[0]).map(([,i])=>i)),r)f({provider:y,model:n.model||"unknown",input:n.messages,error:r,durationMs:u,streaming:true});else {let i=m({provider:y,model:n.model||"unknown",input:n.messages,rawResponse:o,durationMs:u,status:"success",streaming:true,firstTokenMs:s});if(i){let d=ve(o);d.length>0&&g(d,i);}}}}function he(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&ye(a))return Rn(a,r,o);let c=Date.now()-o;return m({provider:y,model:r.model||"unknown",input:{instructions:r.instructions,input:r.input},rawResponse:a,durationMs:c,status:"success",streaming:!1}),a}catch(a){let c=Date.now()-o;throw f({provider:y,model:r.model||"unknown",input:{instructions:r.instructions,input:r.input},error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}async function*Rn(e,n,t){let o=[],r=null,s=null;try{for await(let a of e){o.push(a);let c=a;c.type==="response.done"&&c.response&&(r=c.response),yield a;}}catch(a){throw s=a instanceof Error?a:new Error(String(a)),a}finally{let a=Date.now()-t;s?f({provider:y,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:s,durationMs:a,streaming:true}):m({provider:y,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:r||{streamEvents:o},durationMs:a,status:"success",streaming:true});}}function Ce(e){return async function(...t){let o=Date.now(),r=t[0]||{};try{let s=await e(...t),a=Date.now()-o;return m({provider:y,model:r.model||"unknown",input:r.prompt,rawResponse:s,durationMs:a,status:"success",streaming:!1}),s}catch(s){let a=Date.now()-o;throw f({provider:y,model:r.model||"unknown",input:r.prompt,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function be(e){return async function(...t){let o=Date.now(),r=t[0]||{};try{let s=await e(...t),a=Date.now()-o;return m({provider:y,model:r.model||"unknown",input:r.input,rawResponse:s,durationMs:a,status:"success",streaming:!1,spanType:"embedding"}),s}catch(s){let a=Date.now()-o;throw f({provider:y,model:r.model||"unknown",input:r.input,error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:false}),s}}}function ve(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let o of t)o.id&&n.push(o.id);return n}var M="anthropic";function Ie(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="Anthropic")return true;let t=e;return !!(t.messages&&typeof t.messages=="object")}function Se(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&xn(a))return En(a,r,o);let c=Date.now()-o,u=a,i=m({provider:M,model:r.model||u.model||"unknown",input:{system:r.system,messages:r.messages},rawResponse:a,durationMs:c,status:"success",streaming:!1});if(i&&u.content){let d=Y(u.content);d.length>0&&g(d,i);}return a}catch(a){let c=Date.now()-o;throw f({provider:M,model:r.model||"unknown",input:{system:r.system,messages:r.messages},error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}function Re(e){return function(...t){let o=Date.now(),r=t[0]||{};try{let s=e(...t);return s&&typeof s=="object"?Mn(s,r,o):s}catch(s){let a=Date.now()-o;throw f({provider:M,model:r.model||"unknown",input:{system:r.system,messages:r.messages},error:s instanceof Error?s:new Error(String(s)),durationMs:a,streaming:true}),s}}}function xn(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}function Mn(e,n,t){let o=e;if(!o[Symbol.asyncIterator])return e;let r={content:[],usage:{input_tokens:0,output_tokens:0}},s=false,a,c=false,u=null,i=[],d=async function*(){try{for await(let l of o){if(l.type==="message_start"&&l.message&&(r.model=l.message.model,r.id=l.message.id,r.role=l.message.role,l.message.usage&&(r.usage={...l.message.usage})),l.type==="content_block_start"&&l.content_block&&(u=l.index??i.length,i[u]={...l.content_block},l.content_block.type==="text"&&(i[u].text=""),l.content_block.type==="thinking"&&(i[u].thinking="")),l.type==="content_block_delta"&&l.delta&&u!==null){let p=i[u];p&&(l.delta.text&&(c||(c=!0,a=Date.now()-t),p.type==="thinking"?p.thinking=(p.thinking||"")+l.delta.text:p.type==="text"&&(p.text=(p.text||"")+l.delta.text)),l.delta.partial_json&&p.type==="tool_use"&&(p._inputJson=(p._inputJson||"")+l.delta.partial_json));}if(l.type==="content_block_stop"&&u!==null){let p=i[u];if(p&&p.type==="tool_use"){let w=p._inputJson;if(w){try{p.input=JSON.parse(w);}catch{}delete p._inputJson;}}u=null;}l.type==="message_delta"&&(l.usage?.output_tokens&&(r.usage.output_tokens=l.usage.output_tokens),l.delta?.stop_reason&&(r.stop_reason=l.delta.stop_reason)),yield l;}}catch(l){if(!s){s=true;let p=Date.now()-t;f({provider:M,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:l instanceof Error?l:new Error(String(l)),durationMs:p,streaming:true});}throw l}finally{if(!s){s=true;let l=Date.now()-t;r.content=i.filter(Boolean);let p=m({provider:M,model:r.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:r,durationMs:l,status:"success",streaming:true,firstTokenMs:a});if(p&&r.content){let w=Y(r.content);w.length>0&&g(w,p);}}}};return new Proxy(e,{get(l,p,w){return p===Symbol.asyncIterator?()=>d()[Symbol.asyncIterator]():Reflect.get(l,p,w)}})}async function*En(e,n,t){let o={content:[],usage:{input_tokens:0,output_tokens:0}},r=null,s,a=false,c=null,u=[];try{for await(let i of e){if(i.type==="message_start"&&i.message&&(o.model=i.message.model,o.id=i.message.id,o.role=i.message.role,i.message.usage&&(o.usage={...i.message.usage})),i.type==="content_block_start"&&i.content_block&&(c=i.index??u.length,u[c]={...i.content_block},i.content_block.type==="text"&&(u[c].text=""),i.content_block.type==="thinking"&&(u[c].thinking="")),i.type==="content_block_delta"&&i.delta&&c!==null){let d=u[c];d&&(i.delta.text&&(a||(a=!0,s=Date.now()-t),d.type==="thinking"?d.thinking=(d.thinking||"")+i.delta.text:d.type==="text"&&(d.text=(d.text||"")+i.delta.text)),i.delta.partial_json&&d.type==="tool_use"&&(d._inputJson=(d._inputJson||"")+i.delta.partial_json));}if(i.type==="content_block_stop"&&c!==null){let d=u[c];if(d&&d.type==="tool_use"){let l=d._inputJson;if(l){try{d.input=JSON.parse(l);}catch{}delete d._inputJson;}}c=null;}i.type==="message_delta"&&(i.usage?.output_tokens&&(o.usage.output_tokens=i.usage.output_tokens),i.delta?.stop_reason&&(o.stop_reason=i.delta.stop_reason)),yield i;}}catch(i){throw r=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t;if(o.content=u.filter(Boolean),r)f({provider:M,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},error:r,durationMs:i,streaming:true});else {let d=m({provider:M,model:o.model||n.model||"unknown",input:{system:n.system,messages:n.messages},rawResponse:o,durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(d&&o.content){let l=Y(o.content);l.length>0&&g(l,d);}}}}function Y(e){let n=[];for(let t of e)t.type==="tool_use"&&t.id&&n.push(t.id);return n}var b="bedrock";function Te(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="BedrockRuntimeClient")return true;let t=e;return typeof t.send!="function"||!t.config||typeof t.config!="object"?false:"region"in t.config}function xe(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="send"&&typeof s=="function"?Pn(s.bind(t)):s}})}function Pn(e){return async function(t){switch(t.constructor?.name||""){case "ConverseCommand":return An(e,t);case "ConverseStreamCommand":return Dn(e,t);case "InvokeModelCommand":return On(e,t);case "InvokeModelWithResponseStreamCommand":return Nn(e,t);default:return e(t)}}}async function An(e,n){let t=Date.now(),o=n.input;try{let r=await e(n),s=Date.now()-t,a=m({provider:b,model:o.modelId||"unknown",input:{system:o.system,messages:o.messages},rawResponse:Me(r),durationMs:s,status:"success",streaming:!1});if(a){let c=Ee(r);c.length>0&&g(c,a);}return r}catch(r){throw f({provider:b,model:o.modelId||"unknown",input:{system:o.system,messages:o.messages},error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:false}),r}}async function Dn(e,n){let t=Date.now(),o=n.input;try{let r=await e(n);return r.stream?{...r,stream:Gn(r.stream,o,t)}:r}catch(r){throw f({provider:b,model:o.modelId||"unknown",input:{system:o.system,messages:o.messages},error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:true}),r}}async function*Gn(e,n,t){let o={output:{message:{role:"assistant",content:[]}},usage:{inputTokens:0,outputTokens:0}},r=null,s,a=false,c=new Map,u=new Map;try{for await(let i of e){if(i.contentBlockStart){let d=i.contentBlockStart.contentBlockIndex;if(i.contentBlockStart.start?.toolUse){let l=i.contentBlockStart.start.toolUse;c.set(d,{toolUse:{toolUseId:l.toolUseId,name:l.name,input:{}}}),u.set(d,"");}else c.set(d,{text:""});}if(i.contentBlockDelta){let d=i.contentBlockDelta.contentBlockIndex,l=c.get(d);if(l&&i.contentBlockDelta.delta?.text&&(a||(a=!0,s=Date.now()-t),l.text=(l.text||"")+i.contentBlockDelta.delta.text),l?.toolUse&&i.contentBlockDelta.delta?.toolUse?.input){let p=u.get(d)||"";u.set(d,p+i.contentBlockDelta.delta.toolUse.input);}}if(i.contentBlockStop){let d=i.contentBlockStop.contentBlockIndex,l=c.get(d),p=u.get(d);if(l?.toolUse&&p)try{l.toolUse.input=JSON.parse(p);}catch{}}i.messageStop?.stopReason&&(o.stopReason=i.messageStop.stopReason),i.metadata?.usage&&(o.usage={inputTokens:i.metadata.usage.inputTokens||0,outputTokens:i.metadata.usage.outputTokens||0}),yield i;}}catch(i){throw r=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t,d=Array.from(c.entries()).sort((l,p)=>l[0]-p[0]).map(([,l])=>l);if(o.output.message.content=d,r)f({provider:b,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},error:r,durationMs:i,streaming:true});else {let l=m({provider:b,model:n.modelId||"unknown",input:{system:n.system,messages:n.messages},rawResponse:Me(o),durationMs:i,status:"success",streaming:true,firstTokenMs:s});if(l){let p=Ee(o);p.length>0&&g(p,l);}}}}async function On(e,n){let t=Date.now(),o=n.input;try{let r=await e(n),s=Date.now()-t,a=Bn(r.body);return m({provider:b,model:o.modelId||"unknown",input:D(o.body),rawResponse:a,durationMs:s,status:"success",streaming:!1}),r}catch(r){throw f({provider:b,model:o.modelId||"unknown",input:D(o.body),error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:false}),r}}async function Nn(e,n){let t=Date.now(),o=n.input;try{let r=await e(n);return r.body?{...r,body:jn(r.body,o,t)}:r}catch(r){throw f({provider:b,model:o.modelId||"unknown",input:D(o.body),error:r instanceof Error?r:new Error(String(r)),durationMs:Date.now()-t,streaming:true}),r}}async function*jn(e,n,t){let o=[],r=null;try{for await(let s of e){if(s.chunk?.bytes){let a=Un(s.chunk.bytes);a&&o.push(a);}yield s;}}catch(s){throw r=s instanceof Error?s:new Error(String(s)),s}finally{let s=Date.now()-t;r?f({provider:b,model:n.modelId||"unknown",input:D(n.body),error:r,durationMs:s,streaming:true}):m({provider:b,model:n.modelId||"unknown",input:D(n.body),rawResponse:{streamEvents:o},durationMs:s,status:"success",streaming:true});}}function Me(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function Ee(e){let n=[],t=e.output?.message?.content;if(Array.isArray(t))for(let o of t)o.toolUse?.toolUseId&&n.push(o.toolUse.toolUseId);return n}function D(e){try{let n=typeof e=="string"?e:new TextDecoder().decode(e);return JSON.parse(n)}catch{return e}}function Bn(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}function Un(e){try{let n=new TextDecoder().decode(e);return JSON.parse(n)}catch{return null}}var I="gemini";function _e(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GoogleGenAI")return true;let t=e;return !!(t.models&&typeof t.models=="object"&&typeof t.models.generateContent=="function"&&t.chats&&typeof t.chats=="object")}function Pe(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="models"&&s&&typeof s=="object"?$n(s):o==="chats"&&s&&typeof s=="object"?Jn(s):s}})}function $n(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="generateContent"&&typeof r=="function"?Ln(r.bind(n)):t==="generateContentStream"&&typeof r=="function"?Kn(r.bind(n)):r}})}function Ln(e){return async function(t){let o=Date.now(),r=t.model,s=De(t);try{let a=await e(t),c=Date.now()-o,u=Ge(a),i=m({provider:I,model:r,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Oe(a);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:I,model:r,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:false}),a}}}function Kn(e){return async function(t){let o=Date.now(),r=t.model,s=De(t);try{let a=await e(t);return Ae(a,r,s,o)}catch(a){throw f({provider:I,model:r,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-o,streaming:true}),a}}}async function*Ae(e,n,t,o){let r={candidates:[{content:{parts:[]}}]},s=null,a,c=false;try{for await(let u of e){let i=u.text;if(i){c||(c=!0,a=Date.now()-o);let d=r.candidates[0].content?.parts||[],l=d[d.length-1];l?.text!==void 0?l.text+=i:d.push({text:i});}if(u.candidates?.[0]?.content?.parts)for(let d of u.candidates[0].content.parts)d.functionCall&&r.candidates[0].content?.parts?.push(d);u.usageMetadata&&(r.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(r.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()-o;if(s)f({provider:I,model:n,input:t,error:s,durationMs:u,streaming:true});else {let i=m({provider:I,model:n,input:t,rawResponse:r,durationMs:u,status:"success",streaming:true,firstTokenMs:a});if(i){let d=Wn(r.candidates);d.length>0&&g(d,i);}}}}function Jn(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?Fn(r.bind(n)):r}})}function Fn(e){return function(t){let o=e(t);return zn(o,t.model)}}function zn(e,n){return new Proxy(e,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="sendMessage"&&typeof s=="function"?Vn(s.bind(t),n):o==="sendMessageStream"&&typeof s=="function"?Hn(s.bind(t),n):s}})}function Vn(e,n){return async function(o){let r=Date.now(),s=o.message;try{let a=await e(o),c=Date.now()-r,u=Ge(a),i=m({provider:I,model:n,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Oe(a);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:I,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:false}),a}}}function Hn(e,n){return async function(o){let r=Date.now(),s=o.message;try{let a=await e(o);return Ae(a,n,s,r)}catch(a){throw f({provider:I,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:true}),a}}}function De(e){return e.contents}function Ge(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata,modelVersion:e.modelVersion}}function Oe(e){let n=[],t=e.candidates?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}function Wn(e){let n=[],t=e?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}var S="gemini";function Ne(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="GenerativeModel")return true;let t=e;return typeof t.generateContent=="function"&&typeof t.generateContentStream=="function"&&typeof t.model=="string"}function je(e){return !e||typeof e!="object"?false:!!(e.constructor?.name==="GoogleGenerativeAI"||typeof e.getGenerativeModel=="function"||Ne(e))}function Be(e){if(Ne(e)){let t=e;return Ue(t,t.model)}let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="getGenerativeModel"&&typeof s=="function"?Xn(s.bind(t)):s}})}function Xn(e){return function(t){let o=e(t);return Ue(o,t.model)}}function Ue(e,n){return new Proxy(e,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="generateContent"&&typeof s=="function"?Zn(s.bind(t),n):o==="generateContentStream"&&typeof s=="function"?Qn(s.bind(t),n):o==="startChat"&&typeof s=="function"?et(s.bind(t),n):s}})}function Zn(e,n){return async function(o){let r=Date.now(),s=$e(o);try{let a=await e(o),c=Date.now()-r,u=Le(a.response),i=m({provider:S,model:n,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Ke(a.response);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:false}),a}}}function Qn(e,n){return async function(o){let r=Date.now(),s=$e(o);try{let a=await e(o),c=qe(a.stream,n,s,r);return {...a,stream:c}}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:true}),a}}}async function*qe(e,n,t,o){let r={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()-o);let d=r.candidates[0].content?.parts||[],l=d[d.length-1];l?.text!==void 0?l.text+=i:d.push({text:i});}}catch{}if(u.candidates?.[0]?.content?.parts)for(let i of u.candidates[0].content.parts)i.functionCall&&r.candidates[0].content?.parts?.push(i);u.usageMetadata&&(r.usageMetadata=u.usageMetadata),u.candidates?.[0]?.finishReason&&(r.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()-o;if(s)f({provider:S,model:n,input:t,error:s,durationMs:u,streaming:true});else {let i=m({provider:S,model:n,input:t,rawResponse:r,durationMs:u,status:"success",streaming:true,firstTokenMs:a});if(i){let d=ot(r.candidates);d.length>0&&g(d,i);}}}}function et(e,n){return function(o){let r=e(o);return nt(r,n)}}function nt(e,n){return new Proxy(e,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="sendMessage"&&typeof s=="function"?tt(s.bind(t),n):o==="sendMessageStream"&&typeof s=="function"?rt(s.bind(t),n):s}})}function tt(e,n){return async function(o){let r=Date.now(),s=o;try{let a=await e(o),c=Date.now()-r,u=Le(a.response),i=m({provider:S,model:n,input:s,rawResponse:u,durationMs:c,status:"success",streaming:!1});if(i){let d=Ke(a.response);d.length>0&&g(d,i);}return a}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:false}),a}}}function rt(e,n){return async function(o){let r=Date.now(),s=o;try{let a=await e(o),c=qe(a.stream,n,s,r);return {...a,stream:c}}catch(a){throw f({provider:S,model:n,input:s,error:a instanceof Error?a:new Error(String(a)),durationMs:Date.now()-r,streaming:true}),a}}}function $e(e){return typeof e=="string"?e:e.contents?e.contents:e}function Le(e){return {candidates:e.candidates,usageMetadata:e.usageMetadata}}function Ke(e){let n=[],t=e.candidates?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}function ot(e){let n=[],t=e?.[0]?.content?.parts;return t&&t.forEach((o,r)=>{o.functionCall?.name&&n.push(`gemini-fc-${o.functionCall.name}-${r}`);}),n}var at="openrouter.ai",U="openrouter";function Je(e){if(!e||typeof e!="object")return false;let n=e;return n.chat?.completions?.create?(n.baseURL||"").includes(at):false}function Fe(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="chat"&&s&&typeof s=="object"?it(s):s}})}function it(e){return e&&new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="completions"&&r&&typeof r=="object"?ut(r):r}})}function ut(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?ct(r.bind(n)):r}})}function ct(e){return async function(...t){let o=Date.now(),r=t[0]||{},s=r.stream===true;try{let a=await e(...t);if(s&&dt(a))return lt(a,r,o);let c=Date.now()-o,u=a;return m({provider:U,model:r.model||u.model||"unknown",input:r.messages,rawResponse:a,durationMs:c,status:"success",streaming:!1}),a}catch(a){let c=Date.now()-o;throw f({provider:U,model:r.model||"unknown",input:r.messages,error:a instanceof Error?a:new Error(String(a)),durationMs:c,streaming:s}),a}}}function dt(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*lt(e,n,t){let o={choices:[{message:{content:"",role:"assistant"},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},r=null,s,a=false;try{for await(let c of e){let u=c;!o.id&&u.id&&(o.id=u.id);let i=u.choices?.[0]?.delta?.content;i&&(a||(a=!0,s=Date.now()-t),o.choices[0].message.content+=i);let d=u.choices?.[0]?.finish_reason;d&&(o.choices[0].finish_reason=d),u.usage&&(o.usage=u.usage),yield c;}}catch(c){throw r=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-t;r?f({provider:U,model:n.model||"unknown",input:n.messages,error:r,durationMs:c,streaming:true}):m({provider:U,model:n.model||"unknown",input:n.messages,rawResponse:o,durationMs:c,status:"success",streaming:true,firstTokenMs:s});}}function ze(e,n){return n&&fe(n),j().disabled?(k("Tracing disabled, returning unwrapped client"),e):Je(e)?(R("openrouter"),Fe(e)):we(e)?(R("openai"),ft(e)):Ie(e)?(R("anthropic"),ht(e)):Te(e)?(R("bedrock"),xe(e)):_e(e)?(R("gemini"),Pe(e)):je(e)?(R("gemini"),Be(e)):(G("Unknown client type. Tracing not enabled. Supported: OpenAI, OpenRouter, Anthropic, Bedrock, Gemini"),e)}function ft(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="chat"&&s&&typeof s=="object"?mt(s):o==="responses"&&s&&typeof s=="object"?wt(s):o==="completions"&&s&&typeof s=="object"?kt(s):o==="embeddings"&&s&&typeof s=="object"?yt(s):s}})}function mt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="completions"&&r&&typeof r=="object"?gt(r):r}})}function gt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?ke(r.bind(n)):r}})}function wt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?he(r.bind(n)):r}})}function kt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?Ce(r.bind(n)):r}})}function yt(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?be(r.bind(n)):r}})}function ht(e){let n=e;return new Proxy(n,{get(t,o,r){let s=Reflect.get(t,o,r);return o==="messages"&&s&&typeof s=="object"?Ct(s):s}})}function Ct(e){return new Proxy(e,{get(n,t,o){let r=Reflect.get(n,t,o);return t==="create"&&typeof r=="function"?Se(r.bind(n)):t==="stream"&&typeof r=="function"?Re(r.bind(n)):r}})}function bt(e){return function(t,o){return ze(t,{...e,...o})}}
3
+ export{V as captureSpan,bt as createObserve,un as flush,C as getTraceContext,sn as init,an as isEnabled,ze as observe,In as span,hn as trace};//# sourceMappingURL=index.mjs.map
4
4
  //# sourceMappingURL=index.mjs.map
package/dist/openai.js CHANGED
@@ -1,4 +1,4 @@
1
1
  'use strict';var async_hooks=require('async_hooks');/* @lelemondev/sdk - LLM Observability */
2
- var be=Object.defineProperty;var he=(e,n,t)=>n in e?be(e,n,{enumerable:true,configurable:true,writable:true,value:t}):e[n]=t;var B=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ke=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var I=(e,n,t)=>he(e,typeof n!="symbol"?n+"":n,t);var ee=ke((mn,Se)=>{Se.exports={name:"@lelemondev/sdk",version:"0.9.9",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/generative-ai":"^0.24.1","@types/node":"^20.0.0","@vitest/coverage-v8":"^2.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",typedoc:"^0.28.15",typescript:"^5.9.3",vitest:"^2.0.0"}};});var V=false;function H(e){V=e;}function w(){return V?true:Te("LELEMON_DEBUG")==="true"}var f="[Lelemon]";function d(e,n){w()&&j("debug",e,n);}function P(e,n){w()&&j("info",e,n);}function R(e,n){j("warn",e,n);}function q(e,n,t,r){w()&&console.log(`${f} Captured trace: provider=${e} model=${n} duration=${t}ms status=${r}`);}function _(e,n){console.error(`${f} Failed to capture trace: provider=${e} error=${n.message}`);}function W(e){w()&&console.log(`${f} Wrapped client: provider=${e}`);}function Y(e,n){w()&&console.log(`${f} Sending batch: count=${e} endpoint=${n}`);}function X(e,n){w()&&console.log(`${f} Batch sent successfully: count=${e} duration=${n}ms`);}function Z(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${f} Batch send failed: count=${e} error=${t}`);}function J(e,n,t){w()&&console.log(`${f} Request: ${e} ${n} (${t} bytes)`);}function Q(e,n){w()&&console.log(`${f} Response: status=${e} duration=${n}ms`);}function j(e,n,t){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?r(`${f} ${n}`,t):r(`${f} ${n}`);}function Te(e){if(typeof process<"u"&&process.env)return process.env[e]}var Ce=10,ve=1e3,Ie=1e4,A=class{constructor(n){I(this,"config");I(this,"queue",[]);I(this,"flushPromise",null);I(this,"flushTimer",null);this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??Ce,flushIntervalMs:n.flushIntervalMs??ve,requestTimeoutMs:n.requestTimeoutMs??Ie};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),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 n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).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(n){if(n.length===0)return;let t=Date.now();Y(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),X(n.length,Date.now()-t);}catch(r){Z(n.length,r);}}async request(n,t,r){let o=`${this.config.endpoint}${t}`,s=new AbortController,i=r?JSON.stringify(r):void 0;J(n,o,i?.length??0);let a=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),c=Date.now();try{let u=await fetch(o,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:s.signal});if(clearTimeout(a),Q(u.status,Date.now()-c),!u.ok){let E=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${E}`)}let l=await u.text();return l?JSON.parse(l):{}}catch(u){throw clearTimeout(a),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var xe="@lelemondev/sdk",Ee="nodejs";function Re(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function _e(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function Ae(){try{if(typeof B<"u")return ee().version??"unknown"}catch{}return "unknown"}var C=null;function te(e){if(!C){let t=Re(),r=_e();C={"telemetry.sdk.name":xe,"telemetry.sdk.version":Ae(),"telemetry.sdk.language":Ee},t&&(C["process.runtime.name"]=t.name,C["process.runtime.version"]=t.version),r&&(C["os.type"]=r);}let n={...C};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var N={},b=null,$=null,re="https://api.lelemon.dev";function Me(e={}){N=e,e.debug&&H(true),$=te(e.service),P("Initializing SDK",{endpoint:e.endpoint??re,debug:e.debug??false,disabled:e.disabled??false,telemetry:$}),b=oe(e),b.isEnabled()?P("SDK initialized - tracing enabled"):d("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function O(){return N}function M(){return $}function De(){return h().isEnabled()}function h(){return b||(b=oe(N)),b}async function Pe(){b&&await b.flush();}function oe(e){let n=e.apiKey??qe("LELEMON_API_KEY");return !n&&!e.disabled&&R("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new A({apiKey:n??"",endpoint:e.endpoint??re,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function qe(e){if(typeof process<"u"&&process.env)return process.env[e]}var K=Symbol.for("@lelemondev/sdk:globalContext");function ae(){let e=globalThis;return e[K]||(e[K]={context:{}}),e[K]}function ue(e){ae().context=e,d("Global context updated",e);}function x(){return ae().context}function k(e){try{let n=h();if(!n.isEnabled()){d("Transport disabled, skipping trace capture");return}let t=x(),r=m(),o=v(),s=M(),i={provider:e.provider,model:e.model,input:z(e.input),rawResponse:e.rawResponse?S(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:t.tags,spanType:e.spanType,name:e.name};return q(e.provider,e.model,e.durationMs,e.status),n.enqueue(i),o}catch(n){_(e.provider,n instanceof Error?n:new Error(String(n)));return}}function T(e){try{let n=h();if(!n.isEnabled()){d("Transport disabled, skipping error capture");return}let t=x(),r=m(),o=M(),s={provider:e.provider,model:e.model,input:z(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:v(),parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:t.tags};q(e.provider,e.model,e.durationMs,"error"),d("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(s);}catch(n){_(e.provider,n instanceof Error?n:new Error(String(n)));}}function L(e){try{let n=h();if(!n.isEnabled()){d("Transport disabled, skipping span capture");return}let t=x(),r=m(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,i=M(),a={...t.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete a._traceId,delete a._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:z(e.input),output:S(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:o??r?.traceId,spanId:v(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:a,tags:t.tags};d(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(c);}catch(n){_("unknown",n instanceof Error?n:new Error(String(n)));}}var se=1e5,je=["api_key","apikey","password","secret","authorization"],$e=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],Ne=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],ie={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function ce(){return O().redaction??{}}function Ke(e){let n=e.toLowerCase();return Ne.includes(n)?false:!!(je.some(r=>n.includes(r))||$e.some(r=>n.includes(r))||(ce().keys??[]).some(r=>n.includes(r.toLowerCase())))}function Le(e){let n=ce(),t=e;for(let r of n.patterns??[])r.lastIndex=0,t=t.replace(r,"[REDACTED]");return n.emails&&(t=t.replace(ie.emails,"[EMAIL]")),n.phones&&(t=t.replace(ie.phones,"[PHONE]")),t}function z(e){return S(e,0)}function S(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=Le(e);return t.length>se&&(t=t.slice(0,se)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>S(t,n+1));if(typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))Ke(r)?t[r]="[REDACTED]":t[r]=S(o,n+1);return t}return String(e)}var F=Symbol.for("@lelemondev/sdk:traceStorage");function Fe(){let e=globalThis;return e[F]||(e[F]=new async_hooks.AsyncLocalStorage),e[F]}var de=Fe();function v(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function m(){return de.getStore()}function U(e,n){let t=m();if(t)for(let r of e)t.pendingToolCalls.set(r,n),d(`Registered tool call ${r} \u2192 LLM span ${n}`);}function Ue(e){let n=m();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function Ge(e){let n=m();n&&n.pendingToolCalls.delete(e);}async function Be(e,n){let t=typeof e=="string"?{name:e}:e,r=m(),o=r?.traceId??v(),s=v(),i={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,pendingToolCalls:new Map};return de.run(i,async()=>{let a,c;try{return a=await n(),a}catch(u){throw c=u instanceof Error?u:new Error(String(u)),u}finally{We(i,c?void 0:a,c);}})}var Ve=["text","content","message","output","response","result","answer"];function He(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let o=e;return n in o?o[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let o of Ve)if(o in r&&typeof r[o]=="string")return r[o];return e}function We(e,n,t){let r=h();if(!r.isEnabled()){d("Transport disabled, skipping root span");return}let o=x(),s=Date.now()-e.startTime,i=t?null:He(n,e.outputKey,e.outputTransform),a={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:i,inputTokens:0,outputTokens:0,durationMs:s,status:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId??o.sessionId,userId:e.userId??o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};d(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),r.enqueue(a);}function Ye(e){let n=m();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=Ue(e.toolCallId);L({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:n.traceId,_parentSpanId:t}}),e.toolCallId&&Ge(e.toolCallId);}var p="openai";function le(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function pe(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let i=await e(...t);if(s&&fe(i))return Xe(i,o,r);let a=Date.now()-r,c=i,u=k({provider:p,model:o.model||c.model||"unknown",input:o.messages,rawResponse:i,durationMs:a,status:"success",streaming:!1});if(u){let l=ye(c);l.length>0&&U(l,u);}return i}catch(i){let a=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:o.messages,error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:s}),i}}}function fe(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Xe(e,n,t){let r={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,s,i=false,a=new Map;try{for await(let c of e){let u=c,l=u?.choices?.[0]?.delta?.content;l&&(i||(i=!0,s=Date.now()-t),r.choices[0].message.content+=l);let E=u?.choices?.[0]?.delta?.tool_calls;if(E)for(let g of E){a.has(g.index)||a.set(g.index,{id:"",function:{name:"",arguments:""}});let D=a.get(g.index);g.id&&(D.id=g.id),g.function?.name&&(D.function.name=g.function.name),g.function?.arguments&&(D.function.arguments+=g.function.arguments);}let G=u?.choices?.[0]?.finish_reason;G&&(r.choices[0].finish_reason=G),u?.usage&&(r.usage=u.usage),yield c;}}catch(c){throw o=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-t;if(a.size>0&&(r.choices[0].message.tool_calls=Array.from(a.entries()).sort((u,l)=>u[0]-l[0]).map(([,u])=>u)),o)T({provider:p,model:n.model||"unknown",input:n.messages,error:o,durationMs:c,streaming:true});else {let u=k({provider:p,model:n.model||"unknown",input:n.messages,rawResponse:r,durationMs:c,status:"success",streaming:true,firstTokenMs:s});if(u){let l=ye(r);l.length>0&&U(l,u);}}}}function me(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let i=await e(...t);if(s&&fe(i))return Ze(i,o,r);let a=Date.now()-r;return k({provider:p,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},rawResponse:i,durationMs:a,status:"success",streaming:!1}),i}catch(i){let a=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:s}),i}}}async function*Ze(e,n,t){let r=[],o=null,s=null;try{for await(let i of e){r.push(i);let a=i;a.type==="response.done"&&a.response&&(o=a.response),yield i;}}catch(i){throw s=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t;s?T({provider:p,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:s,durationMs:i,streaming:true}):k({provider:p,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:o||{streamEvents:r},durationMs:i,status:"success",streaming:true});}}function ge(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),i=Date.now()-r;return k({provider:p,model:o.model||"unknown",input:o.prompt,rawResponse:s,durationMs:i,status:"success",streaming:!1}),s}catch(s){let i=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:o.prompt,error:s instanceof Error?s:new Error(String(s)),durationMs:i,streaming:false}),s}}}function we(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),i=Date.now()-r;return k({provider:p,model:o.model||"unknown",input:o.input,rawResponse:s,durationMs:i,status:"success",streaming:!1,spanType:"embedding"}),s}catch(s){let i=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:o.input,error:s instanceof Error?s:new Error(String(s)),durationMs:i,streaming:false}),s}}}function ye(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let r of t)r.id&&n.push(r.id);return n}function zn(e,n){return n&&ue(n),O().disabled?(d("Tracing disabled, returning unwrapped client"),e):le(e)?(W("openai"),Qe(e)):(R("Client is not an OpenAI client. Use @lelemondev/sdk/openai only with OpenAI SDK."),e)}function Qe(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="chat"&&s&&typeof s=="object"?en(s):r==="responses"&&s&&typeof s=="object"?tn(s):r==="completions"&&s&&typeof s=="object"?rn(s):r==="embeddings"&&s&&typeof s=="object"?on(s):s}})}function en(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="completions"&&o&&typeof o=="object"?nn(o):o}})}function nn(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?pe(o.bind(n)):o}})}function tn(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?me(o.bind(n)):o}})}function rn(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?ge(o.bind(n)):o}})}function on(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?we(o.bind(n)):o}})}
3
- exports.captureSpan=L;exports.flush=Pe;exports.getTraceContext=m;exports.init=Me;exports.isEnabled=De;exports.observe=zn;exports.span=Ye;exports.trace=Be;//# sourceMappingURL=openai.js.map
2
+ var G=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ye=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Q=ye((dn,Ce)=>{Ce.exports={name:"@lelemondev/sdk",version:"0.10.0",description:"Automatic LLM observability. Wrap your client, everything is traced.",author:"Lelemon <info@lelemon.dev>",license:"MIT",repository:{type:"git",url:"git+https://github.com/lelemondev/lelemondev-sdk.git"},homepage:"https://lelemon.dev",bugs:{url:"https://github.com/lelemondev/lelemondev-sdk/issues"},keywords:["llm","observability","tracing","openai","anthropic","nextjs","lambda","express","hono","claude","gpt","ai","monitoring","serverless"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./openai":{types:"./dist/openai.d.ts",import:"./dist/openai.mjs",require:"./dist/openai.js"},"./anthropic":{types:"./dist/anthropic.d.ts",import:"./dist/anthropic.mjs",require:"./dist/anthropic.js"},"./bedrock":{types:"./dist/bedrock.d.ts",import:"./dist/bedrock.mjs",require:"./dist/bedrock.js"},"./gemini":{types:"./dist/gemini.d.ts",import:"./dist/gemini.mjs",require:"./dist/gemini.js"},"./google-genai":{types:"./dist/google-genai.d.ts",import:"./dist/google-genai.mjs",require:"./dist/google-genai.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.mjs",require:"./dist/openrouter.js"},"./next":{types:"./dist/next.d.ts",import:"./dist/next.mjs",require:"./dist/next.js"},"./lambda":{types:"./dist/lambda.d.ts",import:"./dist/lambda.mjs",require:"./dist/lambda.js"},"./express":{types:"./dist/express.d.ts",import:"./dist/express.mjs",require:"./dist/express.js"},"./hono":{types:"./dist/hono.d.ts",import:"./dist/hono.mjs",require:"./dist/hono.js"},"./integrations":{types:"./dist/integrations.d.ts",import:"./dist/integrations.mjs",require:"./dist/integrations.js"},"./package.json":"./package.json"},typesVersions:{"*":{openai:["./dist/openai.d.ts"],anthropic:["./dist/anthropic.d.ts"],bedrock:["./dist/bedrock.d.ts"],gemini:["./dist/gemini.d.ts"],"google-genai":["./dist/google-genai.d.ts"],openrouter:["./dist/openrouter.d.ts"],next:["./dist/next.d.ts"],lambda:["./dist/lambda.d.ts"],express:["./dist/express.d.ts"],hono:["./dist/hono.d.ts"],integrations:["./dist/integrations.d.ts"],"*":["./dist/index.d.ts"]}},files:["dist/**/*.js","dist/**/*.mjs","dist/**/*.d.ts","dist/**/*.d.mts","README.md"],sideEffects:false,engines:{node:">=18.0.0"},scripts:{build:"tsup",dev:"tsup --watch",docs:"typedoc && node scripts/generate-llms-txt.mjs",prepublishOnly:"npm run build",lint:"eslint src/",test:"vitest","test:run":"vitest run","test:coverage":"vitest run --coverage","test:e2e":"vitest run tests/e2e",typecheck:"tsc --noEmit"},devDependencies:{"@aws-sdk/client-bedrock-runtime":"^3.962.0","@google/genai":"^1.0.0","@google/generative-ai":"^0.24.1","@anthropic-ai/sdk":"^0.82.0","@types/node":"^22.0.0","@vitest/coverage-v8":"^4.0.0",dotenv:"^17.2.3",openai:"^6.15.0",tsup:"^8.5.1",vite:"^6.0.0",typedoc:"^0.28.18",typescript:"^6.0.0",vitest:"^4.0.0"}};});var B=false;function V(e){B=e;}function w(){return B?true:be("LELEMON_DEBUG")==="true"}var f="[Lelemon]";function d(e,n){w()&&q("debug",e,n);}function D(e,n){w()&&q("info",e,n);}function E(e,n){q("warn",e,n);}function P(e,n,t,r){w()&&console.log(`${f} Captured trace: provider=${e} model=${n} duration=${t}ms status=${r}`);}function R(e,n){console.error(`${f} Failed to capture trace: provider=${e} error=${n.message}`);}function H(e){w()&&console.log(`${f} Wrapped client: provider=${e}`);}function W(e,n){w()&&console.log(`${f} Sending batch: count=${e} endpoint=${n}`);}function Y(e,n){w()&&console.log(`${f} Batch sent successfully: count=${e} duration=${n}ms`);}function X(e,n){let t=n instanceof Error?n.message:String(n);console.error(`${f} Batch send failed: count=${e} error=${t}`);}function Z(e,n,t){w()&&console.log(`${f} Request: ${e} ${n} (${t} bytes)`);}function J(e,n){w()&&console.log(`${f} Response: status=${e} duration=${n}ms`);}function q(e,n,t){let r=e==="error"?console.error:e==="warn"?console.warn:console.log;t!==void 0?r(`${f} ${n}`,t):r(`${f} ${n}`);}function be(e){if(typeof process<"u"&&process.env)return process.env[e]}var he=10,ke=1e3,Te=1e4,_=class{config;queue=[];flushPromise=null;flushTimer=null;constructor(n){this.config={apiKey:n.apiKey,endpoint:n.endpoint,debug:n.debug,disabled:n.disabled,batchSize:n.batchSize??he,flushIntervalMs:n.flushIntervalMs??ke,requestTimeoutMs:n.requestTimeoutMs??Te};}isEnabled(){return !this.config.disabled&&!!this.config.apiKey}enqueue(n){this.config.disabled||(this.queue.push(n),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 n=this.queue;return this.queue=[],this.flushPromise=this.sendBatch(n).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(n){if(n.length===0)return;let t=Date.now();W(n.length,`${this.config.endpoint}/api/v1/ingest`);try{await this.request("POST","/api/v1/ingest",{events:n}),Y(n.length,Date.now()-t);}catch(r){X(n.length,r);}}async request(n,t,r){let o=`${this.config.endpoint}${t}`,s=new AbortController,i=r?JSON.stringify(r):void 0;Z(n,o,i?.length??0);let a=setTimeout(()=>{s.abort();},this.config.requestTimeoutMs),c=Date.now();try{let u=await fetch(o,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:i,signal:s.signal});if(clearTimeout(a),J(u.status,Date.now()-c),!u.ok){let x=await u.text().catch(()=>"Unknown error");throw new Error(`HTTP ${u.status}: ${x}`)}let l=await u.text();return l?JSON.parse(l):{}}catch(u){throw clearTimeout(a),u instanceof Error&&u.name==="AbortError"?new Error(`Request timeout after ${this.config.requestTimeoutMs}ms`):u}}};var ve="@lelemondev/sdk",Ie="nodejs";function Se(){return typeof process<"u"&&process.versions?.node?{name:"nodejs",version:process.versions.node}:typeof Deno<"u"?{name:"deno",version:Deno.version?.deno??"unknown"}:typeof Bun<"u"?{name:"bun",version:Bun.version??"unknown"}:typeof window<"u"&&typeof navigator<"u"?{name:"browser",version:navigator.userAgent}:null}function xe(){if(typeof process<"u"&&process.platform){let e=process.platform;switch(e){case "darwin":return "darwin";case "win32":return "windows";case "linux":return "linux";default:return e}}if(typeof navigator<"u"){let e=navigator.userAgent.toLowerCase();if(e.includes("mac"))return "darwin";if(e.includes("win"))return "windows";if(e.includes("linux"))return "linux"}return null}function Ee(){try{if(typeof G<"u")return Q().version??"unknown"}catch{}return "unknown"}var C=null;function ne(e){if(!C){let t=Se(),r=xe();C={"telemetry.sdk.name":ve,"telemetry.sdk.version":Ee(),"telemetry.sdk.language":Ie},t&&(C["process.runtime.name"]=t.name,C["process.runtime.version"]=t.version),r&&(C["os.type"]=r);}let n={...C};return e?.name&&(n["service.name"]=e.name),e?.version&&(n["service.version"]=e.version),e?.environment&&(n["deployment.environment"]=e.environment),n}var $={},b=null,j=null,te="https://api.lelemon.dev";function _e(e={}){$=e,e.debug&&V(true),j=ne(e.service),D("Initializing SDK",{endpoint:e.endpoint??te,debug:e.debug??false,disabled:e.disabled??false,telemetry:j}),b=re(e),b.isEnabled()?D("SDK initialized - tracing enabled"):d("SDK initialized - tracing disabled (no API key or explicitly disabled)");}function A(){return $}function O(){return j}function Ae(){return h().isEnabled()}function h(){return b||(b=re($)),b}async function Oe(){b&&await b.flush();}function re(e){let n=e.apiKey??Me("LELEMON_API_KEY");return !n&&!e.disabled&&E("No API key provided. Set apiKey in init() or LELEMON_API_KEY env var. Tracing disabled."),new _({apiKey:n??"",endpoint:e.endpoint??te,debug:e.debug??false,disabled:e.disabled??!n,batchSize:e.batchSize,flushIntervalMs:e.flushIntervalMs,requestTimeoutMs:e.requestTimeoutMs})}function Me(e){if(typeof process<"u"&&process.env)return process.env[e]}var N=Symbol.for("@lelemondev/sdk:globalContext");function ie(){let e=globalThis;return e[N]||(e[N]={context:{}}),e[N]}function ae(e){ie().context=e,d("Global context updated",e);}function S(){return ie().context}function k(e){try{let n=h();if(!n.isEnabled()){d("Transport disabled, skipping trace capture");return}let t=S(),r=m(),o=v(),s=O(),i={provider:e.provider,model:e.model,input:L(e.input),rawResponse:e.rawResponse?I(e.rawResponse,0):void 0,durationMs:e.durationMs,status:e.status,streaming:e.streaming,firstTokenMs:e.firstTokenMs,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:o,parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...s?{_telemetry:s}:{}},tags:t.tags,spanType:e.spanType,name:e.name};return P(e.provider,e.model,e.durationMs,e.status),n.enqueue(i),o}catch(n){R(e.provider,n instanceof Error?n:new Error(String(n)));return}}function T(e){try{let n=h();if(!n.isEnabled()){d("Transport disabled, skipping error capture");return}let t=S(),r=m(),o=O(),s={provider:e.provider,model:e.model,input:L(e.input),durationMs:e.durationMs,status:"error",errorMessage:e.error.message,streaming:e.streaming,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:r?.traceId,spanId:v(),parentSpanId:r?.currentSpanId,metadata:{...t.metadata,...e.metadata,...r?{_traceName:r.name}:{},...o?{_telemetry:o}:{}},tags:t.tags};P(e.provider,e.model,e.durationMs,"error"),d("Error details",{message:e.error.message,stack:e.error.stack}),n.enqueue(s);}catch(n){R(e.provider,n instanceof Error?n:new Error(String(n)));}}function K(e){try{let n=h();if(!n.isEnabled()){d("Transport disabled, skipping span capture");return}let t=S(),r=m(),o=e.metadata?._traceId,s=e.metadata?._parentSpanId,i=O(),a={...t.metadata,...e.metadata,...i?{_telemetry:i}:{}};delete a._traceId,delete a._parentSpanId;let c={spanType:e.type,name:e.name,provider:"unknown",model:e.name,input:L(e.input),output:I(e.output,0),durationMs:e.durationMs,status:e.status||"success",errorMessage:e.errorMessage,streaming:!1,sessionId:r?.sessionId??t.sessionId,userId:r?.userId??t.userId,traceId:o??r?.traceId,spanId:v(),parentSpanId:s??r?.currentSpanId,toolCallId:e.toolCallId,metadata:a,tags:t.tags};d(`Span captured: ${e.type}/${e.name}`,{durationMs:e.durationMs}),n.enqueue(c);}catch(n){R("unknown",n instanceof Error?n:new Error(String(n)));}}var oe=1e5,De=["api_key","apikey","password","secret","authorization"],Pe=["access_token","auth_token","bearer_token","refresh_token","id_token","session_token"],qe=["inputtokens","outputtokens","totaltokens","prompttokens","completiontokens","cachereadtokens","cachewritetokens","cachereadinputtokens","cachewriteinputtokens","reasoningtokens"],se={emails:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,phones:/\b\d{9,}\b/g};function ue(){return A().redaction??{}}function je(e){let n=e.toLowerCase();return qe.includes(n)?false:!!(De.some(r=>n.includes(r))||Pe.some(r=>n.includes(r))||(ue().keys??[]).some(r=>n.includes(r.toLowerCase())))}function $e(e){let n=ue(),t=e;for(let r of n.patterns??[])r.lastIndex=0,t=t.replace(r,"[REDACTED]");return n.emails&&(t=t.replace(se.emails,"[EMAIL]")),n.phones&&(t=t.replace(se.phones,"[PHONE]")),t}function L(e){return I(e,0)}function I(e,n){if(n>10)return "[max depth exceeded]";if(e==null)return e;if(typeof e=="string"){let t=$e(e);return t.length>oe&&(t=t.slice(0,oe)+"...[truncated]"),t}if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>I(t,n+1));if(typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))je(r)?t[r]="[REDACTED]":t[r]=I(o,n+1);return t}return String(e)}var z=Symbol.for("@lelemondev/sdk:traceStorage");function Ke(){let e=globalThis;return e[z]||(e[z]=new async_hooks.AsyncLocalStorage),e[z]}var ce=Ke();function v(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function m(){return ce.getStore()}function F(e,n){let t=m();if(t)for(let r of e)t.pendingToolCalls.set(r,n),d(`Registered tool call ${r} \u2192 LLM span ${n}`);}function Le(e){let n=m();if(n)return e&&n.pendingToolCalls.has(e)?n.pendingToolCalls.get(e):n.currentSpanId}function ze(e){let n=m();n&&n.pendingToolCalls.delete(e);}async function Fe(e,n){let t=typeof e=="string"?{name:e}:e,r=m(),o=r?.traceId??v(),s=v(),i={traceId:o,rootSpanId:s,currentSpanId:s,parentSpanId:r?.currentSpanId,name:t.name,startTime:Date.now(),input:t.input,metadata:t.metadata,tags:t.tags,outputKey:t.outputKey,outputTransform:t.outputTransform,sessionId:t.sessionId,userId:t.userId,pendingToolCalls:new Map};return ce.run(i,async()=>{let a,c;try{return a=await n(),a}catch(u){throw c=u instanceof Error?u:new Error(String(u)),u}finally{Be(i,c?void 0:a,c);}})}var Ue=["text","content","message","output","response","result","answer"];function Ge(e,n,t){if(t)try{return t(e)}catch{return e}if(n===false)return e;if(typeof n=="string"&&e&&typeof e=="object"){let o=e;return n in o?o[n]:e}if(e==null||typeof e!="object"||Array.isArray(e))return e;let r=e;for(let o of Ue)if(o in r&&typeof r[o]=="string")return r[o];return e}function Be(e,n,t){let r=h();if(!r.isEnabled()){d("Transport disabled, skipping root span");return}let o=S(),s=Date.now()-e.startTime,i=t?null:Ge(n,e.outputKey,e.outputTransform),a={spanType:"agent",name:e.name,provider:"agent",model:e.name,traceId:e.traceId,spanId:e.rootSpanId,parentSpanId:e.parentSpanId,input:e.input,output:i,inputTokens:0,outputTokens:0,durationMs:s,status:t?"error":"success",errorMessage:t?.message,streaming:false,sessionId:e.sessionId??o.sessionId,userId:e.userId??o.userId,metadata:{...o.metadata,...e.metadata},tags:e.tags??o.tags};d(`Sending root span: ${e.name}`,{durationMs:s,hasError:!!t}),r.enqueue(a);}function Ve(e){let n=m();if(!n){process.env.NODE_ENV!=="production"&&console.warn("[Lelemon] span() called outside of trace() - span will not be captured");return}let t=Le(e.toolCallId);K({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:n.traceId,_parentSpanId:t}}),e.toolCallId&&ze(e.toolCallId);}var p="openai";function de(e){if(!e||typeof e!="object")return false;if(e.constructor?.name==="OpenAI")return true;let t=e;return !!(t.chat&&t.completions)||!!t.responses}function le(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let i=await e(...t);if(s&&pe(i))return He(i,o,r);let a=Date.now()-r,c=i,u=k({provider:p,model:o.model||c.model||"unknown",input:o.messages,rawResponse:i,durationMs:a,status:"success",streaming:!1});if(u){let l=we(c);l.length>0&&F(l,u);}return i}catch(i){let a=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:o.messages,error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:s}),i}}}function pe(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*He(e,n,t){let r={choices:[{message:{content:"",tool_calls:[]},finish_reason:""}],usage:{prompt_tokens:0,completion_tokens:0}},o=null,s,i=false,a=new Map;try{for await(let c of e){let u=c,l=u?.choices?.[0]?.delta?.content;l&&(i||(i=!0,s=Date.now()-t),r.choices[0].message.content+=l);let x=u?.choices?.[0]?.delta?.tool_calls;if(x)for(let g of x){a.has(g.index)||a.set(g.index,{id:"",function:{name:"",arguments:""}});let M=a.get(g.index);g.id&&(M.id=g.id),g.function?.name&&(M.function.name=g.function.name),g.function?.arguments&&(M.function.arguments+=g.function.arguments);}let U=u?.choices?.[0]?.finish_reason;U&&(r.choices[0].finish_reason=U),u?.usage&&(r.usage=u.usage),yield c;}}catch(c){throw o=c instanceof Error?c:new Error(String(c)),c}finally{let c=Date.now()-t;if(a.size>0&&(r.choices[0].message.tool_calls=Array.from(a.entries()).sort((u,l)=>u[0]-l[0]).map(([,u])=>u)),o)T({provider:p,model:n.model||"unknown",input:n.messages,error:o,durationMs:c,streaming:true});else {let u=k({provider:p,model:n.model||"unknown",input:n.messages,rawResponse:r,durationMs:c,status:"success",streaming:true,firstTokenMs:s});if(u){let l=we(r);l.length>0&&F(l,u);}}}}function fe(e){return async function(...t){let r=Date.now(),o=t[0]||{},s=o.stream===true;try{let i=await e(...t);if(s&&pe(i))return We(i,o,r);let a=Date.now()-r;return k({provider:p,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},rawResponse:i,durationMs:a,status:"success",streaming:!1}),i}catch(i){let a=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:{instructions:o.instructions,input:o.input},error:i instanceof Error?i:new Error(String(i)),durationMs:a,streaming:s}),i}}}async function*We(e,n,t){let r=[],o=null,s=null;try{for await(let i of e){r.push(i);let a=i;a.type==="response.done"&&a.response&&(o=a.response),yield i;}}catch(i){throw s=i instanceof Error?i:new Error(String(i)),i}finally{let i=Date.now()-t;s?T({provider:p,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},error:s,durationMs:i,streaming:true}):k({provider:p,model:n.model||"unknown",input:{instructions:n.instructions,input:n.input},rawResponse:o||{streamEvents:r},durationMs:i,status:"success",streaming:true});}}function me(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),i=Date.now()-r;return k({provider:p,model:o.model||"unknown",input:o.prompt,rawResponse:s,durationMs:i,status:"success",streaming:!1}),s}catch(s){let i=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:o.prompt,error:s instanceof Error?s:new Error(String(s)),durationMs:i,streaming:false}),s}}}function ge(e){return async function(...t){let r=Date.now(),o=t[0]||{};try{let s=await e(...t),i=Date.now()-r;return k({provider:p,model:o.model||"unknown",input:o.input,rawResponse:s,durationMs:i,status:"success",streaming:!1,spanType:"embedding"}),s}catch(s){let i=Date.now()-r;throw T({provider:p,model:o.model||"unknown",input:o.input,error:s instanceof Error?s:new Error(String(s)),durationMs:i,streaming:false}),s}}}function we(e){let n=[],t=e.choices?.[0]?.message?.tool_calls;if(Array.isArray(t))for(let r of t)r.id&&n.push(r.id);return n}function $n(e,n){return n&&ae(n),A().disabled?(d("Tracing disabled, returning unwrapped client"),e):de(e)?(H("openai"),Xe(e)):(E("Client is not an OpenAI client. Use @lelemondev/sdk/openai only with OpenAI SDK."),e)}function Xe(e){let n=e;return new Proxy(n,{get(t,r,o){let s=Reflect.get(t,r,o);return r==="chat"&&s&&typeof s=="object"?Ze(s):r==="responses"&&s&&typeof s=="object"?Qe(s):r==="completions"&&s&&typeof s=="object"?en(s):r==="embeddings"&&s&&typeof s=="object"?nn(s):s}})}function Ze(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="completions"&&o&&typeof o=="object"?Je(o):o}})}function Je(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?le(o.bind(n)):o}})}function Qe(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?fe(o.bind(n)):o}})}function en(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?me(o.bind(n)):o}})}function nn(e){return new Proxy(e,{get(n,t,r){let o=Reflect.get(n,t,r);return t==="create"&&typeof o=="function"?ge(o.bind(n)):o}})}
3
+ exports.captureSpan=K;exports.flush=Oe;exports.getTraceContext=m;exports.init=_e;exports.isEnabled=Ae;exports.observe=$n;exports.span=Ve;exports.trace=Fe;//# sourceMappingURL=openai.js.map
4
4
  //# sourceMappingURL=openai.js.map