@ivytrace/lambda-web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ivy contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @ivytrace/lambda-web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Traces Node.js [Lambda Web Functions](https://docs.aws.amazon.com/lambda/latest/dg/web-functions.html) with
4
+ [Ivy](https://ivytrace.dev): every HTTP request your server handles becomes an invocation in Ivy, with its AWS SDK,
5
+ HTTP and fetch calls, logs, LLM calls and errors. No code changes beyond installing the package.
6
+
7
+ Web Functions don't support Lambda layers, so instead of the Ivy layer the tracer ships in your deployment package
8
+ and Node.js loads it before your app.
9
+
10
+ ## Setup
11
+
12
+ ```sh
13
+ npm install @ivytrace/lambda-web
14
+ ```
15
+
16
+ Add these environment variables to your Web Function revision:
17
+
18
+ | variable | value |
19
+ |---|---|
20
+ | `NODE_OPTIONS` | `--import @ivytrace/lambda-web` |
21
+ | `IVY_ENDPOINT` | your Ivy ingest URL |
22
+ | `IVY_API_KEY` | your project's ingest key |
23
+
24
+ Revisions don't inherit settings, so include your existing variables when you create the next revision.
25
+
26
+ Any server built on `node:http` works: Express, Hono's Node.js server, Fastify, plain `http.createServer`.
27
+
28
+ ## How requests show up
29
+
30
+ - The request ID is Lambda's `lambda-web-request-id` header, so you can find a request in Ivy by the ID a client
31
+ received.
32
+ - The function name comes from `AWS_LAMBDA_FUNCTION_NAME` when Lambda sets it, else `IVY_FUNCTION_NAME`, else the
33
+ endpoint name (`lambda-web-endpoint-name`).
34
+ - The request (method, URL, headers, body) and response (status, headers, body) are recorded with the same
35
+ redaction rules and size limits as the Ivy layer. A status of 500 or above marks the invocation as failed.
36
+ - Spans are exported from the process shortly after each request finishes, and on `SIGTERM` when Lambda shuts the
37
+ environment down. If your app calls `process.exit()` right away on `SIGTERM`, requests from the last ~100 ms
38
+ before shutdown may be lost.
39
+
40
+ All `IVY_*` settings of the Ivy layer that apply to the tracer (payload limits, redaction, log capture, …) work
41
+ the same way; see the layer's README.
package/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ var bn="password,secret,token,authorization,cookie,apikey,api_key,accesskey,secretaccesskey,sessiontoken,creditcard,cardnumber,cvv";function w(e,t){let n=e===void 0?NaN:parseInt(e,10);return Number.isFinite(n)&&n>=0?n:t}function it(e,t){return e===void 0||e===""?t:!["0","false","no","off"].includes(e.toLowerCase())}function Sn(e){if(!e)return;let t=e.replace(/\/+$/,"");return t.endsWith("/v1/traces")?t:`${t}/v1/traces`}function Xt(e=process.env){let t=e.IVY_ENDPOINT||void 0;return{endpoint:t,tracesUrl:Sn(t),apiKey:e.IVY_API_KEY||void 0,enabled:!!t&&!it(e.IVY_DISABLE,!1),debug:it(e.IVY_DEBUG,!1),maxPayloadBytes:w(e.IVY_MAX_PAYLOAD_BYTES,16*1024),redactKeys:(e.IVY_REDACT_KEYS??bn).split(",").map(n=>n.trim()).filter(Boolean),extensionPort:w(e.IVY_EXTENSION_PORT,9790),timeoutMarginMs:w(e.IVY_TIMEOUT_MARGIN_MS,100),exportTimeoutMs:w(e.IVY_EXPORT_TIMEOUT_MS,1e3),flushBudgetMs:w(e.IVY_FLUSH_BUDGET_MS,2e3),flushBudgetPerChunkMs:w(e.IVY_FLUSH_BUDGET_PER_CHUNK_MS,500),flushBudgetMaxMs:w(e.IVY_FLUSH_BUDGET_MAX_MS,5e3),exportChunkSpans:Math.max(1,w(e.IVY_EXPORT_CHUNK_SPANS,500)),exportChunkBytes:Math.max(16*1024,w(e.IVY_EXPORT_CHUNK_BYTES,1024*1024)),maxQueueSpans:w(e.IVY_MAX_QUEUE_SPANS,2e3),captureLogs:it(e.IVY_CAPTURE_LOGS,!0),captureWorkers:it(e.IVY_CAPTURE_WORKERS,!0),maxSpans:Math.max(10,w(e.IVY_MAX_SPANS,2e3)),maxInvocationPayloadBytes:w(e.IVY_MAX_INVOCATION_PAYLOAD_BYTES,1024*1024),collapseThreshold:w(e.IVY_COLLAPSE_THRESHOLD,50),collapseKeep:w(e.IVY_COLLAPSE_KEEP,10),collapseKeepSlowest:w(e.IVY_COLLAPSE_KEEP_SLOWEST,3)}}var It=()=>{let[e,t]=process.hrtime();return e*1e3+t/1e6},Qt=Date.now(),Zt=It();function te(){Qt=Date.now(),Zt=It()}function g(){return Qt+(It()-Zt)}function Ct(e){let t="";for(let n=0;n<e;n+=4)t+=(Math.random()*4294967296>>>0).toString(16).padStart(8,"0");return t.slice(0,e*2)}function ee(e=Date.now()){return(Math.floor(e/1e3)>>>0).toString(16).padStart(8,"0")+Ct(12)}function kn(e){let t=2166136261,n=Buffer.from(e,"utf8");for(let r=0;r<n.length;r++)t^=n[r],t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ne(e,t){let n="";for(let o=0;o<5;o++)n+=kn(`${o}:${e}`);let r=Math.floor(t/1e3)>>>0,s=n.slice(0,16)==="0000000000000000"?"0000000000000001":n.slice(0,16);return{traceId:r.toString(16).padStart(8,"0")+n.slice(16),spanId:s}}function re(){let e=Ct(8);for(;e==="0000000000000000";)e=Ct(8);return e}var O={INTERNAL:1,SERVER:2,CLIENT:3,PRODUCER:4,CONSUMER:5},b={UNSET:0,OK:1,ERROR:2};function H(e,t,n,r,s){return{traceId:e,spanId:re(),parentSpanId:s,name:t,kind:n,startMs:r,attributes:{},events:[],status:{code:b.UNSET},payloads:[]}}function Et(e){return e&&e.split(`
2
+ `).filter(t=>!t.includes("/opt/nodejs/ivy/")).join(`
3
+ `)}function T(e,t,n,r){let s=t,o=r??(s&&typeof s=="object"?String(s.name??s.constructor?.name??"Error"):typeof t=="string"?"Error":typeof t),i=String(s&&typeof s=="object"?s.message??"":t);e.status={code:b.ERROR,message:i},e.attributes["error.type"]=o;let a={"exception.type":o,"exception.message":i},c=s&&typeof s=="object"&&typeof s.stack=="string"?Et(s.stack):void 0;c&&(a["exception.stacktrace"]=c),e.events.push({name:"exception",timeMs:n,attributes:a})}var xn={dynamodb:"DynamoDB",s3:"S3",sqs:"SQS",sns:"SNS",lambda:"Lambda",events:"EventBridge",ses:"SES",secretsmanager:"SecretsManager",kinesis:"Kinesis",firehose:"Firehose",states:"SFN",ssm:"SSM",sts:"STS",kms:"KMS","cognito-idp":"CognitoIdentityProvider",scheduler:"Scheduler",bedrock:"Bedrock",execute:"ApiGatewayManagementApi",cloudwatch:"CloudWatch",logs:"CloudWatchLogs"};function se(e){if(!(typeof e!="string"||!e))return e.replace(/Client$/,"")||void 0}function oe(e){return xn[e]??e.charAt(0).toUpperCase()+e.slice(1)}function ie(e){if(!(typeof e!="string"||!e))return e.replace(/Command$/,"")||void 0}var A=e=>typeof e=="string"&&e?e:void 0;function vn(e){let t=A(e);if(!t)return;let n=/:table\/([^/]+)/.exec(t);return n?n[1]:t}function wn(e){let t=new Set,n=r=>{let s=vn(r);s&&t.add(s)};if(n(e.TableName),e.RequestItems&&typeof e.RequestItems=="object"&&Object.keys(e.RequestItems).forEach(n),Array.isArray(e.TransactItems))for(let r of e.TransactItems)for(let s of["Get","Put","Update","Delete","ConditionCheck"])n(r?.[s]?.TableName);if(typeof e.Statement=="string"){let r=/\b(?:from|into|update)\s+"?([A-Za-z0-9_.-]+)"?/i.exec(e.Statement);r&&n(r[1])}return[...t]}function D(e,t,n,r){let s={},o=t&&typeof t=="object"?t:{},i=n&&typeof n=="object"?n:{};switch(e){case"DynamoDB":{let a=wn(o);a.length&&(s["aws.dynamodb.table_names"]=a);break}case"S3":A(o.Bucket)&&(s["aws.s3.bucket"]=o.Bucket),A(o.Key)&&(s["aws.s3.key"]=o.Key);break;case"SQS":{s["messaging.system"]="aws_sqs";let a=A(o.QueueUrl)?.split("/").pop()??A(o.QueueName);a&&(s["messaging.destination.name"]=a),A(i.MessageId)&&(s["messaging.message.id"]=i.MessageId);break}case"SNS":{s["messaging.system"]="aws_sns";let c=(A(o.TopicArn)??A(o.TargetArn))?.split(":").pop()??(A(o.PhoneNumber)?"phone":void 0);c&&(s["messaging.destination.name"]=c),A(i.MessageId)&&(s["messaging.message.id"]=i.MessageId);break}case"Lambda":{let a=A(o.FunctionName);if(a){let c=/^arn:[^:]+:lambda:([^:]+):[^:]+:function:([^:]+)/.exec(a);s["faas.invoked_name"]=c?c[2]:a.split(":")[0];let p=c?.[1]??r;p&&(s["faas.invoked_region"]=p)}break}case"EventBridge":{let a=Array.isArray(o.Entries)?o.Entries:[];if(a.length){s["aws.eventbridge.bus"]=A(a[0]?.EventBusName)?.split("/").pop()??"default";let c=[...new Set(a.map(p=>p?.DetailType).filter(p=>typeof p=="string"))];c.length&&(s["aws.eventbridge.detail_types"]=c)}break}}return s}function ae(e){if(typeof e!="string"||!e.startsWith("AWS4-HMAC-SHA256"))return;let t=/Credential=[^/]+\/\d{8}\/([^/]+)\/([^/]+)\/aws4_request/.exec(e);return t?{region:t[1],service:t[2]}:void 0}function ue(e,t){if(typeof e=="string"&&e.includes("."))return e.slice(e.lastIndexOf(".")+1);if(t){let n=/(?:^|&)Action=([A-Za-z0-9]+)/.exec(t);if(n)return n[1]}}var V="BedrockRuntime",de={invoke:"InvokeModel","invoke-with-response-stream":"InvokeModelWithResponseStream",converse:"Converse","converse-stream":"ConverseStream"},pe=new Set(Object.values(de)),fe=e=>e==="InvokeModelWithResponseStream"||e==="ConverseStream",Nt=e=>e.startsWith("Converse"),S=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_=(...e)=>{for(let t of e){if(t==null||t==="")continue;let n=Number(t);if(Number.isFinite(n))return n}},le=(...e)=>e.find(t=>t!=null&&t!=="");function me(e,t){if(!/^bedrock-runtime(-fips)?\.[a-z0-9-]+\.amazonaws\.com$/i.test(e))return;let n=/^\/model\/([^/?#]+)\/(invoke|invoke-with-response-stream|converse|converse-stream)(?:[?#]|$)/.exec(t);if(!n)return;let r=n[1];try{r=decodeURIComponent(r)}catch{}return{operation:de[n[2]],modelId:r}}var An=new TextDecoder;function B(e){if(S(e)&&!(e instanceof Uint8Array))return e;try{let t=typeof e=="string"?e:e instanceof Uint8Array&&e.byteLength<=1048576?An.decode(e):void 0,n=t===void 0?void 0:JSON.parse(t);return S(n)?n:void 0}catch{return}}function F(e,t){let n={"gen_ai.system":"aws.bedrock","gen_ai.operation.name":/embed/i.test(e??"")?"embeddings":"chat"};e&&(n["gen_ai.request.model"]=e);let r=t??{},s=S(r.inferenceConfig)?r.inferenceConfig:S(r.textGenerationConfig)?r.textGenerationConfig:{},o=_(r.max_tokens,r.max_gen_len,r.max_new_tokens,r.max_completion_tokens,s.maxTokens,s.max_new_tokens,s.maxTokenCount),i=_(r.temperature,s.temperature),a=_(r.top_p,r.p,s.topP,s.top_p);return o!==void 0&&(n["gen_ai.request.max_tokens"]=o),i!==void 0&&(n["gen_ai.request.temperature"]=i),a!==void 0&&(n["gen_ai.request.top_p"]=a),n}function ce(e,t){if(S(e)){for(let n in e)if(n.toLowerCase()===t)return e[n]}}function W(e,t){let n={},r=e??{},s=S(r.usage)?r.usage:{},o=S(r["amazon-bedrock-invocationMetrics"])?r["amazon-bedrock-invocationMetrics"]:{},i=S(r.meta?.billed_units)?r.meta.billed_units:{},c=(Array.isArray(r.results)?r.results:[]).reduce((f,l)=>S(l)&&_(l.tokenCount)!==void 0?(f??0)+Number(l.tokenCount):f,void 0),p=_(s.input_tokens,s.inputTokens,s.prompt_tokens,r.prompt_token_count,i.input_tokens,r.inputTextTokenCount,o.inputTokenCount,ce(t,"x-amzn-bedrock-input-token-count")),u=_(s.output_tokens,s.outputTokens,s.completion_tokens,r.generation_token_count,i.output_tokens,c,o.outputTokenCount,ce(t,"x-amzn-bedrock-output-token-count"));p!==void 0&&(n["gen_ai.usage.input_tokens"]=p),u!==void 0&&(n["gen_ai.usage.output_tokens"]=u);let d=le(r.stop_reason,r.stopReason,r.finish_reason,r.choices?.[0]?.finish_reason,r.outputs?.[0]?.stop_reason,r.generations?.[0]?.finish_reason,r.results?.[0]?.completionReason);return typeof d=="string"&&(n["gen_ai.response.finish_reasons"]=[d]),typeof r.model=="string"&&r.model&&(n["gen_ai.response.model"]=r.model),typeof r.id=="string"&&r.id&&(n["gen_ai.response.id"]=r.id),n}var _n=256*1024,Ot=class{firstChunkMs;anthropic=!1;message={};blocks=[];converse=!1;converseBlocks=[];stopReason;usage={};metrics;text="";add(t){if(S(t))if(this.firstChunkMs??=g(),S(t.chunk)){let n=B(t.chunk.bytes);n&&this.addChunk(n)}else this.addConverse(t)}append(t,n,r){if(typeof r!="string")return;let s=typeof t[n]=="string"?t[n]:"";s.length<_n&&(t[n]=s+r)}addChunk(t){switch(S(t["amazon-bedrock-invocationMetrics"])&&(this.metrics=t["amazon-bedrock-invocationMetrics"]),t.type){case"message_start":if(this.anthropic=!0,S(t.message)){this.message={id:t.message.id,model:t.message.model};let o=_(t.message.usage?.input_tokens);o!==void 0&&(this.usage.input_tokens=o)}return;case"content_block_start":this.anthropic=!0,this.blocks[t.index??this.blocks.length]={...S(t.content_block)?t.content_block:{type:"text",text:""}};return;case"content_block_delta":{let o=this.blocks[t.index??0]??={type:"text",text:""},i=t.delta??{};i.type==="input_json_delta"?this.append(o,"partial",i.partial_json):i.type==="thinking_delta"?this.append(o,"thinking",i.thinking):this.append(o,"text",i.text);return}case"message_delta":typeof t.delta?.stop_reason=="string"&&(this.stopReason=t.delta.stop_reason),_(t.usage?.output_tokens)!==void 0&&(this.usage.output_tokens=Number(t.usage.output_tokens));return;case"content_block_stop":case"message_stop":case"ping":return}if(t.contentBlockDelta||t.contentBlockStart||t.messageStop||t.metadata||t.messageStart){this.addConverse(t);return}this.append(this,"text",t.generation??t.outputText??t.completion??t.outputs?.[0]?.text??t.choices?.[0]?.delta?.content??(t.is_finished?void 0:t.text));let n=le(t.stop_reason,t.outputs?.[0]?.stop_reason,t.completionReason,t.finish_reason,t.choices?.[0]?.finish_reason);typeof n=="string"&&(this.stopReason=n);let r=_(t.prompt_token_count,t.inputTextTokenCount),s=_(t.generation_token_count,t.totalOutputTextTokenCount);r!==void 0&&(this.usage.input_tokens=r),s!==void 0&&(this.usage.output_tokens=(this.usage.output_tokens??0)+s)}addConverse(t){if(this.converse=!0,S(t.contentBlockStart)){let n=t.contentBlockStart.start?.toolUse;this.converseBlocks[t.contentBlockStart.contentBlockIndex??this.converseBlocks.length]=S(n)?{toolUse:{...n,input:""}}:{}}else if(S(t.contentBlockDelta)){let n=t.contentBlockDelta.contentBlockIndex??0,r=this.converseBlocks[n]??={},s=t.contentBlockDelta.delta??{};S(s.toolUse)?this.append(r.toolUse??={input:""},"input",s.toolUse.input):S(s.reasoningContent)?this.append((r.reasoningContent??={reasoningText:{}}).reasoningText,"text",s.reasoningContent.text):this.append(r,"text",s.text)}else if(S(t.messageStop))typeof t.messageStop.stopReason=="string"&&(this.stopReason=t.messageStop.stopReason);else if(S(t.metadata)){if(S(t.metadata.usage)){let{inputTokens:n,outputTokens:r}=t.metadata.usage;_(n)!==void 0&&(this.usage.input_tokens=Number(n)),_(r)!==void 0&&(this.usage.output_tokens=Number(r))}S(t.metadata.metrics)&&(this.metrics=t.metadata.metrics)}}result(){let t={...this.usage};if(this.anthropic){let n=this.blocks.filter(Boolean).map(({partial:r,...s})=>{if(r===void 0)return s;try{return{...s,input:JSON.parse(r)}}catch{return{...s,input:r}}});return{...this.message,role:"assistant",content:n,stop_reason:this.stopReason,usage:t,"amazon-bedrock-invocationMetrics":this.metrics}}return this.converse?{output:{message:{role:"assistant",content:this.converseBlocks.filter(Boolean).map(r=>{if(!S(r.toolUse)||typeof r.toolUse.input!="string")return r;try{return{toolUse:{...r.toolUse,input:JSON.parse(r.toolUse.input||"{}")}}}catch{return r}})}},stopReason:this.stopReason,usage:{inputTokens:t.input_tokens,outputTokens:t.output_tokens},metrics:this.metrics}:{role:"assistant",content:[{type:"text",text:this.text}],stop_reason:this.stopReason,usage:t,"amazon-bedrock-invocationMetrics":this.metrics}}};function he(e,t){let n=new Ot,r=!1,s=o=>{if(!r){r=!0;try{e.endMs=g(),o&&T(e,o,e.endMs);let i=n.result();Object.assign(e.attributes,W(i)),n.firstChunkMs!==void 0&&(e.attributes["gen_ai.response.time_to_first_chunk"]=Math.round(n.firstChunkMs-e.startMs)/1e3),e.payloads.push({key:"ivy.payload.response",value:i})}catch{}}};return{[Symbol.asyncIterator](){let o=t[Symbol.asyncIterator]();return{async next(...i){try{let a=await o.next(...i);if(a.done)s();else try{n.add(a.value)}catch{}return a}catch(a){throw s(a),a}},async return(i){return s(),o.return?o.return(i):{done:!0,value:i}},async throw(i){if(s(i),o.throw)return o.throw(i);throw i}}}}}var P="[redacted]",Bt=e=>e.toLowerCase().replace(/[-_]/g,""),Rn=/(tokens|tokencounts?|tokensdetails|tokenusage)$/,Mn=/(access|refresh|session|id|api|auth|bearer|oauth|csrf|xsrf|client|device|push|secret|security|reset|invite|verification|bot)$/;function Tn(e){let t=Bt(e),n=Rn.exec(t);return!!n&&!Mn.test(t.slice(0,n.index))}var In=0,ge=1,ye=2;function Se(e){let t=[...new Set(e.map(Bt).filter(Boolean))],n=new Map,r=s=>{let o=n.get(s);if(o===void 0){let i=Bt(s),a=Tn(i)?[]:t.filter(c=>i.includes(c));o=a.length?a.every(c=>c.includes("token"))?ge:ye:In,n.size<5e3&&n.set(s,o)}return o};return(s,o)=>{let i=r(s);return i===ge?!(typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"):i===ye}}function C(e,t){if(e.length<=t/3)return{text:e,truncated:!1};let n=Buffer.from(e,"utf8");if(n.length<=t)return{text:e,truncated:!1};let r=n.subarray(0,t).toString("utf8");r.endsWith("\uFFFD")&&(r=r.replace(/�+$/,""));let s=n.length-Buffer.byteLength(r,"utf8");return{text:`${r}\u2026[truncated ${s} bytes]`,truncated:!0}}var Cn=64*1024,En=new TextDecoder("utf-8",{fatal:!0});function be(e){if(e.byteLength<=Cn)try{let t=En.decode(e);try{return JSON.parse(t)}catch{return t}}catch{}return`[binary ${e.byteLength} bytes]`}function On(e){return typeof e.pipe=="function"||typeof e.getReader=="function"||typeof e.on=="function"}var ke={chars:1/0,items:1/0},z=64,Nn=16,Bn=1024*1024;function Pn(e,t){let n=t,r=e.charCodeAt(n-1);return r>=55296&&r<=56319&&n--,`${e.slice(0,n)}\u2026[+${e.length-n} chars]`}var Ln=1024*1024;function Vn(e,t,n){if(t?.isBase64Encoded===!0||e.length>Ln||!/^\s*[[{]/.test(e))return e;let r;try{r=JSON.parse(e)}catch{return e}let s=Pt(r,n,ke);try{return s===JSON.stringify(r)?e:s}catch{return s}}function Pt(e,t,n,r){let s=new WeakSet;try{return JSON.stringify(e,function(o,i){if(o!==""&&t(o,i))return P;o==="body"&&typeof i=="string"&&(i=Vn(i,this,t));let a=o===""?e:this[o];if(a!==null&&typeof a=="object"){if(a instanceof Uint8Array)return be(a);if(a instanceof ArrayBuffer)return be(new Uint8Array(a));if(a instanceof Error)return{name:a.name,message:a.message};if(s.has(a))return"[circular]";if(s.add(a),Array.isArray(a)){if(a.length>n.items)return[...a.slice(0,n.items),`\u2026[+${a.length-n.items} items]`]}else if(!(a instanceof Date)&&On(a))return"[stream]"}if(typeof i=="string"&&i.length>z&&(r?.push(i.length),i.length>n.chars))return Pn(i,n.chars);if(typeof i=="bigint")return i.toString();if(!(typeof i=="function"||typeof i=="symbol"))return i})??""}catch(o){return JSON.stringify(`[unserializable: ${o?.message}]`)}}function qn(e,t){let n=e.sort((s,o)=>o-s),r=0;for(let s=0;s<n.length;s++){r+=n[s];let o=Math.floor((r-t)/(s+1))-Nn;if(o>=(n[s+1]??z))return o}return z}function Y(e,t,n){if(e===void 0)return{text:"",truncated:!1};let r=[],s=Pt(e,n,ke,r),o=s.charCodeAt(0);if(s.length<=t/3||o!==123&&o!==91)return C(s,t);let i=Buffer.byteLength(s,"utf8");if(i<=t)return{text:s,truncated:!1};if(i>Bn)return C(s,t);let a=Math.ceil((i-t)*1.05)+64,c=qn(r,a),p=s;for(let f of[{chars:c,items:1/0},{chars:Math.min(c,4*z),items:20},{chars:z,items:5}]){p=Pt(e,n,f);let l=Buffer.byteLength(p,"utf8");if(l<=t)return{text:`${p}\u2026[truncated ${i-l} bytes]`,truncated:!0}}let u=C(p,t),d=u.text.slice(0,u.text.lastIndexOf("\u2026[truncated "));return{text:`${d}\u2026[truncated ${i-Buffer.byteLength(d,"utf8")} bytes]`,truncated:!0}}function xe(e,t,n,r){if(((t??"").includes("json")||/^\s*[[{]/.test(e))&&e.length<=1024*1024)try{return Y(JSON.parse(e),n,r)}catch{}return C(Lt(e,r),n)}function Kn(e){return e==="true"||e==="false"?e==="true":/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(e)?Number(e):e}function Lt(e,t){return e.replace(/"([^"\\]{1,100})"(\s*:\s*)("(?:[^"\\]|\\.)*"?|[^,}\]\s]+)/g,(n,r,s,o)=>t(r,Kn(o))?`"${r}"${s}"${P}"`:n).replace(/(^|&)([^=&\s"{}]{1,100})=([^&]*)/g,(n,r,s)=>t(s)?`${r}${s}=${encodeURIComponent(P)}`:n)}function Vt(e,t){let n={};if(e)for(let[r,s]of Object.entries(e))s!==void 0&&(n[r.toLowerCase()]=t(r)?P:Array.isArray(s)?s.join(", "):String(s));return JSON.stringify(n)}function at(e,t){let n=e.indexOf("?");if(n===-1)return e;let r=e.indexOf("#",n),o=e.slice(n+1,r===-1?void 0:r).split("&").map(i=>{let a=i.indexOf("="),c=a===-1?i:i.slice(0,a),p=c;try{p=decodeURIComponent(c)}catch{}return a!==-1&&t(p)?`${c}=${encodeURIComponent(P)}`:i});return`${e.slice(0,n)}?${o.join("&")}`}var ut=Symbol.for("ivy.skip-http"),I=class{constructor(t){this.limit=t}limit;chunks=[];bytes=0;total=0;add(t,n){if(t==null||typeof t=="function")return;let r;if(typeof t=="string")r=Buffer.from(t,n&&Buffer.isEncoding(n)?n:"utf8");else if(t instanceof Uint8Array)r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else return;if(this.total+=r.length,this.bytes<this.limit){let s=r.length+this.bytes>this.limit?r.subarray(0,this.limit-this.bytes):r;this.chunks.push(Buffer.from(s)),this.bytes+=s.length}}text(){return Buffer.concat(this.chunks).toString("utf8")}},$n=/json|text|xml|x-www-form-urlencoded|graphql|javascript/i;function q(e){return e==null||e===""||$n.test(String(e))}function R(e,t){if(!e)return;let n=e[t]??e[t.toLowerCase()];if(n!==void 0)return Array.isArray(n)?n.join(", "):String(n);let r=t.toLowerCase();for(let s in e)if(s.toLowerCase()===r)return String(e[s])}var ve;function ct(e,t){let n=e.host.toLowerCase(),r=e.port??(e.protocol==="https:"?443:80),s=`${n}:${r}`;if(ve??=(process.env.AWS_LAMBDA_RUNTIME_API??"127.0.0.1:9001").toLowerCase(),s===ve||(n==="127.0.0.1"||n==="localhost")&&r===t.extensionPort||n==="sandbox.localdomain"||n==="sandbox")return!0;if(t.endpoint)try{let o=new URL(t.endpoint),i=o.port?Number(o.port):o.protocol==="https:"?443:80;if(o.hostname.toLowerCase()===n&&i===r)return!0}catch{}return!1}function Un(e){let t=e.protocol==="https:"?443:80,n=e.port&&e.port!==t?`:${e.port}`:"",r=e.host.includes(":")&&!e.host.startsWith("[")?`[${e.host}]`:e.host;return`${e.protocol}//${r}${n}${e.path||"/"}`}function dt(e,t){let n=e.startChild(`${t.method} ${t.host}`);if(!n)return;n.attributes["http.request.method"]=t.method,n.attributes["url.full"]=at(Un(t),e.isSecret),n.attributes["server.address"]=t.host,n.attributes["server.port"]=t.port??(t.protocol==="https:"?443:80);let r=me(t.host,t.path);return r&&(n.name=`${V}.${r.operation}`,n.attributes["rpc.system"]="aws-api",n.attributes["rpc.service"]=V,n.attributes["rpc.method"]=r.operation,Object.assign(n.attributes,F(r.modelId,void 0))),n}function pt(e,t){e.attributes["http.response.status_code"]=t,t>=400&&(e.status={code:b.ERROR,message:`HTTP ${t}`})}function K(e,t){e.endMs===void 0&&(T(e,t,g()),e.endMs=g())}function ft(e,t,n){t.finalize=()=>{let r=n.requestHeaders?.();t.attributes["ivy.http.request.headers"]=Vt(r,e.isSecret),n.responseHeaders&&(t.attributes["ivy.http.response.headers"]=Vt(n.responseHeaders,e.isSecret));let s=R(r,"content-type"),o=R(n.responseHeaders,"content-type"),i=n.requestBody&&n.requestBody.total>0&&q(s)?n.requestBody.text():void 0,a=n.responseBodyText??(n.responseBody&&n.responseBody.total>0&&q(o)?n.responseBody.text():void 0);i!==void 0&&t.payloads.push({key:"ivy.payload.request",value:i,rawContentType:s??""}),a!==void 0&&t.payloads.push({key:"ivy.payload.response",value:a,rawContentType:o??""}),jn(t,r,n.responseHeaders,i,a)}}function jn(e,t,n,r,s){let o=ae(R(t,"authorization"));if(e.attributes["rpc.service"]===V){o&&(e.attributes["cloud.region"]=o.region);let d=R(n,"x-amzn-requestid");d&&(e.attributes["aws.request_id"]=d),Object.assign(e.attributes,F(e.attributes["gen_ai.request.model"],B(r))),Object.assign(e.attributes,W(B(s),n));return}if(!o)return;let i=oe(o.service),a=ue(R(t,"x-amz-target"),r);e.attributes["rpc.system"]="aws-api",e.attributes["rpc.service"]=i,e.attributes["cloud.region"]=o.region,a&&(e.attributes["rpc.method"]=a,e.name=`${i}.${a}`);let c=R(n,"x-amzn-requestid")??R(n,"x-amz-request-id");c&&(e.attributes["aws.request_id"]=c);let p=d=>{if(d)try{return JSON.parse(d)}catch{return}},u=p(r);if(!u&&i==="S3"){let d=String(e.attributes["url.full"]??""),f=/^https?:\/\/([^/]+)\/([^?]*)/.exec(d);if(f){let l=f[1],h=/^(.+)\.s3[.-]/.exec(l),m=f[2].split("/");u=h?{Bucket:h[1],Key:f[2]||void 0}:{Bucket:m[0],Key:m.slice(1).join("/")||void 0}}}Object.assign(e.attributes,D(i,u,p(s),o.region))}var qt=[];function $(e){if(!qt.length){let t=process.getBuiltinModule("node:module"),n=t._load;t._load=function(r,...s){let o=n.call(this,r,...s);for(let i of qt)try{i(r,o)}catch{}return o}}qt.push(e)}var we=Symbol.for("ivy.aws-sdk.patched"),Re=Symbol.for("ivy.aws-sdk.span"),Hn=new Set(["@smithy/core/client","@smithy/smithy-client","@aws-sdk/smithy-client"]);function Dn(e){try{let t=e?.region;if(typeof t=="string")return Promise.resolve(t);if(typeof t=="function")return Promise.resolve(t()).then(n=>typeof n=="string"?n:void 0,()=>{})}catch{}return Promise.resolve(void 0)}function Fn(e,t){return(n,r)=>async s=>{let o,i="",a;try{if(e.active){i=se(r?.clientName)??"AWS";let f=ie(r?.commandName)??"Unknown";if(o=e.startChild(`${i}.${f}`),o){if(o.attributes["rpc.system"]="aws-api",o.attributes["rpc.service"]=i,o.attributes["rpc.method"]=f,Object.assign(o.attributes,D(i,s?.input,void 0)),i===V&&pe.has(f)){a=f;let l=s?.input,h=Nt(f)?l:B(l?.body);Object.assign(o.attributes,F(l?.modelId,h))}o.payloads.push({key:"ivy.payload.request",value:s?.input}),r[Re]=o}}}catch{o=void 0}if(!o)return n(s);let c=o,p=Dn(t?.config),u=f=>{if(!a||!fe(a)||!f)return!1;try{let l=a==="ConverseStream"?"stream":"body";return!f[l]||typeof f[l][Symbol.asyncIterator]!="function"?!1:(f[l]=he(c,f[l]),!0)}catch{return!1}},d=async(f,l,h=!1)=>{try{let m=f?.output;h||(c.endMs=g());let k=await p;k&&(c.attributes["cloud.region"]=k);let y=m?.$metadata??l?.$metadata;if(y?.requestId&&(c.attributes["aws.request_id"]=y.requestId),y?.httpStatusCode&&(c.attributes["http.response.status_code"]=y.httpStatusCode),Object.assign(c.attributes,D(i,s?.input,m,k)),l)T(c,l,c.endMs??g());else if(!h){c.status.code!==b.ERROR&&(c.status={code:b.UNSET});let{$metadata:x,...st}=m??{};if(c.payloads.push({key:"ivy.payload.response",value:st}),a){let ot=Nt(a)?m:B(m?.body);Object.assign(c.attributes,W(ot,f?.response?.headers))}}}catch{}};try{let f=await n(s);return d(f,void 0,u(f?.output)),f}catch(f){throw d(void 0,f),f}}}var Wn=(e,t)=>async n=>{try{let r=n?.request?.headers;t?.[Re]&&r&&typeof r=="object"&&Object.defineProperty(r,ut,{value:!0,enumerable:!1,configurable:!0})}catch{}return e(n)},Ae=new WeakSet;function _e(e,t){let r=t?.Client?.prototype;if(!r||typeof r.send!="function"||r[we])return;let s=r.send;r.send=function(...o){try{let i=this.middlewareStack;i&&!Ae.has(i)&&(Ae.add(i),i.add(Fn(e,this),{step:"initialize",priority:"high",name:"ivyTracingMiddleware",override:!0}),i.add(Wn,{step:"deserialize",priority:"low",name:"ivyMarkRequestMiddleware",override:!0}))}catch{}return s.apply(this,o)},Object.defineProperty(r,we,{value:!0})}function Me(e){$((n,r)=>{Hn.has(n)&&_e(e,r)});let t=process.getBuiltinModule("node:module")._cache??{};for(let n of Object.keys(t))/[\\/]@(smithy|aws-sdk)[\\/](core[\\/]dist-cjs[\\/]submodules[\\/]client|smithy-client[\\/]dist-cjs)[\\/]/.test(n)&&_e(e,t[n]?.exports)}var zn={log:"info",info:"info",warn:"warn",error:"error",debug:"debug",trace:"debug"};function Te(e){let{format:t}=process.getBuiltinModule("node:util");for(let[n,r]of Object.entries(zn)){let s=console[n];typeof s=="function"&&(console[n]=function(...o){if(e.active)try{e.addLog(r,t(...o))}catch{}return s.apply(this,o)})}}var Yn=1024*1024;function Kt(e){let t={};if(!e)return t;if(typeof e.forEach=="function"&&!Array.isArray(e))e.forEach((n,r)=>t[r]=n);else if(Array.isArray(e))for(let[n,r]of e)t[String(n).toLowerCase()]=r;else if(typeof e=="object")for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}function Gn(e,t){let n=typeof Request<"u"&&e instanceof Request,r=new URL(n?e.url:String(e instanceof URL?e.href:e)),s=String(t?.method??(n?e.method:"GET")).toUpperCase(),o={...n?Kt(e.headers):{},...Kt(t?.headers)};return{info:{method:s,protocol:r.protocol,host:r.hostname.replace(/^\[|\]$/g,""),port:r.port?Number(r.port):void 0,path:r.pathname+r.search},headers:o}}function Ie(e){let t=globalThis.fetch;if(typeof t!="function")return;let n=function(r,s){if(!e.active)return t.call(this,r,s);let o,i;try{let{info:c,headers:p}=Gn(r,s);if(!ct(c,e.config)&&(o=dt(e,c),o)){i={requestHeaders:()=>p};let u=s?.body;(typeof u=="string"||u instanceof URLSearchParams||u instanceof Uint8Array)&&(i.requestBody=new I(Math.max(e.config.maxPayloadBytes*4,64*1024)),i.requestBody.add(u instanceof URLSearchParams?u.toString():u),u instanceof URLSearchParams&&!p["content-type"]&&(p["content-type"]="application/x-www-form-urlencoded")),ft(e,o,i)}}catch{o=void 0}let a=t.call(this,r,s);if(o&&i){let c=o,p=i;a.then(u=>{try{pt(c,u.status),p.responseHeaders=Kt(u.headers);let d=u.headers.get("content-type"),f=Number(u.headers.get("content-length")??NaN);if(!(u.body&&q(d)&&!(f>Yn))){c.endMs=g();return}u.clone().text().then(h=>{p.responseBodyText=h,c.endMs??=g()},()=>{c.endMs??=g()})}catch{c.endMs??=g()}},u=>K(c,u))}return a};Object.defineProperty(n,"name",{value:"fetch"}),globalThis.fetch=n}function lt(e){let t=process.moduleLoadList;return Array.isArray(t)?t.includes(`NativeModule ${e}`):!0}var Ce=Symbol.for("ivy.original");function Ee(e,t){return Object.defineProperty(e,Ce,{value:t}),e}function Oe(e){return e[Ce]??e}function Jn(e,t){let n,r={},[s,o]=e;typeof s=="string"?n=new URL(s):s instanceof URL?n=s:s&&typeof s=="object"&&(r=s),n&&o&&typeof o=="object"&&typeof o!="function"&&(r=o);let i=r.protocol??n?.protocol??t,a=r.hostname??(r.host?String(r.host).replace(/:\d+$/,""):void 0)??n?.hostname??"localhost";a.startsWith("[")&&a.endsWith("]")&&(a=a.slice(1,-1));let c=r.port??(n?.port||void 0),p=c!=null&&c!==""?Number(c):void 0,u=r.path??(n?n.pathname+n.search:"/");return{info:{method:String(r.method??"GET").toUpperCase(),protocol:i,host:a,port:p,path:u},headers:r.headers}}function Xn(e,t,n){let r=dt(e,n);if(!r)return;let s=Math.max(e.config.maxPayloadBytes*4,64*1024),o={requestHeaders:()=>t.getHeaders(),requestBody:new I(s)};ft(e,r,o);let i=t.write;t.write=function(u,...d){try{o.requestBody.add(u,typeof d[0]=="string"?d[0]:void 0)}catch{}return i.call(this,u,...d)};let a=t.end;t.end=function(u,...d){try{typeof u!="function"&&o.requestBody.add(u,typeof d[0]=="string"?d[0]:void 0)}catch{}return a.call(this,u,...d)};let c=t.emit;t.emit=function(u,...d){try{u==="response"?p(d[0]):u==="error"?K(r,d[0]):u==="close"&&r.endMs===void 0&&!o.responseHeaders&&K(r,new Error("socket closed before response"))}catch{}return c.call(this,u,...d)};function p(u){pt(r,u.statusCode??0),o.responseHeaders=u.headers,o.responseBody=new I(s);let d=u.emit;u.emit=function(f,...l){try{f==="data"?o.responseBody.add(l[0],u.readableEncoding??void 0):f==="end"&&r.endMs===void 0?r.endMs=g():f==="error"&&K(r,l[0])}catch{}return d.call(this,f,...l)}}}function Ne(e,t,n){return Ee(function(...s){if(!e.active)return t.apply(this,s);let o;try{o=Jn(s,n),o&&(o.headers?.[ut]||ct(o.info,e.config))&&(o=void 0)}catch{o=void 0}let i=t.apply(this,s);if(o)try{Xn(e,i,o.info)}catch{}return i},t)}var Be=Symbol.for("ivy.http.patched");function Qn(e,t){let n=process.getBuiltinModule(`node:${t}`);n[Be]||(n.request=Ne(e,n.request,`${t}:`),n.get=Ne(e,n.get,`${t}:`),Object.defineProperty(n,Be,{value:!0}),process.getBuiltinModule("node:module").syncBuiltinESMExports())}function Pe(e){let t={http:!1,https:!1},n=(s,o=!1)=>{t[s]||!(o||lt(s))||(t[s]=!0,Qn(e,s))};$(s=>{let o=s.startsWith("node:")?s.slice(5):s;(o==="http"||o==="https")&&n(o,!0)});let r=()=>{n("http"),n("https")};return r(),r}var G=Symbol.for("opentelemetry.js.api.1"),U=Symbol.for("OpenTelemetry Context Key SPAN"),J={UNSET:0,OK:1,ERROR:2};var $t=class e{values;constructor(t){this.values=t?new Map(t):new Map}getValue(t){return this.values.get(t)}setValue(t,n){let r=new e(this.values);return r.values.set(t,n),r}deleteValue(t){let n=new e(this.values);return n.values.delete(t),n}},X=new $t,mt=class{constructor(t=()=>X){this.base=t}base;storage;active(){return this.storage?.getStore()??this.base()}with(t,n,r,...s){this.storage??=new(process.getBuiltinModule("node:async_hooks")).AsyncLocalStorage;let o=r==null?n:n.bind(r);return this.storage.run(t,o,...s)}bind(t,n){if(typeof n!="function")return n;let r=this,s=n;return function(...o){return r.with(t,()=>s.apply(this,o))}}enable(){return this}disable(){return this.storage?.disable(),this.storage=void 0,this}};function Ut(){return globalThis[G]?.context}function Q(){return Ut()?.active()??X}function Z(e){if(e!=null){if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return e.filter(t=>t!=null)}}function tt(e,t){if(t)for(let n in t){let r=Z(t[n]);r!==void 0&&(e[n]=r)}}function Le(e,t,n){let r=e.charCodeAt(0);if((r===123||r===91)&&e.length<=1024*1024)try{return Y(JSON.parse(e),t,n)}catch{return C(Lt(e,n),t)}return C(e,t)}var Zn=e=>e.slice(e.lastIndexOf(".")+1);function ht(e,t,n){let r=Ve(e.attributes,t,n);for(let s of e.events)r=Ve(s.attributes,t,n)||r;return r}function Ve(e,t,n){let r=!1;for(let s in e){let o=e[s],i=Zn(s);if(Array.isArray(o)?o.some(a=>n(i,a)):n(i,o)){e[s]=P;continue}if(typeof o=="string"){let a=Le(o,t,n);e[s]=a.text,r||=a.truncated}else if(Array.isArray(o)&&o.some(a=>typeof a=="string")){let a=[],c=t*4;for(let p=0;p<o.length;p++){let u=o[p];if(typeof u!="string"){a.push(u);continue}if(c<=0){a.push(`\u2026[truncated ${o.length-p} items]`),r=!0;break}let d=Le(u,Math.min(t,c),n);c-=d.text.length,r||=d.truncated,a.push(d.text)}e[s]=a}}return r}function nt(e){if(e!=null){if(Array.isArray(e))return e[0]*1e3+e[1]/1e6;if(e instanceof Date)return e.getTime();if(typeof e=="number")return e<performance.timeOrigin?performance.timeOrigin+e:e}}function jt(e,t,n){let r;t instanceof Date||Array.isArray(t)||typeof t=="number"?n=t:r=t;let s={};return tt(s,r),{name:e,timeMs:nt(n)??g(),attributes:s}}function Ht(e,t){let n=e,r={};if(typeof n=="string")r["exception.message"]=n;else if(n&&typeof n=="object"){let s=n.name??n.code;s!==void 0&&(r["exception.type"]=String(s)),n.message!==void 0&&(r["exception.message"]=String(n.message));let o=typeof n.stack=="string"?Et(n.stack):void 0;o&&(r["exception.stacktrace"]=o)}return{name:"exception",timeMs:nt(t)??g(),attributes:r}}var L=class{constructor(t,n,r){this.ivy=t;this.invocation=n;t.finalize=s=>{ht(s,r.maxBytes,r.isSecret)&&(s.attributes["ivy.payload.truncated"]=!0)}}ivy;invocation;ended=!1;spanContext(){return{traceId:this.ivy.traceId,spanId:this.ivy.spanId,traceFlags:1}}setAttribute(t,n){if(!this.ended){let r=Z(n);r!==void 0&&(this.ivy.attributes[t]=r)}return this}setAttributes(t){return this.ended||tt(this.ivy.attributes,t),this}addEvent(t,n,r){return this.ended||this.ivy.events.push(jt(t,n,r)),this}addLink(){return this}addLinks(){return this}setStatus(t){return this.ended?this:this.ivy.status.code===J.OK?this:t.code===J.UNSET?this:(this.ivy.status=t.message?{code:t.code,message:t.message}:{code:t.code},this)}updateName(t){return this.ended||(this.ivy.name=t),this}recordException(t,n){this.ended||this.ivy.events.push(Ht(t,n))}end(t){if(!this.ended&&(this.ended=!0,this.ivy.endMs=Math.max(nt(t)??g(),this.ivy.startMs),this.ivy.status.code===b.ERROR&&this.ivy.attributes["error.type"]===void 0)){let n=this.ivy.events.find(r=>r.name==="exception");this.ivy.attributes["error.type"]=String(n?.attributes["exception.type"]??"Error")}}isRecording(){return!this.ended}},tr={traceId:"00000000000000000000000000000000",spanId:"0000000000000000",traceFlags:0},et=class{constructor(t=tr){this.context=t}context;spanContext(){return this.context}setAttribute(){return this}setAttributes(){return this}addEvent(){return this}addLink(){return this}addLinks(){return this}setStatus(){return this}updateName(){return this}recordException(){}end(){}isRecording(){return!1}};var er=/^(ivy|faas|cloud|aws|http|url|messaging|error|exception|otel)\./,nr=128,rr=128,sr=e=>er.test(e),gt=class{constructor(t,n,r){this.invocation=t;this.tracer=n;this.caps=r}invocation;tracer;caps;keys=new Set;events=[];hooked=!1;get root(){let t=this.invocation;return!t.done&&this.tracer.active===t?t.root:void 0}hook(t){if(this.hooked)return;this.hooked=!0;let n=t.finalize;t.finalize=r=>{n?.(r);let s={attributes:{},events:this.events};for(let o of this.keys)o in r.attributes&&(s.attributes[o]=r.attributes[o]);ht(s,this.caps.maxBytes,this.caps.isSecret)&&(r.attributes["ivy.payload.truncated"]=!0),Object.assign(r.attributes,s.attributes)}}spanContext(){let t=this.invocation.root;return{traceId:t.traceId,spanId:t.spanId,traceFlags:1}}setAttribute(t,n){let r=this.root;if(!r||sr(t))return this;if(!this.keys.has(t)&&this.keys.size>=nr)return this;let s=Z(n);return s===void 0?this:(this.hook(r),this.keys.add(t),r.attributes[t]=s,this)}setAttributes(t){for(let n in t)this.setAttribute(n,t[n]);return this}addEvent(t,n,r){return this.pushEvent(()=>jt(t,n,r)),this}recordException(t,n){this.pushEvent(()=>Ht(t,n))}pushEvent(t){let n=this.root;if(!n||this.events.length>=rr)return;this.hook(n);let r=t();this.events.push(r),n.events.push(r)}setStatus(t){let n=this.root;return!n||t.code!==J.ERROR||n.status.code===b.ERROR?this:(n.status=t.message?{code:b.ERROR,message:t.message}:{code:b.ERROR},this)}addLink(){return this}addLinks(){return this}updateName(){return this}end(){}isRecording(){return this.root!==void 0}};var or=e=>(e??0)+1,Dt=class{constructor(t,n,r,s,o){this.ivy=t;this.startChild=n;this.caps=r;this.scope=s;this.fallbackContext=o}ivy;startChild;caps;scope;fallbackContext;startSpan(t,n={},r=Q()){let s=this.ivy.active;if(!s||s.done)return new et;let o=n.root?void 0:r?.getValue?.(U),i=this.startChild(t,or(n.kind));if(!i)return new et;o instanceof L&&o.invocation===s&&(i.parentSpanId=o.ivy.spanId);let a=nt(n.startTime);return a!==void 0&&(i.startMs=a),i.attributes["otel.scope.name"]=this.scope,tt(i.attributes,n.attributes),new L(i,s,this.caps)}startActiveSpan(t,...n){let r=n.pop(),[s,o]=n,i=o??Q(),a=this.startSpan(t,s,i);return(Ut()??this.fallbackContext).with(i.setValue(U,a),r,void 0,a)}},yt=class{constructor(t,n,r,s){this.ivy=t;this.startChild=n;this.caps=r;this.fallbackContext=s}ivy;startChild;caps;fallbackContext;tracers=new Map;getTracer(t="unknown"){let n=this.tracers.get(t);return n||(n=new Dt(this.ivy,this.startChild,this.caps,t,this.fallbackContext),this.tracers.set(t,n)),n}};var ir="1.10.0",qe="1.9.0",$e=()=>process.getBuiltinModule("node:fs"),Ue=(...e)=>process.getBuiltinModule("node:path").join(...e),Ke=e=>e.split(".").map(t=>parseInt(t,10)||0),ar=(e,t)=>{let[n,r]=[Ke(e),Ke(t)];return n[0]!==r[0]?n[0]>r[0]:n[1]!==r[1]?n[1]>r[1]:n[2]>r[2]};function je(e){try{let t=JSON.parse($e().readFileSync(Ue(e,"node_modules/@opentelemetry/api/package.json"),"utf8"));if(typeof t.version=="string"&&/^1\.\d+\.\d+$/.test(t.version))return ar(qe,t.version)?qe:t.version}catch{}return ir}function He(e){return $e().existsSync(Ue(e,"node_modules/@opentelemetry/sdk-trace-base"))}function ur(){return globalThis[G]}function De(e,t,n){let r=globalThis,s=ur();return s?.trace?!1:(s||(s=Object.defineProperty({},"version",{value:n,enumerable:!0,writable:!1,configurable:!1}),r[G]=s),s.trace=e,s.context??=t,!0)}var cr=e=>!!e&&["0","false","no","off"].includes(e.toLowerCase());function Fe(e,t=process.env){if(!cr(t.IVY_CAPTURE_OTEL))try{let n=t.LAMBDA_TASK_ROOT??process.cwd(),r=e.startChild.bind(e),s={maxBytes:e.config.maxPayloadBytes,isSecret:e.isSecret},o=new WeakMap,i=()=>{let d=e.active;if(!d||d.done)return X;let f=o.get(d);return f||(f=X.setValue(U,new gt(d,e,s)),o.set(d,f)),f},a=new mt(i),c=new yt(e,r,s,a),p=()=>{De(c,a,je(n))&&(e.startChild=(d,f)=>{let l=r(d,f);if(l){let h=Q().getValue(U);h instanceof L&&h.invocation===e.active&&(l.parentSpanId=h.ivy.spanId)}return l})};if(!He(n)){p();return}let u=e.startInvocation;e.startInvocation=(...d)=>{e.startInvocation=u;try{p()}catch{}return u.apply(e,d)}}catch{}}var dr=/^(ivy\.payload\.|ivy\.http\.(request|response)\.headers$|ai\.prompt|ai\.response\.(text|object|toolCalls|reasoning)|ai\.toolCall\.(args|result)$|gen_ai\.(input|output)\.messages$|gen_ai\.system_instructions$|gen_ai\.tool\.(definitions|call\.arguments|call\.result)$)/,St=e=>dr.test(e),E=e=>Buffer.byteLength(e,"utf8"),bt=class{constructor(t){this.remaining=t}remaining;trimmedBytes=0;trimmedPayloads=0;take(t){return t<=this.remaining?(this.remaining-=t,!0):(this.trimmedBytes+=t,this.trimmedPayloads++,!1)}};function pr(e,t,n=E(JSON.stringify(e))){if(n<=t)return 0;let r=e.attributes.filter(i=>St(i.key)&&"stringValue"in i.value).map(i=>({key:i.key,bytes:E(i.value.stringValue)})).sort((i,a)=>a.bytes-i.bytes),s=0,o=new Set;for(let i of r){if(n-s<=t)break;o.add(i.key),s+=i.bytes}return o.size?(e.attributes=e.attributes.filter(i=>!o.has(i.key)&&i.key!=="ivy.payload.trimmed"),e.attributes.push({key:"ivy.payload.trimmed",value:{boolValue:!0}}),s):0}function We(e,t){let n=[],r=[],s=0;for(let o of e){let i=E(JSON.stringify(o));i>t.bytes&&(pr(o,t.bytes,i),i=E(JSON.stringify(o))),r.length&&(r.length>=t.spans||s+i>t.bytes)&&(n.push(r),r=[],s=0),r.push(o),s+=i+1}return r.length&&n.push(r),n}var fr={name:"ivy-layer",version:"0.1.0"};function ze(e){return typeof e=="string"?{stringValue:e}:typeof e=="boolean"?{boolValue:e}:typeof e=="number"?Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(t=>ze(t))}}:{stringValue:String(e)}}function kt(e){let t=[];for(let n in e){let r=e[n];r==null||typeof r=="number"&&!Number.isFinite(r)||t.push({key:n,value:ze(r)})}return t}function Ft(e){return(BigInt(Math.round(e*1e3))*1000n).toString()}function Wt(e){let t=e.endMs??e.startMs,n={traceId:e.traceId,spanId:e.spanId,name:e.name,kind:e.kind,startTimeUnixNano:Ft(e.startMs),endTimeUnixNano:Ft(Math.max(t,e.startMs)),attributes:kt(e.attributes),events:e.events.map(r=>({timeUnixNano:Ft(r.timeMs),name:r.name,attributes:kt(r.attributes)})),status:e.status.message?{code:e.status.code,message:e.status.message}:{code:e.status.code}};return e.parentSpanId&&(n.parentSpanId=e.parentSpanId),n}function Ye(e){let t=new Map;for(let n of e){let r=JSON.stringify(n.resource),s=t.get(r);s||(s={resource:{attributes:n.resource},scopeSpans:[{scope:fr,spans:[]}]},t.set(r,s)),s.scopeSpans[0].spans.push(...n.spans)}return{resourceSpans:[...t.values()]}}var xt=(e,t)=>typeof e=="string"&&e&&e.split(t).pop()||void 0;function M(e,t,n={}){let r=t==="http"?O.SERVER:t==="pubsub"||t==="datasource"?O.CONSUMER:O.INTERNAL;return{source:e,trigger:t,kind:r,attributes:n}}function lr(e){return typeof e=="string"?e.split("?")[0]:void 0}function vt(e,t,n,r){let s={};typeof t=="string"&&(s["http.request.method"]=t.toUpperCase());let o=lr(n);return o&&(s["url.path"]=o),typeof r=="string"&&r&&(s["http.route"]=r),M(e,"http",s)}function mr(e){let t=e[0]??{},n=t.eventSource??t.EventSource,r=e.length;switch(n){case"aws:sqs":{let s={"messaging.system":"aws_sqs","messaging.batch.message_count":r},o=xt(t.eventSourceARN,":");return o&&(s["messaging.destination.name"]=o),r===1&&t.messageId&&(s["messaging.message.id"]=String(t.messageId)),M("aws:sqs","pubsub",s)}case"aws:sns":{let s={"messaging.system":"aws_sns","messaging.batch.message_count":r},o=xt(t.Sns?.TopicArn,":");return o&&(s["messaging.destination.name"]=o),r===1&&t.Sns?.MessageId&&(s["messaging.message.id"]=String(t.Sns.MessageId)),M("aws:sns","pubsub",s)}case"aws:s3":{let s={};return t.s3?.bucket?.name&&(s["aws.s3.bucket"]=String(t.s3.bucket.name)),t.s3?.object?.key&&(s["aws.s3.key"]=String(t.s3.object.key)),t.eventName&&(s["ivy.trigger.event_name"]=String(t.eventName)),M("aws:s3","datasource",s)}case"aws:dynamodb":{let s={"messaging.batch.message_count":r},o=typeof t.eventSourceARN=="string"?/:table\/([^/]+)/.exec(t.eventSourceARN):null;return o&&(s["aws.dynamodb.table_names"]=[o[1]]),M("aws:dynamodb","datasource",s)}case"aws:kinesis":{let s={"messaging.batch.message_count":r},o=xt(t.eventSourceARN,"/");return o&&t.eventSourceARN?.includes(":stream/")&&(s["messaging.destination.name"]=o),M("aws:kinesis","pubsub",s)}default:return M("unknown","other")}}function Ge(e){if(!e||typeof e!="object"||Array.isArray(e))return M("aws:lambda","other");let t=e,n=t.requestContext;if(Array.isArray(t.Records)&&t.Records.length>0)return mr(t.Records);if(n&&typeof n=="object"){if(n.elb)return vt("aws:alb",t.httpMethod,t.path,void 0);if(t.version==="2.0"&&n.http){let r=typeof n.domainName=="string"&&n.domainName.includes(".lambda-url."),s=typeof t.routeKey=="string"&&t.routeKey!=="$default"?t.routeKey:void 0,o=s?.includes(" ")?s.slice(s.indexOf(" ")+1):s;return vt(r?"aws:function-url":"aws:apigatewayv2",n.http.method,t.rawPath??n.http.path,r?void 0:o)}if(t.httpMethod)return vt("aws:apigateway",t.httpMethod,t.path,t.resource)}if(typeof t.source=="string"&&typeof t["detail-type"]=="string"){if(t.source==="aws.events"&&t["detail-type"]==="Scheduled Event"){let r={},s=xt(t.resources?.[0],"/");return s&&(r["ivy.trigger.rule"]=s),M("aws:scheduled","timer",r)}return M("aws:eventbridge","pubsub",{"aws.eventbridge.source":t.source,"aws.eventbridge.detail_types":[t["detail-type"]]})}return M("aws:lambda","other")}function Je(e,t,n){let r=vt("aws:lambda-web",e,t,void 0);return n&&(r.attributes["aws.lambda.web.endpoint"]=n),r}function Xe(e,t){if(t&&typeof t=="object"&&"statusCode"in t){let n=Number(t.statusCode);return Number.isInteger(n)?n:void 0}if(e==="aws:apigatewayv2"||e==="aws:function-url")return 200}var v=e=>typeof e=="string"&&e?e:Array.isArray(e)&&e.length?e.join(","):void 0,N=e=>typeof e=="number"&&Number.isFinite(e)?e:typeof e=="string"&&/^\d+$/.test(e)?Number(e):void 0,hr=/^(\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{12,}|(?=[^/]*\d)[A-Za-z0-9_-]{16,})$/i;function gr(e){return(e.split("?")[0].split("#")[0]||"/").split("/").map(n=>n&&hr.test(n)?"{id}":n).join("/")}function Ze(e){let t=v(e);return t&&/^[a-z]+:\/\/[^/]+(\/[^?#]*)?/i.exec(t)?.[1]||"/"}var yr=/(^|\.)(api\.openai\.com|api\.anthropic\.com|generativelanguage\.googleapis\.com|api\.mistral\.ai|api\.groq\.com|api\.cohere\.(ai|com)|api\.deepseek\.com|api\.together\.xyz|api\.fireworks\.ai|openrouter\.ai|api\.x\.ai)$|^bedrock-runtime\.[a-z0-9-]+\.amazonaws\.com$|\.openai\.azure\.com$/i,br=/\/(chat\/completions|completions|messages|responses|embeddings|generateContent|streamGenerateContent)$|\/model\/[^/]+\/(converse|converse-stream|invoke|invoke-with-response-stream)$/;function tn(e,t){if(e&&yr.test(e))return!0;let n=t?Ze(t).replace(/:[A-Za-z]+$/,r=>`/${r.slice(1)}`):"";return br.test(n)}function Sr(e){let t=v(e["gen_ai.request.model"])??v(e["ai.model.id"])??v(e["gen_ai.response.model"]);if(!t)return;let n=v(e["gen_ai.provider.name"])??v(e["gen_ai.system"])??v(e["ai.model.provider"])??"";return`llm ${v(e["ai.operationId"])??v(e["gen_ai.operation.name"])??""} ${n} ${t}`}function wt(e){let t=e.attributes,n=Sr(t);if(n)return n;if(t["rpc.system"]==="aws-api"){let s=v(t["aws.dynamodb.table_names"])??v(t["aws.s3.bucket"])??v(t["messaging.destination.name"])??v(t["faas.invoked_name"])??v(t["aws.eventbridge.bus"])??"";return`${v(t["rpc.service"])}.${v(t["rpc.method"])} ${s}`.trim()}let r=v(t["http.request.method"]);return r?`${r} ${v(t["server.address"])??""} ${gr(Ze(t["url.full"]))}`:e.name}var en=["rpc.system","rpc.service","rpc.method","cloud.region","aws.dynamodb.table_names","aws.s3.bucket","messaging.system","messaging.destination.name","faas.invoked_name","faas.invoked_region","aws.eventbridge.bus","http.request.method","server.address","server.port","otel.scope.name","gen_ai.provider.name","gen_ai.system","gen_ai.operation.name","gen_ai.request.model","gen_ai.response.model","ai.model.id","ai.model.provider","ai.operationId"];function zt(e){return{input:N(e["gen_ai.usage.input_tokens"])??N(e["ai.usage.inputTokens"])??N(e["ai.usage.promptTokens"])??N(e["gen_ai.usage.prompt_tokens"]),output:N(e["gen_ai.usage.output_tokens"])??N(e["ai.usage.outputTokens"])??N(e["ai.usage.completionTokens"])??N(e["gen_ai.usage.completion_tokens"])}}var Qe=(e,t)=>{let n;for(let r of e.matchAll(t))n=Number(r[1]);return n};function nn(e){return{input:Qe(e,/"(?:prompt_tokens|input_tokens|inputTokens|promptTokenCount)"\s*:\s*(\d+)/g),output:Qe(e,/"(?:completion_tokens|output_tokens|outputTokens|candidatesTokenCount)"\s*:\s*(\d+)/g)}}var At=class{constructor(t,n){this.opts=t;this.rootSpanId=n}opts;rootSpanId;groups=new Map;counted=new WeakSet;keptFirst=new WeakSet;summaries=new WeakSet;collapsedCalls=0;dropped=0;dropReasons=new Set;isSummary(t){return this.summaries.has(t)}get softLimit(){return this.opts.maxSpans+Math.max(100,Math.floor(this.opts.maxSpans/4))}drop(t,n){this.dropped+=t,this.dropReasons.add(n)}reduce(t,n){let r=this.opts.threshold>0?this.collapse(t,n):t;return r.length>this.opts.maxSpans&&(r=this.limit(r,n)),r}collapse(t,n){let r=kr(t),s=new Map,o=p=>{let u=s.get(p);return u===void 0&&(u=(n||p.endMs!==void 0)&&p.status.code!==b.ERROR&&(r.get(p.spanId)??[]).every(o),s.set(p,u)),u},i=new Map;for(let p of t){if(this.summaries.has(p))continue;let d=`${p.parentSpanId??this.rootSpanId}\0${wt(p)}`,f=p.status.code===b.ERROR;if(!this.counted.has(p)&&(f||p.endMs!==void 0||n)){this.counted.add(p);let l=this.group(d,p);l.calls++}if(!f&&!this.keptFirst.has(p)&&o(p)){let l=i.get(d);l?l.push(p):i.set(d,[p])}}let a=new Set,c=[];for(let[p,u]of i){let d=this.groups.get(p);if(d.calls<=this.opts.threshold)continue;u.sort((h,m)=>h.startMs-m.startMs);let f=Math.min(u.length,Math.max(0,this.opts.keepFirst-d.firstKept));for(let h of u.splice(0,f))this.keptFirst.add(h);d.firstKept+=f,u.sort((h,m)=>rt(m)-rt(h));let l=u.slice(this.opts.keepSlowest);if(l.length){for(let h of l)this.fold(d,h,r,a);d.summary||(d.summary=this.summarySpan(l[0],d),this.summaries.add(d.summary),c.push(d.summary)),this.updateSummary(d)}}return!a.size&&!c.length?t:[...t.filter(p=>!a.has(p)),...c]}group(t,n){let r=this.groups.get(t);return r||(r={signature:wt(n),baseName:n.name,calls:0,firstKept:0,count:0,totalMs:0,maxMs:0,minMs:1/0,start:1/0,end:-1/0,inputTokens:0,outputTokens:0,removedSpans:0},this.groups.set(t,r)),r}fold(t,n,r,s){let o=rt(n);t.count++,t.totalMs+=o,t.maxMs=Math.max(t.maxMs,o),t.minMs=Math.min(t.minMs,o),t.start=Math.min(t.start,n.startMs),t.end=Math.max(t.end,n.endMs??n.startMs);let i=this.tokensOf(n);t.inputTokens+=i.input??0,t.outputTokens+=i.output??0,this.collapsedCalls++;let a=[n];for(;a.length;){let c=a.pop();s.add(c),t.removedSpans++,a.push(...r.get(c.spanId)??[])}}tokensOf(t){let n=zt(t.attributes);if(n.input!==void 0||n.output!==void 0||!tn(t.attributes["server.address"],t.attributes["url.full"]))return n;try{t.finalize?.(t),t.finalize=void 0;let r=zt(t.attributes);if(r.input!==void 0||r.output!==void 0)return r;let s=t.payloads.find(o=>o.key==="ivy.payload.response")?.value;return typeof s=="string"?nn(s):n}catch{return n}}summarySpan(t,n){let r=H(t.traceId,n.baseName,t.kind,n.start,t.parentSpanId??this.rootSpanId);for(let s of en)t.attributes[s]!==void 0&&(r.attributes[s]=t.attributes[s]);return r}updateSummary(t){let n=t.summary;n.name=`${t.baseName} \xD7 ${t.count.toLocaleString("en-US")}`,n.startMs=t.start,n.endMs=t.end,Object.assign(n.attributes,{"ivy.collapsed.count":t.count,"ivy.collapsed.duration_total_ms":Yt(t.totalMs),"ivy.collapsed.duration_max_ms":Yt(t.maxMs),"ivy.collapsed.duration_min_ms":Yt(t.minMs),"ivy.collapsed.kept":t.calls-t.count,"ivy.collapsed.signature":t.signature}),(t.inputTokens||t.outputTokens)&&(n.attributes["ivy.collapsed.input_tokens"]=t.inputTokens,n.attributes["ivy.collapsed.output_tokens"]=t.outputTokens),t.removedSpans>t.count&&(n.attributes["ivy.collapsed.spans"]=t.removedSpans)}finishSummaries(t){let n=new Map;for(let r of t){if(r.status.code!==b.ERROR)continue;let s=`${r.parentSpanId??this.rootSpanId}\0${wt(r)}`;n.set(s,(n.get(s)??0)+1)}for(let[r,s]of this.groups)s.summary&&(s.summary.attributes["ivy.collapsed.errors"]=n.get(r)??0)}limit(t,n){let r=new Map(t.map(u=>[u.spanId,u])),s=new Map,o=u=>{let d=s.get(u);if(d===void 0){let f=u.parentSpanId&&u.parentSpanId!==this.rootSpanId?r.get(u.parentSpanId):void 0;s.set(u,0),d=f?o(f)+1:0,s.set(u,d)}return d},i=new Set,a=u=>{for(let d=u;d&&!i.has(d);d=d.parentSpanId?r.get(d.parentSpanId):void 0)i.add(d)};for(let u of t)(u.status.code===b.ERROR||this.summaries.has(u)||!n&&u.endMs===void 0)&&a(u);let c=t.filter(u=>!i.has(u)).sort((u,d)=>o(u)-o(d)||rt(d)-rt(u));for(let u of c){if(i.size>=this.opts.maxSpans)break;(!u.parentSpanId||u.parentSpanId===this.rootSpanId||i.has(r.get(u.parentSpanId)))&&i.add(u)}let p=t.filter(u=>i.has(u));return p.length<t.length&&this.drop(t.length-p.length,"span limit"),p}};function kr(e){let t=new Map;for(let n of e){if(!n.parentSpanId)continue;let r=t.get(n.parentSpanId);r?r.push(n):t.set(n.parentSpanId,[n])}return t}var rt=e=>(e.endMs??e.startMs)-e.startMs,Yt=e=>Math.round(e*1e3)/1e3;var _t=500,xr=4*1024,Rt=class{constructor(t,n,r=()=>{}){this.config=t;this.sink=n;this.log=r;this.isSecret=Se(t.redactKeys)}config;sink;log;current;scope;isSecret;coldStart=!0;resource;onInvocationStart;get active(){return this.scope?this.scope.getStore():this.current}enableConcurrency(){this.scope??=new(process.getBuiltinModule("node:async_hooks")).AsyncLocalStorage}runInvocation(t,n){return this.scope?this.scope.run(t,n):n()}startInvocation(t,n,r=Ge(t)){this.onInvocationStart?.(),te();let s=g(),o=n.functionName??process.env.AWS_LAMBDA_FUNCTION_NAME??"unknown",i=H(ee(s),o,r.kind,s);n.awsRequestId&&Object.assign(i,ne(n.awsRequestId,s));let a=n.awsRequestId??i.spanId;Object.assign(i.attributes,r.attributes,{"ivy.invocation":!0,"faas.invocation_id":a,"faas.coldstart":this.coldStart,"faas.trigger":r.trigger,"ivy.trigger.source":r.source}),n.invokedFunctionArn&&(i.attributes["cloud.resource_id"]=n.invokedFunctionArn),i.payloads.push({key:"ivy.payload.request",value:t}),this.coldStart=!1,this.resource||(this.resource=this.buildResource(n));let c=this.config,p=new At({threshold:c.collapseThreshold,keepFirst:c.collapseKeep,keepSlowest:c.collapseKeepSlowest,maxSpans:c.maxSpans},i.spanId),u={requestId:a,root:i,children:[],trigger:r,event:t,logCount:0,reducer:p,done:!1};this.scope||(this.current=u);let d=n.getRemainingTimeInMillis?.();return typeof d=="number"&&d>this.config.timeoutMarginMs+50&&(u.timer=setTimeout(()=>this.onTimeout(u),d-this.config.timeoutMarginMs),u.timer.unref()),u}startChild(t,n=O.CLIENT){let r=this.active;if(!r||r.done||!this.hasRoom(r))return;let s=H(r.root.traceId,t,n,g(),r.root.spanId);return r.children.push(s),s}addLog(t,n){let r=this.active;!r||r.done||r.logCount++>=_t||r.root.events.push({name:"log",timeMs:g(),attributes:{"log.severity":t,"log.message":C(n,xr).text}})}adopt(t,n,r,s,o){if(t.done)return;let i=t.openWorkerSpans??=new Map;for(let a of n){if(a.startMs<t.root.startMs)continue;a.traceId=t.root.traceId,(!a.parentSpanId||a.parentSpanId===s)&&(a.parentSpanId=o);let c=i.get(a.spanId);if(c)Object.assign(c,a);else if(this.hasRoom(t))t.children.push(a);else continue;a.endMs===void 0?i.set(a.spanId,c??a):i.delete(a.spanId)}for(let a of r)if(!(a.timeMs<t.root.startMs)){if(t.logCount++>=_t)break;t.root.events.push(a)}}hasRoom(t){return t.children.length<t.reducer.softLimit||(t.children=t.reducer.reduce(t.children,!1),t.children.length<t.reducer.softLimit)?!0:(t.reducer.drop(1,"span limit"),!1)}endInvocation(t,n,r){t.done||(t.done=!0,this.current===t&&(this.current=void 0),t.timer&&clearTimeout(t.timer),this.complete(t.root,t,n,r),setImmediate(()=>this.flush(t,!0)))}complete(t,n,r,s,o){let i=g();if(t.endMs=i,r!=null)T(t,r,i,o);else if(t.payloads.push({key:"ivy.payload.response",value:s}),n.trigger.trigger==="http"){let a=Xe(n.trigger.source,s);a!==void 0&&(t.attributes["http.response.status_code"]=a,a>=500&&(t.status={code:b.ERROR,message:`HTTP ${a}`}))}try{t.attributes["ivy.memory_used_mb"]=Math.round(process.memoryUsage.rss()/1048576)}catch{}}onTimeout(t){if(!t.done)try{let n={...t.root,attributes:{...t.root.attributes},events:[...t.root.events],payloads:[...t.root.payloads]},r=new Error(`Task timed out (ivy: flushed ${this.config.timeoutMarginMs}ms before the deadline)`);r.name="Timeout",r.stack=void 0,this.complete(n,t,r,void 0,"Timeout"),this.flush(t,!1,n)}catch(n){this.log(`timeout flush failed: ${n.message}`)}}flush(t,n,r){try{let s=r??t.root,o=s.endMs??g(),i=t.reducer;t.children=i.reduce(t.children,n),n&&i.finishSummaries(t.children);let a=t.children.map(f=>{let l=n?f:{...f,attributes:{...f.attributes}};return l.endMs===void 0&&(l.endMs=o,l.attributes["ivy.incomplete"]=!0),l});i.collapsedCalls&&(s.attributes["ivy.collapsed_calls"]=i.collapsedCalls),i.dropped&&(s.attributes["ivy.dropped_spans"]=i.dropped,s.attributes["ivy.dropped_spans.reason"]=[...i.dropReasons].join(", ")),t.logCount>_t&&(s.attributes["ivy.dropped_logs"]=t.logCount-_t);let c=new bt(this.config.maxInvocationPayloadBytes);this.applyPayloads(s,c);let p=new Map;for(let f of vr(a))this.applyPayloads(f,c),p.set(f,Wt(f));c.trimmedPayloads&&(s.attributes["ivy.trimmed_payload_bytes"]=c.trimmedBytes,s.attributes["ivy.trimmed_payloads"]=c.trimmedPayloads);let u=this.resource??[],d=We(a.map(f=>p.get(f)),{spans:this.config.exportChunkSpans,bytes:this.config.exportChunkBytes});this.sink({requestId:t.requestId,final:n&&!d.length,resource:u,spans:[Wt(s)]}),d.forEach((f,l)=>this.sink({requestId:t.requestId,final:n&&l===d.length-1,resource:u,spans:f}))}catch(s){this.log(`flush failed: ${s.message}`)}}applyPayloads(t,n){try{t.finalize?.(t)}catch{}t.finalize=void 0;let r=!1;for(let o in t.attributes){let i=t.attributes[o];typeof i=="string"&&St(o)&&!n.take(E(i))&&(delete t.attributes[o],r=!0)}let s=!1;for(let o of t.payloads){if(n.remaining<=0){n.take(typeof o.value=="string"?Math.min(E(o.value),this.config.maxPayloadBytes):1),r=!0;continue}try{let i=o.rawContentType!==void 0&&typeof o.value=="string"?xe(o.value,o.rawContentType,this.config.maxPayloadBytes,this.isSecret):Y(o.value,this.config.maxPayloadBytes,this.isSecret);if(!i.text)continue;n.take(E(i.text))?t.attributes[o.key]=i.text:r=!0,s||=i.truncated}catch{}}t.payloads=[],s&&(t.attributes["ivy.payload.truncated"]=!0),r&&(t.attributes["ivy.payload.trimmed"]=!0)}buildResource(t){let n=process.env,r=t.functionName??n.AWS_LAMBDA_FUNCTION_NAME??"unknown",s={"service.name":r,"cloud.provider":"aws","cloud.platform":"aws_lambda","faas.name":r,"telemetry.sdk.name":"ivy-layer","telemetry.sdk.language":"nodejs","process.runtime.version":process.versions.node,"host.arch":process.arch==="x64"?"amd64":process.arch},o=n.AWS_REGION??n.AWS_DEFAULT_REGION;o&&(s["cloud.region"]=o);let i=t.invokedFunctionArn?.split(":")[4];i&&(s["cloud.account.id"]=i);let a=t.functionVersion??n.AWS_LAMBDA_FUNCTION_VERSION;a&&(s["faas.version"]=a);let c=parseInt(t.memoryLimitInMB??n.AWS_LAMBDA_FUNCTION_MEMORY_SIZE??"",10);return Number.isFinite(c)&&(s["faas.max_memory"]=c*1024*1024),n.AWS_LAMBDA_LOG_STREAM_NAME&&(s["faas.instance"]=n.AWS_LAMBDA_LOG_STREAM_NAME),kt(s)}};function vr(e){let t=a=>a.status.code===b.ERROR,n=e.filter(t),r=e.filter(a=>!t(a)),s=a=>(a.endMs??a.startMs)-a.startMs,o=Math.max(5,Math.ceil(r.length/10)),i=new Set([...r].sort((a,c)=>s(c)-s(a)).slice(0,o));return[...n,...r.filter(a=>i.has(a)),...r.filter(a=>!i.has(a)).sort((a,c)=>a.startMs-c.startMs)]}var wr,rn=()=>wr??={http:new(process.getBuiltinModule("node:http")).Agent({keepAlive:!0,maxSockets:2}),https:new(process.getBuiltinModule("node:https")).Agent({keepAlive:!0,maxSockets:2})};function Ar(e,t,n){return new Promise((r,s)=>{let o=!1,i=m=>{o||(o=!0,clearTimeout(a),m())},a=setTimeout(()=>{i(()=>s(new Error(`timeout after ${n.timeoutMs}ms`))),h.destroy()},n.timeoutMs),c=Buffer.from(t,"utf8"),p={"content-type":"application/json",...n.headers};n.gzip&&c.length>1024&&(c=process.getBuiltinModule("node:zlib").gzipSync(c),p["content-encoding"]="gzip"),p["content-length"]=c.length;let u=new URL(e),d=u.protocol==="https:",f=Oe(process.getBuiltinModule(d?"node:https":"node:http").request),l=n.keepAlive===!1?!1:d?rn().https:rn().http,h=f(u,{method:"POST",headers:p,agent:l},m=>{let k=[];m.on("data",y=>k.push(y)),m.on("end",()=>i(()=>r({status:m.statusCode??0,body:Buffer.concat(k).toString("utf8"),retryAfter:[m.headers["retry-after"]].flat()[0]}))),m.on("error",y=>i(()=>s(y)))});h.on("error",m=>i(()=>s(m))),h.end(c)})}function _r(e){return e===408||e===429||e>=500}function Rr(e,t=Date.now()){if(!e)return;let n=e.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}var Mr=e=>new Promise(t=>setTimeout(t,e));async function sn(e,t,n){let r=Date.now()+n.budgetMs,s=n.attempts??3;for(let o=0;o<s;o++){let i=r-Date.now();if(i<50)break;try{let c=await Ar(e,t,{...n,timeoutMs:Math.min(n.timeoutMs,i)});if(c.status>=200&&c.status<300)return{ok:!0};if(n.onError?.(`export failed with HTTP ${c.status}: ${c.body.slice(0,200)}`),!_r(c.status))return{ok:!1};let p=c.status===429||c.status===503?Rr(c.retryAfter):void 0;if(p!==void 0)return{ok:!1,retryAfterMs:p}}catch(c){n.onError?.(`export failed: ${c.message}`)}let a=100*3**o;if(Date.now()+a>=r)break;await Mr(a)}return{ok:!1}}var Tr=5e3,Ir=5*6e4,Cr=60*6e4,Mt=class{constructor(t){this.opts=t}opts;batches=[];queued=0;flushing;dropped=0;nextAttemptAt=0;backoffMs=0;serverPauseUntil=0;get size(){return this.queued}get pending(){return this.batches.length}add(t){if(t.spans.length){for(;this.batches.length&&this.queued+t.spans.length>this.opts.maxQueueSpans;){let n=this.batches.shift();this.queued-=n.spans.length,this.drop(n.spans.length,"queue full")}if(t.spans.length>this.opts.maxQueueSpans){this.drop(t.spans.length,"batch larger than queue");return}this.batches.push(t),this.queued+=t.spans.length}}drop(t,n){this.dropped+=t,this.opts.log?.(`dropped ${t} spans (${n}); ${this.dropped} dropped since last successful export`)}flush(t,n=!1){return this.flushing?this.flushing:(this.flushing=this.doFlush(t,n).finally(()=>{this.flushing=void 0}),this.flushing)}async doFlush(t,n){let r=this.opts.now??Date.now,s=r()+t;if(r()<this.serverPauseUntil||!n&&r()<this.nextAttemptAt)return;let o=this.opts.maxSpansPerRequest??500;for(;this.batches.length&&s-r()>50;){let i=[],a=0,c=on(this.batches[0]);for(;this.batches.length&&(a===0||a+this.batches[0].spans.length<=o&&on(this.batches[0])===c);){let h=this.batches.shift();i.push(h),a+=h.spans.length}this.queued-=a;let p=this.dropped;if(p>0){let h=i[0].spans[0];h.attributes=h.attributes.filter(m=>m.key!=="ivy.dropped_spans"),h.attributes.push({key:"ivy.dropped_spans",value:{intValue:String(p)}})}let u=JSON.stringify(Ye(i)),d=await this.send(u,s-r()),{ok:f,retryAfterMs:l}=typeof d=="boolean"?{ok:d,retryAfterMs:void 0}:d;if(f)this.dropped-=p,this.backoffMs=0,this.nextAttemptAt=0;else{this.drop(a,l===void 0?"export failed":`rejected, retry after ${Math.round(l/1e3)} s`),this.backoffMs=Math.min(Ir,this.backoffMs?this.backoffMs*2:Tr),this.nextAttemptAt=r()+this.backoffMs,l!==void 0&&(this.serverPauseUntil=r()+Math.min(l,Cr),this.nextAttemptAt=Math.max(this.nextAttemptAt,this.serverPauseUntil));return}}}send(t,n){if(this.opts.send)return this.opts.send(t,n);let r={};return this.opts.apiKey&&(r.authorization=`Bearer ${this.opts.apiKey}`),sn(this.opts.url,t,{headers:r,gzip:!0,timeoutMs:this.opts.exportTimeoutMs,budgetMs:n,onError:this.opts.log})}},on=e=>e.spans.length>0&&e.spans.every(t=>t.attributes.some(n=>n.key==="ivy.invocation"&&"boolValue"in n.value&&n.value.boolValue));var Er=100,Or=800;function an(e,t,n=Nr(e,t)){let r,s=()=>{r=void 0,n.flush(e.flushBudgetMaxMs).catch(()=>{}).finally(()=>{n.pending&&!r&&o()})},o=()=>{r=setTimeout(s,Er),r.unref()},i=()=>{r&&clearTimeout(r),r=void 0;let a=process.listenerCount("SIGTERM")===1;n.flush(Or,!0).catch(()=>{}).finally(()=>{a&&(process.removeListener("SIGTERM",i),process.kill(process.pid,"SIGTERM"))})};return process.prependListener("SIGTERM",i),{sink(a){n.add(a),a.final&&!r&&o()},queue:n}}function Nr(e,t){return new Mt({url:e.tracesUrl,apiKey:e.apiKey,maxQueueSpans:e.maxQueueSpans,exportTimeoutMs:e.exportTimeoutMs,maxSpansPerRequest:e.exportChunkSpans,log:t})}var un=Symbol.for("ivy.http-server.patched"),Br="lambda-web-request-id",Pr="lambda-web-endpoint-name";function dn(e,t={}){let r=process.getBuiltinModule("node:http").Server.prototype;if(r[un])return;Object.defineProperty(r,un,{value:!0});let s=r.emit;r.emit=function(o,...i){if(o!=="request")return s.call(this,o,...i);let a;try{a=Lr(e,i[0],i[1],t)}catch{a=void 0}return a?e.runInvocation(a,()=>s.call(this,o,...i)):s.call(this,o,...i)}}function Lr(e,t,n,r){let s=t.headers,o=R(s,Pr),i=t.url??"/",a=Math.max(e.config.maxPayloadBytes*4,64*1024),c=new I(a),p={method:t.method,url:at(i,e.isSecret),headers:s},u=e.startInvocation(p,{awsRequestId:R(s,Br),functionName:r.functionName??o},Je(t.method,i,o)),d=t.emit;t.emit=function(y,...x){try{y==="data"&&c.add(x[0],this.readableEncoding??void 0)}catch{}return e.runInvocation(u,()=>d.call(this,y,...x))};let f=n.emit;n.emit=function(y,...x){return e.runInvocation(u,()=>f.call(this,y,...x))};let l=new I(a),h=n.write;n.write=function(y,...x){try{l.add(y,typeof x[0]=="string"?x[0]:void 0)}catch{}return h.call(this,y,...x)};let m=n.end;n.end=function(y,...x){try{typeof y!="function"&&l.add(y,typeof x[0]=="string"?x[0]:void 0)}catch{}return m.call(this,y,...x)};let k=y=>{if(!u.done)try{let x=cn(c,R(s,"content-type"));x!==void 0&&(p.body=x);let st=Vr(t);st&&(u.root.attributes["http.route"]=st);let ot=n.getHeaders(),Gt={statusCode:n.statusCode,headers:ot},Jt=cn(l,R(ot,"content-type"));if(Jt!==void 0&&(Gt.body=Jt),y){let Tt=new Error("The connection closed before the response was complete");Tt.name="ConnectionClosed",Tt.stack=void 0,e.endInvocation(u,Tt,void 0)}else e.endInvocation(u,null,Gt)}catch{}};return n.once("finish",()=>k(!1)),n.once("close",()=>k(!n.writableFinished)),u}function cn(e,t){if(e.total===0||!q(t))return;let n=e.text();if(e.bytes===e.total&&/json/i.test(t??""))try{return JSON.parse(n)}catch{}return n}function Vr(e){let t=e,n=t.route?.path;if(typeof n=="string")return`${typeof t.baseUrl=="string"?t.baseUrl:""}${n}`||void 0}var pn="ivy.workers.traced";function fn(e){return!!e&&typeof e=="object"&&e.ivyWorkerBatch===1}var ln=Symbol.for("ivy.worker_threads.patched");function mn(e,t){let n=!1,r=()=>{n=!0,qr(e,t)};return $(s=>{!n&&(s==="worker_threads"||s==="node:worker_threads")&&r()}),()=>{!n&&lt("worker_threads")&&r()}}function qr(e,t){let n=process.getBuiltinModule("node:worker_threads");if(n[ln])return;Object.defineProperty(n,ln,{value:!0}),n.setEnvironmentData(pn,!0);let r=new Map,s=(c,p)=>{let u=r.get(c),d=u&&!u.inv.done?u.inv:e.active;if(!d||d.done)return;let f=u?.inv===d?u.span.spanId:d.root.spanId;e.adopt(d,p.spans,p.logs,p.root,f)},o,i=n.Worker;n.Worker=new Proxy(i,{construct(c,p,u){let[d,f]=p,l=Array.isArray(f?.execArgv)?f.execArgv:void 0,h=k=>Reflect.construct(c,[d,{...f,execArgv:[...k,"--require",t]},...p.slice(2)],u),m;try{m=h(l??o??process.execArgv)}catch(k){let y=!l&&!o?$r(k):void 0;if(y){o=process.execArgv.filter(x=>!y.includes(x));try{m=h(o)}catch{m=void 0}}m??=Reflect.construct(c,p,u)}try{a(m,d,f)}catch{}return m}}),process.getBuiltinModule("node:module").syncBuiltinESMExports();function a(c,p,u){let d=c.threadId,f=e.active,l=f?e.startChild(Ur(p,u),O.INTERNAL):void 0;if(f&&l){l.attributes["thread.id"]=d,typeof u?.name=="string"&&u.name&&(l.attributes["thread.name"]=u.name);let m=hn(p,u);m&&(l.attributes["code.file.path"]=m),r.set(d,{span:l,inv:f})}let h=c.emit;c.emit=function(m,...k){if(m==="message"&&fn(k[0])){try{s(d,k[0])}catch{}return!0}try{m==="error"&&l?T(l,k[0],g()):m==="exit"&&(r.delete(d),l&&Kr(l,k[0]))}catch{}return h.call(this,m,...k)}}}function Kr(e,t){e.endMs=g(),typeof t=="number"&&(e.attributes["process.exit.code"]=t,t!==0&&e.status.code!==b.ERROR&&(e.status={code:b.ERROR,message:`Worker exited with code ${t}`}))}function $r(e){let t=e;if(t?.code!=="ERR_WORKER_INVALID_EXEC_ARGV"||typeof t.message!="string")return;let r=t.message.split(": ").slice(1).join(": ").split(", ").filter(Boolean);return r.length?r:void 0}function hn(e,t){if(!t?.eval){if(e instanceof URL)return e.protocol==="file:"?decodeURIComponent(e.pathname):void 0;if(typeof e=="string")return e.startsWith("file:")?decodeURIComponent(new URL(e).pathname):e.includes(":")&&!e.startsWith("/")?void 0:e}}function Ur(e,t){if(typeof t?.name=="string"&&t.name)return`worker ${t.name}`;if(t?.eval)return"worker (eval)";let n=hn(e,t);return n?`worker ${n.split(/[\\/]/).pop()}`:"worker"}var yn=console.warn.bind(console),j=Xt(),gn=e=>j.debug&&yn(`[ivy] ${e}`);if(j.enabled)try{let e=an(j,gn),t=new Rt(j,e.sink,gn);t.enableConcurrency();let n=Pe(t),r=j.captureWorkers?mn(t,`${import.meta.dirname}/worker.cjs`):void 0;t.onInvocationStart=()=>{n(),r?.()},Ie(t),Me(t),j.captureLogs&&Te(t),Fe(t),dn(t,{functionName:process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.IVY_FUNCTION_NAME||void 0})}catch(e){yn(`[ivy] tracing disabled, setup failed: ${e.message}`)}
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@ivytrace/lambda-web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Ivy tracing for AWS Lambda Web Functions",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./index.mjs"
8
+ },
9
+ "files": [
10
+ "index.mjs",
11
+ "worker.cjs",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=24"
16
+ },
17
+ "license": "MIT",
18
+ "homepage": "https://ivytrace.dev",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/ivytrace/ivy.git",
22
+ "directory": "packages/layer/web"
23
+ },
24
+ "keywords": [
25
+ "aws",
26
+ "lambda",
27
+ "web-functions",
28
+ "tracing",
29
+ "opentelemetry"
30
+ ]
31
+ }
package/worker.cjs ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";var Ge="password,secret,token,authorization,cookie,apikey,api_key,accesskey,secretaccesskey,sessiontoken,creditcard,cardnumber,cvv";function k(e,t){let n=e===void 0?NaN:parseInt(e,10);return Number.isFinite(n)&&n>=0?n:t}function tt(e,t){return e===void 0||e===""?t:!["0","false","no","off"].includes(e.toLowerCase())}function Je(e){if(!e)return;let t=e.replace(/\/+$/,"");return t.endsWith("/v1/traces")?t:`${t}/v1/traces`}function et(e=process.env){let t=e.IVY_ENDPOINT||void 0;return{endpoint:t,tracesUrl:Je(t),apiKey:e.IVY_API_KEY||void 0,enabled:!!t&&!tt(e.IVY_DISABLE,!1),debug:tt(e.IVY_DEBUG,!1),maxPayloadBytes:k(e.IVY_MAX_PAYLOAD_BYTES,16*1024),redactKeys:(e.IVY_REDACT_KEYS??Ge).split(",").map(n=>n.trim()).filter(Boolean),extensionPort:k(e.IVY_EXTENSION_PORT,9790),timeoutMarginMs:k(e.IVY_TIMEOUT_MARGIN_MS,100),exportTimeoutMs:k(e.IVY_EXPORT_TIMEOUT_MS,1e3),flushBudgetMs:k(e.IVY_FLUSH_BUDGET_MS,2e3),flushBudgetPerChunkMs:k(e.IVY_FLUSH_BUDGET_PER_CHUNK_MS,500),flushBudgetMaxMs:k(e.IVY_FLUSH_BUDGET_MAX_MS,5e3),exportChunkSpans:Math.max(1,k(e.IVY_EXPORT_CHUNK_SPANS,500)),exportChunkBytes:Math.max(16*1024,k(e.IVY_EXPORT_CHUNK_BYTES,1024*1024)),maxQueueSpans:k(e.IVY_MAX_QUEUE_SPANS,2e3),captureLogs:tt(e.IVY_CAPTURE_LOGS,!0),captureWorkers:tt(e.IVY_CAPTURE_WORKERS,!0),maxSpans:Math.max(10,k(e.IVY_MAX_SPANS,2e3)),maxInvocationPayloadBytes:k(e.IVY_MAX_INVOCATION_PAYLOAD_BYTES,1024*1024),collapseThreshold:k(e.IVY_COLLAPSE_THRESHOLD,50),collapseKeep:k(e.IVY_COLLAPSE_KEEP,10),collapseKeepSlowest:k(e.IVY_COLLAPSE_KEEP_SLOWEST,3)}}var xt=()=>{let[e,t]=process.hrtime();return e*1e3+t/1e6},Ht=Date.now(),Ft=xt();function Dt(){Ht=Date.now(),Ft=xt()}function m(){return Ht+(xt()-Ft)}function vt(e){let t="";for(let n=0;n<e;n+=4)t+=(Math.random()*4294967296>>>0).toString(16).padStart(8,"0");return t.slice(0,e*2)}function zt(e=Date.now()){return(Math.floor(e/1e3)>>>0).toString(16).padStart(8,"0")+vt(12)}function Xe(e){let t=2166136261,n=Buffer.from(e,"utf8");for(let r=0;r<n.length;r++)t^=n[r],t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Yt(e,t){let n="";for(let o=0;o<5;o++)n+=Xe(`${o}:${e}`);let r=Math.floor(t/1e3)>>>0,s=n.slice(0,16)==="0000000000000000"?"0000000000000001":n.slice(0,16);return{traceId:r.toString(16).padStart(8,"0")+n.slice(16),spanId:s}}function Wt(){let e=vt(8);for(;e==="0000000000000000";)e=vt(8);return e}var N={INTERNAL:1,SERVER:2,CLIENT:3,PRODUCER:4,CONSUMER:5},y={UNSET:0,OK:1,ERROR:2};function K(e,t,n,r,s){return{traceId:e,spanId:Wt(),parentSpanId:s,name:t,kind:n,startMs:r,attributes:{},events:[],status:{code:y.UNSET},payloads:[]}}function wt(e){return e&&e.split(`
2
+ `).filter(t=>!t.includes("/opt/nodejs/ivy/")).join(`
3
+ `)}function T(e,t,n,r){let s=t,o=r??(s&&typeof s=="object"?String(s.name??s.constructor?.name??"Error"):typeof t=="string"?"Error":typeof t),i=String(s&&typeof s=="object"?s.message??"":t);e.status={code:y.ERROR,message:i},e.attributes["error.type"]=o;let a={"exception.type":o,"exception.message":i},c=s&&typeof s=="object"&&typeof s.stack=="string"?wt(s.stack):void 0;c&&(a["exception.stacktrace"]=c),e.events.push({name:"exception",timeMs:n,attributes:a})}var Qe={dynamodb:"DynamoDB",s3:"S3",sqs:"SQS",sns:"SNS",lambda:"Lambda",events:"EventBridge",ses:"SES",secretsmanager:"SecretsManager",kinesis:"Kinesis",firehose:"Firehose",states:"SFN",ssm:"SSM",sts:"STS",kms:"KMS","cognito-idp":"CognitoIdentityProvider",scheduler:"Scheduler",bedrock:"Bedrock",execute:"ApiGatewayManagementApi",cloudwatch:"CloudWatch",logs:"CloudWatchLogs"};function Gt(e){if(!(typeof e!="string"||!e))return e.replace(/Client$/,"")||void 0}function Jt(e){return Qe[e]??e.charAt(0).toUpperCase()+e.slice(1)}function Xt(e){if(!(typeof e!="string"||!e))return e.replace(/Command$/,"")||void 0}var x=e=>typeof e=="string"&&e?e:void 0;function Ze(e){let t=x(e);if(!t)return;let n=/:table\/([^/]+)/.exec(t);return n?n[1]:t}function tn(e){let t=new Set,n=r=>{let s=Ze(r);s&&t.add(s)};if(n(e.TableName),e.RequestItems&&typeof e.RequestItems=="object"&&Object.keys(e.RequestItems).forEach(n),Array.isArray(e.TransactItems))for(let r of e.TransactItems)for(let s of["Get","Put","Update","Delete","ConditionCheck"])n(r?.[s]?.TableName);if(typeof e.Statement=="string"){let r=/\b(?:from|into|update)\s+"?([A-Za-z0-9_.-]+)"?/i.exec(e.Statement);r&&n(r[1])}return[...t]}function q(e,t,n,r){let s={},o=t&&typeof t=="object"?t:{},i=n&&typeof n=="object"?n:{};switch(e){case"DynamoDB":{let a=tn(o);a.length&&(s["aws.dynamodb.table_names"]=a);break}case"S3":x(o.Bucket)&&(s["aws.s3.bucket"]=o.Bucket),x(o.Key)&&(s["aws.s3.key"]=o.Key);break;case"SQS":{s["messaging.system"]="aws_sqs";let a=x(o.QueueUrl)?.split("/").pop()??x(o.QueueName);a&&(s["messaging.destination.name"]=a),x(i.MessageId)&&(s["messaging.message.id"]=i.MessageId);break}case"SNS":{s["messaging.system"]="aws_sns";let c=(x(o.TopicArn)??x(o.TargetArn))?.split(":").pop()??(x(o.PhoneNumber)?"phone":void 0);c&&(s["messaging.destination.name"]=c),x(i.MessageId)&&(s["messaging.message.id"]=i.MessageId);break}case"Lambda":{let a=x(o.FunctionName);if(a){let c=/^arn:[^:]+:lambda:([^:]+):[^:]+:function:([^:]+)/.exec(a);s["faas.invoked_name"]=c?c[2]:a.split(":")[0];let d=c?.[1]??r;d&&(s["faas.invoked_region"]=d)}break}case"EventBridge":{let a=Array.isArray(o.Entries)?o.Entries:[];if(a.length){s["aws.eventbridge.bus"]=x(a[0]?.EventBusName)?.split("/").pop()??"default";let c=[...new Set(a.map(d=>d?.DetailType).filter(d=>typeof d=="string"))];c.length&&(s["aws.eventbridge.detail_types"]=c)}break}}return s}function Qt(e){if(typeof e!="string"||!e.startsWith("AWS4-HMAC-SHA256"))return;let t=/Credential=[^/]+\/\d{8}\/([^/]+)\/([^/]+)\/aws4_request/.exec(e);return t?{region:t[1],service:t[2]}:void 0}function Zt(e,t){if(typeof e=="string"&&e.includes("."))return e.slice(e.lastIndexOf(".")+1);if(t){let n=/(?:^|&)Action=([A-Za-z0-9]+)/.exec(t);if(n)return n[1]}}var B="BedrockRuntime",ee={invoke:"InvokeModel","invoke-with-response-stream":"InvokeModelWithResponseStream",converse:"Converse","converse-stream":"ConverseStream"},ne=new Set(Object.values(ee)),re=e=>e==="InvokeModelWithResponseStream"||e==="ConverseStream",At=e=>e.startsWith("Converse"),g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),v=(...e)=>{for(let t of e){if(t==null||t==="")continue;let n=Number(t);if(Number.isFinite(n))return n}},se=(...e)=>e.find(t=>t!=null&&t!=="");function oe(e,t){if(!/^bedrock-runtime(-fips)?\.[a-z0-9-]+\.amazonaws\.com$/i.test(e))return;let n=/^\/model\/([^/?#]+)\/(invoke|invoke-with-response-stream|converse|converse-stream)(?:[?#]|$)/.exec(t);if(!n)return;let r=n[1];try{r=decodeURIComponent(r)}catch{}return{operation:ee[n[2]],modelId:r}}var en=new TextDecoder;function M(e){if(g(e)&&!(e instanceof Uint8Array))return e;try{let t=typeof e=="string"?e:e instanceof Uint8Array&&e.byteLength<=1048576?en.decode(e):void 0,n=t===void 0?void 0:JSON.parse(t);return g(n)?n:void 0}catch{return}}function $(e,t){let n={"gen_ai.system":"aws.bedrock","gen_ai.operation.name":/embed/i.test(e??"")?"embeddings":"chat"};e&&(n["gen_ai.request.model"]=e);let r=t??{},s=g(r.inferenceConfig)?r.inferenceConfig:g(r.textGenerationConfig)?r.textGenerationConfig:{},o=v(r.max_tokens,r.max_gen_len,r.max_new_tokens,r.max_completion_tokens,s.maxTokens,s.max_new_tokens,s.maxTokenCount),i=v(r.temperature,s.temperature),a=v(r.top_p,r.p,s.topP,s.top_p);return o!==void 0&&(n["gen_ai.request.max_tokens"]=o),i!==void 0&&(n["gen_ai.request.temperature"]=i),a!==void 0&&(n["gen_ai.request.top_p"]=a),n}function te(e,t){if(g(e)){for(let n in e)if(n.toLowerCase()===t)return e[n]}}function j(e,t){let n={},r=e??{},s=g(r.usage)?r.usage:{},o=g(r["amazon-bedrock-invocationMetrics"])?r["amazon-bedrock-invocationMetrics"]:{},i=g(r.meta?.billed_units)?r.meta.billed_units:{},c=(Array.isArray(r.results)?r.results:[]).reduce((f,l)=>g(l)&&v(l.tokenCount)!==void 0?(f??0)+Number(l.tokenCount):f,void 0),d=v(s.input_tokens,s.inputTokens,s.prompt_tokens,r.prompt_token_count,i.input_tokens,r.inputTextTokenCount,o.inputTokenCount,te(t,"x-amzn-bedrock-input-token-count")),u=v(s.output_tokens,s.outputTokens,s.completion_tokens,r.generation_token_count,i.output_tokens,c,o.outputTokenCount,te(t,"x-amzn-bedrock-output-token-count"));d!==void 0&&(n["gen_ai.usage.input_tokens"]=d),u!==void 0&&(n["gen_ai.usage.output_tokens"]=u);let p=se(r.stop_reason,r.stopReason,r.finish_reason,r.choices?.[0]?.finish_reason,r.outputs?.[0]?.stop_reason,r.generations?.[0]?.finish_reason,r.results?.[0]?.completionReason);return typeof p=="string"&&(n["gen_ai.response.finish_reasons"]=[p]),typeof r.model=="string"&&r.model&&(n["gen_ai.response.model"]=r.model),typeof r.id=="string"&&r.id&&(n["gen_ai.response.id"]=r.id),n}var nn=256*1024,_t=class{firstChunkMs;anthropic=!1;message={};blocks=[];converse=!1;converseBlocks=[];stopReason;usage={};metrics;text="";add(t){if(g(t))if(this.firstChunkMs??=m(),g(t.chunk)){let n=M(t.chunk.bytes);n&&this.addChunk(n)}else this.addConverse(t)}append(t,n,r){if(typeof r!="string")return;let s=typeof t[n]=="string"?t[n]:"";s.length<nn&&(t[n]=s+r)}addChunk(t){switch(g(t["amazon-bedrock-invocationMetrics"])&&(this.metrics=t["amazon-bedrock-invocationMetrics"]),t.type){case"message_start":if(this.anthropic=!0,g(t.message)){this.message={id:t.message.id,model:t.message.model};let o=v(t.message.usage?.input_tokens);o!==void 0&&(this.usage.input_tokens=o)}return;case"content_block_start":this.anthropic=!0,this.blocks[t.index??this.blocks.length]={...g(t.content_block)?t.content_block:{type:"text",text:""}};return;case"content_block_delta":{let o=this.blocks[t.index??0]??={type:"text",text:""},i=t.delta??{};i.type==="input_json_delta"?this.append(o,"partial",i.partial_json):i.type==="thinking_delta"?this.append(o,"thinking",i.thinking):this.append(o,"text",i.text);return}case"message_delta":typeof t.delta?.stop_reason=="string"&&(this.stopReason=t.delta.stop_reason),v(t.usage?.output_tokens)!==void 0&&(this.usage.output_tokens=Number(t.usage.output_tokens));return;case"content_block_stop":case"message_stop":case"ping":return}if(t.contentBlockDelta||t.contentBlockStart||t.messageStop||t.metadata||t.messageStart){this.addConverse(t);return}this.append(this,"text",t.generation??t.outputText??t.completion??t.outputs?.[0]?.text??t.choices?.[0]?.delta?.content??(t.is_finished?void 0:t.text));let n=se(t.stop_reason,t.outputs?.[0]?.stop_reason,t.completionReason,t.finish_reason,t.choices?.[0]?.finish_reason);typeof n=="string"&&(this.stopReason=n);let r=v(t.prompt_token_count,t.inputTextTokenCount),s=v(t.generation_token_count,t.totalOutputTextTokenCount);r!==void 0&&(this.usage.input_tokens=r),s!==void 0&&(this.usage.output_tokens=(this.usage.output_tokens??0)+s)}addConverse(t){if(this.converse=!0,g(t.contentBlockStart)){let n=t.contentBlockStart.start?.toolUse;this.converseBlocks[t.contentBlockStart.contentBlockIndex??this.converseBlocks.length]=g(n)?{toolUse:{...n,input:""}}:{}}else if(g(t.contentBlockDelta)){let n=t.contentBlockDelta.contentBlockIndex??0,r=this.converseBlocks[n]??={},s=t.contentBlockDelta.delta??{};g(s.toolUse)?this.append(r.toolUse??={input:""},"input",s.toolUse.input):g(s.reasoningContent)?this.append((r.reasoningContent??={reasoningText:{}}).reasoningText,"text",s.reasoningContent.text):this.append(r,"text",s.text)}else if(g(t.messageStop))typeof t.messageStop.stopReason=="string"&&(this.stopReason=t.messageStop.stopReason);else if(g(t.metadata)){if(g(t.metadata.usage)){let{inputTokens:n,outputTokens:r}=t.metadata.usage;v(n)!==void 0&&(this.usage.input_tokens=Number(n)),v(r)!==void 0&&(this.usage.output_tokens=Number(r))}g(t.metadata.metrics)&&(this.metrics=t.metadata.metrics)}}result(){let t={...this.usage};if(this.anthropic){let n=this.blocks.filter(Boolean).map(({partial:r,...s})=>{if(r===void 0)return s;try{return{...s,input:JSON.parse(r)}}catch{return{...s,input:r}}});return{...this.message,role:"assistant",content:n,stop_reason:this.stopReason,usage:t,"amazon-bedrock-invocationMetrics":this.metrics}}return this.converse?{output:{message:{role:"assistant",content:this.converseBlocks.filter(Boolean).map(r=>{if(!g(r.toolUse)||typeof r.toolUse.input!="string")return r;try{return{toolUse:{...r.toolUse,input:JSON.parse(r.toolUse.input||"{}")}}}catch{return r}})}},stopReason:this.stopReason,usage:{inputTokens:t.input_tokens,outputTokens:t.output_tokens},metrics:this.metrics}:{role:"assistant",content:[{type:"text",text:this.text}],stop_reason:this.stopReason,usage:t,"amazon-bedrock-invocationMetrics":this.metrics}}};function ie(e,t){let n=new _t,r=!1,s=o=>{if(!r){r=!0;try{e.endMs=m(),o&&T(e,o,e.endMs);let i=n.result();Object.assign(e.attributes,j(i)),n.firstChunkMs!==void 0&&(e.attributes["gen_ai.response.time_to_first_chunk"]=Math.round(n.firstChunkMs-e.startMs)/1e3),e.payloads.push({key:"ivy.payload.response",value:i})}catch{}}};return{[Symbol.asyncIterator](){let o=t[Symbol.asyncIterator]();return{async next(...i){try{let a=await o.next(...i);if(a.done)s();else try{n.add(a.value)}catch{}return a}catch(a){throw s(a),a}},async return(i){return s(),o.return?o.return(i):{done:!0,value:i}},async throw(i){if(s(i),o.throw)return o.throw(i);throw i}}}}}var C="[redacted]",Tt=e=>e.toLowerCase().replace(/[-_]/g,""),rn=/(tokens|tokencounts?|tokensdetails|tokenusage)$/,sn=/(access|refresh|session|id|api|auth|bearer|oauth|csrf|xsrf|client|device|push|secret|security|reset|invite|verification|bot)$/;function on(e){let t=Tt(e),n=rn.exec(t);return!!n&&!sn.test(t.slice(0,n.index))}var an=0,ae=1,ue=2;function pe(e){let t=[...new Set(e.map(Tt).filter(Boolean))],n=new Map,r=s=>{let o=n.get(s);if(o===void 0){let i=Tt(s),a=on(i)?[]:t.filter(c=>i.includes(c));o=a.length?a.every(c=>c.includes("token"))?ae:ue:an,n.size<5e3&&n.set(s,o)}return o};return(s,o)=>{let i=r(s);return i===ae?!(typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"):i===ue}}function _(e,t){if(e.length<=t/3)return{text:e,truncated:!1};let n=Buffer.from(e,"utf8");if(n.length<=t)return{text:e,truncated:!1};let r=n.subarray(0,t).toString("utf8");r.endsWith("\uFFFD")&&(r=r.replace(/�+$/,""));let s=n.length-Buffer.byteLength(r,"utf8");return{text:`${r}\u2026[truncated ${s} bytes]`,truncated:!0}}var un=64*1024,cn=new TextDecoder("utf-8",{fatal:!0});function ce(e){if(e.byteLength<=un)try{let t=cn.decode(e);try{return JSON.parse(t)}catch{return t}}catch{}return`[binary ${e.byteLength} bytes]`}function pn(e){return typeof e.pipe=="function"||typeof e.getReader=="function"||typeof e.on=="function"}var de={chars:1/0,items:1/0},U=64,dn=16,fn=1024*1024;function ln(e,t){let n=t,r=e.charCodeAt(n-1);return r>=55296&&r<=56319&&n--,`${e.slice(0,n)}\u2026[+${e.length-n} chars]`}var mn=1024*1024;function gn(e,t,n){if(t?.isBase64Encoded===!0||e.length>mn||!/^\s*[[{]/.test(e))return e;let r;try{r=JSON.parse(e)}catch{return e}let s=It(r,n,de);try{return s===JSON.stringify(r)?e:s}catch{return s}}function It(e,t,n,r){let s=new WeakSet;try{return JSON.stringify(e,function(o,i){if(o!==""&&t(o,i))return C;o==="body"&&typeof i=="string"&&(i=gn(i,this,t));let a=o===""?e:this[o];if(a!==null&&typeof a=="object"){if(a instanceof Uint8Array)return ce(a);if(a instanceof ArrayBuffer)return ce(new Uint8Array(a));if(a instanceof Error)return{name:a.name,message:a.message};if(s.has(a))return"[circular]";if(s.add(a),Array.isArray(a)){if(a.length>n.items)return[...a.slice(0,n.items),`\u2026[+${a.length-n.items} items]`]}else if(!(a instanceof Date)&&pn(a))return"[stream]"}if(typeof i=="string"&&i.length>U&&(r?.push(i.length),i.length>n.chars))return ln(i,n.chars);if(typeof i=="bigint")return i.toString();if(!(typeof i=="function"||typeof i=="symbol"))return i})??""}catch(o){return JSON.stringify(`[unserializable: ${o?.message}]`)}}function hn(e,t){let n=e.sort((s,o)=>o-s),r=0;for(let s=0;s<n.length;s++){r+=n[s];let o=Math.floor((r-t)/(s+1))-dn;if(o>=(n[s+1]??U))return o}return U}function H(e,t,n){if(e===void 0)return{text:"",truncated:!1};let r=[],s=It(e,n,de,r),o=s.charCodeAt(0);if(s.length<=t/3||o!==123&&o!==91)return _(s,t);let i=Buffer.byteLength(s,"utf8");if(i<=t)return{text:s,truncated:!1};if(i>fn)return _(s,t);let a=Math.ceil((i-t)*1.05)+64,c=hn(r,a),d=s;for(let f of[{chars:c,items:1/0},{chars:Math.min(c,4*U),items:20},{chars:U,items:5}]){d=It(e,n,f);let l=Buffer.byteLength(d,"utf8");if(l<=t)return{text:`${d}\u2026[truncated ${i-l} bytes]`,truncated:!0}}let u=_(d,t),p=u.text.slice(0,u.text.lastIndexOf("\u2026[truncated "));return{text:`${p}\u2026[truncated ${i-Buffer.byteLength(p,"utf8")} bytes]`,truncated:!0}}function fe(e,t,n,r){if(((t??"").includes("json")||/^\s*[[{]/.test(e))&&e.length<=1024*1024)try{return H(JSON.parse(e),n,r)}catch{}return _(Mt(e,r),n)}function yn(e){return e==="true"||e==="false"?e==="true":/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(e)?Number(e):e}function Mt(e,t){return e.replace(/"([^"\\]{1,100})"(\s*:\s*)("(?:[^"\\]|\\.)*"?|[^,}\]\s]+)/g,(n,r,s,o)=>t(r,yn(o))?`"${r}"${s}"${C}"`:n).replace(/(^|&)([^=&\s"{}]{1,100})=([^&]*)/g,(n,r,s)=>t(s)?`${r}${s}=${encodeURIComponent(C)}`:n)}function Ct(e,t){let n={};if(e)for(let[r,s]of Object.entries(e))s!==void 0&&(n[r.toLowerCase()]=t(r)?C:Array.isArray(s)?s.join(", "):String(s));return JSON.stringify(n)}function le(e,t){let n=e.indexOf("?");if(n===-1)return e;let r=e.indexOf("#",n),o=e.slice(n+1,r===-1?void 0:r).split("&").map(i=>{let a=i.indexOf("="),c=a===-1?i:i.slice(0,a),d=c;try{d=decodeURIComponent(c)}catch{}return a!==-1&&t(d)?`${c}=${encodeURIComponent(C)}`:i});return`${e.slice(0,n)}?${o.join("&")}`}var rt=Symbol.for("ivy.skip-http"),E=class{constructor(t){this.limit=t}limit;chunks=[];bytes=0;total=0;add(t,n){if(t==null||typeof t=="function")return;let r;if(typeof t=="string")r=Buffer.from(t,n&&Buffer.isEncoding(n)?n:"utf8");else if(t instanceof Uint8Array)r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else return;if(this.total+=r.length,this.bytes<this.limit){let s=r.length+this.bytes>this.limit?r.subarray(0,this.limit-this.bytes):r;this.chunks.push(Buffer.from(s)),this.bytes+=s.length}}text(){return Buffer.concat(this.chunks).toString("utf8")}},bn=/json|text|xml|x-www-form-urlencoded|graphql|javascript/i;function nt(e){return e==null||e===""||bn.test(String(e))}function R(e,t){if(!e)return;let n=e[t]??e[t.toLowerCase()];if(n!==void 0)return Array.isArray(n)?n.join(", "):String(n);let r=t.toLowerCase();for(let s in e)if(s.toLowerCase()===r)return String(e[s])}var me;function st(e,t){let n=e.host.toLowerCase(),r=e.port??(e.protocol==="https:"?443:80),s=`${n}:${r}`;if(me??=(process.env.AWS_LAMBDA_RUNTIME_API??"127.0.0.1:9001").toLowerCase(),s===me||(n==="127.0.0.1"||n==="localhost")&&r===t.extensionPort||n==="sandbox.localdomain"||n==="sandbox")return!0;if(t.endpoint)try{let o=new URL(t.endpoint),i=o.port?Number(o.port):o.protocol==="https:"?443:80;if(o.hostname.toLowerCase()===n&&i===r)return!0}catch{}return!1}function Sn(e){let t=e.protocol==="https:"?443:80,n=e.port&&e.port!==t?`:${e.port}`:"",r=e.host.includes(":")&&!e.host.startsWith("[")?`[${e.host}]`:e.host;return`${e.protocol}//${r}${n}${e.path||"/"}`}function ot(e,t){let n=e.startChild(`${t.method} ${t.host}`);if(!n)return;n.attributes["http.request.method"]=t.method,n.attributes["url.full"]=le(Sn(t),e.isSecret),n.attributes["server.address"]=t.host,n.attributes["server.port"]=t.port??(t.protocol==="https:"?443:80);let r=oe(t.host,t.path);return r&&(n.name=`${B}.${r.operation}`,n.attributes["rpc.system"]="aws-api",n.attributes["rpc.service"]=B,n.attributes["rpc.method"]=r.operation,Object.assign(n.attributes,$(r.modelId,void 0))),n}function it(e,t){e.attributes["http.response.status_code"]=t,t>=400&&(e.status={code:y.ERROR,message:`HTTP ${t}`})}function L(e,t){e.endMs===void 0&&(T(e,t,m()),e.endMs=m())}function at(e,t,n){t.finalize=()=>{let r=n.requestHeaders?.();t.attributes["ivy.http.request.headers"]=Ct(r,e.isSecret),n.responseHeaders&&(t.attributes["ivy.http.response.headers"]=Ct(n.responseHeaders,e.isSecret));let s=R(r,"content-type"),o=R(n.responseHeaders,"content-type"),i=n.requestBody&&n.requestBody.total>0&&nt(s)?n.requestBody.text():void 0,a=n.responseBodyText??(n.responseBody&&n.responseBody.total>0&&nt(o)?n.responseBody.text():void 0);i!==void 0&&t.payloads.push({key:"ivy.payload.request",value:i,rawContentType:s??""}),a!==void 0&&t.payloads.push({key:"ivy.payload.response",value:a,rawContentType:o??""}),kn(t,r,n.responseHeaders,i,a)}}function kn(e,t,n,r,s){let o=Qt(R(t,"authorization"));if(e.attributes["rpc.service"]===B){o&&(e.attributes["cloud.region"]=o.region);let p=R(n,"x-amzn-requestid");p&&(e.attributes["aws.request_id"]=p),Object.assign(e.attributes,$(e.attributes["gen_ai.request.model"],M(r))),Object.assign(e.attributes,j(M(s),n));return}if(!o)return;let i=Jt(o.service),a=Zt(R(t,"x-amz-target"),r);e.attributes["rpc.system"]="aws-api",e.attributes["rpc.service"]=i,e.attributes["cloud.region"]=o.region,a&&(e.attributes["rpc.method"]=a,e.name=`${i}.${a}`);let c=R(n,"x-amzn-requestid")??R(n,"x-amz-request-id");c&&(e.attributes["aws.request_id"]=c);let d=p=>{if(p)try{return JSON.parse(p)}catch{return}},u=d(r);if(!u&&i==="S3"){let p=String(e.attributes["url.full"]??""),f=/^https?:\/\/([^/]+)\/([^?]*)/.exec(p);if(f){let l=f[1],h=/^(.+)\.s3[.-]/.exec(l),S=f[2].split("/");u=h?{Bucket:h[1],Key:f[2]||void 0}:{Bucket:S[0],Key:S.slice(1).join("/")||void 0}}}Object.assign(e.attributes,q(i,u,d(s),o.region))}var Rt=[];function ut(e){if(!Rt.length){let t=process.getBuiltinModule("node:module"),n=t._load;t._load=function(r,...s){let o=n.call(this,r,...s);for(let i of Rt)try{i(r,o)}catch{}return o}}Rt.push(e)}var ge=Symbol.for("ivy.aws-sdk.patched"),be=Symbol.for("ivy.aws-sdk.span"),xn=new Set(["@smithy/core/client","@smithy/smithy-client","@aws-sdk/smithy-client"]);function vn(e){try{let t=e?.region;if(typeof t=="string")return Promise.resolve(t);if(typeof t=="function")return Promise.resolve(t()).then(n=>typeof n=="string"?n:void 0,()=>{})}catch{}return Promise.resolve(void 0)}function wn(e,t){return(n,r)=>async s=>{let o,i="",a;try{if(e.active){i=Gt(r?.clientName)??"AWS";let f=Xt(r?.commandName)??"Unknown";if(o=e.startChild(`${i}.${f}`),o){if(o.attributes["rpc.system"]="aws-api",o.attributes["rpc.service"]=i,o.attributes["rpc.method"]=f,Object.assign(o.attributes,q(i,s?.input,void 0)),i===B&&ne.has(f)){a=f;let l=s?.input,h=At(f)?l:M(l?.body);Object.assign(o.attributes,$(l?.modelId,h))}o.payloads.push({key:"ivy.payload.request",value:s?.input}),r[be]=o}}}catch{o=void 0}if(!o)return n(s);let c=o,d=vn(t?.config),u=f=>{if(!a||!re(a)||!f)return!1;try{let l=a==="ConverseStream"?"stream":"body";return!f[l]||typeof f[l][Symbol.asyncIterator]!="function"?!1:(f[l]=ie(c,f[l]),!0)}catch{return!1}},p=async(f,l,h=!1)=>{try{let S=f?.output;h||(c.endMs=m());let kt=await d;kt&&(c.attributes["cloud.region"]=kt);let Z=S?.$metadata??l?.$metadata;if(Z?.requestId&&(c.attributes["aws.request_id"]=Z.requestId),Z?.httpStatusCode&&(c.attributes["http.response.status_code"]=Z.httpStatusCode),Object.assign(c.attributes,q(i,s?.input,S,kt)),l)T(c,l,c.endMs??m());else if(!h){c.status.code!==y.ERROR&&(c.status={code:y.UNSET});let{$metadata:rr,...Ye}=S??{};if(c.payloads.push({key:"ivy.payload.response",value:Ye}),a){let We=At(a)?S:M(S?.body);Object.assign(c.attributes,j(We,f?.response?.headers))}}}catch{}};try{let f=await n(s);return p(f,void 0,u(f?.output)),f}catch(f){throw p(void 0,f),f}}}var _n=(e,t)=>async n=>{try{let r=n?.request?.headers;t?.[be]&&r&&typeof r=="object"&&Object.defineProperty(r,rt,{value:!0,enumerable:!1,configurable:!0})}catch{}return e(n)},he=new WeakSet;function ye(e,t){let r=t?.Client?.prototype;if(!r||typeof r.send!="function"||r[ge])return;let s=r.send;r.send=function(...o){try{let i=this.middlewareStack;i&&!he.has(i)&&(he.add(i),i.add(wn(e,this),{step:"initialize",priority:"high",name:"ivyTracingMiddleware",override:!0}),i.add(_n,{step:"deserialize",priority:"low",name:"ivyMarkRequestMiddleware",override:!0}))}catch{}return s.apply(this,o)},Object.defineProperty(r,ge,{value:!0})}function Se(e){ut((n,r)=>{xn.has(n)&&ye(e,r)});let t=process.getBuiltinModule("node:module")._cache??{};for(let n of Object.keys(t))/[\\/]@(smithy|aws-sdk)[\\/](core[\\/]dist-cjs[\\/]submodules[\\/]client|smithy-client[\\/]dist-cjs)[\\/]/.test(n)&&ye(e,t[n]?.exports)}var An={log:"info",info:"info",warn:"warn",error:"error",debug:"debug",trace:"debug"};function ke(e){let{format:t}=process.getBuiltinModule("node:util");for(let[n,r]of Object.entries(An)){let s=console[n];typeof s=="function"&&(console[n]=function(...o){if(e.active)try{e.addLog(r,t(...o))}catch{}return s.apply(this,o)})}}var Tn=1024*1024;function Et(e){let t={};if(!e)return t;if(typeof e.forEach=="function"&&!Array.isArray(e))e.forEach((n,r)=>t[r]=n);else if(Array.isArray(e))for(let[n,r]of e)t[String(n).toLowerCase()]=r;else if(typeof e=="object")for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}function In(e,t){let n=typeof Request<"u"&&e instanceof Request,r=new URL(n?e.url:String(e instanceof URL?e.href:e)),s=String(t?.method??(n?e.method:"GET")).toUpperCase(),o={...n?Et(e.headers):{},...Et(t?.headers)};return{info:{method:s,protocol:r.protocol,host:r.hostname.replace(/^\[|\]$/g,""),port:r.port?Number(r.port):void 0,path:r.pathname+r.search},headers:o}}function xe(e){let t=globalThis.fetch;if(typeof t!="function")return;let n=function(r,s){if(!e.active)return t.call(this,r,s);let o,i;try{let{info:c,headers:d}=In(r,s);if(!st(c,e.config)&&(o=ot(e,c),o)){i={requestHeaders:()=>d};let u=s?.body;(typeof u=="string"||u instanceof URLSearchParams||u instanceof Uint8Array)&&(i.requestBody=new E(Math.max(e.config.maxPayloadBytes*4,64*1024)),i.requestBody.add(u instanceof URLSearchParams?u.toString():u),u instanceof URLSearchParams&&!d["content-type"]&&(d["content-type"]="application/x-www-form-urlencoded")),at(e,o,i)}}catch{o=void 0}let a=t.call(this,r,s);if(o&&i){let c=o,d=i;a.then(u=>{try{it(c,u.status),d.responseHeaders=Et(u.headers);let p=u.headers.get("content-type"),f=Number(u.headers.get("content-length")??NaN);if(!(u.body&&nt(p)&&!(f>Tn))){c.endMs=m();return}u.clone().text().then(h=>{d.responseBodyText=h,c.endMs??=m()},()=>{c.endMs??=m()})}catch{c.endMs??=m()}},u=>L(c,u))}return a};Object.defineProperty(n,"name",{value:"fetch"}),globalThis.fetch=n}function ve(e){let t=process.moduleLoadList;return Array.isArray(t)?t.includes(`NativeModule ${e}`):!0}var Mn=Symbol.for("ivy.original");function we(e,t){return Object.defineProperty(e,Mn,{value:t}),e}function Cn(e,t){let n,r={},[s,o]=e;typeof s=="string"?n=new URL(s):s instanceof URL?n=s:s&&typeof s=="object"&&(r=s),n&&o&&typeof o=="object"&&typeof o!="function"&&(r=o);let i=r.protocol??n?.protocol??t,a=r.hostname??(r.host?String(r.host).replace(/:\d+$/,""):void 0)??n?.hostname??"localhost";a.startsWith("[")&&a.endsWith("]")&&(a=a.slice(1,-1));let c=r.port??(n?.port||void 0),d=c!=null&&c!==""?Number(c):void 0,u=r.path??(n?n.pathname+n.search:"/");return{info:{method:String(r.method??"GET").toUpperCase(),protocol:i,host:a,port:d,path:u},headers:r.headers}}function Rn(e,t,n){let r=ot(e,n);if(!r)return;let s=Math.max(e.config.maxPayloadBytes*4,64*1024),o={requestHeaders:()=>t.getHeaders(),requestBody:new E(s)};at(e,r,o);let i=t.write;t.write=function(u,...p){try{o.requestBody.add(u,typeof p[0]=="string"?p[0]:void 0)}catch{}return i.call(this,u,...p)};let a=t.end;t.end=function(u,...p){try{typeof u!="function"&&o.requestBody.add(u,typeof p[0]=="string"?p[0]:void 0)}catch{}return a.call(this,u,...p)};let c=t.emit;t.emit=function(u,...p){try{u==="response"?d(p[0]):u==="error"?L(r,p[0]):u==="close"&&r.endMs===void 0&&!o.responseHeaders&&L(r,new Error("socket closed before response"))}catch{}return c.call(this,u,...p)};function d(u){it(r,u.statusCode??0),o.responseHeaders=u.headers,o.responseBody=new E(s);let p=u.emit;u.emit=function(f,...l){try{f==="data"?o.responseBody.add(l[0],u.readableEncoding??void 0):f==="end"&&r.endMs===void 0?r.endMs=m():f==="error"&&L(r,l[0])}catch{}return p.call(this,f,...l)}}}function _e(e,t,n){return we(function(...s){if(!e.active)return t.apply(this,s);let o;try{o=Cn(s,n),o&&(o.headers?.[rt]||st(o.info,e.config))&&(o=void 0)}catch{o=void 0}let i=t.apply(this,s);if(o)try{Rn(e,i,o.info)}catch{}return i},t)}var Ae=Symbol.for("ivy.http.patched");function En(e,t){let n=process.getBuiltinModule(`node:${t}`);n[Ae]||(n.request=_e(e,n.request,`${t}:`),n.get=_e(e,n.get,`${t}:`),Object.defineProperty(n,Ae,{value:!0}),process.getBuiltinModule("node:module").syncBuiltinESMExports())}function Te(e){let t={http:!1,https:!1},n=(s,o=!1)=>{t[s]||!(o||ve(s))||(t[s]=!0,En(e,s))};ut(s=>{let o=s.startsWith("node:")?s.slice(5):s;(o==="http"||o==="https")&&n(o,!0)});let r=()=>{n("http"),n("https")};return r(),r}var F=Symbol.for("opentelemetry.js.api.1"),V=Symbol.for("OpenTelemetry Context Key SPAN"),D={UNSET:0,OK:1,ERROR:2};var Ot=class e{values;constructor(t){this.values=t?new Map(t):new Map}getValue(t){return this.values.get(t)}setValue(t,n){let r=new e(this.values);return r.values.set(t,n),r}deleteValue(t){let n=new e(this.values);return n.values.delete(t),n}},z=new Ot,ct=class{constructor(t=()=>z){this.base=t}base;storage;active(){return this.storage?.getStore()??this.base()}with(t,n,r,...s){this.storage??=new(process.getBuiltinModule("node:async_hooks")).AsyncLocalStorage;let o=r==null?n:n.bind(r);return this.storage.run(t,o,...s)}bind(t,n){if(typeof n!="function")return n;let r=this,s=n;return function(...o){return r.with(t,()=>s.apply(this,o))}}enable(){return this}disable(){return this.storage?.disable(),this.storage=void 0,this}};function Nt(){return globalThis[F]?.context}function Y(){return Nt()?.active()??z}function W(e){if(e!=null){if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return e.filter(t=>t!=null)}}function G(e,t){if(t)for(let n in t){let r=W(t[n]);r!==void 0&&(e[n]=r)}}function Ie(e,t,n){let r=e.charCodeAt(0);if((r===123||r===91)&&e.length<=1024*1024)try{return H(JSON.parse(e),t,n)}catch{return _(Mt(e,n),t)}return _(e,t)}var On=e=>e.slice(e.lastIndexOf(".")+1);function pt(e,t,n){let r=Me(e.attributes,t,n);for(let s of e.events)r=Me(s.attributes,t,n)||r;return r}function Me(e,t,n){let r=!1;for(let s in e){let o=e[s],i=On(s);if(Array.isArray(o)?o.some(a=>n(i,a)):n(i,o)){e[s]=C;continue}if(typeof o=="string"){let a=Ie(o,t,n);e[s]=a.text,r||=a.truncated}else if(Array.isArray(o)&&o.some(a=>typeof a=="string")){let a=[],c=t*4;for(let d=0;d<o.length;d++){let u=o[d];if(typeof u!="string"){a.push(u);continue}if(c<=0){a.push(`\u2026[truncated ${o.length-d} items]`),r=!0;break}let p=Ie(u,Math.min(t,c),n);c-=p.text.length,r||=p.truncated,a.push(p.text)}e[s]=a}}return r}function X(e){if(e!=null){if(Array.isArray(e))return e[0]*1e3+e[1]/1e6;if(e instanceof Date)return e.getTime();if(typeof e=="number")return e<performance.timeOrigin?performance.timeOrigin+e:e}}function Bt(e,t,n){let r;t instanceof Date||Array.isArray(t)||typeof t=="number"?n=t:r=t;let s={};return G(s,r),{name:e,timeMs:X(n)??m(),attributes:s}}function Lt(e,t){let n=e,r={};if(typeof n=="string")r["exception.message"]=n;else if(n&&typeof n=="object"){let s=n.name??n.code;s!==void 0&&(r["exception.type"]=String(s)),n.message!==void 0&&(r["exception.message"]=String(n.message));let o=typeof n.stack=="string"?wt(n.stack):void 0;o&&(r["exception.stacktrace"]=o)}return{name:"exception",timeMs:X(t)??m(),attributes:r}}var O=class{constructor(t,n,r){this.ivy=t;this.invocation=n;t.finalize=s=>{pt(s,r.maxBytes,r.isSecret)&&(s.attributes["ivy.payload.truncated"]=!0)}}ivy;invocation;ended=!1;spanContext(){return{traceId:this.ivy.traceId,spanId:this.ivy.spanId,traceFlags:1}}setAttribute(t,n){if(!this.ended){let r=W(n);r!==void 0&&(this.ivy.attributes[t]=r)}return this}setAttributes(t){return this.ended||G(this.ivy.attributes,t),this}addEvent(t,n,r){return this.ended||this.ivy.events.push(Bt(t,n,r)),this}addLink(){return this}addLinks(){return this}setStatus(t){return this.ended?this:this.ivy.status.code===D.OK?this:t.code===D.UNSET?this:(this.ivy.status=t.message?{code:t.code,message:t.message}:{code:t.code},this)}updateName(t){return this.ended||(this.ivy.name=t),this}recordException(t,n){this.ended||this.ivy.events.push(Lt(t,n))}end(t){if(!this.ended&&(this.ended=!0,this.ivy.endMs=Math.max(X(t)??m(),this.ivy.startMs),this.ivy.status.code===y.ERROR&&this.ivy.attributes["error.type"]===void 0)){let n=this.ivy.events.find(r=>r.name==="exception");this.ivy.attributes["error.type"]=String(n?.attributes["exception.type"]??"Error")}}isRecording(){return!this.ended}},Nn={traceId:"00000000000000000000000000000000",spanId:"0000000000000000",traceFlags:0},J=class{constructor(t=Nn){this.context=t}context;spanContext(){return this.context}setAttribute(){return this}setAttributes(){return this}addEvent(){return this}addLink(){return this}addLinks(){return this}setStatus(){return this}updateName(){return this}recordException(){}end(){}isRecording(){return!1}};var Bn=/^(ivy|faas|cloud|aws|http|url|messaging|error|exception|otel)\./,Ln=128,Vn=128,Pn=e=>Bn.test(e),dt=class{constructor(t,n,r){this.invocation=t;this.tracer=n;this.caps=r}invocation;tracer;caps;keys=new Set;events=[];hooked=!1;get root(){let t=this.invocation;return!t.done&&this.tracer.active===t?t.root:void 0}hook(t){if(this.hooked)return;this.hooked=!0;let n=t.finalize;t.finalize=r=>{n?.(r);let s={attributes:{},events:this.events};for(let o of this.keys)o in r.attributes&&(s.attributes[o]=r.attributes[o]);pt(s,this.caps.maxBytes,this.caps.isSecret)&&(r.attributes["ivy.payload.truncated"]=!0),Object.assign(r.attributes,s.attributes)}}spanContext(){let t=this.invocation.root;return{traceId:t.traceId,spanId:t.spanId,traceFlags:1}}setAttribute(t,n){let r=this.root;if(!r||Pn(t))return this;if(!this.keys.has(t)&&this.keys.size>=Ln)return this;let s=W(n);return s===void 0?this:(this.hook(r),this.keys.add(t),r.attributes[t]=s,this)}setAttributes(t){for(let n in t)this.setAttribute(n,t[n]);return this}addEvent(t,n,r){return this.pushEvent(()=>Bt(t,n,r)),this}recordException(t,n){this.pushEvent(()=>Lt(t,n))}pushEvent(t){let n=this.root;if(!n||this.events.length>=Vn)return;this.hook(n);let r=t();this.events.push(r),n.events.push(r)}setStatus(t){let n=this.root;return!n||t.code!==D.ERROR||n.status.code===y.ERROR?this:(n.status=t.message?{code:y.ERROR,message:t.message}:{code:y.ERROR},this)}addLink(){return this}addLinks(){return this}updateName(){return this}end(){}isRecording(){return this.root!==void 0}};var Kn=e=>(e??0)+1,Vt=class{constructor(t,n,r,s,o){this.ivy=t;this.startChild=n;this.caps=r;this.scope=s;this.fallbackContext=o}ivy;startChild;caps;scope;fallbackContext;startSpan(t,n={},r=Y()){let s=this.ivy.active;if(!s||s.done)return new J;let o=n.root?void 0:r?.getValue?.(V),i=this.startChild(t,Kn(n.kind));if(!i)return new J;o instanceof O&&o.invocation===s&&(i.parentSpanId=o.ivy.spanId);let a=X(n.startTime);return a!==void 0&&(i.startMs=a),i.attributes["otel.scope.name"]=this.scope,G(i.attributes,n.attributes),new O(i,s,this.caps)}startActiveSpan(t,...n){let r=n.pop(),[s,o]=n,i=o??Y(),a=this.startSpan(t,s,i);return(Nt()??this.fallbackContext).with(i.setValue(V,a),r,void 0,a)}},ft=class{constructor(t,n,r,s){this.ivy=t;this.startChild=n;this.caps=r;this.fallbackContext=s}ivy;startChild;caps;fallbackContext;tracers=new Map;getTracer(t="unknown"){let n=this.tracers.get(t);return n||(n=new Vt(this.ivy,this.startChild,this.caps,t,this.fallbackContext),this.tracers.set(t,n)),n}};var qn="1.10.0",Ce="1.9.0",Ee=()=>process.getBuiltinModule("node:fs"),Oe=(...e)=>process.getBuiltinModule("node:path").join(...e),Re=e=>e.split(".").map(t=>parseInt(t,10)||0),$n=(e,t)=>{let[n,r]=[Re(e),Re(t)];return n[0]!==r[0]?n[0]>r[0]:n[1]!==r[1]?n[1]>r[1]:n[2]>r[2]};function Ne(e){try{let t=JSON.parse(Ee().readFileSync(Oe(e,"node_modules/@opentelemetry/api/package.json"),"utf8"));if(typeof t.version=="string"&&/^1\.\d+\.\d+$/.test(t.version))return $n(Ce,t.version)?Ce:t.version}catch{}return qn}function Be(e){return Ee().existsSync(Oe(e,"node_modules/@opentelemetry/sdk-trace-base"))}function jn(){return globalThis[F]}function Le(e,t,n){let r=globalThis,s=jn();return s?.trace?!1:(s||(s=Object.defineProperty({},"version",{value:n,enumerable:!0,writable:!1,configurable:!1}),r[F]=s),s.trace=e,s.context??=t,!0)}var Un=e=>!!e&&["0","false","no","off"].includes(e.toLowerCase());function Ve(e,t=process.env){if(!Un(t.IVY_CAPTURE_OTEL))try{let n=t.LAMBDA_TASK_ROOT??process.cwd(),r=e.startChild.bind(e),s={maxBytes:e.config.maxPayloadBytes,isSecret:e.isSecret},o=new WeakMap,i=()=>{let p=e.active;if(!p||p.done)return z;let f=o.get(p);return f||(f=z.setValue(V,new dt(p,e,s)),o.set(p,f)),f},a=new ct(i),c=new ft(e,r,s,a),d=()=>{Le(c,a,Ne(n))&&(e.startChild=(p,f)=>{let l=r(p,f);if(l){let h=Y().getValue(V);h instanceof O&&h.invocation===e.active&&(l.parentSpanId=h.ivy.spanId)}return l})};if(!Be(n)){d();return}let u=e.startInvocation;e.startInvocation=(...p)=>{e.startInvocation=u;try{d()}catch{}return u.apply(e,p)}}catch{}}var Hn=/^(ivy\.payload\.|ivy\.http\.(request|response)\.headers$|ai\.prompt|ai\.response\.(text|object|toolCalls|reasoning)|ai\.toolCall\.(args|result)$|gen_ai\.(input|output)\.messages$|gen_ai\.system_instructions$|gen_ai\.tool\.(definitions|call\.arguments|call\.result)$)/,lt=e=>Hn.test(e),A=e=>Buffer.byteLength(e,"utf8"),P=class{constructor(t){this.remaining=t}remaining;trimmedBytes=0;trimmedPayloads=0;take(t){return t<=this.remaining?(this.remaining-=t,!0):(this.trimmedBytes+=t,this.trimmedPayloads++,!1)}};function Fn(e,t,n=A(JSON.stringify(e))){if(n<=t)return 0;let r=e.attributes.filter(i=>lt(i.key)&&"stringValue"in i.value).map(i=>({key:i.key,bytes:A(i.value.stringValue)})).sort((i,a)=>a.bytes-i.bytes),s=0,o=new Set;for(let i of r){if(n-s<=t)break;o.add(i.key),s+=i.bytes}return o.size?(e.attributes=e.attributes.filter(i=>!o.has(i.key)&&i.key!=="ivy.payload.trimmed"),e.attributes.push({key:"ivy.payload.trimmed",value:{boolValue:!0}}),s):0}function Pe(e,t){let n=[],r=[],s=0;for(let o of e){let i=A(JSON.stringify(o));i>t.bytes&&(Fn(o,t.bytes,i),i=A(JSON.stringify(o))),r.length&&(r.length>=t.spans||s+i>t.bytes)&&(n.push(r),r=[],s=0),r.push(o),s+=i+1}return r.length&&n.push(r),n}function Ke(e){return typeof e=="string"?{stringValue:e}:typeof e=="boolean"?{boolValue:e}:typeof e=="number"?Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(t=>Ke(t))}}:{stringValue:String(e)}}function mt(e){let t=[];for(let n in e){let r=e[n];r==null||typeof r=="number"&&!Number.isFinite(r)||t.push({key:n,value:Ke(r)})}return t}function Pt(e){return(BigInt(Math.round(e*1e3))*1000n).toString()}function Kt(e){let t=e.endMs??e.startMs,n={traceId:e.traceId,spanId:e.spanId,name:e.name,kind:e.kind,startTimeUnixNano:Pt(e.startMs),endTimeUnixNano:Pt(Math.max(t,e.startMs)),attributes:mt(e.attributes),events:e.events.map(r=>({timeUnixNano:Pt(r.timeMs),name:r.name,attributes:mt(r.attributes)})),status:e.status.message?{code:e.status.code,message:e.status.message}:{code:e.status.code}};return e.parentSpanId&&(n.parentSpanId=e.parentSpanId),n}var gt=(e,t)=>typeof e=="string"&&e&&e.split(t).pop()||void 0;function w(e,t,n={}){let r=t==="http"?N.SERVER:t==="pubsub"||t==="datasource"?N.CONSUMER:N.INTERNAL;return{source:e,trigger:t,kind:r,attributes:n}}function Dn(e){return typeof e=="string"?e.split("?")[0]:void 0}function qt(e,t,n,r){let s={};typeof t=="string"&&(s["http.request.method"]=t.toUpperCase());let o=Dn(n);return o&&(s["url.path"]=o),typeof r=="string"&&r&&(s["http.route"]=r),w(e,"http",s)}function zn(e){let t=e[0]??{},n=t.eventSource??t.EventSource,r=e.length;switch(n){case"aws:sqs":{let s={"messaging.system":"aws_sqs","messaging.batch.message_count":r},o=gt(t.eventSourceARN,":");return o&&(s["messaging.destination.name"]=o),r===1&&t.messageId&&(s["messaging.message.id"]=String(t.messageId)),w("aws:sqs","pubsub",s)}case"aws:sns":{let s={"messaging.system":"aws_sns","messaging.batch.message_count":r},o=gt(t.Sns?.TopicArn,":");return o&&(s["messaging.destination.name"]=o),r===1&&t.Sns?.MessageId&&(s["messaging.message.id"]=String(t.Sns.MessageId)),w("aws:sns","pubsub",s)}case"aws:s3":{let s={};return t.s3?.bucket?.name&&(s["aws.s3.bucket"]=String(t.s3.bucket.name)),t.s3?.object?.key&&(s["aws.s3.key"]=String(t.s3.object.key)),t.eventName&&(s["ivy.trigger.event_name"]=String(t.eventName)),w("aws:s3","datasource",s)}case"aws:dynamodb":{let s={"messaging.batch.message_count":r},o=typeof t.eventSourceARN=="string"?/:table\/([^/]+)/.exec(t.eventSourceARN):null;return o&&(s["aws.dynamodb.table_names"]=[o[1]]),w("aws:dynamodb","datasource",s)}case"aws:kinesis":{let s={"messaging.batch.message_count":r},o=gt(t.eventSourceARN,"/");return o&&t.eventSourceARN?.includes(":stream/")&&(s["messaging.destination.name"]=o),w("aws:kinesis","pubsub",s)}default:return w("unknown","other")}}function qe(e){if(!e||typeof e!="object"||Array.isArray(e))return w("aws:lambda","other");let t=e,n=t.requestContext;if(Array.isArray(t.Records)&&t.Records.length>0)return zn(t.Records);if(n&&typeof n=="object"){if(n.elb)return qt("aws:alb",t.httpMethod,t.path,void 0);if(t.version==="2.0"&&n.http){let r=typeof n.domainName=="string"&&n.domainName.includes(".lambda-url."),s=typeof t.routeKey=="string"&&t.routeKey!=="$default"?t.routeKey:void 0,o=s?.includes(" ")?s.slice(s.indexOf(" ")+1):s;return qt(r?"aws:function-url":"aws:apigatewayv2",n.http.method,t.rawPath??n.http.path,r?void 0:o)}if(t.httpMethod)return qt("aws:apigateway",t.httpMethod,t.path,t.resource)}if(typeof t.source=="string"&&typeof t["detail-type"]=="string"){if(t.source==="aws.events"&&t["detail-type"]==="Scheduled Event"){let r={},s=gt(t.resources?.[0],"/");return s&&(r["ivy.trigger.rule"]=s),w("aws:scheduled","timer",r)}return w("aws:eventbridge","pubsub",{"aws.eventbridge.source":t.source,"aws.eventbridge.detail_types":[t["detail-type"]]})}return w("aws:lambda","other")}function $e(e,t){if(t&&typeof t=="object"&&"statusCode"in t){let n=Number(t.statusCode);return Number.isInteger(n)?n:void 0}if(e==="aws:apigatewayv2"||e==="aws:function-url")return 200}var b=e=>typeof e=="string"&&e?e:Array.isArray(e)&&e.length?e.join(","):void 0,I=e=>typeof e=="number"&&Number.isFinite(e)?e:typeof e=="string"&&/^\d+$/.test(e)?Number(e):void 0,Yn=/^(\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{12,}|(?=[^/]*\d)[A-Za-z0-9_-]{16,})$/i;function Wn(e){return(e.split("?")[0].split("#")[0]||"/").split("/").map(n=>n&&Yn.test(n)?"{id}":n).join("/")}function Ue(e){let t=b(e);return t&&/^[a-z]+:\/\/[^/]+(\/[^?#]*)?/i.exec(t)?.[1]||"/"}var Gn=/(^|\.)(api\.openai\.com|api\.anthropic\.com|generativelanguage\.googleapis\.com|api\.mistral\.ai|api\.groq\.com|api\.cohere\.(ai|com)|api\.deepseek\.com|api\.together\.xyz|api\.fireworks\.ai|openrouter\.ai|api\.x\.ai)$|^bedrock-runtime\.[a-z0-9-]+\.amazonaws\.com$|\.openai\.azure\.com$/i,Jn=/\/(chat\/completions|completions|messages|responses|embeddings|generateContent|streamGenerateContent)$|\/model\/[^/]+\/(converse|converse-stream|invoke|invoke-with-response-stream)$/;function He(e,t){if(e&&Gn.test(e))return!0;let n=t?Ue(t).replace(/:[A-Za-z]+$/,r=>`/${r.slice(1)}`):"";return Jn.test(n)}function Xn(e){let t=b(e["gen_ai.request.model"])??b(e["ai.model.id"])??b(e["gen_ai.response.model"]);if(!t)return;let n=b(e["gen_ai.provider.name"])??b(e["gen_ai.system"])??b(e["ai.model.provider"])??"";return`llm ${b(e["ai.operationId"])??b(e["gen_ai.operation.name"])??""} ${n} ${t}`}function ht(e){let t=e.attributes,n=Xn(t);if(n)return n;if(t["rpc.system"]==="aws-api"){let s=b(t["aws.dynamodb.table_names"])??b(t["aws.s3.bucket"])??b(t["messaging.destination.name"])??b(t["faas.invoked_name"])??b(t["aws.eventbridge.bus"])??"";return`${b(t["rpc.service"])}.${b(t["rpc.method"])} ${s}`.trim()}let r=b(t["http.request.method"]);return r?`${r} ${b(t["server.address"])??""} ${Wn(Ue(t["url.full"]))}`:e.name}var Fe=["rpc.system","rpc.service","rpc.method","cloud.region","aws.dynamodb.table_names","aws.s3.bucket","messaging.system","messaging.destination.name","faas.invoked_name","faas.invoked_region","aws.eventbridge.bus","http.request.method","server.address","server.port","otel.scope.name","gen_ai.provider.name","gen_ai.system","gen_ai.operation.name","gen_ai.request.model","gen_ai.response.model","ai.model.id","ai.model.provider","ai.operationId"];function $t(e){return{input:I(e["gen_ai.usage.input_tokens"])??I(e["ai.usage.inputTokens"])??I(e["ai.usage.promptTokens"])??I(e["gen_ai.usage.prompt_tokens"]),output:I(e["gen_ai.usage.output_tokens"])??I(e["ai.usage.outputTokens"])??I(e["ai.usage.completionTokens"])??I(e["gen_ai.usage.completion_tokens"])}}var je=(e,t)=>{let n;for(let r of e.matchAll(t))n=Number(r[1]);return n};function De(e){return{input:je(e,/"(?:prompt_tokens|input_tokens|inputTokens|promptTokenCount)"\s*:\s*(\d+)/g),output:je(e,/"(?:completion_tokens|output_tokens|outputTokens|candidatesTokenCount)"\s*:\s*(\d+)/g)}}var yt=class{constructor(t,n){this.opts=t;this.rootSpanId=n}opts;rootSpanId;groups=new Map;counted=new WeakSet;keptFirst=new WeakSet;summaries=new WeakSet;collapsedCalls=0;dropped=0;dropReasons=new Set;isSummary(t){return this.summaries.has(t)}get softLimit(){return this.opts.maxSpans+Math.max(100,Math.floor(this.opts.maxSpans/4))}drop(t,n){this.dropped+=t,this.dropReasons.add(n)}reduce(t,n){let r=this.opts.threshold>0?this.collapse(t,n):t;return r.length>this.opts.maxSpans&&(r=this.limit(r,n)),r}collapse(t,n){let r=Qn(t),s=new Map,o=d=>{let u=s.get(d);return u===void 0&&(u=(n||d.endMs!==void 0)&&d.status.code!==y.ERROR&&(r.get(d.spanId)??[]).every(o),s.set(d,u)),u},i=new Map;for(let d of t){if(this.summaries.has(d))continue;let p=`${d.parentSpanId??this.rootSpanId}\0${ht(d)}`,f=d.status.code===y.ERROR;if(!this.counted.has(d)&&(f||d.endMs!==void 0||n)){this.counted.add(d);let l=this.group(p,d);l.calls++}if(!f&&!this.keptFirst.has(d)&&o(d)){let l=i.get(p);l?l.push(d):i.set(p,[d])}}let a=new Set,c=[];for(let[d,u]of i){let p=this.groups.get(d);if(p.calls<=this.opts.threshold)continue;u.sort((h,S)=>h.startMs-S.startMs);let f=Math.min(u.length,Math.max(0,this.opts.keepFirst-p.firstKept));for(let h of u.splice(0,f))this.keptFirst.add(h);p.firstKept+=f,u.sort((h,S)=>Q(S)-Q(h));let l=u.slice(this.opts.keepSlowest);if(l.length){for(let h of l)this.fold(p,h,r,a);p.summary||(p.summary=this.summarySpan(l[0],p),this.summaries.add(p.summary),c.push(p.summary)),this.updateSummary(p)}}return!a.size&&!c.length?t:[...t.filter(d=>!a.has(d)),...c]}group(t,n){let r=this.groups.get(t);return r||(r={signature:ht(n),baseName:n.name,calls:0,firstKept:0,count:0,totalMs:0,maxMs:0,minMs:1/0,start:1/0,end:-1/0,inputTokens:0,outputTokens:0,removedSpans:0},this.groups.set(t,r)),r}fold(t,n,r,s){let o=Q(n);t.count++,t.totalMs+=o,t.maxMs=Math.max(t.maxMs,o),t.minMs=Math.min(t.minMs,o),t.start=Math.min(t.start,n.startMs),t.end=Math.max(t.end,n.endMs??n.startMs);let i=this.tokensOf(n);t.inputTokens+=i.input??0,t.outputTokens+=i.output??0,this.collapsedCalls++;let a=[n];for(;a.length;){let c=a.pop();s.add(c),t.removedSpans++,a.push(...r.get(c.spanId)??[])}}tokensOf(t){let n=$t(t.attributes);if(n.input!==void 0||n.output!==void 0||!He(t.attributes["server.address"],t.attributes["url.full"]))return n;try{t.finalize?.(t),t.finalize=void 0;let r=$t(t.attributes);if(r.input!==void 0||r.output!==void 0)return r;let s=t.payloads.find(o=>o.key==="ivy.payload.response")?.value;return typeof s=="string"?De(s):n}catch{return n}}summarySpan(t,n){let r=K(t.traceId,n.baseName,t.kind,n.start,t.parentSpanId??this.rootSpanId);for(let s of Fe)t.attributes[s]!==void 0&&(r.attributes[s]=t.attributes[s]);return r}updateSummary(t){let n=t.summary;n.name=`${t.baseName} \xD7 ${t.count.toLocaleString("en-US")}`,n.startMs=t.start,n.endMs=t.end,Object.assign(n.attributes,{"ivy.collapsed.count":t.count,"ivy.collapsed.duration_total_ms":jt(t.totalMs),"ivy.collapsed.duration_max_ms":jt(t.maxMs),"ivy.collapsed.duration_min_ms":jt(t.minMs),"ivy.collapsed.kept":t.calls-t.count,"ivy.collapsed.signature":t.signature}),(t.inputTokens||t.outputTokens)&&(n.attributes["ivy.collapsed.input_tokens"]=t.inputTokens,n.attributes["ivy.collapsed.output_tokens"]=t.outputTokens),t.removedSpans>t.count&&(n.attributes["ivy.collapsed.spans"]=t.removedSpans)}finishSummaries(t){let n=new Map;for(let r of t){if(r.status.code!==y.ERROR)continue;let s=`${r.parentSpanId??this.rootSpanId}\0${ht(r)}`;n.set(s,(n.get(s)??0)+1)}for(let[r,s]of this.groups)s.summary&&(s.summary.attributes["ivy.collapsed.errors"]=n.get(r)??0)}limit(t,n){let r=new Map(t.map(u=>[u.spanId,u])),s=new Map,o=u=>{let p=s.get(u);if(p===void 0){let f=u.parentSpanId&&u.parentSpanId!==this.rootSpanId?r.get(u.parentSpanId):void 0;s.set(u,0),p=f?o(f)+1:0,s.set(u,p)}return p},i=new Set,a=u=>{for(let p=u;p&&!i.has(p);p=p.parentSpanId?r.get(p.parentSpanId):void 0)i.add(p)};for(let u of t)(u.status.code===y.ERROR||this.summaries.has(u)||!n&&u.endMs===void 0)&&a(u);let c=t.filter(u=>!i.has(u)).sort((u,p)=>o(u)-o(p)||Q(p)-Q(u));for(let u of c){if(i.size>=this.opts.maxSpans)break;(!u.parentSpanId||u.parentSpanId===this.rootSpanId||i.has(r.get(u.parentSpanId)))&&i.add(u)}let d=t.filter(u=>i.has(u));return d.length<t.length&&this.drop(t.length-d.length,"span limit"),d}};function Qn(e){let t=new Map;for(let n of e){if(!n.parentSpanId)continue;let r=t.get(n.parentSpanId);r?r.push(n):t.set(n.parentSpanId,[n])}return t}var Q=e=>(e.endMs??e.startMs)-e.startMs,jt=e=>Math.round(e*1e3)/1e3;var bt=500,Zn=4*1024,St=class{constructor(t,n,r=()=>{}){this.config=t;this.sink=n;this.log=r;this.isSecret=pe(t.redactKeys)}config;sink;log;current;scope;isSecret;coldStart=!0;resource;onInvocationStart;get active(){return this.scope?this.scope.getStore():this.current}enableConcurrency(){this.scope??=new(process.getBuiltinModule("node:async_hooks")).AsyncLocalStorage}runInvocation(t,n){return this.scope?this.scope.run(t,n):n()}startInvocation(t,n,r=qe(t)){this.onInvocationStart?.(),Dt();let s=m(),o=n.functionName??process.env.AWS_LAMBDA_FUNCTION_NAME??"unknown",i=K(zt(s),o,r.kind,s);n.awsRequestId&&Object.assign(i,Yt(n.awsRequestId,s));let a=n.awsRequestId??i.spanId;Object.assign(i.attributes,r.attributes,{"ivy.invocation":!0,"faas.invocation_id":a,"faas.coldstart":this.coldStart,"faas.trigger":r.trigger,"ivy.trigger.source":r.source}),n.invokedFunctionArn&&(i.attributes["cloud.resource_id"]=n.invokedFunctionArn),i.payloads.push({key:"ivy.payload.request",value:t}),this.coldStart=!1,this.resource||(this.resource=this.buildResource(n));let c=this.config,d=new yt({threshold:c.collapseThreshold,keepFirst:c.collapseKeep,keepSlowest:c.collapseKeepSlowest,maxSpans:c.maxSpans},i.spanId),u={requestId:a,root:i,children:[],trigger:r,event:t,logCount:0,reducer:d,done:!1};this.scope||(this.current=u);let p=n.getRemainingTimeInMillis?.();return typeof p=="number"&&p>this.config.timeoutMarginMs+50&&(u.timer=setTimeout(()=>this.onTimeout(u),p-this.config.timeoutMarginMs),u.timer.unref()),u}startChild(t,n=N.CLIENT){let r=this.active;if(!r||r.done||!this.hasRoom(r))return;let s=K(r.root.traceId,t,n,m(),r.root.spanId);return r.children.push(s),s}addLog(t,n){let r=this.active;!r||r.done||r.logCount++>=bt||r.root.events.push({name:"log",timeMs:m(),attributes:{"log.severity":t,"log.message":_(n,Zn).text}})}adopt(t,n,r,s,o){if(t.done)return;let i=t.openWorkerSpans??=new Map;for(let a of n){if(a.startMs<t.root.startMs)continue;a.traceId=t.root.traceId,(!a.parentSpanId||a.parentSpanId===s)&&(a.parentSpanId=o);let c=i.get(a.spanId);if(c)Object.assign(c,a);else if(this.hasRoom(t))t.children.push(a);else continue;a.endMs===void 0?i.set(a.spanId,c??a):i.delete(a.spanId)}for(let a of r)if(!(a.timeMs<t.root.startMs)){if(t.logCount++>=bt)break;t.root.events.push(a)}}hasRoom(t){return t.children.length<t.reducer.softLimit||(t.children=t.reducer.reduce(t.children,!1),t.children.length<t.reducer.softLimit)?!0:(t.reducer.drop(1,"span limit"),!1)}endInvocation(t,n,r){t.done||(t.done=!0,this.current===t&&(this.current=void 0),t.timer&&clearTimeout(t.timer),this.complete(t.root,t,n,r),setImmediate(()=>this.flush(t,!0)))}complete(t,n,r,s,o){let i=m();if(t.endMs=i,r!=null)T(t,r,i,o);else if(t.payloads.push({key:"ivy.payload.response",value:s}),n.trigger.trigger==="http"){let a=$e(n.trigger.source,s);a!==void 0&&(t.attributes["http.response.status_code"]=a,a>=500&&(t.status={code:y.ERROR,message:`HTTP ${a}`}))}try{t.attributes["ivy.memory_used_mb"]=Math.round(process.memoryUsage.rss()/1048576)}catch{}}onTimeout(t){if(!t.done)try{let n={...t.root,attributes:{...t.root.attributes},events:[...t.root.events],payloads:[...t.root.payloads]},r=new Error(`Task timed out (ivy: flushed ${this.config.timeoutMarginMs}ms before the deadline)`);r.name="Timeout",r.stack=void 0,this.complete(n,t,r,void 0,"Timeout"),this.flush(t,!1,n)}catch(n){this.log(`timeout flush failed: ${n.message}`)}}flush(t,n,r){try{let s=r??t.root,o=s.endMs??m(),i=t.reducer;t.children=i.reduce(t.children,n),n&&i.finishSummaries(t.children);let a=t.children.map(f=>{let l=n?f:{...f,attributes:{...f.attributes}};return l.endMs===void 0&&(l.endMs=o,l.attributes["ivy.incomplete"]=!0),l});i.collapsedCalls&&(s.attributes["ivy.collapsed_calls"]=i.collapsedCalls),i.dropped&&(s.attributes["ivy.dropped_spans"]=i.dropped,s.attributes["ivy.dropped_spans.reason"]=[...i.dropReasons].join(", ")),t.logCount>bt&&(s.attributes["ivy.dropped_logs"]=t.logCount-bt);let c=new P(this.config.maxInvocationPayloadBytes);this.applyPayloads(s,c);let d=new Map;for(let f of tr(a))this.applyPayloads(f,c),d.set(f,Kt(f));c.trimmedPayloads&&(s.attributes["ivy.trimmed_payload_bytes"]=c.trimmedBytes,s.attributes["ivy.trimmed_payloads"]=c.trimmedPayloads);let u=this.resource??[],p=Pe(a.map(f=>d.get(f)),{spans:this.config.exportChunkSpans,bytes:this.config.exportChunkBytes});this.sink({requestId:t.requestId,final:n&&!p.length,resource:u,spans:[Kt(s)]}),p.forEach((f,l)=>this.sink({requestId:t.requestId,final:n&&l===p.length-1,resource:u,spans:f}))}catch(s){this.log(`flush failed: ${s.message}`)}}applyPayloads(t,n){try{t.finalize?.(t)}catch{}t.finalize=void 0;let r=!1;for(let o in t.attributes){let i=t.attributes[o];typeof i=="string"&&lt(o)&&!n.take(A(i))&&(delete t.attributes[o],r=!0)}let s=!1;for(let o of t.payloads){if(n.remaining<=0){n.take(typeof o.value=="string"?Math.min(A(o.value),this.config.maxPayloadBytes):1),r=!0;continue}try{let i=o.rawContentType!==void 0&&typeof o.value=="string"?fe(o.value,o.rawContentType,this.config.maxPayloadBytes,this.isSecret):H(o.value,this.config.maxPayloadBytes,this.isSecret);if(!i.text)continue;n.take(A(i.text))?t.attributes[o.key]=i.text:r=!0,s||=i.truncated}catch{}}t.payloads=[],s&&(t.attributes["ivy.payload.truncated"]=!0),r&&(t.attributes["ivy.payload.trimmed"]=!0)}buildResource(t){let n=process.env,r=t.functionName??n.AWS_LAMBDA_FUNCTION_NAME??"unknown",s={"service.name":r,"cloud.provider":"aws","cloud.platform":"aws_lambda","faas.name":r,"telemetry.sdk.name":"ivy-layer","telemetry.sdk.language":"nodejs","process.runtime.version":process.versions.node,"host.arch":process.arch==="x64"?"amd64":process.arch},o=n.AWS_REGION??n.AWS_DEFAULT_REGION;o&&(s["cloud.region"]=o);let i=t.invokedFunctionArn?.split(":")[4];i&&(s["cloud.account.id"]=i);let a=t.functionVersion??n.AWS_LAMBDA_FUNCTION_VERSION;a&&(s["faas.version"]=a);let c=parseInt(t.memoryLimitInMB??n.AWS_LAMBDA_FUNCTION_MEMORY_SIZE??"",10);return Number.isFinite(c)&&(s["faas.max_memory"]=c*1024*1024),n.AWS_LAMBDA_LOG_STREAM_NAME&&(s["faas.instance"]=n.AWS_LAMBDA_LOG_STREAM_NAME),mt(s)}};function tr(e){let t=a=>a.status.code===y.ERROR,n=e.filter(t),r=e.filter(a=>!t(a)),s=a=>(a.endMs??a.startMs)-a.startMs,o=Math.max(5,Math.ceil(r.length/10)),i=new Set([...r].sort((a,c)=>s(c)-s(a)).slice(0,o));return[...n,...r.filter(a=>i.has(a)),...r.filter(a=>!i.has(a)).sort((a,c)=>a.startMs-c.startMs)]}var Ut="ivy.workers.traced";var er=500;function ze(){let e=process.getBuiltinModule("node:worker_threads"),t=e.parentPort;if(e.getEnvironmentData(Ut)!==!0||!t)return;e.setEnvironmentData(Ut,void 0);let n=et(),r=new St(n,()=>{}),s=Te(r);xe(r),Se(r),n.captureLogs&&ke(r),Ve(r);let o=r.startInvocation({},{}),i=e.MessagePort.prototype.postMessage,a=new P(1/0),c=!1,d=u=>{if(!c){c=!0;try{s();let p=[],f=[];for(let S of o.children)(S.endMs===void 0&&u!=="all"?f:p).push(S);let l=u==="snapshot"?f.map(nr):[];if(!p.length&&!l.length&&!o.root.events.length)return;o.children=f;for(let S of p)r.applyPayloads(S,a);let h={ivyWorkerBatch:1,root:o.root.spanId,spans:[...p,...l],logs:o.root.events.splice(0)};o.logCount=0,i.call(t,h)}catch{}finally{c=!1}}};setInterval(()=>d("ended"),er).unref(),process.on("exit",()=>d("all")),e.MessagePort.prototype.postMessage=function(...u){return d("snapshot"),i.apply(this,u)}}var nr=e=>({...e,attributes:{...e.attributes},events:[...e.events],payloads:[],finalize:void 0});try{ze()}catch(e){et().debug&&console.warn(`[ivy] worker tracing disabled: ${e.message}`)}