@tracehatch/sdk 0.3.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/CHANGELOG.md +9 -0
- package/GUIDE.md +387 -0
- package/LICENSE +21 -0
- package/README.md +134 -0
- package/dist/auto.cjs +2 -0
- package/dist/auto.cjs.map +1 -0
- package/dist/auto.d.cts +2 -0
- package/dist/auto.d.ts +2 -0
- package/dist/auto.js +2 -0
- package/dist/auto.js.map +1 -0
- package/dist/chunk-KHVJY566.js +9 -0
- package/dist/chunk-KHVJY566.js.map +1 -0
- package/dist/chunk-U5REKR34.cjs +9 -0
- package/dist/chunk-U5REKR34.cjs.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +243 -0
- package/dist/index.d.ts +243 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +69 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';var async_hooks=require('async_hooks'),perf_hooks=require('perf_hooks'),crypto=require('crypto'),buffer=require('buffer'),An=require('http'),En=require('https'),zlib=require('zlib'),util=require('util'),fs=require('fs'),path=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var An__default=/*#__PURE__*/_interopDefault(An);var En__default=/*#__PURE__*/_interopDefault(En);var Pt=Symbol.for("tracehatch.sdk.v1.state"),Bt=globalThis,y=Bt[Pt]??={storage:new async_hooks.AsyncLocalStorage,pendingEnds:new Set};function R(){return y.storage.getStore()}var x={maxCount:2147483647,maxSpansPerBatch:1e3,maxTracesPerBatch:1e3,maxNameLength:256,maxAgentLength:128,maxSessionIdLength:128,maxUserIdLength:128,maxUserNameLength:256,maxReleaseLength:128,maxTagsPerTrace:32,maxTagLength:64,maxScoresPerTrace:100,maxScoreNameLength:128,maxScoreValueLength:256,maxScoreCommentLength:2048,maxMetadataBytes:16384,maxAttributesPerSpan:64,maxAttributeKeyLength:256,maxAttributesObjectBytes:8192,maxErrorTypeLength:128,maxErrorMessageBytes:2048,maxStackBytes:65536,maxEventsPerSpan:100,maxAttributeBytes:1048576,bodyHeadBytes:786432,bodyTailBytes:262144,traceBodyBytes:65536},g={system:"gen_ai.system",requestModel:"gen_ai.request.model",responseModel:"gen_ai.response.model",temperature:"gen_ai.request.temperature",maxTokens:"gen_ai.request.max_tokens",topP:"gen_ai.request.top_p",inputTokens:"gen_ai.usage.input_tokens",outputTokens:"gen_ai.usage.output_tokens",cachedInputTokens:"gen_ai.usage.cached_input_tokens",cacheCreationInputTokens:"gen_ai.usage.cache_creation_input_tokens",cacheCreation5mInputTokens:"gen_ai.usage.cache_creation_5m_input_tokens",cacheCreation1hInputTokens:"gen_ai.usage.cache_creation_1h_input_tokens",pricingIncomplete:"tracehatch.pricing.incomplete",reasoningTokens:"gen_ai.usage.reasoning_tokens",finishReasons:"gen_ai.response.finish_reasons",responseStatus:"gen_ai.response.status",timeToFirstTokenMs:"gen_ai.response.time_to_first_token_ms",tokensPerSecond:"gen_ai.usage.tokens_per_second",requestTools:"gen_ai.request.tools",responseToolCalls:"gen_ai.response.tool_calls",toolName:"tool.name",toolCallId:"tool.call_id",errorType:"error.type",errorStatus:"error.status",httpStatus:"http.response.status_code",retrievalQuery:"retrieval.query",retrievalDocumentCount:"retrieval.document_count",agent:"tracehatch.agent",release:"tracehatch.release",sessionId:"session.id",userId:"user.id",sdkName:"tracehatch.sdk.name",sdkVersion:"tracehatch.sdk.version",clockSkewMs:"tracehatch.clock_skew_ms",attributesTruncated:"tracehatch.attributes_truncated"},$e=[g.inputTokens,g.outputTokens,g.cachedInputTokens,g.cacheCreationInputTokens,g.cacheCreation5mInputTokens,g.cacheCreation1hInputTokens,g.timeToFirstTokenMs];var _e="[0-7][0-9a-hjkmnp-tv-z]{25}",Ne=new RegExp(`^span_${_e}$`),Le=new RegExp(`^scr_${_e}$`),ze=globalThis;new ze.TextEncoder;new ze.TextDecoder;var $t=Date.now(),Nt=perf_hooks.performance.now();function F(){return new Date($t+perf_hooks.performance.now()-Nt).toISOString()}var re="0.3.0",De="https://api.tracehatch.com",b={wireVersion:1,batchMaxSpans:100,batchMaxBytes:5242880,batchMaxDelayMs:2e3,maxQueueBytes:10485760,maxInFlightBatches:4,requestTimeoutMs:1e4,flushTimeoutMs:5e3,retryAttempts:5,retryBaseMs:1e3,retryMaxMs:3e4,retryAfterMaxMs:6e4,retryJitter:.25,gzipMinBytes:1024,warnIntervalMs:6e4,configRefreshMs:3e5,maxAttributeBytes:1048576,bodyHeadBytes:786432,bodyTailBytes:262144,traceBodyBytes:65536,maxTagsPerTrace:32,maxAttributesPerSpan:64,maxNameLength:256,maxStackBytes:8192,maxCapturedRequestBytes:8388608,maxCapturedResponseBytes:8388608,autoRunIdleMs:6e5,captureSettleMs:12e4,retryWindowMs:6e4,maxRememberedFailures:256,toolMetadataSettleMs:25,signalFlushMs:2e3};var Lt=globalThis.URL,zt=[[/^api\.openai\.com$/,"openai"],[/^api\.anthropic\.com$/,"anthropic"],[/\.openai\.azure\.com$/,"azure_openai"],[/^api\.groq\.com$/,"groq"],[/^api\.mistral\.ai$/,"mistral"],[/^api\.together\.xyz$/,"together"],[/^openrouter\.ai$/,"openrouter"],[/^api\.deepseek\.com$/,"deepseek"],[/^api\.x\.ai$/,"xai"],[/^api\.perplexity\.ai$/,"perplexity"],[/^api\.fireworks\.ai$/,"fireworks"],[/^api\.cerebras\.ai$/,"cerebras"],[/^generativelanguage\.googleapis\.com$/,"gemini"]];function Fe(n){let e=n.hostname.toLowerCase();for(let[t,r]of zt)if(t.test(e))return r;return (e==="localhost"||e==="127.0.0.1")&&n.port==="11434"?"ollama":e}var Ue="[A-Za-z0-9_-]+",Dt=[["POST",/\/chat\/completions$/,"chat.completions"],["POST",/\/embeddings$/,"embeddings"],["POST",/\/responses$/,"responses"],["POST",new RegExp(`/responses/(${Ue})/cancel$`),"responses.cancel"],["GET",new RegExp(`/responses/(${Ue})$`),"responses.retrieve"]];function je(n,e,t={}){let r;try{r=typeof e=="string"?new Lt(e):e;}catch{return}if(r.protocol!=="http:"&&r.protocol!=="https:")return;let s=n.toUpperCase(),o=r.pathname.replace(/\/+$/,"");if(t.api!=="anthropic")for(let[i,a,d]of Dt){if(s!==i)continue;let u=a.exec(o);if(u)return {api:"openai",system:Fe(r),operation:d,...u[1]?{responseId:u[1]}:{}}}if(t.api!=="openai"&&s==="POST"&&/\/messages$/.test(o)&&(t.api==="anthropic"||r.hostname.toLowerCase()==="api.anthropic.com"||!!t.header?.("anthropic-version")))return {api:"anthropic",system:Fe(r),operation:"messages"}}var se=class{buffer="";event;data=[];push(e){this.buffer+=e;let t=[];for(;;){let r=this.buffer.search(/\r\n|\n|\r/);if(r===-1)break;let s=this.buffer.slice(0,r),o=this.buffer.startsWith(`\r
|
|
2
|
+
`,r)?2:1;this.buffer=this.buffer.slice(r+o);let i=this.line(s);i&&t.push(i);}return t}end(){let e=[];if(this.buffer.length>0){let r=this.line(this.buffer);this.buffer="",r&&e.push(r);}let t=this.dispatch();return t&&e.push(t),e}line(e){if(e==="")return this.dispatch();if(e.startsWith(":"))return;let t=e.indexOf(":"),r=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t+1);s.startsWith(" ")&&(s=s.slice(1)),r==="data"?this.data.push(s):r==="event"&&(this.event=s);}dispatch(){if(this.data.length===0){this.event=void 0;return}let e={data:this.data.join(`
|
|
3
|
+
`)};return this.event!==void 0&&(e.event=this.event),this.event=void 0,this.data=[],e}};var Ft=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ut=new globalThis.TextEncoder;function J(n){let e=Ut.encode(n),t=e.length*8,r=Math.ceil((e.length+9)/64)*64,s=new Uint8Array(r);s.set(e),s[e.length]=128;let o=new DataView(s.buffer);o.setUint32(r-8,Math.floor(t/4294967296)),o.setUint32(r-4,t>>>0);let i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let u=0;u<r;u+=64){for(let S=0;S<16;S++)a[S]=o.getUint32(u+S*4);for(let S=16;S<64;S++){let C=a[S-15],B=a[S-2],O=P(C,7)^P(C,18)^C>>>3,v=P(B,17)^P(B,19)^B>>>10;a[S]=a[S-16]+O+a[S-7]+v>>>0;}let[c,p,l,m,h,_,k,I]=i;for(let S=0;S<64;S++){let C=P(h,6)^P(h,11)^P(h,25),B=h&_^~h&k,O=I+C+B+Ft[S]+a[S]>>>0,v=P(c,2)^P(c,13)^P(c,22),A=c&p^c&l^p&l,$=v+A>>>0;I=k,k=_,_=h,h=m+O>>>0,m=l,l=p,p=c,c=O+$>>>0;}i[0]=i[0]+c>>>0,i[1]=i[1]+p>>>0,i[2]=i[2]+l>>>0,i[3]=i[3]+m>>>0,i[4]=i[4]+h>>>0,i[5]=i[5]+_>>>0,i[6]=i[6]+k>>>0,i[7]=i[7]+I>>>0;}let d="";for(let u of i)d+=u.toString(16).padStart(8,"0");return d}function P(n,e){return n>>>e|n<<32-e}function f(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{}}function w(n){return Array.isArray(n)?n:[]}function E(n,e,t){typeof t=="string"&&(n[e]=t),typeof t=="number"&&Number.isFinite(t)&&(n[e]=t);}function jt(n){try{let e=JSON.stringify(n);return e===void 0?void 0:e.slice(0,2048)}catch{return}}function Te(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}function qt(n,e){let t={[g.system]:n};return E(t,g.requestModel,e.model),E(t,g.temperature,e.temperature),E(t,g.topP,e.top_p),E(t,g.maxTokens,e.max_completion_tokens??e.max_output_tokens??e.max_tokens),Array.isArray(e.tools)&&(t[g.requestTools]=e.tools.length),t}function Ht(n,e){let t={},r=f(e.usage);E(t,g.responseModel,e.model);let s=r.cache_read_input_tokens??f(r.prompt_tokens_details).cached_tokens??f(r.input_tokens_details).cached_tokens,o=r.input_tokens??r.prompt_tokens;if(E(t,g.inputTokens,n==="anthropic"&&typeof o=="number"?o+Number(s??0)+Number(r.cache_creation_input_tokens??0):o),E(t,g.outputTokens,r.output_tokens??r.completion_tokens),E(t,g.cachedInputTokens,s),n==="anthropic"){E(t,g.cacheCreationInputTokens,r.cache_creation_input_tokens);let c=f(r.cache_creation);E(t,g.cacheCreation5mInputTokens,c.ephemeral_5m_input_tokens),E(t,g.cacheCreation1hInputTokens,c.ephemeral_1h_input_tokens);}E(t,g.reasoningTokens,f(r.output_tokens_details).reasoning_tokens??f(r.output_tokens_details).thinking_tokens??f(r.completion_tokens_details).reasoning_tokens),E(t,g.responseStatus,e.status);let i=f(r.server_tool_use);(w(e.output).some(c=>{let p=f(c).type;return typeof p=="string"&&p.endsWith("_call")&&p!=="function_call"&&p!=="custom_tool_call"})||w(e.content).some(c=>f(c).type==="server_tool_use")||Object.values(i).some(c=>typeof c=="number"&&c>0)||typeof e.service_tier=="string"&&!["default","standard","auto"].includes(e.service_tier))&&(t[g.pricingIncomplete]=true);let d=w(e.choices).map(c=>f(c).finish_reason).filter(c=>typeof c=="string");typeof e.stop_reason=="string"&&d.push(e.stop_reason),d.length>0&&(t[g.finishReasons]=d.slice(0,32));let u=Se(n,e).length;return u>0&&(t[g.responseToolCalls]=u),t}function Se(n,e){let t=[],r=(s,o,i)=>{typeof s!="string"||s.length===0||t.push({id:s,name:typeof o=="string"&&o?o:"tool",arguments:Te(i)});};if(n==="anthropic"){for(let s of w(e.content)){let o=f(s);o.type==="tool_use"&&r(o.id,o.name,o.input);}return t}if(e.output!==void 0){for(let s of w(e.output)){let o=f(s);o.type==="function_call"&&r(o.call_id??o.id,o.name,o.arguments);}return t}for(let s of w(e.choices)){let o=f(f(s).message);for(let i of w(o.tool_calls)){let a=f(i),d=f(a.function);r(a.id,d.name,d.arguments);}}return t}function oe(n){return /abort|cancel/i.test(String(f(n).name??""))}function U(n){let e=f(n),t=typeof e.status=="number"?e.status:void 0,r=String(e.name??""),s=t===429?"rate_limit":t===408||/timeout/i.test(r)?"timeout":t===401||t===403?"auth":t!==void 0&&t>=500?"provider_error":t!==void 0&&t>=400&&t<=422?"invalid_request":r||"provider_error",o=typeof e.message=="string"&&e.message?e.message:n instanceof Error?n.message:String(n),i={type:s,message:o};return typeof e.stack=="string"&&(i.stack=e.stack),t!==void 0&&(i.status=t),i}function qe(n,e){let t=f(f(e).error),r=typeof t.message=="string"&&t.message?t.message:typeof f(e).message=="string"?String(f(e).message):`Provider responded with HTTP ${n}`;return U({status:n,message:r})}function He(n,e){let t=f(e);return {name:n.operation,kind:n.operation==="embeddings"?"embedding":"generation",attributes:qt(n.system,t),input:e,messages:t.messages}}var Wt=262144,Kt=32,Gt=128,Jt=256,Vt=new globalThis.TextEncoder,ie=class{options;remaining=Wt;truncated=false;firstTokenAt;outputTokens;usage={};attributes={};parts=new Map;streamedTools=new Map;completeToolCalls;finalOutput;failure;failureCancelled=false;outputBytes=0;pendingResponse=false;streaming=false;terminal=false;sawChatChoice=false;untrackedChoices=false;openChoices=new Set;responseId;operation;api;constructor(e,t){this.options=t,this.api=e.api,this.operation=e.operation==="responses.retrieve"||e.operation==="responses.cancel"?"responses":e.operation;}stream(){this.streaming=true;}fail(e,t=false){this.failure=e,this.failureCancelled=t;}take(e){if(typeof e!="string")return "";let t=e.slice(0,this.remaining);return this.remaining-=t.length,t.length<e.length&&(this.truncated=true),t}part(e,t){if(!this.options.captureBodies)return;let r=this.parts.get(e);if(r)return r;if(this.parts.size>=Kt){this.truncated=true;return}return this.parts.set(e,t),t}append(e,t,r){typeof r!="string"||r.length===0||(this.token(),this.outputBytes=Math.min(2147483647,this.outputBytes+Vt.encode(r).length),e&&(e[t]=String(e[t]??"")+this.take(r)));}tool(e,t){if(typeof e!="string"||e.length===0)return;let r=this.streamedTools.get(e);if(r)return r;if(this.streamedTools.size>=Jt)return;let s={id:e,name:t.name??"tool",arguments:""};return this.streamedTools.set(e,s),s}appendArguments(e,t){!e||typeof t!="string"||(typeof e.arguments!="string"&&(e.arguments=""),e.arguments.length<65536&&(e.arguments=e.arguments+t));}token(){this.firstTokenAt===void 0&&(this.firstTokenAt=this.options.now(),this.attributes[g.timeToFirstTokenMs]=Math.max(0,this.firstTokenAt-this.options.startedAt));}response(e){let t=f(e);typeof t.id=="string"&&t.id&&(this.responseId=t.id),typeof t.status=="string"&&(this.pendingResponse=t.status==="queued"||t.status==="in_progress");let r=f(t.usage);this.usage={...this.usage,...Object.fromEntries(Object.entries(r).filter(([,i])=>i!=null))};let s=Ht(this.api,{...t,usage:this.usage}),o=s[g.outputTokens];typeof o=="number"&&(this.outputTokens=o),Object.assign(this.attributes,s);}complete(e){if(this.terminal=true,this.response(e),this.finalOutput=e,this.completeToolCalls=Se(this.api,f(e)),this.operation==="responses"){let t=f(e);if(t.status==="queued"||t.status==="in_progress")return;this.responseOutcome(t),t.status==="cancelled"&&(this.failureCancelled=true);}}responseOutcome(e){if(this.pendingResponse=false,typeof e.status=="string"&&(this.attributes[g.responseStatus]=e.status),e.status==="failed"){let t=f(e.error);this.failure={type:typeof t.code=="string"&&t.code?t.code:"provider_error",message:typeof t.message=="string"&&t.message?t.message:"Provider response failed"};}if(e.status==="incomplete"){let t=f(e.incomplete_details).reason;typeof t=="string"&&(this.attributes[g.finishReasons]=[t]),this.failure={type:"incomplete_response",message:typeof t=="string"?`Provider response incomplete: ${t}`:"Provider response incomplete"};}}chunk(e){let t=f(e);if(this.operation==="chat.completions"){this.response(t);for(let r of w(t.choices)){let s=f(r),o=f(s.delta),i=typeof s.index=="number"?s.index:0;this.sawChatChoice=true,Number.isInteger(i)&&i>=0&&i<Gt?typeof s.finish_reason=="string"&&s.finish_reason.length>0?this.openChoices.delete(i):this.openChoices.add(i):this.untrackedChoices=true;let a=this.part(`choice:${i}`,{index:i,role:"assistant"});this.append(a,"content",o.content),this.append(a,"refusal",o.refusal),this.append(a,"reasoning",o.reasoning_content);for(let d of w(o.tool_calls)){let u=f(d),c=f(u.function),p=typeof u.index=="number"?u.index:0,l=`tool:${i}:${p}`,m=this.part(l,{type:"function_call",index:p,choice_index:i});m&&typeof u.id=="string"&&(m.id=this.take(u.id)),this.append(m,"name",c.name),this.append(m,"arguments",c.arguments);let h=this.tool(typeof u.id=="string"?u.id:void 0,{name:typeof c.name=="string"?c.name:void 0})??this.streamedToolAt(l);h&&(typeof u.id=="string"&&this.streamedToolKeys.set(l,u.id),typeof c.name=="string"&&c.name&&(h.name=c.name),this.appendArguments(h,c.arguments));}}this.terminal=this.sawChatChoice&&this.openChoices.size===0&&!this.untrackedChoices;return}if(this.operation==="responses"){if(t.response!==void 0&&this.response(t.response),t.type==="response.output_text.delta"||t.type==="response.refusal.delta"||t.type==="response.reasoning_summary_text.delta"){let r=typeof t.output_index=="number"?t.output_index:0,s=this.part(`${String(t.type)}:${r}`,{type:t.type,output_index:r});this.append(s,"text",t.delta);}if(t.type==="response.function_call_arguments.delta"){let r=typeof t.output_index=="number"?t.output_index:0,s=this.part(`function:${r}`,{type:"function_call",output_index:r});this.append(s,"arguments",t.delta),this.appendArguments(this.streamedToolAt(`function:${r}`),t.delta);}if(t.type==="response.output_item.added"){let r=f(t.item);if(r.type==="function_call"){let s=typeof t.output_index=="number"?t.output_index:0,o=this.part(`function:${s}`,{type:"function_call",output_index:s});o&&(o.name=this.take(r.name),o.call_id=this.take(r.call_id));let i=this.tool(r.call_id??r.id,{name:typeof r.name=="string"?r.name:void 0});i&&(this.streamedToolKeys.set(`function:${s}`,i.id),this.appendArguments(i,r.arguments));}}if(t.type==="response.completed"||t.type==="response.incomplete"||t.type==="response.failed"){this.terminal=true,this.finalOutput=t.response,this.completeToolCalls=Se(this.api,f(t.response));let r=f(t.response);this.responseOutcome({...r,status:r.status??String(t.type).slice(9)});}t.type==="error"&&(this.failure=U(t.error??t));return}if(t.type==="message_start"&&this.response(t.message),t.type==="message_stop"&&(this.terminal=true),t.type==="message_delta"&&this.response({...f(t.delta),usage:t.usage}),t.type==="content_block_start"){let r=f(t.content_block),s=typeof t.index=="number"?t.index:0,o=this.part(`block:${s}`,{type:r.type,index:s});if(o&&(typeof r.id=="string"&&(o.id=this.take(r.id)),typeof r.name=="string"&&(o.name=this.take(r.name)),r.type==="tool_use")){let i=jt(r.input);i!==void 0&&(o.input=Te(i));}if(r.type==="tool_use"){let i=this.tool(r.id,{name:typeof r.name=="string"?r.name:void 0});i&&this.streamedToolKeys.set(`block:${s}`,i.id);}this.append(o,"text",r.text),this.append(o,"thinking",r.thinking);}if(t.type==="content_block_delta"){let r=typeof t.index=="number"?t.index:0,s=f(t.delta),o=this.part(`block:${r}`,{index:r});this.append(o,"text",s.text),this.append(o,"thinking",s.thinking),this.append(o,"partial_json",s.partial_json),this.appendArguments(this.streamedToolAt(`block:${r}`),s.partial_json);}t.type==="error"&&(this.failure=U(t.error??t));}streamedToolKeys=new Map;streamedToolAt(e){let t=this.streamedToolKeys.get(e);return t?this.streamedTools.get(t):void 0}output(){if(this.finalOutput!==void 0)return this.finalOutput;if(!this.options.captureBodies)return;let e=[...this.parts.values()];return this.truncated?{content:e,truncated:true}:e}toolCalls(){return this.completeToolCalls?this.completeToolCalls:[...this.streamedTools.values()].map(e=>({...e,arguments:Te(e.arguments)}))}finish(e={}){let t=e.cancelled===true||this.failureCancelled||this.pendingResponse;this.streaming&&!this.terminal&&!t&&this.failure===void 0&&(this.failure={type:"incomplete_stream",message:"Provider stream ended before its terminal event"});for(let a of this.parts.values())if(a.type==="tool_use"&&typeof a.partial_json=="string")try{a.input=JSON.parse(a.partial_json);}catch{}let r={...this.attributes};if(this.firstTokenAt!==void 0&&this.outputTokens!==void 0){let a=(this.options.now()-this.firstTokenAt)/1e3;a>0&&(r[g.tokensPerSecond]=this.outputTokens/a);}let s=this.toolCalls();s.length>0&&(r[g.responseToolCalls]=s.length),this.failure&&(r[g.errorType]=this.failure.type,this.failure.status!==void 0&&(r[g.errorStatus]=this.failure.status));let o=this.pendingResponse&&this.failure===void 0&&!e.cancelled,i={status:this.failure?this.failureCancelled?"cancelled":"error":t&&!o?"cancelled":"ok",attributes:r,output:this.output(),outputBytes:this.outputBytes,outputTruncated:this.truncated&&this.finalOutput===void 0,pending:o,toolCalls:s};return this.failure&&(i.error=this.failure),this.responseId&&(i.responseId=this.responseId),i}};function we(n){let e=f(n),t=w(e.messages),r=e.input,s=t.length?t:w(r);for(let o=s.length-1;o>=0;o--){let i=f(s[o]);if(i.role!=="user")continue;let a=w(i.content);if(!(a.length>0&&a.every(d=>f(d).type==="tool_result")))return i.content}return r}function ve(n){if(typeof n=="string")return n||void 0;let e=f(n),t=[];for(let s of w(e.choices)){let o=f(f(s).message),i=o.content??o.refusal;typeof i=="string"&&i&&t.push(i);}let r=Array.isArray(n)?n:w(e.content).length?w(e.content):w(e.output);for(let s of r){let o=f(s);if(typeof o.content=="string"&&o.content)t.push(o.content);else if(typeof o.text=="string"&&o.text&&o.type!=="response.reasoning_summary_text.delta")t.push(o.text);else for(let i of w(o.content)){let a=f(i);(a.type==="text"||a.type==="output_text")&&typeof a.text=="string"&&t.push(a.text);}}return t.length?t.join(`
|
|
4
|
+
`):void 0}var We=8192;function ae(n){return typeof n=="string"?n:w(n).map(e=>{let t=f(e);return typeof t.text=="string"?t.text:typeof t.input_text=="string"?t.input_text:""}).join(`
|
|
5
|
+
`)}function ke(n,e){let t=`${n.slice(0,We)}\0${e.slice(0,We)}`;if(!(t.length<=1))return J(`tracehatch.conversation.v1\0${t}`)}function V(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}function Xt(n){let e=w(n.messages).map(u=>f(u)),t=e.filter(u=>u.role==="system"||u.role==="developer").map(u=>ae(u.content)).join(`
|
|
6
|
+
`),r=e.find(u=>u.role==="user"),s=e.at(-1),o=new Map;for(let u of e)if(u.role==="assistant")for(let c of w(u.tool_calls)){let p=f(c),l=f(p.function);typeof p.id=="string"&&o.set(p.id,{id:p.id,name:typeof l.name=="string"&&l.name?l.name:"tool",arguments:V(l.arguments)});}let i=[];for(let u=e.length-1;u>=0;u--){let c=e[u];if(c.role!=="tool")break;let p=c.tool_call_id;if(typeof p!="string")continue;let l=o.get(p);i.unshift({callId:p,...l?{name:l.name,input:l.arguments}:{},output:V(c.content),isError:false});}let a={turn:s?.role==="tool"?"tool":s?.role==="user"?"user":"none",toolResults:i},d=r?ke(t,ae(r.content)):void 0;return d&&(a.fingerprint=d),typeof n.user=="string"&&n.user&&(a.userId=n.user),a}function Qt(n){let e=typeof n.instructions=="string"?n.instructions:"",t=typeof n.input=="string"?[{role:"user",content:n.input,type:"message"}]:w(n.input).map(p=>f(p)),r=p=>(p.type===void 0||p.type==="message")&&p.role==="user",s=t.find(r),o=t.at(-1),i=new Map;for(let p of t){if(p.type!=="function_call")continue;let l=p.call_id??p.id;typeof l=="string"&&i.set(l,{id:l,name:typeof p.name=="string"&&p.name?p.name:"tool",arguments:V(p.arguments)});}let a=[];for(let p=t.length-1;p>=0;p--){let l=t[p];if(l.type!=="function_call_output")break;let m=l.call_id;if(typeof m!="string")continue;let h=i.get(m);a.unshift({callId:m,...h?{name:h.name,input:h.arguments}:{},output:V(l.output),isError:false});}let d={turn:o?.type==="function_call_output"?"tool":o&&r(o)?"user":"none",toolResults:a},u=typeof n.conversation=="string"?n.conversation:f(n.conversation).id;typeof u=="string"&&u&&(d.conversationId=u),typeof n.previous_response_id=="string"&&n.previous_response_id&&(d.previousResponseId=n.previous_response_id);let c=s?ke(e,ae(s.content)):void 0;return c&&(d.fingerprint=c),typeof n.user=="string"&&n.user&&(d.userId=n.user),d}function Zt(n){let e=w(n.messages).map(l=>f(l)),t=ae(n.system),r=l=>typeof l.content=="string"?[{type:"text",text:l.content}]:w(l.content).map(m=>f(m)),s=l=>{let m=r(l);return l.role==="user"&&m.length>0&&m.every(h=>h.type==="tool_result")},o=e.find(l=>l.role==="user"&&!s(l)),i=e.at(-1),a=new Map;for(let l of e)if(l.role==="assistant")for(let m of r(l))m.type==="tool_use"&&typeof m.id=="string"&&a.set(m.id,{id:m.id,name:typeof m.name=="string"&&m.name?m.name:"tool",arguments:m.input});let d=[];if(i&&s(i))for(let l of r(i)){let m=l.tool_use_id;if(typeof m!="string")continue;let h=a.get(m);d.push({callId:m,...h?{name:h.name,input:h.arguments}:{},output:typeof l.content=="string"?V(l.content):l.content,isError:l.is_error===true});}let u={turn:i?s(i)?"tool":i.role==="user"?"user":"none":"none",toolResults:d},c=o?ke(t,r(o).map(l=>typeof l.text=="string"?l.text:"").join(`
|
|
7
|
+
`)):void 0;c&&(u.fingerprint=c);let p=f(n.metadata).user_id;return typeof p=="string"&&p&&(u.userId=p),u}function Ge(n,e){let t=f(e);try{switch(n.operation){case "chat.completions":return Xt(t);case "responses":return Qt(t);case "messages":return Zt(t);default:return {turn:"none",toolResults:[]}}}catch{return {turn:"none",toolResults:[]}}}function Ke(n){return `auto-${n.slice(0,32)}`}var Yt={maxConversations:1e4,turnGapMs:5*6e4},en=5e4,X=class{conversations=new Map;responses=new Map;options;constructor(e={}){this.options={...Yt,...e};}key(e){if(e.conversationId)return `conv:${e.conversationId}`;if(e.previousResponseId){let t=this.responses.get(e.previousResponseId);if(t)return t}if(e.fingerprint)return `fp:${e.fingerprint}`}begin(e,t){let r={toolSpans:[]};e.userId&&(r.userId=e.userId);let s=this.key(e),o=s?this.conversations.get(s):void 0,i=o?.sessionId??e.conversationId??(e.fingerprint?Ke(e.fingerprint):void 0);i&&(r.sessionId=i),s&&o&&(this.conversations.delete(s),this.conversations.set(s,o));let a=o?.openTraceId!==void 0&&e.turn==="tool"&&t-o.lastEndedAt<=this.options.turnGapMs;if(a?r.traceId=o.openTraceId:o?.openTraceId&&(r.endTraceId=o.openTraceId,o.openTraceId=void 0),e.turn==="tool"){let d=new Map((o?.lastToolCalls??[]).map(u=>[u.id,u]));for(let u of e.toolResults){let c=d.get(u.callId);r.toolSpans.push({callId:u.callId,name:u.name??c?.name??"tool",input:u.input??c?.arguments,output:u.output,status:u.isError?"error":"ok",startedAt:a?o.lastEndedAt:t,endedAt:t});}}return r}complete(e,t){let r=t.toolCalls.length===0,s=this.key(e);if(!s)return {final:r};let o=this.conversations.get(s)?.sessionId??e.conversationId??(e.fingerprint?Ke(e.fingerprint):void 0);for(this.conversations.delete(s),this.conversations.set(s,{sessionId:o,openTraceId:r?void 0:t.traceId,lastEndedAt:t.endedAt,lastToolCalls:t.toolCalls});this.conversations.size>this.options.maxConversations;){let i=this.conversations.keys().next().value;if(i===void 0)break;this.conversations.delete(i);}if(t.responseId)for(this.responses.delete(t.responseId),this.responses.set(t.responseId,s);this.responses.size>en;){let i=this.responses.keys().next().value;if(i===void 0)break;this.responses.delete(i);}return {final:r}}release(e){for(let t of this.conversations.values())t.openTraceId===e&&(t.openTraceId=void 0);}};function ce(n){return process.env[`TRACEHATCH_${n}`]}function Je(n={}){return {apiKey:n.apiKey??ce("API_KEY"),baseUrl:n.baseUrl??ce("BASE_URL"),release:n.release??ce("RELEASE"),agent:n.agent??ce("AGENT")}}function Ve(n){let e=new URL(n);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new TypeError("Tracehatch baseUrl must be an HTTP(S) URL without credentials, query, or fragment");return e.pathname=e.pathname.replace(/\/+$/,"")||"/api/v1",e.toString().replace(/\/+$/,"")}function Xe(){let n=process.env;return !!(n.AWS_LAMBDA_FUNCTION_NAME||n.VERCEL||n.NETLIFY||n.FUNCTIONS_WORKER_RUNTIME||n.CF_PAGES)}var Ie="0123456789abcdefghjkmnpqrstvwxyz";var tn=new Map;for(let n=0;n<Ie.length;n++)tn.set(Ie[n],n);function Qe(n){let e=0n;for(let s of n)e=e<<8n|BigInt(s);let t=Math.ceil(n.length*8/5),r=new Array(t);for(let s=t-1;s>=0;s--)r[s]=Ie[Number(e&31n)],e>>=5n;return r.join("")}function H(n){let e=crypto.randomBytes(16);return e.writeUIntBE(Date.now(),0,6),e[6]=e[6]&15|112,e[8]=e[8]&63|128,`${n}_${Qe(e)}`}var rn=/(?:authorization|proxyauthorization|apikey|x[a-z0-9]+key|password|passwd|secret|accesstoken|refreshtoken|authtoken|clientsecret|privatekey|credential|cookie|setcookie|token)$/i,Ze=/\[REDACTED:[\w.-]+\]/g;function sn(n){let e=n.replace(/\D/g,"");if(e.length<13||e.length>19||/^(\d)\1+$/.test(e))return false;let t=0,r=false;for(let s=e.length-1;s>=0;s--){let o=Number(e[s]);r&&(o*=2,o>9&&(o-=9)),t+=o,r=!r;}return t%10===0}var Ye=[{name:"secret",pattern:/\b(?:sk-(?:proj-|ant-api\d{2}-)?[A-Za-z0-9_-]{12,}|(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|[a-z][a-z0-9]{1,15}_(?:live|test|pat)_[A-Za-z0-9_-]{12,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b|\bBearer\s+[A-Za-z0-9._~+/-]+=*|\b(?:api[_-]?key|password|passwd|client[_-]?secret|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[^\s,"';}]+/gi},{name:"email",pattern:/\b[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9-]+(?:\.[A-Z0-9-]+)+\b/gi},{name:"iban",pattern:/\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]){11,30}\b/g},{name:"card",pattern:/(?<![\w])\d(?:[ -]?\d){12,18}(?![\w])/g,accepts:sn},{name:"phone",pattern:/(?<![\w])(?:\+\d{1,3}[ .-]?)?(?:\(\d{2,4}\)|\d{2,4})[ .-]?\d{3,4}[ .-]?\d{3,4}(?![\w])/g,accepts:n=>{let e=n.replace(/\D/g,"").length;return e>=10&&e<=15}}];function et(n,e={}){let t=Object.create(null),r=new WeakSet,s=0,o=true,i=[];try{o=e.builtIns!==!1,o&&i.push(...Ye);for(let c of e.rules??[]){if(!/^[\w.-]{1,64}$/.test(c.name))continue;let p=c.pattern.flags.replace(/[gy]/g,"")+"g";i.push({name:c.name,pattern:new RegExp(c.pattern.source,p)});}}catch{i.length===0&&i.push(...Ye);}function a(c){return t[c]=(t[c]??0)+1,`[REDACTED:${c}]`}function d(c){for(let p of i)c=c.split(/(\[REDACTED:[\w.-]+\])/g).map(l=>(Ze.lastIndex=0,Ze.test(l)?l:l.replace(p.pattern,m=>p.accepts&&!p.accepts(m)?m:a(p.name)))).join("");return c}function u(c,p){if(s++,s>5e4||p>32)return "[Truncated]";if(typeof c=="string")return d(c);if(typeof c=="bigint")return d(c.toString());if(typeof c=="number")return Number.isFinite(c)?c:null;if(c===null||typeof c=="boolean")return c;if(typeof c>"u")return null;if(typeof c!="object")return `[${typeof c}]`;if(r.has(c))return "[Circular]";r.add(c);try{if(c instanceof Date){let h=Date.prototype.getTime.call(c);return Number.isFinite(h)?Date.prototype.toISOString.call(c):null}let l=Object.getOwnPropertyDescriptors(c);if(Array.isArray(c)){let h=[],_=Number(l.length?.value??0),k=Math.min(_,5e4-s);for(let I=0;I<k;I++){let S=l[String(I)];if(h.push(S&&"value"in S?u(S.value,p+1):null),s>=5e4)break}return h.length<_&&h.push("[Truncated]"),h}let m=Object.create(null);for(let[h,_]of Object.entries(l)){if(!_.enumerable)continue;if(s>=5e4)break;let k=d(h);m[k]=o&&rn.test(h.replace(/[^a-z0-9]/gi,""))?a("secret"):"value"in _?u(_.value,p+1):"[Getter]";}return m}catch{return "[Unserializable]"}finally{r.delete(c);}}try{return {value:u(n,0),counts:t}}catch{return {value:"[Unserializable]",counts:t}}}function T(n,e){if(!(n===null||typeof n!="object"))try{let t=Object.getOwnPropertyDescriptor(n,e);return t&&"value"in t?t.value:void 0}catch{return}}function L(n,e){return et(n,e.redact===false?{builtIns:false}:e.redact).value}function Ae(n){return JSON.stringify(n)??"null"}function W(n){return n==null?0:buffer.Buffer.byteLength(typeof n=="string"?n:Ae(n))}function rt(n,e){let t=Math.max(0,Math.min(e,n.length));for(;t>0&&t<n.length&&(n[t]&192)===128;)t--;return n.subarray(0,t).toString("utf8")}function an(n,e){let t=Math.max(0,n.length-e);for(;t<n.length&&(n[t]&192)===128;)t++;return n.subarray(t).toString("utf8")}function tt(n,e){let t=buffer.Buffer.from(n);return t.length<=e?n:rt(t,e)}function st(n,e){if(W(n)<=e)return n;let t=buffer.Buffer.from(typeof n=="string"?n:Ae(n)),r=`\u2026[truncated ${t.length} B]\u2026`,s=Math.max(0,e-buffer.Buffer.byteLength(r)),o=Math.floor(s*.75);return rt(t,o)+r+an(t,s-o)}function M(n,e,t,r=""){let s=typeof n=="string"?L(n,t):r,o=String(s).slice(0,e);return /[\uD800-\uDBFF]$/.test(o)?o.slice(0,-1):o}function nt(n,e,t,r){if(typeof n!="string")return "";if(M(n,t,r)===n)return n;let o=crypto.createHash("sha256").update(`tracehatch.sdk.identifier.v1\0${e}\0`).update(JSON.stringify(n)).digest("hex");return `redacted-${e}-${o}`}function cn(n){if(n.redact===false)return "disabled";try{return JSON.stringify([n.redact.builtIns!==!1,...(n.redact.rules??[]).map(({name:e,pattern:t})=>[e,t.source,t.flags.replace(/[gy]/g,"")])])}catch{return Symbol("invalid redaction policy")}}function it(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Q(n,e){let t=it(L(n,e));if(!t)return;let r=Object.create(null),s=false;for(let[o,i]of Object.entries(t)){let a=o.slice(0,x.maxAttributeKeyLength);if(!a)continue;if($e.includes(a)&&typeof i=="number"&&(!Number.isFinite(i)||i<0||i>x.maxCount)){a!==g.timeToFirstTokenMs&&(r[g.pricingIncomplete]=true);continue}let d;if(typeof i=="string"||typeof i=="boolean"||typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(c=>typeof c=="string")?d=i:d=Ae(i),Object.keys(r).length>=x.maxAttributesPerSpan){s=true;break}let u={...r,[a]:d};if(W(u)>x.maxAttributesObjectBytes){s=true;continue}o!==a&&(s=true),r[a]=d;}if(s)for(r[g.attributesTruncated]=true;Object.keys(r).length>x.maxAttributesPerSpan||W(r)>x.maxAttributesObjectBytes;){let o=Object.keys(r).reverse().find(i=>i!==g.attributesTruncated);if(!o)break;delete r[o];}return r}function un(n,e){let t=it(L(n,e));if(!t)return;let r=Object.create(null);for(let[s,o]of Object.entries(t))W({...r,[s]:o})<=x.maxMetadataBytes&&(r[s]=o);return r}function Ee(n,e){let t;try{if(!Array.isArray(n))return;t=Math.min(n.length,x.maxEventsPerSpan);}catch{return}let r=[];for(let s=0;s<t;s++){let o=T(n,String(s)),i=T(o,"ts");if(typeof i!="string"||!Number.isFinite(Date.parse(i)))continue;let a=T(o,"level");r.push({ts:new Date(i).toISOString(),level:a==="debug"||a==="warn"||a==="error"?a:"info",name:M(T(o,"name"),x.maxNameLength,e,"event")||"event",attributes:Q(T(o,"attributes"),e)});}return r}function de(n,e){let t={id:n.id,trace_id:n.trace_id,parent_id:n.parent_id,name:M(T(n,"name"),x.maxNameLength,e,"span")||"span",kind:n.kind,status:n.status,started_at:n.started_at,ended_at:n.ended_at,attempt:Math.max(1,Math.min(1e3,Math.floor(n.attempt)||1)),attributes:Q(T(n,"attributes"),e),events:Ee(T(n,"events"),e)},r=T(n,"error");if(r!==void 0){t.error={};let s=T(r,"type"),o=T(r,"message"),i=T(r,"stack");typeof s=="string"&&(t.error.type=M(s,x.maxErrorTypeLength,e)),typeof o=="string"&&(t.error.message=tt(String(L(o,e)),x.maxErrorMessageBytes)),typeof i=="string"&&(t.error.stack=tt(String(L(i,e)),b.maxStackBytes));}for(let s of ["input","output","messages"]){let o=T(n,s),i=`${s}_bytes`,a=`${s}_truncated`,d=T(n,i),u=typeof d=="number"&&Number.isSafeInteger(d)&&d>=0?Math.min(d,x.maxCount):void 0;if(o!==void 0){if(t[i]=u??Math.min(x.maxCount,W(L(o,{...e,redact:false}))),e.captureBodies){let c=L(o,e);t[s]=st(c,x.maxAttributeBytes),(T(n,a)===true||W(c)>x.maxAttributeBytes)&&(t[a]=true);}}else u!==void 0&&(t[i]=u),e.captureBodies&&T(n,a)===true&&(t[a]=true);}return t}function Re(n,e,t,r="span_id"){if(!Le.test(n))return;let s=M(T(e,"name"),x.maxScoreNameLength,t).trim(),o=T(e,"value"),i=typeof o=="string"?M(o,x.maxScoreValueLength,t).trim():o;if(!s||!(typeof i=="number"&&Number.isFinite(i)||typeof i=="string"&&i.length>0))return;let a=T(e,r);if(a!==void 0&&(typeof a!="string"||!Ne.test(a)))return;let d={id:n,name:s,value:i};typeof a=="string"&&(d.span_id=a);let u=T(e,"comment");if(!(u!==void 0&&typeof u!="string"))return typeof u=="string"&&(d.comment=M(u,x.maxScoreCommentLength,t)),d}function Z(n,e){let t=y.serializedTraceIdentities??=new WeakMap,r=t.get(n),s=cn(e),o=r?.policy===s,i={id:n.id,name:M(T(n,"name"),x.maxNameLength,e,"trace")||"trace",started_at:n.started_at,ended_at:n.ended_at,status:n.status,root_span_id:n.root_span_id,...n.expected_span_count!==void 0?{expected_span_count:n.expected_span_count}:{}};for(let[h,_]of [["agent",x.maxAgentLength],["release",x.maxReleaseLength]]){let k=M(T(n,h),_,e);k&&(i[h]=k);}let a=T(n,"session_id"),d=o&&r?.sessionId===a?r.sessionId:nt(a,"session",x.maxSessionIdLength,e);d&&(i.session_id=d);let u=T(n,"user"),c=T(u,"id"),p=o&&r?.userId===c?r.userId:nt(c,"user",x.maxUserIdLength,e);if(p){i.user={id:p};let h=T(u,"name"),_=T(u,"email");typeof h=="string"&&(i.user.name=M(h,x.maxUserNameLength,e)),typeof _=="string"&&(i.user.email=M(_,320,e));}let l=L(T(n,"tags"),e);Array.isArray(l)&&(i.tags=[...new Set(l.filter(h=>typeof h=="string").map(h=>h.slice(0,x.maxTagLength)).filter(Boolean))].slice(0,x.maxTagsPerTrace)),i.metadata=un(T(n,"metadata"),e);let m=T(n,"scores");if(Array.isArray(m)){i.scores=[];for(let h=0;h<Math.min(m.length,x.maxScoresPerTrace);h++){let _=T(m,String(h)),k=T(_,"id"),I=typeof k=="string"?Re(k,_,e):void 0;I&&i.scores.push(I);}}if(e.captureBodies)for(let h of ["input","output"]){let _=T(n,h);_!==void 0&&(i[h]=st(L(_,e),x.traceBodyBytes));}return t.set(i,{policy:s,sessionId:d,userId:p}),i}var j=class{constructor(e,t,r,s={},o,i,a={}){this.trace=e;this.parent=o;this.isTool=r==="tool",this.isTool&&(this.toolCallId=ot(s.attributes)),this.id=i??H("span");let d=a.startedAt??F();if(this.data={id:this.id,trace_id:e?.id??"",parent_id:o?.id??null,name:t,kind:r,started_at:d,ended_at:d,status:"ok",attempt:1,input:s.input,attributes:s.attributes},this.sanitize(),!i&&this.isRecording&&e?.registerSpan(this),s.signal){let u=s.signal,c=()=>this.end({status:"cancelled"});u.aborted?c():(u.addEventListener("abort",c,{once:true}),this.removeAbort=()=>u.removeEventListener("abort",c));}}trace;parent;id;ended=false;outputSet=false;removeAbort;data;isTool;toolCallId;get isRecording(){return !this.ended&&!!this.trace?.isRecording}get isEnded(){return this.ended}get hasOutput(){return this.outputSet}sanitize(){try{this.trace&&(this.data=de(this.data,this.trace.client.options));}catch{}}run(e){return this.trace?y.storage.run({trace:this.trace,span:this},e):e()}setInput(e){this.ended||(this.data.input=e,delete this.data.input_bytes,delete this.data.input_truncated,this.sanitize());}setOutput(e){this.ended||(this.outputSet=true,this.data.output=e,delete this.data.output_bytes,delete this.data.output_truncated,this.sanitize());}setOutputBytes(e){this.ended||(this.data.output_bytes=Math.min(2147483647,Math.max(0,e)));}markOutputTruncated(){this.ended||(this.data.output_truncated=true);}setMessages(e){this.ended||(this.data.messages=e,delete this.data.messages_bytes,delete this.data.messages_truncated,this.sanitize());}setAttributes(e){if(!this.ended)try{if(!this.trace)return;let t=Q(e,this.trace.client.options);this.data.attributes=Q({...this.data.attributes,...t},this.trace.client.options),this.isTool&&Object.hasOwn(e,g.toolCallId)&&(this.toolCallId=ot(e));}catch{}}addEvent(e,t,r="info"){if(!(this.ended||(this.data.events?.length??0)>=100))try{if(!this.trace)return;let s=Ee([{ts:F(),name:e,attributes:t,level:r}],this.trace.client.options);this.data.events=[...this.data.events??[],...s??[]];}catch{}}setAttempt(e){this.ended||(this.data.attempt=e);}end(e={}){if(!this.ended&&(this.ended=true,this.removeAbort?.(),this.trace?.unregisterSpan(this),!!this.trace?.isRecording))try{"output"in e&&(this.data.output=e.output,delete this.data.output_bytes,delete this.data.output_truncated),this.data.ended_at=e.endedAt??F(),this.data.status=e.status??("error"in e?"error":"ok"),"error"in e&&(this.data.error=ct(e.error)),this.isTool&&this.toolCallId&&this.trace.rememberToolCall(this.toolCallId),this.trace.client.enqueue(this.data,this.trace.snapshot());}catch{}}};function ot(n){try{let e=n&&Object.getOwnPropertyDescriptor(n,g.toolCallId)?.value;return typeof e=="string"&&e?e:void 0}catch{return}}function ct(n){try{return n instanceof Error?{type:n.name||n.constructor.name,message:n.message,stack:n.stack}:{type:"Error",message:String(n)}}catch{return {type:"Error",message:"Unserializable error"}}}function pe(n,e,t={}){let r=R(),s=r?.span;for(;s?.isEnded&&s.parent;)s=s.parent;return new j(r?.trace,n,e,t,s)}async function ut(n,e,t,r={}){if(!R()&&y.client?.isEnabled)return at(n,()=>ut(n,e,t,r),{signal:r.signal});let s;try{s=pe(n,e,r);}catch{return await t(dn)}try{let o=await s.run(()=>t(s));return s.end(o===void 0||s.hasOutput?{}:{output:o}),o}catch(o){throw s.end({error:o,status:r.signal?.aborted?"cancelled":"error"}),o}}async function jr(n,e,t={}){let r=Number.isFinite(t.retries)?Math.min(999,Math.max(0,Math.floor(t.retries))):0,s=Number.isFinite(t.backoffMs)?Math.max(0,Math.min(6e4,t.backoffMs)):0;return ut(n,"tool",async o=>{for(let i=1;;i++){let a=perf_hooks.performance.now();"setAttempt"in o&&o.setAttempt(i);try{let d=await e(o);return o.addEvent("tool.attempt",{attempt:i,duration_ms:perf_hooks.performance.now()-a}),d}catch(d){if(o.addEvent("tool.attempt",{attempt:i,duration_ms:perf_hooks.performance.now()-a,error:ct(d).message??"Error"},"error"),i>r||t.signal?.aborted)throw d;s&&await new Promise(u=>setTimeout(u,s));}}},{...t,attributes:{...t.attributes,[g.toolName]:n}})}var dn={id:"",setOutput(){},setAttributes(){},addEvent(){}};var K=class{linker=new X;open=new Map;boundLinkers=new WeakMap;recordedTools=new WeakMap;boundLinker(e){let t=this.boundLinkers.get(e);return t||(t=new X,this.boundLinkers.set(e,t)),t}beginBound(e,t,r){for(let s of this.boundLinker(e).begin(t,r).toolSpans)this.recordTool(e,s);}completeBound(e,t,r){this.boundLinker(e).complete(t,{traceId:e.id,...r});}begin(e,t,r,s,o){let i=this.linker.begin(r,o);i.endTraceId&&this.end(i.endTraceId,"ok");let a=i.traceId?this.open.get(i.traceId):void 0,d=a?.trace;if(!d||d.isEnded){i.traceId&&this.linker.release(i.traceId);let u={metadata:{"tracehatch.capture":"auto"}};i.sessionId&&(u.sessionId=i.sessionId),i.userId&&(u.user={id:i.userId}),d=new q(e,s??t.operation,u,{inferProviderBodies:true});}else a&&(clearTimeout(a.timer),this.open.delete(d.id));for(let u of i.toolSpans)this.recordTool(d,u);return d}recordTool(e,t){try{let r=this.recordedTools.get(e);if(r||(r=new Set,this.recordedTools.set(e,r)),r.has(t.callId)||e.hasRecordedToolCall(t.callId))return;r.add(t.callId);let s=new j(e,t.name,"tool",{input:t.input,attributes:{[g.toolName]:t.name,[g.toolCallId]:t.callId}},e.root,void 0,{startedAt:new Date(t.startedAt).toISOString()}),o=new Error("The tool reported an error");o.name="tool_error",s.end({status:t.status,output:t.output,endedAt:new Date(t.endedAt).toISOString(),...t.status==="error"?{error:o}:{}});}catch{}}complete(e,t,r){let{final:s}=this.linker.complete(t,{traceId:e.id,responseId:r.responseId,toolCalls:r.toolCalls,endedAt:r.endedAt});if(s||r.status!=="ok"){this.end(e.id,r.status,new Date(r.endedAt).toISOString(),e);return}let o=setTimeout(()=>this.end(e.id,"cancelled"),b.autoRunIdleMs);o.unref?.(),this.open.set(e.id,{trace:e,timer:o,lastEndedAt:r.endedAt});}end(e,t,r,s){let o=this.open.get(e);o&&(clearTimeout(o.timer),this.open.delete(e)),this.linker.release(e);let i=s??o?.trace;!i||i.isEnded||(i.end({outcome:t,endedAt:r??(o?new Date(o.lastEndedAt).toISOString():void 0)}),Xe()&&pn(i.client));}endAll(e="ok"){for(let t of [...this.open.keys()])this.end(t,e);}};function pn(n){let e=n.flush();try{globalThis[Symbol.for("@vercel/request-context")]?.get?.()?.waitUntil?.(e);}catch{}}function dt(){let n=y.capture??={},e=globalThis.fetch;if(typeof e!="function"||n.patchedFetch&&e===n.patchedFetch)return;n.originalFetch=e;let t=(r,s)=>In(r,s);n.patchedFetch=t,globalThis.fetch=t;}function pt(){let n=y.capture;n?.patchedFetch&&(globalThis.fetch===n.patchedFetch&&n.originalFetch&&(globalThis.fetch=n.originalFetch),n.patchedFetch=void 0,n.originalFetch=void 0);}function ee(){return y.autoRuns??=new K}var ln=1e3,z=new Map,Y=new Map,D=new Map,fn=new TextDecoder;async function hn(n,e){if(!n.length||e?.aborted)return;let t,r,s=new Promise(o=>{t=setTimeout(o,b.toolMetadataSettleMs),r=o,e?.addEventListener("abort",r,{once:true});});try{await Promise.race([Promise.allSettled(n),s]);}finally{clearTimeout(t),r&&e?.removeEventListener("abort",r);}}function mn(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(String).join(", ")}function gn(n,e){return t=>{let r=n?.headers,s=t.toLowerCase();if(r){if(r instanceof Headers)return r.get(t);let i=(Array.isArray(r)?r:Object.entries(r)).find(([a])=>typeof a=="string"&&a.toLowerCase()===s);if(i)return mn(i[1])}return e?.headers.get(t)}}function yn(n,e){let t=typeof Request<"u"&&n instanceof Request?n:void 0,r=typeof n=="string"?n:n instanceof URL?n.href:t?.url;if(!r)return;let s=e?.method??t?.method??"GET",o=je(s,r,{header:gn(e,t)});return o?{route:o,url:r,method:s}:void 0}async function bn(n,e){let t=e?.body;if(t==null){if(typeof Request<"u"&&n instanceof Request){if(n.body===null)return;let r=await n.clone().text();return r.length>b.maxCapturedRequestBytes?null:r}return}if(typeof t=="string")return t.length>b.maxCapturedRequestBytes?null:t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){let r=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return r.byteLength>b.maxCapturedRequestBytes?null:fn.decode(r)}return null}function te(n){if(!(n===void 0||n===""))try{return JSON.parse(n)}catch{return}}function xn(n){let e=new Error(n.message);return e.name=n.type,n.stack&&(e.stack=n.stack),e}function Ce(n,e){for(D.delete(n),D.set(n,{attempt:e,at:Date.now()});D.size>b.maxRememberedFailures;){let t=D.keys().next().value;if(t===void 0)break;D.delete(t);}}function _n(n){let e=D.get(n);return e?Date.now()-e.at>b.retryWindowMs?(D.delete(n),1):e.attempt+1:1}function Tn(n,e,t){let r=f(t);return e.system!=="openai"||e.operation!=="chat.completions"||r.stream!==true||f(r.stream_options).include_usage!==void 0||typeof n?.body!="string"?n:{...n,body:JSON.stringify({...r,stream_options:{...f(r.stream_options),include_usage:true}})}}async function Oe(n){let e=Number(n.headers.get("content-length"));if(Number.isFinite(e)&&e>b.maxCapturedResponseBytes){await n.body?.cancel().catch(()=>{});return}let t=await n.text();return t.length>b.maxCapturedResponseBytes?void 0:t}async function Sn(n,e){if(!n)return;let t=n.getReader(),r=new se,s=new TextDecoder,o=i=>{for(let a of i){if(a.data==="[DONE]")continue;let d=te(a.data);d!==void 0&&e.chunk(d);}};for(;;){let{done:i,value:a}=await t.read();if(i)break;o(r.push(s.decode(a,{stream:true})));}o(r.push(s.decode())),o(r.end());}function G(n,e){let{span:t}=n;n.trace.captureProviderOutput(ve(e.output)),t.setAttributes(e.attributes),e.output!==void 0&&t.setOutput(e.output),e.outputTruncated?(t.markOutputTruncated(),t.setOutputBytes(e.outputBytes)):e.output===void 0&&e.outputBytes>0&&t.setOutputBytes(e.outputBytes),t.end({status:e.status,...e.error?{error:xn(e.error)}:{}}),e.status==="ok"?D.delete(n.requestKey):Ce(n.requestKey,n.attempt),n.auto?ee().complete(n.auto,n.signals,{responseId:e.responseId,toolCalls:e.toolCalls,endedAt:Date.now(),status:e.status}):ee().completeBound(n.trace,n.signals,{responseId:e.responseId,toolCalls:e.toolCalls,endedAt:Date.now(),status:e.status});}function le(n,e,t){n.accumulator.fail(e,t),G(n,n.accumulator.finish({cancelled:t}));}function wn(n,e){for(z.delete(n),z.set(n,e);z.size>ln;){let t=z.keys().next().value;if(t===void 0)break;z.delete(t);}}async function vn(n,e){let{accumulator:t}=e,r;try{r=n.clone();}catch{G(e,t.finish());return}try{if(e.toolPairing&&await e.toolPairing,!n.ok){let a=await Oe(r);le(e,qe(n.status,te(a)??a),!1);return}if((r.headers.get("content-type")??"").includes("text/event-stream")){t.stream(),await Sn(r.body,t),G(e,t.finish());return}let o=te(await Oe(r));o!==void 0&&t.complete(o);let i=t.finish();i.pending&&i.responseId?wn(i.responseId,e):G(e,i);}catch(s){oe(s)?G(e,t.finish({cancelled:true})):le(e,U(s),false);}}async function kn(n,e,t){try{let r=n.clone();if(!n.ok){await r.body?.cancel().catch(()=>{});return}let s=te(await Oe(r));if(s===void 0)return;e.accumulator.complete(s);let o=e.accumulator.finish();if(o.pending)return;z.delete(t),G(e,o);}catch{}}async function In(n,e){let t=y.capture?.originalFetch??globalThis.fetch,r=y.client;if(!r?.isEnabled)return t(n,e);let s;try{s=yn(n,e);}catch{s=void 0;}if(!s)return t(n,e);let o=R();if(o&&!o.trace.isRecording)return t(n,e);let{route:i}=s;if(i.operation==="responses.retrieve"||i.operation==="responses.cancel"){let v=i.responseId;Y.size>0&&await Promise.allSettled([...Y.keys()]);let A=v?z.get(v):void 0;if(!v||!A||!A.span.isRecording)return v&&z.delete(v),t(n,e);let $=await A.span.run(()=>t(n,e));return A.trace.track(kn($,A,v)),$}let a;try{a=await bn(n,e);}catch{a=null;}if(a===null)return t(n,e);let d=te(a),u=He(i,d),c=Ge(i,d),p=J(`${s.method} ${s.url}\0${a??""}`),l=perf_hooks.performance.now(),m=f(d).model,h,_,k;if(o){_=o.trace;let v=Date.now();if(c.previousResponseId&&c.turn==="tool"&&c.toolResults.some(A=>A.name===void 0||A.input===void 0)){let A=[...Y].filter(([,xe])=>xe===_).map(([xe])=>xe),$=e?.signal??(n instanceof Request?n.signal:void 0);k=hn(A,$).then(()=>{ee().beginBound(_,c,v);}),_.track(k);}else ee().beginBound(_,c,v);}else h=ee().begin(r,i,c,typeof m=="string"?m:void 0,Date.now()),_=h;let I={input:u.input,attributes:u.attributes};_.captureProviderInput(we(d));let S=h?h.root.run(()=>pe(u.name,u.kind,I)):pe(u.name,u.kind,I);if(!S.isRecording)return t(n,e);u.messages!==void 0&&S.setMessages(u.messages);let C=_n(p);C>1&&S.setAttempt(C);let B={span:S,trace:_,auto:h,signals:c,accumulator:new ie(i,{captureBodies:r.options.captureBodies,startedAt:l,now:()=>perf_hooks.performance.now()}),requestKey:p,attempt:C,toolPairing:k},O;try{O=await S.run(()=>t(n,Tn(e,i,d)));}catch(v){try{k?(Ce(p,C),_.track(k.then(()=>le(B,U(v),oe(v))))):le(B,U(v),oe(v));}catch{}throw v}try{S.setAttributes({[g.httpStatus]:O.status}),O.ok||Ce(p,C);let v=vn(O,B);if(_.track(v),!(O.headers.get("content-type")??"").includes("text/event-stream")){Y.set(v,_);let $=()=>Y.delete(v);v.then($,$);}}catch{}return O}var Me=new Map,Rn="x-tracehatch-session-id",Cn="x-tracehatch-user-id";function lt(n){let t=(Array.isArray(n)?n[0]:n)?.trim();return t||void 0}function ft(n){return (n.url??"/").split("?")[0]??"/"}function On(n,e){let t=e.method??"GET",r=ft(e),s=lt(e.headers[Rn]),o=lt(e.headers[Cn]);return new q(n,`${t} ${r}`.slice(0,256),{metadata:{http:{method:t,path:r}},...s?{sessionId:s}:{},...o?{user:{id:o}}:{}},{discardIfEmpty:true,inferProviderBodies:true})}function Mn(n,e,t){try{let r=t.statusCode;n.setMetadata({http:{method:e.method??"GET",path:ft(e),status:r}}),n.end({outcome:r>=500?"error":"ok"});}catch{}}function ht(){let n=y.capture??={};if(!n.serverPatched){n.serverPatched=true;for(let e of [An__default.default.Server,En__default.default.Server]){let t=e.prototype,r=t.emit;Me.set(t,r);let s=function(o,...i){if(o!=="request")return r.apply(this,[o,...i]);let a=y.client;if(!a?.isEnabled)return r.apply(this,[o,...i]);let d;try{let[u,c]=i;d=On(a,u),c.once("close",()=>Mn(d,u,c));}catch{return r.apply(this,[o,...i])}return d.run(()=>r.apply(this,[o,...i]))};t.emit=s;}}}function mt(){let n=y.capture;if(n?.serverPatched){for(let[e,t]of Me)e.emit=t;Me.clear(),n.serverPatched=false;}}var Pn=["SIGTERM","SIGINT"],ne=new Map;async function Bn(n){try{y.autoRuns?.endAll("ok"),await y.client?.flush(b.signalFlushMs);}catch{}let e=ne.get(n);e&&(process.off(n,e),ne.delete(n)),process.listenerCount(n)===0&&process.kill(process.pid,n);}function gt(){let n=y.capture??={};if(!n.signalsInstalled){n.signalsInstalled=true;for(let e of Pn){let t=()=>{Bn(e);};ne.set(e,t),process.on(e,t);}}}function yt(){let n=y.capture;if(n?.signalsInstalled){for(let[e,t]of ne)process.off(e,t);ne.clear(),n.signalsInstalled=false;}}function bt(){y.autoRuns??=new K,dt(),ht(),gt();}function xt(){pt(),mt(),yt();}var fe=class{constructor(e=false){this.enabled=e;}enabled;lastWarning=Number.NEGATIVE_INFINITY;warn(e){let t=Date.now();if(!(t-this.lastWarning<b.warnIntervalMs)){this.lastWarning=t;try{console.warn(`[tracehatch] ${e}`);}catch{}}}debug(e){if(this.enabled)try{console.debug(`[tracehatch] ${e}`);}catch{}}};function he(n,e,t){let r=new Map;for(let i of n)r.set(i.traceId,i.traceJson);let s={name:"@tracehatch/sdk",version:re,runtime:`node/${process.versions.node}`,wire:b.wireVersion,redacted:e,...t>0?{dropped_spans:t}:{}},o=`{"sdk":${JSON.stringify(s)},"traces":[${[...r.values()].join(",")}],"spans":[${n.map(i=>i.spanJson).join(",")}]}`;return {entries:n,json:o,bytes:Buffer.byteLength(o),droppedSpans:t}}function _t(n,e){let t=JSON.stringify(n),r=JSON.stringify(e);return {spanJson:t,traceJson:r,traceId:e.id,bytes:Buffer.byteLength(t)+Buffer.byteLength(r),queuedAt:Date.now()}}var me=class{constructor(e=b.maxQueueBytes){this.maxBytes=e;}maxBytes;entries=[];bytes=0;get length(){return this.entries.length}peek(){return this.entries[0]}push(e){if(e.bytes>this.maxBytes)return 1;let t=0;for(;this.bytes+e.bytes>this.maxBytes;)this.shift(),t+=1;return this.entries.push(e),this.bytes+=e.bytes,t}shift(){let e=this.entries.shift();return e&&(this.bytes-=e.bytes),e}clear(){let e=this.entries.length;return this.entries=[],this.bytes=0,e}};function Tt(n){return n===408||n===429||n>=500}function St(n,e){if(e!==null){let r=Number(e),s=/^\d+(?:\.\d+)?$/.test(e.trim())?r*1e3:Date.parse(e)-Date.now();if(Number.isFinite(s))return Math.min(b.retryAfterMaxMs,Math.max(0,s))}let t=1+(Math.random()*2-1)*b.retryJitter;return Math.min(b.retryMaxMs,b.retryBaseMs*2**n*t)}function wt(n,e){return e.aborted?Promise.resolve():new Promise(t=>{let r=()=>{clearTimeout(s),e.removeEventListener("abort",r),t();},s=setTimeout(r,n);s.unref?.(),e.addEventListener("abort",r,{once:true});})}var zn=util.promisify(zlib.gzip),Dn=new Set(["unauthenticated","key_revoked","forbidden","validation_failed","sdk_upgrade_required","payload_too_large","rate_limited","quota_exceeded","overloaded"]);async function vt(n,e,t){let r=new AbortController,s=()=>r.abort(),o=setTimeout(()=>r.abort(),b.requestTimeoutMs);o.unref?.(),t.addEventListener("abort",s,{once:true}),t.aborted&&r.abort();let i,a=new Promise((d,u)=>{i=()=>u(new Error("Exporter request aborted")),r.signal.addEventListener("abort",i,{once:true}),r.signal.aborted&&i();});try{return await Promise.race([a,(async()=>{let d=Buffer.byteLength(n)>=b.gzipMinBytes,u=d?await zn(n):n;if(r.signal.aborted)throw new Error("Exporter request aborted");let c=await fetch(`${e.baseUrl.replace(/\/$/,"")}/ingest`,{method:"POST",redirect:"error",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json",...d?{"Content-Encoding":"gzip"}:{},"User-Agent":`tracehatch-sdk/${re} (node/${process.versions.node})`,"X-Request-Id":crypto.randomUUID()},body:u,signal:r.signal}),p;try{p=await c.json();}catch{p=void 0;}let l={status:c.status,retryAfter:c.headers.get("Retry-After")};if(p&&typeof p=="object"&&(c.status===202&&"batch_id"in p&&typeof p.batch_id=="string"&&/^bat_[0-7][0-9a-hjkmnp-tv-z]{25}$/.test(p.batch_id)&&"accepted"in p&&typeof p.accepted=="number"&&Number.isSafeInteger(p.accepted)&&p.accepted>=0&&(l.acceptedSpans=p.accepted),"code"in p&&typeof p.code=="string"&&Dn.has(p.code)&&(l.problemCode=p.code),"sampling"in p&&p.sampling&&typeof p.sampling=="object"&&"rate"in p.sampling)){let m=p.sampling.rate;typeof m=="number"&&Number.isFinite(m)&&m>=0&&m<=1&&(l.samplingRate=m);}return l})()])}finally{clearTimeout(o),t.removeEventListener("abort",s),i&&r.signal.removeEventListener("abort",i);}}var ge=class{constructor(e){this.options=e;this.logger=new fe(e.debug);}options;queue=new me;logger;active=new Set;waiters=new Set;abort=new AbortController;timer;immediate;droppedSpans=0;acceptedSpans=0;inFlightSpans=0;lastError;pendingDroppedSpans=0;stopped=false;closing=false;shutdownPromise;samplingRate=1;enqueue(e,t){if(!(this.stopped||this.closing))try{let r=this.queue.push(_t(e,t));r&&this.drop(r,"Export queue is full; oldest spans were dropped.",{code:"queue_full"}),this.schedule();}catch{this.drop(1,"A span could not be serialised and was dropped.",{code:"serialization_error"});}}stats(){return {queuedSpans:this.queue.length,queuedBytes:this.queue.bytes,inFlightBatches:this.active.size,droppedSpans:this.droppedSpans}}flush(e=b.flushTimeoutMs){return this.stopped||this.queue.length===0&&this.active.size===0?Promise.resolve():new Promise(t=>{let r=()=>{clearTimeout(s),this.waiters.delete(r),t();},s=setTimeout(r,Number.isFinite(e)?Math.max(0,e):b.flushTimeoutMs);this.waiters.add(r);try{this.pump();}catch{r();}})}async flushWithResult(e){await this.flush(e);let t=this.queue.length+this.inFlightSpans;return {status:t>0?"timeout":this.droppedSpans>0?"failed":this.acceptedSpans>0?"accepted":"empty",acceptedSpans:this.acceptedSpans,droppedSpans:this.droppedSpans,pendingSpans:t,...this.lastError?{lastError:{...this.lastError}}:{}}}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.closing=true,this.shutdownPromise=(async()=>{await this.flush(),this.stopped=true,this.clearScheduling(),this.abort.abort();let e=this.queue.clear();e&&this.drop(e,"Shutdown timed out; remaining spans were dropped.",{code:"shutdown_timeout"}),await Promise.allSettled([...this.active]);for(let t of [...this.waiters])t();})().catch(()=>{}),this.shutdownPromise)}clearScheduling(){this.timer&&clearTimeout(this.timer),this.immediate&&clearImmediate(this.immediate),this.timer=void 0,this.immediate=void 0;}schedule(){if(this.stopped||this.queue.length===0||this.active.size>=b.maxInFlightBatches)return;if(this.waiters.size>0||this.queue.length>=b.batchMaxSpans){this.immediate||(this.immediate=setImmediate(()=>{this.immediate=void 0,this.pump();}),this.immediate.unref?.());return}if(this.timer)return;let e=Date.now()-(this.queue.peek()?.queuedAt??Date.now());this.timer=setTimeout(()=>{this.timer=void 0,this.pump();},Math.max(0,b.batchMaxDelayMs-e)),this.timer.unref?.();}pump(){if(!this.stopped){for(this.clearScheduling();this.queue.length>0&&this.active.size<b.maxInFlightBatches;){let e=Date.now()-(this.queue.peek()?.queuedAt??Date.now());if(this.waiters.size===0&&this.queue.length<b.batchMaxSpans&&e<b.batchMaxDelayMs)break;let t=this.takeBatch();if(!t)continue;this.inFlightSpans+=t.entries.length;let r=t.entries.length,s=i=>{r-=i,this.inFlightSpans-=i;},o=this.deliver(t,s).catch(()=>{this.drop(r,"Export failed; spans were dropped.",{code:"export_error"});}).finally(()=>{this.inFlightSpans-=r,this.active.delete(o),this.pump();});this.active.add(o);}if(this.queue.length===0&&this.active.size===0)for(let e of [...this.waiters])e();this.schedule();}}takeBatch(){let e=[],t;for(;this.queue.length>0&&e.length<b.batchMaxSpans;){let r=this.queue.peek();if(!r)break;let s=he([...e,r],this.options.redacted,this.pendingDroppedSpans);if(s.bytes>b.batchMaxBytes){if(e.length>0)break;this.queue.shift(),this.drop(1,"A span exceeds the batch size limit and was dropped.",{code:"payload_too_large"});continue}this.queue.shift(),e.push(r),t=s;}return t&&(this.pendingDroppedSpans=0),t}applySamplingRate(e){if(e!==this.samplingRate){this.samplingRate=e,e<1?this.logger.warn(`The workspace is over its monthly trace allowance; new traces are sampled at ${Math.round(e*100)}% until usage resets.`):this.logger.debug("Server-side sampling ended; new traces are sent in full.");try{this.options.onSamplingRate?.(e);}catch{this.logger.debug("A sampling update could not be applied.");}}}async deliver(e,t){let r={code:"network_error"};for(let s=0;s<b.retryAttempts;s+=1){if(this.stopped){this.drop(e.entries.length,"Shutdown timed out; remaining spans were dropped.",{code:"shutdown_timeout"}),t(e.entries.length);return}let o=null;try{let i=await vt(e.json,this.options,this.abort.signal);if(i.status>=200&&i.status<300){if(i.status!==202||i.acceptedSpans!==e.entries.length){this.drop(e.entries.length,"The API did not acknowledge this batch; check TRACEHATCH_BASE_URL.",{code:"unexpected_response",httpStatus:i.status}),t(e.entries.length);return}this.acceptedSpans+=e.entries.length,t(e.entries.length),this.applySamplingRate(i.samplingRate??1);return}if(r={code:i.problemCode??"http_error",httpStatus:i.status},i.status===413){if(e.entries.length===1){this.drop(1,"The API rejected an oversized span; the span was dropped.",{code:"payload_too_large",httpStatus:i.status}),t(1);return}let a=Math.ceil(e.entries.length/2);await this.deliver(he(e.entries.slice(0,a),this.options.redacted,e.droppedSpans),t),await this.deliver(he(e.entries.slice(a),this.options.redacted,0),t);return}if(!Tt(i.status)){let a=i.problemCode?` (${i.problemCode})`:` (HTTP ${i.status})`;this.drop(e.entries.length,`The API rejected a batch${a}; spans were dropped.`,r),t(e.entries.length);return}o=i.retryAfter;}catch{r={code:"network_error"};}if(this.stopped||s+1===b.retryAttempts){this.drop(e.entries.length,"Export retries were exhausted; spans were dropped.",r),t(e.entries.length);return}await wt(St(s,o),this.abort.signal);}}drop(e,t,r){this.droppedSpans+=e,this.pendingDroppedSpans+=e,this.lastError=r,this.logger.warn(t);}};var qn=12;function*kt(n){let e=n;for(let t=0;t<qn;t++){yield e;let r=path.dirname(e);if(r===e)return;e=r;}}function be(n){try{return fs.readFileSync(n,"utf8")}catch{return}}function It(n=process.cwd()){for(let t of kt(n)){let r=be(path.join(t,"package.json"));if(r!==void 0){try{let s=JSON.parse(r).name;if(typeof s=="string"&&s.trim())return s.trim().slice(0,128)}catch{}break}}let e=path.basename(n).trim();return e?e.slice(0,128):void 0}var Hn=["VERCEL_GIT_COMMIT_SHA","RAILWAY_GIT_COMMIT_SHA","RENDER_GIT_COMMIT","HEROKU_SLUG_COMMIT","GITHUB_SHA","CI_COMMIT_SHA","SOURCE_VERSION","COMMIT_SHA"],Pe=/^[0-9a-f]{7,64}$/i;function At(n=process.cwd(),e=process.env){for(let t of Hn){let r=e[t]?.trim();if(r)return r.slice(0,128)}for(let t of kt(n)){let r=be(path.join(t,".git","HEAD"))?.trim();if(r===void 0)continue;if(Pe.test(r))return r;let s=/^ref:\s*(\S+)$/.exec(r)?.[1];if(!s)return;let o=be(path.join(t,".git",s))?.trim();if(o&&Pe.test(o))return o;let d=be(path.join(t,".git","packed-refs"))?.split(`
|
|
8
|
+
`).find(u=>u.endsWith(` ${s}`))?.split(" ")[0];return d&&Pe.test(d)?d:void 0}}var Wn=new Set(["apiKey","baseUrl","release","agent","captureBodies","redact","sampling","debug","flushOnExit"]);function Kn(n){for(let e of Object.keys(n))if(!Wn.has(e))throw new TypeError(`Unknown Tracehatch option: ${e}`);for(let e of ["apiKey","baseUrl","release","agent"])if(n[e]!==void 0&&typeof n[e]!="string")throw new TypeError(`Tracehatch ${e} must be a string`);for(let e of ["captureBodies","debug","flushOnExit"])if(n[e]!==void 0&&typeof n[e]!="boolean")throw new TypeError(`Tracehatch ${e} must be a boolean`);if(n.sampling!==void 0){let e=n.sampling?.rate;if(!Number.isFinite(e)||e<0||e>1||Object.keys(n.sampling).some(t=>t!=="rate"))throw new TypeError("Tracehatch sampling.rate must be between 0 and 1")}if(n.redact!==void 0&&n.redact!==false){let e=n.redact;if(!e||typeof e!="object"||Object.keys(e).some(t=>!["builtIns","rules"].includes(t))||e.builtIns!==void 0&&typeof e.builtIns!="boolean"||e.rules!==void 0&&(!Array.isArray(e.rules)||e.rules.some(t=>!t||typeof t.name!="string"||!/^[\w.-]{1,64}$/.test(t.name)||!(t.pattern instanceof RegExp))))throw new TypeError("Tracehatch redact must be false or an object with builtIns and named RegExp rules")}}var Be=class{options;exporter;enabled=true;rate;onExit;closing;constructor(e){this.options={captureBodies:e.captureBodies??true,redact:e.redact??{},release:e.release,agent:e.agent},this.rate=e.sampling?.rate??1;let t=Ve(e.baseUrl?.trim()?e.baseUrl:De);if(e.apiKey?.trim())this.exporter=new ge({apiKey:e.apiKey,baseUrl:t,redacted:e.redact!==false,debug:e.debug,onSamplingRate:r=>{this.rate=Math.min(e.sampling?.rate??1,r);}}),(e.flushOnExit??true)&&(this.onExit=()=>{y.autoRuns?.endAll("ok"),this.flush();},process.on("beforeExit",this.onExit));else if(!y.missingKeyWarned){y.missingKeyWarned=true;try{console.warn("[tracehatch] No API key configured; tracing is disabled.");}catch{}}}get isEnabled(){return this.enabled&&!!this.exporter}samples(e){let t=2166136261;for(let r of e)t=Math.imul(t^r.charCodeAt(0),16777619);return this.isEnabled&&(t>>>0)/4294967296<this.rate}enqueue(e,t){if(this.isEnabled)try{this.exporter?.enqueue(de(e,this.options),Z(t,this.options));}catch{}}async flush(e){try{await Et(e),await this.exporter?.flush(e);}catch{}}async flushWithResult(e){return this.exporter?(await Et(e),this.exporter.flushWithResult(e)):Ct()}shutdown(){return this.enabled=false,this.onExit&&process.off("beforeExit",this.onExit),y.client===this&&xt(),this.closing??=(async()=>{try{await this.exporter?.shutdown();}catch{}})()}stats(){return this.exporter?.stats()??{queuedSpans:0,queuedBytes:0,inFlightBatches:0,droppedSpans:0}}};function Gn(n={}){Kn(n);let e=Je(n),t=n.apiKey??e.apiKey,r={...n,apiKey:t,baseUrl:n.baseUrl??e.baseUrl,release:n.release??e.release??At(),agent:n.agent??e.agent??It()},s=new Be(r),o=y.client;return y.autoRuns?.endAll("ok"),y.client=s,o?.shutdown(),s.isEnabled&&bt(),s}function Rt(){return y.client??Gn()}async function Zs(n){await y.client?.flush(n);}async function Ys(n){return y.client?.flushWithResult(n)??Ct()}async function Et(n){if(y.pendingEnds??=new Set,y.pendingEnds.size===0&&!y.pendingCaptures?.size)return;let e,t=new Promise(s=>{e=setTimeout(s,Number.isFinite(n)?Math.max(0,n):b.flushTimeoutMs),e.unref?.();}),r=async()=>{for(;y.pendingEnds.size>0||y.pendingCaptures?.size;)await Promise.allSettled([...y.pendingEnds,...y.pendingCaptures??[]]);};try{await Promise.race([r(),t]);}finally{clearTimeout(e);}}function Ct(){return {status:"disabled",acceptedSpans:0,droppedSpans:0,pendingSpans:0}}async function ei(){y.autoRuns?.endAll("ok"),await y.client?.shutdown();}var q=class{constructor(e,t,r={},s={}){this.client=e;this.internal=s;this.inputSet=r.input!==void 0,this.sampled=e.samples(this.id);let o=H("span"),i=R()?.trace;if(this.data={id:this.id,root_span_id:o,name:t,status:"pending",started_at:F(),agent:r.agent??e.options.agent,release:e.options.release,input:r.input,tags:r.tags,session_id:r.sessionId,user:r.user,metadata:r.metadata},this.sanitize(),i&&this.setMetadata({parent_trace_id:i.id}),this.root=new j(this,r.rootName??"agent.run","agent",{input:r.input},void 0,o),r.signal){let a=r.signal,d=()=>this.end({outcome:"cancelled"});a.aborted?d():(a.addEventListener("abort",d,{once:true}),this.removeAbort=()=>a.removeEventListener("abort",d));}}client;internal;id=H("run");root;sampled;ended=false;ending=false;outputSet=false;inputSet=false;inferredInputSet=false;activeSpans=new Set;captures=new Set;recordedToolCalls=new Set;expectedSpanCount=1;data;removeAbort;get isRecording(){return !this.ended&&this.sampled&&this.client.isEnabled}get isEnded(){return this.ended}get hasOutput(){return this.outputSet}get hasChildren(){return this.expectedSpanCount>1}registerSpan(e){this.activeSpans.has(e)||(this.expectedSpanCount+=1,this.activeSpans.add(e));}unregisterSpan(e){this.activeSpans.delete(e);}rememberToolCall(e){this.recordedToolCalls.add(e);}hasRecordedToolCall(e){return this.recordedToolCalls.has(e)}track(e){this.captures.add(e);let t=y.pendingCaptures??=new Set;t.add(e);let r=()=>{this.captures.delete(e),t.delete(e);};e.then(r,r);}async settle(){let e,t=new Promise(r=>{e=setTimeout(r,b.captureSettleMs),e.unref?.();});try{await Promise.race([Promise.allSettled([...this.captures]),t]);}finally{clearTimeout(e);}}sanitize(){try{this.data=Z(this.data,this.client.options);}catch{}}snapshot(){return this.data}run(e){return this.root.run(()=>e(this))}setInput(e){this.ended||(this.inputSet=true,this.data.input=e,this.root.setInput(e),this.sanitize());}setOutput(e){this.ended||(this.outputSet=true,this.data.output=e,this.root.setOutput(e),this.sanitize());}captureProviderInput(e){this.ended||!this.internal.inferProviderBodies||!this.client.options.captureBodies||this.inputSet||this.inferredInputSet||e===void 0||(this.inferredInputSet=true,this.data.input=e,this.root.setInput(e),this.sanitize());}captureProviderOutput(e){this.ended||!this.internal.inferProviderBodies||!this.client.options.captureBodies||this.outputSet||e===void 0||(this.data.output=e,this.root.setOutput(e),this.sanitize());}setUser(e){this.ended||(this.data.user=e,this.sanitize());}setSession(e){this.ended||(this.data.session_id=e,this.sanitize());}addTags(...e){this.ended||(this.data.tags=[...new Set([...this.data.tags??[],...e])],this.sanitize());}setMetadata(e){if(!this.ended)try{let t=Z({...this.data,metadata:e},this.client.options).metadata;this.data.metadata={...this.data.metadata,...t},this.sanitize();}catch{}}score(e){if(!(!this.isRecording||(this.data.scores?.length??0)>=x.maxScoresPerTrace))try{let t=Re(H("scr"),e,this.client.options,"spanId");t&&(this.data.scores=[...this.data.scores??[],t]);}catch{}}end(e={}){if(!(this.ended||this.ending)){if(this.captures.size>0){this.ending=true;let t=this.settle().then(()=>{this.ending=false,this.end(e);}),r=y.pendingEnds??=new Set;r.add(t),t.finally(()=>r.delete(t));return}try{if(this.internal.discardIfEmpty&&!this.hasChildren){this.ended=!0;return}for(let t of this.activeSpans)t.end({status:"cancelled"});this.data.status=e.outcome??("error"in e?"error":"ok"),this.data.ended_at=e.endedAt??F(),this.data.expected_span_count=this.expectedSpanCount,"output"in e&&(this.data.output=e.output),this.sanitize(),this.root.end({status:this.data.status,endedAt:this.data.ended_at,..."output"in e?{output:e.output}:{},..."error"in e?{error:e.error}:{}});}finally{this.ended=true,this.removeAbort?.();}}}};function Jn(n,e={}){try{return new q(Rt(),n,e)}catch{return Ot()}}async function at(n,e,t={}){let r;try{r=Jn(n,t);}catch{return await e(Ot())}try{let s=await r.run(e);return r.end(s===void 0||r.hasOutput?{}:{output:s}),s}catch(s){throw r.end({error:s,outcome:t.signal?.aborted?"cancelled":"error"}),s}}function Ot(){let n={id:"",isRecording:false,isEnded:true,hasChildren:false,setInput(){},setOutput(){},setUser(){},setSession(){},addTags(){},setMetadata(){},score(){},end(){},track(){},run(e){return e(n)}};return n}function di(n){R()?.trace.setUser(n);}function pi(n){R()?.trace.setSession(n);}function li(...n){R()?.trace.addTags(...n);}function fi(n){R()?.trace.setMetadata(n);}function hi(n){R()?.trace.score(n);}exports.a=y;exports.b=q;exports.c=Jn;exports.d=at;exports.e=di;exports.f=pi;exports.g=li;exports.h=fi;exports.i=hi;exports.j=ut;exports.k=jr;exports.l=Be;exports.m=Gn;exports.n=Zs;exports.o=Ys;exports.p=ei;//# sourceMappingURL=chunk-U5REKR34.cjs.map
|
|
9
|
+
//# sourceMappingURL=chunk-U5REKR34.cjs.map
|