promptlayer 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var ks=Object.create;var Ze=Object.defineProperty,ws=Object.defineProperties,xs=Object.getOwnPropertyDescriptor,Ss=Object.getOwnPropertyDescriptors,Ps=Object.getOwnPropertyNames,on=Object.getOwnPropertySymbols,Cs=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty,so=Object.prototype.propertyIsEnumerable;var bn=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t);var oo=(t,n,e)=>n in t?Ze(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e,S=(t,n)=>{for(var e in n||(n={}))kn.call(n,e)&&oo(t,e,n[e]);if(on)for(var e of on(n))so.call(n,e)&&oo(t,e,n[e]);return t},Y=(t,n)=>ws(t,Ss(n));var sn=(t,n)=>{var e={};for(var o in t)kn.call(t,o)&&n.indexOf(o)<0&&(e[o]=t[o]);if(t!=null&&on)for(var o of on(t))n.indexOf(o)<0&&so.call(t,o)&&(e[o]=t[o]);return e};var Ts=(t,n)=>{for(var e in n)Ze(t,e,{get:n[e],enumerable:!0})},ro=(t,n,e,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Ps(n))!kn.call(t,s)&&s!==e&&Ze(t,s,{get:()=>n[s],enumerable:!(o=xs(n,s))||o.enumerable});return t};var lt=(t,n,e)=>(e=t!=null?ks(Cs(t)):{},ro(n||!t||!t.__esModule?Ze(e,"default",{value:t,enumerable:!0}):e,t)),Es=t=>ro(Ze({},"__esModule",{value:!0}),t);var T=(t,n,e)=>new Promise((o,s)=>{var i=u=>{try{p(e.next(u))}catch(_){s(_)}},l=u=>{try{p(e.throw(u))}catch(_){s(_)}},p=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,l);p((e=e.apply(t,n)).next())}),ft=function(t,n){this[0]=t,this[1]=n},rn=(t,n,e)=>{var o=(l,p,u,_)=>{try{var m=e[l](p),y=(p=m.value)instanceof ft,k=m.done;Promise.resolve(y?p[0]:p).then(h=>y?o(l==="return"?l:"next",p[1]?{done:h.done,value:h.value}:h,u,_):u({value:h,done:k})).catch(h=>o("throw",h,u,_))}catch(h){_(h)}},s=l=>i[l]=p=>new Promise((u,_)=>o(l,p,u,_)),i={};return e=e.apply(t,n),i[bn("asyncIterator")]=()=>i,s("next"),s("throw"),s("return"),i};var an=(t,n,e)=>(n=t[bn("asyncIterator")])?n.call(t):(t=t[bn("iterator")](),n={},e=(o,s)=>(s=t[o])&&(n[o]=i=>new Promise((l,p,u)=>(i=s.call(t,i),u=i.done,Promise.resolve(i.value).then(_=>l({value:_,done:u}),p)))),e("next"),e("return"),n);var wr={};Ts(wr,{PromptLayer:()=>Mn});module.exports=Es(wr);var Po=lt(require("ably")),Co=require("centrifuge"),To=lt(require("p-retry"));var io={png:"image/png",webp:"image/webp",jpeg:"image/jpeg",jpg:"image/jpeg",gif:"image/gif",url:"image/png"},rt=(t,n,e,o)=>S({id:t,type:"function",function:{name:n,arguments:typeof e=="string"?e:JSON.stringify(e)}},o?{tool_id:o}:{}),b=o=>{var s=o,{type:t,item_id:n}=s,e=sn(s,["type","item_id"]);let i=S({type:t},e);return n&&(i.id=n),i},Pt=(t,n)=>({role:"assistant",input_variables:[],template_format:"f-string",content:t,tool_calls:n}),Ct=(t,n)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:n});function ao(t){var n,e,o,s;return S(S({type:"url_citation",url:(n=t.url)!=null?n:"",title:(e=t.title)!=null?e:"",start_index:(o=t.start_index)!=null?o:0,end_index:(s=t.end_index)!=null?s:0},t.cited_text!=null?{cited_text:t.cited_text}:{}),t.encrypted_index!=null?{encrypted_index:t.encrypted_index}:{})}var co=(t,n,e)=>{var l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt;let o=[],s=[];if(Array.isArray(t.content)){for(let U of t.content){if(!U||typeof U!="object")continue;let X=U.type;if(X==="text"){let tt=(l=U.text)!=null?l:"",ut=(u=(p=U.citations)!=null?p:U.annotations)!=null?u:[],et=[];for(let nt of ut)nt&&typeof nt=="object"&&et.push(ao(nt));o.push(b(S({type:"text",text:tt},et.length>0?{annotations:et}:{})))}else if(X==="thinking")o.push(b({type:"thinking",thinking:(_=U.thinking)!=null?_:"",signature:(m=U.signature)!=null?m:""}));else if(X==="tool_use")s.push(rt((y=U.id)!=null?y:"",(k=U.name)!=null?k:"",(h=U.input)!=null?h:{}));else if(X==="server_tool_use")o.push(b({type:"server_tool_use",id:(P=U.id)!=null?P:"",name:(x=U.name)!=null?x:"",input:(g=U.input)!=null?g:{}}));else if(X==="web_search_tool_result"){let tt=(w=U.content)!=null?w:[],ut=[];for(let et of tt)if(et&&typeof et=="object"&&et.type==="web_search_result"){let nt=et;ut.push({type:"web_search_result",url:nt.url,title:nt.title,encrypted_content:nt.encrypted_content,page_age:nt.page_age})}o.push(b({type:"web_search_tool_result",tool_use_id:(f=U.tool_use_id)!=null?f:"",content:ut}))}else X==="bash_code_execution_tool_result"&&o.push(b({type:"bash_code_execution_tool_result",tool_use_id:(R=U.tool_use_id)!=null?R:"",content:(I=U.content)!=null?I:{}}))}let st=Pt(o,s);return Ct(st,n)}if(t.type==="content_block_start")if(((q=t.content_block)==null?void 0:q.type)==="thinking")o.push(b({type:"thinking",thinking:"",signature:""}));else if(((j=t.content_block)==null?void 0:j.type)==="text")o.push(b({type:"text",text:""}));else if(((O=t.content_block)==null?void 0:O.type)==="tool_use")s.push(rt((L=t.content_block.id)!=null?L:"",(W=t.content_block.name)!=null?W:"",{}));else if(((N=t.content_block)==null?void 0:N.type)==="server_tool_use")o.push(b({type:"server_tool_use",id:(V=t.content_block.id)!=null?V:"",name:($=t.content_block.name)!=null?$:"",input:(Z=t.content_block.input)!=null?Z:{}}));else if(((G=t.content_block)==null?void 0:G.type)==="web_search_tool_result"){let st=(Q=t.content_block.content)!=null?Q:[],U=[];for(let X of st)if(X&&typeof X=="object"&&X.type==="web_search_result"){let tt=X;U.push({type:"web_search_result",url:tt.url,title:tt.title,encrypted_content:tt.encrypted_content,page_age:tt.page_age})}o.push(b({type:"web_search_tool_result",tool_use_id:(H=t.content_block.tool_use_id)!=null?H:"",content:U}))}else((it=t.content_block)==null?void 0:it.type)==="bash_code_execution_tool_result"&&o.push(b({type:"bash_code_execution_tool_result",tool_use_id:(at=t.content_block.tool_use_id)!=null?at:"",content:(D=t.content_block.content)!=null?D:{}}));else if(t.type==="content_block_delta"){if(((ot=t.delta)==null?void 0:ot.type)==="thinking_delta")o.push(b({type:"thinking",thinking:(ct=t.delta.thinking)!=null?ct:"",signature:""}));else if(((gt=t.delta)==null?void 0:gt.type)==="text_delta")o.push(b({type:"text",text:(ht=t.delta.text)!=null?ht:""}));else if(((yt=t.delta)==null?void 0:yt.type)==="signature_delta")o.push(b({type:"thinking",thinking:"",signature:(Rt=t.delta.signature)!=null?Rt:""}));else if(((bt=t.delta)==null?void 0:bt.type)==="input_json_delta")(e==null?void 0:e[t.index])==="server_tool_use"?o.push(b({type:"server_tool_use",id:"",name:"",input:(kt=t.delta.partial_json)!=null?kt:{}})):s.push(rt("","",(wt=t.delta.partial_json)!=null?wt:""));else if(((xt=t.delta)==null?void 0:xt.type)==="citations_delta"&&t.delta.citation){let st=t.delta.citation,U=[ao(st)];o.push(b({type:"text",text:"",annotations:U}))}}let i=Pt(o,s);return Ct(i,n)},As=t=>typeof t=="string"&&t.startsWith("image/");function lo(t){var e,o,s,i;let n=t.web;return n&&typeof n=="object"?{uri:(e=n.uri)!=null?e:"",title:(o=n.title)!=null?o:""}:{uri:(s=t.uri)!=null?s:"",title:(i=t.title)!=null?i:""}}function Os(t){if(!t||typeof t!="object")return;let n=t.content,e=n==null?void 0:n.parts;if(!Array.isArray(e))return;let o=[];for(let s of e)s&&typeof s=="object"&&typeof s.text=="string"&&o.push(s.text);return o.length>0?o.join(""):void 0}function Is(t){var o,s,i,l;if(!t||typeof t!="object")return[];let n=(o=t.citations)!=null?o:[],e=[];for(let p of n){if(!p||typeof p!="object")continue;let u=(s=p.uri)!=null?s:"";if(!u)continue;let _=(i=p.startIndex)!=null?i:0,m=(l=p.endIndex)!=null?l:0;e.push({type:"url_citation",url:u,title:u,start_index:_,end_index:m})}return e}function Ls(t,n){if(!t||typeof t!="object")return[];let e=t.groundingMetadata,o=t.citationMetadata,s=Ns(e,n),i=Is(o);return[...s,...i]}function Ns(t,n){var p,u,_,m,y,k,h,P,x;let e=t&&typeof t=="object"?(p=t.groundingChunks)!=null?p:[]:[],o=t&&typeof t=="object"?(u=t.groundingSupports)!=null?u:[]:[];function s(g,w,f){let R=g.text;if(R!=null&&R!=="")return R;if(n!=null&&f>w)return n.slice(w,f)||void 0}if(o.length>0&&e.length>0){let g=[],w=new Set;for(let f of o){if(!f||typeof f!="object")continue;let R=(_=f.segment)!=null?_:{},I=(m=f.groundingChunkIndices)!=null?m:[],q=(y=R.startIndex)!=null?y:0,j=(k=R.endIndex)!=null?k:0,O=s(R,q,j);for(let L of I){if(typeof L!="number"||L>=e.length)continue;let W=e[L];if(!W||typeof W!="object")continue;let N=W.maps;if(N&&typeof N=="object"){let G=(h=N.uri)!=null?h:"",Q=(P=N.title)!=null?P:"",H=N.placeId;(G||Q)&&g.push(S(Y(S({type:"map_citation",url:G,title:Q||G},H!=null?{place_id:H}:{}),{start_index:q,end_index:j}),O!=null?{cited_text:O}:{}));continue}let V=W.retrievedContext;if(V&&typeof V=="object"){let G=(x=V.title)!=null?x:"";G&&!w.has(G)&&(w.add(G),g.push({type:"file_citation",file_id:G,filename:G,index:L}));continue}let{uri:$,title:Z}=lo(W);$&&g.push(S({type:"url_citation",url:$,title:Z||$,start_index:q,end_index:j},O!=null?{cited_text:O}:{}))}}return g}if(!t||typeof t!="object")return[];let i=[],l=new Set;return e.forEach((g,w)=>{var O,L,W;if(!g||typeof g!="object")return;let f=g,R=f.maps;if(R&&typeof R=="object"){let N=(O=R.uri)!=null?O:"",V=(L=R.title)!=null?L:"",$=R.placeId;(N||V)&&i.push(Y(S({type:"map_citation",url:N,title:V||N},$!=null?{place_id:$}:{}),{start_index:0,end_index:0}));return}let I=f.retrievedContext;if(I&&typeof I=="object"){let N=(W=I.title)!=null?W:"";N&&!l.has(N)&&(l.add(N),i.push({type:"file_citation",file_id:N,filename:N,index:w}));return}let{uri:q,title:j}=lo(f);q&&i.push({type:"url_citation",url:q,title:j||q,start_index:0,end_index:0})}),i}var uo=(t,n)=>{var u,_,m,y,k,h,P,x,g;let e=[],o=[];for(let w of(u=t.candidates)!=null?u:[])if(w.content&&w.content.parts&&Array.isArray(w.content.parts))for(let f of w.content.parts)if(f.text!=null)f.thought===!0?e.push(b({type:"thinking",thinking:f.text,signature:(_=f.thoughtSignature)!=null?_:""})):e.push(b(S({type:"text",text:f.text},f.thoughtSignature?{thought_signature:f.thoughtSignature}:{})));else if(f.functionCall)o.push(rt(f.functionCall.id||"",f.functionCall.name||"",f.functionCall.args||{}));else if(f.executableCode){let R=f.executableCode;e.push(b(S({type:"code",code:(m=R.code)!=null?m:""},R.language!=null?{language:R.language}:{})))}else if(f.codeExecutionResult){let R=f.codeExecutionResult;e.push(b({type:"code_execution_result",output:(y=R.output)!=null?y:"",outcome:(k=R.outcome)!=null?k:"OUTCOME_OK"}))}else{let R=f.inlineData;if(R&&f.thought!==!0){let I=(h=R.mimeType)!=null?h:"image/png",q=(P=R.data)!=null?P:"";if(As(I)&&q){let j={};f.thoughtSignature&&(j.thought_signature=f.thoughtSignature),f.aspectRatio!=null&&(j.aspect_ratio=f.aspectRatio),f.imageSize!=null&&(j.image_size=f.imageSize),e.push(b(S({type:"output_media",url:q,mime_type:I,media_type:"image"},Object.keys(j).length?{provider_metadata:j}:{})))}}}let s=(x=t.candidates)==null?void 0:x[0],i=Os(s),l=Ls(s,i);if(l.length>0)for(let w=0;w<e.length;w++){let f=e[w];if(f&&typeof f=="object"&&f.type==="text"){let R=(g=f.annotations)!=null?g:[];e[w]=Y(S({},f),{annotations:[...R,...l]})}}let p=Pt(e,o);return Ct(p,n)},wn=(t,n)=>{let e=[],o=[];for(let i of t.choices)if(i.delta){i.delta.content&&e.push(b({type:"text",text:i.delta.content}));let l=i.delta.tool_calls||i.delta.toolCalls;if(l&&Array.isArray(l))for(let p of l)p.function&&o.push(rt(p.id||"",p.function.name||"",p.function.arguments||""))}let s=Pt(e,o);return Ct(s,n)},po=(t,n)=>{var l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt,st,U,X,tt,ut,et,nt,Ot,It,Lt,Nt,Ut,qt,Mt,jt,Wt,$t,Kt,Ft,Gt,Dt,Bt,zt,Vt,Jt,Yt,Xt,Ht,Zt,Qt,vt,te,ee,ne,oe,se,re,ie,ae,le,ce,ue,pe,de,_e,me,fe,ge,he,ye,Re,be,ke,we,xe,Se,Pe,Ce,Te,Ee,Ae,Oe,Ie,Le,Ne,Ue,qe,Me,je,We,$e,Ke,Fe,Ge,De,Be,ze,Ve,Je,Ye,Xe,He,C,M,a,c,E,pt,jn,Wn,$n,Kn,Fn,Gn,Dn,Bn,zn,Vn,Jn,Yn,Xn,Hn,Zn,Qn,vn,to,eo,no;let e=[],o=[],s=t==null?void 0:t.type;if(s==="response.reasoning_summary_text.delta"){let r=(l=t==null?void 0:t.delta)!=null?l:"",A=(p=t==null?void 0:t.item_id)!=null?p:"";r&&e.push(b({type:"thinking",item_id:A,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_text.done"){let r=(u=t==null?void 0:t.text)!=null?u:"",A=(_=t==null?void 0:t.item_id)!=null?_:"";r&&e.push(b({type:"thinking",item_id:A,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_part.added"){let r=(m=t==null?void 0:t.part)!=null?m:{},A=(y=t==null?void 0:t.item_id)!=null?y:"";if((r==null?void 0:r.type)==="summary_text"){let d=(k=r==null?void 0:r.text)!=null?k:"";e.push(b({type:"thinking",item_id:A,thinking:d,signature:""}))}}else if(s==="response.reasoning_summary_part.done"){let r=(h=t==null?void 0:t.part)!=null?h:{},A=(P=t==null?void 0:t.item_id)!=null?P:"";if((r==null?void 0:r.type)==="summary_text"){let d=(x=r==null?void 0:r.text)!=null?x:"";d&&e.push(b({type:"thinking",item_id:A,thinking:d,signature:""}))}}else if(s==="response.function_call_arguments.delta"){let r=(g=t==null?void 0:t.item_id)!=null?g:"",A=(w=t==null?void 0:t.delta)!=null?w:"";A&&o.push(rt("","",A,r))}else if(s==="response.function_call_arguments.done"){let r=(f=t==null?void 0:t.item_id)!=null?f:"",A=(R=t==null?void 0:t.arguments)!=null?R:"";A&&o.push(rt("","",A,r))}else if(s==="response.output_item.added"){let r=(I=t==null?void 0:t.item)!=null?I:{},A=r==null?void 0:r.type,d=(q=r==null?void 0:r.id)!=null?q:"";A==="reasoning"?e.push(b({type:"thinking",thinking:"",signature:"",item_id:d})):A==="function_call"?o.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"","",d)):A==="message"?e.push(b({type:"text",item_id:d,text:""})):A==="code_interpreter_call"?e.push(b({type:"code",item_id:d,code:(j=r==null?void 0:r.code)!=null?j:"",container_id:(O=r==null?void 0:r.container_id)!=null?O:""})):A==="image_generation_call"?e.push(b({type:"output_media",item_id:d,url:"",mime_type:"image/png",media_type:"image"})):A==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:d,server_label:(L=r==null?void 0:r.server_label)!=null?L:"",tools:(W=r==null?void 0:r.tools)!=null?W:[]})):A==="mcp_call"?e.push(b({type:"mcp_call",item_id:d,name:(N=r==null?void 0:r.name)!=null?N:"",server_label:(V=r==null?void 0:r.server_label)!=null?V:"",arguments:($=r==null?void 0:r.arguments)!=null?$:"",output:r==null?void 0:r.output,error:r==null?void 0:r.error,approval_request_id:r==null?void 0:r.approval_request_id})):A==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:d,name:(Z=r==null?void 0:r.name)!=null?Z:"",arguments:(G=r==null?void 0:r.arguments)!=null?G:"",server_label:(Q=r==null?void 0:r.server_label)!=null?Q:""})):A==="shell_call"?e.push(b({type:"shell_call",item_id:d,call_id:(H=r==null?void 0:r.call_id)!=null?H:"",action:(it=r==null?void 0:r.action)!=null?it:{},status:(at=r==null?void 0:r.status)!=null?at:"in_progress"})):A==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:d,call_id:(D=r==null?void 0:r.call_id)!=null?D:"",output:(ot=r==null?void 0:r.output)!=null?ot:[],status:(ct=r==null?void 0:r.status)!=null?ct:"in_progress"})):A==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:d,call_id:(gt=r==null?void 0:r.call_id)!=null?gt:"",operation:(ht=r==null?void 0:r.operation)!=null?ht:{},status:(yt=r==null?void 0:r.status)!=null?yt:"in_progress"})):A==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:d,call_id:(Rt=r==null?void 0:r.call_id)!=null?Rt:"",output:(bt=r==null?void 0:r.output)!=null?bt:"",status:(kt=r==null?void 0:r.status)!=null?kt:"in_progress"}))}else if(s==="response.content_part.added"){let r=(wt=t==null?void 0:t.part)!=null?wt:{},A=(xt=r==null?void 0:r.type)!=null?xt:"output_text",d=(st=t==null?void 0:t.item_id)!=null?st:"";A==="output_text"&&e.push(b({type:"text",item_id:d,text:(U=r==null?void 0:r.text)!=null?U:"",annotations:(r==null?void 0:r.annotations)||[]}))}else if(s==="response.content_part.done"){let r=(X=t==null?void 0:t.part)!=null?X:{},A=(tt=r==null?void 0:r.type)!=null?tt:"output_text",d=(ut=t==null?void 0:t.item_id)!=null?ut:"";A==="output_text"&&e.push(b({type:"text",item_id:d,text:(et=r==null?void 0:r.text)!=null?et:"",annotations:(r==null?void 0:r.annotations)||[]}))}else if(s==="response.output_text.annotation.added"){let r=(t==null?void 0:t.annotation)||{},A=r==null?void 0:r.type,d=null;A==="url_citation"?d={type:"url_citation",title:(nt=r==null?void 0:r.title)!=null?nt:"",url:(Ot=r==null?void 0:r.url)!=null?Ot:"",start_index:(It=r==null?void 0:r.start_index)!=null?It:0,end_index:(Lt=r==null?void 0:r.end_index)!=null?Lt:0}:A==="file_citation"?d={type:"file_citation",index:(Nt=r==null?void 0:r.index)!=null?Nt:0,file_id:(Ut=r==null?void 0:r.file_id)!=null?Ut:"",filename:(qt=r==null?void 0:r.filename)!=null?qt:""}:d=r,e.push(b({type:"text",item_id:(Mt=t==null?void 0:t.item_id)!=null?Mt:"",text:"",annotations:[d]}))}else if(s==="response.code_interpreter_call.in_progress")e.push(b({type:"code",item_id:(jt=t==null?void 0:t.item_id)!=null?jt:"",code:(Wt=t==null?void 0:t.code)!=null?Wt:"",container_id:($t=t==null?void 0:t.container_id)!=null?$t:""}));else if(s==="response.code_interpreter_call_code.delta")e.push(b({type:"code",item_id:(Kt=t==null?void 0:t.item_id)!=null?Kt:"",code:(Ft=t==null?void 0:t.delta)!=null?Ft:"",container_id:(Gt=t==null?void 0:t.container_id)!=null?Gt:""}));else if(s==="response.output_text.delta"){let r=(Dt=t==null?void 0:t.delta)!=null?Dt:"";r&&e.push(b({type:"text",item_id:(Bt=t==null?void 0:t.item_id)!=null?Bt:"",text:r}))}else if(s==="response.output_text.done")e.push(b({type:"text",item_id:(zt=t==null?void 0:t.item_id)!=null?zt:"",text:(Vt=t==null?void 0:t.text)!=null?Vt:""}));else if(s==="response.output_item.done"){let r=(Jt=t==null?void 0:t.item)!=null?Jt:{},A=r==null?void 0:r.type,d=(Yt=r==null?void 0:r.id)!=null?Yt:"";if(A==="reasoning"){let K=((Xt=r==null?void 0:r.summary)!=null?Xt:[]).map(dt=>{var J;return(J=dt==null?void 0:dt.text)!=null?J:""}).join("");e.push(b({type:"thinking",item_id:d,thinking:K,signature:""}))}else if(A==="function_call")o.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"",(r==null?void 0:r.arguments)||"",d));else if(A==="message"){let B=(Ht=r==null?void 0:r.content)!=null?Ht:[];for(let K of B)(K==null?void 0:K.type)==="output_text"&&e.push(b({type:"text",item_id:d,text:(Zt=K==null?void 0:K.text)!=null?Zt:""}))}else if(A==="code_interpreter_call")e.push(b({type:"code",item_id:d,code:(Qt=r==null?void 0:r.code)!=null?Qt:"",container_id:(vt=r==null?void 0:r.container_id)!=null?vt:""}));else if(A==="image_generation_call"){let B=(te=r==null?void 0:r.result)!=null?te:"",dt=((ee=r==null?void 0:r.output_format)!=null?ee:"png")==="webp"?"image/webp":"image/png",J={};for(let mt of["revised_prompt","background","size","quality","output_format"])(r==null?void 0:r[mt])!=null&&(J[mt]=r[mt]);e.push(b(S({type:"output_media",item_id:d,url:B,mime_type:dt,media_type:"image"},Object.keys(J).length?{provider_metadata:J}:{})))}else A==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:d,server_label:(ne=r==null?void 0:r.server_label)!=null?ne:"",tools:(oe=r==null?void 0:r.tools)!=null?oe:[],error:r==null?void 0:r.error})):A==="mcp_call"?e.push(b({type:"mcp_call",item_id:d,name:(se=r==null?void 0:r.name)!=null?se:"",server_label:(re=r==null?void 0:r.server_label)!=null?re:"",arguments:(ie=r==null?void 0:r.arguments)!=null?ie:"",output:r==null?void 0:r.output,error:r==null?void 0:r.error,approval_request_id:r==null?void 0:r.approval_request_id})):A==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:d,name:(ae=r==null?void 0:r.name)!=null?ae:"",arguments:(le=r==null?void 0:r.arguments)!=null?le:"",server_label:(ce=r==null?void 0:r.server_label)!=null?ce:""})):A==="shell_call"?e.push(b({type:"shell_call",item_id:d,call_id:(ue=r==null?void 0:r.call_id)!=null?ue:"",action:(pe=r==null?void 0:r.action)!=null?pe:{},status:(de=r==null?void 0:r.status)!=null?de:"completed"})):A==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:d,call_id:(_e=r==null?void 0:r.call_id)!=null?_e:"",output:(me=r==null?void 0:r.output)!=null?me:[],status:(fe=r==null?void 0:r.status)!=null?fe:"completed"})):A==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:d,call_id:(ge=r==null?void 0:r.call_id)!=null?ge:"",operation:(he=r==null?void 0:r.operation)!=null?he:{},status:(ye=r==null?void 0:r.status)!=null?ye:"completed"})):A==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:d,call_id:(Re=r==null?void 0:r.call_id)!=null?Re:"",output:(be=r==null?void 0:r.output)!=null?be:"",status:(ke=r==null?void 0:r.status)!=null?ke:"completed"}))}else if(s==="response.code_interpreter_call_code.done")e.push(b({type:"code",item_id:(we=t==null?void 0:t.item_id)!=null?we:"",code:(xe=t==null?void 0:t.code)!=null?xe:"",container_id:(Se=t==null?void 0:t.container_id)!=null?Se:""}));else if(s==="response.code_interpreter_call.interpreting")e.push(b({type:"code",item_id:(Pe=t==null?void 0:t.item_id)!=null?Pe:"",code:(Ce=t==null?void 0:t.code)!=null?Ce:"",container_id:(Te=t==null?void 0:t.container_id)!=null?Te:""}));else if(s==="response.code_interpreter_call.completed")e.push(b({type:"code",item_id:(Ee=t==null?void 0:t.item_id)!=null?Ee:"",code:(Ae=t==null?void 0:t.code)!=null?Ae:"",container_id:(Oe=t==null?void 0:t.container_id)!=null?Oe:""}));else if(s==="response.image_generation_call.in_progress")e.push(b({type:"output_media",item_id:(Ie=t==null?void 0:t.item_id)!=null?Ie:"",url:"",mime_type:"image/png",media_type:"image"}));else if(s==="response.image_generation_call.generating")e.push(b({type:"output_media",item_id:(Le=t==null?void 0:t.item_id)!=null?Le:"",url:"",mime_type:"image/png",media_type:"image"}));else if(s==="response.image_generation_call.partial_image"){let A=((Ne=t==null?void 0:t.output_format)!=null?Ne:"png")==="webp"?"image/webp":"image/png",d={};for(let B of["background","size","quality","output_format"])(t==null?void 0:t[B])!=null&&(d[B]=t[B]);e.push(b(S({type:"output_media",item_id:(Ue=t==null?void 0:t.item_id)!=null?Ue:"",url:(qe=t==null?void 0:t.partial_image_b64)!=null?qe:"",mime_type:A,media_type:"image"},Object.keys(d).length?{provider_metadata:d}:{})))}else if(s==="response.shell_call_command.added")e.push(b({type:"shell_call",action:{command:(Me=t==null?void 0:t.command)!=null?Me:""}}));else if(s==="response.shell_call_command.delta")e.push(b({type:"shell_call",action:{command:(je=t==null?void 0:t.delta)!=null?je:""}}));else if(s==="response.shell_call_command.done")e.push(b({type:"shell_call",action:{command:(We=t==null?void 0:t.command)!=null?We:""}}));else if(s==="response.shell_call_output_content.delta")e.push(b({type:"shell_call_output",item_id:($e=t==null?void 0:t.item_id)!=null?$e:"",output:[(Ke=t==null?void 0:t.delta)!=null?Ke:{}]}));else if(s==="response.shell_call_output_content.done")e.push(b({type:"shell_call_output",item_id:(Fe=t==null?void 0:t.item_id)!=null?Fe:"",output:(Ge=t==null?void 0:t.output)!=null?Ge:[]}));else if(s==="response.apply_patch_call_operation_diff.delta")e.push(b({type:"apply_patch_call",item_id:(De=t==null?void 0:t.item_id)!=null?De:"",operation:{diff:(Be=t==null?void 0:t.delta)!=null?Be:""}}));else if(s==="response.apply_patch_call_operation_diff.done")e.push(b({type:"apply_patch_call",item_id:(ze=t==null?void 0:t.item_id)!=null?ze:"",operation:{diff:(Ve=t==null?void 0:t.diff)!=null?Ve:""}}));else if(s==="response.completed"){let r=(Je=t==null?void 0:t.response)!=null?Je:{},A=(Ye=r==null?void 0:r.output)!=null?Ye:[];for(let d of A){let B=d==null?void 0:d.type,K=(Xe=d==null?void 0:d.id)!=null?Xe:"";if(B==="reasoning"){let J=((He=d==null?void 0:d.summary)!=null?He:[]).map(mt=>{var St;return(St=mt==null?void 0:mt.text)!=null?St:""}).join("");e.push(b({type:"thinking",item_id:K,thinking:J,signature:""}))}else if(B==="function_call")o.push(rt((d==null?void 0:d.call_id)||"",(d==null?void 0:d.name)||"",(d==null?void 0:d.arguments)||"",K));else if(B==="message"){let dt=(C=d==null?void 0:d.content)!=null?C:[];for(let J of dt)(J==null?void 0:J.type)==="output_text"&&e.push(b({type:"text",item_id:K,text:(M=J==null?void 0:J.text)!=null?M:"",annotations:(J==null?void 0:J.annotations)||[]}))}else if(B==="code_interpreter_call")e.push(b({type:"code",item_id:K,code:(a=d==null?void 0:d.code)!=null?a:"",container_id:(c=d==null?void 0:d.container_id)!=null?c:""}));else if(B==="image_generation_call"){let dt=(E=d==null?void 0:d.result)!=null?E:"",mt=((pt=d==null?void 0:d.output_format)!=null?pt:"png")==="webp"?"image/webp":"image/png",St={};for(let Rn of["revised_prompt","background","size","quality","output_format"])(d==null?void 0:d[Rn])!=null&&(St[Rn]=d[Rn]);e.push(b(S({type:"output_media",item_id:K,url:dt,mime_type:mt,media_type:"image"},Object.keys(St).length?{provider_metadata:St}:{})))}else B==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:K,server_label:(jn=d==null?void 0:d.server_label)!=null?jn:"",tools:(Wn=d==null?void 0:d.tools)!=null?Wn:[],error:d==null?void 0:d.error})):B==="mcp_call"?e.push(b({type:"mcp_call",item_id:K,name:($n=d==null?void 0:d.name)!=null?$n:"",server_label:(Kn=d==null?void 0:d.server_label)!=null?Kn:"",arguments:(Fn=d==null?void 0:d.arguments)!=null?Fn:"",output:d==null?void 0:d.output,error:d==null?void 0:d.error,approval_request_id:d==null?void 0:d.approval_request_id})):B==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:K,name:(Gn=d==null?void 0:d.name)!=null?Gn:"",arguments:(Dn=d==null?void 0:d.arguments)!=null?Dn:"",server_label:(Bn=d==null?void 0:d.server_label)!=null?Bn:""})):B==="shell_call"?e.push(b({type:"shell_call",item_id:K,call_id:(zn=d==null?void 0:d.call_id)!=null?zn:"",action:(Vn=d==null?void 0:d.action)!=null?Vn:{},status:(Jn=d==null?void 0:d.status)!=null?Jn:"completed"})):B==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:K,call_id:(Yn=d==null?void 0:d.call_id)!=null?Yn:"",output:(Xn=d==null?void 0:d.output)!=null?Xn:[],status:(Hn=d==null?void 0:d.status)!=null?Hn:"completed"})):B==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:K,call_id:(Zn=d==null?void 0:d.call_id)!=null?Zn:"",operation:(Qn=d==null?void 0:d.operation)!=null?Qn:{},status:(vn=d==null?void 0:d.status)!=null?vn:"completed"})):B==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:K,call_id:(to=d==null?void 0:d.call_id)!=null?to:"",output:(eo=d==null?void 0:d.output)!=null?eo:"",status:(no=d==null?void 0:d.status)!=null?no:"completed"}))}}let i=Pt(e,o||[]);return Ct(i,n)},_o=(t,n)=>{var i,l,p,u;let e=[],o=[];if("contentBlockDelta"in t){let _=((i=t.contentBlockDelta)==null?void 0:i.delta)||{};if("reasoningContent"in _){let m=((l=_.reasoningContent)==null?void 0:l.text)||"",y=((p=_.reasoningContent)==null?void 0:p.signature)||"";e.push(b({type:"thinking",thinking:m,signature:y}))}else if("text"in _)e.push(b({type:"text",text:_.text||""}));else if("toolUse"in _){let m=_.toolUse||{};o.push(rt(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in t){let _=((u=t.contentBlockStart)==null?void 0:u.start)||{};if("toolUse"in _){let m=_.toolUse||{};o.push(rt(m.toolUseId||"",m.name||"",""))}}let s=Pt(e,o);return Ct(s,n)},Us=["size","quality","background","output_format"],mo=(t,n)=>{var i,l,p,u,_,m,y;let e=[],o=(i=t==null?void 0:t.type)!=null?i:"";if(o==="image_generation.partial_image"){let k=(l=t==null?void 0:t.b64_json)!=null?l:"";if(k){let h=(p=t==null?void 0:t.output_format)!=null?p:"png",P=(u=io[h])!=null?u:"image/png",x={},g=t==null?void 0:t.partial_image_index;g!=null&&(x.partial_image_index=g),e.push(b(S({type:"output_media",url:k,mime_type:P,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}}else if(o==="image_generation.completed"){let k=(_=t==null?void 0:t.b64_json)!=null?_:"",h=(m=t==null?void 0:t.output_format)!=null?m:"png",P=(y=io[h])!=null?y:"image/png",x={};for(let g of Us)(t==null?void 0:t[g])!=null&&(x[g]=t[g]);e.push(b(S({type:"output_media",url:k,mime_type:P,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}return{prompt_template:{type:"completion",content:e,input_variables:[]},metadata:n}};var Ro=["openai","openai.azure"],ln=t=>{var s,i,l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt,st,U,X,tt,ut,et,nt,Ot,It,Lt,Nt,Ut,qt,Mt,jt,Wt,$t,Kt,Ft,Gt,Dt,Bt,zt,Vt,Jt,Yt,Xt,Ht,Zt,Qt,vt,te,ee,ne,oe,se,re,ie,ae,le,ce,ue,pe,de,_e,me,fe,ge,he,ye,Re,be,ke,we,xe,Se,Pe,Ce,Te,Ee,Ae,Oe,Ie,Le,Ne,Ue,qe,Me,je,We,$e,Ke,Fe,Ge,De,Be,ze,Ve,Je,Ye,Xe,He;let n={id:null,object:"response",created_at:null,status:null,error:null,incomplete_details:null,instructions:null,max_output_tokens:null,model:null,output:[],parallel_tool_calls:!0,previous_response_id:null,reasoning:{},store:!0,temperature:1,text:void 0,tool_choice:"auto",tools:[],top_p:1,truncation:"disabled",usage:null,user:null,metadata:{}},e={},o={};for(let C of t){let M=C==null?void 0:C.type;if(M==="response.created"){let a=C.response||{};n.id=(s=a.id)!=null?s:n.id,n.created_at=(i=a.created_at)!=null?i:n.created_at,n.model=(l=a.model)!=null?l:n.model,n.status=(p=a.status)!=null?p:n.status,n.parallel_tool_calls=(u=a.parallel_tool_calls)!=null?u:n.parallel_tool_calls,n.temperature=(_=a.temperature)!=null?_:n.temperature,n.tool_choice=(m=a.tool_choice)!=null?m:n.tool_choice,n.tools=(y=a.tools)!=null?y:n.tools,n.top_p=(k=a.top_p)!=null?k:n.top_p,n.truncation=(h=a.truncation)!=null?h:n.truncation,n.max_output_tokens=(P=a.max_output_tokens)!=null?P:n.max_output_tokens,n.previous_response_id=(x=a.previous_response_id)!=null?x:n.previous_response_id,n.store=(g=a.store)!=null?g:n.store,n.user=(w=a.user)!=null?w:n.user,n.metadata=(f=a.metadata)!=null?f:n.metadata;let c=a.text;c&&(n.text=c);let E=a.reasoning;E&&(n.reasoning=E);continue}if(M==="response.in_progress"){let a=C.response||{};n.status=(R=a.status)!=null?R:n.status;continue}if(M==="response.output_item.added"){let a=C.item||{},c=a.id,E=a.type,pt=C.output_index;pt!=null&&c&&(o[pt]=c),E==="reasoning"?e[c]={type:"reasoning",id:c,summary:[],status:(I=a.status)!=null?I:"in_progress"}:E==="function_call"?e[c]={type:"function_call",id:c,call_id:a.call_id,name:a.name,arguments:"",status:(q=a.status)!=null?q:"in_progress"}:E==="message"?e[c]={type:"message",id:c,role:(j=a.role)!=null?j:"assistant",content:[],status:(O=a.status)!=null?O:"in_progress"}:E==="code_interpreter_call"?e[c]={type:"code_interpreter_call",id:c,container_id:a.container_id,code:(L=a.code)!=null?L:"",status:(W=a.status)!=null?W:"in_progress"}:E==="image_generation_call"?e[c]={type:"image_generation_call",id:c,status:(N=a.status)!=null?N:"in_progress",revised_prompt:(V=a.revised_prompt)!=null?V:"",result:($=a.result)!=null?$:"",background:a.background,size:a.size,quality:a.quality,output_format:a.output_format}:E==="web_search_call"?e[c]={type:"web_search_call",id:c,status:(Z=a.status)!=null?Z:"in_progress"}:E==="file_search_call"?e[c]={type:"file_search_call",id:c,status:(G=a.status)!=null?G:"in_progress"}:E==="mcp_list_tools"?e[c]={type:"mcp_list_tools",id:c,server_label:(Q=a.server_label)!=null?Q:"",tools:(H=a.tools)!=null?H:[],error:(it=a.error)!=null?it:null}:E==="mcp_call"?e[c]={type:"mcp_call",id:c,name:(at=a.name)!=null?at:"",server_label:(D=a.server_label)!=null?D:"",arguments:(ot=a.arguments)!=null?ot:"",output:(ct=a.output)!=null?ct:null,error:(gt=a.error)!=null?gt:null,approval_request_id:(ht=a.approval_request_id)!=null?ht:null,status:(yt=a.status)!=null?yt:"in_progress"}:E==="mcp_approval_request"?e[c]={type:"mcp_approval_request",id:c,name:(Rt=a.name)!=null?Rt:"",arguments:(bt=a.arguments)!=null?bt:"",server_label:(kt=a.server_label)!=null?kt:""}:E==="shell_call"?e[c]={type:"shell_call",id:c,call_id:(wt=a.call_id)!=null?wt:"",action:(xt=a.action)!=null?xt:{},status:(st=a.status)!=null?st:"in_progress"}:E==="shell_call_output"?e[c]={type:"shell_call_output",id:c,call_id:(U=a.call_id)!=null?U:"",output:(X=a.output)!=null?X:[],status:(tt=a.status)!=null?tt:"in_progress"}:E==="apply_patch_call"?e[c]={type:"apply_patch_call",id:c,call_id:(ut=a.call_id)!=null?ut:"",operation:(et=a.operation)!=null?et:{},status:(nt=a.status)!=null?nt:"in_progress"}:E==="apply_patch_call_output"&&(e[c]={type:"apply_patch_call_output",id:c,call_id:(Ot=a.call_id)!=null?Ot:"",output:(It=a.output)!=null?It:"",status:(Lt=a.status)!=null?Lt:"in_progress"});continue}if(M==="response.reasoning_summary_part.added"){let a=C.item_id,c=C.part||{};if(a in e&&e[a].type==="reasoning"){let E={type:(Nt=c.type)!=null?Nt:"summary_text",text:(Ut=c.text)!=null?Ut:""};e[a].summary.push(E)}continue}if(M==="response.reasoning_summary_text.delta"){let a=C.item_id,c=(qt=C.delta)!=null?qt:"",E=(Mt=C.summary_index)!=null?Mt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=E;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[E].text+=c}continue}if(M==="response.reasoning_summary_text.done"){let a=C.item_id,c=(jt=C.text)!=null?jt:"",E=(Wt=C.summary_index)!=null?Wt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=E;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[E].text=c}continue}if(M==="response.reasoning_summary_part.done"){let a=C.item_id,c=C.part||{};if(a in e&&e[a].type==="reasoning"){let E=($t=C.summary_index)!=null?$t:0;E<e[a].summary.length&&(e[a].summary[E]={type:(Kt=c.type)!=null?Kt:"summary_text",text:(Ft=c.text)!=null?Ft:""})}continue}if(M==="response.function_call_arguments.delta"){let a=C.item_id,c=(Gt=C.delta)!=null?Gt:"";a in e&&(e[a].arguments=`${e[a].arguments||""}${c}`);continue}if(M==="response.function_call_arguments.done"){let a=C.item_id,c=(Dt=C.arguments)!=null?Dt:"";a in e&&(e[a].arguments=c);continue}if(M==="response.content_part.added"){let a=C.part||{},c=Object.values(e).find(E=>E.type==="message");if(c){let E={type:(Bt=a.type)!=null?Bt:"output_text",text:(zt=a.text)!=null?zt:"",annotations:(Vt=a.annotations)!=null?Vt:[]};c.content.push(E)}continue}if(M==="response.output_text.delta"){let a=(Jt=C.delta)!=null?Jt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let E=c.content[c.content.length-1];E&&E.type==="output_text"&&(E.text=`${E.text||""}${a}`);break}continue}if(M==="response.output_text.done"){let a=(Yt=C.text)!=null?Yt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let E=c.content[c.content.length-1];E&&E.type==="output_text"&&(E.text=a);break}continue}if(M==="response.output_item.done"){let a=C.item||{},c=a.id;c in e&&(e[c].status=(Xt=a.status)!=null?Xt:"completed",a.type==="reasoning"?e[c].summary=(Ht=a.summary)!=null?Ht:e[c].summary:a.type==="function_call"?(e[c].arguments=(Zt=a.arguments)!=null?Zt:e[c].arguments,e[c].call_id=(Qt=a.call_id)!=null?Qt:e[c].call_id,e[c].name=(vt=a.name)!=null?vt:e[c].name):a.type==="message"?(e[c].content=(te=a.content)!=null?te:e[c].content,e[c].role=(ee=a.role)!=null?ee:e[c].role):a.type==="image_generation_call"?(e[c].result=(ne=a.result)!=null?ne:e[c].result,e[c].revised_prompt=(oe=a.revised_prompt)!=null?oe:e[c].revised_prompt,e[c].background=(se=a.background)!=null?se:e[c].background,e[c].size=(re=a.size)!=null?re:e[c].size,e[c].quality=(ie=a.quality)!=null?ie:e[c].quality,e[c].output_format=(ae=a.output_format)!=null?ae:e[c].output_format):a.type==="code_interpreter_call"?(e[c].code=(le=a.code)!=null?le:e[c].code,e[c].container_id=(ce=a.container_id)!=null?ce:e[c].container_id):a.type==="mcp_list_tools"?(e[c].tools=(ue=a.tools)!=null?ue:e[c].tools,e[c].error=(pe=a.error)!=null?pe:e[c].error):a.type==="mcp_call"?(e[c].name=(de=a.name)!=null?de:e[c].name,e[c].arguments=(_e=a.arguments)!=null?_e:e[c].arguments,e[c].output=(me=a.output)!=null?me:e[c].output,e[c].error=(fe=a.error)!=null?fe:e[c].error,e[c].server_label=(ge=a.server_label)!=null?ge:e[c].server_label):a.type==="mcp_approval_request"?(e[c].name=(he=a.name)!=null?he:e[c].name,e[c].arguments=(ye=a.arguments)!=null?ye:e[c].arguments,e[c].server_label=(Re=a.server_label)!=null?Re:e[c].server_label):a.type==="shell_call"?(e[c].action=(be=a.action)!=null?be:e[c].action,e[c].call_id=(ke=a.call_id)!=null?ke:e[c].call_id):a.type==="shell_call_output"?(e[c].output=(we=a.output)!=null?we:e[c].output,e[c].call_id=(xe=a.call_id)!=null?xe:e[c].call_id):a.type==="apply_patch_call"?(e[c].operation=(Se=a.operation)!=null?Se:e[c].operation,e[c].call_id=(Pe=a.call_id)!=null?Pe:e[c].call_id):a.type==="apply_patch_call_output"?(e[c].output=(Ce=a.output)!=null?Ce:e[c].output,e[c].call_id=(Te=a.call_id)!=null?Te:e[c].call_id):(a.type==="web_search_call"||a.type==="file_search_call")&&(e[c].action=a.action),n.output.push(e[c]));continue}if(M==="response.image_generation_call.in_progress"){let a=C.item_id;a in e&&(e[a].status="in_progress");continue}if(M==="response.image_generation_call.generating"){let a=C.item_id;a in e&&(e[a].status="generating");continue}if(M==="response.image_generation_call.partial_image"){let a=C.item_id;a in e&&(e[a].result=(Ee=C.partial_image_b64)!=null?Ee:e[a].result,e[a].background=(Ae=C.background)!=null?Ae:e[a].background,e[a].size=(Oe=C.size)!=null?Oe:e[a].size,e[a].quality=(Ie=C.quality)!=null?Ie:e[a].quality,e[a].output_format=(Le=C.output_format)!=null?Le:e[a].output_format);continue}if(M==="response.shell_call_command.added"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[C.command_index]=(Ne=C.command)!=null?Ne:"",e[a].action=c}continue}if(M==="response.shell_call_command.delta"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]);let E=(Ue=C.command_index)!=null?Ue:0;c.commands[E]=((qe=c.commands[E])!=null?qe:"")+((Me=C.delta)!=null?Me:""),e[a].action=c}continue}if(M==="response.shell_call_command.done"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[C.command_index]=(je=C.command)!=null?je:"",e[a].action=c}continue}if(M==="response.shell_call_output_content.delta"){let a=C.item_id;if(a&&a in e){e[a].output||(e[a].output=[]);let c=(We=C.command_index)!=null?We:0,E=($e=e[a].output[c])!=null?$e:{stdout:"",stderr:""},pt=(Ke=C.delta)!=null?Ke:{};pt.stdout&&(E.stdout=((Fe=E.stdout)!=null?Fe:"")+pt.stdout),pt.stderr&&(E.stderr=((Ge=E.stderr)!=null?Ge:"")+pt.stderr),e[a].output[c]=E}continue}if(M==="response.shell_call_output_content.done"){let a=C.item_id;a&&a in e&&(e[a].output=(De=C.output)!=null?De:e[a].output);continue}if(M==="response.apply_patch_call_operation_diff.delta"){let a=C.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=((Be=c.diff)!=null?Be:"")+((ze=C.delta)!=null?ze:""),e[a].operation=c}continue}if(M==="response.apply_patch_call_operation_diff.done"){let a=C.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=(Ve=C.diff)!=null?Ve:c.diff,e[a].operation=c}continue}if(M==="response.completed"){let a=C.response||{};n.status=(Ye=(Je=a.status)!=null?Je:n.status)!=null?Ye:"completed",n.usage=(Xe=a.usage)!=null?Xe:n.usage,n.output=(He=a.output)!=null?He:n.output,a.reasoning&&(n.reasoning=a.reasoning);continue}}return n},xn=t=>{var p,u,_,m,y,k,h,P,x,g;let n=null,e,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},s=t.at(-1);if(!s)return o;let i;for(let w of t){if(w.choices.length===0)continue;let f=w.choices[0].delta;f.content&&(n=`${n||""}${f.content||""}`),f.function_call&&(e={name:`${e?e.name:""}${f.function_call.name||""}`,arguments:`${e?e.arguments:""}${f.function_call.arguments||""}`});let R=(p=f.tool_calls)==null?void 0:p[0];if(R){i=i||[];let I=i.at(-1);if(!I||R.id){i.push({id:R.id||"",type:R.type||"function",function:{name:((u=R.function)==null?void 0:u.name)||"",arguments:((_=R.function)==null?void 0:_.arguments)||""}});continue}I.function.name=`${I.function.name}${((m=R.function)==null?void 0:m.name)||""}`,I.function.arguments=`${I.function.arguments}${((y=R.function)==null?void 0:y.arguments)||""}`}}let l=t[0].choices.at(0);return o.choices.push({finish_reason:(k=l==null?void 0:l.finish_reason)!=null?k:"stop",index:(h=l==null?void 0:l.index)!=null?h:0,logprobs:(P=l==null?void 0:l.logprobs)!=null?P:null,message:{role:"assistant",content:n,function_call:e||void 0,tool_calls:i||void 0,refusal:(x=l==null?void 0:l.delta.refusal)!=null?x:null}}),o.id=s.id,o.model=s.model,o.created=s.created,o.system_fingerprint=s.system_fingerprint,o.usage=(g=s.usage)!=null?g:void 0,o},fo=t=>{let n={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},e=t.at(-1);if(!e)return n;let o="";for(let s of t)s.choices.length>0&&s.choices[0].text&&(o=`${o}${s.choices[0].text}`);return n.choices[0].text=o,n.id=e.id,n.created=e.created,n.model=e.model,n.system_fingerprint=e.system_fingerprint,n.usage=e.usage,n},Sn=t=>{var m,y,k,h,P,x;let n={id:"",model:"",content:[],role:"assistant",type:"message",stop_reason:"stop_sequence",stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,server_tool_use:null,service_tier:null}};if(!t.at(-1))return n;let o=null,s=null,i="",l="",p="",u="",_={};for(let g of t)if(g.type==="message_start")n=S({},g.message);else if(g.type==="content_block_start")o=S({},g.content_block),s="index"in g&&typeof g.index=="number"?g.index:null,o.type==="thinking"?(i="",l=""):o.type==="text"?p="":(o.type==="tool_use"||o.type==="server_tool_use")&&(u="");else if(g.type==="content_block_delta"){let w=g.delta,f="index"in g&&typeof g.index=="number"?g.index:null;if((w==null?void 0:w.type)==="citations_delta"){let R=w.citation;if(R&&typeof R=="object"&&R.type==="web_search_result_location"&&f!==null){let I=S(S({type:"url_citation",url:(m=R.url)!=null?m:"",title:(y=R.title)!=null?y:"",start_index:(k=R.start_index)!=null?k:0,end_index:(h=R.end_index)!=null?h:0},R.cited_text!=null?{cited_text:R.cited_text}:{}),R.encrypted_index!=null?{encrypted_index:R.encrypted_index}:{});_[f]||(_[f]=[]),_[f].push(I)}}else o!==null&&(o.type==="thinking"?(w&&"signature"in w&&(i=w.signature||""),w&&"thinking"in w&&(l+=w.thinking||"")):o.type==="text"?w&&"text"in w&&(p+=w.text||""):(o.type==="tool_use"||o.type==="server_tool_use")&&(w==null?void 0:w.type)==="input_json_delta"&&(u+=w.partial_json||""))}else if(g.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=i,o.thinking=l;else if(o.type==="text")o.text=p,o.citations=null,s!==null&&((P=_[s])!=null&&P.length)&&(o.annotations=_[s]);else if(o.type==="tool_use"||o.type==="server_tool_use")try{o.input=u?JSON.parse(u):{}}catch(w){o.input={}}n.content.push(o),o=null,s=null,i="",l="",p="",u=""}else g.type==="message_delta"&&("usage"in g&&g.usage&&(n.usage=Y(S({},n.usage),{output_tokens:(x=g.usage.output_tokens)!=null?x:0})),"delta"in g&&g.delta&&("stop_reason"in g.delta&&g.delta.stop_reason!==void 0&&(n.stop_reason=g.delta.stop_reason),"stop_sequence"in g.delta&&g.delta.stop_sequence!==void 0&&(n.stop_sequence=g.delta.stop_sequence)));return n},go=t=>{let n={completion:"",id:"",model:"",stop_reason:"",type:"completion"},e=t.at(-1);if(!e)return n;let o="";for(let s of t)o=`${o}${s.completion}`;return n.completion=o,n.id=e.id,n.model=e.model,n.stop_reason=e.stop_reason,n},qs=t=>{var l,p,u,_,m,y,k,h,P,x;let n=null,e={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=t.at(-1).data;if(!o)return e;let s;for(let g of t){if(g.data.choices.length===0)continue;let w=g.data.choices[0].delta;w.content&&(n=`${n||""}${w.content||""}`);let f=(l=w.toolCalls)==null?void 0:l[0];if(f){s=s||[];let R=s.at(-1);if(!R||f.id){s.push({id:f.id||"",type:f.type||"function",function:{name:((p=f.function)==null?void 0:p.name)||"",arguments:((u=f.function)==null?void 0:u.arguments)||""}});continue}R.function.name=`${R.function.name}${((_=f.function)==null?void 0:_.name)||""}`,R.function.arguments=`${R.function.arguments}${((m=f.function)==null?void 0:m.arguments)||""}`}}let i=t[0].data.choices.at(0);return e.choices.push({finish_reason:(y=i==null?void 0:i.finish_reason)!=null?y:"stop",index:(k=i==null?void 0:i.index)!=null?k:0,logprobs:(h=i==null?void 0:i.logprobs)!=null?h:null,message:{role:"assistant",content:n,tool_calls:s||void 0,refusal:(P=i==null?void 0:i.delta.refusal)!=null?P:null}}),e.id=o.id,e.model=o.model,e.created=o.created,e.usage=(x=o.usage)!=null?x:void 0,e},ho=t=>{let n={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},e=[],o=null,s="",i="",l="",p="";for(let u of t)if("contentBlockStart"in u){let _=u.contentBlockStart;if("start"in _&&"toolUse"in _.start){let m=_.start.toolUse;o={toolUse:{toolUseId:m.toolUseId,name:m.name}},s=""}}else if("contentBlockDelta"in u){let _=u.contentBlockDelta.delta;if("text"in _)i+=_.text;else if("reasoningContent"in _){let m=_.reasoningContent;"text"in m?p+=m.text:"signature"in m&&(l+=m.signature)}else if("toolUse"in _&&"input"in _.toolUse){let m=_.toolUse.input;if(s+=m,!m.trim())continue}}else if("contentBlockStop"in u)if(o&&s){try{o.toolUse.input=JSON.parse(s)}catch(_){o.toolUse.input={}}e.push(o),o=null,s=""}else i?(e.push({text:i}),i=""):p&&l&&(e.push({reasoningContent:{reasoningText:{text:p,signature:l}}}),p="",l="");else if("messageStop"in u)n.stopReason=u.messageStop.stopReason;else if("metadata"in u){let _=u.metadata;n.usage=(_==null?void 0:_.usage)||{},n.metrics=(_==null?void 0:_.metrics)||{}}return n.output.message={role:"assistant",content:e},n},Ms=(t,n,e,o,s,i,l,p,u)=>{var k,h,P;let _=S({},l),m=[];if(t){let x={text:t,thought:!0};p&&(x.thoughtSignature=p),m.push(x)}if(n){let x={text:n,thought:null};u&&(x.thoughtSignature=u),m.push(x)}for(let x of s)m.push({executableCode:x});for(let x of i)m.push({codeExecutionResult:x});for(let x of o)m.push({inlineData:x});for(let x of e)m.push({functionCall:x});m.length>0&&((h=(k=_.candidates)==null?void 0:k[0])!=null&&h.content)&&(_.candidates[0].content.parts=m);let y=(P=l==null?void 0:l.candidates)==null?void 0:P[0];return y&&(_.candidates||(_.candidates=[]),_.candidates[0]||(_.candidates[0]={content:{parts:[]}}),y.groundingMetadata!=null&&(_.candidates[0].groundingMetadata=y.groundingMetadata),y.urlContextMetadata!=null&&(_.candidates[0].urlContextMetadata=y.urlContextMetadata),y.citationMetadata!=null&&(_.candidates[0].citationMetadata=y.citationMetadata)),_},bo=t=>{var m,y,k,h,P,x,g;let{GenerateContentResponse:n}=require("@google/genai");if(!t.length)return new n;let e="",o="",s=[],i=[],l=[],p=[],u=null,_=null;for(let w of t)if(w.candidates&&((y=(m=w.candidates[0])==null?void 0:m.content)!=null&&y.parts))for(let f of w.candidates[0].content.parts)if(f.text!=null)f.thought===!0?(e+=f.text,f.thoughtSignature&&(u=f.thoughtSignature)):(o+=f.text,f.thoughtSignature&&(_=f.thoughtSignature));else if(f.functionCall)s.push(f.functionCall);else if(f.inlineData){let R=f.inlineData;i.push({data:(k=R.data)!=null?k:"",mimeType:(h=R.mimeType)!=null?h:"image/png"})}else f.executableCode?l.push({code:(P=f.executableCode.code)!=null?P:"",language:f.executableCode.language}):f.codeExecutionResult&&p.push({output:(x=f.codeExecutionResult.output)!=null?x:"",outcome:(g=f.codeExecutionResult.outcome)!=null?g:"OUTCOME_OK"});return Ms(e,o,s,i,l,p,t[t.length-1],u,_)},js=t=>bo(t),Ws=t=>bo(t),$s=["size","quality","background","output_format"],Pn=t=>{var i,l,p,u,_;let n={created:null,data:[],usage:null},e={},o="png";for(let m of t){let y=(i=m==null?void 0:m.type)!=null?i:"";if(y==="image_generation.partial_image"){let k=m.b64_json;if(k!=null){let h=(l=m.partial_image_index)!=null?l:0;e[h]=k}}else if(y==="image_generation.completed"){let k=m.b64_json;if(k!=null){let h=(p=m.partial_image_index)!=null?p:0;e[h]=k}n.created=(u=m.created_at)!=null?u:n.created,n.usage=(_=m.usage)!=null?_:n.usage;for(let h of $s)m[h]!=null&&(n[h]=m[h]);m.output_format&&(o=m.output_format)}}n.output_format||(n.output_format=o);let s=Object.keys(e).map(Number).sort((m,y)=>m-y);return s.length>0&&(n.data=s.map(m=>({b64_json:e[m]}))),n},ko=(t,n="openai.chat.completions.create")=>{if(n==="openai.responses.create"||n==="openai.AzureOpenAI.responses.create")return ln(t);if(n==="openai.images.generate"||n==="openai.AzureOpenAI.images.generate")return Pn(t);if("completion"in t[0])return t.reduce((e,o)=>Y(S({},o),{completion:`${e.completion}${o.completion}`}),{});if(n==="anthropic.messages.create")return Sn(t);if("text"in t[0].choices[0]){let e="";for(let s of t)e=`${e}${s.choices[0].text}`;let o=structuredClone(t.at(-1));return o.choices[0].text=e,o}if("delta"in t[0].choices[0]){let e=xn(t);return e.choices[0]=S(S({},e.choices[0]),e.choices[0].message),e}return""},yo=(t,n,e)=>{let o=n.model.provider,s=n.model.name;if(o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&s.startsWith("claude"))return co(t,n,e==null?void 0:e.anthropicBlockTypeByIndex);if(o==="google"||o==="vertexai"&&s.startsWith("gemini"))return uo(t,n);if(o==="amazon.bedrock")return _o(t,n);if(o==="mistral")return wn(t.data,n);if(o==="openai"||o==="openai.azure"){let i=n.model.api_type||"chat-completions";return i==="responses"?po(t,n):i==="images"?mo(t,n):wn(t,n)}return null};function wo(t,n,e,o){return rn(this,null,function*(){var k,h,P;let s={request_id:null,raw_response:null,prompt_blueprint:null},i={},l=o.model.provider;l=="amazon.bedrock"&&(i=t==null?void 0:t.$metadata,t=t==null?void 0:t.stream);let p=[],u=l==="anthropic"||l==="anthropic.bedrock"||l==="vertexai"&&((P=(h=(k=o.model)==null?void 0:k.name)==null?void 0:h.startsWith)==null?void 0:P.call(h,"claude")),_={};try{for(var x=an(t),g,w,f;g=!(w=yield new ft(x.next())).done;g=!1){let R=w.value;p.push(R),u&&(R==null?void 0:R.type)==="content_block_start"&&R.content_block&&(_[R.index]=R.content_block.type),s.raw_response=R,s.prompt_blueprint=yo(R,o,{anthropicBlockTypeByIndex:_}),yield s}}catch(w){f=[w]}finally{try{g&&(w=x.return)&&(yield new ft(w.call(x)))}finally{if(f)throw f[0]}}let m=e(p);l==="amazon.bedrock"&&(m.ResponseMetadata=i),s.raw_response=m,s.prompt_blueprint=yo(m,o),yield s;let y=yield new ft(n({request_response:m}));s.request_id=y.request_id,s.prompt_blueprint=y.prompt_blueprint,yield s})}var xo={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:xn},completion:{function_name:"openai.completions.create",stream_function:fo}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:ln}},"openai:images":{completion:{function_name:"openai.images.generate",stream_function:Pn}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:Sn},completion:{function_name:"anthropic.completions.create",stream_function:go}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:xn},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:fo}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ln},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ln}},"openai.azure:images":{completion:{function_name:"openai.AzureOpenAI.images.generate",stream_function:Pn}},google:{chat:{function_name:"google.convo.send_message",stream_function:js},completion:{function_name:"google.model.generate_content",stream_function:Ws}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:ho},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:ho}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:Sn},completion:{function_name:"anthropic.completions.create",stream_function:go}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:qs},completion:{function_name:"",stream_function:null}}};var Eo="1.3.2",Ks=()=>{var t;if(typeof process!="undefined"&&((t=process.versions)!=null&&t.node)){let n=process.versions.node.split(".");return`${n[0]}.${n[1]}`}return"unknown"},Fs=Ks(),Gs=`promptlayer-js/${Eo} (node ${Fs})`,z=()=>({"User-Agent":Gs,"X-SDK-Version":Eo}),Cn="SET_WORKFLOW_COMPLETE";var Qe=class extends Error{constructor(n,e){super(`Server error: ${n} ${e}`),this.name="PromptLayerRetryableHttpError",this.status=n,this.statusText=e}};function Ds(t,n,e,o){return T(this,null,function*(){let s=yield F(`${t}/workflow-version-execution-results?workflow_version_execution_id=${n}&return_all_outputs=${e}`,S({headers:o},z()));if(!s.ok)throw new Error("Failed to fetch final output");return s.json()})}function Ao(t,n,e,o,s){return function(i){return T(this,null,function*(){if(i.name===Cn)try{let l=JSON.parse(i.data),p=l.result_code,u;if(p==="OK"||p==null)u=l.final_output;else if(p==="EXCEEDS_SIZE_LIMIT")u=yield Ds(t,e,o,s),n.resolve(u);else throw new Error(`Unsupported final output code: ${p}`);n.resolve(u)}catch(l){n.reject(l)}})}}function Bs(p){return T(this,arguments,function*({token:t,channelName:n,executionId:e,returnAllOutputs:o,headers:s,timeout:i,baseURL:l}){let u=new Po.default.Realtime(t),_=u.channels.get(n),m={},y=new Promise((h,P)=>{m.resolve=h,m.reject=P}),k=Ao(l,m,e,o,s);yield _.subscribe(Cn,k);try{return yield new Promise((h,P)=>{let x=setTimeout(()=>{P(new Error("Workflow execution did not complete properly (timeout)"))},i);y.then(g=>{clearTimeout(x),h(g)}).catch(g=>{clearTimeout(x),P(g)})})}finally{console.log("Closing client"),_.unsubscribe(Cn,k),u.close(),console.log("Closed client")}})}var F=(t,n)=>T(null,null,function*(){return(0,To.default)(()=>T(null,null,function*(){let e=yield fetch(t,n);if(e.status>=500&&e.status<600||e.status===429)throw new Qe(e.status,e.statusText);return e}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:e=>{console.info(`PromptLayer API request attempt ${e.attemptNumber} failed. ${e.retriesLeft} retries left.`)}})}),Oo=(t,n,e,o=!0)=>T(null,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?Vs(t,n,e.request_response,e,o):yield Io(t,n,e,o)}),Io=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(e)}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);v(i,"WARNING: While logging your request, PromptLayer experienced the following error:")}if(i&&e.return_pl_id)return[e.request_response,i.request_id]}catch(s){if(o)throw s;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${s}`)}return e.request_response}),Lo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-metadata`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track metadata";if(o)throw new Error(l);return v(i,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),No=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-score`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track score";if(o)throw new Error(l);return v(i,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),Uo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-prompt`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track prompt";if(o)throw new Error(l);return v(i,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${s}`),!1}return!0}),qo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/track-group`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track group";if(o)throw new Error(l);return v(i,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${s}`),!1}return!0}),Mo=(t,n,e=!0)=>T(null,null,function*(){try{let o=yield F(`${n}/create-group`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify({api_key:t})}),s=yield o.json();if(o.status!==200){let i=s.message||s.error||"Failed to create group";if(e)throw new Error(i);return v(s,"WARNING: While creating a group PromptLayer had the following error"),!1}return s.id}catch(o){if(e)throw o;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${o}`),!1}}),Tn=(t,n,e,o,s=!0)=>T(null,null,function*(){try{let i=new URL(`${n}/prompt-templates/${e}`),l=yield F(i,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(o)}),p=yield l.json();if(l.status!==200){let u=p.message||p.error||"Failed to fetch prompt template";if(s)throw new Error(u);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${u}`),null}return p.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${p.warning}`),p}catch(i){if(s)throw i;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${i}`),null}}),jo=(t,n,e,o=!0)=>T(null,null,function*(){let s=yield F(`${n}/rest/prompt-templates`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify({prompt_template:S({},e),prompt_version:S({},e),release_labels:e.release_labels?e.release_labels:void 0})}),i=yield s.json();if(s.status!==200&&s.status!==201){let l=i.message||i.error||"Failed to publish prompt template";if(o)throw new Error(l);v(i,"WARNING: While publishing a prompt template PromptLayer had the following error")}return i}),Wo=(t,n,e,o=!0)=>T(null,null,function*(){var p;let s=new URL(`${n}/prompt-templates`);Object.entries(e||{}).forEach(([u,_])=>s.searchParams.append(u,_.toString()));let i=yield F(s,{headers:S({"Content-Type":"application/json","X-API-KEY":t},z())}),l=yield i.json();if(i.status!==200){let u=l.message||l.error||"Failed to fetch prompt templates";if(o)throw new Error(u);return v(l,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(p=l.items)!=null?p:[]}),zs=t=>T(null,null,function*(){let n=new URL(`${t.baseURL}/connection/websocket`);n.protocol=n.protocol==="https:"?"wss:":"ws:";let e=new Co.Centrifuge(n.toString(),{token:t.token}),o=e.newSubscription(t.channelName);return new Promise((s,i)=>{let l=m=>{_(),s(m)},p=Ao(t.baseURL,{resolve:l,reject:i},t.executionId,t.returnAllOutputs,t.headers);o.on("publication",m=>{p({name:m.data.message_name,data:m.data.data})});let u=setTimeout(()=>{i(new Error("Workflow execution did not complete properly (timeout)"))},t.timeout),_=()=>{clearTimeout(u),o.unsubscribe(),e.disconnect()};o.on("error",m=>{_(),i(`Centrifugo subscription error: ${m}`)}),e.on("error",m=>{_(),i(`Centrifugo client error: ${m}`)}),o.subscribe(),e.connect()})}),$o=_=>T(null,[_],function*({workflow_name:t,input_variables:n,metadata:e={},workflow_label_name:o=null,workflow_version_number:s=null,return_all_outputs:i=!1,api_key:l,timeout:p=36e5,baseURL:u}){let m={input_variables:n,metadata:e,workflow_label_name:o,workflow_version_number:s,return_all_outputs:i},y=S({"Content-Type":"application/json","X-API-KEY":l},z());try{let k=yield F(`${u}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:y,body:JSON.stringify(m)});if(k.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield k.json().catch(()=>({}))).error||k.statusText}`};let h=yield k.json();h.warning&&console.warn(`WARNING: ${h.warning}`);let P=h.workflow_version_execution_id;if(!P)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let x=`workflow_updates:${P}`,w=yield(yield F(`${u}/ws-token-request-library?capability=${x}`,{method:"POST",headers:y})).json(),R={token:w.token_details.token,channelName:x,executionId:P,returnAllOutputs:i,headers:y,timeout:p,baseURL:u};return w.messaging_backend==="centrifugo"?zs(R):yield Bs(R)}catch(k){throw console.error(`Failed to run workflow: ${k instanceof Error?k.message:k}`),k}});function Vs(t,n,e,o,s=!0){return rn(this,null,function*(){let i=[];try{for(var u=an(e),_,m,y;_=!(m=yield new ft(u.next())).done;_=!1){let k=m.value;yield o.return_pl_id?[k,null]:k,i.push(k)}}catch(m){y=[m]}finally{try{_&&(m=u.return)&&(yield new ft(m.call(u)))}finally{if(y)throw y[0]}}let l=ko(i,o.function_name),p=yield new ft(Io(t,n,Y(S({},o),{request_response:l,request_end_time:new Date().toISOString()}),s));if(p&&o.return_pl_id){let k=p[1];yield[i.at(-1),k]}})}var v=(t,n)=>{try{console.warn(`${n}: ${t.message}`)}catch(e){console.warn(`${n}: ${t}`)}},Ko=(t,n,e=!0)=>T(null,null,function*(){try{let o=yield F(`${t}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(n)}),s=yield o.json();if(o.status!==200){let i=s.message||s.error||"Failed to track request";if(e)throw new Error(i);v(s,"WARNING: While logging your request, PromptLayer experienced the following error:")}return s}catch(o){if(e)throw o;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${o}`)}return{}}),Js=(t,n)=>T(null,null,function*(){return yield t.chat.completions.create(n)}),Ys=(t,n)=>T(null,null,function*(){return yield t.completions.create(n)}),Fo={chat:Js,completion:Ys},Go=(t,n)=>T(null,null,function*(){var i,l;let e=require("openai").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey});n==null||delete n.apiKey,n==null||delete n.baseURL;let s=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(s==="chat-completions"){let p=Fo[t.prompt_template.type];return yield p(o,n)}else return s==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Do=(t,n)=>T(null,null,function*(){var i,l;let{AzureOpenAI:e}=require("openai"),o=new e({endpoint:process.env.AZURE_OPENAI_ENDPOINT||n.baseURL,apiVersion:process.env.OPENAI_API_VERSION||n.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||n.apiKey});n==null||delete n.baseURL,n==null||delete n.apiVersion,n==null||delete n.apiKey;let s=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(s==="chat-completions"){let p=Fo[t.prompt_template.type];return yield p(o,n)}else return s==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Bo=(t,n)=>T(null,null,function*(){return t.messages.create(n)}),Xs=(t,n)=>T(null,null,function*(){return t.completions.create(n)}),zo={chat:Bo,completion:Xs},Vo=(t,n)=>T(null,null,function*(){let e=require("@anthropic-ai/sdk").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey}),s=zo[t.prompt_template.type];return s(o,n)}),Jo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/log-request`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(e)}),i=yield s.json();if(s.status!==201){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);return v(i,"WARNING: While logging your request PromptLayer had the following error"),null}return i}catch(s){if(o)throw s;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${s}`),null}}),Hs=(t,n)=>T(null,null,function*(){var l,p;let e=n==null?void 0:n.history,o=n==null?void 0:n.generationConfig,s=e.length>0?(l=e[e.length-1])==null?void 0:l.parts:"",i=t.chats.create({model:n==null?void 0:n.model,history:(p=e.slice(0,-1))!=null?p:[],config:o});return n!=null&&n.stream?yield i.sendMessageStream({message:s}):yield i.sendMessage({message:s})}),Zs=(t,o)=>T(null,null,function*(){var s=o,{stream:n}=s,e=sn(s,["stream"]);return n?yield t.generateContentStream(S({},e)):yield t.generateContent(S({},e))}),Qs={chat:Hs,completion:Zs},En=(t,n)=>T(null,null,function*(){let{GoogleGenAI:e}=yield import("@google/genai"),o=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,s=process.env.VERTEX_AI_PROJECT_ID||process.env.GOOGLE_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT,i=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,l={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:s,scopes:["https://www.googleapis.com/auth/cloud-platform"]},p=o?new e({apiKey:o}):new e({vertexai:!0,project:s,location:i,googleAuthOptions:l}),u=Qs[t.prompt_template.type];return yield u(p,n)}),So=t=>t.replace(/_([a-z])/g,(n,e)=>e.toUpperCase()),cn=(t,n=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(e=>cn(e,n)):Object.fromEntries(Object.entries(t).map(([e,o])=>n.has(e)?[So(e),o]:[So(e),cn(o,n)])),Yo=(t,n,e={},o=!1)=>{var u,_,m,y,k,h,P,x,g;let s=(m=n==null?void 0:n.client)!=null?m:(_=(u=t.metadata)==null?void 0:u.model)==null?void 0:_.provider,i=(k=(y=t.metadata)==null?void 0:y.model)==null?void 0:k.api_type;if(!s)throw new Error("Provider type not found in prompt blueprint or custom provider");let l=Y(S({},t.llm_kwargs||{}),{stream:o});["google","vertexai"].includes(s)&&((P=(h=t.metadata)==null?void 0:h.model)!=null&&P.name.startsWith("gemini"))&&(l=cn(l,new Set(["function_declarations","properties"])));let p={baseURL:(g=n==null?void 0:n.base_url)!=null?g:(x=t.provider_base_url)==null?void 0:x.url,apiKey:n==null?void 0:n.api_key};return Object.entries(p).forEach(([w,f])=>{f!==void 0&&(l[w]=f)}),o&&Ro.includes(s)&&i==="chat-completions"&&(l.stream_options={include_usage:!0}),{provider_type:s,kwargs:l}},Xo=(t,n)=>{let e=xo[t];if(!e)throw new Error(`Unsupported provider type: ${t}`);let o=n.type,s=e[o];if(!s)throw new Error(`Unsupported template type '${n.type}' for provider '${t}'`);return s},Ho=(t,n)=>T(null,null,function*(){var o;let e=(o=t.metadata)==null?void 0:o.model;if(!e)throw new Error("Model metadata not found in prompt blueprint");if(e.name.startsWith("gemini"))return En(t,n);if(e.name.startsWith("claude")){let{AnthropicVertex:s}=yield import("@anthropic-ai/vertex-sdk"),i=new s({baseURL:n.baseURL});if(t.prompt_template.type==="chat")return Bo(i,n);throw new Error(`Unsupported prompt template type '${t.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${e.name}' for Vertex AI request`)}),Zo=(t,n)=>T(null,null,function*(){let{BedrockRuntimeClient:e,ConverseCommand:o,ConverseStreamCommand:s}=yield import("@aws-sdk/client-bedrock-runtime"),i=new e({credentials:{accessKeyId:(n==null?void 0:n.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(n==null?void 0:n.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(n==null?void 0:n.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(n==null?void 0:n.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(n!=null&&n.stream){delete n.stream;let l=new s(S({},n));return yield i.send(l)}else{n==null||delete n.stream;let l=new o(S({},n));return yield i.send(l)}}),Qo=(t,n)=>T(null,null,function*(){let{AnthropicBedrock:e}=yield import("@anthropic-ai/bedrock-sdk"),o=new e({awsAccessKey:n.aws_access_key,awsSecretKey:n.aws_secret_key,awsRegion:n.aws_region,awsSessionToken:n.aws_session_token,baseURL:n.base_url}),s=zo[t.prompt_template.type];return s(o,n)}),vo=(t,n)=>T(null,null,function*(){let{Mistral:e}=yield import("@mistralai/mistralai"),o=new e({apiKey:process.env.MISTRAL_API_KEY});return n=cn(n,new Set),n!=null&&n.stream?(delete n.stream,yield o.chat.stream(n)):(delete n.stream,yield o.chat.complete(n))}),An=t=>{var n,e,o,s,i,l;if(typeof globalThis.process!="undefined")return(o=(e=(n=globalThis.process.env)==null?void 0:n[t])==null?void 0:e.trim())!=null?o:void 0;if(typeof globalThis.Deno!="undefined")return(l=(i=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:i.call(s,t))==null?void 0:l.trim()};var un=class{constructor(n,e,o=!0){this.create=()=>Mo(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var _t=require("@opentelemetry/api"),ve=require("@opentelemetry/core");var On=class{constructor(n,e,o){this.apiKey=e,this.baseURL=o,this.enableTracing=n,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(n){return n?Object.fromEntries(Object.entries(n)):{}}spanKindToString(n){return{[_t.SpanKind.INTERNAL]:"SpanKind.INTERNAL",[_t.SpanKind.SERVER]:"SpanKind.SERVER",[_t.SpanKind.CLIENT]:"SpanKind.CLIENT",[_t.SpanKind.PRODUCER]:"SpanKind.PRODUCER",[_t.SpanKind.CONSUMER]:"SpanKind.CONSUMER"}[n]||"SpanKind.INTERNAL"}statusCodeToString(n){return{[_t.SpanStatusCode.ERROR]:"StatusCode.ERROR",[_t.SpanStatusCode.OK]:"StatusCode.OK",[_t.SpanStatusCode.UNSET]:"StatusCode.UNSET"}[n]||"StatusCode.UNSET"}toNanoseconds(n){return(BigInt(n[0])*BigInt(1e9)+BigInt(n[1])).toString()}export(n){if(!this.enableTracing)return Promise.resolve(ve.ExportResultCode.SUCCESS);let e=n.map(o=>{var s;return{name:o.name,context:{trace_id:o.spanContext().traceId,span_id:o.spanContext().spanId,trace_state:((s=o.spanContext().traceState)==null?void 0:s.serialize())||""},kind:this.spanKindToString(o.kind),parent_id:o.parentSpanId||null,start_time:this.toNanoseconds(o.startTime),end_time:this.toNanoseconds(o.endTime),status:{status_code:this.statusCodeToString(o.status.code),description:o.status.message},attributes:this.attributesToObject(o.attributes),events:o.events.map(i=>({name:i.name,timestamp:this.toNanoseconds(i.time),attributes:this.attributesToObject(i.attributes)})),links:o.links.map(i=>({context:i.context,attributes:this.attributesToObject(i.attributes)})),resource:{attributes:Y(S({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return F(this.url,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},z()),body:JSON.stringify({spans:e})}).then(o=>o.ok?ve.ExportResultCode.SUCCESS:(console.error(`Error exporting spans
1
+ "use strict";var ks=Object.create;var Ze=Object.defineProperty,ws=Object.defineProperties,xs=Object.getOwnPropertyDescriptor,Ss=Object.getOwnPropertyDescriptors,Ps=Object.getOwnPropertyNames,on=Object.getOwnPropertySymbols,Cs=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty,so=Object.prototype.propertyIsEnumerable;var bn=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t);var oo=(t,n,e)=>n in t?Ze(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e,S=(t,n)=>{for(var e in n||(n={}))kn.call(n,e)&&oo(t,e,n[e]);if(on)for(var e of on(n))so.call(n,e)&&oo(t,e,n[e]);return t},Y=(t,n)=>ws(t,Ss(n));var sn=(t,n)=>{var e={};for(var o in t)kn.call(t,o)&&n.indexOf(o)<0&&(e[o]=t[o]);if(t!=null&&on)for(var o of on(t))n.indexOf(o)<0&&so.call(t,o)&&(e[o]=t[o]);return e};var Ts=(t,n)=>{for(var e in n)Ze(t,e,{get:n[e],enumerable:!0})},ro=(t,n,e,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Ps(n))!kn.call(t,s)&&s!==e&&Ze(t,s,{get:()=>n[s],enumerable:!(o=xs(n,s))||o.enumerable});return t};var lt=(t,n,e)=>(e=t!=null?ks(Cs(t)):{},ro(n||!t||!t.__esModule?Ze(e,"default",{value:t,enumerable:!0}):e,t)),Es=t=>ro(Ze({},"__esModule",{value:!0}),t);var T=(t,n,e)=>new Promise((o,s)=>{var i=u=>{try{p(e.next(u))}catch(_){s(_)}},l=u=>{try{p(e.throw(u))}catch(_){s(_)}},p=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,l);p((e=e.apply(t,n)).next())}),ft=function(t,n){this[0]=t,this[1]=n},rn=(t,n,e)=>{var o=(l,p,u,_)=>{try{var m=e[l](p),y=(p=m.value)instanceof ft,k=m.done;Promise.resolve(y?p[0]:p).then(h=>y?o(l==="return"?l:"next",p[1]?{done:h.done,value:h.value}:h,u,_):u({value:h,done:k})).catch(h=>o("throw",h,u,_))}catch(h){_(h)}},s=l=>i[l]=p=>new Promise((u,_)=>o(l,p,u,_)),i={};return e=e.apply(t,n),i[bn("asyncIterator")]=()=>i,s("next"),s("throw"),s("return"),i};var an=(t,n,e)=>(n=t[bn("asyncIterator")])?n.call(t):(t=t[bn("iterator")](),n={},e=(o,s)=>(s=t[o])&&(n[o]=i=>new Promise((l,p,u)=>(i=s.call(t,i),u=i.done,Promise.resolve(i.value).then(_=>l({value:_,done:u}),p)))),e("next"),e("return"),n);var wr={};Ts(wr,{PromptLayer:()=>Mn});module.exports=Es(wr);var Po=lt(require("ably")),Co=require("centrifuge"),To=lt(require("p-retry"));var io={png:"image/png",webp:"image/webp",jpeg:"image/jpeg",jpg:"image/jpeg",gif:"image/gif",url:"image/png"},rt=(t,n,e,o)=>S({id:t,type:"function",function:{name:n,arguments:typeof e=="string"?e:JSON.stringify(e)}},o?{tool_id:o}:{}),b=o=>{var s=o,{type:t,item_id:n}=s,e=sn(s,["type","item_id"]);let i=S({type:t},e);return n&&(i.id=n),i},Pt=(t,n)=>({role:"assistant",input_variables:[],template_format:"f-string",content:t,tool_calls:n}),Ct=(t,n)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:n});function ao(t){var n,e,o,s;return S(S({type:"url_citation",url:(n=t.url)!=null?n:"",title:(e=t.title)!=null?e:"",start_index:(o=t.start_index)!=null?o:0,end_index:(s=t.end_index)!=null?s:0},t.cited_text!=null?{cited_text:t.cited_text}:{}),t.encrypted_index!=null?{encrypted_index:t.encrypted_index}:{})}var co=(t,n,e)=>{var l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt;let o=[],s=[];if(Array.isArray(t.content)){for(let U of t.content){if(!U||typeof U!="object")continue;let X=U.type;if(X==="text"){let tt=(l=U.text)!=null?l:"",ut=(u=(p=U.citations)!=null?p:U.annotations)!=null?u:[],et=[];for(let nt of ut)nt&&typeof nt=="object"&&et.push(ao(nt));o.push(b(S({type:"text",text:tt},et.length>0?{annotations:et}:{})))}else if(X==="thinking")o.push(b({type:"thinking",thinking:(_=U.thinking)!=null?_:"",signature:(m=U.signature)!=null?m:""}));else if(X==="tool_use")s.push(rt((y=U.id)!=null?y:"",(k=U.name)!=null?k:"",(h=U.input)!=null?h:{}));else if(X==="server_tool_use")o.push(b({type:"server_tool_use",id:(P=U.id)!=null?P:"",name:(x=U.name)!=null?x:"",input:(g=U.input)!=null?g:{}}));else if(X==="web_search_tool_result"){let tt=(w=U.content)!=null?w:[],ut=[];for(let et of tt)if(et&&typeof et=="object"&&et.type==="web_search_result"){let nt=et;ut.push({type:"web_search_result",url:nt.url,title:nt.title,encrypted_content:nt.encrypted_content,page_age:nt.page_age})}o.push(b({type:"web_search_tool_result",tool_use_id:(f=U.tool_use_id)!=null?f:"",content:ut}))}else X==="bash_code_execution_tool_result"&&o.push(b({type:"bash_code_execution_tool_result",tool_use_id:(R=U.tool_use_id)!=null?R:"",content:(I=U.content)!=null?I:{}}))}let st=Pt(o,s);return Ct(st,n)}if(t.type==="content_block_start")if(((q=t.content_block)==null?void 0:q.type)==="thinking")o.push(b({type:"thinking",thinking:"",signature:""}));else if(((j=t.content_block)==null?void 0:j.type)==="text")o.push(b({type:"text",text:""}));else if(((O=t.content_block)==null?void 0:O.type)==="tool_use")s.push(rt((L=t.content_block.id)!=null?L:"",(W=t.content_block.name)!=null?W:"",{}));else if(((N=t.content_block)==null?void 0:N.type)==="server_tool_use")o.push(b({type:"server_tool_use",id:(V=t.content_block.id)!=null?V:"",name:($=t.content_block.name)!=null?$:"",input:(Z=t.content_block.input)!=null?Z:{}}));else if(((G=t.content_block)==null?void 0:G.type)==="web_search_tool_result"){let st=(Q=t.content_block.content)!=null?Q:[],U=[];for(let X of st)if(X&&typeof X=="object"&&X.type==="web_search_result"){let tt=X;U.push({type:"web_search_result",url:tt.url,title:tt.title,encrypted_content:tt.encrypted_content,page_age:tt.page_age})}o.push(b({type:"web_search_tool_result",tool_use_id:(H=t.content_block.tool_use_id)!=null?H:"",content:U}))}else((it=t.content_block)==null?void 0:it.type)==="bash_code_execution_tool_result"&&o.push(b({type:"bash_code_execution_tool_result",tool_use_id:(at=t.content_block.tool_use_id)!=null?at:"",content:(D=t.content_block.content)!=null?D:{}}));else if(t.type==="content_block_delta"){if(((ot=t.delta)==null?void 0:ot.type)==="thinking_delta")o.push(b({type:"thinking",thinking:(ct=t.delta.thinking)!=null?ct:"",signature:""}));else if(((gt=t.delta)==null?void 0:gt.type)==="text_delta")o.push(b({type:"text",text:(ht=t.delta.text)!=null?ht:""}));else if(((yt=t.delta)==null?void 0:yt.type)==="signature_delta")o.push(b({type:"thinking",thinking:"",signature:(Rt=t.delta.signature)!=null?Rt:""}));else if(((bt=t.delta)==null?void 0:bt.type)==="input_json_delta")(e==null?void 0:e[t.index])==="server_tool_use"?o.push(b({type:"server_tool_use",id:"",name:"",input:(kt=t.delta.partial_json)!=null?kt:{}})):s.push(rt("","",(wt=t.delta.partial_json)!=null?wt:""));else if(((xt=t.delta)==null?void 0:xt.type)==="citations_delta"&&t.delta.citation){let st=t.delta.citation,U=[ao(st)];o.push(b({type:"text",text:"",annotations:U}))}}let i=Pt(o,s);return Ct(i,n)},As=t=>typeof t=="string"&&t.startsWith("image/");function lo(t){var e,o,s,i;let n=t.web;return n&&typeof n=="object"?{uri:(e=n.uri)!=null?e:"",title:(o=n.title)!=null?o:""}:{uri:(s=t.uri)!=null?s:"",title:(i=t.title)!=null?i:""}}function Os(t){if(!t||typeof t!="object")return;let n=t.content,e=n==null?void 0:n.parts;if(!Array.isArray(e))return;let o=[];for(let s of e)s&&typeof s=="object"&&typeof s.text=="string"&&o.push(s.text);return o.length>0?o.join(""):void 0}function Is(t){var o,s,i,l;if(!t||typeof t!="object")return[];let n=(o=t.citations)!=null?o:[],e=[];for(let p of n){if(!p||typeof p!="object")continue;let u=(s=p.uri)!=null?s:"";if(!u)continue;let _=(i=p.startIndex)!=null?i:0,m=(l=p.endIndex)!=null?l:0;e.push({type:"url_citation",url:u,title:u,start_index:_,end_index:m})}return e}function Ls(t,n){if(!t||typeof t!="object")return[];let e=t.groundingMetadata,o=t.citationMetadata,s=Ns(e,n),i=Is(o);return[...s,...i]}function Ns(t,n){var p,u,_,m,y,k,h,P,x;let e=t&&typeof t=="object"?(p=t.groundingChunks)!=null?p:[]:[],o=t&&typeof t=="object"?(u=t.groundingSupports)!=null?u:[]:[];function s(g,w,f){let R=g.text;if(R!=null&&R!=="")return R;if(n!=null&&f>w)return n.slice(w,f)||void 0}if(o.length>0&&e.length>0){let g=[],w=new Set;for(let f of o){if(!f||typeof f!="object")continue;let R=(_=f.segment)!=null?_:{},I=(m=f.groundingChunkIndices)!=null?m:[],q=(y=R.startIndex)!=null?y:0,j=(k=R.endIndex)!=null?k:0,O=s(R,q,j);for(let L of I){if(typeof L!="number"||L>=e.length)continue;let W=e[L];if(!W||typeof W!="object")continue;let N=W.maps;if(N&&typeof N=="object"){let G=(h=N.uri)!=null?h:"",Q=(P=N.title)!=null?P:"",H=N.placeId;(G||Q)&&g.push(S(Y(S({type:"map_citation",url:G,title:Q||G},H!=null?{place_id:H}:{}),{start_index:q,end_index:j}),O!=null?{cited_text:O}:{}));continue}let V=W.retrievedContext;if(V&&typeof V=="object"){let G=(x=V.title)!=null?x:"";G&&!w.has(G)&&(w.add(G),g.push({type:"file_citation",file_id:G,filename:G,index:L}));continue}let{uri:$,title:Z}=lo(W);$&&g.push(S({type:"url_citation",url:$,title:Z||$,start_index:q,end_index:j},O!=null?{cited_text:O}:{}))}}return g}if(!t||typeof t!="object")return[];let i=[],l=new Set;return e.forEach((g,w)=>{var O,L,W;if(!g||typeof g!="object")return;let f=g,R=f.maps;if(R&&typeof R=="object"){let N=(O=R.uri)!=null?O:"",V=(L=R.title)!=null?L:"",$=R.placeId;(N||V)&&i.push(Y(S({type:"map_citation",url:N,title:V||N},$!=null?{place_id:$}:{}),{start_index:0,end_index:0}));return}let I=f.retrievedContext;if(I&&typeof I=="object"){let N=(W=I.title)!=null?W:"";N&&!l.has(N)&&(l.add(N),i.push({type:"file_citation",file_id:N,filename:N,index:w}));return}let{uri:q,title:j}=lo(f);q&&i.push({type:"url_citation",url:q,title:j||q,start_index:0,end_index:0})}),i}var uo=(t,n)=>{var u,_,m,y,k,h,P,x,g;let e=[],o=[];for(let w of(u=t.candidates)!=null?u:[])if(w.content&&w.content.parts&&Array.isArray(w.content.parts))for(let f of w.content.parts)if(f.text!=null)f.thought===!0?e.push(b({type:"thinking",thinking:f.text,signature:(_=f.thoughtSignature)!=null?_:""})):e.push(b(S({type:"text",text:f.text},f.thoughtSignature?{thought_signature:f.thoughtSignature}:{})));else if(f.functionCall)o.push(rt(f.functionCall.id||"",f.functionCall.name||"",f.functionCall.args||{}));else if(f.executableCode){let R=f.executableCode;e.push(b(S({type:"code",code:(m=R.code)!=null?m:""},R.language!=null?{language:R.language}:{})))}else if(f.codeExecutionResult){let R=f.codeExecutionResult;e.push(b({type:"code_execution_result",output:(y=R.output)!=null?y:"",outcome:(k=R.outcome)!=null?k:"OUTCOME_OK"}))}else{let R=f.inlineData;if(R&&f.thought!==!0){let I=(h=R.mimeType)!=null?h:"image/png",q=(P=R.data)!=null?P:"";if(As(I)&&q){let j={};f.thoughtSignature&&(j.thought_signature=f.thoughtSignature),f.aspectRatio!=null&&(j.aspect_ratio=f.aspectRatio),f.imageSize!=null&&(j.image_size=f.imageSize),e.push(b(S({type:"output_media",url:q,mime_type:I,media_type:"image"},Object.keys(j).length?{provider_metadata:j}:{})))}}}let s=(x=t.candidates)==null?void 0:x[0],i=Os(s),l=Ls(s,i);if(l.length>0)for(let w=0;w<e.length;w++){let f=e[w];if(f&&typeof f=="object"&&f.type==="text"){let R=(g=f.annotations)!=null?g:[];e[w]=Y(S({},f),{annotations:[...R,...l]})}}let p=Pt(e,o);return Ct(p,n)},wn=(t,n)=>{let e=[],o=[];for(let i of t.choices)if(i.delta){i.delta.content&&e.push(b({type:"text",text:i.delta.content}));let l=i.delta.tool_calls||i.delta.toolCalls;if(l&&Array.isArray(l))for(let p of l)p.function&&o.push(rt(p.id||"",p.function.name||"",p.function.arguments||""))}let s=Pt(e,o);return Ct(s,n)},po=(t,n)=>{var l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt,st,U,X,tt,ut,et,nt,Ot,It,Lt,Nt,Ut,qt,Mt,jt,Wt,$t,Kt,Ft,Gt,Dt,Bt,zt,Vt,Jt,Yt,Xt,Ht,Zt,Qt,vt,te,ee,ne,oe,se,re,ie,ae,le,ce,ue,pe,de,_e,me,fe,ge,he,ye,Re,be,ke,we,xe,Se,Pe,Ce,Te,Ee,Ae,Oe,Ie,Le,Ne,Ue,qe,Me,je,We,$e,Ke,Fe,Ge,De,Be,ze,Ve,Je,Ye,Xe,He,C,M,a,c,E,pt,jn,Wn,$n,Kn,Fn,Gn,Dn,Bn,zn,Vn,Jn,Yn,Xn,Hn,Zn,Qn,vn,to,eo,no;let e=[],o=[],s=t==null?void 0:t.type;if(s==="response.reasoning_summary_text.delta"){let r=(l=t==null?void 0:t.delta)!=null?l:"",A=(p=t==null?void 0:t.item_id)!=null?p:"";r&&e.push(b({type:"thinking",item_id:A,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_text.done"){let r=(u=t==null?void 0:t.text)!=null?u:"",A=(_=t==null?void 0:t.item_id)!=null?_:"";r&&e.push(b({type:"thinking",item_id:A,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_part.added"){let r=(m=t==null?void 0:t.part)!=null?m:{},A=(y=t==null?void 0:t.item_id)!=null?y:"";if((r==null?void 0:r.type)==="summary_text"){let d=(k=r==null?void 0:r.text)!=null?k:"";e.push(b({type:"thinking",item_id:A,thinking:d,signature:""}))}}else if(s==="response.reasoning_summary_part.done"){let r=(h=t==null?void 0:t.part)!=null?h:{},A=(P=t==null?void 0:t.item_id)!=null?P:"";if((r==null?void 0:r.type)==="summary_text"){let d=(x=r==null?void 0:r.text)!=null?x:"";d&&e.push(b({type:"thinking",item_id:A,thinking:d,signature:""}))}}else if(s==="response.function_call_arguments.delta"){let r=(g=t==null?void 0:t.item_id)!=null?g:"",A=(w=t==null?void 0:t.delta)!=null?w:"";A&&o.push(rt("","",A,r))}else if(s==="response.function_call_arguments.done"){let r=(f=t==null?void 0:t.item_id)!=null?f:"",A=(R=t==null?void 0:t.arguments)!=null?R:"";A&&o.push(rt("","",A,r))}else if(s==="response.output_item.added"){let r=(I=t==null?void 0:t.item)!=null?I:{},A=r==null?void 0:r.type,d=(q=r==null?void 0:r.id)!=null?q:"";A==="reasoning"?e.push(b({type:"thinking",thinking:"",signature:"",item_id:d})):A==="function_call"?o.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"","",d)):A==="message"?e.push(b({type:"text",item_id:d,text:""})):A==="code_interpreter_call"?e.push(b({type:"code",item_id:d,code:(j=r==null?void 0:r.code)!=null?j:"",container_id:(O=r==null?void 0:r.container_id)!=null?O:""})):A==="image_generation_call"?e.push(b({type:"output_media",item_id:d,url:"",mime_type:"image/png",media_type:"image"})):A==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:d,server_label:(L=r==null?void 0:r.server_label)!=null?L:"",tools:(W=r==null?void 0:r.tools)!=null?W:[]})):A==="mcp_call"?e.push(b({type:"mcp_call",item_id:d,name:(N=r==null?void 0:r.name)!=null?N:"",server_label:(V=r==null?void 0:r.server_label)!=null?V:"",arguments:($=r==null?void 0:r.arguments)!=null?$:"",output:r==null?void 0:r.output,error:r==null?void 0:r.error,approval_request_id:r==null?void 0:r.approval_request_id})):A==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:d,name:(Z=r==null?void 0:r.name)!=null?Z:"",arguments:(G=r==null?void 0:r.arguments)!=null?G:"",server_label:(Q=r==null?void 0:r.server_label)!=null?Q:""})):A==="shell_call"?e.push(b({type:"shell_call",item_id:d,call_id:(H=r==null?void 0:r.call_id)!=null?H:"",action:(it=r==null?void 0:r.action)!=null?it:{},status:(at=r==null?void 0:r.status)!=null?at:"in_progress"})):A==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:d,call_id:(D=r==null?void 0:r.call_id)!=null?D:"",output:(ot=r==null?void 0:r.output)!=null?ot:[],status:(ct=r==null?void 0:r.status)!=null?ct:"in_progress"})):A==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:d,call_id:(gt=r==null?void 0:r.call_id)!=null?gt:"",operation:(ht=r==null?void 0:r.operation)!=null?ht:{},status:(yt=r==null?void 0:r.status)!=null?yt:"in_progress"})):A==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:d,call_id:(Rt=r==null?void 0:r.call_id)!=null?Rt:"",output:(bt=r==null?void 0:r.output)!=null?bt:"",status:(kt=r==null?void 0:r.status)!=null?kt:"in_progress"}))}else if(s==="response.content_part.added"){let r=(wt=t==null?void 0:t.part)!=null?wt:{},A=(xt=r==null?void 0:r.type)!=null?xt:"output_text",d=(st=t==null?void 0:t.item_id)!=null?st:"";A==="output_text"&&e.push(b({type:"text",item_id:d,text:(U=r==null?void 0:r.text)!=null?U:"",annotations:(r==null?void 0:r.annotations)||[]}))}else if(s==="response.content_part.done"){let r=(X=t==null?void 0:t.part)!=null?X:{},A=(tt=r==null?void 0:r.type)!=null?tt:"output_text",d=(ut=t==null?void 0:t.item_id)!=null?ut:"";A==="output_text"&&e.push(b({type:"text",item_id:d,text:(et=r==null?void 0:r.text)!=null?et:"",annotations:(r==null?void 0:r.annotations)||[]}))}else if(s==="response.output_text.annotation.added"){let r=(t==null?void 0:t.annotation)||{},A=r==null?void 0:r.type,d=null;A==="url_citation"?d={type:"url_citation",title:(nt=r==null?void 0:r.title)!=null?nt:"",url:(Ot=r==null?void 0:r.url)!=null?Ot:"",start_index:(It=r==null?void 0:r.start_index)!=null?It:0,end_index:(Lt=r==null?void 0:r.end_index)!=null?Lt:0}:A==="file_citation"?d={type:"file_citation",index:(Nt=r==null?void 0:r.index)!=null?Nt:0,file_id:(Ut=r==null?void 0:r.file_id)!=null?Ut:"",filename:(qt=r==null?void 0:r.filename)!=null?qt:""}:d=r,e.push(b({type:"text",item_id:(Mt=t==null?void 0:t.item_id)!=null?Mt:"",text:"",annotations:[d]}))}else if(s==="response.code_interpreter_call.in_progress")e.push(b({type:"code",item_id:(jt=t==null?void 0:t.item_id)!=null?jt:"",code:(Wt=t==null?void 0:t.code)!=null?Wt:"",container_id:($t=t==null?void 0:t.container_id)!=null?$t:""}));else if(s==="response.code_interpreter_call_code.delta")e.push(b({type:"code",item_id:(Kt=t==null?void 0:t.item_id)!=null?Kt:"",code:(Ft=t==null?void 0:t.delta)!=null?Ft:"",container_id:(Gt=t==null?void 0:t.container_id)!=null?Gt:""}));else if(s==="response.output_text.delta"){let r=(Dt=t==null?void 0:t.delta)!=null?Dt:"";r&&e.push(b({type:"text",item_id:(Bt=t==null?void 0:t.item_id)!=null?Bt:"",text:r}))}else if(s==="response.output_text.done")e.push(b({type:"text",item_id:(zt=t==null?void 0:t.item_id)!=null?zt:"",text:(Vt=t==null?void 0:t.text)!=null?Vt:""}));else if(s==="response.output_item.done"){let r=(Jt=t==null?void 0:t.item)!=null?Jt:{},A=r==null?void 0:r.type,d=(Yt=r==null?void 0:r.id)!=null?Yt:"";if(A==="reasoning"){let K=((Xt=r==null?void 0:r.summary)!=null?Xt:[]).map(dt=>{var J;return(J=dt==null?void 0:dt.text)!=null?J:""}).join("");e.push(b({type:"thinking",item_id:d,thinking:K,signature:""}))}else if(A==="function_call")o.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"",(r==null?void 0:r.arguments)||"",d));else if(A==="message"){let B=(Ht=r==null?void 0:r.content)!=null?Ht:[];for(let K of B)(K==null?void 0:K.type)==="output_text"&&e.push(b({type:"text",item_id:d,text:(Zt=K==null?void 0:K.text)!=null?Zt:""}))}else if(A==="code_interpreter_call")e.push(b({type:"code",item_id:d,code:(Qt=r==null?void 0:r.code)!=null?Qt:"",container_id:(vt=r==null?void 0:r.container_id)!=null?vt:""}));else if(A==="image_generation_call"){let B=(te=r==null?void 0:r.result)!=null?te:"",dt=((ee=r==null?void 0:r.output_format)!=null?ee:"png")==="webp"?"image/webp":"image/png",J={};for(let mt of["revised_prompt","background","size","quality","output_format"])(r==null?void 0:r[mt])!=null&&(J[mt]=r[mt]);e.push(b(S({type:"output_media",item_id:d,url:B,mime_type:dt,media_type:"image"},Object.keys(J).length?{provider_metadata:J}:{})))}else A==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:d,server_label:(ne=r==null?void 0:r.server_label)!=null?ne:"",tools:(oe=r==null?void 0:r.tools)!=null?oe:[],error:r==null?void 0:r.error})):A==="mcp_call"?e.push(b({type:"mcp_call",item_id:d,name:(se=r==null?void 0:r.name)!=null?se:"",server_label:(re=r==null?void 0:r.server_label)!=null?re:"",arguments:(ie=r==null?void 0:r.arguments)!=null?ie:"",output:r==null?void 0:r.output,error:r==null?void 0:r.error,approval_request_id:r==null?void 0:r.approval_request_id})):A==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:d,name:(ae=r==null?void 0:r.name)!=null?ae:"",arguments:(le=r==null?void 0:r.arguments)!=null?le:"",server_label:(ce=r==null?void 0:r.server_label)!=null?ce:""})):A==="shell_call"?e.push(b({type:"shell_call",item_id:d,call_id:(ue=r==null?void 0:r.call_id)!=null?ue:"",action:(pe=r==null?void 0:r.action)!=null?pe:{},status:(de=r==null?void 0:r.status)!=null?de:"completed"})):A==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:d,call_id:(_e=r==null?void 0:r.call_id)!=null?_e:"",output:(me=r==null?void 0:r.output)!=null?me:[],status:(fe=r==null?void 0:r.status)!=null?fe:"completed"})):A==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:d,call_id:(ge=r==null?void 0:r.call_id)!=null?ge:"",operation:(he=r==null?void 0:r.operation)!=null?he:{},status:(ye=r==null?void 0:r.status)!=null?ye:"completed"})):A==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:d,call_id:(Re=r==null?void 0:r.call_id)!=null?Re:"",output:(be=r==null?void 0:r.output)!=null?be:"",status:(ke=r==null?void 0:r.status)!=null?ke:"completed"}))}else if(s==="response.code_interpreter_call_code.done")e.push(b({type:"code",item_id:(we=t==null?void 0:t.item_id)!=null?we:"",code:(xe=t==null?void 0:t.code)!=null?xe:"",container_id:(Se=t==null?void 0:t.container_id)!=null?Se:""}));else if(s==="response.code_interpreter_call.interpreting")e.push(b({type:"code",item_id:(Pe=t==null?void 0:t.item_id)!=null?Pe:"",code:(Ce=t==null?void 0:t.code)!=null?Ce:"",container_id:(Te=t==null?void 0:t.container_id)!=null?Te:""}));else if(s==="response.code_interpreter_call.completed")e.push(b({type:"code",item_id:(Ee=t==null?void 0:t.item_id)!=null?Ee:"",code:(Ae=t==null?void 0:t.code)!=null?Ae:"",container_id:(Oe=t==null?void 0:t.container_id)!=null?Oe:""}));else if(s==="response.image_generation_call.in_progress")e.push(b({type:"output_media",item_id:(Ie=t==null?void 0:t.item_id)!=null?Ie:"",url:"",mime_type:"image/png",media_type:"image"}));else if(s==="response.image_generation_call.generating")e.push(b({type:"output_media",item_id:(Le=t==null?void 0:t.item_id)!=null?Le:"",url:"",mime_type:"image/png",media_type:"image"}));else if(s==="response.image_generation_call.partial_image"){let A=((Ne=t==null?void 0:t.output_format)!=null?Ne:"png")==="webp"?"image/webp":"image/png",d={};for(let B of["background","size","quality","output_format"])(t==null?void 0:t[B])!=null&&(d[B]=t[B]);e.push(b(S({type:"output_media",item_id:(Ue=t==null?void 0:t.item_id)!=null?Ue:"",url:(qe=t==null?void 0:t.partial_image_b64)!=null?qe:"",mime_type:A,media_type:"image"},Object.keys(d).length?{provider_metadata:d}:{})))}else if(s==="response.shell_call_command.added")e.push(b({type:"shell_call",action:{command:(Me=t==null?void 0:t.command)!=null?Me:""}}));else if(s==="response.shell_call_command.delta")e.push(b({type:"shell_call",action:{command:(je=t==null?void 0:t.delta)!=null?je:""}}));else if(s==="response.shell_call_command.done")e.push(b({type:"shell_call",action:{command:(We=t==null?void 0:t.command)!=null?We:""}}));else if(s==="response.shell_call_output_content.delta")e.push(b({type:"shell_call_output",item_id:($e=t==null?void 0:t.item_id)!=null?$e:"",output:[(Ke=t==null?void 0:t.delta)!=null?Ke:{}]}));else if(s==="response.shell_call_output_content.done")e.push(b({type:"shell_call_output",item_id:(Fe=t==null?void 0:t.item_id)!=null?Fe:"",output:(Ge=t==null?void 0:t.output)!=null?Ge:[]}));else if(s==="response.apply_patch_call_operation_diff.delta")e.push(b({type:"apply_patch_call",item_id:(De=t==null?void 0:t.item_id)!=null?De:"",operation:{diff:(Be=t==null?void 0:t.delta)!=null?Be:""}}));else if(s==="response.apply_patch_call_operation_diff.done")e.push(b({type:"apply_patch_call",item_id:(ze=t==null?void 0:t.item_id)!=null?ze:"",operation:{diff:(Ve=t==null?void 0:t.diff)!=null?Ve:""}}));else if(s==="response.completed"){let r=(Je=t==null?void 0:t.response)!=null?Je:{},A=(Ye=r==null?void 0:r.output)!=null?Ye:[];for(let d of A){let B=d==null?void 0:d.type,K=(Xe=d==null?void 0:d.id)!=null?Xe:"";if(B==="reasoning"){let J=((He=d==null?void 0:d.summary)!=null?He:[]).map(mt=>{var St;return(St=mt==null?void 0:mt.text)!=null?St:""}).join("");e.push(b({type:"thinking",item_id:K,thinking:J,signature:""}))}else if(B==="function_call")o.push(rt((d==null?void 0:d.call_id)||"",(d==null?void 0:d.name)||"",(d==null?void 0:d.arguments)||"",K));else if(B==="message"){let dt=(C=d==null?void 0:d.content)!=null?C:[];for(let J of dt)(J==null?void 0:J.type)==="output_text"&&e.push(b({type:"text",item_id:K,text:(M=J==null?void 0:J.text)!=null?M:"",annotations:(J==null?void 0:J.annotations)||[]}))}else if(B==="code_interpreter_call")e.push(b({type:"code",item_id:K,code:(a=d==null?void 0:d.code)!=null?a:"",container_id:(c=d==null?void 0:d.container_id)!=null?c:""}));else if(B==="image_generation_call"){let dt=(E=d==null?void 0:d.result)!=null?E:"",mt=((pt=d==null?void 0:d.output_format)!=null?pt:"png")==="webp"?"image/webp":"image/png",St={};for(let Rn of["revised_prompt","background","size","quality","output_format"])(d==null?void 0:d[Rn])!=null&&(St[Rn]=d[Rn]);e.push(b(S({type:"output_media",item_id:K,url:dt,mime_type:mt,media_type:"image"},Object.keys(St).length?{provider_metadata:St}:{})))}else B==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:K,server_label:(jn=d==null?void 0:d.server_label)!=null?jn:"",tools:(Wn=d==null?void 0:d.tools)!=null?Wn:[],error:d==null?void 0:d.error})):B==="mcp_call"?e.push(b({type:"mcp_call",item_id:K,name:($n=d==null?void 0:d.name)!=null?$n:"",server_label:(Kn=d==null?void 0:d.server_label)!=null?Kn:"",arguments:(Fn=d==null?void 0:d.arguments)!=null?Fn:"",output:d==null?void 0:d.output,error:d==null?void 0:d.error,approval_request_id:d==null?void 0:d.approval_request_id})):B==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:K,name:(Gn=d==null?void 0:d.name)!=null?Gn:"",arguments:(Dn=d==null?void 0:d.arguments)!=null?Dn:"",server_label:(Bn=d==null?void 0:d.server_label)!=null?Bn:""})):B==="shell_call"?e.push(b({type:"shell_call",item_id:K,call_id:(zn=d==null?void 0:d.call_id)!=null?zn:"",action:(Vn=d==null?void 0:d.action)!=null?Vn:{},status:(Jn=d==null?void 0:d.status)!=null?Jn:"completed"})):B==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:K,call_id:(Yn=d==null?void 0:d.call_id)!=null?Yn:"",output:(Xn=d==null?void 0:d.output)!=null?Xn:[],status:(Hn=d==null?void 0:d.status)!=null?Hn:"completed"})):B==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:K,call_id:(Zn=d==null?void 0:d.call_id)!=null?Zn:"",operation:(Qn=d==null?void 0:d.operation)!=null?Qn:{},status:(vn=d==null?void 0:d.status)!=null?vn:"completed"})):B==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:K,call_id:(to=d==null?void 0:d.call_id)!=null?to:"",output:(eo=d==null?void 0:d.output)!=null?eo:"",status:(no=d==null?void 0:d.status)!=null?no:"completed"}))}}let i=Pt(e,o||[]);return Ct(i,n)},_o=(t,n)=>{var i,l,p,u;let e=[],o=[];if("contentBlockDelta"in t){let _=((i=t.contentBlockDelta)==null?void 0:i.delta)||{};if("reasoningContent"in _){let m=((l=_.reasoningContent)==null?void 0:l.text)||"",y=((p=_.reasoningContent)==null?void 0:p.signature)||"";e.push(b({type:"thinking",thinking:m,signature:y}))}else if("text"in _)e.push(b({type:"text",text:_.text||""}));else if("toolUse"in _){let m=_.toolUse||{};o.push(rt(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in t){let _=((u=t.contentBlockStart)==null?void 0:u.start)||{};if("toolUse"in _){let m=_.toolUse||{};o.push(rt(m.toolUseId||"",m.name||"",""))}}let s=Pt(e,o);return Ct(s,n)},Us=["size","quality","background","output_format"],mo=(t,n)=>{var i,l,p,u,_,m,y;let e=[],o=(i=t==null?void 0:t.type)!=null?i:"";if(o==="image_generation.partial_image"){let k=(l=t==null?void 0:t.b64_json)!=null?l:"";if(k){let h=(p=t==null?void 0:t.output_format)!=null?p:"png",P=(u=io[h])!=null?u:"image/png",x={},g=t==null?void 0:t.partial_image_index;g!=null&&(x.partial_image_index=g),e.push(b(S({type:"output_media",url:k,mime_type:P,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}}else if(o==="image_generation.completed"){let k=(_=t==null?void 0:t.b64_json)!=null?_:"",h=(m=t==null?void 0:t.output_format)!=null?m:"png",P=(y=io[h])!=null?y:"image/png",x={};for(let g of Us)(t==null?void 0:t[g])!=null&&(x[g]=t[g]);e.push(b(S({type:"output_media",url:k,mime_type:P,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}return{prompt_template:{type:"completion",content:e,input_variables:[]},metadata:n}};var Ro=["openai","openai.azure"],ln=t=>{var s,i,l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt,st,U,X,tt,ut,et,nt,Ot,It,Lt,Nt,Ut,qt,Mt,jt,Wt,$t,Kt,Ft,Gt,Dt,Bt,zt,Vt,Jt,Yt,Xt,Ht,Zt,Qt,vt,te,ee,ne,oe,se,re,ie,ae,le,ce,ue,pe,de,_e,me,fe,ge,he,ye,Re,be,ke,we,xe,Se,Pe,Ce,Te,Ee,Ae,Oe,Ie,Le,Ne,Ue,qe,Me,je,We,$e,Ke,Fe,Ge,De,Be,ze,Ve,Je,Ye,Xe,He;let n={id:null,object:"response",created_at:null,status:null,error:null,incomplete_details:null,instructions:null,max_output_tokens:null,model:null,output:[],parallel_tool_calls:!0,previous_response_id:null,reasoning:{},store:!0,temperature:1,text:void 0,tool_choice:"auto",tools:[],top_p:1,truncation:"disabled",usage:null,user:null,metadata:{}},e={},o={};for(let C of t){let M=C==null?void 0:C.type;if(M==="response.created"){let a=C.response||{};n.id=(s=a.id)!=null?s:n.id,n.created_at=(i=a.created_at)!=null?i:n.created_at,n.model=(l=a.model)!=null?l:n.model,n.status=(p=a.status)!=null?p:n.status,n.parallel_tool_calls=(u=a.parallel_tool_calls)!=null?u:n.parallel_tool_calls,n.temperature=(_=a.temperature)!=null?_:n.temperature,n.tool_choice=(m=a.tool_choice)!=null?m:n.tool_choice,n.tools=(y=a.tools)!=null?y:n.tools,n.top_p=(k=a.top_p)!=null?k:n.top_p,n.truncation=(h=a.truncation)!=null?h:n.truncation,n.max_output_tokens=(P=a.max_output_tokens)!=null?P:n.max_output_tokens,n.previous_response_id=(x=a.previous_response_id)!=null?x:n.previous_response_id,n.store=(g=a.store)!=null?g:n.store,n.user=(w=a.user)!=null?w:n.user,n.metadata=(f=a.metadata)!=null?f:n.metadata;let c=a.text;c&&(n.text=c);let E=a.reasoning;E&&(n.reasoning=E);continue}if(M==="response.in_progress"){let a=C.response||{};n.status=(R=a.status)!=null?R:n.status;continue}if(M==="response.output_item.added"){let a=C.item||{},c=a.id,E=a.type,pt=C.output_index;pt!=null&&c&&(o[pt]=c),E==="reasoning"?e[c]={type:"reasoning",id:c,summary:[],status:(I=a.status)!=null?I:"in_progress"}:E==="function_call"?e[c]={type:"function_call",id:c,call_id:a.call_id,name:a.name,arguments:"",status:(q=a.status)!=null?q:"in_progress"}:E==="message"?e[c]={type:"message",id:c,role:(j=a.role)!=null?j:"assistant",content:[],status:(O=a.status)!=null?O:"in_progress"}:E==="code_interpreter_call"?e[c]={type:"code_interpreter_call",id:c,container_id:a.container_id,code:(L=a.code)!=null?L:"",status:(W=a.status)!=null?W:"in_progress"}:E==="image_generation_call"?e[c]={type:"image_generation_call",id:c,status:(N=a.status)!=null?N:"in_progress",revised_prompt:(V=a.revised_prompt)!=null?V:"",result:($=a.result)!=null?$:"",background:a.background,size:a.size,quality:a.quality,output_format:a.output_format}:E==="web_search_call"?e[c]={type:"web_search_call",id:c,status:(Z=a.status)!=null?Z:"in_progress"}:E==="file_search_call"?e[c]={type:"file_search_call",id:c,status:(G=a.status)!=null?G:"in_progress"}:E==="mcp_list_tools"?e[c]={type:"mcp_list_tools",id:c,server_label:(Q=a.server_label)!=null?Q:"",tools:(H=a.tools)!=null?H:[],error:(it=a.error)!=null?it:null}:E==="mcp_call"?e[c]={type:"mcp_call",id:c,name:(at=a.name)!=null?at:"",server_label:(D=a.server_label)!=null?D:"",arguments:(ot=a.arguments)!=null?ot:"",output:(ct=a.output)!=null?ct:null,error:(gt=a.error)!=null?gt:null,approval_request_id:(ht=a.approval_request_id)!=null?ht:null,status:(yt=a.status)!=null?yt:"in_progress"}:E==="mcp_approval_request"?e[c]={type:"mcp_approval_request",id:c,name:(Rt=a.name)!=null?Rt:"",arguments:(bt=a.arguments)!=null?bt:"",server_label:(kt=a.server_label)!=null?kt:""}:E==="shell_call"?e[c]={type:"shell_call",id:c,call_id:(wt=a.call_id)!=null?wt:"",action:(xt=a.action)!=null?xt:{},status:(st=a.status)!=null?st:"in_progress"}:E==="shell_call_output"?e[c]={type:"shell_call_output",id:c,call_id:(U=a.call_id)!=null?U:"",output:(X=a.output)!=null?X:[],status:(tt=a.status)!=null?tt:"in_progress"}:E==="apply_patch_call"?e[c]={type:"apply_patch_call",id:c,call_id:(ut=a.call_id)!=null?ut:"",operation:(et=a.operation)!=null?et:{},status:(nt=a.status)!=null?nt:"in_progress"}:E==="apply_patch_call_output"&&(e[c]={type:"apply_patch_call_output",id:c,call_id:(Ot=a.call_id)!=null?Ot:"",output:(It=a.output)!=null?It:"",status:(Lt=a.status)!=null?Lt:"in_progress"});continue}if(M==="response.reasoning_summary_part.added"){let a=C.item_id,c=C.part||{};if(a in e&&e[a].type==="reasoning"){let E={type:(Nt=c.type)!=null?Nt:"summary_text",text:(Ut=c.text)!=null?Ut:""};e[a].summary.push(E)}continue}if(M==="response.reasoning_summary_text.delta"){let a=C.item_id,c=(qt=C.delta)!=null?qt:"",E=(Mt=C.summary_index)!=null?Mt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=E;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[E].text+=c}continue}if(M==="response.reasoning_summary_text.done"){let a=C.item_id,c=(jt=C.text)!=null?jt:"",E=(Wt=C.summary_index)!=null?Wt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=E;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[E].text=c}continue}if(M==="response.reasoning_summary_part.done"){let a=C.item_id,c=C.part||{};if(a in e&&e[a].type==="reasoning"){let E=($t=C.summary_index)!=null?$t:0;E<e[a].summary.length&&(e[a].summary[E]={type:(Kt=c.type)!=null?Kt:"summary_text",text:(Ft=c.text)!=null?Ft:""})}continue}if(M==="response.function_call_arguments.delta"){let a=C.item_id,c=(Gt=C.delta)!=null?Gt:"";a in e&&(e[a].arguments=`${e[a].arguments||""}${c}`);continue}if(M==="response.function_call_arguments.done"){let a=C.item_id,c=(Dt=C.arguments)!=null?Dt:"";a in e&&(e[a].arguments=c);continue}if(M==="response.content_part.added"){let a=C.part||{},c=Object.values(e).find(E=>E.type==="message");if(c){let E={type:(Bt=a.type)!=null?Bt:"output_text",text:(zt=a.text)!=null?zt:"",annotations:(Vt=a.annotations)!=null?Vt:[]};c.content.push(E)}continue}if(M==="response.output_text.delta"){let a=(Jt=C.delta)!=null?Jt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let E=c.content[c.content.length-1];E&&E.type==="output_text"&&(E.text=`${E.text||""}${a}`);break}continue}if(M==="response.output_text.done"){let a=(Yt=C.text)!=null?Yt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let E=c.content[c.content.length-1];E&&E.type==="output_text"&&(E.text=a);break}continue}if(M==="response.output_item.done"){let a=C.item||{},c=a.id;c in e&&(e[c].status=(Xt=a.status)!=null?Xt:"completed",a.type==="reasoning"?e[c].summary=(Ht=a.summary)!=null?Ht:e[c].summary:a.type==="function_call"?(e[c].arguments=(Zt=a.arguments)!=null?Zt:e[c].arguments,e[c].call_id=(Qt=a.call_id)!=null?Qt:e[c].call_id,e[c].name=(vt=a.name)!=null?vt:e[c].name):a.type==="message"?(e[c].content=(te=a.content)!=null?te:e[c].content,e[c].role=(ee=a.role)!=null?ee:e[c].role):a.type==="image_generation_call"?(e[c].result=(ne=a.result)!=null?ne:e[c].result,e[c].revised_prompt=(oe=a.revised_prompt)!=null?oe:e[c].revised_prompt,e[c].background=(se=a.background)!=null?se:e[c].background,e[c].size=(re=a.size)!=null?re:e[c].size,e[c].quality=(ie=a.quality)!=null?ie:e[c].quality,e[c].output_format=(ae=a.output_format)!=null?ae:e[c].output_format):a.type==="code_interpreter_call"?(e[c].code=(le=a.code)!=null?le:e[c].code,e[c].container_id=(ce=a.container_id)!=null?ce:e[c].container_id):a.type==="mcp_list_tools"?(e[c].tools=(ue=a.tools)!=null?ue:e[c].tools,e[c].error=(pe=a.error)!=null?pe:e[c].error):a.type==="mcp_call"?(e[c].name=(de=a.name)!=null?de:e[c].name,e[c].arguments=(_e=a.arguments)!=null?_e:e[c].arguments,e[c].output=(me=a.output)!=null?me:e[c].output,e[c].error=(fe=a.error)!=null?fe:e[c].error,e[c].server_label=(ge=a.server_label)!=null?ge:e[c].server_label):a.type==="mcp_approval_request"?(e[c].name=(he=a.name)!=null?he:e[c].name,e[c].arguments=(ye=a.arguments)!=null?ye:e[c].arguments,e[c].server_label=(Re=a.server_label)!=null?Re:e[c].server_label):a.type==="shell_call"?(e[c].action=(be=a.action)!=null?be:e[c].action,e[c].call_id=(ke=a.call_id)!=null?ke:e[c].call_id):a.type==="shell_call_output"?(e[c].output=(we=a.output)!=null?we:e[c].output,e[c].call_id=(xe=a.call_id)!=null?xe:e[c].call_id):a.type==="apply_patch_call"?(e[c].operation=(Se=a.operation)!=null?Se:e[c].operation,e[c].call_id=(Pe=a.call_id)!=null?Pe:e[c].call_id):a.type==="apply_patch_call_output"?(e[c].output=(Ce=a.output)!=null?Ce:e[c].output,e[c].call_id=(Te=a.call_id)!=null?Te:e[c].call_id):(a.type==="web_search_call"||a.type==="file_search_call")&&(e[c].action=a.action),n.output.push(e[c]));continue}if(M==="response.image_generation_call.in_progress"){let a=C.item_id;a in e&&(e[a].status="in_progress");continue}if(M==="response.image_generation_call.generating"){let a=C.item_id;a in e&&(e[a].status="generating");continue}if(M==="response.image_generation_call.partial_image"){let a=C.item_id;a in e&&(e[a].result=(Ee=C.partial_image_b64)!=null?Ee:e[a].result,e[a].background=(Ae=C.background)!=null?Ae:e[a].background,e[a].size=(Oe=C.size)!=null?Oe:e[a].size,e[a].quality=(Ie=C.quality)!=null?Ie:e[a].quality,e[a].output_format=(Le=C.output_format)!=null?Le:e[a].output_format);continue}if(M==="response.shell_call_command.added"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[C.command_index]=(Ne=C.command)!=null?Ne:"",e[a].action=c}continue}if(M==="response.shell_call_command.delta"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]);let E=(Ue=C.command_index)!=null?Ue:0;c.commands[E]=((qe=c.commands[E])!=null?qe:"")+((Me=C.delta)!=null?Me:""),e[a].action=c}continue}if(M==="response.shell_call_command.done"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[C.command_index]=(je=C.command)!=null?je:"",e[a].action=c}continue}if(M==="response.shell_call_output_content.delta"){let a=C.item_id;if(a&&a in e){e[a].output||(e[a].output=[]);let c=(We=C.command_index)!=null?We:0,E=($e=e[a].output[c])!=null?$e:{stdout:"",stderr:""},pt=(Ke=C.delta)!=null?Ke:{};pt.stdout&&(E.stdout=((Fe=E.stdout)!=null?Fe:"")+pt.stdout),pt.stderr&&(E.stderr=((Ge=E.stderr)!=null?Ge:"")+pt.stderr),e[a].output[c]=E}continue}if(M==="response.shell_call_output_content.done"){let a=C.item_id;a&&a in e&&(e[a].output=(De=C.output)!=null?De:e[a].output);continue}if(M==="response.apply_patch_call_operation_diff.delta"){let a=C.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=((Be=c.diff)!=null?Be:"")+((ze=C.delta)!=null?ze:""),e[a].operation=c}continue}if(M==="response.apply_patch_call_operation_diff.done"){let a=C.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=(Ve=C.diff)!=null?Ve:c.diff,e[a].operation=c}continue}if(M==="response.completed"){let a=C.response||{};n.status=(Ye=(Je=a.status)!=null?Je:n.status)!=null?Ye:"completed",n.usage=(Xe=a.usage)!=null?Xe:n.usage,n.output=(He=a.output)!=null?He:n.output,a.reasoning&&(n.reasoning=a.reasoning);continue}}return n},xn=t=>{var p,u,_,m,y,k,h,P,x,g;let n=null,e,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},s=t.at(-1);if(!s)return o;let i;for(let w of t){if(w.choices.length===0)continue;let f=w.choices[0].delta;f.content&&(n=`${n||""}${f.content||""}`),f.function_call&&(e={name:`${e?e.name:""}${f.function_call.name||""}`,arguments:`${e?e.arguments:""}${f.function_call.arguments||""}`});let R=(p=f.tool_calls)==null?void 0:p[0];if(R){i=i||[];let I=i.at(-1);if(!I||R.id){i.push({id:R.id||"",type:R.type||"function",function:{name:((u=R.function)==null?void 0:u.name)||"",arguments:((_=R.function)==null?void 0:_.arguments)||""}});continue}I.function.name=`${I.function.name}${((m=R.function)==null?void 0:m.name)||""}`,I.function.arguments=`${I.function.arguments}${((y=R.function)==null?void 0:y.arguments)||""}`}}let l=t[0].choices.at(0);return o.choices.push({finish_reason:(k=l==null?void 0:l.finish_reason)!=null?k:"stop",index:(h=l==null?void 0:l.index)!=null?h:0,logprobs:(P=l==null?void 0:l.logprobs)!=null?P:null,message:{role:"assistant",content:n,function_call:e||void 0,tool_calls:i||void 0,refusal:(x=l==null?void 0:l.delta.refusal)!=null?x:null}}),o.id=s.id,o.model=s.model,o.created=s.created,o.system_fingerprint=s.system_fingerprint,o.usage=(g=s.usage)!=null?g:void 0,o},fo=t=>{let n={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},e=t.at(-1);if(!e)return n;let o="";for(let s of t)s.choices.length>0&&s.choices[0].text&&(o=`${o}${s.choices[0].text}`);return n.choices[0].text=o,n.id=e.id,n.created=e.created,n.model=e.model,n.system_fingerprint=e.system_fingerprint,n.usage=e.usage,n},Sn=t=>{var m,y,k,h,P,x;let n={id:"",model:"",content:[],role:"assistant",type:"message",stop_reason:"stop_sequence",stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,server_tool_use:null,service_tier:null}};if(!t.at(-1))return n;let o=null,s=null,i="",l="",p="",u="",_={};for(let g of t)if(g.type==="message_start")n=S({},g.message);else if(g.type==="content_block_start")o=S({},g.content_block),s="index"in g&&typeof g.index=="number"?g.index:null,o.type==="thinking"?(i="",l=""):o.type==="text"?p="":(o.type==="tool_use"||o.type==="server_tool_use")&&(u="");else if(g.type==="content_block_delta"){let w=g.delta,f="index"in g&&typeof g.index=="number"?g.index:null;if((w==null?void 0:w.type)==="citations_delta"){let R=w.citation;if(R&&typeof R=="object"&&R.type==="web_search_result_location"&&f!==null){let I=S(S({type:"url_citation",url:(m=R.url)!=null?m:"",title:(y=R.title)!=null?y:"",start_index:(k=R.start_index)!=null?k:0,end_index:(h=R.end_index)!=null?h:0},R.cited_text!=null?{cited_text:R.cited_text}:{}),R.encrypted_index!=null?{encrypted_index:R.encrypted_index}:{});_[f]||(_[f]=[]),_[f].push(I)}}else o!==null&&(o.type==="thinking"?(w&&"signature"in w&&(i=w.signature||""),w&&"thinking"in w&&(l+=w.thinking||"")):o.type==="text"?w&&"text"in w&&(p+=w.text||""):(o.type==="tool_use"||o.type==="server_tool_use")&&(w==null?void 0:w.type)==="input_json_delta"&&(u+=w.partial_json||""))}else if(g.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=i,o.thinking=l;else if(o.type==="text")o.text=p,o.citations=null,s!==null&&((P=_[s])!=null&&P.length)&&(o.annotations=_[s]);else if(o.type==="tool_use"||o.type==="server_tool_use")try{o.input=u?JSON.parse(u):{}}catch(w){o.input={}}n.content.push(o),o=null,s=null,i="",l="",p="",u=""}else g.type==="message_delta"&&("usage"in g&&g.usage&&(n.usage=Y(S({},n.usage),{output_tokens:(x=g.usage.output_tokens)!=null?x:0})),"delta"in g&&g.delta&&("stop_reason"in g.delta&&g.delta.stop_reason!==void 0&&(n.stop_reason=g.delta.stop_reason),"stop_sequence"in g.delta&&g.delta.stop_sequence!==void 0&&(n.stop_sequence=g.delta.stop_sequence)));return n},go=t=>{let n={completion:"",id:"",model:"",stop_reason:"",type:"completion"},e=t.at(-1);if(!e)return n;let o="";for(let s of t)o=`${o}${s.completion}`;return n.completion=o,n.id=e.id,n.model=e.model,n.stop_reason=e.stop_reason,n},qs=t=>{var l,p,u,_,m,y,k,h,P,x;let n=null,e={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=t.at(-1).data;if(!o)return e;let s;for(let g of t){if(g.data.choices.length===0)continue;let w=g.data.choices[0].delta;w.content&&(n=`${n||""}${w.content||""}`);let f=(l=w.toolCalls)==null?void 0:l[0];if(f){s=s||[];let R=s.at(-1);if(!R||f.id){s.push({id:f.id||"",type:f.type||"function",function:{name:((p=f.function)==null?void 0:p.name)||"",arguments:((u=f.function)==null?void 0:u.arguments)||""}});continue}R.function.name=`${R.function.name}${((_=f.function)==null?void 0:_.name)||""}`,R.function.arguments=`${R.function.arguments}${((m=f.function)==null?void 0:m.arguments)||""}`}}let i=t[0].data.choices.at(0);return e.choices.push({finish_reason:(y=i==null?void 0:i.finish_reason)!=null?y:"stop",index:(k=i==null?void 0:i.index)!=null?k:0,logprobs:(h=i==null?void 0:i.logprobs)!=null?h:null,message:{role:"assistant",content:n,tool_calls:s||void 0,refusal:(P=i==null?void 0:i.delta.refusal)!=null?P:null}}),e.id=o.id,e.model=o.model,e.created=o.created,e.usage=(x=o.usage)!=null?x:void 0,e},ho=t=>{let n={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},e=[],o=null,s="",i="",l="",p="";for(let u of t)if("contentBlockStart"in u){let _=u.contentBlockStart;if("start"in _&&"toolUse"in _.start){let m=_.start.toolUse;o={toolUse:{toolUseId:m.toolUseId,name:m.name}},s=""}}else if("contentBlockDelta"in u){let _=u.contentBlockDelta.delta;if("text"in _)i+=_.text;else if("reasoningContent"in _){let m=_.reasoningContent;"text"in m?p+=m.text:"signature"in m&&(l+=m.signature)}else if("toolUse"in _&&"input"in _.toolUse){let m=_.toolUse.input;if(s+=m,!m.trim())continue}}else if("contentBlockStop"in u)if(o&&s){try{o.toolUse.input=JSON.parse(s)}catch(_){o.toolUse.input={}}e.push(o),o=null,s=""}else i?(e.push({text:i}),i=""):p&&l&&(e.push({reasoningContent:{reasoningText:{text:p,signature:l}}}),p="",l="");else if("messageStop"in u)n.stopReason=u.messageStop.stopReason;else if("metadata"in u){let _=u.metadata;n.usage=(_==null?void 0:_.usage)||{},n.metrics=(_==null?void 0:_.metrics)||{}}return n.output.message={role:"assistant",content:e},n},Ms=(t,n,e,o,s,i,l,p,u)=>{var k,h,P;let _=S({},l),m=[];if(t){let x={text:t,thought:!0};p&&(x.thoughtSignature=p),m.push(x)}if(n){let x={text:n,thought:null};u&&(x.thoughtSignature=u),m.push(x)}for(let x of s)m.push({executableCode:x});for(let x of i)m.push({codeExecutionResult:x});for(let x of o)m.push({inlineData:x});for(let x of e)m.push({functionCall:x});m.length>0&&((h=(k=_.candidates)==null?void 0:k[0])!=null&&h.content)&&(_.candidates[0].content.parts=m);let y=(P=l==null?void 0:l.candidates)==null?void 0:P[0];return y&&(_.candidates||(_.candidates=[]),_.candidates[0]||(_.candidates[0]={content:{parts:[]}}),y.groundingMetadata!=null&&(_.candidates[0].groundingMetadata=y.groundingMetadata),y.urlContextMetadata!=null&&(_.candidates[0].urlContextMetadata=y.urlContextMetadata),y.citationMetadata!=null&&(_.candidates[0].citationMetadata=y.citationMetadata)),_},bo=t=>{var m,y,k,h,P,x,g;let{GenerateContentResponse:n}=require("@google/genai");if(!t.length)return new n;let e="",o="",s=[],i=[],l=[],p=[],u=null,_=null;for(let w of t)if(w.candidates&&((y=(m=w.candidates[0])==null?void 0:m.content)!=null&&y.parts))for(let f of w.candidates[0].content.parts)if(f.text!=null)f.thought===!0?(e+=f.text,f.thoughtSignature&&(u=f.thoughtSignature)):(o+=f.text,f.thoughtSignature&&(_=f.thoughtSignature));else if(f.functionCall)s.push(f.functionCall);else if(f.inlineData){let R=f.inlineData;i.push({data:(k=R.data)!=null?k:"",mimeType:(h=R.mimeType)!=null?h:"image/png"})}else f.executableCode?l.push({code:(P=f.executableCode.code)!=null?P:"",language:f.executableCode.language}):f.codeExecutionResult&&p.push({output:(x=f.codeExecutionResult.output)!=null?x:"",outcome:(g=f.codeExecutionResult.outcome)!=null?g:"OUTCOME_OK"});return Ms(e,o,s,i,l,p,t[t.length-1],u,_)},js=t=>bo(t),Ws=t=>bo(t),$s=["size","quality","background","output_format"],Pn=t=>{var i,l,p,u,_;let n={created:null,data:[],usage:null},e={},o="png";for(let m of t){let y=(i=m==null?void 0:m.type)!=null?i:"";if(y==="image_generation.partial_image"){let k=m.b64_json;if(k!=null){let h=(l=m.partial_image_index)!=null?l:0;e[h]=k}}else if(y==="image_generation.completed"){let k=m.b64_json;if(k!=null){let h=(p=m.partial_image_index)!=null?p:0;e[h]=k}n.created=(u=m.created_at)!=null?u:n.created,n.usage=(_=m.usage)!=null?_:n.usage;for(let h of $s)m[h]!=null&&(n[h]=m[h]);m.output_format&&(o=m.output_format)}}n.output_format||(n.output_format=o);let s=Object.keys(e).map(Number).sort((m,y)=>m-y);return s.length>0&&(n.data=s.map(m=>({b64_json:e[m]}))),n},ko=(t,n="openai.chat.completions.create")=>{if(n==="openai.responses.create"||n==="openai.AzureOpenAI.responses.create")return ln(t);if(n==="openai.images.generate"||n==="openai.AzureOpenAI.images.generate")return Pn(t);if("completion"in t[0])return t.reduce((e,o)=>Y(S({},o),{completion:`${e.completion}${o.completion}`}),{});if(n==="anthropic.messages.create")return Sn(t);if("text"in t[0].choices[0]){let e="";for(let s of t)e=`${e}${s.choices[0].text}`;let o=structuredClone(t.at(-1));return o.choices[0].text=e,o}if("delta"in t[0].choices[0]){let e=xn(t);return e.choices[0]=S(S({},e.choices[0]),e.choices[0].message),e}return""},yo=(t,n,e)=>{let o=n.model.provider,s=n.model.name;if(o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&s.startsWith("claude"))return co(t,n,e==null?void 0:e.anthropicBlockTypeByIndex);if(o==="google"||o==="vertexai"&&s.startsWith("gemini"))return uo(t,n);if(o==="amazon.bedrock")return _o(t,n);if(o==="mistral")return wn(t.data,n);if(o==="openai"||o==="openai.azure"){let i=n.model.api_type||"chat-completions";return i==="responses"?po(t,n):i==="images"?mo(t,n):wn(t,n)}return null};function wo(t,n,e,o){return rn(this,null,function*(){var k,h,P;let s={request_id:null,raw_response:null,prompt_blueprint:null},i={},l=o.model.provider;l=="amazon.bedrock"&&(i=t==null?void 0:t.$metadata,t=t==null?void 0:t.stream);let p=[],u=l==="anthropic"||l==="anthropic.bedrock"||l==="vertexai"&&((P=(h=(k=o.model)==null?void 0:k.name)==null?void 0:h.startsWith)==null?void 0:P.call(h,"claude")),_={};try{for(var x=an(t),g,w,f;g=!(w=yield new ft(x.next())).done;g=!1){let R=w.value;p.push(R),u&&(R==null?void 0:R.type)==="content_block_start"&&R.content_block&&(_[R.index]=R.content_block.type),s.raw_response=R,s.prompt_blueprint=yo(R,o,{anthropicBlockTypeByIndex:_}),yield s}}catch(w){f=[w]}finally{try{g&&(w=x.return)&&(yield new ft(w.call(x)))}finally{if(f)throw f[0]}}let m=e(p);l==="amazon.bedrock"&&(m.ResponseMetadata=i),s.raw_response=m,s.prompt_blueprint=yo(m,o),yield s;let y=yield new ft(n({request_response:m}));s.request_id=y.request_id,s.prompt_blueprint=y.prompt_blueprint,yield s})}var xo={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:xn},completion:{function_name:"openai.completions.create",stream_function:fo}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:ln}},"openai:images":{completion:{function_name:"openai.images.generate",stream_function:Pn}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:Sn},completion:{function_name:"anthropic.completions.create",stream_function:go}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:xn},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:fo}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ln},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ln}},"openai.azure:images":{completion:{function_name:"openai.AzureOpenAI.images.generate",stream_function:Pn}},google:{chat:{function_name:"google.convo.send_message",stream_function:js},completion:{function_name:"google.model.generate_content",stream_function:Ws}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:ho},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:ho}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:Sn},completion:{function_name:"anthropic.completions.create",stream_function:go}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:qs},completion:{function_name:"",stream_function:null}}};var Eo="1.3.4",Ks=()=>{var t;if(typeof process!="undefined"&&((t=process.versions)!=null&&t.node)){let n=process.versions.node.split(".");return`${n[0]}.${n[1]}`}return"unknown"},Fs=Ks(),Gs=`promptlayer-js/${Eo} (node ${Fs})`,z=()=>({"User-Agent":Gs,"X-SDK-Version":Eo}),Cn="SET_WORKFLOW_COMPLETE";var Qe=class extends Error{constructor(n,e){super(`Server error: ${n} ${e}`),this.name="PromptLayerRetryableHttpError",this.status=n,this.statusText=e}};function Ds(t,n,e,o){return T(this,null,function*(){let s=yield F(`${t}/workflow-version-execution-results?workflow_version_execution_id=${n}&return_all_outputs=${e}`,S({headers:o},z()));if(!s.ok)throw new Error("Failed to fetch final output");return s.json()})}function Ao(t,n,e,o,s){return function(i){return T(this,null,function*(){if(i.name===Cn)try{let l=JSON.parse(i.data),p=l.result_code,u;if(p==="OK"||p==null)u=l.final_output;else if(p==="EXCEEDS_SIZE_LIMIT")u=yield Ds(t,e,o,s),n.resolve(u);else throw new Error(`Unsupported final output code: ${p}`);n.resolve(u)}catch(l){n.reject(l)}})}}function Bs(p){return T(this,arguments,function*({token:t,channelName:n,executionId:e,returnAllOutputs:o,headers:s,timeout:i,baseURL:l}){let u=new Po.default.Realtime(t),_=u.channels.get(n),m={},y=new Promise((h,P)=>{m.resolve=h,m.reject=P}),k=Ao(l,m,e,o,s);yield _.subscribe(Cn,k);try{return yield new Promise((h,P)=>{let x=setTimeout(()=>{P(new Error("Workflow execution did not complete properly (timeout)"))},i);y.then(g=>{clearTimeout(x),h(g)}).catch(g=>{clearTimeout(x),P(g)})})}finally{console.log("Closing client"),_.unsubscribe(Cn,k),u.close(),console.log("Closed client")}})}var F=(t,n)=>T(null,null,function*(){return(0,To.default)(()=>T(null,null,function*(){let e=yield fetch(t,n);if(e.status>=500&&e.status<600||e.status===429)throw new Qe(e.status,e.statusText);return e}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:e=>{console.info(`PromptLayer API request attempt ${e.attemptNumber} failed. ${e.retriesLeft} retries left.`)}})}),Oo=(t,n,e,o=!0)=>T(null,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?Vs(t,n,e.request_response,e,o):yield Io(t,n,e,o)}),Io=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(e)}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);v(i,"WARNING: While logging your request, PromptLayer experienced the following error:")}if(i&&e.return_pl_id)return[e.request_response,i.request_id]}catch(s){if(o)throw s;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${s}`)}return e.request_response}),Lo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-metadata`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track metadata";if(o)throw new Error(l);return v(i,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),No=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-score`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track score";if(o)throw new Error(l);return v(i,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),Uo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-prompt`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track prompt";if(o)throw new Error(l);return v(i,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${s}`),!1}return!0}),qo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/track-group`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track group";if(o)throw new Error(l);return v(i,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${s}`),!1}return!0}),Mo=(t,n,e=!0)=>T(null,null,function*(){try{let o=yield F(`${n}/create-group`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify({api_key:t})}),s=yield o.json();if(o.status!==200){let i=s.message||s.error||"Failed to create group";if(e)throw new Error(i);return v(s,"WARNING: While creating a group PromptLayer had the following error"),!1}return s.id}catch(o){if(e)throw o;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${o}`),!1}}),Tn=(t,n,e,o,s=!0)=>T(null,null,function*(){try{let i=new URL(`${n}/prompt-templates/${e}`),l=yield F(i,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(o)}),p=yield l.json();if(l.status!==200){let u=p.message||p.error||"Failed to fetch prompt template";if(s)throw new Error(u);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${u}`),null}return p.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${p.warning}`),p}catch(i){if(s)throw i;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${i}`),null}}),jo=(t,n,e,o=!0)=>T(null,null,function*(){let s=yield F(`${n}/rest/prompt-templates`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify({prompt_template:S({},e),prompt_version:S({},e),release_labels:e.release_labels?e.release_labels:void 0})}),i=yield s.json();if(s.status!==200&&s.status!==201){let l=i.message||i.error||"Failed to publish prompt template";if(o)throw new Error(l);v(i,"WARNING: While publishing a prompt template PromptLayer had the following error")}return i}),Wo=(t,n,e,o=!0)=>T(null,null,function*(){var p;let s=new URL(`${n}/prompt-templates`);Object.entries(e||{}).forEach(([u,_])=>s.searchParams.append(u,_.toString()));let i=yield F(s,{headers:S({"Content-Type":"application/json","X-API-KEY":t},z())}),l=yield i.json();if(i.status!==200){let u=l.message||l.error||"Failed to fetch prompt templates";if(o)throw new Error(u);return v(l,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(p=l.items)!=null?p:[]}),zs=t=>T(null,null,function*(){let n=new URL(`${t.baseURL}/connection/websocket`);n.protocol=n.protocol==="https:"?"wss:":"ws:";let e=new Co.Centrifuge(n.toString(),{token:t.token}),o=e.newSubscription(t.channelName);return new Promise((s,i)=>{let l=m=>{_(),s(m)},p=Ao(t.baseURL,{resolve:l,reject:i},t.executionId,t.returnAllOutputs,t.headers);o.on("publication",m=>{p({name:m.data.message_name,data:m.data.data})});let u=setTimeout(()=>{i(new Error("Workflow execution did not complete properly (timeout)"))},t.timeout),_=()=>{clearTimeout(u),o.unsubscribe(),e.disconnect()};o.on("error",m=>{_(),i(`Centrifugo subscription error: ${m}`)}),e.on("error",m=>{_(),i(`Centrifugo client error: ${m}`)}),o.subscribe(),e.connect()})}),$o=_=>T(null,[_],function*({workflow_name:t,input_variables:n,metadata:e={},workflow_label_name:o=null,workflow_version_number:s=null,return_all_outputs:i=!1,api_key:l,timeout:p=36e5,baseURL:u}){let m={input_variables:n,metadata:e,workflow_label_name:o,workflow_version_number:s,return_all_outputs:i},y=S({"Content-Type":"application/json","X-API-KEY":l},z());try{let k=yield F(`${u}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:y,body:JSON.stringify(m)});if(k.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield k.json().catch(()=>({}))).error||k.statusText}`};let h=yield k.json();h.warning&&console.warn(`WARNING: ${h.warning}`);let P=h.workflow_version_execution_id;if(!P)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let x=`workflow_updates:${P}`,w=yield(yield F(`${u}/ws-token-request-library?capability=${x}`,{method:"POST",headers:y})).json(),R={token:w.token_details.token,channelName:x,executionId:P,returnAllOutputs:i,headers:y,timeout:p,baseURL:u};return w.messaging_backend==="centrifugo"?zs(R):yield Bs(R)}catch(k){throw console.error(`Failed to run workflow: ${k instanceof Error?k.message:k}`),k}});function Vs(t,n,e,o,s=!0){return rn(this,null,function*(){let i=[];try{for(var u=an(e),_,m,y;_=!(m=yield new ft(u.next())).done;_=!1){let k=m.value;yield o.return_pl_id?[k,null]:k,i.push(k)}}catch(m){y=[m]}finally{try{_&&(m=u.return)&&(yield new ft(m.call(u)))}finally{if(y)throw y[0]}}let l=ko(i,o.function_name),p=yield new ft(Io(t,n,Y(S({},o),{request_response:l,request_end_time:new Date().toISOString()}),s));if(p&&o.return_pl_id){let k=p[1];yield[i.at(-1),k]}})}var v=(t,n)=>{try{console.warn(`${n}: ${t.message}`)}catch(e){console.warn(`${n}: ${t}`)}},Ko=(t,n,e=!0)=>T(null,null,function*(){try{let o=yield F(`${t}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(n)}),s=yield o.json();if(o.status!==200){let i=s.message||s.error||"Failed to track request";if(e)throw new Error(i);v(s,"WARNING: While logging your request, PromptLayer experienced the following error:")}return s}catch(o){if(e)throw o;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${o}`)}return{}}),Js=(t,n)=>T(null,null,function*(){return yield t.chat.completions.create(n)}),Ys=(t,n)=>T(null,null,function*(){return yield t.completions.create(n)}),Fo={chat:Js,completion:Ys},Go=(t,n)=>T(null,null,function*(){var i,l;let e=require("openai").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey});n==null||delete n.apiKey,n==null||delete n.baseURL;let s=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(s==="chat-completions"){let p=Fo[t.prompt_template.type];return yield p(o,n)}else return s==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Do=(t,n)=>T(null,null,function*(){var i,l;let{AzureOpenAI:e}=require("openai"),o=new e({endpoint:process.env.AZURE_OPENAI_ENDPOINT||n.baseURL,apiVersion:process.env.OPENAI_API_VERSION||n.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||n.apiKey});n==null||delete n.baseURL,n==null||delete n.apiVersion,n==null||delete n.apiKey;let s=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(s==="chat-completions"){let p=Fo[t.prompt_template.type];return yield p(o,n)}else return s==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Bo=(t,n)=>T(null,null,function*(){return t.messages.create(n)}),Xs=(t,n)=>T(null,null,function*(){return t.completions.create(n)}),zo={chat:Bo,completion:Xs},Vo=(t,n)=>T(null,null,function*(){let e=require("@anthropic-ai/sdk").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey}),s=zo[t.prompt_template.type];return s(o,n)}),Jo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/log-request`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(e)}),i=yield s.json();if(s.status!==201){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);return v(i,"WARNING: While logging your request PromptLayer had the following error"),null}return i}catch(s){if(o)throw s;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${s}`),null}}),Hs=(t,n)=>T(null,null,function*(){var l,p;let e=n==null?void 0:n.history,o=n==null?void 0:n.generationConfig,s=e.length>0?(l=e[e.length-1])==null?void 0:l.parts:"",i=t.chats.create({model:n==null?void 0:n.model,history:(p=e.slice(0,-1))!=null?p:[],config:o});return n!=null&&n.stream?yield i.sendMessageStream({message:s}):yield i.sendMessage({message:s})}),Zs=(t,o)=>T(null,null,function*(){var s=o,{stream:n}=s,e=sn(s,["stream"]);return n?yield t.generateContentStream(S({},e)):yield t.generateContent(S({},e))}),Qs={chat:Hs,completion:Zs},En=(t,n)=>T(null,null,function*(){let{GoogleGenAI:e}=yield import("@google/genai"),o=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,s=process.env.VERTEX_AI_PROJECT_ID||process.env.GOOGLE_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT,i=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,l={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:s,scopes:["https://www.googleapis.com/auth/cloud-platform"]},p=o?new e({apiKey:o}):new e({vertexai:!0,project:s,location:i,googleAuthOptions:l}),u=Qs[t.prompt_template.type];return yield u(p,n)}),So=t=>t.replace(/_([a-z])/g,(n,e)=>e.toUpperCase()),cn=(t,n=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(e=>cn(e,n)):Object.fromEntries(Object.entries(t).map(([e,o])=>n.has(e)?[So(e),o]:[So(e),cn(o,n)])),Yo=(t,n,e={},o=!1)=>{var u,_,m,y,k,h,P,x,g;let s=(m=n==null?void 0:n.client)!=null?m:(_=(u=t.metadata)==null?void 0:u.model)==null?void 0:_.provider,i=(k=(y=t.metadata)==null?void 0:y.model)==null?void 0:k.api_type;if(!s)throw new Error("Provider type not found in prompt blueprint or custom provider");let l=Y(S({},t.llm_kwargs||{}),{stream:o});["google","vertexai"].includes(s)&&((P=(h=t.metadata)==null?void 0:h.model)!=null&&P.name.startsWith("gemini"))&&(l=cn(l,new Set(["function_declarations","properties"])));let p={baseURL:(g=n==null?void 0:n.base_url)!=null?g:(x=t.provider_base_url)==null?void 0:x.url,apiKey:n==null?void 0:n.api_key};return Object.entries(p).forEach(([w,f])=>{f!==void 0&&(l[w]=f)}),o&&Ro.includes(s)&&i==="chat-completions"&&(l.stream_options={include_usage:!0}),{provider_type:s,kwargs:l}},Xo=(t,n)=>{let e=xo[t];if(!e)throw new Error(`Unsupported provider type: ${t}`);let o=n.type,s=e[o];if(!s)throw new Error(`Unsupported template type '${n.type}' for provider '${t}'`);return s},Ho=(t,n)=>T(null,null,function*(){var o;let e=(o=t.metadata)==null?void 0:o.model;if(!e)throw new Error("Model metadata not found in prompt blueprint");if(e.name.startsWith("gemini"))return En(t,n);if(e.name.startsWith("claude")){let{AnthropicVertex:s}=yield import("@anthropic-ai/vertex-sdk"),i=new s({baseURL:n.baseURL});if(t.prompt_template.type==="chat")return Bo(i,n);throw new Error(`Unsupported prompt template type '${t.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${e.name}' for Vertex AI request`)}),Zo=(t,n)=>T(null,null,function*(){let{BedrockRuntimeClient:e,ConverseCommand:o,ConverseStreamCommand:s}=yield import("@aws-sdk/client-bedrock-runtime"),i=new e({credentials:{accessKeyId:(n==null?void 0:n.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(n==null?void 0:n.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(n==null?void 0:n.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(n==null?void 0:n.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(n!=null&&n.stream){delete n.stream;let l=new s(S({},n));return yield i.send(l)}else{n==null||delete n.stream;let l=new o(S({},n));return yield i.send(l)}}),Qo=(t,n)=>T(null,null,function*(){let{AnthropicBedrock:e}=yield import("@anthropic-ai/bedrock-sdk"),o=new e({awsAccessKey:n.aws_access_key,awsSecretKey:n.aws_secret_key,awsRegion:n.aws_region,awsSessionToken:n.aws_session_token,baseURL:n.base_url}),s=zo[t.prompt_template.type];return s(o,n)}),vo=(t,n)=>T(null,null,function*(){let{Mistral:e}=yield import("@mistralai/mistralai"),o=new e({apiKey:process.env.MISTRAL_API_KEY});return n=cn(n,new Set),n!=null&&n.stream?(delete n.stream,yield o.chat.stream(n)):(delete n.stream,yield o.chat.complete(n))}),An=t=>{var n,e,o,s,i,l;if(typeof globalThis.process!="undefined")return(o=(e=(n=globalThis.process.env)==null?void 0:n[t])==null?void 0:e.trim())!=null?o:void 0;if(typeof globalThis.Deno!="undefined")return(l=(i=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:i.call(s,t))==null?void 0:l.trim()};var un=class{constructor(n,e,o=!0){this.create=()=>Mo(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var _t=require("@opentelemetry/api"),ve=require("@opentelemetry/core");var On=class{constructor(n,e,o){this.apiKey=e,this.baseURL=o,this.enableTracing=n,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(n){return n?Object.fromEntries(Object.entries(n)):{}}spanKindToString(n){return{[_t.SpanKind.INTERNAL]:"SpanKind.INTERNAL",[_t.SpanKind.SERVER]:"SpanKind.SERVER",[_t.SpanKind.CLIENT]:"SpanKind.CLIENT",[_t.SpanKind.PRODUCER]:"SpanKind.PRODUCER",[_t.SpanKind.CONSUMER]:"SpanKind.CONSUMER"}[n]||"SpanKind.INTERNAL"}statusCodeToString(n){return{[_t.SpanStatusCode.ERROR]:"StatusCode.ERROR",[_t.SpanStatusCode.OK]:"StatusCode.OK",[_t.SpanStatusCode.UNSET]:"StatusCode.UNSET"}[n]||"StatusCode.UNSET"}toNanoseconds(n){return(BigInt(n[0])*BigInt(1e9)+BigInt(n[1])).toString()}export(n){if(!this.enableTracing)return Promise.resolve(ve.ExportResultCode.SUCCESS);let e=n.map(o=>{var s;return{name:o.name,context:{trace_id:o.spanContext().traceId,span_id:o.spanContext().spanId,trace_state:((s=o.spanContext().traceState)==null?void 0:s.serialize())||""},kind:this.spanKindToString(o.kind),parent_id:o.parentSpanId||null,start_time:this.toNanoseconds(o.startTime),end_time:this.toNanoseconds(o.endTime),status:{status_code:this.statusCodeToString(o.status.code),description:o.status.message},attributes:this.attributesToObject(o.attributes),events:o.events.map(i=>({name:i.name,timestamp:this.toNanoseconds(i.time),attributes:this.attributesToObject(i.attributes)})),links:o.links.map(i=>({context:i.context,attributes:this.attributesToObject(i.attributes)})),resource:{attributes:Y(S({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return F(this.url,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},z()),body:JSON.stringify({spans:e})}).then(o=>o.ok?ve.ExportResultCode.SUCCESS:(console.error(`Error exporting spans
2
2
  HTTP error! status: ${o.status}`),ve.ExportResultCode.FAILED)).catch(o=>(console.error("Error exporting spans:",o),ve.ExportResultCode.FAILED))}shutdown(){return Promise.resolve()}},ts=On;var es=lt(require("@opentelemetry/api")),ns=require("@opentelemetry/sdk-trace-base"),os=require("@opentelemetry/sdk-trace-node"),Tt=(t="promptlayer-tracer")=>es.trace.getTracer(t),ss=(t,n,e)=>{let o=new os.NodeTracerProvider,s=new ts(t,n,e),i=new ns.SimpleSpanProcessor(s);o.addSpanProcessor(i),o.register()};var vs=Tt(),In=(t,n,e,o="",s="openai")=>{let i={construct:(l,p)=>{let u=Reflect.construct(l,p);return Object.defineProperties(u,{function_name:{value:o,writable:!0},provider:{value:s}}),new Proxy(u,i)},get:(l,p,u)=>{let _=l[p],m=`${Reflect.get(l,"function_name")}.${p.toString()}`;return typeof _=="object"?(Object.defineProperties(_,{function_name:{value:m,writable:!0},provider:{value:s}}),new Proxy(_,i)):typeof _=="function"?(...y)=>{var w,f,R,I,q,j;let k=new Date().toISOString(),h=Reflect.get(l,"provider"),P=(w=y[0])==null?void 0:w.return_pl_id,x=(f=y[0])==null?void 0:f.pl_tags,g=(R=y[0])==null?void 0:R.pl_warn_on_error;return(I=y[0])==null||delete I.return_pl_id,(q=y[0])==null||delete q.pl_tags,(j=y[0])==null||delete j.pl_warn_on_error,vs.startActiveSpan(`${h}.${m}`,O=>T(null,null,function*(){try{O.setAttribute("function_input",JSON.stringify(y));let L=Reflect.apply(_,l,y),W=O.spanContext().spanId;return L instanceof Promise?new Promise((N,V)=>{L.then($=>T(null,null,function*(){let Z=yield Oo(t,n,{api_key:t,provider_type:h,function_name:m,request_start_time:k,request_end_time:new Date().toISOString(),request_response:$,kwargs:y[0],return_pl_id:P,tags:x,span_id:W},!g);O.setAttribute("function_output",JSON.stringify(Z)),O.setAttribute("response_status","success"),O.end(),N(Z)})).catch($=>{O.recordException($),O.setAttribute("response_status","error"),O.end(),V($)})}):(O.setAttribute("function_output",JSON.stringify(L)),O.setAttribute("response_status","success"),O.end(),L)}catch(L){throw O.recordException(L),O.setAttribute("response_status","error"),O.end(),L}}))}:Reflect.get(l,p,u)}};return new Proxy(e,i)};var tn=t=>Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)),en=t=>T(null,null,function*(){var o;if(((o=t.headers.get("content-type"))!=null?o:"").includes("application/json"))return t.json();let e=yield t.text();if(!e)return{};try{return JSON.parse(e)}catch(s){return{message:e}}}),rs=t=>t instanceof Blob?t:t instanceof Uint8Array?new Blob([t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)],{type:"application/zip"}):new Blob([t],{type:"application/zip"});var pn=t=>`${t}/api/public/v2/skill-collections`,dn=(t,n)=>`${pn(t)}/${encodeURIComponent(n)}`,is=(t,n)=>`${dn(t,n)}/versions`;var Ln=t=>"zipFile"in t;var as=["claude_code","openai","openclaw"],ls=(t,n)=>{if(!t){if(n==="publishing")throw new Error("provider is required when publishing a skill collection.");return}if(!as.includes(t))throw new Error(`provider must be one of: ${as.join(", ")}.`)},cs=(t,n,e,o,s=!0)=>T(null,null,function*(){let i=new URL(dn(n,e));Object.entries(o||{}).forEach(([p,u])=>{u!==void 0&&i.searchParams.append(p,String(u))});let l=yield F(i,{headers:S({"X-API-KEY":t},z())});if(l.status!==200){let p=yield en(l),u=p.message||p.error||"Failed to pull skill collection";if(s)throw new Error(u);return v(p,"WARNING: While pulling a skill collection PromptLayer had the following error"),null}return(o==null?void 0:o.format)==="zip"?l.arrayBuffer():yield l.json()}),us=(t,n,e,o=!0)=>T(null,null,function*(){ls(e.provider,"publishing");let s=Ln(e)?(()=>{var _;let p=new FormData,u=tn({name:e.name,folder_id:e.folderId,provider:e.provider,commit_message:e.commitMessage});return p.append("files",rs(e.zipFile),(_=e.fileName)!=null?_:"skill-collection.zip"),p.append("json",JSON.stringify(u)),p})():JSON.stringify(tn({name:e.name,folder_id:e.folderId,provider:e.provider,files:e.files,commit_message:e.commitMessage})),i=Ln(e)?yield F(pn(n),{method:"POST",headers:S({"X-API-KEY":t},z()),body:s}):yield F(pn(n),{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:s}),l=yield en(i);if(i.status!==201){let p=l.message||l.error||"Failed to publish skill collection";if(o)throw new Error(p);return v(l,"WARNING: While publishing a skill collection PromptLayer had the following error"),null}return l}),ps=(t,n,e,o,s=!0)=>T(null,null,function*(){let i=yield F(dn(n,e),{method:"PATCH",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(tn(o))}),l=yield en(i);if(i.status!==200){let p=l.message||l.error||"Failed to update skill collection";if(s)throw new Error(p);return v(l,"WARNING: While updating a skill collection PromptLayer had the following error"),null}return l}),ds=(t,n,e,o,s=!0)=>T(null,null,function*(){ls(o.provider,"updating");let i=tn({file_updates:o.fileUpdates,moves:o.moves,deletes:o.deletes,commit_message:o.commitMessage,release_label:o.releaseLabel,provider:o.provider}),l=yield F(is(n,e),{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(i)}),p=yield en(l);if(l.status!==201){let u=p.message||p.error||"Failed to save skill collection version";if(s)throw new Error(u);return v(p,"WARNING: While saving a skill collection version PromptLayer had the following error"),null}return p});var Nn=t=>Array.isArray(t)&&t.length>0,tr=t=>Nn(t.fileUpdates)||Nn(t.moves)||Nn(t.deletes)||t.commitMessage!==void 0||t.releaseLabel!==void 0||t.provider!==void 0,er=(t,n,e)=>{var o;return Y(S({},t!=null?t:{}),{success:(o=t==null?void 0:t.success)!=null?o:!0,skill_collection:n,version:e})},_n=class{constructor(n,e,o=!0){this.pull=(n,e)=>cs(this.apiKey,this.baseURL,n,e,this.throwOnError);this.publish=n=>us(this.apiKey,this.baseURL,n,this.throwOnError);this.update=(n,e)=>T(this,null,function*(){var _,m,y,k;let o=e.name!==void 0,s=tr(e);if(!o&&!s)throw new Error("At least one of name, fileUpdates, moves, deletes, commitMessage, releaseLabel, or provider must be provided.");let i=n,l=null,p,u=null;if(o){let h=yield ps(this.apiKey,this.baseURL,n,{name:e.name},this.throwOnError);if(!h)return null;l=h,p=h.skill_collection,u=(_=h.version)!=null?_:null,i=String(h.skill_collection.id)}if(s){let h=yield ds(this.apiKey,this.baseURL,i,{fileUpdates:e.fileUpdates,moves:e.moves,deletes:e.deletes,commitMessage:e.commitMessage,releaseLabel:e.releaseLabel,provider:e.provider},this.throwOnError);if(!h)return null;l=h,p=(m=h.skill_collection)!=null?m:p,u=(y=h.version)!=null?y:u}if(!p){let h=yield this.pull(i);if(!h)return null;if(h instanceof ArrayBuffer)throw new Error("Expected JSON skill collection response but received binary data.");l=h,p=h.skill_collection,u=(k=h.version)!=null?k:u}return er(l,p,u)});this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var mn=lt(require("@opentelemetry/api"));var ms=(t,n,e)=>function(...o){let s=Tt(),i=l=>{try{e&&Object.entries(e).forEach(([u,_])=>{l.setAttribute(u,_)}),l.setAttribute("function_input",JSON.stringify(o));let p=n(...o);return p instanceof Promise?p.then(u=>(l.setAttribute("function_output",JSON.stringify(u)),l.setStatus({code:mn.SpanStatusCode.OK}),u)).catch(u=>{throw _s(l,u,o),u}).finally(()=>l.end()):(l.setAttribute("function_output",JSON.stringify(p)),l.setStatus({code:mn.SpanStatusCode.OK}),l.end(),p)}catch(p){throw _s(l,p,o),p}};return s.startActiveSpan(t,i)},_s=(t,n,e)=>{t.setAttribute("function_input",JSON.stringify(e)),t.setStatus({code:mn.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),t.end()};var qn=lt(require("nunjucks")),nr=6e4,fs=1e3,or=512,Et=class t{constructor(n,e=fs){this.entries=new Map;this.nonRenderable=new Map;this.ttlMs=n*1e3,this.maxSize=e}static makeKey(n,e){var o,s,i,l;return e?[n,(o=e.version)!=null?o:null,(s=e.label)!=null?s:null,(i=e.provider)!=null?i:null,(l=e.model)!=null?l:null]:[n,null,null,null,null]}static serialize(n){return JSON.stringify(n)}get(n){let e=t.serialize(n),o=this.entries.get(e);if(!o)return[null,!1];let s=performance.now()-o.timestamp<this.ttlMs;return[structuredClone(o.response),s]}put(n,e){let o=t.serialize(n);this.entries.size>=this.maxSize&&!this.entries.has(o)&&this.evictOldestEntry(),this.entries.set(o,{response:structuredClone(e),timestamp:performance.now()})}isNonRenderable(n){let e=t.serialize(n),o=this.nonRenderable.get(e);return o===void 0?!1:performance.now()-o>=nr?(this.nonRenderable.delete(e),!1):!0}markNonRenderable(n){let e=t.serialize(n);this.nonRenderable.size>=fs&&!this.nonRenderable.has(e)&&this.evictOldestNonRenderable(),this.nonRenderable.set(e,performance.now())}clear(){this.entries.clear(),this.nonRenderable.clear()}invalidate(n){for(let e of this.entries.keys())JSON.parse(e)[0]===n&&this.entries.delete(e);for(let e of this.nonRenderable.keys())JSON.parse(e)[0]===n&&this.nonRenderable.delete(e)}evictOldestEntry(){let n=null,e=1/0;for(let[o,s]of this.entries)s.timestamp<e&&(e=s.timestamp,n=o);n!==null&&this.entries.delete(n)}evictOldestNonRenderable(){let n=null,e=1/0;for(let[o,s]of this.nonRenderable)s<e&&(e=s,n=o);n!==null&&this.nonRenderable.delete(n)}};function gs(t){return t?!!(t.metadata_filters||t.model_parameter_overrides):!1}function hs(t){var o,s;let n=t.prompt_template;if(!n)return!1;if(n.type==="chat"){let i=(o=n.messages)!=null?o:[];for(let l of i)if(l.role==="placeholder")return!1}let e=(s=n.tools)!=null?s:[];for(let i of e)if(i.type==="variable")return!1;return!0}function ys(t){let n=new Set(["input_variables","metadata_filters","model_parameter_overrides"]),e={};if(t)for(let[o,s]of Object.entries(t))n.has(o)||(e[o]=s);return e.skip_input_variable_rendering=!0,e}var sr=new qn.default.Environment(null,{autoescape:!1}),nn=new Map;function rr(t){let n=nn.get(t);if(!n){if(nn.size>=or){let e=nn.keys().next().value;e!==void 0&&nn.delete(e)}n=qn.default.compile(t,sr),nn.set(t,n)}return n}function ir(t,n){return rr(t).render(n)}function ar(t,n){return t.replace(/\{(\w+)(?:[!:][^}]*)?\}/g,(e,o)=>{if(o in n){let s=n[o];return s!=null?String(s):""}return""})}function At(t,n,e){try{return n==="jinja2"?ir(t,e):ar(t,e)}catch(o){return t}}function lr(t){var n,e;return t.type==="chat"?((n=t.messages)!=null?n:[]).map(s=>{var i;return(i=s.template_format)!=null?i:"f-string"}):t.type==="completion"?[(e=t.template_format)!=null?e:"f-string"]:["f-string"]}function cr(t,n){var e,o,s,i,l;if(t.type==="chat"){let p=(e=t.messages)!=null?e:[];for(let u of p){let _=(o=u.template_format)!=null?o:"f-string",m=(s=u.content)!=null?s:[];for(let y of m)y&&y.type==="text"&&typeof y.text=="string"&&(y.text=At(y.text,_,n))}}else if(t.type==="completion"){let p=(i=t.template_format)!=null?i:"f-string",u=(l=t.content)!=null?l:[];for(let _ of u)_&&_.type==="text"&&typeof _.text=="string"&&(_.text=At(_.text,p,n))}}var ur=new Set(["text","input_text"]);function Un(t,n,e){var o;if(typeof t=="string")return At(t,n,e);if(Array.isArray(t)){for(let s of t)if(s&&typeof s=="object"&&"text"in s&&typeof s.text=="string"){let i=s,l=(o=i.type)!=null?o:"text";ur.has(l)&&(i.text=At(i.text,n,e))}return t}return t}function fn(t,n,e){for(let o of t)o&&typeof o.text=="string"&&(o.text=At(o.text,n,e))}function pr(t){if("system_instruction"in t)return t.system_instruction;let n=t.generation_config;if(n&&typeof n=="object"&&!Array.isArray(n))return n.system_instruction}function dr(t,n,e){var _,m,y,k,h,P,x;let o=n.length>0?n[0]:"f-string",s=(_=t.messages)!=null?_:[];for(let g of s)"content"in g&&(g.content=Un(g.content,o,e));let i=(m=t.input)!=null?m:[];for(let g of i)if(g&&typeof g=="object"&&"content"in g){let w=g;w.content=Un(w.content,o,e)}"system"in t&&(t.system=Un(t.system,o,e));let l=(y=t.contents)!=null?y:[];for(let g of l)g&&typeof g=="object"&&fn((k=g.parts)!=null?k:[],o,e);let p=(h=t.history)!=null?h:[];for(let g of p)g&&typeof g=="object"&&fn((P=g.parts)!=null?P:[],o,e);let u=pr(t);u&&typeof u=="object"&&!Array.isArray(u)?fn((x=u.parts)!=null?x:[],o,e):Array.isArray(u)&&fn(u,o,e),typeof t.prompt=="string"&&(t.prompt=At(t.prompt,o,e))}function gn(t,n){let e=t.llm_kwargs!==null&&t.llm_kwargs!==void 0,o;if(e)o=n!=null?n:{};else{if(!n)return t;o=n}let s=t.prompt_template;if(s){cr(s,o);let i=lr(s);t.llm_kwargs&&dr(t.llm_kwargs,i,o)}return t}function _r(t){if(t instanceof Qe||t instanceof TypeError)return!0;let n=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();if(n.includes("timeout")||n.includes("timed out")||n.includes("econnreset")||n.includes("econnrefused")||n.includes("network"))return!0;if(t&&typeof t=="object"&&"status"in t){let e=t.status;if(typeof e=="number"&&e>=500)return!0}return!1}var hn=class{constructor(n,e,o=!0,s=null){this.get=(n,e)=>T(this,null,function*(){return this._cache&&!gs(e)?this._getWithCache(n,e):this._fetchNormal(n,e)});this._fetchNormal=(n,e)=>Tn(this.apiKey,this.baseURL,n,e,this.throwOnError);this._getWithCache=(n,e)=>T(this,null,function*(){let o=this._cache,s=Et.makeKey(n,e),i=e==null?void 0:e.input_variables;if(o.isNonRenderable(s))return this._fetchNormal(n,e);let[l,p]=o.get(s);if(l!==null&&p)return gn(l,i);let u=l,_=ys(e),m;try{m=yield Tn(this.apiKey,this.baseURL,n,_,!0)}catch(y){if(_r(y)){if(u!==null)return gn(u,i);if(!this.throwOnError)return null}if(!this.throwOnError)return null;throw y}return m?hs(m)?(o.put(s,m),gn(m,i)):(o.markNonRenderable(s),this._fetchNormal(n,e)):null});this.publish=n=>T(this,null,function*(){let e=yield jo(this.apiKey,this.baseURL,n,this.throwOnError);if(this._cache&&e){let o=n.prompt_name;o&&this._cache.invalidate(o)}return e});this.invalidate=n=>{this._cache&&(n?this._cache.invalidate(n):this._cache.clear())};this.all=n=>Wo(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o,this._cache=s}};var mr=(t,n,e,o=!0)=>{if(!(e.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[s,i]of Object.entries(e.metadata))if(typeof s!="string"||typeof i!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return Lo(t,n,e,o)},fr=(t,n,e,o=!0)=>{if(typeof e.score!="number")throw new Error("Score must be a number");if(e.score<0||e.score>100)throw new Error("Score must be a number between 0 and 100.");return No(t,n,e,o)},gr=(t,n,e,o=!0)=>{if(!(e.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return Uo(t,n,e,o)},hr=(t,n,e,o=!0)=>qo(t,n,e,o),yn=class{constructor(n,e,o=!0){this.group=n=>hr(this.apiKey,this.baseURL,n,this.throwOnError);this.metadata=n=>mr(this.apiKey,this.baseURL,n,this.throwOnError);this.prompt=n=>gr(this.apiKey,this.baseURL,n,this.throwOnError);this.score=n=>fr(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};function yr(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function Rr(t){return t&&typeof t=="object"&&t.constructor?t.constructor.name:""}function Rs(t){let n=yr(t),e=Rr(t),o=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();return n===429||/ratelimit/i.test(e)?"PROVIDER_RATE_LIMIT":/timeout/i.test(e)?"PROVIDER_TIMEOUT":n===401||/authentication/i.test(e)?"PROVIDER_AUTH_ERROR":o.includes("quota")?"PROVIDER_QUOTA_LIMIT":o.includes("timeout")||o.includes("timed out")?"PROVIDER_TIMEOUT":n!==void 0?"PROVIDER_ERROR":"UNKNOWN_ERROR"}var bs=lt(require("@opentelemetry/api"));var br={openai:Go,anthropic:Vo,"openai.azure":Do,google:En,vertexai:Ho,"amazon.bedrock":Zo,"anthropic.bedrock":Qo,mistral:vo},kr=t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=["status","value","error_message","raw_error_message","is_output_node"];return Object.values(t).every(o=>typeof o!="object"||o===null?!1:n.every(s=>s in o))},Mn=class{constructor({apiKey:n=An("PROMPTLAYER_API_KEY"),baseURL:e=An("PROMPTLAYER_BASE_URL"),enableTracing:o=!1,throwOnError:s=!0,cacheTtlSeconds:i=0}={}){if(n===void 0)throw new Error("PromptLayer API key not provided. Please set the PROMPTLAYER_API_KEY environment variable or pass the api_key parameter.");this.apiKey=n,this.baseURL=e||"https://api.promptlayer.com",this.enableTracing=o,this.throwOnError=s;let l=i>0?new Et(i):null;this.templates=new hn(n,this.baseURL,this.throwOnError,l),this.skills=new _n(n,this.baseURL,this.throwOnError),this.group=new un(n,this.baseURL,this.throwOnError),this.track=new yn(n,this.baseURL,this.throwOnError),this.wrapWithSpan=ms,o&&ss(o,n,this.baseURL)}invalidate(n){this.templates.invalidate(n)}get Anthropic(){try{let n=require("@anthropic-ai/sdk").default;return In(this.apiKey,this.baseURL,n,"anthropic","anthropic")}catch(n){console.error("To use the Anthropic module, you must install the @anthropic-ai/sdk package.")}}get OpenAI(){try{let n=require("openai").default;return In(this.apiKey,this.baseURL,n,"openai","openai")}catch(n){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(k){return T(this,arguments,function*({promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:s,tags:i,metadata:l,groupId:p,modelParameterOverrides:u,stream:_=!1,provider:m,model:y}){return Tt().startActiveSpan("PromptLayer Run",P=>T(this,null,function*(){try{let x={promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:s,tags:i,metadata:l,groupId:p,modelParameterOverrides:u,stream:_};P.setAttribute("function_input",JSON.stringify(x));let g=s,w={label:o,version:e,metadata_filters:l,provider:m,model:y,model_parameter_overrides:u};s&&(w.input_variables=s);let f=yield this.templates.get(n,w);if(!f)throw new Error(`Cannot proceed: prompt template '${n}' could not be fetched. Check the warnings above for the actual error.`);let R=f.prompt_template;if(!f.llm_kwargs){let D=`Prompt '${n}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashboard.`;if(this.throwOnError)throw new Error(D);console.warn(`WARNING: ${D}`)}let I=f.metadata;if(!I)throw new Error(`Prompt '${n}' does not have any metadata associated with it.`);let q=I.model;if(!q)throw new Error(`Prompt '${n}' does not have a model parameters associated with it.`);let j=f.custom_provider,O=new Date().toISOString(),{provider_type:L,kwargs:W}=Yo(f,j,u,_),N=L;if(L==="openai"||L==="openai.azure"){let D=q.api_type;N=`${L}:${D}`}q.name.startsWith("gemini")?N="google":q.name.startsWith("claude")&&(N="anthropic");let V=Xo(N,R),{function_name:$,stream_function:Z}=V,G=br[L];if(!G)throw new Error(`No request function found for provider: ${L}`);let Q=D=>{let ot=new Date().toISOString();return Ko(this.baseURL,S({function_name:$,provider_type:L,args:[],kwargs:W,tags:i,request_start_time:O,request_end_time:ot,api_key:this.apiKey,metadata:l,prompt_id:f.id,prompt_version:f.version,prompt_input_variables:g,group_id:p,return_prompt_blueprint:!0,span_id:P.spanContext().spanId},D),this.throwOnError)},H;try{H=yield G(f,W)}catch(D){let ot=Rs(D),ct=D instanceof Error?D.message:String(D);throw yield Q({request_response:{},status:"ERROR",error_type:ot,error_message:ct}),D}if(_)return wo(H,Q,Z,l||f.metadata);let it=yield Q({request_response:H}),at={request_id:it.request_id,raw_response:H,prompt_blueprint:it.prompt_blueprint};return P.setAttribute("function_output",JSON.stringify(at)),at}catch(x){throw P.setStatus({code:bs.SpanStatusCode.ERROR,message:x instanceof Error?x.message:"Unknown error"}),x}finally{P.end()}}))})}runWorkflow(p){return T(this,arguments,function*({workflowName:n,inputVariables:e={},metadata:o={},workflowLabelName:s=null,workflowVersion:i=null,returnAllOutputs:l=!1}){try{let u=yield $o({workflow_name:n,input_variables:e,metadata:o,workflow_label_name:s,workflow_version_number:i,return_all_outputs:l,api_key:this.apiKey,baseURL:this.baseURL});if(!l&&kr(u)){let m=Object.values(u).filter(k=>k.is_output_node===!0);if(m.length===0)throw new Error(JSON.stringify(u,null,2));if(!m.some(k=>k.status==="SUCCESS"))throw new Error(JSON.stringify(u,null,2))}return u}catch(u){throw u instanceof Error?(console.error("Error running workflow:",u.message),new Error(`Error running workflow: ${u.message}`)):(console.error("Unknown error running workflow:",u),new Error("Unknown error running workflow"))}})}logRequest(n){return T(this,null,function*(){return Jo(this.apiKey,this.baseURL,n,this.throwOnError)})}};0&&(module.exports={PromptLayer});
3
3
  //# sourceMappingURL=index.js.map
@@ -1,3 +1,5 @@
1
- "use strict";var ft=Object.create;var b=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames,F=Object.getOwnPropertySymbols,ht=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty,bt=Object.prototype.propertyIsEnumerable;var G=(n,t,e)=>t in n?b(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,d=(n,t)=>{for(var e in t||(t={}))z.call(t,e)&&G(n,e,t[e]);if(F)for(var e of F(t))bt.call(t,e)&&G(n,e,t[e]);return n};var xt=(n,t)=>{for(var e in t)b(n,e,{get:t[e],enumerable:!0})},K=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yt(t))!z.call(n,s)&&s!==e&&b(n,s,{get:()=>t[s],enumerable:!(o=gt(t,s))||o.enumerable});return n};var O=(n,t,e)=>(e=n!=null?ft(ht(n)):{},K(t||!n||!n.__esModule?b(e,"default",{value:n,enumerable:!0}):e,n)),At=n=>K(b({},"__esModule",{value:!0}),n);var u=(n,t,e)=>new Promise((o,s)=>{var r=l=>{try{i(e.next(l))}catch(c){s(c)}},a=l=>{try{i(e.throw(l))}catch(c){s(c)}},i=l=>l.done?o(l.value):Promise.resolve(l.value).then(r,a);i((e=e.apply(n,t)).next())});var Ht={};xt(Ht,{PromptLayerOpenAIAgentsProcessor:()=>h,instrumentOpenAIAgents:()=>_t});module.exports=At(Ht);var wt=O(require("ably")),Pt=require("centrifuge"),D=O(require("p-retry"));var g="1.3.2",kt=()=>{var n;if(typeof process!="undefined"&&((n=process.versions)!=null&&n.node)){let t=process.versions.node.split(".");return`${t[0]}.${t[1]}`}return"unknown"},Ot=kt(),Et=`promptlayer-js/${g} (node ${Ot})`,V=()=>({"User-Agent":Et,"X-SDK-Version":g});var E=class extends Error{constructor(t,e){super(`Server error: ${t} ${e}`),this.name="PromptLayerRetryableHttpError",this.status=t,this.statusText=e}};var J=(n,t)=>u(null,null,function*(){return(0,D.default)(()=>u(null,null,function*(){let e=yield fetch(n,t);if(e.status>=500&&e.status<600||e.status===429)throw new E(e.status,e.statusText);return e}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:e=>{console.info(`PromptLayer API request attempt ${e.attemptNumber} failed. ${e.retriesLeft} retries left.`)}})});var C=n=>{var t,e,o,s,r,a;if(typeof globalThis.process!="undefined")return(o=(e=(t=globalThis.process.env)==null?void 0:t[n])==null?void 0:e.trim())!=null?o:void 0;if(typeof globalThis.Deno!="undefined")return(a=(r=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:r.call(s,n))==null?void 0:a.trim()},Y=n=>{if(n!==void 0){let e=n.trim();if(!e)throw new Error("PromptLayer API key not provided. Please set PROMPTLAYER_API_KEY or pass apiKey.");return e}let t=C("PROMPTLAYER_API_KEY");if(!t)throw new Error("PromptLayer API key not provided. Please set PROMPTLAYER_API_KEY or pass apiKey.");return t};var Ct=1,Nt=3,p=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),et=n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean",Mt=n=>n.replace(/[^a-zA-Z0-9_.-]/g,"_"),A=n=>n===null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:Array.isArray(n)?n.map(t=>A(t)):p(n)?Object.fromEntries(Object.entries(n).map(([t,e])=>[t,A(e)])):String(n),y=n=>{let t=e=>Array.isArray(e)?e.map(o=>t(o)):p(e)?Object.keys(e).sort().reduce((o,s)=>(o[s]=t(e[s]),o),{}):e;return JSON.stringify(t(A(n)))},_=(n,t,e)=>{e!=null&&e!==""&&(n[t]=String(e))},X=(n,t,e)=>{if(e!=null&&e!==""){let o=Number(e);Number.isNaN(o)||(n[t]=o)}},m=(n,t,e,o)=>{o&&e!==void 0&&e!==null&&(n[t]=y(e))},S=(n,t,e)=>{t.forEach((o,s)=>{Object.entries(o).forEach(([r,a])=>{e[`${n}.${s}.${r}`]=et(a)?a:y(a)})})},nt=n=>Array.isArray(n)?n.map(t=>{var r,a,i,l,c;if(!p(t))return null;let e=p(t.function)?t.function:null,o=(a=(r=e==null?void 0:e.name)!=null?r:t.name)!=null?a:"tool",s=(l=(i=e==null?void 0:e.arguments)!=null?i:t.arguments)!=null?l:{};if(typeof s=="string")try{s=JSON.parse(s)}catch(k){s=s}return{id:String((c=t.id)!=null?c:""),type:"tool_call",name:String(o),arguments:A(s)}}).filter(t=>t!==null):[],ot=n=>{var e,o;let t=(o=(e=n.call_id)!=null?e:n.callId)!=null?o:n.id;return t!=null?String(t):void 0},jt=n=>{if(n==null)return;if(typeof n=="string")return n;if(Array.isArray(n)){let e=x(n);return e!=null?e:y(n)}if(p(n)){let e=x([n]);return e!=null?e:y(n)}let t=x(n);return t!==void 0?t:y(n)},Z=n=>{var e,o,s;let t=(e=n.arguments)!=null?e:{};if(typeof t=="string")try{t=JSON.parse(t)}catch(r){t=t}return{role:"assistant",tool_calls:[{id:(o=ot(n))!=null?o:"",type:"tool_call",name:String((s=n.name)!=null?s:"tool"),arguments:A(t)}]}},H=(n,t)=>{var r;let e=ot(n),o=jt((r=t!=null?t:n.output)!=null?r:n.content);if(!e&&!o)return null;let s={role:"tool"};return e&&(s.tool_call_id=e),o!==void 0&&(s.content=o),s};function x(n){if(n!=null){if(typeof n=="string")return n;if(Array.isArray(n)){let t=n.map(e=>{var s;if(!p(e))return null;let o=e.type;if(o==="text"||o==="input_text"||o==="output_text"){let r=(s=e.text)!=null?s:e.content;return r!=null?String(r):null}return null}).filter(e=>e!==null);return t.length>0?t.join(`
2
- `):void 0}return String(n)}}var Q=n=>Array.isArray(n)?n.map(t=>{if(!p(t))return null;let e={};t.role!==void 0&&(e.role=String(t.role));let o=x(t.content);o&&(e.content=o);let s=nt(t.tool_calls);return s.length>0&&(e.tool_calls=s),t.tool_call_id&&(e.tool_call_id=String(t.tool_call_id)),Object.keys(e).length>0?e:null}).filter(t=>t!==null):[],v=n=>{let t={},e=n.role,o=x(n.content),s=nt(n.tool_calls);return e!=null?t.role=String(e):(o||s.length>0)&&(t.role="assistant"),o&&(t.content=o),s.length>0&&(t.tool_calls=s),n.tool_call_id&&(t.tool_call_id=String(n.tool_call_id)),Object.keys(t).length>0?t:null},Lt=new Set(["function_call","computer_call","shell_call","apply_patch_call","custom_tool_call","mcp_call"]),qt=new Set(["function_call_output","function_call_result","computer_call_output","computer_call_result","shell_call_output","apply_patch_call_output","custom_tool_call_output"]),tt=n=>typeof n=="string"?[{role:"user",content:n}]:Array.isArray(n)?n.flatMap(t=>{if(!p(t))return[];if(t.type==="message_output_item"&&p(t.rawItem)){let o=v(t.rawItem);return o?[o]:[]}if(t.type==="tool_call_item"&&p(t.rawItem)){let o=Z(t.rawItem);return o?[o]:[]}if(t.type==="tool_call_output_item"&&p(t.rawItem)){let o=H(t.rawItem,t.output);return o?[o]:[]}if(typeof t.type=="string"&&Lt.has(t.type)){let o=Z(t);return o?[o]:[]}if(typeof t.type=="string"&&qt.has(t.type)){let o=H(t);return o?[o]:[]}let e=v(t);return e?[e]:[]}).filter(t=>t!==null):[],st=(n,t)=>{var e,o;p(t)&&(X(n,"gen_ai.usage.input_tokens",(e=t.input_tokens)!=null?e:t.prompt_tokens),X(n,"gen_ai.usage.output_tokens",(o=t.output_tokens)!=null?o:t.completion_tokens))},Ut=(n,t)=>{let e={"gen_ai.provider.name":"openai.responses"};return _(e,"gen_ai.request.model",n.model),st(e,n.usage),S("gen_ai.prompt",Q(n.input),e),S("gen_ai.completion",Q(n.output),e),m(e,"openai_agents.model_config_json",n.model_config,t),m(e,"openai_agents.generation.raw_input_json",n.input,t),m(e,"openai_agents.generation.raw_output_json",n.output,t),e},$t=(n,t)=>{var r,a,i;let e={"gen_ai.provider.name":"openai.responses"},o=p(n._response)?n._response:{},s=p(o.usage)?o.usage:void 0;return _(e,"gen_ai.request.model",o.model),_(e,"gen_ai.response.model",o.model),_(e,"gen_ai.response.id",(a=(r=n.response_id)!=null?r:o.id)!=null?a:o.response_id),st(e,s),S("gen_ai.prompt",tt((i=n._input)!=null?i:o.input),e),S("gen_ai.completion",tt(o.output),e),m(e,"openai_agents.response.raw_json",o,t),_(e,"openai_agents.response.object",o.object),e},Wt=(n,t)=>{let e={node_type:"CODE_EXECUTION",tool_name:n.name,"openai_agents.function.name":n.name};return _(e,"function_input",n.input),_(e,"function_output",n.output),_(e,"openai_agents.function.input",n.input),_(e,"openai_agents.function.output",n.output),m(e,"openai_agents.function.mcp_data_json",n.mcp_data,t),e},Ft=(n,t)=>{let e={"openai_agents.agent.name":n.name};return _(e,"openai_agents.agent.output_type",n.output_type),m(e,"openai_agents.agent.handoffs_json",n.handoffs,t),m(e,"openai_agents.agent.tools_json",n.tools,t),e},Gt=n=>{let t={};return _(t,"openai_agents.handoff.from_agent",n.from_agent),_(t,"openai_agents.handoff.to_agent",n.to_agent),t},zt=n=>({"openai_agents.guardrail.name":n.name,"openai_agents.guardrail.triggered":n.triggered}),Kt=(n,t)=>{let e={"openai_agents.custom.name":n.name};return m(e,"openai_agents.custom.data_json",n.data,t),e},Bt=(n,t)=>t?{"openai_agents.raw_json":y(n)}:{},rt=()=>g,N=n=>n.spanData.type==="generation"||n.spanData.type==="response"?Nt:Ct,M=n=>{switch(n.spanData.type){case"function":return`Function: ${n.spanData.name}`;case"agent":return`Agent: ${n.spanData.name}`;case"guardrail":return`Guardrail: ${n.spanData.name}`;case"custom":return String(n.spanData.name);default:return n.spanData.type.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}},j=(n,t)=>{let e={"promptlayer.telemetry.source":"openai-agents-js","promptlayer.telemetry.source_version":rt(),"openai_agents.trace_id_original":n.traceId,"openai_agents.workflow_name":n.name};return n.groupId&&(e["openai_agents.group_id"]=n.groupId),p(n.metadata)&&(Object.entries(n.metadata).forEach(([o,s])=>{et(s)&&(e[`openai_agents.metadata.${Mt(o)}`]=s)}),m(e,"openai_agents.metadata_json",n.metadata,t)),e},L=n=>{let t={"promptlayer.telemetry.source":"openai-agents-js","promptlayer.telemetry.source_version":rt(),"openai_agents.span_id_original":n.spanId,"openai_agents.span_type":n.spanData.type};return n.parentId&&(t["openai_agents.parent_id_original"]=n.parentId),t},at=(n,t)=>{switch(n.type){case"generation":return Ut(n,t);case"response":return $t(n,t);case"function":return Wt(n,t);case"agent":return Ft(n,t);case"handoff":return Gt(n);case"guardrail":return zt(n);case"custom":return Kt(n,t);default:return Bt(n,t)}},I=0,it=1,lt=2;var U=n=>typeof n=="string"?{stringValue:n}:typeof n=="boolean"?{boolValue:n}:typeof n=="number"?Number.isInteger(n)?{intValue:String(n)}:{doubleValue:n}:n===null?{stringValue:"null"}:Array.isArray(n)?{arrayValue:{values:n.map(t=>U(t))}}:{kvlistValue:{values:Object.entries(n).map(([t,e])=>({key:t,value:U(e)}))}},q=n=>Object.entries(n).map(([t,e])=>({key:t,value:U(e)})),ct=(n,{serviceName:t="promptlayer-openai-agents-js",scopeName:e="promptlayer.integrations.openai_agents",scopeVersion:o=g}={})=>({resourceSpans:[{resource:{attributes:q({"service.name":t})},scopeSpans:[{scope:{name:e,version:o},spans:n.map(s=>{var a,i;let r={traceId:s.traceId,spanId:s.spanId,name:s.name,kind:s.kind,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:(a=s.endTimeUnixNano)!=null?a:s.startTimeUnixNano,attributes:q(s.attributes),events:((i=s.events)!=null?i:[]).map(l=>{var c;return{name:l.name,timeUnixNano:l.timeUnixNano,attributes:q((c=l.attributes)!=null?c:{})}}),links:[]};return s.parentSpanId&&(r.parentSpanId=s.parentSpanId),s.traceState&&(r.traceState=s.traceState),s.status&&(r.status=d({code:s.status.code},s.status.message?{message:s.status.message}:{})),r})}]}]});var pt=require("crypto"),Dt=/^[0-9a-f]{32}$/i,$=n=>(0,pt.createHash)("sha256").update(n,"utf8").digest("hex"),R=n=>{let t=n.startsWith("trace_")?n.slice(6):n;return Dt.test(t)?t.toLowerCase():$(n).slice(0,32)},w=n=>$(n).slice(0,16),W=n=>$(`${n}:root`).slice(0,16);var Vt=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})?$/,f=()=>(BigInt(Date.now())*BigInt(1e6)).toString(),T=n=>{if(!n)return;let t=Vt.exec(n);if(!t){let i=Date.parse(n);return Number.isNaN(i)?void 0:(BigInt(i)*BigInt(1e6)).toString()}let[,e,o="",s="Z"]=t,r=Date.parse(`${e}${s}`);if(Number.isNaN(r))return;let a=BigInt((o+"000000000").slice(0,9));return(BigInt(r)*BigInt(1e6)+a).toString()},ut=(...n)=>{let t=n.filter(e=>e!==void 0);return t.length===0?f():t.reduce((e,o)=>BigInt(o)<BigInt(e)?o:e)},dt=(...n)=>{let t=n.filter(e=>e!==void 0);return t.length===0?f():t.reduce((e,o)=>BigInt(o)>BigInt(e)?o:e)};var P=n=>{let t=n.length;for(;t>0&&n.charCodeAt(t-1)===47;)t-=1;return n.slice(0,t)};var Jt=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i,Yt="0".repeat(32),Xt="0".repeat(16),h=class{constructor({apiKey:t,baseURL:e,includeRawPayloads:o=!0}){this.traceStates=new Map;this.completedTraceQueue=new Map;this.pendingExports=new Map;this.apiKey=t,this.baseURL=P(e),this.includeRawPayloads=o}start(){}onTraceStart(t){return u(this,null,function*(){var s;if(this.traceStates.has(t.traceId))return;let e=this.resolveUpstreamTraceContext(t.metadata),o=(s=e==null?void 0:e.traceId)!=null?s:R(t.traceId);this.traceStates.set(t.traceId,{rootSpan:{traceId:o,spanId:W(t.traceId),name:t.name||"OpenAI Agents Trace",kind:1,startTimeUnixNano:f(),parentSpanId:e==null?void 0:e.parentSpanId,traceState:e==null?void 0:e.traceState,attributes:j(t,this.includeRawPayloads),status:{code:I},events:[]},spans:new Map})})}onTraceEnd(t){return u(this,null,function*(){let e=this.traceStates.get(t.traceId);if(!e)return;let o=Array.from(e.spans.values()).sort((l,c)=>BigInt(l.startTimeUnixNano)<BigInt(c.startTimeUnixNano)?-1:1),s=o.map(l=>l.startTimeUnixNano),r=o.map(l=>{var c;return(c=l.endTimeUnixNano)!=null?c:l.startTimeUnixNano}),a=dt(f(),...r);e.rootSpan.startTimeUnixNano=ut(e.rootSpan.startTimeUnixNano,...s),e.rootSpan.endTimeUnixNano=a;let i=ct([e.rootSpan,...o]);this.traceStates.delete(t.traceId),this.completedTraceQueue.set(t.traceId,i),this.startExportForTrace(t.traceId)})}onSpanStart(t){return u(this,null,function*(){var r;let e=this.ensureTraceStateForSpan(t),o=e.spans.get(t.spanId),s=o!=null?o:this.createSpanRecord(t,e.rootSpan.spanId);s.traceId=e.rootSpan.traceId,s.traceState=e.rootSpan.traceState,s.name=M(t),s.kind=N(t),s.startTimeUnixNano=(r=T(t.startedAt))!=null?r:s.startTimeUnixNano,s.parentSpanId=t.parentId?w(t.parentId):e.rootSpan.spanId,s.attributes=d(d({},s.attributes),L(t)),e.spans.set(t.spanId,s)})}onSpanEnd(t){return u(this,null,function*(){var s,r,a,i;let e=this.ensureTraceStateForSpan(t),o=(s=e.spans.get(t.spanId))!=null?s:this.createSpanRecord(t,e.rootSpan.spanId);o.attributes=d(d({},o.attributes),at(t.spanData,this.includeRawPayloads)),o.endTimeUnixNano=(a=(r=T(t.endedAt))!=null?r:o.endTimeUnixNano)!=null?a:f(),o.status=this.statusForSpan(t),t.error&&(o.events=[...(i=o.events)!=null?i:[],{name:"exception",timeUnixNano:o.endTimeUnixNano,attributes:{"exception.type":"OpenAIAgentsError","exception.message":t.error.message,"openai_agents.error_json":JSON.stringify(t.error)}}]),e.spans.set(t.spanId,o)})}shutdown(){return u(this,null,function*(){yield this.forceFlush()})}forceFlush(){return u(this,null,function*(){for(let t=0;t<2;t+=1){for(let e of this.completedTraceQueue.keys())this.startExportForTrace(e);if(this.pendingExports.size===0||(yield Promise.all(Array.from(this.pendingExports.values())),this.completedTraceQueue.size===0))return}})}traceLikeFromSpan(t){var s,r,a,i,l;let e=this.asRecord(t.traceMetadata),o=this.asRecord(e==null?void 0:e.metadata);return{traceId:t.traceId,name:(r=(s=this.readString(e==null?void 0:e.workflow_name))!=null?s:this.readString(e==null?void 0:e.workflowName))!=null?r:"OpenAI Agents Trace",groupId:(i=(a=this.readString(e==null?void 0:e.group_id))!=null?a:this.readString(e==null?void 0:e.groupId))!=null?i:null,metadata:(l=o!=null?o:e)!=null?l:{}}}ensureTraceStateForSpan(t){var i,l;let e=this.traceStates.get(t.traceId);if(e)return e;let o=this.traceLikeFromSpan(t),s=this.resolveUpstreamTraceContext(o.metadata),a={rootSpan:{traceId:(i=s==null?void 0:s.traceId)!=null?i:R(t.traceId),spanId:W(t.traceId),name:o.name,kind:1,startTimeUnixNano:(l=T(t.startedAt))!=null?l:f(),parentSpanId:s==null?void 0:s.parentSpanId,traceState:s==null?void 0:s.traceState,attributes:j(o,this.includeRawPayloads),status:{code:I},events:[]},spans:new Map};return this.traceStates.set(t.traceId,a),a}createSpanRecord(t,e){var o,s,r,a;return{traceId:(s=(o=this.traceStates.get(t.traceId))==null?void 0:o.rootSpan.traceId)!=null?s:R(t.traceId),spanId:w(t.spanId),parentSpanId:t.parentId?w(t.parentId):e,name:M(t),kind:N(t),startTimeUnixNano:(r=T(t.startedAt))!=null?r:f(),traceState:(a=this.traceStates.get(t.traceId))==null?void 0:a.rootSpan.traceState,attributes:d({},L(t)),status:{code:I},events:[]}}statusForSpan(t){return t.error?{code:lt,message:t.error.message}:{code:it}}exportPayload(t){return u(this,null,function*(){let e=yield J(`${this.baseURL}/v1/traces`,{method:"POST",headers:d({"Content-Type":"application/json","X-API-KEY":this.apiKey,"X-PromptLayer-Integration":"openai-agents-js"},V()),body:JSON.stringify(t)});if(!e.ok)throw new Error(`Failed to export OpenAI Agents traces: ${e.status} ${e.statusText}`)})}startExportForTrace(t){if(this.pendingExports.has(t))return;let e=this.completedTraceQueue.get(t);if(!e)return;let o=this.exportPayload(e).then(()=>{this.completedTraceQueue.delete(t)}).catch(s=>{console.error(`Failed to export OpenAI Agents trace '${t}'.`,s)}).finally(()=>{this.pendingExports.delete(t)});this.pendingExports.set(t,o)}resolveUpstreamTraceContext(t){let e=this.asRecord(t);if(!e)return null;let o=e.traceparent;if(typeof o!="string"||!o.trim())return null;let s=o.trim().match(Jt);if(!s)return null;let[,r,a,i]=s,l=r.toLowerCase(),c=a.toLowerCase(),k=i.toLowerCase();if(l==="ff"||c===Yt||k===Xt)return null;let mt=typeof e.tracestate=="string"&&e.tracestate.trim()?e.tracestate.trim():void 0;return{traceId:c,parentSpanId:k,traceState:mt}}asRecord(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}readString(t){return typeof t=="string"&&t.trim()?t:void 0}};var Zt=n=>{var t;return P((t=n!=null?n:C("PROMPTLAYER_BASE_URL"))!=null?t:"https://api.promptlayer.com")},_t=(...s)=>u(null,[...s],function*({apiKey:n,baseURL:t,exclusive:e=!0,includeRawPayloads:o=!0}={}){let r=Y(n),a=yield import("@openai/agents"),i=new h({apiKey:r,baseURL:Zt(t),includeRawPayloads:o});return e?a.setTraceProcessors([i]):a.addTraceProcessor(i),i});0&&(module.exports={PromptLayerOpenAIAgentsProcessor,instrumentOpenAIAgents});
1
+ "use strict";var ft=Object.create;var b=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols,ht=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty,bt=Object.prototype.propertyIsEnumerable;var z=(n,t,e)=>t in n?b(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,d=(n,t)=>{for(var e in t||(t={}))K.call(t,e)&&z(n,e,t[e]);if(G)for(var e of G(t))bt.call(t,e)&&z(n,e,t[e]);return n};var xt=(n,t)=>{for(var e in t)b(n,e,{get:t[e],enumerable:!0})},B=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yt(t))!K.call(n,s)&&s!==e&&b(n,s,{get:()=>t[s],enumerable:!(o=gt(t,s))||o.enumerable});return n};var O=(n,t,e)=>(e=n!=null?ft(ht(n)):{},B(t||!n||!n.__esModule?b(e,"default",{value:n,enumerable:!0}):e,n)),At=n=>B(b({},"__esModule",{value:!0}),n);var u=(n,t,e)=>new Promise((o,s)=>{var r=l=>{try{i(e.next(l))}catch(p){s(p)}},a=l=>{try{i(e.throw(l))}catch(p){s(p)}},i=l=>l.done?o(l.value):Promise.resolve(l.value).then(r,a);i((e=e.apply(n,t)).next())});var Qt={};xt(Qt,{PromptLayerOpenAIAgentsProcessor:()=>h,instrumentOpenAIAgents:()=>_t});module.exports=At(Qt);var wt=O(require("ably")),Pt=require("centrifuge"),V=O(require("p-retry"));var g="1.3.4",kt=()=>{var n;if(typeof process!="undefined"&&((n=process.versions)!=null&&n.node)){let t=process.versions.node.split(".");return`${t[0]}.${t[1]}`}return"unknown"},Ot=kt(),Et=`promptlayer-js/${g} (node ${Ot})`,J=()=>({"User-Agent":Et,"X-SDK-Version":g});var E=class extends Error{constructor(t,e){super(`Server error: ${t} ${e}`),this.name="PromptLayerRetryableHttpError",this.status=t,this.statusText=e}};var Y=(n,t)=>u(null,null,function*(){return(0,V.default)(()=>u(null,null,function*(){let e=yield fetch(n,t);if(e.status>=500&&e.status<600||e.status===429)throw new E(e.status,e.statusText);return e}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:e=>{console.info(`PromptLayer API request attempt ${e.attemptNumber} failed. ${e.retriesLeft} retries left.`)}})});var C=n=>{var t,e,o,s,r,a;if(typeof globalThis.process!="undefined")return(o=(e=(t=globalThis.process.env)==null?void 0:t[n])==null?void 0:e.trim())!=null?o:void 0;if(typeof globalThis.Deno!="undefined")return(a=(r=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:r.call(s,n))==null?void 0:a.trim()},X=n=>{if(n!==void 0){let e=n.trim();if(!e)throw new Error("PromptLayer API key not provided. Please set PROMPTLAYER_API_KEY or pass apiKey.");return e}let t=C("PROMPTLAYER_API_KEY");if(!t)throw new Error("PromptLayer API key not provided. Please set PROMPTLAYER_API_KEY or pass apiKey.");return t};var Ct=1,Nt=3,c=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),et=n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean",Mt=n=>n.replace(/[^a-zA-Z0-9_.-]/g,"_"),A=n=>n===null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:Array.isArray(n)?n.map(t=>A(t)):c(n)?Object.fromEntries(Object.entries(n).map(([t,e])=>[t,A(e)])):String(n),y=n=>{let t=e=>Array.isArray(e)?e.map(o=>t(o)):c(e)?Object.keys(e).sort().reduce((o,s)=>(o[s]=t(e[s]),o),{}):e;return JSON.stringify(t(A(n)))},_=(n,t,e)=>{e!=null&&e!==""&&(n[t]=String(e))},N=(n,t,e)=>{if(e!=null&&e!==""){let o=Number(e);Number.isNaN(o)||(n[t]=o)}},m=(n,t,e,o)=>{o&&e!==void 0&&e!==null&&(n[t]=y(e))},T=(n,t,e)=>{t.forEach((o,s)=>{Object.entries(o).forEach(([r,a])=>{e[`${n}.${s}.${r}`]=et(a)?a:y(a)})})},nt=n=>Array.isArray(n)?n.map(t=>{var r,a,i,l,p;if(!c(t))return null;let e=c(t.function)?t.function:null,o=(a=(r=e==null?void 0:e.name)!=null?r:t.name)!=null?a:"tool",s=(l=(i=e==null?void 0:e.arguments)!=null?i:t.arguments)!=null?l:{};if(typeof s=="string")try{s=JSON.parse(s)}catch(k){s=s}return{id:String((p=t.id)!=null?p:""),type:"tool_call",name:String(o),arguments:A(s)}}).filter(t=>t!==null):[],ot=n=>{var e,o;let t=(o=(e=n.call_id)!=null?e:n.callId)!=null?o:n.id;return t!=null?String(t):void 0},Lt=n=>{if(n==null)return;if(typeof n=="string")return n;if(Array.isArray(n)){let e=x(n);return e!=null?e:y(n)}if(c(n)){let e=x([n]);return e!=null?e:y(n)}let t=x(n);return t!==void 0?t:y(n)},Z=n=>{var e,o,s;let t=(e=n.arguments)!=null?e:{};if(typeof t=="string")try{t=JSON.parse(t)}catch(r){t=t}return{role:"assistant",tool_calls:[{id:(o=ot(n))!=null?o:"",type:"tool_call",name:String((s=n.name)!=null?s:"tool"),arguments:A(t)}]}},H=(n,t)=>{var r;let e=ot(n),o=Lt((r=t!=null?t:n.output)!=null?r:n.content);if(!e&&!o)return null;let s={role:"tool"};return e&&(s.tool_call_id=e),o!==void 0&&(s.content=o),s};function x(n){if(n!=null){if(typeof n=="string")return n;if(Array.isArray(n)){let t=n.map(e=>{var s;if(!c(e))return null;let o=e.type;if(o==="text"||o==="input_text"||o==="output_text"){let r=(s=e.text)!=null?s:e.content;return r!=null?String(r):null}return null}).filter(e=>e!==null);return t.length>0?t.join(`
2
+ `):void 0}return String(n)}}var Q=n=>Array.isArray(n)?n.map(t=>{if(!c(t))return null;let e={};t.role!==void 0&&(e.role=String(t.role));let o=x(t.content);o&&(e.content=o);let s=nt(t.tool_calls);return s.length>0&&(e.tool_calls=s),t.tool_call_id&&(e.tool_call_id=String(t.tool_call_id)),Object.keys(e).length>0?e:null}).filter(t=>t!==null):[],v=n=>{let t={},e=n.role,o=x(n.content),s=nt(n.tool_calls);return e!=null?t.role=String(e):(o||s.length>0)&&(t.role="assistant"),o&&(t.content=o),s.length>0&&(t.tool_calls=s),n.tool_call_id&&(t.tool_call_id=String(n.tool_call_id)),Object.keys(t).length>0?t:null},jt=n=>{let t=n.summary;if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.map(o=>{var r;if(!c(o))return null;let s=(r=o.text)!=null?r:o.content;return s!=null?String(s):null}).filter(o=>o!==null&&o!=="");return e.length>0?e.join(`
3
+
4
+ `):void 0},qt=new Set(["function_call","computer_call","shell_call","apply_patch_call","custom_tool_call","mcp_call"]),Ut=new Set(["function_call_output","function_call_result","computer_call_output","computer_call_result","shell_call_output","apply_patch_call_output","custom_tool_call_output"]),tt=n=>typeof n=="string"?[{role:"user",content:n}]:Array.isArray(n)?n.flatMap(t=>{if(!c(t))return[];if(t.type==="reasoning"){let o=jt(t);return o?[{role:"assistant",thinking:o}]:[]}if(t.type==="message_output_item"&&c(t.rawItem)){let o=v(t.rawItem);return o?[o]:[]}if(t.type==="tool_call_item"&&c(t.rawItem)){let o=Z(t.rawItem);return o?[o]:[]}if(t.type==="tool_call_output_item"&&c(t.rawItem)){let o=H(t.rawItem,t.output);return o?[o]:[]}if(typeof t.type=="string"&&qt.has(t.type)){let o=Z(t);return o?[o]:[]}if(typeof t.type=="string"&&Ut.has(t.type)){let o=H(t);return o?[o]:[]}let e=v(t);return e?[e]:[]}).filter(t=>t!==null):[],st=(n,t)=>{var o,s;if(!c(t))return;N(n,"gen_ai.usage.input_tokens",(o=t.input_tokens)!=null?o:t.prompt_tokens),N(n,"gen_ai.usage.output_tokens",(s=t.output_tokens)!=null?s:t.completion_tokens);let e=c(t.output_tokens_details)?t.output_tokens_details:c(t.completion_tokens_details)?t.completion_tokens_details:void 0;N(n,"gen_ai.usage.reasoning.output_tokens",e==null?void 0:e.reasoning_tokens)},$t=(n,t)=>{let e={node_type:"LLM_CALL","gen_ai.provider.name":"openai.responses"};return _(e,"gen_ai.request.model",n.model),st(e,n.usage),T("gen_ai.prompt",Q(n.input),e),T("gen_ai.completion",Q(n.output),e),m(e,"openai_agents.model_config_json",n.model_config,t),m(e,"openai_agents.generation.raw_input_json",n.input,t),m(e,"openai_agents.generation.raw_output_json",n.output,t),e},Wt=(n,t)=>{var r,a,i;let e={node_type:"LLM_CALL","gen_ai.provider.name":"openai.responses"},o=c(n._response)?n._response:{},s=c(o.usage)?o.usage:void 0;return _(e,"gen_ai.request.model",o.model),_(e,"gen_ai.response.model",o.model),_(e,"gen_ai.response.id",(a=(r=n.response_id)!=null?r:o.id)!=null?a:o.response_id),st(e,s),T("gen_ai.prompt",tt((i=n._input)!=null?i:o.input),e),T("gen_ai.completion",tt(o.output),e),m(e,"openai_agents.response.raw_json",o,t),_(e,"openai_agents.response.object",o.object),e},Ft=(n,t)=>{let e={node_type:"CODE_EXECUTION",tool_name:n.name,"openai_agents.function.name":n.name};return _(e,"function_input",n.input),_(e,"function_output",n.output),_(e,"openai_agents.function.input",n.input),_(e,"openai_agents.function.output",n.output),m(e,"openai_agents.function.mcp_data_json",n.mcp_data,t),e},Gt=(n,t)=>{let e={node_type:"LLM_SESSION","openai_agents.agent.name":n.name};return _(e,"openai_agents.agent.output_type",n.output_type),m(e,"openai_agents.agent.handoffs_json",n.handoffs,t),m(e,"openai_agents.agent.tools_json",n.tools,t),e},zt=n=>{let t={};return _(t,"openai_agents.handoff.from_agent",n.from_agent),_(t,"openai_agents.handoff.to_agent",n.to_agent),t},Kt=n=>({"openai_agents.guardrail.name":n.name,"openai_agents.guardrail.triggered":n.triggered}),Bt=(n,t)=>{let e={"openai_agents.custom.name":n.name};return m(e,"openai_agents.custom.data_json",n.data,t),e},Dt=(n,t)=>t?{"openai_agents.raw_json":y(n)}:{},rt=()=>g,M=n=>n.spanData.type==="generation"||n.spanData.type==="response"?Nt:Ct,L=n=>{switch(n.spanData.type){case"function":return`Tool: ${n.spanData.name}`;case"generation":case"response":return"LLM call";case"agent":return"LLM session";case"guardrail":return`Guardrail: ${n.spanData.name}`;case"custom":return String(n.spanData.name);default:return n.spanData.type.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}},j=(n,t)=>{let e={node_type:"LLM_SESSION","promptlayer.telemetry.source":"openai-agents-js","promptlayer.telemetry.source_version":rt(),"openai_agents.trace_id_original":n.traceId,"openai_agents.workflow_name":n.name};return n.groupId&&(e["openai_agents.group_id"]=n.groupId),c(n.metadata)&&(Object.entries(n.metadata).forEach(([o,s])=>{et(s)&&(e[`openai_agents.metadata.${Mt(o)}`]=s)}),m(e,"openai_agents.metadata_json",n.metadata,t)),e},q=n=>{let t={"promptlayer.telemetry.source":"openai-agents-js","promptlayer.telemetry.source_version":rt(),"openai_agents.span_id_original":n.spanId,"openai_agents.span_type":n.spanData.type};return n.parentId&&(t["openai_agents.parent_id_original"]=n.parentId),t},at=(n,t)=>{switch(n.type){case"generation":return $t(n,t);case"response":return Wt(n,t);case"function":return Ft(n,t);case"agent":return Gt(n,t);case"handoff":return zt(n);case"guardrail":return Kt(n);case"custom":return Bt(n,t);default:return Dt(n,t)}},I=0,it=1,lt=2;var $=n=>typeof n=="string"?{stringValue:n}:typeof n=="boolean"?{boolValue:n}:typeof n=="number"?Number.isInteger(n)?{intValue:String(n)}:{doubleValue:n}:n===null?{stringValue:"null"}:Array.isArray(n)?{arrayValue:{values:n.map(t=>$(t))}}:{kvlistValue:{values:Object.entries(n).map(([t,e])=>({key:t,value:$(e)}))}},U=n=>Object.entries(n).map(([t,e])=>({key:t,value:$(e)})),ct=(n,{serviceName:t="promptlayer-openai-agents-js",scopeName:e="promptlayer.integrations.openai_agents",scopeVersion:o=g}={})=>({resourceSpans:[{resource:{attributes:U({"service.name":t})},scopeSpans:[{scope:{name:e,version:o},spans:n.map(s=>{var a,i;let r={traceId:s.traceId,spanId:s.spanId,name:s.name,kind:s.kind,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:(a=s.endTimeUnixNano)!=null?a:s.startTimeUnixNano,attributes:U(s.attributes),events:((i=s.events)!=null?i:[]).map(l=>{var p;return{name:l.name,timeUnixNano:l.timeUnixNano,attributes:U((p=l.attributes)!=null?p:{})}}),links:[]};return s.parentSpanId&&(r.parentSpanId=s.parentSpanId),s.traceState&&(r.traceState=s.traceState),s.status&&(r.status=d({code:s.status.code},s.status.message?{message:s.status.message}:{})),r})}]}]});var pt=require("crypto"),Vt=/^[0-9a-f]{32}$/i,W=n=>(0,pt.createHash)("sha256").update(n,"utf8").digest("hex"),R=n=>{let t=n.startsWith("trace_")?n.slice(6):n;return Vt.test(t)?t.toLowerCase():W(n).slice(0,32)},w=n=>W(n).slice(0,16),F=n=>W(`${n}:root`).slice(0,16);var Jt=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})?$/,f=()=>(BigInt(Date.now())*BigInt(1e6)).toString(),S=n=>{if(!n)return;let t=Jt.exec(n);if(!t){let i=Date.parse(n);return Number.isNaN(i)?void 0:(BigInt(i)*BigInt(1e6)).toString()}let[,e,o="",s="Z"]=t,r=Date.parse(`${e}${s}`);if(Number.isNaN(r))return;let a=BigInt((o+"000000000").slice(0,9));return(BigInt(r)*BigInt(1e6)+a).toString()},ut=(...n)=>{let t=n.filter(e=>e!==void 0);return t.length===0?f():t.reduce((e,o)=>BigInt(o)<BigInt(e)?o:e)},dt=(...n)=>{let t=n.filter(e=>e!==void 0);return t.length===0?f():t.reduce((e,o)=>BigInt(o)>BigInt(e)?o:e)};var P=n=>{let t=n.length;for(;t>0&&n.charCodeAt(t-1)===47;)t-=1;return n.slice(0,t)};var Yt=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i,Xt="0".repeat(32),Zt="0".repeat(16),h=class{constructor({apiKey:t,baseURL:e,includeRawPayloads:o=!0}){this.traceStates=new Map;this.completedTraceQueue=new Map;this.pendingExports=new Map;this.apiKey=t,this.baseURL=P(e),this.includeRawPayloads=o}start(){}onTraceStart(t){return u(this,null,function*(){var s;if(this.traceStates.has(t.traceId))return;let e=this.resolveUpstreamTraceContext(t.metadata),o=(s=e==null?void 0:e.traceId)!=null?s:R(t.traceId);this.traceStates.set(t.traceId,{rootSpan:{traceId:o,spanId:F(t.traceId),name:"OpenAI session",kind:1,startTimeUnixNano:f(),parentSpanId:e==null?void 0:e.parentSpanId,traceState:e==null?void 0:e.traceState,attributes:j(t,this.includeRawPayloads),status:{code:I},events:[]},spans:new Map})})}onTraceEnd(t){return u(this,null,function*(){let e=this.traceStates.get(t.traceId);if(!e)return;let o=Array.from(e.spans.values()).sort((l,p)=>BigInt(l.startTimeUnixNano)<BigInt(p.startTimeUnixNano)?-1:1),s=o.map(l=>l.startTimeUnixNano),r=o.map(l=>{var p;return(p=l.endTimeUnixNano)!=null?p:l.startTimeUnixNano}),a=dt(f(),...r);e.rootSpan.startTimeUnixNano=ut(e.rootSpan.startTimeUnixNano,...s),e.rootSpan.endTimeUnixNano=a;let i=ct([e.rootSpan,...o]);this.traceStates.delete(t.traceId),this.completedTraceQueue.set(t.traceId,i),this.startExportForTrace(t.traceId)})}onSpanStart(t){return u(this,null,function*(){var r;let e=this.ensureTraceStateForSpan(t),o=e.spans.get(t.spanId),s=o!=null?o:this.createSpanRecord(t,e.rootSpan.spanId);s.traceId=e.rootSpan.traceId,s.traceState=e.rootSpan.traceState,s.name=L(t),s.kind=M(t),s.startTimeUnixNano=(r=S(t.startedAt))!=null?r:s.startTimeUnixNano,s.parentSpanId=t.parentId?w(t.parentId):e.rootSpan.spanId,s.attributes=d(d({},s.attributes),q(t)),e.spans.set(t.spanId,s)})}onSpanEnd(t){return u(this,null,function*(){var s,r,a,i;let e=this.ensureTraceStateForSpan(t),o=(s=e.spans.get(t.spanId))!=null?s:this.createSpanRecord(t,e.rootSpan.spanId);o.attributes=d(d({},o.attributes),at(t.spanData,this.includeRawPayloads)),o.endTimeUnixNano=(a=(r=S(t.endedAt))!=null?r:o.endTimeUnixNano)!=null?a:f(),o.status=this.statusForSpan(t),t.error&&(o.events=[...(i=o.events)!=null?i:[],{name:"exception",timeUnixNano:o.endTimeUnixNano,attributes:{"exception.type":"OpenAIAgentsError","exception.message":t.error.message,"openai_agents.error_json":JSON.stringify(t.error)}}]),e.spans.set(t.spanId,o)})}shutdown(){return u(this,null,function*(){yield this.forceFlush()})}forceFlush(){return u(this,null,function*(){for(let t=0;t<2;t+=1){for(let e of this.completedTraceQueue.keys())this.startExportForTrace(e);if(this.pendingExports.size===0||(yield Promise.all(Array.from(this.pendingExports.values())),this.completedTraceQueue.size===0))return}})}traceLikeFromSpan(t){var s,r,a,i,l;let e=this.asRecord(t.traceMetadata),o=this.asRecord(e==null?void 0:e.metadata);return{traceId:t.traceId,name:(r=(s=this.readString(e==null?void 0:e.workflow_name))!=null?s:this.readString(e==null?void 0:e.workflowName))!=null?r:"OpenAI Agents Trace",groupId:(i=(a=this.readString(e==null?void 0:e.group_id))!=null?a:this.readString(e==null?void 0:e.groupId))!=null?i:null,metadata:(l=o!=null?o:e)!=null?l:{}}}ensureTraceStateForSpan(t){var i,l;let e=this.traceStates.get(t.traceId);if(e)return e;let o=this.traceLikeFromSpan(t),s=this.resolveUpstreamTraceContext(o.metadata),a={rootSpan:{traceId:(i=s==null?void 0:s.traceId)!=null?i:R(t.traceId),spanId:F(t.traceId),name:"OpenAI session",kind:1,startTimeUnixNano:(l=S(t.startedAt))!=null?l:f(),parentSpanId:s==null?void 0:s.parentSpanId,traceState:s==null?void 0:s.traceState,attributes:j(o,this.includeRawPayloads),status:{code:I},events:[]},spans:new Map};return this.traceStates.set(t.traceId,a),a}createSpanRecord(t,e){var o,s,r,a;return{traceId:(s=(o=this.traceStates.get(t.traceId))==null?void 0:o.rootSpan.traceId)!=null?s:R(t.traceId),spanId:w(t.spanId),parentSpanId:t.parentId?w(t.parentId):e,name:L(t),kind:M(t),startTimeUnixNano:(r=S(t.startedAt))!=null?r:f(),traceState:(a=this.traceStates.get(t.traceId))==null?void 0:a.rootSpan.traceState,attributes:d({},q(t)),status:{code:I},events:[]}}statusForSpan(t){return t.error?{code:lt,message:t.error.message}:{code:it}}exportPayload(t){return u(this,null,function*(){let e=yield Y(`${this.baseURL}/v1/traces`,{method:"POST",headers:d({"Content-Type":"application/json","X-API-KEY":this.apiKey,"X-PromptLayer-Integration":"openai-agents-js"},J()),body:JSON.stringify(t)});if(!e.ok)throw new Error(`Failed to export OpenAI Agents traces: ${e.status} ${e.statusText}`)})}startExportForTrace(t){if(this.pendingExports.has(t))return;let e=this.completedTraceQueue.get(t);if(!e)return;let o=this.exportPayload(e).then(()=>{this.completedTraceQueue.delete(t)}).catch(s=>{console.error(`Failed to export OpenAI Agents trace '${t}'.`,s)}).finally(()=>{this.pendingExports.delete(t)});this.pendingExports.set(t,o)}resolveUpstreamTraceContext(t){let e=this.asRecord(t);if(!e)return null;let o=e.traceparent;if(typeof o!="string"||!o.trim())return null;let s=o.trim().match(Yt);if(!s)return null;let[,r,a,i]=s,l=r.toLowerCase(),p=a.toLowerCase(),k=i.toLowerCase();if(l==="ff"||p===Xt||k===Zt)return null;let mt=typeof e.tracestate=="string"&&e.tracestate.trim()?e.tracestate.trim():void 0;return{traceId:p,parentSpanId:k,traceState:mt}}asRecord(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}readString(t){return typeof t=="string"&&t.trim()?t:void 0}};var Ht=n=>{var t;return P((t=n!=null?n:C("PROMPTLAYER_BASE_URL"))!=null?t:"https://api.promptlayer.com")},_t=(...s)=>u(null,[...s],function*({apiKey:n,baseURL:t,exclusive:e=!0,includeRawPayloads:o=!0}={}){let r=X(n),a=yield import("@openai/agents"),i=new h({apiKey:r,baseURL:Ht(t),includeRawPayloads:o});return e?a.setTraceProcessors([i]):a.addTraceProcessor(i),i});0&&(module.exports={PromptLayerOpenAIAgentsProcessor,instrumentOpenAIAgents});
3
5
  //# sourceMappingURL=openai-agents.js.map