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