@mcp-use/inspector 0.4.10 → 0.4.11-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/cli.js +3 -3
  2. package/dist/client/assets/chunk-VL2OQCWN-BE4txAap.js +8 -0
  3. package/dist/client/assets/{embeddings-BvWgxmh-.js → embeddings-D0mnwVrX.js} +1 -1
  4. package/dist/client/assets/{index-F8MAAt6D.js → index-B0MYHYe6.js} +1 -1
  5. package/dist/client/assets/{index-CWYxvW-c.js → index-BEMSyME5.js} +2 -2
  6. package/dist/client/assets/{index-DHsHh1_g.js → index-BgupETL3.js} +1 -1
  7. package/dist/client/assets/{index-Dnm19mgK.js → index-CQ9XIRcv.js} +2 -2
  8. package/dist/client/assets/index-DrYUC3_O.js +1775 -0
  9. package/dist/client/assets/index-mBO7pd_t.js +1 -0
  10. package/dist/client/assets/index-wkxN17B9.js +4 -0
  11. package/dist/client/assets/langfuse-MO3AMDBE-DYoZ4Kwk.js +570 -0
  12. package/dist/client/index.html +2 -2
  13. package/dist/server/{chunk-UAGOQUEV.js → chunk-5JZ2RXUR.js} +3 -3
  14. package/dist/server/{chunk-GZSRGACL.js → chunk-AFTM3F6I.js} +1 -1
  15. package/dist/server/{chunk-G2KU64MV.js → chunk-JTBAUVJ3.js} +1 -1
  16. package/dist/server/{chunk-HPZTE753.js → chunk-RK4WSNY7.js} +3 -3
  17. package/dist/server/{chunk-BE2QCYB4.js → chunk-VMVT3HVZ.js} +3 -3
  18. package/dist/server/cli.js +4 -4
  19. package/dist/server/index.js +5 -5
  20. package/dist/server/middleware.js +5 -5
  21. package/dist/server/server.js +5 -5
  22. package/dist/server/shared-routes.js +2 -2
  23. package/dist/server/shared-static.js +2 -2
  24. package/dist/server/shared-utils-browser.js +1 -1
  25. package/dist/server/shared-utils.js +1 -1
  26. package/package.json +2 -2
  27. package/dist/client/assets/browser-BkJdGGVq.js +0 -611
  28. package/dist/client/assets/chunk-VL2OQCWN-Dm4XquLI.js +0 -8
  29. package/dist/client/assets/index-BxUJEXs5.js +0 -1734
  30. package/dist/client/assets/index-CEkgKN2t.js +0 -1
  31. package/dist/client/assets/index-WLUXcbDv.js +0 -4
  32. package/dist/client/assets/langfuse-6AJGHMAV-QljN0jPu.js +0 -1
  33. package/dist/client/assets/v4-BKrj-4V8.js +0 -1
@@ -1,611 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-WLUXcbDv.js","assets/index-CEkgKN2t.js","assets/index-BxUJEXs5.js","assets/index-Ba21hizt.css","assets/chunk-VL2OQCWN-Dm4XquLI.js","assets/v4-BKrj-4V8.js","assets/langfuse-6AJGHMAV-QljN0jPu.js"])))=>i.map(i=>d[i]);
2
- var BS=Object.defineProperty;var zS=(e,t,r)=>t in e?BS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var cs=(e,t,r)=>zS(e,typeof t!="symbol"?t+"":t,r);import{b as sc,_ as le,c as Di,d as Rc,u as jr,a as Ut,e as Qf,n as Xt,s as nt,f as yn,o as Pe,h as qS,Z as ie,i as wr,j as kh,l as Vu,k as HS,m as Fy,p as Uy,q as Fi,r as ed,t as By,g as GS,S as VS,C as Ih,v as WS,w as JS,B as KS,x as ZS}from"./index-BxUJEXs5.js";import{u as YS,w as XS,s as QS,x as eE,y as td,z as tE,v as et,P as Dr,p as xo,a as xs,b as zy,c as qy,g as ot,i as rd,d as fn,j as nd,k as rE,h as nE,_ as iE,$ as sE,e as aE,f as oE,t as Mh,l as Hy,V as id,m as cE,n as li,o as lE,T as uE,A as pt,B as fE,C as dE,D as hE,E as pE,F as mE,G as gE,H as yE,I as _E,J as vE,K as wE,L as bE,M as SE,N as Gy,O as EE,Q as TE,R as Po,S as CE,U as AE,W as OE,X as xE,Y as PE,Z as kE,a0 as IE,a1 as ME,a2 as RE,a3 as NE,a4 as $E,a5 as Rh,a6 as LE,a7 as jE,a8 as DE,q as FE,r as UE,a9 as BE}from"./chunk-VL2OQCWN-Dm4XquLI.js";import{AsyncLocalStorage as Vy}from"node:async_hooks";import{v as Wy}from"./v4-BKrj-4V8.js";var Nc={},ya={},$c,Nh;function Gt(){if(Nh)return $c;Nh=1;function e(p){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m},e(p)}function t(p,m,w){return Object.defineProperty(p,"prototype",{writable:!1}),p}function r(p,m){if(!(p instanceof m))throw new TypeError("Cannot call a class as a function")}function n(p,m,w){return m=f(m),i(p,l()?Reflect.construct(m,w||[],f(p).constructor):m.apply(p,w))}function i(p,m){if(m&&(e(m)=="object"||typeof m=="function"))return m;if(m!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return s(p)}function s(p){if(p===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return p}function a(p,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function");p.prototype=Object.create(m&&m.prototype,{constructor:{value:p,writable:!0,configurable:!0}}),Object.defineProperty(p,"prototype",{writable:!1}),m&&d(p,m)}function o(p){var m=typeof Map=="function"?new Map:void 0;return o=function(y){if(y===null||!u(y))return y;if(typeof y!="function")throw new TypeError("Super expression must either be null or a function");if(m!==void 0){if(m.has(y))return m.get(y);m.set(y,g)}function g(){return c(y,arguments,f(this).constructor)}return g.prototype=Object.create(y.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),d(g,y)},o(p)}function c(p,m,w){if(l())return Reflect.construct.apply(null,arguments);var y=[null];y.push.apply(y,m);var g=new(p.bind.apply(p,y));return w&&d(g,w.prototype),g}function l(){try{var p=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(l=function(){return!!p})()}function u(p){try{return Function.toString.call(p).indexOf("[native code]")!==-1}catch{return typeof p=="function"}}function d(p,m){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(w,y){return w.__proto__=y,w},d(p,m)}function f(p){return f=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(m){return m.__proto__||Object.getPrototypeOf(m)},f(p)}var h=(function(p){function m(w){var y;return r(this,m),y=n(this,m,[`Format functions must be synchronous taking a two arguments: (info, opts)
3
- Found: `.concat(w.toString().split(`
4
- `)[0],`
5
- `)]),Error.captureStackTrace(y,m),y}return a(m,p),t(m)})(o(Error));return $c=function(p){if(p.length>2)throw new h(p);function m(){var y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.options=y}m.prototype.transform=p;function w(y){return new m(y)}return w.Format=m,w},$c}var ls={exports:{}},Lc={exports:{}},jc={exports:{}};function Jy(){return()=>{}}function Ky(e){return JSON.stringify(e)}function Zy(){}function Yy(){}const zE={debuglog:Jy,inspect:Ky,inherits:Zy,format:Yy},qE=Object.freeze(Object.defineProperty({__proto__:null,debuglog:Jy,default:zE,format:Yy,inherits:Zy,inspect:Ky},Symbol.toStringTag,{value:"Module"})),Ar=sc(qE);var Dc={exports:{}},$h;function HE(){return $h||($h=1,(function(e){var t={};e.exports=t;var r={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(r).forEach(function(n){var i=r[n],s=t[n]=[];s.open="\x1B["+i[0]+"m",s.close="\x1B["+i[1]+"m"})})(Dc)),Dc.exports}const GE={},Ps=Object.freeze(Object.defineProperty({__proto__:null,default:GE},Symbol.toStringTag,{value:"Module"})),br=sc(Ps);var Fc,Lh;function VE(){return Lh||(Lh=1,Fc=function(e,t){t=t||process.argv||[];var r=t.indexOf("--"),n=/^-{1,2}/.test(e)?"":"--",i=t.indexOf(n+e);return i!==-1&&(r===-1?!0:i<r)}),Fc}var Uc,jh;function WE(){if(jh)return Uc;jh=1;var e={},t=VE(),r=e,n=void 0;t("no-color")||t("no-colors")||t("color=false")?n=!1:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(n=!0),"FORCE_COLOR"in r&&(n=r.FORCE_COLOR.length===0||parseInt(r.FORCE_COLOR,10)!==0);function i(o){return o===0?!1:{level:o,hasBasic:!0,has256:o>=2,has16m:o>=3}}function s(o){if(n===!1)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(o&&!o.isTTY&&n!==!0)return 0;var c=n?1:0;if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(function(u){return u in r})||r.CI_NAME==="codeship"?1:c;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in r){var l=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:(r.TERM==="dumb",c)}function a(o){var c=s(o);return i(c)}return Uc={supportsColor:a,stdout:a(process.stdout),stderr:a(process.stderr)},Uc}var Bc={exports:{}},Dh;function JE(){return Dh||(Dh=1,(function(e){e.exports=function(r,n){var i="";r=r||"Run the trap, drop the bass",r=r.split("");var s={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","۝","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return r.forEach(function(a){a=a.toLowerCase();var o=s[a]||[" "],c=Math.floor(Math.random()*o.length);typeof s[a]<"u"?i+=s[a][c]:i+=a}),i}})(Bc)),Bc.exports}var zc={exports:{}},Fh;function KE(){return Fh||(Fh=1,(function(e){e.exports=function(r,n){r=r||" he is here ";var i={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},s=[].concat(i.up,i.down,i.mid);function a(l){var u=Math.floor(Math.random()*l);return u}function o(l){var u=!1;return s.filter(function(d){u=d===l}),u}function c(l,u){var d="",f,h;u=u||{},u.up=typeof u.up<"u"?u.up:!0,u.mid=typeof u.mid<"u"?u.mid:!0,u.down=typeof u.down<"u"?u.down:!0,u.size=typeof u.size<"u"?u.size:"maxi",l=l.split("");for(h in l)if(!o(h)){switch(d=d+l[h],f={up:0,down:0,mid:0},u.size){case"mini":f.up=a(8),f.mid=a(2),f.down=a(8);break;case"maxi":f.up=a(16)+3,f.mid=a(4)+1,f.down=a(64)+3;break;default:f.up=a(8)+1,f.mid=a(6)/2,f.down=a(8)+1;break}var p=["up","mid","down"];for(var m in p)for(var w=p[m],y=0;y<=f[w];y++)u[w]&&(d=d+i[w][a(i[w].length)])}return d}return c(r,n)}})(zc)),zc.exports}var qc={exports:{}},Uh;function ZE(){return Uh||(Uh=1,(function(e){e.exports=function(t){return function(r,n,i){if(r===" ")return r;switch(n%3){case 0:return t.red(r);case 1:return t.white(r);case 2:return t.blue(r)}}}})(qc)),qc.exports}var Hc={exports:{}},Bh;function YE(){return Bh||(Bh=1,(function(e){e.exports=function(t){return function(r,n,i){return n%2===0?r:t.inverse(r)}}})(Hc)),Hc.exports}var Gc={exports:{}},zh;function XE(){return zh||(zh=1,(function(e){e.exports=function(t){var r=["red","yellow","green","blue","magenta"];return function(n,i,s){return n===" "?n:t[r[i++%r.length]](n)}}})(Gc)),Gc.exports}var Vc={exports:{}},qh;function QE(){return qh||(qh=1,(function(e){e.exports=function(t){var r=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(n,i,s){return n===" "?n:t[r[Math.round(Math.random()*(r.length-2))]](n)}}})(Vc)),Vc.exports}var Hh;function eT(){return Hh||(Hh=1,(function(e){var t={};e.exports=t,t.themes={};var r=Ar,n=t.styles=HE(),i=Object.defineProperties,s=new RegExp(/[\r\n]+/g);t.supportsColor=WE().supportsColor,typeof t.enabled>"u"&&(t.enabled=t.supportsColor()!==!1),t.enable=function(){t.enabled=!0},t.disable=function(){t.enabled=!1},t.stripColors=t.strip=function(m){return(""+m).replace(/\x1B\[\d+m/g,"")},t.stylize=function(w,y){if(!t.enabled)return w+"";var g=n[y];return!g&&y in t?t[y](w):g.open+w+g.close};var a=/[|\\{}()[\]^$+*?.]/g,o=function(m){if(typeof m!="string")throw new TypeError("Expected a string");return m.replace(a,"\\$&")};function c(m){var w=function y(){return d.apply(y,arguments)};return w._styles=m,w.__proto__=u,w}var l=(function(){var m={};return n.grey=n.gray,Object.keys(n).forEach(function(w){n[w].closeRe=new RegExp(o(n[w].close),"g"),m[w]={get:function(){return c(this._styles.concat(w))}}}),m})(),u=i(function(){},l);function d(){var m=Array.prototype.slice.call(arguments),w=m.map(function(A){return A!=null&&A.constructor===String?A:r.inspect(A)}).join(" ");if(!t.enabled||!w)return w;for(var y=w.indexOf(`
6
- `)!=-1,g=this._styles,_=g.length;_--;){var b=n[g[_]];w=b.open+w.replace(b.closeRe,b.open)+b.close,y&&(w=w.replace(s,function(A){return b.close+A+b.open}))}return w}t.setTheme=function(m){if(typeof m=="string"){console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");return}for(var w in m)(function(y){t[y]=function(g){if(typeof m[y]=="object"){var _=g;for(var b in m[y])_=t[m[y][b]](_);return _}return t[m[y]](g)}})(w)};function f(){var m={};return Object.keys(l).forEach(function(w){m[w]={get:function(){return c([w])}}}),m}var h=function(w,y){var g=y.split("");return g=g.map(w),g.join("")};t.trap=JE(),t.zalgo=KE(),t.maps={},t.maps.america=ZE()(t),t.maps.zebra=YE()(t),t.maps.rainbow=XE()(t),t.maps.random=QE()(t);for(var p in t.maps)(function(m){t[m]=function(w){return h(t.maps[m],w)}})(p);i(t,f())})(jc)),jc.exports}var Gh;function Xy(){return Gh||(Gh=1,(function(e){var t=eT();e.exports=t})(Lc)),Lc.exports}var Wc={},Jc={},_a={},Vh;function tT(){return Vh||(Vh=1,_a.levels={error:0,warn:1,help:2,data:3,info:4,debug:5,prompt:6,verbose:7,input:8,silly:9},_a.colors={error:"red",warn:"yellow",help:"cyan",data:"grey",info:"green",debug:"blue",prompt:"grey",verbose:"cyan",input:"grey",silly:"magenta"}),_a}var va={},Wh;function rT(){return Wh||(Wh=1,va.levels={error:0,warn:1,info:2,http:3,verbose:4,debug:5,silly:6},va.colors={error:"red",warn:"yellow",info:"green",http:"green",verbose:"cyan",debug:"blue",silly:"magenta"}),va}var wa={},Jh;function nT(){return Jh||(Jh=1,wa.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},wa.colors={emerg:"red",alert:"yellow",crit:"red",error:"red",warning:"red",notice:"yellow",info:"green",debug:"blue"}),wa}var Kh;function iT(){return Kh||(Kh=1,(function(e){Object.defineProperty(e,"cli",{value:tT()}),Object.defineProperty(e,"npm",{value:rT()}),Object.defineProperty(e,"syslog",{value:nT()})})(Jc)),Jc}var Zh;function Ge(){return Zh||(Zh=1,(function(e){Object.defineProperty(e,"LEVEL",{value:Symbol.for("level")}),Object.defineProperty(e,"MESSAGE",{value:Symbol.for("message")}),Object.defineProperty(e,"SPLAT",{value:Symbol.for("splat")}),Object.defineProperty(e,"configs",{value:iT()})})(Wc)),Wc}var Yh;function sd(){if(Yh)return ls.exports;Yh=1;function e(f){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(h){return typeof h}:function(h){return h&&typeof Symbol=="function"&&h.constructor===Symbol&&h!==Symbol.prototype?"symbol":typeof h},e(f)}function t(f,h){if(!(f instanceof h))throw new TypeError("Cannot call a class as a function")}function r(f,h){for(var p=0;p<h.length;p++){var m=h[p];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(f,i(m.key),m)}}function n(f,h,p){return h&&r(f.prototype,h),p&&r(f,p),Object.defineProperty(f,"prototype",{writable:!1}),f}function i(f){var h=s(f,"string");return e(h)=="symbol"?h:h+""}function s(f,h){if(e(f)!="object"||!f)return f;var p=f[Symbol.toPrimitive];if(p!==void 0){var m=p.call(f,h);if(e(m)!="object")return m;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(f)}var a=Xy(),o=Ge(),c=o.LEVEL,l=o.MESSAGE;a.enabled=!0;var u=/\s+/,d=(function(){function f(){var h=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t(this,f),h.colors&&this.addColors(h.colors),this.options=h}return n(f,[{key:"addColors",value:function(p){return f.addColors(p)}},{key:"colorize",value:function(p,m,w){if(typeof w>"u"&&(w=m),!Array.isArray(f.allColors[p]))return a[f.allColors[p]](w);for(var y=0,g=f.allColors[p].length;y<g;y++)w=a[f.allColors[p][y]](w);return w}},{key:"transform",value:function(p,m){return m.all&&typeof p[l]=="string"&&(p[l]=this.colorize(p[c],p.level,p[l])),(m.level||m.all||!m.message)&&(p.level=this.colorize(p[c],p.level)),(m.all||m.message)&&(p.message=this.colorize(p[c],p.level,p.message)),p}}],[{key:"addColors",value:function(p){var m=Object.keys(p).reduce(function(w,y){return w[y]=u.test(p[y])?p[y].split(u):p[y],w},{});return f.allColors=Object.assign({},f.allColors||{},m),f.allColors}}])})();return ls.exports=function(f){return new d(f)},ls.exports.Colorizer=ls.exports.Format=d,ls.exports}var Kc,Xh;function sT(){if(Xh)return Kc;Xh=1;var e=sd(),t=e.Colorizer;return Kc=function(r){return t.addColors(r.colors||r),r},Kc}var Zc,Qh;function aT(){if(Qh)return Zc;Qh=1;var e=Gt();return Zc=e(function(t){return t.message=" ".concat(t.message),t}),Zc}var ba={exports:{}},us={exports:{}},ep;function Qy(){if(ep)return us.exports;ep=1;function e(y){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g},e(y)}function t(y){return s(y)||i(y)||n(y)||r()}function r(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
7
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function n(y,g){if(y){if(typeof y=="string")return a(y,g);var _={}.toString.call(y).slice(8,-1);return _==="Object"&&y.constructor&&(_=y.constructor.name),_==="Map"||_==="Set"?Array.from(y):_==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(_)?a(y,g):void 0}}function i(y){if(typeof Symbol<"u"&&y[Symbol.iterator]!=null||y["@@iterator"]!=null)return Array.from(y)}function s(y){if(Array.isArray(y))return a(y)}function a(y,g){(g==null||g>y.length)&&(g=y.length);for(var _=0,b=Array(g);_<g;_++)b[_]=y[_];return b}function o(y,g){if(!(y instanceof g))throw new TypeError("Cannot call a class as a function")}function c(y,g){for(var _=0;_<g.length;_++){var b=g[_];b.enumerable=b.enumerable||!1,b.configurable=!0,"value"in b&&(b.writable=!0),Object.defineProperty(y,u(b.key),b)}}function l(y,g,_){return g&&c(y.prototype,g),_&&c(y,_),Object.defineProperty(y,"prototype",{writable:!1}),y}function u(y){var g=d(y,"string");return e(g)=="symbol"?g:g+""}function d(y,g){if(e(y)!="object"||!y)return y;var _=y[Symbol.toPrimitive];if(_!==void 0){var b=_.call(y,g);if(e(b)!="object")return b;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(y)}var f=Ge(),h=f.configs,p=f.LEVEL,m=f.MESSAGE,w=(function(){function y(){var g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{levels:h.npm.levels};o(this,y),this.paddings=y.paddingForLevels(g.levels,g.filler),this.options=g}return l(y,[{key:"transform",value:function(_,b){return _.message="".concat(this.paddings[_[p]]).concat(_.message),_[m]&&(_[m]="".concat(this.paddings[_[p]]).concat(_[m])),_}}],[{key:"getLongestLevel",value:function(_){var b=Object.keys(_).map(function(A){return A.length});return Math.max.apply(Math,t(b))}},{key:"paddingForLevel",value:function(_,b,A){var P=A+1-_.length,x=Math.floor(P/b.length),T="".concat(b).concat(b.repeat(x));return T.slice(0,P)}},{key:"paddingForLevels",value:function(_){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:" ",A=y.getLongestLevel(_);return Object.keys(_).reduce(function(P,x){return P[x]=y.paddingForLevel(x,b,A),P},{})}}])})();return us.exports=function(y){return new w(y)},us.exports.Padder=us.exports.Format=w,us.exports}var tp;function oT(){if(tp)return ba.exports;tp=1;function e(p){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m},e(p)}function t(p,m){if(!(p instanceof m))throw new TypeError("Cannot call a class as a function")}function r(p,m){for(var w=0;w<m.length;w++){var y=m[w];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(p,i(y.key),y)}}function n(p,m,w){return m&&r(p.prototype,m),Object.defineProperty(p,"prototype",{writable:!1}),p}function i(p){var m=s(p,"string");return e(m)=="symbol"?m:m+""}function s(p,m){if(e(p)!="object"||!p)return p;var w=p[Symbol.toPrimitive];if(w!==void 0){var y=w.call(p,m);if(e(y)!="object")return y;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(p)}var a=sd(),o=a.Colorizer,c=Qy(),l=c.Padder,u=Ge(),d=u.configs,f=u.MESSAGE,h=(function(){function p(){var m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t(this,p),m.levels||(m.levels=d.cli.levels),this.colorizer=new o(m),this.padder=new l(m),this.options=m}return n(p,[{key:"transform",value:function(w,y){return this.colorizer.transform(this.padder.transform(w,y),y),w[f]="".concat(w.level,":").concat(w.message),w}}])})();return ba.exports=function(p){return new h(p)},ba.exports.Format=h,ba.exports}var Sa={exports:{}},rp;function cT(){if(rp)return Sa.exports;rp=1;var e=Gt();function t(n){if(n.every(r))return function(i){for(var s=i,a=0;a<n.length;a++)if(s=n[a].transform(s,n[a].options),!s)return!1;return s}}function r(n){if(typeof n.transform!="function")throw new Error(["No transform function found on format. Did you create a format instance?","const myFormat = format(formatFn);","const instance = myFormat();"].join(`
8
- `));return!0}return Sa.exports=function(){for(var n=arguments.length,i=new Array(n),s=0;s<n;s++)i[s]=arguments[s];var a=e(t(i)),o=a();return o.Format=a.Format,o},Sa.exports.cascade=t,Sa.exports}var Yc,np;function lT(){if(np)return Yc;np=1;function e(c){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},e(c)}function t(c,l,u){return(l=r(l))in c?Object.defineProperty(c,l,{value:u,enumerable:!0,configurable:!0,writable:!0}):c[l]=u,c}function r(c){var l=n(c,"string");return e(l)=="symbol"?l:l+""}function n(c,l){if(e(c)!="object"||!c)return c;var u=c[Symbol.toPrimitive];if(u!==void 0){var d=u.call(c,l);if(e(d)!="object")return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return(l==="string"?String:Number)(c)}var i=Gt(),s=Ge(),a=s.LEVEL,o=s.MESSAGE;return Yc=i(function(c,l){var u=l.stack,d=l.cause;if(c instanceof Error){var f=Object.assign({},c,t(t(t({level:c.level},a,c[a]||c.level),"message",c.message),o,c[o]||c.message));return u&&(f.stack=c.stack),d&&(f.cause=c.cause),f}if(!(c.message instanceof Error))return c;var h=c.message;return Object.assign(c,h),c.message=h.message,c[o]=h.message,u&&(c.stack=h.stack),d&&(c.cause=h.cause),c}),Yc}var Ea={exports:{}},ip;function Xs(){return ip||(ip=1,(function(e,t){const{hasOwnProperty:r}=Object.prototype,n=y();n.configure=y,n.stringify=n,n.default=n,t.stringify=n,t.configure=y,e.exports=n;const i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function s(g){return g.length<5e3&&!i.test(g)?`"${g}"`:JSON.stringify(g)}function a(g,_){if(g.length>200||_)return g.sort(_);for(let b=1;b<g.length;b++){const A=g[b];let P=b;for(;P!==0&&g[P-1]>A;)g[P]=g[P-1],P--;g[P]=A}return g}const o=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(g){return o.call(g)!==void 0&&g.length!==0}function l(g,_,b){g.length<b&&(b=g.length);const A=_===","?"":" ";let P=`"0":${A}${g[0]}`;for(let x=1;x<b;x++)P+=`${_}"${x}":${A}${g[x]}`;return P}function u(g){if(r.call(g,"circularValue")){const _=g.circularValue;if(typeof _=="string")return`"${_}"`;if(_==null)return _;if(_===Error||_===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function d(g){let _;if(r.call(g,"deterministic")&&(_=g.deterministic,typeof _!="boolean"&&typeof _!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return _===void 0?!0:_}function f(g,_){let b;if(r.call(g,_)&&(b=g[_],typeof b!="boolean"))throw new TypeError(`The "${_}" argument must be of type boolean`);return b===void 0?!0:b}function h(g,_){let b;if(r.call(g,_)){if(b=g[_],typeof b!="number")throw new TypeError(`The "${_}" argument must be of type number`);if(!Number.isInteger(b))throw new TypeError(`The "${_}" argument must be an integer`);if(b<1)throw new RangeError(`The "${_}" argument must be >= 1`)}return b===void 0?1/0:b}function p(g){return g===1?"1 item":`${g} items`}function m(g){const _=new Set;for(const b of g)(typeof b=="string"||typeof b=="number")&&_.add(String(b));return _}function w(g){if(r.call(g,"strict")){const _=g.strict;if(typeof _!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(_)return b=>{let A=`Object can not safely be stringified. Received type ${typeof b}`;throw typeof b!="function"&&(A+=` (${b.toString()})`),new Error(A)}}}function y(g){g={...g};const _=w(g);_&&(g.bigint===void 0&&(g.bigint=!1),"circularValue"in g||(g.circularValue=Error));const b=u(g),A=f(g,"bigint"),P=d(g),x=typeof P=="function"?P:void 0,T=h(g,"maximumDepth"),R=h(g,"maximumBreadth");function M(ee,L,z,W,q,V){let Y=L[ee];switch(typeof Y=="object"&&Y!==null&&typeof Y.toJSON=="function"&&(Y=Y.toJSON(ee)),Y=W.call(L,ee,Y),typeof Y){case"string":return s(Y);case"object":{if(Y===null)return"null";if(z.indexOf(Y)!==-1)return b;let Q="",ae=",";const X=V;if(Array.isArray(Y)){if(Y.length===0)return"[]";if(T<z.length+1)return'"[Array]"';z.push(Y),q!==""&&(V+=q,Q+=`
9
- ${V}`,ae=`,
10
- ${V}`);const re=Math.min(Y.length,R);let k=0;for(;k<re-1;k++){const J=M(String(k),Y,z,W,q,V);Q+=J!==void 0?J:"null",Q+=ae}const I=M(String(k),Y,z,W,q,V);if(Q+=I!==void 0?I:"null",Y.length-1>R){const J=Y.length-R-1;Q+=`${ae}"... ${p(J)} not stringified"`}return q!==""&&(Q+=`
11
- ${X}`),z.pop(),`[${Q}]`}let se=Object.keys(Y);const C=se.length;if(C===0)return"{}";if(T<z.length+1)return'"[Object]"';let S="",D="";q!==""&&(V+=q,ae=`,
12
- ${V}`,S=" ");const j=Math.min(C,R);P&&!c(Y)&&(se=a(se,x)),z.push(Y);for(let re=0;re<j;re++){const k=se[re],I=M(k,Y,z,W,q,V);I!==void 0&&(Q+=`${D}${s(k)}:${S}${I}`,D=ae)}if(C>R){const re=C-R;Q+=`${D}"...":${S}"${p(re)} not stringified"`,D=ae}return q!==""&&D.length>1&&(Q=`
13
- ${V}${Q}
14
- ${X}`),z.pop(),`{${Q}}`}case"number":return isFinite(Y)?String(Y):_?_(Y):"null";case"boolean":return Y===!0?"true":"false";case"undefined":return;case"bigint":if(A)return String(Y);default:return _?_(Y):void 0}}function U(ee,L,z,W,q,V){switch(typeof L=="object"&&L!==null&&typeof L.toJSON=="function"&&(L=L.toJSON(ee)),typeof L){case"string":return s(L);case"object":{if(L===null)return"null";if(z.indexOf(L)!==-1)return b;const Y=V;let Q="",ae=",";if(Array.isArray(L)){if(L.length===0)return"[]";if(T<z.length+1)return'"[Array]"';z.push(L),q!==""&&(V+=q,Q+=`
15
- ${V}`,ae=`,
16
- ${V}`);const C=Math.min(L.length,R);let S=0;for(;S<C-1;S++){const j=U(String(S),L[S],z,W,q,V);Q+=j!==void 0?j:"null",Q+=ae}const D=U(String(S),L[S],z,W,q,V);if(Q+=D!==void 0?D:"null",L.length-1>R){const j=L.length-R-1;Q+=`${ae}"... ${p(j)} not stringified"`}return q!==""&&(Q+=`
17
- ${Y}`),z.pop(),`[${Q}]`}z.push(L);let X="";q!==""&&(V+=q,ae=`,
18
- ${V}`,X=" ");let se="";for(const C of W){const S=U(C,L[C],z,W,q,V);S!==void 0&&(Q+=`${se}${s(C)}:${X}${S}`,se=ae)}return q!==""&&se.length>1&&(Q=`
19
- ${V}${Q}
20
- ${Y}`),z.pop(),`{${Q}}`}case"number":return isFinite(L)?String(L):_?_(L):"null";case"boolean":return L===!0?"true":"false";case"undefined":return;case"bigint":if(A)return String(L);default:return _?_(L):void 0}}function H(ee,L,z,W,q){switch(typeof L){case"string":return s(L);case"object":{if(L===null)return"null";if(typeof L.toJSON=="function"){if(L=L.toJSON(ee),typeof L!="object")return H(ee,L,z,W,q);if(L===null)return"null"}if(z.indexOf(L)!==-1)return b;const V=q;if(Array.isArray(L)){if(L.length===0)return"[]";if(T<z.length+1)return'"[Array]"';z.push(L),q+=W;let S=`
21
- ${q}`;const D=`,
22
- ${q}`,j=Math.min(L.length,R);let re=0;for(;re<j-1;re++){const I=H(String(re),L[re],z,W,q);S+=I!==void 0?I:"null",S+=D}const k=H(String(re),L[re],z,W,q);if(S+=k!==void 0?k:"null",L.length-1>R){const I=L.length-R-1;S+=`${D}"... ${p(I)} not stringified"`}return S+=`
23
- ${V}`,z.pop(),`[${S}]`}let Y=Object.keys(L);const Q=Y.length;if(Q===0)return"{}";if(T<z.length+1)return'"[Object]"';q+=W;const ae=`,
24
- ${q}`;let X="",se="",C=Math.min(Q,R);c(L)&&(X+=l(L,ae,R),Y=Y.slice(L.length),C-=L.length,se=ae),P&&(Y=a(Y,x)),z.push(L);for(let S=0;S<C;S++){const D=Y[S],j=H(D,L[D],z,W,q);j!==void 0&&(X+=`${se}${s(D)}: ${j}`,se=ae)}if(Q>R){const S=Q-R;X+=`${se}"...": "${p(S)} not stringified"`,se=ae}return se!==""&&(X=`
25
- ${q}${X}
26
- ${V}`),z.pop(),`{${X}}`}case"number":return isFinite(L)?String(L):_?_(L):"null";case"boolean":return L===!0?"true":"false";case"undefined":return;case"bigint":if(A)return String(L);default:return _?_(L):void 0}}function F(ee,L,z){switch(typeof L){case"string":return s(L);case"object":{if(L===null)return"null";if(typeof L.toJSON=="function"){if(L=L.toJSON(ee),typeof L!="object")return F(ee,L,z);if(L===null)return"null"}if(z.indexOf(L)!==-1)return b;let W="";const q=L.length!==void 0;if(q&&Array.isArray(L)){if(L.length===0)return"[]";if(T<z.length+1)return'"[Array]"';z.push(L);const X=Math.min(L.length,R);let se=0;for(;se<X-1;se++){const S=F(String(se),L[se],z);W+=S!==void 0?S:"null",W+=","}const C=F(String(se),L[se],z);if(W+=C!==void 0?C:"null",L.length-1>R){const S=L.length-R-1;W+=`,"... ${p(S)} not stringified"`}return z.pop(),`[${W}]`}let V=Object.keys(L);const Y=V.length;if(Y===0)return"{}";if(T<z.length+1)return'"[Object]"';let Q="",ae=Math.min(Y,R);q&&c(L)&&(W+=l(L,",",R),V=V.slice(L.length),ae-=L.length,Q=","),P&&(V=a(V,x)),z.push(L);for(let X=0;X<ae;X++){const se=V[X],C=F(se,L[se],z);C!==void 0&&(W+=`${Q}${s(se)}:${C}`,Q=",")}if(Y>R){const X=Y-R;W+=`${Q}"...":"${p(X)} not stringified"`}return z.pop(),`{${W}}`}case"number":return isFinite(L)?String(L):_?_(L):"null";case"boolean":return L===!0?"true":"false";case"undefined":return;case"bigint":if(A)return String(L);default:return _?_(L):void 0}}function K(ee,L,z){if(arguments.length>1){let W="";if(typeof z=="number"?W=" ".repeat(Math.min(z,10)):typeof z=="string"&&(W=z.slice(0,10)),L!=null){if(typeof L=="function")return M("",{"":ee},[],L,W,"");if(Array.isArray(L))return U("",ee,[],m(L),W,"")}if(W.length!==0)return H("",ee,[],W,"")}return F("",ee,[])}return K}})(Ea,Ea.exports)),Ea.exports}var Xc,sp;function uT(){if(sp)return Xc;sp=1;var e=Gt(),t=Ge(),r=t.MESSAGE,n=Xs();function i(s,a){return typeof a=="bigint"?a.toString():a}return Xc=e(function(s,a){var o=n.configure(a);return s[r]=o(s,a.replacer||i,a.space),s}),Xc}var Qc,ap;function fT(){if(ap)return Qc;ap=1;var e=Gt();return Qc=e(function(t,r){return r.message?(t.message="[".concat(r.label,"] ").concat(t.message),t):(t.label=r.label,t)}),Qc}var el,op;function dT(){if(op)return el;op=1;var e=Gt(),t=Ge(),r=t.MESSAGE,n=Xs();return el=e(function(i){var s={};return i.message&&(s["@message"]=i.message,delete i.message),i.timestamp&&(s["@timestamp"]=i.timestamp,delete i.timestamp),s["@fields"]=i,i[r]=n(s),i}),el}var tl,cp;function hT(){if(cp)return tl;cp=1;function e(o){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c},e(o)}function t(o,c,l){return(c=r(c))in o?Object.defineProperty(o,c,{value:l,enumerable:!0,configurable:!0,writable:!0}):o[c]=l,o}function r(o){var c=n(o,"string");return e(c)=="symbol"?c:c+""}function n(o,c){if(e(o)!="object"||!o)return o;var l=o[Symbol.toPrimitive];if(l!==void 0){var u=l.call(o,c);if(e(u)!="object")return u;throw new TypeError("@@toPrimitive must return a primitive value.")}return(c==="string"?String:Number)(o)}var i=Gt();function s(o,c,l){var u=c.reduce(function(f,h){return f[h]=o[h],delete o[h],f},{}),d=Object.keys(o).reduce(function(f,h){return f[h]=o[h],delete o[h],f},{});return Object.assign(o,u,t({},l,d)),o}function a(o,c,l){return o[l]=c.reduce(function(u,d){return u[d]=o[d],delete o[d],u},{}),o}return tl=i(function(o){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l="metadata";c.key&&(l=c.key);var u=[];return!c.fillExcept&&!c.fillWith&&(u.push("level"),u.push("message")),c.fillExcept&&(u=c.fillExcept),u.length>0?s(o,u,l):c.fillWith?a(o,c.fillWith,l):o}),tl}var rl,lp;function pT(){if(lp)return rl;lp=1;var e=1e3,t=e*60,r=t*60,n=r*24,i=n*7,s=n*365.25;rl=function(u,d){d=d||{};var f=typeof u;if(f==="string"&&u.length>0)return a(u);if(f==="number"&&isFinite(u))return d.long?c(u):o(u);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(u))};function a(u){if(u=String(u),!(u.length>100)){var d=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(u);if(d){var f=parseFloat(d[1]),h=(d[2]||"ms").toLowerCase();switch(h){case"years":case"year":case"yrs":case"yr":case"y":return f*s;case"weeks":case"week":case"w":return f*i;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*r;case"minutes":case"minute":case"mins":case"min":case"m":return f*t;case"seconds":case"second":case"secs":case"sec":case"s":return f*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function o(u){var d=Math.abs(u);return d>=n?Math.round(u/n)+"d":d>=r?Math.round(u/r)+"h":d>=t?Math.round(u/t)+"m":d>=e?Math.round(u/e)+"s":u+"ms"}function c(u){var d=Math.abs(u);return d>=n?l(u,d,n,"day"):d>=r?l(u,d,r,"hour"):d>=t?l(u,d,t,"minute"):d>=e?l(u,d,e,"second"):u+" ms"}function l(u,d,f,h){var p=d>=f*1.5;return Math.round(u/f)+" "+h+(p?"s":"")}return rl}var nl,up;function mT(){if(up)return nl;up=1;var e=void 0,t=Gt(),r=pT();return nl=t(function(n){var i=+new Date;return e.diff=i-(e.prevTime||i),e.prevTime=i,n.ms="+".concat(r(e.diff)),n}),nl}var il,fp;function gT(){if(fp)return il;fp=1;var e=Ar.inspect,t=Gt(),r=Ge(),n=r.LEVEL,i=r.MESSAGE,s=r.SPLAT;return il=t(function(a){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=Object.assign({},a);return delete c[n],delete c[i],delete c[s],a[i]=e(c,!1,o.depth||null,o.colorize),a}),il}var fs={exports:{}},dp;function yT(){if(dp)return fs.exports;dp=1;function e(l){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(u){return typeof u}:function(u){return u&&typeof Symbol=="function"&&u.constructor===Symbol&&u!==Symbol.prototype?"symbol":typeof u},e(l)}function t(l,u){if(!(l instanceof u))throw new TypeError("Cannot call a class as a function")}function r(l,u){for(var d=0;d<u.length;d++){var f=u[d];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(l,i(f.key),f)}}function n(l,u,d){return u&&r(l.prototype,u),Object.defineProperty(l,"prototype",{writable:!1}),l}function i(l){var u=s(l,"string");return e(u)=="symbol"?u:u+""}function s(l,u){if(e(l)!="object"||!l)return l;var d=l[Symbol.toPrimitive];if(d!==void 0){var f=d.call(l,u);if(e(f)!="object")return f;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(l)}var a=Ge(),o=a.MESSAGE,c=(function(){function l(u){t(this,l),this.template=u}return n(l,[{key:"transform",value:function(d){return d[o]=this.template(d),d}}])})();return fs.exports=function(l){return new c(l)},fs.exports.Printf=fs.exports.Format=c,fs.exports}var sl,hp;function _T(){if(hp)return sl;hp=1;var e=Gt(),t=Ge(),r=t.MESSAGE,n=Xs();return sl=e(function(i){var s=n(Object.assign({},i,{level:void 0,message:void 0,splat:void 0})),a=i.padding&&i.padding[i.level]||"";return s!=="{}"?i[r]="".concat(i.level,":").concat(a," ").concat(i.message," ").concat(s):i[r]="".concat(i.level,":").concat(a," ").concat(i.message),i}),sl}var al,pp;function vT(){if(pp)return al;pp=1;function e(g){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},e(g)}function t(g){return s(g)||i(g)||n(g)||r()}function r(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
27
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function n(g,_){if(g){if(typeof g=="string")return a(g,_);var b={}.toString.call(g).slice(8,-1);return b==="Object"&&g.constructor&&(b=g.constructor.name),b==="Map"||b==="Set"?Array.from(g):b==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(b)?a(g,_):void 0}}function i(g){if(typeof Symbol<"u"&&g[Symbol.iterator]!=null||g["@@iterator"]!=null)return Array.from(g)}function s(g){if(Array.isArray(g))return a(g)}function a(g,_){(_==null||_>g.length)&&(_=g.length);for(var b=0,A=Array(_);b<_;b++)A[b]=g[b];return A}function o(g,_){if(!(g instanceof _))throw new TypeError("Cannot call a class as a function")}function c(g,_){for(var b=0;b<_.length;b++){var A=_[b];A.enumerable=A.enumerable||!1,A.configurable=!0,"value"in A&&(A.writable=!0),Object.defineProperty(g,u(A.key),A)}}function l(g,_,b){return _&&c(g.prototype,_),Object.defineProperty(g,"prototype",{writable:!1}),g}function u(g){var _=d(g,"string");return e(_)=="symbol"?_:_+""}function d(g,_){if(e(g)!="object"||!g)return g;var b=g[Symbol.toPrimitive];if(b!==void 0){var A=b.call(g,_);if(e(A)!="object")return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(g)}var f=Ar,h=Ge(),p=h.SPLAT,m=/%[scdjifoO%]/g,w=/%%/g,y=(function(){function g(_){o(this,g),this.options=_}return l(g,[{key:"_splat",value:function(b,A){var P=b.message,x=b[p]||b.splat||[],T=P.match(w),R=T&&T.length||0,M=A.length-R,U=M-x.length,H=U<0?x.splice(U,-1*U):[],F=H.length;if(F)for(var K=0;K<F;K++)Object.assign(b,H[K]);return b.message=f.format.apply(f,[P].concat(t(x))),b}},{key:"transform",value:function(b){var A=b.message,P=b[p]||b.splat;if(!P||!P.length)return b;var x=A&&A.match&&A.match(m);if(!x&&(P||P.length)){var T=P.length>1?P.splice(0):P,R=T.length;if(R)for(var M=0;M<R;M++)Object.assign(b,T[M]);return b}return x?this._splat(b,x):b}}])})();return al=function(g){return new y(g)},al}var e_=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,Yr="\\d\\d?",Wr="\\d\\d",wT="\\d{3}",bT="\\d{4}",ws="[^\\s]+",t_=/\[([^]*?)\]/gm;function r_(e,t){for(var r=[],n=0,i=e.length;n<i;n++)r.push(e[n].substr(0,t));return r}var mp=function(e){return function(t,r){var n=r[e].map(function(s){return s.toLowerCase()}),i=n.indexOf(t.toLowerCase());return i>-1?i:null}};function dn(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];for(var n=0,i=t;n<i.length;n++){var s=i[n];for(var a in s)e[a]=s[a]}return e}var n_=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],i_=["January","February","March","April","May","June","July","August","September","October","November","December"],ST=r_(i_,3),ET=r_(n_,3),ad={dayNamesShort:ET,dayNames:n_,monthNamesShort:ST,monthNames:i_,amPm:["am","pm"],DoFn:function(e){return e+["th","st","nd","rd"][e%10>3?0:(e-e%10!==10?1:0)*e%10]}},ko=dn({},ad),s_=function(e){return ko=dn(ko,e)},gp=function(e){return e.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},Tt=function(e,t){for(t===void 0&&(t=2),e=String(e);e.length<t;)e="0"+e;return e},TT={D:function(e){return String(e.getDate())},DD:function(e){return Tt(e.getDate())},Do:function(e,t){return t.DoFn(e.getDate())},d:function(e){return String(e.getDay())},dd:function(e){return Tt(e.getDay())},ddd:function(e,t){return t.dayNamesShort[e.getDay()]},dddd:function(e,t){return t.dayNames[e.getDay()]},M:function(e){return String(e.getMonth()+1)},MM:function(e){return Tt(e.getMonth()+1)},MMM:function(e,t){return t.monthNamesShort[e.getMonth()]},MMMM:function(e,t){return t.monthNames[e.getMonth()]},YY:function(e){return Tt(String(e.getFullYear()),4).substr(2)},YYYY:function(e){return Tt(e.getFullYear(),4)},h:function(e){return String(e.getHours()%12||12)},hh:function(e){return Tt(e.getHours()%12||12)},H:function(e){return String(e.getHours())},HH:function(e){return Tt(e.getHours())},m:function(e){return String(e.getMinutes())},mm:function(e){return Tt(e.getMinutes())},s:function(e){return String(e.getSeconds())},ss:function(e){return Tt(e.getSeconds())},S:function(e){return String(Math.round(e.getMilliseconds()/100))},SS:function(e){return Tt(Math.round(e.getMilliseconds()/10),2)},SSS:function(e){return Tt(e.getMilliseconds(),3)},a:function(e,t){return e.getHours()<12?t.amPm[0]:t.amPm[1]},A:function(e,t){return e.getHours()<12?t.amPm[0].toUpperCase():t.amPm[1].toUpperCase()},ZZ:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+Tt(Math.floor(Math.abs(t)/60)*100+Math.abs(t)%60,4)},Z:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+Tt(Math.floor(Math.abs(t)/60),2)+":"+Tt(Math.abs(t)%60,2)}},yp=function(e){return+e-1},_p=[null,Yr],vp=[null,ws],wp=["isPm",ws,function(e,t){var r=e.toLowerCase();return r===t.amPm[0]?0:r===t.amPm[1]?1:null}],bp=["timezoneOffset","[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",function(e){var t=(e+"").match(/([+-]|\d\d)/gi);if(t){var r=+t[1]*60+parseInt(t[2],10);return t[0]==="+"?r:-r}return 0}],CT={D:["day",Yr],DD:["day",Wr],Do:["day",Yr+ws,function(e){return parseInt(e,10)}],M:["month",Yr,yp],MM:["month",Wr,yp],YY:["year",Wr,function(e){var t=new Date,r=+(""+t.getFullYear()).substr(0,2);return+(""+(+e>68?r-1:r)+e)}],h:["hour",Yr,void 0,"isPm"],hh:["hour",Wr,void 0,"isPm"],H:["hour",Yr],HH:["hour",Wr],m:["minute",Yr],mm:["minute",Wr],s:["second",Yr],ss:["second",Wr],YYYY:["year",bT],S:["millisecond","\\d",function(e){return+e*100}],SS:["millisecond",Wr,function(e){return+e*10}],SSS:["millisecond",wT],d:_p,dd:_p,ddd:vp,dddd:vp,MMM:["month",ws,mp("monthNamesShort")],MMMM:["month",ws,mp("monthNames")],a:wp,A:wp,ZZ:bp,Z:bp},Io={default:"ddd MMM DD YYYY HH:mm:ss",shortDate:"M/D/YY",mediumDate:"MMM D, YYYY",longDate:"MMMM D, YYYY",fullDate:"dddd, MMMM D, YYYY",isoDate:"YYYY-MM-DD",isoDateTime:"YYYY-MM-DDTHH:mm:ssZ",shortTime:"HH:mm",mediumTime:"HH:mm:ss",longTime:"HH:mm:ss.SSS"},a_=function(e){return dn(Io,e)},o_=function(e,t,r){if(t===void 0&&(t=Io.default),r===void 0&&(r={}),typeof e=="number"&&(e=new Date(e)),Object.prototype.toString.call(e)!=="[object Date]"||isNaN(e.getTime()))throw new Error("Invalid Date pass to format");t=Io[t]||t;var n=[];t=t.replace(t_,function(s,a){return n.push(a),"@@@"});var i=dn(dn({},ko),r);return t=t.replace(e_,function(s){return TT[s](e,i)}),t.replace(/@@@/g,function(){return n.shift()})};function c_(e,t,r){if(r===void 0&&(r={}),typeof t!="string")throw new Error("Invalid format in fecha parse");if(t=Io[t]||t,e.length>1e3)return null;var n=new Date,i={year:n.getFullYear(),month:0,day:1,hour:0,minute:0,second:0,millisecond:0,isPm:null,timezoneOffset:null},s=[],a=[],o=t.replace(t_,function(b,A){return a.push(gp(A)),"@@@"}),c={},l={};o=gp(o).replace(e_,function(b){var A=CT[b],P=A[0],x=A[1],T=A[3];if(c[P])throw new Error("Invalid format. "+P+" specified twice in format");return c[P]=!0,T&&(l[T]=!0),s.push(A),"("+x+")"}),Object.keys(l).forEach(function(b){if(!c[b])throw new Error("Invalid format. "+b+" is required in specified format")}),o=o.replace(/@@@/g,function(){return a.shift()});var u=e.match(new RegExp(o,"i"));if(!u)return null;for(var d=dn(dn({},ko),r),f=1;f<u.length;f++){var h=s[f-1],p=h[0],m=h[2],w=m?m(u[f],d):+u[f];if(w==null)return null;i[p]=w}i.isPm===1&&i.hour!=null&&+i.hour!=12?i.hour=+i.hour+12:i.isPm===0&&+i.hour==12&&(i.hour=0);var y;if(i.timezoneOffset==null){y=new Date(i.year,i.month,i.day,i.hour,i.minute,i.second,i.millisecond);for(var g=[["month","getMonth"],["day","getDate"],["hour","getHours"],["minute","getMinutes"],["second","getSeconds"]],f=0,_=g.length;f<_;f++)if(c[g[f][0]]&&i[g[f][0]]!==y[g[f][1]]())return null}else if(y=new Date(Date.UTC(i.year,i.month,i.day,i.hour,i.minute-i.timezoneOffset,i.second,i.millisecond)),i.month>11||i.month<0||i.day>31||i.day<1||i.hour>23||i.hour<0||i.minute>59||i.minute<0||i.second>59||i.second<0)return null;return y}var AT={format:o_,parse:c_,defaultI18n:ad,setGlobalDateI18n:s_,setGlobalDateMasks:a_};const OT=Object.freeze(Object.defineProperty({__proto__:null,assign:dn,default:AT,defaultI18n:ad,format:o_,parse:c_,setGlobalDateI18n:s_,setGlobalDateMasks:a_},Symbol.toStringTag,{value:"Module"})),xT=sc(OT);var ol,Sp;function PT(){if(Sp)return ol;Sp=1;var e=xT,t=Gt();return ol=t(function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return n.format&&(r.timestamp=typeof n.format=="function"?n.format():e.format(new Date,n.format)),r.timestamp||(r.timestamp=new Date().toISOString()),n.alias&&(r[n.alias]=r.timestamp),r}),ol}var cl,Ep;function kT(){if(Ep)return cl;Ep=1;var e=Xy(),t=Gt(),r=Ge(),n=r.MESSAGE;return cl=t(function(i,s){return s.level!==!1&&(i.level=e.strip(i.level)),s.message!==!1&&(i.message=e.strip(String(i.message))),s.raw!==!1&&i[n]&&(i[n]=e.strip(String(i[n]))),i}),cl}var Tp;function l_(){if(Tp)return ya;Tp=1;var e=ya.format=Gt();return ya.levels=sT(),Object.defineProperty(e,"align",{value:aT()}),Object.defineProperty(e,"cli",{value:oT()}),Object.defineProperty(e,"colorize",{value:sd()}),Object.defineProperty(e,"combine",{value:cT()}),Object.defineProperty(e,"errors",{value:lT()}),Object.defineProperty(e,"json",{value:uT()}),Object.defineProperty(e,"label",{value:fT()}),Object.defineProperty(e,"logstash",{value:dT()}),Object.defineProperty(e,"metadata",{value:hT()}),Object.defineProperty(e,"ms",{value:mT()}),Object.defineProperty(e,"padLevels",{value:Qy()}),Object.defineProperty(e,"prettyPrint",{value:gT()}),Object.defineProperty(e,"printf",{value:yT()}),Object.defineProperty(e,"simple",{value:_T()}),Object.defineProperty(e,"splat",{value:vT()}),Object.defineProperty(e,"timestamp",{value:PT()}),Object.defineProperty(e,"uncolorize",{value:kT()}),ya}var ll={},Cp;function u_(){return Cp||(Cp=1,(function(e){var t=Ar,r=t.format;e.warn={deprecated:function(i){return function(){throw new Error(r("{ %s } was removed in winston@3.0.0.",i))}},useFormat:function(i){return function(){throw new Error([r("{ %s } was removed in winston@3.0.0.",i),"Use a custom winston.format = winston.format(function) instead."].join(`
28
- `))}},forFunctions:function(i,s,a){a.forEach(function(o){i[o]=e.warn[s](o)})},forProperties:function(i,s,a){a.forEach(function(o){var c=e.warn[s](o);Object.defineProperty(i,o,{get:c,set:c})})}}})(ll)),ll}const IT="3.18.3",MT={version:IT};var ul={},Ta={exports:{}},fl={exports:{}},dl,Ap;function RT(){if(Ap)return dl;Ap=1,dl=e;function e(r,n){if(t("noDeprecation"))return r;var i=!1;function s(){if(!i){if(t("throwDeprecation"))throw new Error(n);t("traceDeprecation")?console.trace(n):console.warn(n),i=!0}return r.apply(this,arguments)}return s}function t(r){try{if(!globalThis.localStorage)return!1}catch{return!1}var n=globalThis.localStorage[r];return n==null?!1:String(n).toLowerCase()==="true"}return dl}var Ca={exports:{}},Op;function f_(){if(Op)return Ca.exports;Op=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(A,P,x){return Function.prototype.apply.call(A,P,x)},r;e&&typeof e.ownKeys=="function"?r=e.ownKeys:Object.getOwnPropertySymbols?r=function(A){return Object.getOwnPropertyNames(A).concat(Object.getOwnPropertySymbols(A))}:r=function(A){return Object.getOwnPropertyNames(A)};function n(b){console&&console.warn&&console.warn(b)}var i=Number.isNaN||function(A){return A!==A};function s(){s.init.call(this)}Ca.exports=s,Ca.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(b){if(typeof b!="number"||b<0||i(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");a=b}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(A){if(typeof A!="number"||A<0||i(A))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+A+".");return this._maxListeners=A,this};function c(b){return b._maxListeners===void 0?s.defaultMaxListeners:b._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(A){for(var P=[],x=1;x<arguments.length;x++)P.push(arguments[x]);var T=A==="error",R=this._events;if(R!==void 0)T=T&&R.error===void 0;else if(!T)return!1;if(T){var M;if(P.length>0&&(M=P[0]),M instanceof Error)throw M;var U=new Error("Unhandled error."+(M?" ("+M.message+")":""));throw U.context=M,U}var H=R[A];if(H===void 0)return!1;if(typeof H=="function")t(H,this,P);else for(var F=H.length,K=p(H,F),x=0;x<F;++x)t(K[x],this,P);return!0};function l(b,A,P,x){var T,R,M;if(o(P),R=b._events,R===void 0?(R=b._events=Object.create(null),b._eventsCount=0):(R.newListener!==void 0&&(b.emit("newListener",A,P.listener?P.listener:P),R=b._events),M=R[A]),M===void 0)M=R[A]=P,++b._eventsCount;else if(typeof M=="function"?M=R[A]=x?[P,M]:[M,P]:x?M.unshift(P):M.push(P),T=c(b),T>0&&M.length>T&&!M.warned){M.warned=!0;var U=new Error("Possible EventEmitter memory leak detected. "+M.length+" "+String(A)+" listeners added. Use emitter.setMaxListeners() to increase limit");U.name="MaxListenersExceededWarning",U.emitter=b,U.type=A,U.count=M.length,n(U)}return b}s.prototype.addListener=function(A,P){return l(this,A,P,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(A,P){return l(this,A,P,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(b,A,P){var x={fired:!1,wrapFn:void 0,target:b,type:A,listener:P},T=u.bind(x);return T.listener=P,x.wrapFn=T,T}s.prototype.once=function(A,P){return o(P),this.on(A,d(this,A,P)),this},s.prototype.prependOnceListener=function(A,P){return o(P),this.prependListener(A,d(this,A,P)),this},s.prototype.removeListener=function(A,P){var x,T,R,M,U;if(o(P),T=this._events,T===void 0)return this;if(x=T[A],x===void 0)return this;if(x===P||x.listener===P)--this._eventsCount===0?this._events=Object.create(null):(delete T[A],T.removeListener&&this.emit("removeListener",A,x.listener||P));else if(typeof x!="function"){for(R=-1,M=x.length-1;M>=0;M--)if(x[M]===P||x[M].listener===P){U=x[M].listener,R=M;break}if(R<0)return this;R===0?x.shift():m(x,R),x.length===1&&(T[A]=x[0]),T.removeListener!==void 0&&this.emit("removeListener",A,U||P)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(A){var P,x,T;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[A]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[A]),this;if(arguments.length===0){var R=Object.keys(x),M;for(T=0;T<R.length;++T)M=R[T],M!=="removeListener"&&this.removeAllListeners(M);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(P=x[A],typeof P=="function")this.removeListener(A,P);else if(P!==void 0)for(T=P.length-1;T>=0;T--)this.removeListener(A,P[T]);return this};function f(b,A,P){var x=b._events;if(x===void 0)return[];var T=x[A];return T===void 0?[]:typeof T=="function"?P?[T.listener||T]:[T]:P?w(T):p(T,T.length)}s.prototype.listeners=function(A){return f(this,A,!0)},s.prototype.rawListeners=function(A){return f(this,A,!1)},s.listenerCount=function(b,A){return typeof b.listenerCount=="function"?b.listenerCount(A):h.call(b,A)},s.prototype.listenerCount=h;function h(b){var A=this._events;if(A!==void 0){var P=A[b];if(typeof P=="function")return 1;if(P!==void 0)return P.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]};function p(b,A){for(var P=new Array(A),x=0;x<A;++x)P[x]=b[x];return P}function m(b,A){for(;A+1<b.length;A++)b[A]=b[A+1];b.pop()}function w(b){for(var A=new Array(b.length),P=0;P<A.length;++P)A[P]=b[P].listener||b[P];return A}function y(b,A){return new Promise(function(P,x){function T(M){b.removeListener(A,R),x(M)}function R(){typeof b.removeListener=="function"&&b.removeListener("error",T),P([].slice.call(arguments))}_(b,A,R,{once:!0}),A!=="error"&&g(b,T,{once:!0})})}function g(b,A,P){typeof b.on=="function"&&_(b,"error",A,P)}function _(b,A,P,x){if(typeof b.on=="function")x.once?b.once(A,P):b.on(A,P);else if(typeof b.addEventListener=="function")b.addEventListener(A,function T(R){x.once&&b.removeEventListener(A,T),P(R)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Ca.exports}var hl,xp;function d_(){return xp||(xp=1,hl=f_().EventEmitter),hl}var pl={},Aa={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var Pp;function NT(){return Pp||(Pp=1,Aa.read=function(e,t,r,n,i){var s,a,o=i*8-n-1,c=(1<<o)-1,l=c>>1,u=-7,d=r?i-1:0,f=r?-1:1,h=e[t+d];for(d+=f,s=h&(1<<-u)-1,h>>=-u,u+=o;u>0;s=s*256+e[t+d],d+=f,u-=8);for(a=s&(1<<-u)-1,s>>=-u,u+=n;u>0;a=a*256+e[t+d],d+=f,u-=8);if(s===0)s=1-l;else{if(s===c)return a?NaN:(h?-1:1)*(1/0);a=a+Math.pow(2,n),s=s-l}return(h?-1:1)*a*Math.pow(2,s-n)},Aa.write=function(e,t,r,n,i,s){var a,o,c,l=s*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:s-1,p=n?1:-1,m=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+d>=1?t+=f/c:t+=f*Math.pow(2,1-d),t*c>=2&&(a++,c/=2),a+d>=u?(o=0,a=u):a+d>=1?(o=(t*c-1)*Math.pow(2,i),a=a+d):(o=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+h]=o&255,h+=p,o/=256,i-=8);for(a=a<<i|o,l+=i;l>0;e[r+h]=a&255,h+=p,a/=256,l-=8);e[r+h-p]|=m*128}),Aa}/*!
29
- * The buffer module from node.js, for the browser.
30
- *
31
- * @author Feross Aboukhadijeh <https://feross.org>
32
- * @license MIT
33
- */var kp;function ac(){return kp||(kp=1,(function(e){const t=YS(),r=NT(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=o,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=s(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const O=new Uint8Array(1),v={foo:function(){return 42}};return Object.setPrototypeOf(v,Uint8Array.prototype),Object.setPrototypeOf(O,v),O.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function a(O){if(O>i)throw new RangeError('The value "'+O+'" is invalid for option "size"');const v=new Uint8Array(O);return Object.setPrototypeOf(v,o.prototype),v}function o(O,v,E){if(typeof O=="number"){if(typeof v=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(O)}return c(O,v,E)}o.poolSize=8192;function c(O,v,E){if(typeof O=="string")return f(O,v);if(ArrayBuffer.isView(O))return p(O);if(O==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof O);if(Lt(O,ArrayBuffer)||O&&Lt(O.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Lt(O,SharedArrayBuffer)||O&&Lt(O.buffer,SharedArrayBuffer)))return m(O,v,E);if(typeof O=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const N=O.valueOf&&O.valueOf();if(N!=null&&N!==O)return o.from(N,v,E);const B=w(O);if(B)return B;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof O[Symbol.toPrimitive]=="function")return o.from(O[Symbol.toPrimitive]("string"),v,E);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof O)}o.from=function(O,v,E){return c(O,v,E)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(O){if(typeof O!="number")throw new TypeError('"size" argument must be of type number');if(O<0)throw new RangeError('The value "'+O+'" is invalid for option "size"')}function u(O,v,E){return l(O),O<=0?a(O):v!==void 0?typeof E=="string"?a(O).fill(v,E):a(O).fill(v):a(O)}o.alloc=function(O,v,E){return u(O,v,E)};function d(O){return l(O),a(O<0?0:y(O)|0)}o.allocUnsafe=function(O){return d(O)},o.allocUnsafeSlow=function(O){return d(O)};function f(O,v){if((typeof v!="string"||v==="")&&(v="utf8"),!o.isEncoding(v))throw new TypeError("Unknown encoding: "+v);const E=_(O,v)|0;let N=a(E);const B=N.write(O,v);return B!==E&&(N=N.slice(0,B)),N}function h(O){const v=O.length<0?0:y(O.length)|0,E=a(v);for(let N=0;N<v;N+=1)E[N]=O[N]&255;return E}function p(O){if(Lt(O,Uint8Array)){const v=new Uint8Array(O);return m(v.buffer,v.byteOffset,v.byteLength)}return h(O)}function m(O,v,E){if(v<0||O.byteLength<v)throw new RangeError('"offset" is outside of buffer bounds');if(O.byteLength<v+(E||0))throw new RangeError('"length" is outside of buffer bounds');let N;return v===void 0&&E===void 0?N=new Uint8Array(O):E===void 0?N=new Uint8Array(O,v):N=new Uint8Array(O,v,E),Object.setPrototypeOf(N,o.prototype),N}function w(O){if(o.isBuffer(O)){const v=y(O.length)|0,E=a(v);return E.length===0||O.copy(E,0,0,v),E}if(O.length!==void 0)return typeof O.length!="number"||wn(O.length)?a(0):h(O);if(O.type==="Buffer"&&Array.isArray(O.data))return h(O.data)}function y(O){if(O>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return O|0}function g(O){return+O!=O&&(O=0),o.alloc(+O)}o.isBuffer=function(v){return v!=null&&v._isBuffer===!0&&v!==o.prototype},o.compare=function(v,E){if(Lt(v,Uint8Array)&&(v=o.from(v,v.offset,v.byteLength)),Lt(E,Uint8Array)&&(E=o.from(E,E.offset,E.byteLength)),!o.isBuffer(v)||!o.isBuffer(E))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(v===E)return 0;let N=v.length,B=E.length;for(let G=0,Z=Math.min(N,B);G<Z;++G)if(v[G]!==E[G]){N=v[G],B=E[G];break}return N<B?-1:B<N?1:0},o.isEncoding=function(v){switch(String(v).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(v,E){if(!Array.isArray(v))throw new TypeError('"list" argument must be an Array of Buffers');if(v.length===0)return o.alloc(0);let N;if(E===void 0)for(E=0,N=0;N<v.length;++N)E+=v[N].length;const B=o.allocUnsafe(E);let G=0;for(N=0;N<v.length;++N){let Z=v[N];if(Lt(Z,Uint8Array))G+Z.length>B.length?(o.isBuffer(Z)||(Z=o.from(Z)),Z.copy(B,G)):Uint8Array.prototype.set.call(B,Z,G);else if(o.isBuffer(Z))Z.copy(B,G);else throw new TypeError('"list" argument must be an Array of Buffers');G+=Z.length}return B};function _(O,v){if(o.isBuffer(O))return O.length;if(ArrayBuffer.isView(O)||Lt(O,ArrayBuffer))return O.byteLength;if(typeof O!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof O);const E=O.length,N=arguments.length>2&&arguments[2]===!0;if(!N&&E===0)return 0;let B=!1;for(;;)switch(v){case"ascii":case"latin1":case"binary":return E;case"utf8":case"utf-8":return ye(O).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E*2;case"hex":return E>>>1;case"base64":return xr(O).length;default:if(B)return N?-1:ye(O).length;v=(""+v).toLowerCase(),B=!0}}o.byteLength=_;function b(O,v,E){let N=!1;if((v===void 0||v<0)&&(v=0),v>this.length||((E===void 0||E>this.length)&&(E=this.length),E<=0)||(E>>>=0,v>>>=0,E<=v))return"";for(O||(O="utf8");;)switch(O){case"hex":return q(this,v,E);case"utf8":case"utf-8":return K(this,v,E);case"ascii":return z(this,v,E);case"latin1":case"binary":return W(this,v,E);case"base64":return F(this,v,E);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,v,E);default:if(N)throw new TypeError("Unknown encoding: "+O);O=(O+"").toLowerCase(),N=!0}}o.prototype._isBuffer=!0;function A(O,v,E){const N=O[v];O[v]=O[E],O[E]=N}o.prototype.swap16=function(){const v=this.length;if(v%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let E=0;E<v;E+=2)A(this,E,E+1);return this},o.prototype.swap32=function(){const v=this.length;if(v%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let E=0;E<v;E+=4)A(this,E,E+3),A(this,E+1,E+2);return this},o.prototype.swap64=function(){const v=this.length;if(v%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let E=0;E<v;E+=8)A(this,E,E+7),A(this,E+1,E+6),A(this,E+2,E+5),A(this,E+3,E+4);return this},o.prototype.toString=function(){const v=this.length;return v===0?"":arguments.length===0?K(this,0,v):b.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(v){if(!o.isBuffer(v))throw new TypeError("Argument must be a Buffer");return this===v?!0:o.compare(this,v)===0},o.prototype.inspect=function(){let v="";const E=e.INSPECT_MAX_BYTES;return v=this.toString("hex",0,E).replace(/(.{2})/g,"$1 ").trim(),this.length>E&&(v+=" ... "),"<Buffer "+v+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(v,E,N,B,G){if(Lt(v,Uint8Array)&&(v=o.from(v,v.offset,v.byteLength)),!o.isBuffer(v))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof v);if(E===void 0&&(E=0),N===void 0&&(N=v?v.length:0),B===void 0&&(B=0),G===void 0&&(G=this.length),E<0||N>v.length||B<0||G>this.length)throw new RangeError("out of range index");if(B>=G&&E>=N)return 0;if(B>=G)return-1;if(E>=N)return 1;if(E>>>=0,N>>>=0,B>>>=0,G>>>=0,this===v)return 0;let Z=G-B,be=N-E;const Be=Math.min(Z,be),De=this.slice(B,G),ze=v.slice(E,N);for(let $e=0;$e<Be;++$e)if(De[$e]!==ze[$e]){Z=De[$e],be=ze[$e];break}return Z<be?-1:be<Z?1:0};function P(O,v,E,N,B){if(O.length===0)return-1;if(typeof E=="string"?(N=E,E=0):E>2147483647?E=2147483647:E<-2147483648&&(E=-2147483648),E=+E,wn(E)&&(E=B?0:O.length-1),E<0&&(E=O.length+E),E>=O.length){if(B)return-1;E=O.length-1}else if(E<0)if(B)E=0;else return-1;if(typeof v=="string"&&(v=o.from(v,N)),o.isBuffer(v))return v.length===0?-1:x(O,v,E,N,B);if(typeof v=="number")return v=v&255,typeof Uint8Array.prototype.indexOf=="function"?B?Uint8Array.prototype.indexOf.call(O,v,E):Uint8Array.prototype.lastIndexOf.call(O,v,E):x(O,[v],E,N,B);throw new TypeError("val must be string, number or Buffer")}function x(O,v,E,N,B){let G=1,Z=O.length,be=v.length;if(N!==void 0&&(N=String(N).toLowerCase(),N==="ucs2"||N==="ucs-2"||N==="utf16le"||N==="utf-16le")){if(O.length<2||v.length<2)return-1;G=2,Z/=2,be/=2,E/=2}function Be(ze,$e){return G===1?ze[$e]:ze.readUInt16BE($e*G)}let De;if(B){let ze=-1;for(De=E;De<Z;De++)if(Be(O,De)===Be(v,ze===-1?0:De-ze)){if(ze===-1&&(ze=De),De-ze+1===be)return ze*G}else ze!==-1&&(De-=De-ze),ze=-1}else for(E+be>Z&&(E=Z-be),De=E;De>=0;De--){let ze=!0;for(let $e=0;$e<be;$e++)if(Be(O,De+$e)!==Be(v,$e)){ze=!1;break}if(ze)return De}return-1}o.prototype.includes=function(v,E,N){return this.indexOf(v,E,N)!==-1},o.prototype.indexOf=function(v,E,N){return P(this,v,E,N,!0)},o.prototype.lastIndexOf=function(v,E,N){return P(this,v,E,N,!1)};function T(O,v,E,N){E=Number(E)||0;const B=O.length-E;N?(N=Number(N),N>B&&(N=B)):N=B;const G=v.length;N>G/2&&(N=G/2);let Z;for(Z=0;Z<N;++Z){const be=parseInt(v.substr(Z*2,2),16);if(wn(be))return Z;O[E+Z]=be}return Z}function R(O,v,E,N){return Pr(ye(v,O.length-E),O,E,N)}function M(O,v,E,N){return Pr(Vt(v),O,E,N)}function U(O,v,E,N){return Pr(xr(v),O,E,N)}function H(O,v,E,N){return Pr(Or(v,O.length-E),O,E,N)}o.prototype.write=function(v,E,N,B){if(E===void 0)B="utf8",N=this.length,E=0;else if(N===void 0&&typeof E=="string")B=E,N=this.length,E=0;else if(isFinite(E))E=E>>>0,isFinite(N)?(N=N>>>0,B===void 0&&(B="utf8")):(B=N,N=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const G=this.length-E;if((N===void 0||N>G)&&(N=G),v.length>0&&(N<0||E<0)||E>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let Z=!1;for(;;)switch(B){case"hex":return T(this,v,E,N);case"utf8":case"utf-8":return R(this,v,E,N);case"ascii":case"latin1":case"binary":return M(this,v,E,N);case"base64":return U(this,v,E,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,v,E,N);default:if(Z)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),Z=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function F(O,v,E){return v===0&&E===O.length?t.fromByteArray(O):t.fromByteArray(O.slice(v,E))}function K(O,v,E){E=Math.min(O.length,E);const N=[];let B=v;for(;B<E;){const G=O[B];let Z=null,be=G>239?4:G>223?3:G>191?2:1;if(B+be<=E){let Be,De,ze,$e;switch(be){case 1:G<128&&(Z=G);break;case 2:Be=O[B+1],(Be&192)===128&&($e=(G&31)<<6|Be&63,$e>127&&(Z=$e));break;case 3:Be=O[B+1],De=O[B+2],(Be&192)===128&&(De&192)===128&&($e=(G&15)<<12|(Be&63)<<6|De&63,$e>2047&&($e<55296||$e>57343)&&(Z=$e));break;case 4:Be=O[B+1],De=O[B+2],ze=O[B+3],(Be&192)===128&&(De&192)===128&&(ze&192)===128&&($e=(G&15)<<18|(Be&63)<<12|(De&63)<<6|ze&63,$e>65535&&$e<1114112&&(Z=$e))}}Z===null?(Z=65533,be=1):Z>65535&&(Z-=65536,N.push(Z>>>10&1023|55296),Z=56320|Z&1023),N.push(Z),B+=be}return L(N)}const ee=4096;function L(O){const v=O.length;if(v<=ee)return String.fromCharCode.apply(String,O);let E="",N=0;for(;N<v;)E+=String.fromCharCode.apply(String,O.slice(N,N+=ee));return E}function z(O,v,E){let N="";E=Math.min(O.length,E);for(let B=v;B<E;++B)N+=String.fromCharCode(O[B]&127);return N}function W(O,v,E){let N="";E=Math.min(O.length,E);for(let B=v;B<E;++B)N+=String.fromCharCode(O[B]);return N}function q(O,v,E){const N=O.length;(!v||v<0)&&(v=0),(!E||E<0||E>N)&&(E=N);let B="";for(let G=v;G<E;++G)B+=os[O[G]];return B}function V(O,v,E){const N=O.slice(v,E);let B="";for(let G=0;G<N.length-1;G+=2)B+=String.fromCharCode(N[G]+N[G+1]*256);return B}o.prototype.slice=function(v,E){const N=this.length;v=~~v,E=E===void 0?N:~~E,v<0?(v+=N,v<0&&(v=0)):v>N&&(v=N),E<0?(E+=N,E<0&&(E=0)):E>N&&(E=N),E<v&&(E=v);const B=this.subarray(v,E);return Object.setPrototypeOf(B,o.prototype),B};function Y(O,v,E){if(O%1!==0||O<0)throw new RangeError("offset is not uint");if(O+v>E)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(v,E,N){v=v>>>0,E=E>>>0,N||Y(v,E,this.length);let B=this[v],G=1,Z=0;for(;++Z<E&&(G*=256);)B+=this[v+Z]*G;return B},o.prototype.readUintBE=o.prototype.readUIntBE=function(v,E,N){v=v>>>0,E=E>>>0,N||Y(v,E,this.length);let B=this[v+--E],G=1;for(;E>0&&(G*=256);)B+=this[v+--E]*G;return B},o.prototype.readUint8=o.prototype.readUInt8=function(v,E){return v=v>>>0,E||Y(v,1,this.length),this[v]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(v,E){return v=v>>>0,E||Y(v,2,this.length),this[v]|this[v+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(v,E){return v=v>>>0,E||Y(v,2,this.length),this[v]<<8|this[v+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(v,E){return v=v>>>0,E||Y(v,4,this.length),(this[v]|this[v+1]<<8|this[v+2]<<16)+this[v+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(v,E){return v=v>>>0,E||Y(v,4,this.length),this[v]*16777216+(this[v+1]<<16|this[v+2]<<8|this[v+3])},o.prototype.readBigUInt64LE=Wt(function(v){v=v>>>0,J(v,"offset");const E=this[v],N=this[v+7];(E===void 0||N===void 0)&&ne(v,this.length-8);const B=E+this[++v]*2**8+this[++v]*2**16+this[++v]*2**24,G=this[++v]+this[++v]*2**8+this[++v]*2**16+N*2**24;return BigInt(B)+(BigInt(G)<<BigInt(32))}),o.prototype.readBigUInt64BE=Wt(function(v){v=v>>>0,J(v,"offset");const E=this[v],N=this[v+7];(E===void 0||N===void 0)&&ne(v,this.length-8);const B=E*2**24+this[++v]*2**16+this[++v]*2**8+this[++v],G=this[++v]*2**24+this[++v]*2**16+this[++v]*2**8+N;return(BigInt(B)<<BigInt(32))+BigInt(G)}),o.prototype.readIntLE=function(v,E,N){v=v>>>0,E=E>>>0,N||Y(v,E,this.length);let B=this[v],G=1,Z=0;for(;++Z<E&&(G*=256);)B+=this[v+Z]*G;return G*=128,B>=G&&(B-=Math.pow(2,8*E)),B},o.prototype.readIntBE=function(v,E,N){v=v>>>0,E=E>>>0,N||Y(v,E,this.length);let B=E,G=1,Z=this[v+--B];for(;B>0&&(G*=256);)Z+=this[v+--B]*G;return G*=128,Z>=G&&(Z-=Math.pow(2,8*E)),Z},o.prototype.readInt8=function(v,E){return v=v>>>0,E||Y(v,1,this.length),this[v]&128?(255-this[v]+1)*-1:this[v]},o.prototype.readInt16LE=function(v,E){v=v>>>0,E||Y(v,2,this.length);const N=this[v]|this[v+1]<<8;return N&32768?N|4294901760:N},o.prototype.readInt16BE=function(v,E){v=v>>>0,E||Y(v,2,this.length);const N=this[v+1]|this[v]<<8;return N&32768?N|4294901760:N},o.prototype.readInt32LE=function(v,E){return v=v>>>0,E||Y(v,4,this.length),this[v]|this[v+1]<<8|this[v+2]<<16|this[v+3]<<24},o.prototype.readInt32BE=function(v,E){return v=v>>>0,E||Y(v,4,this.length),this[v]<<24|this[v+1]<<16|this[v+2]<<8|this[v+3]},o.prototype.readBigInt64LE=Wt(function(v){v=v>>>0,J(v,"offset");const E=this[v],N=this[v+7];(E===void 0||N===void 0)&&ne(v,this.length-8);const B=this[v+4]+this[v+5]*2**8+this[v+6]*2**16+(N<<24);return(BigInt(B)<<BigInt(32))+BigInt(E+this[++v]*2**8+this[++v]*2**16+this[++v]*2**24)}),o.prototype.readBigInt64BE=Wt(function(v){v=v>>>0,J(v,"offset");const E=this[v],N=this[v+7];(E===void 0||N===void 0)&&ne(v,this.length-8);const B=(E<<24)+this[++v]*2**16+this[++v]*2**8+this[++v];return(BigInt(B)<<BigInt(32))+BigInt(this[++v]*2**24+this[++v]*2**16+this[++v]*2**8+N)}),o.prototype.readFloatLE=function(v,E){return v=v>>>0,E||Y(v,4,this.length),r.read(this,v,!0,23,4)},o.prototype.readFloatBE=function(v,E){return v=v>>>0,E||Y(v,4,this.length),r.read(this,v,!1,23,4)},o.prototype.readDoubleLE=function(v,E){return v=v>>>0,E||Y(v,8,this.length),r.read(this,v,!0,52,8)},o.prototype.readDoubleBE=function(v,E){return v=v>>>0,E||Y(v,8,this.length),r.read(this,v,!1,52,8)};function Q(O,v,E,N,B,G){if(!o.isBuffer(O))throw new TypeError('"buffer" argument must be a Buffer instance');if(v>B||v<G)throw new RangeError('"value" argument is out of bounds');if(E+N>O.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(v,E,N,B){if(v=+v,E=E>>>0,N=N>>>0,!B){const be=Math.pow(2,8*N)-1;Q(this,v,E,N,be,0)}let G=1,Z=0;for(this[E]=v&255;++Z<N&&(G*=256);)this[E+Z]=v/G&255;return E+N},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(v,E,N,B){if(v=+v,E=E>>>0,N=N>>>0,!B){const be=Math.pow(2,8*N)-1;Q(this,v,E,N,be,0)}let G=N-1,Z=1;for(this[E+G]=v&255;--G>=0&&(Z*=256);)this[E+G]=v/Z&255;return E+N},o.prototype.writeUint8=o.prototype.writeUInt8=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,1,255,0),this[E]=v&255,E+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,2,65535,0),this[E]=v&255,this[E+1]=v>>>8,E+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,2,65535,0),this[E]=v>>>8,this[E+1]=v&255,E+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,4,4294967295,0),this[E+3]=v>>>24,this[E+2]=v>>>16,this[E+1]=v>>>8,this[E]=v&255,E+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,4,4294967295,0),this[E]=v>>>24,this[E+1]=v>>>16,this[E+2]=v>>>8,this[E+3]=v&255,E+4};function ae(O,v,E,N,B){I(v,N,B,O,E,7);let G=Number(v&BigInt(4294967295));O[E++]=G,G=G>>8,O[E++]=G,G=G>>8,O[E++]=G,G=G>>8,O[E++]=G;let Z=Number(v>>BigInt(32)&BigInt(4294967295));return O[E++]=Z,Z=Z>>8,O[E++]=Z,Z=Z>>8,O[E++]=Z,Z=Z>>8,O[E++]=Z,E}function X(O,v,E,N,B){I(v,N,B,O,E,7);let G=Number(v&BigInt(4294967295));O[E+7]=G,G=G>>8,O[E+6]=G,G=G>>8,O[E+5]=G,G=G>>8,O[E+4]=G;let Z=Number(v>>BigInt(32)&BigInt(4294967295));return O[E+3]=Z,Z=Z>>8,O[E+2]=Z,Z=Z>>8,O[E+1]=Z,Z=Z>>8,O[E]=Z,E+8}o.prototype.writeBigUInt64LE=Wt(function(v,E=0){return ae(this,v,E,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Wt(function(v,E=0){return X(this,v,E,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(v,E,N,B){if(v=+v,E=E>>>0,!B){const Be=Math.pow(2,8*N-1);Q(this,v,E,N,Be-1,-Be)}let G=0,Z=1,be=0;for(this[E]=v&255;++G<N&&(Z*=256);)v<0&&be===0&&this[E+G-1]!==0&&(be=1),this[E+G]=(v/Z>>0)-be&255;return E+N},o.prototype.writeIntBE=function(v,E,N,B){if(v=+v,E=E>>>0,!B){const Be=Math.pow(2,8*N-1);Q(this,v,E,N,Be-1,-Be)}let G=N-1,Z=1,be=0;for(this[E+G]=v&255;--G>=0&&(Z*=256);)v<0&&be===0&&this[E+G+1]!==0&&(be=1),this[E+G]=(v/Z>>0)-be&255;return E+N},o.prototype.writeInt8=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,1,127,-128),v<0&&(v=255+v+1),this[E]=v&255,E+1},o.prototype.writeInt16LE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,2,32767,-32768),this[E]=v&255,this[E+1]=v>>>8,E+2},o.prototype.writeInt16BE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,2,32767,-32768),this[E]=v>>>8,this[E+1]=v&255,E+2},o.prototype.writeInt32LE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,4,2147483647,-2147483648),this[E]=v&255,this[E+1]=v>>>8,this[E+2]=v>>>16,this[E+3]=v>>>24,E+4},o.prototype.writeInt32BE=function(v,E,N){return v=+v,E=E>>>0,N||Q(this,v,E,4,2147483647,-2147483648),v<0&&(v=4294967295+v+1),this[E]=v>>>24,this[E+1]=v>>>16,this[E+2]=v>>>8,this[E+3]=v&255,E+4},o.prototype.writeBigInt64LE=Wt(function(v,E=0){return ae(this,v,E,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Wt(function(v,E=0){return X(this,v,E,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function se(O,v,E,N,B,G){if(E+N>O.length)throw new RangeError("Index out of range");if(E<0)throw new RangeError("Index out of range")}function C(O,v,E,N,B){return v=+v,E=E>>>0,B||se(O,v,E,4),r.write(O,v,E,N,23,4),E+4}o.prototype.writeFloatLE=function(v,E,N){return C(this,v,E,!0,N)},o.prototype.writeFloatBE=function(v,E,N){return C(this,v,E,!1,N)};function S(O,v,E,N,B){return v=+v,E=E>>>0,B||se(O,v,E,8),r.write(O,v,E,N,52,8),E+8}o.prototype.writeDoubleLE=function(v,E,N){return S(this,v,E,!0,N)},o.prototype.writeDoubleBE=function(v,E,N){return S(this,v,E,!1,N)},o.prototype.copy=function(v,E,N,B){if(!o.isBuffer(v))throw new TypeError("argument should be a Buffer");if(N||(N=0),!B&&B!==0&&(B=this.length),E>=v.length&&(E=v.length),E||(E=0),B>0&&B<N&&(B=N),B===N||v.length===0||this.length===0)return 0;if(E<0)throw new RangeError("targetStart out of bounds");if(N<0||N>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),v.length-E<B-N&&(B=v.length-E+N);const G=B-N;return this===v&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(E,N,B):Uint8Array.prototype.set.call(v,this.subarray(N,B),E),G},o.prototype.fill=function(v,E,N,B){if(typeof v=="string"){if(typeof E=="string"?(B=E,E=0,N=this.length):typeof N=="string"&&(B=N,N=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!o.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(v.length===1){const Z=v.charCodeAt(0);(B==="utf8"&&Z<128||B==="latin1")&&(v=Z)}}else typeof v=="number"?v=v&255:typeof v=="boolean"&&(v=Number(v));if(E<0||this.length<E||this.length<N)throw new RangeError("Out of range index");if(N<=E)return this;E=E>>>0,N=N===void 0?this.length:N>>>0,v||(v=0);let G;if(typeof v=="number")for(G=E;G<N;++G)this[G]=v;else{const Z=o.isBuffer(v)?v:o.from(v,B),be=Z.length;if(be===0)throw new TypeError('The value "'+v+'" is invalid for argument "value"');for(G=0;G<N-E;++G)this[G+E]=Z[G%be]}return this};const D={};function j(O,v,E){D[O]=class extends E{constructor(){super(),Object.defineProperty(this,"message",{value:v.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${O}]`,this.stack,delete this.name}get code(){return O}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${O}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(O){return O?`${O} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(O,v){return`The "${O}" argument must be of type number. Received type ${typeof v}`},TypeError),j("ERR_OUT_OF_RANGE",function(O,v,E){let N=`The value of "${O}" is out of range.`,B=E;return Number.isInteger(E)&&Math.abs(E)>2**32?B=re(String(E)):typeof E=="bigint"&&(B=String(E),(E>BigInt(2)**BigInt(32)||E<-(BigInt(2)**BigInt(32)))&&(B=re(B)),B+="n"),N+=` It must be ${v}. Received ${B}`,N},RangeError);function re(O){let v="",E=O.length;const N=O[0]==="-"?1:0;for(;E>=N+4;E-=3)v=`_${O.slice(E-3,E)}${v}`;return`${O.slice(0,E)}${v}`}function k(O,v,E){J(v,"offset"),(O[v]===void 0||O[v+E]===void 0)&&ne(v,O.length-(E+1))}function I(O,v,E,N,B,G){if(O>E||O<v){const Z=typeof v=="bigint"?"n":"";let be;throw v===0||v===BigInt(0)?be=`>= 0${Z} and < 2${Z} ** ${(G+1)*8}${Z}`:be=`>= -(2${Z} ** ${(G+1)*8-1}${Z}) and < 2 ** ${(G+1)*8-1}${Z}`,new D.ERR_OUT_OF_RANGE("value",be,O)}k(N,B,G)}function J(O,v){if(typeof O!="number")throw new D.ERR_INVALID_ARG_TYPE(v,"number",O)}function ne(O,v,E){throw Math.floor(O)!==O?(J(O,E),new D.ERR_OUT_OF_RANGE("offset","an integer",O)):v<0?new D.ERR_BUFFER_OUT_OF_BOUNDS:new D.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${v}`,O)}const Te=/[^+/0-9A-Za-z-_]/g;function ue(O){if(O=O.split("=")[0],O=O.trim().replace(Te,""),O.length<2)return"";for(;O.length%4!==0;)O=O+"=";return O}function ye(O,v){v=v||1/0;let E;const N=O.length;let B=null;const G=[];for(let Z=0;Z<N;++Z){if(E=O.charCodeAt(Z),E>55295&&E<57344){if(!B){if(E>56319){(v-=3)>-1&&G.push(239,191,189);continue}else if(Z+1===N){(v-=3)>-1&&G.push(239,191,189);continue}B=E;continue}if(E<56320){(v-=3)>-1&&G.push(239,191,189),B=E;continue}E=(B-55296<<10|E-56320)+65536}else B&&(v-=3)>-1&&G.push(239,191,189);if(B=null,E<128){if((v-=1)<0)break;G.push(E)}else if(E<2048){if((v-=2)<0)break;G.push(E>>6|192,E&63|128)}else if(E<65536){if((v-=3)<0)break;G.push(E>>12|224,E>>6&63|128,E&63|128)}else if(E<1114112){if((v-=4)<0)break;G.push(E>>18|240,E>>12&63|128,E>>6&63|128,E&63|128)}else throw new Error("Invalid code point")}return G}function Vt(O){const v=[];for(let E=0;E<O.length;++E)v.push(O.charCodeAt(E)&255);return v}function Or(O,v){let E,N,B;const G=[];for(let Z=0;Z<O.length&&!((v-=2)<0);++Z)E=O.charCodeAt(Z),N=E>>8,B=E%256,G.push(B),G.push(N);return G}function xr(O){return t.toByteArray(ue(O))}function Pr(O,v,E,N){let B;for(B=0;B<N&&!(B+E>=v.length||B>=O.length);++B)v[B+E]=O[B];return B}function Lt(O,v){return O instanceof v||O!=null&&O.constructor!=null&&O.constructor.name!=null&&O.constructor.name===v.name}function wn(O){return O!==O}const os=(function(){const O="0123456789abcdef",v=new Array(256);for(let E=0;E<16;++E){const N=E*16;for(let B=0;B<16;++B)v[N+B]=O[E]+O[B]}return v})();function Wt(O){return typeof BigInt>"u"?bn:O}function bn(){throw new Error("BigInt not supported")}})(pl)),pl}var ml,Ip;function h_(){if(Ip)return ml;Ip=1;function e(a,o){var c=this,l=this._readableState&&this._readableState.destroyed,u=this._writableState&&this._writableState.destroyed;return l||u?(o?o(a):a&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(i,this,a)):process.nextTick(i,this,a)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(a||null,function(d){!o&&d?c._writableState?c._writableState.errorEmitted?process.nextTick(r,c):(c._writableState.errorEmitted=!0,process.nextTick(t,c,d)):process.nextTick(t,c,d):o?(process.nextTick(r,c),o(d)):process.nextTick(r,c)}),this)}function t(a,o){i(a,o),r(a)}function r(a){a._writableState&&!a._writableState.emitClose||a._readableState&&!a._readableState.emitClose||a.emit("close")}function n(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function i(a,o){a.emit("error",o)}function s(a,o){var c=a._readableState,l=a._writableState;c&&c.autoDestroy||l&&l.autoDestroy?a.destroy(o):a.emit("error",o)}return ml={destroy:e,undestroy:n,errorOrDestroy:s},ml}var gl={},Mp;function es(){if(Mp)return gl;Mp=1;function e(o,c){o.prototype=Object.create(c.prototype),o.prototype.constructor=o,o.__proto__=c}var t={};function r(o,c,l){l||(l=Error);function u(f,h,p){return typeof c=="string"?c:c(f,h,p)}var d=(function(f){e(h,f);function h(p,m,w){return f.call(this,u(p,m,w))||this}return h})(l);d.prototype.name=l.name,d.prototype.code=o,t[o]=d}function n(o,c){if(Array.isArray(o)){var l=o.length;return o=o.map(function(u){return String(u)}),l>2?"one of ".concat(c," ").concat(o.slice(0,l-1).join(", "),", or ")+o[l-1]:l===2?"one of ".concat(c," ").concat(o[0]," or ").concat(o[1]):"of ".concat(c," ").concat(o[0])}else return"of ".concat(c," ").concat(String(o))}function i(o,c,l){return o.substr(0,c.length)===c}function s(o,c,l){return(l===void 0||l>o.length)&&(l=o.length),o.substring(l-c.length,l)===c}function a(o,c,l){return typeof l!="number"&&(l=0),l+c.length>o.length?!1:o.indexOf(c,l)!==-1}return r("ERR_INVALID_OPT_VALUE",function(o,c){return'The value "'+c+'" is invalid for option "'+o+'"'},TypeError),r("ERR_INVALID_ARG_TYPE",function(o,c,l){var u;typeof c=="string"&&i(c,"not ")?(u="must not be",c=c.replace(/^not /,"")):u="must be";var d;if(s(o," argument"))d="The ".concat(o," ").concat(u," ").concat(n(c,"type"));else{var f=a(o,".")?"property":"argument";d='The "'.concat(o,'" ').concat(f," ").concat(u," ").concat(n(c,"type"))}return d+=". Received type ".concat(typeof l),d},TypeError),r("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),r("ERR_METHOD_NOT_IMPLEMENTED",function(o){return"The "+o+" method is not implemented"}),r("ERR_STREAM_PREMATURE_CLOSE","Premature close"),r("ERR_STREAM_DESTROYED",function(o){return"Cannot call "+o+" after a stream was destroyed"}),r("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),r("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),r("ERR_STREAM_WRITE_AFTER_END","write after end"),r("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),r("ERR_UNKNOWN_ENCODING",function(o){return"Unknown encoding: "+o},TypeError),r("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),gl.codes=t,gl}var yl,Rp;function p_(){if(Rp)return yl;Rp=1;var e=es().codes.ERR_INVALID_OPT_VALUE;function t(n,i,s){return n.highWaterMark!=null?n.highWaterMark:i?n[s]:null}function r(n,i,s,a){var o=t(i,a,s);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0){var c=a?s:"highWaterMark";throw new e(c,o)}return Math.floor(o)}return n.objectMode?16:16*1024}return yl={getHighWaterMark:r},yl}var Oa={exports:{}},Np;function Qs(){return Np||(Np=1,typeof Object.create=="function"?Oa.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Oa.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}}),Oa.exports}var _l,$p;function $T(){if($p)return _l;$p=1;function e(p,m){var w=Object.keys(p);if(Object.getOwnPropertySymbols){var y=Object.getOwnPropertySymbols(p);m&&(y=y.filter(function(g){return Object.getOwnPropertyDescriptor(p,g).enumerable})),w.push.apply(w,y)}return w}function t(p){for(var m=1;m<arguments.length;m++){var w=arguments[m]!=null?arguments[m]:{};m%2?e(Object(w),!0).forEach(function(y){r(p,y,w[y])}):Object.getOwnPropertyDescriptors?Object.defineProperties(p,Object.getOwnPropertyDescriptors(w)):e(Object(w)).forEach(function(y){Object.defineProperty(p,y,Object.getOwnPropertyDescriptor(w,y))})}return p}function r(p,m,w){return m=a(m),m in p?Object.defineProperty(p,m,{value:w,enumerable:!0,configurable:!0,writable:!0}):p[m]=w,p}function n(p,m){if(!(p instanceof m))throw new TypeError("Cannot call a class as a function")}function i(p,m){for(var w=0;w<m.length;w++){var y=m[w];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(p,a(y.key),y)}}function s(p,m,w){return m&&i(p.prototype,m),Object.defineProperty(p,"prototype",{writable:!1}),p}function a(p){var m=o(p,"string");return typeof m=="symbol"?m:String(m)}function o(p,m){if(typeof p!="object"||p===null)return p;var w=p[Symbol.toPrimitive];if(w!==void 0){var y=w.call(p,m);if(typeof y!="object")return y;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(p)}var c=ac(),l=c.Buffer,u=Ar,d=u.inspect,f=d&&d.custom||"inspect";function h(p,m,w){l.prototype.copy.call(p,m,w)}return _l=(function(){function p(){n(this,p),this.head=null,this.tail=null,this.length=0}return s(p,[{key:"push",value:function(w){var y={data:w,next:null};this.length>0?this.tail.next=y:this.head=y,this.tail=y,++this.length}},{key:"unshift",value:function(w){var y={data:w,next:this.head};this.length===0&&(this.tail=y),this.head=y,++this.length}},{key:"shift",value:function(){if(this.length!==0){var w=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,w}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(w){if(this.length===0)return"";for(var y=this.head,g=""+y.data;y=y.next;)g+=w+y.data;return g}},{key:"concat",value:function(w){if(this.length===0)return l.alloc(0);for(var y=l.allocUnsafe(w>>>0),g=this.head,_=0;g;)h(g.data,y,_),_+=g.data.length,g=g.next;return y}},{key:"consume",value:function(w,y){var g;return w<this.head.data.length?(g=this.head.data.slice(0,w),this.head.data=this.head.data.slice(w)):w===this.head.data.length?g=this.shift():g=y?this._getString(w):this._getBuffer(w),g}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(w){var y=this.head,g=1,_=y.data;for(w-=_.length;y=y.next;){var b=y.data,A=w>b.length?b.length:w;if(A===b.length?_+=b:_+=b.slice(0,w),w-=A,w===0){A===b.length?(++g,y.next?this.head=y.next:this.head=this.tail=null):(this.head=y,y.data=b.slice(A));break}++g}return this.length-=g,_}},{key:"_getBuffer",value:function(w){var y=l.allocUnsafe(w),g=this.head,_=1;for(g.data.copy(y),w-=g.data.length;g=g.next;){var b=g.data,A=w>b.length?b.length:w;if(b.copy(y,y.length-w,0,A),w-=A,w===0){A===b.length?(++_,g.next?this.head=g.next:this.head=this.tail=null):(this.head=g,g.data=b.slice(A));break}++_}return this.length-=_,y}},{key:f,value:function(w,y){return d(this,t(t({},y),{},{depth:0,customInspect:!1}))}}]),p})(),_l}var vl={},xa={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var Lp;function LT(){return Lp||(Lp=1,(function(e,t){var r=ac(),n=r.Buffer;function i(a,o){for(var c in a)o[c]=a[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s);function s(a,o,c){return n(a,o,c)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(a,o,c){if(typeof a=="number")throw new TypeError("Argument must not be a number");return n(a,o,c)},s.alloc=function(a,o,c){if(typeof a!="number")throw new TypeError("Argument must be a number");var l=n(a);return o!==void 0?typeof c=="string"?l.fill(o,c):l.fill(o):l.fill(0),l},s.allocUnsafe=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return n(a)},s.allocUnsafeSlow=function(a){if(typeof a!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(a)}})(xa,xa.exports)),xa.exports}var jp;function Wu(){if(jp)return vl;jp=1;var e=LT().Buffer,t=e.isEncoding||function(y){switch(y=""+y,y&&y.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(y){if(!y)return"utf8";for(var g;;)switch(y){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return y;default:if(g)return;y=(""+y).toLowerCase(),g=!0}}function n(y){var g=r(y);if(typeof g!="string"&&(e.isEncoding===t||!t(y)))throw new Error("Unknown encoding: "+y);return g||y}vl.StringDecoder=i;function i(y){this.encoding=n(y);var g;switch(this.encoding){case"utf16le":this.text=d,this.end=f,g=4;break;case"utf8":this.fillLast=c,g=4;break;case"base64":this.text=h,this.end=p,g=3;break;default:this.write=m,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(g)}i.prototype.write=function(y){if(y.length===0)return"";var g,_;if(this.lastNeed){if(g=this.fillLast(y),g===void 0)return"";_=this.lastNeed,this.lastNeed=0}else _=0;return _<y.length?g?g+this.text(y,_):this.text(y,_):g||""},i.prototype.end=u,i.prototype.text=l,i.prototype.fillLast=function(y){if(this.lastNeed<=y.length)return y.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);y.copy(this.lastChar,this.lastTotal-this.lastNeed,0,y.length),this.lastNeed-=y.length};function s(y){return y<=127?0:y>>5===6?2:y>>4===14?3:y>>3===30?4:y>>6===2?-1:-2}function a(y,g,_){var b=g.length-1;if(b<_)return 0;var A=s(g[b]);return A>=0?(A>0&&(y.lastNeed=A-1),A):--b<_||A===-2?0:(A=s(g[b]),A>=0?(A>0&&(y.lastNeed=A-2),A):--b<_||A===-2?0:(A=s(g[b]),A>=0?(A>0&&(A===2?A=0:y.lastNeed=A-3),A):0))}function o(y,g,_){if((g[0]&192)!==128)return y.lastNeed=0,"�";if(y.lastNeed>1&&g.length>1){if((g[1]&192)!==128)return y.lastNeed=1,"�";if(y.lastNeed>2&&g.length>2&&(g[2]&192)!==128)return y.lastNeed=2,"�"}}function c(y){var g=this.lastTotal-this.lastNeed,_=o(this,y);if(_!==void 0)return _;if(this.lastNeed<=y.length)return y.copy(this.lastChar,g,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);y.copy(this.lastChar,g,0,y.length),this.lastNeed-=y.length}function l(y,g){var _=a(this,y,g);if(!this.lastNeed)return y.toString("utf8",g);this.lastTotal=_;var b=y.length-(_-this.lastNeed);return y.copy(this.lastChar,0,b),y.toString("utf8",g,b)}function u(y){var g=y&&y.length?this.write(y):"";return this.lastNeed?g+"�":g}function d(y,g){if((y.length-g)%2===0){var _=y.toString("utf16le",g);if(_){var b=_.charCodeAt(_.length-1);if(b>=55296&&b<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=y[y.length-2],this.lastChar[1]=y[y.length-1],_.slice(0,-1)}return _}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=y[y.length-1],y.toString("utf16le",g,y.length-1)}function f(y){var g=y&&y.length?this.write(y):"";if(this.lastNeed){var _=this.lastTotal-this.lastNeed;return g+this.lastChar.toString("utf16le",0,_)}return g}function h(y,g){var _=(y.length-g)%3;return _===0?y.toString("base64",g):(this.lastNeed=3-_,this.lastTotal=3,_===1?this.lastChar[0]=y[y.length-1]:(this.lastChar[0]=y[y.length-2],this.lastChar[1]=y[y.length-1]),y.toString("base64",g,y.length-_))}function p(y){var g=y&&y.length?this.write(y):"";return this.lastNeed?g+this.lastChar.toString("base64",0,3-this.lastNeed):g}function m(y){return y.toString(this.encoding)}function w(y){return y&&y.length?this.write(y):""}return vl}var wl,Dp;function od(){if(Dp)return wl;Dp=1;var e=es().codes.ERR_STREAM_PREMATURE_CLOSE;function t(s){var a=!1;return function(){if(!a){a=!0;for(var o=arguments.length,c=new Array(o),l=0;l<o;l++)c[l]=arguments[l];s.apply(this,c)}}}function r(){}function n(s){return s.setHeader&&typeof s.abort=="function"}function i(s,a,o){if(typeof a=="function")return i(s,null,a);a||(a={}),o=t(o||r);var c=a.readable||a.readable!==!1&&s.readable,l=a.writable||a.writable!==!1&&s.writable,u=function(){s.writable||f()},d=s._writableState&&s._writableState.finished,f=function(){l=!1,d=!0,c||o.call(s)},h=s._readableState&&s._readableState.endEmitted,p=function(){c=!1,h=!0,l||o.call(s)},m=function(_){o.call(s,_)},w=function(){var _;if(c&&!h)return(!s._readableState||!s._readableState.ended)&&(_=new e),o.call(s,_);if(l&&!d)return(!s._writableState||!s._writableState.ended)&&(_=new e),o.call(s,_)},y=function(){s.req.on("finish",f)};return n(s)?(s.on("complete",f),s.on("abort",w),s.req?y():s.on("request",y)):l&&!s._writableState&&(s.on("end",u),s.on("close",u)),s.on("end",p),s.on("finish",f),a.error!==!1&&s.on("error",m),s.on("close",w),function(){s.removeListener("complete",f),s.removeListener("abort",w),s.removeListener("request",y),s.req&&s.req.removeListener("finish",f),s.removeListener("end",u),s.removeListener("close",u),s.removeListener("finish",f),s.removeListener("end",p),s.removeListener("error",m),s.removeListener("close",w)}}return wl=i,wl}var bl,Fp;function jT(){if(Fp)return bl;Fp=1;var e;function t(_,b,A){return b=r(b),b in _?Object.defineProperty(_,b,{value:A,enumerable:!0,configurable:!0,writable:!0}):_[b]=A,_}function r(_){var b=n(_,"string");return typeof b=="symbol"?b:String(b)}function n(_,b){if(typeof _!="object"||_===null)return _;var A=_[Symbol.toPrimitive];if(A!==void 0){var P=A.call(_,b);if(typeof P!="object")return P;throw new TypeError("@@toPrimitive must return a primitive value.")}return(b==="string"?String:Number)(_)}var i=od(),s=Symbol("lastResolve"),a=Symbol("lastReject"),o=Symbol("error"),c=Symbol("ended"),l=Symbol("lastPromise"),u=Symbol("handlePromise"),d=Symbol("stream");function f(_,b){return{value:_,done:b}}function h(_){var b=_[s];if(b!==null){var A=_[d].read();A!==null&&(_[l]=null,_[s]=null,_[a]=null,b(f(A,!1)))}}function p(_){process.nextTick(h,_)}function m(_,b){return function(A,P){_.then(function(){if(b[c]){A(f(void 0,!0));return}b[u](A,P)},P)}}var w=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((e={get stream(){return this[d]},next:function(){var b=this,A=this[o];if(A!==null)return Promise.reject(A);if(this[c])return Promise.resolve(f(void 0,!0));if(this[d].destroyed)return new Promise(function(R,M){process.nextTick(function(){b[o]?M(b[o]):R(f(void 0,!0))})});var P=this[l],x;if(P)x=new Promise(m(P,this));else{var T=this[d].read();if(T!==null)return Promise.resolve(f(T,!1));x=new Promise(this[u])}return this[l]=x,x}},t(e,Symbol.asyncIterator,function(){return this}),t(e,"return",function(){var b=this;return new Promise(function(A,P){b[d].destroy(null,function(x){if(x){P(x);return}A(f(void 0,!0))})})}),e),w),g=function(b){var A,P=Object.create(y,(A={},t(A,d,{value:b,writable:!0}),t(A,s,{value:null,writable:!0}),t(A,a,{value:null,writable:!0}),t(A,o,{value:null,writable:!0}),t(A,c,{value:b._readableState.endEmitted,writable:!0}),t(A,u,{value:function(T,R){var M=P[d].read();M?(P[l]=null,P[s]=null,P[a]=null,T(f(M,!1))):(P[s]=T,P[a]=R)},writable:!0}),A));return P[l]=null,i(b,function(x){if(x&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"){var T=P[a];T!==null&&(P[l]=null,P[s]=null,P[a]=null,T(x)),P[o]=x;return}var R=P[s];R!==null&&(P[l]=null,P[s]=null,P[a]=null,R(f(void 0,!0))),P[c]=!0}),b.on("readable",p.bind(null,P)),P};return bl=g,bl}var Sl,Up;function DT(){return Up||(Up=1,Sl=function(){throw new Error("Readable.from is not available in the browser")}),Sl}var El,Bp;function m_(){if(Bp)return El;Bp=1,El=R;var e;R.ReadableState=T,f_().EventEmitter;var t=function(I,J){return I.listeners(J).length},r=d_(),n=ac().Buffer,i=(typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function s(k){return n.from(k)}function a(k){return n.isBuffer(k)||k instanceof i}var o=Ar,c;o&&o.debuglog?c=o.debuglog("stream"):c=function(){};var l=$T(),u=h_(),d=p_(),f=d.getHighWaterMark,h=es().codes,p=h.ERR_INVALID_ARG_TYPE,m=h.ERR_STREAM_PUSH_AFTER_EOF,w=h.ERR_METHOD_NOT_IMPLEMENTED,y=h.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,g,_,b;Qs()(R,r);var A=u.errorOrDestroy,P=["error","close","destroy","pause","resume"];function x(k,I,J){if(typeof k.prependListener=="function")return k.prependListener(I,J);!k._events||!k._events[I]?k.on(I,J):Array.isArray(k._events[I])?k._events[I].unshift(J):k._events[I]=[J,k._events[I]]}function T(k,I,J){e=e||Ui(),k=k||{},typeof J!="boolean"&&(J=I instanceof e),this.objectMode=!!k.objectMode,J&&(this.objectMode=this.objectMode||!!k.readableObjectMode),this.highWaterMark=f(this,k,"readableHighWaterMark",J),this.buffer=new l,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=k.emitClose!==!1,this.autoDestroy=!!k.autoDestroy,this.destroyed=!1,this.defaultEncoding=k.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,k.encoding&&(g||(g=Wu().StringDecoder),this.decoder=new g(k.encoding),this.encoding=k.encoding)}function R(k){if(e=e||Ui(),!(this instanceof R))return new R(k);var I=this instanceof e;this._readableState=new T(k,this,I),this.readable=!0,k&&(typeof k.read=="function"&&(this._read=k.read),typeof k.destroy=="function"&&(this._destroy=k.destroy)),r.call(this)}Object.defineProperty(R.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(I){this._readableState&&(this._readableState.destroyed=I)}}),R.prototype.destroy=u.destroy,R.prototype._undestroy=u.undestroy,R.prototype._destroy=function(k,I){I(k)},R.prototype.push=function(k,I){var J=this._readableState,ne;return J.objectMode?ne=!0:typeof k=="string"&&(I=I||J.defaultEncoding,I!==J.encoding&&(k=n.from(k,I),I=""),ne=!0),M(this,k,I,!1,ne)},R.prototype.unshift=function(k){return M(this,k,null,!0,!1)};function M(k,I,J,ne,Te){c("readableAddChunk",I);var ue=k._readableState;if(I===null)ue.reading=!1,L(k,ue);else{var ye;if(Te||(ye=H(ue,I)),ye)A(k,ye);else if(ue.objectMode||I&&I.length>0)if(typeof I!="string"&&!ue.objectMode&&Object.getPrototypeOf(I)!==n.prototype&&(I=s(I)),ne)ue.endEmitted?A(k,new y):U(k,ue,I,!0);else if(ue.ended)A(k,new m);else{if(ue.destroyed)return!1;ue.reading=!1,ue.decoder&&!J?(I=ue.decoder.write(I),ue.objectMode||I.length!==0?U(k,ue,I,!1):q(k,ue)):U(k,ue,I,!1)}else ne||(ue.reading=!1,q(k,ue))}return!ue.ended&&(ue.length<ue.highWaterMark||ue.length===0)}function U(k,I,J,ne){I.flowing&&I.length===0&&!I.sync?(I.awaitDrain=0,k.emit("data",J)):(I.length+=I.objectMode?1:J.length,ne?I.buffer.unshift(J):I.buffer.push(J),I.needReadable&&z(k)),q(k,I)}function H(k,I){var J;return!a(I)&&typeof I!="string"&&I!==void 0&&!k.objectMode&&(J=new p("chunk",["string","Buffer","Uint8Array"],I)),J}R.prototype.isPaused=function(){return this._readableState.flowing===!1},R.prototype.setEncoding=function(k){g||(g=Wu().StringDecoder);var I=new g(k);this._readableState.decoder=I,this._readableState.encoding=this._readableState.decoder.encoding;for(var J=this._readableState.buffer.head,ne="";J!==null;)ne+=I.write(J.data),J=J.next;return this._readableState.buffer.clear(),ne!==""&&this._readableState.buffer.push(ne),this._readableState.length=ne.length,this};var F=1073741824;function K(k){return k>=F?k=F:(k--,k|=k>>>1,k|=k>>>2,k|=k>>>4,k|=k>>>8,k|=k>>>16,k++),k}function ee(k,I){return k<=0||I.length===0&&I.ended?0:I.objectMode?1:k!==k?I.flowing&&I.length?I.buffer.head.data.length:I.length:(k>I.highWaterMark&&(I.highWaterMark=K(k)),k<=I.length?k:I.ended?I.length:(I.needReadable=!0,0))}R.prototype.read=function(k){c("read",k),k=parseInt(k,10);var I=this._readableState,J=k;if(k!==0&&(I.emittedReadable=!1),k===0&&I.needReadable&&((I.highWaterMark!==0?I.length>=I.highWaterMark:I.length>0)||I.ended))return c("read: emitReadable",I.length,I.ended),I.length===0&&I.ended?D(this):z(this),null;if(k=ee(k,I),k===0&&I.ended)return I.length===0&&D(this),null;var ne=I.needReadable;c("need readable",ne),(I.length===0||I.length-k<I.highWaterMark)&&(ne=!0,c("length less than watermark",ne)),I.ended||I.reading?(ne=!1,c("reading or ended",ne)):ne&&(c("do read"),I.reading=!0,I.sync=!0,I.length===0&&(I.needReadable=!0),this._read(I.highWaterMark),I.sync=!1,I.reading||(k=ee(J,I)));var Te;return k>0?Te=S(k,I):Te=null,Te===null?(I.needReadable=I.length<=I.highWaterMark,k=0):(I.length-=k,I.awaitDrain=0),I.length===0&&(I.ended||(I.needReadable=!0),J!==k&&I.ended&&D(this)),Te!==null&&this.emit("data",Te),Te};function L(k,I){if(c("onEofChunk"),!I.ended){if(I.decoder){var J=I.decoder.end();J&&J.length&&(I.buffer.push(J),I.length+=I.objectMode?1:J.length)}I.ended=!0,I.sync?z(k):(I.needReadable=!1,I.emittedReadable||(I.emittedReadable=!0,W(k)))}}function z(k){var I=k._readableState;c("emitReadable",I.needReadable,I.emittedReadable),I.needReadable=!1,I.emittedReadable||(c("emitReadable",I.flowing),I.emittedReadable=!0,process.nextTick(W,k))}function W(k){var I=k._readableState;c("emitReadable_",I.destroyed,I.length,I.ended),!I.destroyed&&(I.length||I.ended)&&(k.emit("readable"),I.emittedReadable=!1),I.needReadable=!I.flowing&&!I.ended&&I.length<=I.highWaterMark,C(k)}function q(k,I){I.readingMore||(I.readingMore=!0,process.nextTick(V,k,I))}function V(k,I){for(;!I.reading&&!I.ended&&(I.length<I.highWaterMark||I.flowing&&I.length===0);){var J=I.length;if(c("maybeReadMore read 0"),k.read(0),J===I.length)break}I.readingMore=!1}R.prototype._read=function(k){A(this,new w("_read()"))},R.prototype.pipe=function(k,I){var J=this,ne=this._readableState;switch(ne.pipesCount){case 0:ne.pipes=k;break;case 1:ne.pipes=[ne.pipes,k];break;default:ne.pipes.push(k);break}ne.pipesCount+=1,c("pipe count=%d opts=%j",ne.pipesCount,I);var Te=(!I||I.end!==!1)&&k!==process.stdout&&k!==process.stderr,ue=Te?Vt:bn;ne.endEmitted?process.nextTick(ue):J.once("end",ue),k.on("unpipe",ye);function ye(O,v){c("onunpipe"),O===J&&v&&v.hasUnpiped===!1&&(v.hasUnpiped=!0,Pr())}function Vt(){c("onend"),k.end()}var Or=Y(J);k.on("drain",Or);var xr=!1;function Pr(){c("cleanup"),k.removeListener("close",os),k.removeListener("finish",Wt),k.removeListener("drain",Or),k.removeListener("error",wn),k.removeListener("unpipe",ye),J.removeListener("end",Vt),J.removeListener("end",bn),J.removeListener("data",Lt),xr=!0,ne.awaitDrain&&(!k._writableState||k._writableState.needDrain)&&Or()}J.on("data",Lt);function Lt(O){c("ondata");var v=k.write(O);c("dest.write",v),v===!1&&((ne.pipesCount===1&&ne.pipes===k||ne.pipesCount>1&&re(ne.pipes,k)!==-1)&&!xr&&(c("false write response, pause",ne.awaitDrain),ne.awaitDrain++),J.pause())}function wn(O){c("onerror",O),bn(),k.removeListener("error",wn),t(k,"error")===0&&A(k,O)}x(k,"error",wn);function os(){k.removeListener("finish",Wt),bn()}k.once("close",os);function Wt(){c("onfinish"),k.removeListener("close",os),bn()}k.once("finish",Wt);function bn(){c("unpipe"),J.unpipe(k)}return k.emit("pipe",J),ne.flowing||(c("pipe resume"),J.resume()),k};function Y(k){return function(){var J=k._readableState;c("pipeOnDrain",J.awaitDrain),J.awaitDrain&&J.awaitDrain--,J.awaitDrain===0&&t(k,"data")&&(J.flowing=!0,C(k))}}R.prototype.unpipe=function(k){var I=this._readableState,J={hasUnpiped:!1};if(I.pipesCount===0)return this;if(I.pipesCount===1)return k&&k!==I.pipes?this:(k||(k=I.pipes),I.pipes=null,I.pipesCount=0,I.flowing=!1,k&&k.emit("unpipe",this,J),this);if(!k){var ne=I.pipes,Te=I.pipesCount;I.pipes=null,I.pipesCount=0,I.flowing=!1;for(var ue=0;ue<Te;ue++)ne[ue].emit("unpipe",this,{hasUnpiped:!1});return this}var ye=re(I.pipes,k);return ye===-1?this:(I.pipes.splice(ye,1),I.pipesCount-=1,I.pipesCount===1&&(I.pipes=I.pipes[0]),k.emit("unpipe",this,J),this)},R.prototype.on=function(k,I){var J=r.prototype.on.call(this,k,I),ne=this._readableState;return k==="data"?(ne.readableListening=this.listenerCount("readable")>0,ne.flowing!==!1&&this.resume()):k==="readable"&&!ne.endEmitted&&!ne.readableListening&&(ne.readableListening=ne.needReadable=!0,ne.flowing=!1,ne.emittedReadable=!1,c("on readable",ne.length,ne.reading),ne.length?z(this):ne.reading||process.nextTick(ae,this)),J},R.prototype.addListener=R.prototype.on,R.prototype.removeListener=function(k,I){var J=r.prototype.removeListener.call(this,k,I);return k==="readable"&&process.nextTick(Q,this),J},R.prototype.removeAllListeners=function(k){var I=r.prototype.removeAllListeners.apply(this,arguments);return(k==="readable"||k===void 0)&&process.nextTick(Q,this),I};function Q(k){var I=k._readableState;I.readableListening=k.listenerCount("readable")>0,I.resumeScheduled&&!I.paused?I.flowing=!0:k.listenerCount("data")>0&&k.resume()}function ae(k){c("readable nexttick read 0"),k.read(0)}R.prototype.resume=function(){var k=this._readableState;return k.flowing||(c("resume"),k.flowing=!k.readableListening,X(this,k)),k.paused=!1,this};function X(k,I){I.resumeScheduled||(I.resumeScheduled=!0,process.nextTick(se,k,I))}function se(k,I){c("resume",I.reading),I.reading||k.read(0),I.resumeScheduled=!1,k.emit("resume"),C(k),I.flowing&&!I.reading&&k.read(0)}R.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function C(k){var I=k._readableState;for(c("flow",I.flowing);I.flowing&&k.read()!==null;);}R.prototype.wrap=function(k){var I=this,J=this._readableState,ne=!1;k.on("end",function(){if(c("wrapped end"),J.decoder&&!J.ended){var ye=J.decoder.end();ye&&ye.length&&I.push(ye)}I.push(null)}),k.on("data",function(ye){if(c("wrapped data"),J.decoder&&(ye=J.decoder.write(ye)),!(J.objectMode&&ye==null)&&!(!J.objectMode&&(!ye||!ye.length))){var Vt=I.push(ye);Vt||(ne=!0,k.pause())}});for(var Te in k)this[Te]===void 0&&typeof k[Te]=="function"&&(this[Te]=(function(Vt){return function(){return k[Vt].apply(k,arguments)}})(Te));for(var ue=0;ue<P.length;ue++)k.on(P[ue],this.emit.bind(this,P[ue]));return this._read=function(ye){c("wrapped _read",ye),ne&&(ne=!1,k.resume())},this},typeof Symbol=="function"&&(R.prototype[Symbol.asyncIterator]=function(){return _===void 0&&(_=jT()),_(this)}),Object.defineProperty(R.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(R.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(R.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(I){this._readableState&&(this._readableState.flowing=I)}}),R._fromList=S,Object.defineProperty(R.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function S(k,I){if(I.length===0)return null;var J;return I.objectMode?J=I.buffer.shift():!k||k>=I.length?(I.decoder?J=I.buffer.join(""):I.buffer.length===1?J=I.buffer.first():J=I.buffer.concat(I.length),I.buffer.clear()):J=I.buffer.consume(k,I.decoder),J}function D(k){var I=k._readableState;c("endReadable",I.endEmitted),I.endEmitted||(I.ended=!0,process.nextTick(j,I,k))}function j(k,I){if(c("endReadableNT",k.endEmitted,k.length),!k.endEmitted&&k.length===0&&(k.endEmitted=!0,I.readable=!1,I.emit("end"),k.autoDestroy)){var J=I._writableState;(!J||J.autoDestroy&&J.finished)&&I.destroy()}}typeof Symbol=="function"&&(R.from=function(k,I){return b===void 0&&(b=DT()),b(R,k,I)});function re(k,I){for(var J=0,ne=k.length;J<ne;J++)if(k[J]===I)return J;return-1}return El}var Tl,zp;function Ui(){if(zp)return Tl;zp=1;var e=Object.keys||function(l){var u=[];for(var d in l)u.push(d);return u};Tl=a;var t=m_(),r=oc();Qs()(a,t);for(var n=e(r.prototype),i=0;i<n.length;i++){var s=n[i];a.prototype[s]||(a.prototype[s]=r.prototype[s])}function a(l){if(!(this instanceof a))return new a(l);t.call(this,l),r.call(this,l),this.allowHalfOpen=!0,l&&(l.readable===!1&&(this.readable=!1),l.writable===!1&&(this.writable=!1),l.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",o)))}Object.defineProperty(a.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(a.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(a.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function o(){this._writableState.ended||process.nextTick(c,this)}function c(l){l.end()}return Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(u){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=u,this._writableState.destroyed=u)}}),Tl}var Cl,qp;function oc(){if(qp)return Cl;qp=1,Cl=T;function e(C){var S=this;this.next=null,this.entry=null,this.finish=function(){se(S,C)}}var t;T.WritableState=P;var r={deprecate:RT()},n=d_(),i=ac().Buffer,s=(typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function a(C){return i.from(C)}function o(C){return i.isBuffer(C)||C instanceof s}var c=h_(),l=p_(),u=l.getHighWaterMark,d=es().codes,f=d.ERR_INVALID_ARG_TYPE,h=d.ERR_METHOD_NOT_IMPLEMENTED,p=d.ERR_MULTIPLE_CALLBACK,m=d.ERR_STREAM_CANNOT_PIPE,w=d.ERR_STREAM_DESTROYED,y=d.ERR_STREAM_NULL_VALUES,g=d.ERR_STREAM_WRITE_AFTER_END,_=d.ERR_UNKNOWN_ENCODING,b=c.errorOrDestroy;Qs()(T,n);function A(){}function P(C,S,D){t=t||Ui(),C=C||{},typeof D!="boolean"&&(D=S instanceof t),this.objectMode=!!C.objectMode,D&&(this.objectMode=this.objectMode||!!C.writableObjectMode),this.highWaterMark=u(this,C,"writableHighWaterMark",D),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var j=C.decodeStrings===!1;this.decodeStrings=!j,this.defaultEncoding=C.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(re){L(S,re)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=C.emitClose!==!1,this.autoDestroy=!!C.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}P.prototype.getBuffer=function(){for(var S=this.bufferedRequest,D=[];S;)D.push(S),S=S.next;return D},(function(){try{Object.defineProperty(P.prototype,"buffer",{get:r.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var x;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(x=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(S){return x.call(this,S)?!0:this!==T?!1:S&&S._writableState instanceof P}})):x=function(S){return S instanceof this};function T(C){t=t||Ui();var S=this instanceof t;if(!S&&!x.call(T,this))return new T(C);this._writableState=new P(C,this,S),this.writable=!0,C&&(typeof C.write=="function"&&(this._write=C.write),typeof C.writev=="function"&&(this._writev=C.writev),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.final=="function"&&(this._final=C.final)),n.call(this)}T.prototype.pipe=function(){b(this,new m)};function R(C,S){var D=new g;b(C,D),process.nextTick(S,D)}function M(C,S,D,j){var re;return D===null?re=new y:typeof D!="string"&&!S.objectMode&&(re=new f("chunk",["string","Buffer"],D)),re?(b(C,re),process.nextTick(j,re),!1):!0}T.prototype.write=function(C,S,D){var j=this._writableState,re=!1,k=!j.objectMode&&o(C);return k&&!i.isBuffer(C)&&(C=a(C)),typeof S=="function"&&(D=S,S=null),k?S="buffer":S||(S=j.defaultEncoding),typeof D!="function"&&(D=A),j.ending?R(this,D):(k||M(this,j,C,D))&&(j.pendingcb++,re=H(this,j,k,C,S,D)),re},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var C=this._writableState;C.corked&&(C.corked--,!C.writing&&!C.corked&&!C.bufferProcessing&&C.bufferedRequest&&q(this,C))},T.prototype.setDefaultEncoding=function(S){if(typeof S=="string"&&(S=S.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((S+"").toLowerCase())>-1))throw new _(S);return this._writableState.defaultEncoding=S,this},Object.defineProperty(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function U(C,S,D){return!C.objectMode&&C.decodeStrings!==!1&&typeof S=="string"&&(S=i.from(S,D)),S}Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function H(C,S,D,j,re,k){if(!D){var I=U(S,j,re);j!==I&&(D=!0,re="buffer",j=I)}var J=S.objectMode?1:j.length;S.length+=J;var ne=S.length<S.highWaterMark;if(ne||(S.needDrain=!0),S.writing||S.corked){var Te=S.lastBufferedRequest;S.lastBufferedRequest={chunk:j,encoding:re,isBuf:D,callback:k,next:null},Te?Te.next=S.lastBufferedRequest:S.bufferedRequest=S.lastBufferedRequest,S.bufferedRequestCount+=1}else F(C,S,!1,J,j,re,k);return ne}function F(C,S,D,j,re,k,I){S.writelen=j,S.writecb=I,S.writing=!0,S.sync=!0,S.destroyed?S.onwrite(new w("write")):D?C._writev(re,S.onwrite):C._write(re,k,S.onwrite),S.sync=!1}function K(C,S,D,j,re){--S.pendingcb,D?(process.nextTick(re,j),process.nextTick(ae,C,S),C._writableState.errorEmitted=!0,b(C,j)):(re(j),C._writableState.errorEmitted=!0,b(C,j),ae(C,S))}function ee(C){C.writing=!1,C.writecb=null,C.length-=C.writelen,C.writelen=0}function L(C,S){var D=C._writableState,j=D.sync,re=D.writecb;if(typeof re!="function")throw new p;if(ee(D),S)K(C,D,j,S,re);else{var k=V(D)||C.destroyed;!k&&!D.corked&&!D.bufferProcessing&&D.bufferedRequest&&q(C,D),j?process.nextTick(z,C,D,k,re):z(C,D,k,re)}}function z(C,S,D,j){D||W(C,S),S.pendingcb--,j(),ae(C,S)}function W(C,S){S.length===0&&S.needDrain&&(S.needDrain=!1,C.emit("drain"))}function q(C,S){S.bufferProcessing=!0;var D=S.bufferedRequest;if(C._writev&&D&&D.next){var j=S.bufferedRequestCount,re=new Array(j),k=S.corkedRequestsFree;k.entry=D;for(var I=0,J=!0;D;)re[I]=D,D.isBuf||(J=!1),D=D.next,I+=1;re.allBuffers=J,F(C,S,!0,S.length,re,"",k.finish),S.pendingcb++,S.lastBufferedRequest=null,k.next?(S.corkedRequestsFree=k.next,k.next=null):S.corkedRequestsFree=new e(S),S.bufferedRequestCount=0}else{for(;D;){var ne=D.chunk,Te=D.encoding,ue=D.callback,ye=S.objectMode?1:ne.length;if(F(C,S,!1,ye,ne,Te,ue),D=D.next,S.bufferedRequestCount--,S.writing)break}D===null&&(S.lastBufferedRequest=null)}S.bufferedRequest=D,S.bufferProcessing=!1}T.prototype._write=function(C,S,D){D(new h("_write()"))},T.prototype._writev=null,T.prototype.end=function(C,S,D){var j=this._writableState;return typeof C=="function"?(D=C,C=null,S=null):typeof S=="function"&&(D=S,S=null),C!=null&&this.write(C,S),j.corked&&(j.corked=1,this.uncork()),j.ending||X(this,j,D),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function V(C){return C.ending&&C.length===0&&C.bufferedRequest===null&&!C.finished&&!C.writing}function Y(C,S){C._final(function(D){S.pendingcb--,D&&b(C,D),S.prefinished=!0,C.emit("prefinish"),ae(C,S)})}function Q(C,S){!S.prefinished&&!S.finalCalled&&(typeof C._final=="function"&&!S.destroyed?(S.pendingcb++,S.finalCalled=!0,process.nextTick(Y,C,S)):(S.prefinished=!0,C.emit("prefinish")))}function ae(C,S){var D=V(S);if(D&&(Q(C,S),S.pendingcb===0&&(S.finished=!0,C.emit("finish"),S.autoDestroy))){var j=C._readableState;(!j||j.autoDestroy&&j.endEmitted)&&C.destroy()}return D}function X(C,S,D){S.ending=!0,ae(C,S),D&&(S.finished?process.nextTick(D):C.once("finish",D)),S.ended=!0,C.writable=!1}function se(C,S,D){var j=C.entry;for(C.entry=null;j;){var re=j.callback;S.pendingcb--,re(D),j=j.next}S.corkedRequestsFree.next=C}return Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(S){this._writableState&&(this._writableState.destroyed=S)}}),T.prototype.destroy=c.destroy,T.prototype._undestroy=c.undestroy,T.prototype._destroy=function(C,S){S(C)},Cl}var Hp;function g_(){if(Hp)return fl.exports;Hp=1;var e=Ar,t=oc(),r=Ge(),n=r.LEVEL,i=fl.exports=function(){var a=this,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.call(this,{objectMode:!0,highWaterMark:o.highWaterMark}),this.format=o.format,this.level=o.level,this.handleExceptions=o.handleExceptions,this.handleRejections=o.handleRejections,this.silent=o.silent,o.log&&(this.log=o.log),o.logv&&(this.logv=o.logv),o.close&&(this.close=o.close),this.once("pipe",function(c){a.levels=c.levels,a.parent=c}),this.once("unpipe",function(c){c===a.parent&&(a.parent=null,a.close&&a.close())})};return e.inherits(i,t),i.prototype._write=function(a,o,c){if(this.silent||a.exception===!0&&!this.handleExceptions)return c(null);var l=this.level||this.parent&&this.parent.level;if(!l||this.levels[l]>=this.levels[a[n]]){if(a&&!this.format)return this.log(a,c);var u=void 0,d=void 0;try{d=this.format.transform(Object.assign({},a),this.format.options)}catch(f){u=f}if(u||!d){if(c(),u)throw u;return}return this.log(d,c)}return this._writableState.sync=!1,c(null)},i.prototype._writev=function(a,o){if(this.logv){var c=a.filter(this._accept,this);return c.length?this.logv(c,o):o(null)}for(var l=0;l<a.length;l++)if(this._accept(a[l])){if(a[l].chunk&&!this.format){this.log(a[l].chunk,a[l].callback);continue}var u=void 0,d=void 0;try{d=this.format.transform(Object.assign({},a[l].chunk),this.format.options)}catch(f){u=f}if(u||!d){if(a[l].callback(),u)throw o(null),u}else this.log(d,a[l].callback)}return o(null)},i.prototype._accept=function(a){var o=a.chunk;if(this.silent)return!1;var c=this.level||this.parent&&this.parent.level;return!!((o.exception===!0||!c||this.levels[c]>=this.levels[o[n]])&&(this.handleExceptions||o.exception!==!0))},i.prototype._nop=function(){},fl.exports}var Al={exports:{}},Gp;function FT(){if(Gp)return Al.exports;Gp=1;var e=Ar,t=Ge(),r=t.LEVEL,n=g_(),i=Al.exports=function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(n.call(this,a),!a.transport||typeof a.transport.log!="function")throw new Error("Invalid transport, must be an object with a log method.");this.transport=a.transport,this.level=this.level||a.transport.level,this.handleExceptions=this.handleExceptions||a.transport.handleExceptions,this._deprecated();function o(c){this.emit("error",c,this.transport)}this.transport.__winstonError||(this.transport.__winstonError=o.bind(this),this.transport.on("error",this.transport.__winstonError))};return e.inherits(i,n),i.prototype._write=function(a,o,c){if(this.silent||a.exception===!0&&!this.handleExceptions)return c(null);(!this.level||this.levels[this.level]>=this.levels[a[r]])&&this.transport.log(a[r],a.message,a,this._nop),c(null)},i.prototype._writev=function(a,o){for(var c=0;c<a.length;c++)this._accept(a[c])&&(this.transport.log(a[c].chunk[r],a[c].chunk.message,a[c].chunk,this._nop),a[c].callback());return o(null)},i.prototype._deprecated=function(){console.error([this.transport.name+" is a legacy winston transport. Consider upgrading: ","- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md"].join(`
34
- `))},i.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)},Al.exports}var Vp;function ea(){return Vp||(Vp=1,Ta.exports=g_(),Ta.exports.LegacyTransportStream=FT()),Ta.exports}var Ol,Wp;function UT(){if(Wp)return Ol;Wp=1;function e(g){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},e(g)}function t(g,_){if(!(g instanceof _))throw new TypeError("Cannot call a class as a function")}function r(g,_){for(var b=0;b<_.length;b++){var A=_[b];A.enumerable=A.enumerable||!1,A.configurable=!0,"value"in A&&(A.writable=!0),Object.defineProperty(g,i(A.key),A)}}function n(g,_,b){return _&&r(g.prototype,_),Object.defineProperty(g,"prototype",{writable:!1}),g}function i(g){var _=s(g,"string");return e(_)=="symbol"?_:_+""}function s(g,_){if(e(g)!="object"||!g)return g;var b=g[Symbol.toPrimitive];if(b!==void 0){var A=b.call(g,_);if(e(A)!="object")return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(g)}function a(g,_,b){return _=u(_),o(g,l()?Reflect.construct(_,b||[],u(g).constructor):_.apply(g,b))}function o(g,_){if(_&&(e(_)=="object"||typeof _=="function"))return _;if(_!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return c(g)}function c(g){if(g===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return g}function l(){try{var g=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(l=function(){return!!g})()}function u(g){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(_){return _.__proto__||Object.getPrototypeOf(_)},u(g)}function d(g,_){if(typeof _!="function"&&_!==null)throw new TypeError("Super expression must either be null or a function");g.prototype=Object.create(_&&_.prototype,{constructor:{value:g,writable:!0,configurable:!0}}),Object.defineProperty(g,"prototype",{writable:!1}),_&&f(g,_)}function f(g,_){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(b,A){return b.__proto__=A,b},f(g,_)}var h=br,p=Ge(),m=p.LEVEL,w=p.MESSAGE,y=ea();return Ol=(function(g){function _(){var b,A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return t(this,_),b=a(this,_,[A]),b.name=A.name||"console",b.stderrLevels=b._stringArrayToSet(A.stderrLevels),b.consoleWarnLevels=b._stringArrayToSet(A.consoleWarnLevels),b.eol=typeof A.eol=="string"?A.eol:h.EOL,b.forceConsole=A.forceConsole||!1,b._consoleLog=console.log.bind(console),b._consoleWarn=console.warn.bind(console),b._consoleError=console.error.bind(console),b.setMaxListeners(30),b}return d(_,g),n(_,[{key:"log",value:function(A,P){var x=this;if(setImmediate(function(){return x.emit("logged",A)}),this.stderrLevels[A[m]]){console._stderr&&!this.forceConsole?console._stderr.write("".concat(A[w]).concat(this.eol)):this._consoleError(A[w]),P&&P();return}else if(this.consoleWarnLevels[A[m]]){console._stderr&&!this.forceConsole?console._stderr.write("".concat(A[w]).concat(this.eol)):this._consoleWarn(A[w]),P&&P();return}console._stdout&&!this.forceConsole?console._stdout.write("".concat(A[w]).concat(this.eol)):this._consoleLog(A[w]),P&&P()}},{key:"_stringArrayToSet",value:function(A,P){if(!A)return{};if(P=P||"Cannot make set from type other than Array of string elements",!Array.isArray(A))throw new Error(P);return A.reduce(function(x,T){if(typeof T!="string")throw new Error(P);return x[T]=!0,x},{})}}])})(y),Ol}function Ln(...e){return e.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}function y_(...e){return Ln(...e)}function Mo(e){const t=e.split("/");return t.pop(),t.join("/")||"/"}function cd(e,t){const r=e.split("/");let n=r[r.length-1]||"";return t&&n.endsWith(t)&&(n=n.slice(0,-t.length)),n}function __(e){const t=cd(e),r=t.lastIndexOf(".");return r>0?t.slice(r):""}function v_(e){return e.replace(/\/+/g,"/")}function ld(e){return e.startsWith("/")}const w_="/",b_=":",BT={join:Ln,resolve:y_,dirname:Mo,basename:cd,extname:__,normalize:v_,isAbsolute:ld,sep:w_,delimiter:b_},S_=Object.freeze(Object.defineProperty({__proto__:null,basename:cd,default:BT,delimiter:b_,dirname:Mo,extname:__,isAbsolute:ld,join:Ln,normalize:v_,resolve:y_,sep:w_},Symbol.toStringTag,{value:"Module"})),zT=sc(S_);var Pa={exports:{}},ka={exports:{}},Ia={exports:{}},Jp;function ud(){return Jp||(Jp=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;function r(n){return n&&typeof n.length=="number"&&n.length>=0&&n.length%1===0}e.exports=t.default})(Ia,Ia.exports)),Ia.exports}var pr={},Ma={exports:{}},Ra={exports:{}},Kp;function qT(){return Kp||(Kp=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(r){return function(...n){var i=n.pop();return r.call(this,n,i)}},e.exports=t.default})(Ra,Ra.exports)),Ra.exports}var kr={},Zp;function HT(){if(Zp)return kr;Zp=1,Object.defineProperty(kr,"__esModule",{value:!0}),kr.fallback=n,kr.wrap=i;var e=kr.hasQueueMicrotask=typeof queueMicrotask=="function"&&queueMicrotask,t=kr.hasSetImmediate=typeof setImmediate=="function"&&setImmediate,r=kr.hasNextTick=typeof process=="object"&&typeof process.nextTick=="function";function n(a){setTimeout(a,0)}function i(a){return(o,...c)=>a(()=>o(...c))}var s;return e?s=queueMicrotask:t?s=setImmediate:r?s=process.nextTick:s=n,kr.default=i(s),kr}var Yp;function GT(){return Yp||(Yp=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var r=qT(),n=o(r),i=HT(),s=o(i),a=ts();function o(d){return d&&d.__esModule?d:{default:d}}function c(d){return(0,a.isAsync)(d)?function(...f){const h=f.pop(),p=d.apply(this,f);return l(p,h)}:(0,n.default)(function(f,h){var p;try{p=d.apply(this,f)}catch(m){return h(m)}if(p&&typeof p.then=="function")return l(p,h);h(null,p)})}function l(d,f){return d.then(h=>{u(f,null,h)},h=>{u(f,h&&(h instanceof Error||h.message)?h:new Error(h))})}function u(d,f,h){try{d(f,h)}catch(p){(0,s.default)(m=>{throw m},p)}}e.exports=t.default})(Ma,Ma.exports)),Ma.exports}var Xp;function ts(){if(Xp)return pr;Xp=1,Object.defineProperty(pr,"__esModule",{value:!0}),pr.isAsyncIterable=pr.isAsyncGenerator=pr.isAsync=void 0;var e=GT(),t=r(e);function r(o){return o&&o.__esModule?o:{default:o}}function n(o){return o[Symbol.toStringTag]==="AsyncFunction"}function i(o){return o[Symbol.toStringTag]==="AsyncGenerator"}function s(o){return typeof o[Symbol.asyncIterator]=="function"}function a(o){if(typeof o!="function")throw new Error("expected a function");return n(o)?(0,t.default)(o):o}return pr.default=a,pr.isAsync=n,pr.isAsyncGenerator=i,pr.isAsyncIterable=s,pr}var Na={exports:{}},Qp;function ta(){return Qp||(Qp=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;function r(n,i){if(i||(i=n.length),!i)throw new Error("arity is undefined");function s(...a){return typeof a[i-1]=="function"?n.apply(this,a):new Promise((o,c)=>{a[i-1]=(l,...u)=>{if(l)return c(l);o(u.length>1?u:u[0])},n.apply(this,a)})}return s}e.exports=t.default})(Na,Na.exports)),Na.exports}var em;function VT(){return em||(em=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=ud(),n=c(r),i=ts(),s=c(i),a=ta(),o=c(a);function c(l){return l&&l.__esModule?l:{default:l}}t.default=(0,o.default)((l,u,d)=>{var f=(0,n.default)(u)?[]:{};l(u,(h,p,m)=>{(0,s.default)(h)((w,...y)=>{y.length<2&&([y]=y),f[p]=y,m(w)})},h=>d(h,f))},3),e.exports=t.default})(ka,ka.exports)),ka.exports}var $a={exports:{}},La={exports:{}},ja={exports:{}},Da={exports:{}},tm;function E_(){return tm||(tm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;function r(n){function i(...s){if(n!==null){var a=n;n=null,a.apply(this,s)}}return Object.assign(i,n),i}e.exports=t.default})(Da,Da.exports)),Da.exports}var Fa={exports:{}},Ua={exports:{}},rm;function WT(){return rm||(rm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(r){return r[Symbol.iterator]&&r[Symbol.iterator]()},e.exports=t.default})(Ua,Ua.exports)),Ua.exports}var nm;function JT(){return nm||(nm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=u;var r=ud(),n=a(r),i=WT(),s=a(i);function a(d){return d&&d.__esModule?d:{default:d}}function o(d){var f=-1,h=d.length;return function(){return++f<h?{value:d[f],key:f}:null}}function c(d){var f=-1;return function(){var p=d.next();return p.done?null:(f++,{value:p.value,key:f})}}function l(d){var f=d?Object.keys(d):[],h=-1,p=f.length;return function m(){var w=f[++h];return w==="__proto__"?m():h<p?{value:d[w],key:w}:null}}function u(d){if((0,n.default)(d))return o(d);var f=(0,s.default)(d);return f?c(f):l(d)}e.exports=t.default})(Fa,Fa.exports)),Fa.exports}var Ba={exports:{}},im;function T_(){return im||(im=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;function r(n){return function(...i){if(n===null)throw new Error("Callback was already called.");var s=n;n=null,s.apply(this,i)}}e.exports=t.default})(Ba,Ba.exports)),Ba.exports}var za={exports:{}},qa={exports:{}},sm;function fd(){return sm||(sm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r={};t.default=r,e.exports=t.default})(qa,qa.exports)),qa.exports}var am;function KT(){return am||(am=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=s;var r=fd(),n=i(r);function i(a){return a&&a.__esModule?a:{default:a}}function s(a,o,c,l){let u=!1,d=!1,f=!1,h=0,p=0;function m(){h>=o||f||u||(f=!0,a.next().then(({value:g,done:_})=>{if(!(d||u)){if(f=!1,_){u=!0,h<=0&&l(null);return}h++,c(g,p,w),p++,m()}}).catch(y))}function w(g,_){if(h-=1,!d){if(g)return y(g);if(g===!1){u=!0,d=!0;return}if(_===n.default||u&&h<=0)return u=!0,l(null);m()}}function y(g){d||(f=!1,u=!0,l(g))}m()}e.exports=t.default})(za,za.exports)),za.exports}var om;function ZT(){return om||(om=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=E_(),n=h(r),i=JT(),s=h(i),a=T_(),o=h(a),c=ts(),l=KT(),u=h(l),d=fd(),f=h(d);function h(p){return p&&p.__esModule?p:{default:p}}t.default=p=>(m,w,y)=>{if(y=(0,n.default)(y),p<=0)throw new RangeError("concurrency limit cannot be less than 1");if(!m)return y(null);if((0,c.isAsyncGenerator)(m))return(0,u.default)(m,p,w,y);if((0,c.isAsyncIterable)(m))return(0,u.default)(m[Symbol.asyncIterator](),p,w,y);var g=(0,s.default)(m),_=!1,b=!1,A=0,P=!1;function x(R,M){if(!b)if(A-=1,R)_=!0,y(R);else if(R===!1)_=!0,b=!0;else{if(M===f.default||_&&A<=0)return _=!0,y(null);P||T()}}function T(){for(P=!0;A<p&&!_;){var R=g();if(R===null){_=!0,A<=0&&y(null);return}A+=1,w(R.value,R.key,(0,o.default)(x))}P=!1}T()},e.exports=t.default})(ja,ja.exports)),ja.exports}var cm;function C_(){return cm||(cm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=ZT(),n=c(r),i=ts(),s=c(i),a=ta(),o=c(a);function c(u){return u&&u.__esModule?u:{default:u}}function l(u,d,f,h){return(0,n.default)(d)(u,(0,s.default)(f),h)}t.default=(0,o.default)(l,4),e.exports=t.default})(La,La.exports)),La.exports}var lm;function YT(){return lm||(lm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=C_(),n=a(r),i=ta(),s=a(i);function a(c){return c&&c.__esModule?c:{default:c}}function o(c,l,u){return(0,n.default)(c,1,l,u)}t.default=(0,s.default)(o,3),e.exports=t.default})($a,$a.exports)),$a.exports}var um;function XT(){return um||(um=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var r=VT(),n=a(r),i=YT(),s=a(i);function a(c){return c&&c.__esModule?c:{default:c}}function o(c,l){return(0,n.default)(s.default,c,l)}e.exports=t.default})(Pa,Pa.exports)),Pa.exports}var Ha={exports:{}},xl,fm;function A_(){if(fm)return xl;fm=1,xl=o;var e=es().codes,t=e.ERR_METHOD_NOT_IMPLEMENTED,r=e.ERR_MULTIPLE_CALLBACK,n=e.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=e.ERR_TRANSFORM_WITH_LENGTH_0,s=Ui();Qs()(o,s);function a(u,d){var f=this._transformState;f.transforming=!1;var h=f.writecb;if(h===null)return this.emit("error",new r);f.writechunk=null,f.writecb=null,d!=null&&this.push(d),h(u);var p=this._readableState;p.reading=!1,(p.needReadable||p.length<p.highWaterMark)&&this._read(p.highWaterMark)}function o(u){if(!(this instanceof o))return new o(u);s.call(this,u),this._transformState={afterTransform:a.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,u&&(typeof u.transform=="function"&&(this._transform=u.transform),typeof u.flush=="function"&&(this._flush=u.flush)),this.on("prefinish",c)}function c(){var u=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(d,f){l(u,d,f)}):l(this,null,null)}o.prototype.push=function(u,d){return this._transformState.needTransform=!1,s.prototype.push.call(this,u,d)},o.prototype._transform=function(u,d,f){f(new t("_transform()"))},o.prototype._write=function(u,d,f){var h=this._transformState;if(h.writecb=f,h.writechunk=u,h.writeencoding=d,!h.transforming){var p=this._readableState;(h.needTransform||p.needReadable||p.length<p.highWaterMark)&&this._read(p.highWaterMark)}},o.prototype._read=function(u){var d=this._transformState;d.writechunk!==null&&!d.transforming?(d.transforming=!0,this._transform(d.writechunk,d.writeencoding,d.afterTransform)):d.needTransform=!0},o.prototype._destroy=function(u,d){s.prototype._destroy.call(this,u,function(f){d(f)})};function l(u,d,f){if(d)return u.emit("error",d);if(f!=null&&u.push(f),u._writableState.length)throw new i;if(u._transformState.transforming)throw new n;return u.push(null)}return xl}var Pl,dm;function QT(){if(dm)return Pl;dm=1,Pl=t;var e=A_();Qs()(t,e);function t(r){if(!(this instanceof t))return new t(r);e.call(this,r)}return t.prototype._transform=function(r,n,i){i(null,r)},Pl}var kl,hm;function eC(){if(hm)return kl;hm=1;var e;function t(f){var h=!1;return function(){h||(h=!0,f.apply(void 0,arguments))}}var r=es().codes,n=r.ERR_MISSING_ARGS,i=r.ERR_STREAM_DESTROYED;function s(f){if(f)throw f}function a(f){return f.setHeader&&typeof f.abort=="function"}function o(f,h,p,m){m=t(m);var w=!1;f.on("close",function(){w=!0}),e===void 0&&(e=od()),e(f,{readable:h,writable:p},function(g){if(g)return m(g);w=!0,m()});var y=!1;return function(g){if(!w&&!y){if(y=!0,a(f))return f.abort();if(typeof f.destroy=="function")return f.destroy();m(g||new i("pipe"))}}}function c(f){f()}function l(f,h){return f.pipe(h)}function u(f){return!f.length||typeof f[f.length-1]!="function"?s:f.pop()}function d(){for(var f=arguments.length,h=new Array(f),p=0;p<f;p++)h[p]=arguments[p];var m=u(h);if(Array.isArray(h[0])&&(h=h[0]),h.length<2)throw new n("streams");var w,y=h.map(function(g,_){var b=_<h.length-1,A=_>0;return o(g,b,A,function(P){w||(w=P),P&&y.forEach(c),!b&&(y.forEach(c),m(w))})});return h.reduce(l)}return kl=d,kl}var pm;function rs(){return pm||(pm=1,(function(e,t){t=e.exports=m_(),t.Stream=t,t.Readable=t,t.Writable=oc(),t.Duplex=Ui(),t.Transform=A_(),t.PassThrough=QT(),t.finished=od(),t.pipeline=eC()})(Ha,Ha.exports)),Ha.exports}var Il={exports:{}},Ml,mm;function tC(){if(mm)return Ml;mm=1;var e=[],t=[],r=function(){};function n(f){return~e.indexOf(f)?!1:(e.push(f),!0)}function i(f){r=f}function s(f){for(var h=[],p=0;p<e.length;p++){if(e[p].async){h.push(e[p]);continue}if(e[p](f))return!0}return h.length?new Promise(function(w){Promise.all(h.map(function(g){return g(f)})).then(function(g){w(g.some(Boolean))})}):!1}function a(f){return~t.indexOf(f)?!1:(t.push(f),!0)}function o(){r.apply(r,arguments)}function c(f){for(var h=0;h<t.length;h++)f=t[h].apply(t[h],arguments);return f}function l(f,h){var p=Object.prototype.hasOwnProperty;for(var m in h)p.call(h,m)&&(f[m]=h[m]);return f}function u(f){return f.enabled=!1,f.modify=a,f.set=i,f.use=n,l(function(){return!1},f)}function d(f){function h(){var p=Array.prototype.slice.call(arguments,0);return o.call(o,f,c(p,f)),!0}return f.enabled=!0,f.modify=a,f.set=i,f.use=n,l(h,f)}return Ml=function(h){return h.introduce=l,h.enabled=s,h.process=c,h.modify=a,h.write=o,h.nope=u,h.yep=d,h.set=i,h.use=n,h},Ml}var Rl,gm;function rC(){if(gm)return Rl;gm=1;var e=tC(),t=e(function r(n,i){return i=i||{},i.namespace=n,i.prod=!0,i.dev=!1,i.force||r.force?r.yep(i):r.nope(i)});return Rl=t,Rl}var ym;function cc(){return ym||(ym=1,Il.exports=rC()),Il.exports}var Nl,_m;function nC(){if(_m)return Nl;_m=1;var e=br,t=Wu(),r=t.StringDecoder,n=rs(),i=n.Stream;function s(){}return Nl=function(a,o){var c=Buffer.alloc(65536),l=new r("utf8"),u=new i,d="",f=0,h=0;return a.start===-1&&delete a.start,u.readable=!0,u.destroy=function(){u.destroyed=!0,u.emit("end"),u.emit("close")},e.open(a.file,"a+","0644",function(p,m){if(p){o?o(p):u.emit("error",p),u.destroy();return}(function w(){if(u.destroyed){e.close(m,s);return}return e.read(m,c,0,c.length,f,function(y,g){if(y){o?o(y):u.emit("error",y),u.destroy();return}if(!g)return d&&((a.start==null||h>a.start)&&(o?o(null,d):u.emit("line",d)),h++,d=""),setTimeout(w,1e3);var _=l.write(c.slice(0,g));o||u.emit("data",_),_=(d+_).split(/\n+/);for(var b=_.length-1,A=0;A<b;A++)(a.start==null||h>a.start)&&(o?o(null,_[A]):u.emit("line",_[A])),h++;return d=_[b],f+=g,w()})})()}),o?u.destroy:u},Nl}var $l,vm;function iC(){if(vm)return $l;vm=1;function e(M){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(U){return typeof U}:function(U){return U&&typeof Symbol=="function"&&U.constructor===Symbol&&U!==Symbol.prototype?"symbol":typeof U},e(M)}function t(M,U){if(!(M instanceof U))throw new TypeError("Cannot call a class as a function")}function r(M,U){for(var H=0;H<U.length;H++){var F=U[H];F.enumerable=F.enumerable||!1,F.configurable=!0,"value"in F&&(F.writable=!0),Object.defineProperty(M,i(F.key),F)}}function n(M,U,H){return U&&r(M.prototype,U),Object.defineProperty(M,"prototype",{writable:!1}),M}function i(M){var U=s(M,"string");return e(U)=="symbol"?U:U+""}function s(M,U){if(e(M)!="object"||!M)return M;var H=M[Symbol.toPrimitive];if(H!==void 0){var F=H.call(M,U);if(e(F)!="object")return F;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(M)}function a(M,U,H){return U=u(U),o(M,l()?Reflect.construct(U,H||[],u(M).constructor):U.apply(M,H))}function o(M,U){if(U&&(e(U)=="object"||typeof U=="function"))return U;if(U!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return c(M)}function c(M){if(M===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return M}function l(){try{var M=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(l=function(){return!!M})()}function u(M){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(U){return U.__proto__||Object.getPrototypeOf(U)},u(M)}function d(M,U){if(typeof U!="function"&&U!==null)throw new TypeError("Super expression must either be null or a function");M.prototype=Object.create(U&&U.prototype,{constructor:{value:M,writable:!0,configurable:!0}}),Object.defineProperty(M,"prototype",{writable:!1}),U&&f(M,U)}function f(M,U){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(H,F){return H.__proto__=F,H},f(M,U)}var h=br,p=zT,m=XT(),w=br,y=Ge(),g=y.MESSAGE,_=rs(),b=_.Stream,A=_.PassThrough,P=ea(),x=cc()("winston:file"),T=br,R=nC();return $l=(function(M){function U(){var H,F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t(this,U),H=a(this,U,[F]),H.name=F.name||"file";function K(ee){for(var L=arguments.length,z=new Array(L>1?L-1:0),W=1;W<L;W++)z[W-1]=arguments[W];z.slice(1).forEach(function(q){if(F[q])throw new Error("Cannot set ".concat(q," and ").concat(ee," together"))})}if(H._stream=new A,H._stream.setMaxListeners(30),H._onError=H._onError.bind(H),F.filename||F.dirname)K("filename or dirname","stream"),H._basename=H.filename=F.filename?p.basename(F.filename):"winston.log",H.dirname=F.dirname||p.dirname(F.filename),H.options=F.options||{flags:"a"};else if(F.stream)console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"),K("stream","filename","maxsize"),H._dest=H._stream.pipe(H._setupStream(F.stream)),H.dirname=p.dirname(H._dest.path);else throw new Error("Cannot log to file without filename or stream.");return H.maxsize=F.maxsize||null,H.rotationFormat=F.rotationFormat||!1,H.zippedArchive=F.zippedArchive||!1,H.maxFiles=F.maxFiles||null,H.eol=typeof F.eol=="string"?F.eol:T.EOL,H.tailable=F.tailable||!1,H.lazy=F.lazy||!1,H._size=0,H._pendingSize=0,H._created=0,H._drain=!1,H._opening=!1,H._ending=!1,H._fileExist=!1,H.dirname&&H._createLogDirIfNotExist(H.dirname),H.lazy||H.open(),H}return d(U,M),n(U,[{key:"finishIfEnding",value:function(){var F=this;this._ending&&(this._opening?this.once("open",function(){F._stream.once("finish",function(){return F.emit("finish")}),setImmediate(function(){return F._stream.end()})}):(this._stream.once("finish",function(){return F.emit("finish")}),setImmediate(function(){return F._stream.end()})))}},{key:"log",value:function(F){var K=this,ee=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){};if(this.silent)return ee(),!0;if(this._drain){this._stream.once("drain",function(){K._drain=!1,K.log(F,ee)});return}if(this._rotate){this._stream.once("rotate",function(){K._rotate=!1,K.log(F,ee)});return}if(this.lazy){if(!this._fileExist){this._opening||this.open(),this.once("open",function(){K._fileExist=!0,K.log(F,ee)});return}if(this._needsNewFile(this._pendingSize)){this._dest.once("close",function(){K._opening||K.open(),K.once("open",function(){K.log(F,ee)})});return}}var L="".concat(F[g]).concat(this.eol),z=Buffer.byteLength(L);function W(){var V=this;if(this._size+=z,this._pendingSize-=z,x("logged %s %s",this._size,L),this.emit("logged",F),!this._rotate&&!this._opening&&this._needsNewFile()){if(this.lazy){this._endStream(function(){V.emit("fileclosed")});return}this._rotate=!0,this._endStream(function(){return V._rotateFile()})}}this._pendingSize+=z,this._opening&&!this.rotatedWhileOpening&&this._needsNewFile(this._size+this._pendingSize)&&(this.rotatedWhileOpening=!0);var q=this._stream.write(L,W.bind(this));return q?ee():(this._drain=!0,this._stream.once("drain",function(){K._drain=!1,ee()})),x("written",q,this._drain),this.finishIfEnding(),q}},{key:"query",value:function(F,K){typeof F=="function"&&(K=F,F={}),F=ae(F);var ee=p.join(this.dirname,this.filename),L="",z=[],W=0,q=h.createReadStream(ee,{encoding:"utf8"});q.on("error",function(X){if(q.readable&&q.destroy(),!!K)return X.code!=="ENOENT"?K(X):K(null,z)}),q.on("data",function(X){X=(L+X).split(/\n+/);for(var se=X.length-1,C=0;C<se;C++)(!F.start||W>=F.start)&&V(X[C]),W++;L=X[se]}),q.on("close",function(){L&&V(L,!0),F.order==="desc"&&(z=z.reverse()),K&&K(null,z)});function V(X,se){try{var C=JSON.parse(X);Q(C)&&Y(C)}catch(S){se||q.emit("error",S)}}function Y(X){if(F.rows&&z.length>=F.rows&&F.order!=="desc"){q.readable&&q.destroy();return}F.fields&&(X=F.fields.reduce(function(se,C){return se[C]=X[C],se},{})),F.order==="desc"&&z.length>=F.rows&&z.shift(),z.push(X)}function Q(X){if(X&&e(X)==="object"){var se=new Date(X.timestamp);if(!(F.from&&se<F.from||F.until&&se>F.until||F.level&&F.level!==X.level))return!0}}function ae(X){return X=X||{},X.rows=X.rows||X.limit||10,X.start=X.start||0,X.until=X.until||new Date,e(X.until)!=="object"&&(X.until=new Date(X.until)),X.from=X.from||X.until-1440*60*1e3,e(X.from)!=="object"&&(X.from=new Date(X.from)),X.order=X.order||"desc",X}}},{key:"stream",value:function(){var F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},K=p.join(this.dirname,this.filename),ee=new b,L={file:K,start:F.start};return ee.destroy=R(L,function(z,W){if(z)return ee.emit("error",z);try{ee.emit("data",W),W=JSON.parse(W),ee.emit("log",W)}catch(q){ee.emit("error",q)}}),ee}},{key:"open",value:function(){var F=this;this.filename&&(this._opening||(this._opening=!0,this.stat(function(K,ee){if(K)return F.emit("error",K);x("stat done: %s { size: %s }",F.filename,ee),F._size=ee,F._dest=F._createStream(F._stream),F._opening=!1,F.once("open",function(){F._stream.emit("rotate")||(F._rotate=!1)})})))}},{key:"stat",value:function(F){var K=this,ee=this._getFile(),L=p.join(this.dirname,ee);h.stat(L,function(z,W){if(z&&z.code==="ENOENT")return x("ENOENT ok",L),K.filename=ee,F(null,0);if(z)return x("err ".concat(z.code," ").concat(L)),F(z);if(!W||K._needsNewFile(W.size))return K._incFile(function(){return K.stat(F)});K.filename=ee,F(null,W.size)})}},{key:"close",value:function(F){var K=this;this._stream&&this._stream.end(function(){F&&F(),K.emit("flush"),K.emit("closed")})}},{key:"_needsNewFile",value:function(F){return F=F||this._size,this.maxsize&&F>=this.maxsize}},{key:"_onError",value:function(F){this.emit("error",F)}},{key:"_setupStream",value:function(F){return F.on("error",this._onError),F}},{key:"_cleanupStream",value:function(F){return F.removeListener("error",this._onError),F.destroy(),F}},{key:"_rotateFile",value:function(){var F=this;this._incFile(function(){return F.open()})}},{key:"_endStream",value:function(){var F=this,K=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(){};this._dest?(this._stream.unpipe(this._dest),this._dest.end(function(){F._cleanupStream(F._dest),K()})):K()}},{key:"_createStream",value:function(F){var K=this,ee=p.join(this.dirname,this.filename);x("create stream start",ee,this.options);var L=h.createWriteStream(ee,this.options).on("error",function(z){return x(z)}).on("close",function(){return x("close",L.path,L.bytesWritten)}).on("open",function(){x("file open ok",ee),K.emit("open",ee),F.pipe(L),K.rotatedWhileOpening&&(K._stream=new A,K._stream.setMaxListeners(30),K._rotateFile(),K.rotatedWhileOpening=!1,K._cleanupStream(L),F.end())});return x("create stream ok",ee),L}},{key:"_incFile",value:function(F){x("_incFile",this.filename);var K=p.extname(this._basename),ee=p.basename(this._basename,K),L=[];this.zippedArchive&&L.push((function(z){var W=this._created>0&&!this.tailable?this._created:"";this._compressFile(p.join(this.dirname,"".concat(ee).concat(W).concat(K)),p.join(this.dirname,"".concat(ee).concat(W).concat(K,".gz")),z)}).bind(this)),L.push((function(z){this.tailable?this._checkMaxFilesTailable(K,ee,z):(this._created+=1,this._checkMaxFilesIncrementing(K,ee,z))}).bind(this)),m(L,F)}},{key:"_getFile",value:function(){var F=p.extname(this._basename),K=p.basename(this._basename,F),ee=this.rotationFormat?this.rotationFormat():this._created;return!this.tailable&&this._created?"".concat(K).concat(ee).concat(F):"".concat(K).concat(F)}},{key:"_checkMaxFilesIncrementing",value:function(F,K,ee){if(!this.maxFiles||this._created<this.maxFiles)return setImmediate(ee);var L=this._created-this.maxFiles,z=L!==0?L:"",W=this.zippedArchive?".gz":"",q="".concat(K).concat(z).concat(F).concat(W),V=p.join(this.dirname,q);h.unlink(V,ee)}},{key:"_checkMaxFilesTailable",value:function(F,K,ee){var L=this,z=[];if(this.maxFiles){for(var W=this.zippedArchive?".gz":"",q=this.maxFiles-1;q>1;q--)z.push((function(V,Y){var Q=this,ae="".concat(K).concat(V-1).concat(F).concat(W),X=p.join(this.dirname,ae);h.exists(X,function(se){if(!se)return Y(null);ae="".concat(K).concat(V).concat(F).concat(W),h.rename(X,p.join(Q.dirname,ae),Y)})}).bind(this,q));m(z,function(){h.rename(p.join(L.dirname,"".concat(K).concat(F).concat(W)),p.join(L.dirname,"".concat(K,"1").concat(F).concat(W)),ee)})}}},{key:"_compressFile",value:function(F,K,ee){h.access(F,h.F_OK,function(L){if(L)return ee();var z=w.createGzip(),W=h.createReadStream(F),q=h.createWriteStream(K);q.on("finish",function(){h.unlink(F,ee)}),W.pipe(z).pipe(q)})}},{key:"_createLogDirIfNotExist",value:function(F){h.existsSync(F)||h.mkdirSync(F,{recursive:!0})}}])})(P),$l}var Ll,wm;function sC(){if(wm)return Ll;wm=1;function e(x){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(T){return typeof T}:function(T){return T&&typeof Symbol=="function"&&T.constructor===Symbol&&T!==Symbol.prototype?"symbol":typeof T},e(x)}function t(x,T){var R=Object.keys(x);if(Object.getOwnPropertySymbols){var M=Object.getOwnPropertySymbols(x);T&&(M=M.filter(function(U){return Object.getOwnPropertyDescriptor(x,U).enumerable})),R.push.apply(R,M)}return R}function r(x){for(var T=1;T<arguments.length;T++){var R=arguments[T]!=null?arguments[T]:{};T%2?t(Object(R),!0).forEach(function(M){n(x,M,R[M])}):Object.getOwnPropertyDescriptors?Object.defineProperties(x,Object.getOwnPropertyDescriptors(R)):t(Object(R)).forEach(function(M){Object.defineProperty(x,M,Object.getOwnPropertyDescriptor(R,M))})}return x}function n(x,T,R){return(T=o(T))in x?Object.defineProperty(x,T,{value:R,enumerable:!0,configurable:!0,writable:!0}):x[T]=R,x}function i(x,T){if(!(x instanceof T))throw new TypeError("Cannot call a class as a function")}function s(x,T){for(var R=0;R<T.length;R++){var M=T[R];M.enumerable=M.enumerable||!1,M.configurable=!0,"value"in M&&(M.writable=!0),Object.defineProperty(x,o(M.key),M)}}function a(x,T,R){return T&&s(x.prototype,T),Object.defineProperty(x,"prototype",{writable:!1}),x}function o(x){var T=c(x,"string");return e(T)=="symbol"?T:T+""}function c(x,T){if(e(x)!="object"||!x)return x;var R=x[Symbol.toPrimitive];if(R!==void 0){var M=R.call(x,T);if(e(M)!="object")return M;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(x)}function l(x,T,R){return T=h(T),u(x,f()?Reflect.construct(T,R||[],h(x).constructor):T.apply(x,R))}function u(x,T){if(T&&(e(T)=="object"||typeof T=="function"))return T;if(T!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return d(x)}function d(x){if(x===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return x}function f(){try{var x=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(f=function(){return!!x})()}function h(x){return h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(T){return T.__proto__||Object.getPrototypeOf(T)},h(x)}function p(x,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function");x.prototype=Object.create(T&&T.prototype,{constructor:{value:x,writable:!0,configurable:!0}}),Object.defineProperty(x,"prototype",{writable:!1}),T&&m(x,T)}function m(x,T){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(R,M){return R.__proto__=M,R},m(x,T)}var w=br,y=br,g=rs(),_=g.Stream,b=ea(),A=Xs(),P=A.configure;return Ll=(function(x){function T(){var R,M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return i(this,T),R=l(this,T,[M]),R.options=M,R.name=M.name||"http",R.ssl=!!M.ssl,R.host=M.host||"localhost",R.port=M.port,R.auth=M.auth,R.path=M.path||"",R.maximumDepth=M.maximumDepth,R.agent=M.agent,R.headers=M.headers||{},R.headers["content-type"]="application/json",R.batch=M.batch||!1,R.batchInterval=M.batchInterval||5e3,R.batchCount=M.batchCount||10,R.batchOptions=[],R.batchTimeoutID=-1,R.batchCallback={},R.port||(R.port=R.ssl?443:80),R}return p(T,x),a(T,[{key:"log",value:function(M,U){var H=this;this._request(M,null,null,function(F,K){K&&K.statusCode!==200&&(F=new Error("Invalid HTTP Status Code: ".concat(K.statusCode))),F?H.emit("warn",F):H.emit("logged",M)}),U&&setImmediate(U)}},{key:"query",value:function(M,U){typeof M=="function"&&(U=M,M={}),M={method:"query",params:this.normalizeQuery(M)};var H=M.params.auth||null;delete M.params.auth;var F=M.params.path||null;delete M.params.path,this._request(M,H,F,function(K,ee,L){if(ee&&ee.statusCode!==200&&(K=new Error("Invalid HTTP Status Code: ".concat(ee.statusCode))),K)return U(K);if(typeof L=="string")try{L=JSON.parse(L)}catch(z){return U(z)}U(null,L)})}},{key:"stream",value:function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},U=new _;M={method:"stream",params:M};var H=M.params.path||null;delete M.params.path;var F=M.params.auth||null;delete M.params.auth;var K="",ee=this._request(M,F,H);return U.destroy=function(){return ee.destroy()},ee.on("data",function(L){L=(K+L).split(/\n+/);for(var z=L.length-1,W=0;W<z;W++)try{U.emit("log",JSON.parse(L[W]))}catch(q){U.emit("error",q)}K=L[z]}),ee.on("error",function(L){return U.emit("error",L)}),U}},{key:"_request",value:function(M,U,H,F){M=M||{},U=U||this.auth,H=H||this.path||"",this.batch?this._doBatch(M,F,U,H):this._doRequest(M,F,U,H)}},{key:"_doBatch",value:function(M,U,H,F){if(this.batchOptions.push(M),this.batchOptions.length===1){var K=this;this.batchCallback=U,this.batchTimeoutID=setTimeout(function(){K.batchTimeoutID=-1,K._doBatchRequest(K.batchCallback,H,F)},this.batchInterval)}this.batchOptions.length===this.batchCount&&this._doBatchRequest(this.batchCallback,H,F)}},{key:"_doBatchRequest",value:function(M,U,H){this.batchTimeoutID>0&&(clearTimeout(this.batchTimeoutID),this.batchTimeoutID=-1);var F=this.batchOptions.slice();this.batchOptions=[],this._doRequest(F,M,U,H)}},{key:"_doRequest",value:function(M,U,H,F){var K=Object.assign({},this.headers);H&&H.bearer&&(K.Authorization="Bearer ".concat(H.bearer));var ee=(this.ssl?y:w).request(r(r({},this.options),{},{method:"POST",host:this.host,port:this.port,path:"/".concat(F.replace(/^\//,"")),headers:K,auth:H&&H.username&&H.password?"".concat(H.username,":").concat(H.password):"",agent:this.agent}));ee.on("error",U),ee.on("response",function(z){return z.on("end",function(){return U(null,z)}).resume()});var L=P(r({},this.maximumDepth&&{maximumDepth:this.maximumDepth}));ee.end(Buffer.from(L(M,this.options.replacer),"utf8"))}}])})(b),Ll}var jl,bm;function O_(){if(bm)return jl;bm=1;const e=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function";return e.writable=t=>e(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object",e.readable=t=>e(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object",e.duplex=t=>e.writable(t)&&e.readable(t),e.transform=t=>e.duplex(t)&&typeof t._transform=="function",jl=e,jl}var Dl,Sm;function aC(){if(Sm)return Dl;Sm=1;function e(g){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},e(g)}function t(g,_){if(!(g instanceof _))throw new TypeError("Cannot call a class as a function")}function r(g,_){for(var b=0;b<_.length;b++){var A=_[b];A.enumerable=A.enumerable||!1,A.configurable=!0,"value"in A&&(A.writable=!0),Object.defineProperty(g,i(A.key),A)}}function n(g,_,b){return _&&r(g.prototype,_),Object.defineProperty(g,"prototype",{writable:!1}),g}function i(g){var _=s(g,"string");return e(_)=="symbol"?_:_+""}function s(g,_){if(e(g)!="object"||!g)return g;var b=g[Symbol.toPrimitive];if(b!==void 0){var A=b.call(g,_);if(e(A)!="object")return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(g)}function a(g,_,b){return _=u(_),o(g,l()?Reflect.construct(_,b||[],u(g).constructor):_.apply(g,b))}function o(g,_){if(_&&(e(_)=="object"||typeof _=="function"))return _;if(_!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return c(g)}function c(g){if(g===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return g}function l(){try{var g=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(l=function(){return!!g})()}function u(g){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(_){return _.__proto__||Object.getPrototypeOf(_)},u(g)}function d(g,_){if(typeof _!="function"&&_!==null)throw new TypeError("Super expression must either be null or a function");g.prototype=Object.create(_&&_.prototype,{constructor:{value:g,writable:!0,configurable:!0}}),Object.defineProperty(g,"prototype",{writable:!1}),_&&f(g,_)}function f(g,_){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(b,A){return b.__proto__=A,b},f(g,_)}var h=O_(),p=Ge(),m=p.MESSAGE,w=br,y=ea();return Dl=(function(g){function _(){var b,A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(t(this,_),b=a(this,_,[A]),!A.stream||!h(A.stream))throw new Error("options.stream is required.");return b._stream=A.stream,b._stream.setMaxListeners(1/0),b.isObjectMode=A.stream._writableState.objectMode,b.eol=typeof A.eol=="string"?A.eol:w.EOL,b}return d(_,g),n(_,[{key:"log",value:function(A,P){var x=this;if(setImmediate(function(){return x.emit("logged",A)}),this.isObjectMode){this._stream.write(A),P&&P();return}this._stream.write("".concat(A[m]).concat(this.eol)),P&&P()}}])})(y),Dl}var Em;function oC(){return Em||(Em=1,(function(e){Object.defineProperty(e,"Console",{configurable:!0,enumerable:!0,get:function(){return UT()}}),Object.defineProperty(e,"File",{configurable:!0,enumerable:!0,get:function(){return iC()}}),Object.defineProperty(e,"Http",{configurable:!0,enumerable:!0,get:function(){return sC()}}),Object.defineProperty(e,"Stream",{configurable:!0,enumerable:!0,get:function(){return aC()}})})(ul)),ul}var Yn={},Tm;function dd(){if(Tm)return Yn;Tm=1;var e=l_(),t=Ge(),r=t.configs;return Yn.cli=e.levels(r.cli),Yn.npm=e.levels(r.npm),Yn.syslog=e.levels(r.syslog),Yn.addColors=e.levels,Yn}var Ga={exports:{}},Va={exports:{}},Cm;function cC(){return Cm||(Cm=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=ud(),n=w(r),i=fd(),s=w(i),a=C_(),o=w(a),c=E_(),l=w(c),u=T_(),d=w(u),f=ts(),h=w(f),p=ta(),m=w(p);function w(b){return b&&b.__esModule?b:{default:b}}function y(b,A,P){P=(0,l.default)(P);var x=0,T=0,{length:R}=b,M=!1;R===0&&P(null);function U(H,F){H===!1&&(M=!0),M!==!0&&(H?P(H):(++T===R||F===s.default)&&P(null))}for(;x<R;x++)A(b[x],x,(0,d.default)(U))}function g(b,A,P){return(0,o.default)(b,1/0,A,P)}function _(b,A,P){var x=(0,n.default)(b)?y:g;return x(b,(0,h.default)(A),P)}t.default=(0,m.default)(_,3),e.exports=t.default})(Va,Va.exports)),Va.exports}var Wa={exports:{}},Am;function lC(){return Am||(Am=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;function r(n){return(i,s,a)=>n(i,a)}e.exports=t.default})(Wa,Wa.exports)),Wa.exports}var Om;function hd(){return Om||(Om=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=cC(),n=u(r),i=lC(),s=u(i),a=ts(),o=u(a),c=ta(),l=u(c);function u(f){return f&&f.__esModule?f:{default:f}}function d(f,h,p){return(0,n.default)(f,(0,s.default)((0,o.default)(h)),p)}t.default=(0,l.default)(d,3),e.exports=t.default})(Ga,Ga.exports)),Ga.exports}var Fl,xm;function uC(){if(xm)return Fl;xm=1;var e=Object.prototype.toString;return Fl=function(r){if(typeof r.displayName=="string"&&r.constructor.name)return r.displayName;if(typeof r.name=="string"&&r.name)return r.name;if(typeof r=="object"&&r.constructor&&typeof r.constructor.name=="string")return r.constructor.name;var n=r.toString(),i=e.call(r).slice(8,-1);return i==="Function"?n=n.substring(n.indexOf("(")+1,n.indexOf(")")):n=i,n||"anonymous"},Fl}var Ul,Pm;function x_(){if(Pm)return Ul;Pm=1;var e=uC();return Ul=function(r){var n=0,i;function s(){return n||(n=1,i=r.apply(this,arguments),r=null),i}return s.displayName=e(r),s},Ul}var Bl={},km;function P_(){return km||(km=1,(function(e){e.get=function(i){var s=Error.stackTraceLimit;Error.stackTraceLimit=1/0;var a={},o=Error.prepareStackTrace;Error.prepareStackTrace=function(l,u){return u},Error.captureStackTrace(a,i||e.get);var c=a.stack;return Error.prepareStackTrace=o,Error.stackTraceLimit=s,c},e.parse=function(i){if(!i.stack)return[];var s=this,a=i.stack.split(`
35
- `).slice(1);return a.map(function(o){if(o.match(/^\s*[-]{4,}$/))return s._createParsedCallSite({fileName:o,lineNumber:null,functionName:null,typeName:null,methodName:null,columnNumber:null,native:null});var c=o.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);if(c){var l=null,u=null,d=null,f=null,h=null,p=c[5]==="native";if(c[1]){d=c[1];var m=d.lastIndexOf(".");if(d[m-1]=="."&&m--,m>0){l=d.substr(0,m),u=d.substr(m+1);var w=l.indexOf(".Module");w>0&&(d=d.substr(w+1),l=l.substr(0,w))}f=null}u&&(f=l,h=u),u==="<anonymous>"&&(h=null,d=null);var y={fileName:c[2]||null,lineNumber:parseInt(c[3],10)||null,functionName:d,typeName:f,methodName:h,columnNumber:parseInt(c[4],10)||null,native:p};return s._createParsedCallSite(y)}}).filter(function(o){return!!o})};function t(i){for(var s in i)this[s]=i[s]}var r=["this","typeName","functionName","methodName","fileName","lineNumber","columnNumber","function","evalOrigin"],n=["topLevel","eval","native","constructor"];r.forEach(function(i){t.prototype[i]=null,t.prototype["get"+i[0].toUpperCase()+i.substr(1)]=function(){return this[i]}}),n.forEach(function(i){t.prototype[i]=!1,t.prototype["is"+i[0].toUpperCase()+i.substr(1)]=function(){return this[i]}}),e._createParsedCallSite=function(i){return new t(i)}})(Bl)),Bl}var zl,Im;function fC(){if(Im)return zl;Im=1;function e(m){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},e(m)}function t(m,w){if(!(m instanceof w))throw new TypeError("Cannot call a class as a function")}function r(m,w){for(var y=0;y<w.length;y++){var g=w[y];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(m,i(g.key),g)}}function n(m,w,y){return w&&r(m.prototype,w),Object.defineProperty(m,"prototype",{writable:!1}),m}function i(m){var w=s(m,"string");return e(w)=="symbol"?w:w+""}function s(m,w){if(e(m)!="object"||!m)return m;var y=m[Symbol.toPrimitive];if(y!==void 0){var g=y.call(m,w);if(e(g)!="object")return g;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(m)}function a(m,w,y){return w=u(w),o(m,l()?Reflect.construct(w,y||[],u(m).constructor):w.apply(m,y))}function o(m,w){if(w&&(e(w)=="object"||typeof w=="function"))return w;if(w!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return c(m)}function c(m){if(m===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m}function l(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(l=function(){return!!m})()}function u(m){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(w){return w.__proto__||Object.getPrototypeOf(w)},u(m)}function d(m,w){if(typeof w!="function"&&w!==null)throw new TypeError("Super expression must either be null or a function");m.prototype=Object.create(w&&w.prototype,{constructor:{value:m,writable:!0,configurable:!0}}),Object.defineProperty(m,"prototype",{writable:!1}),w&&f(m,w)}function f(m,w){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(y,g){return y.__proto__=g,y},f(m,w)}var h=rs(),p=h.Writable;return zl=(function(m){function w(y){var g;if(t(this,w),g=a(this,w,[{objectMode:!0}]),!y)throw new Error("ExceptionStream requires a TransportStream instance.");return g.handleExceptions=!0,g.transport=y,g}return d(w,m),n(w,[{key:"_write",value:function(g,_,b){return g.exception?this.transport.log(g,b):(b(),!0)}}])})(p),zl}var ql,Mm;function k_(){if(Mm)return ql;Mm=1;function e(f){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(h){return typeof h}:function(h){return h&&typeof Symbol=="function"&&h.constructor===Symbol&&h!==Symbol.prototype?"symbol":typeof h},e(f)}function t(f,h){if(!(f instanceof h))throw new TypeError("Cannot call a class as a function")}function r(f,h){for(var p=0;p<h.length;p++){var m=h[p];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(f,i(m.key),m)}}function n(f,h,p){return h&&r(f.prototype,h),Object.defineProperty(f,"prototype",{writable:!1}),f}function i(f){var h=s(f,"string");return e(h)=="symbol"?h:h+""}function s(f,h){if(e(f)!="object"||!f)return f;var p=f[Symbol.toPrimitive];if(p!==void 0){var m=p.call(f,h);if(e(m)!="object")return m;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(f)}var a=br,o=hd(),c=cc()("winston:exception"),l=x_(),u=P_(),d=fC();return ql=(function(){function f(h){if(t(this,f),!h)throw new Error("Logger is required to handle exceptions");this.logger=h,this.handlers=new Map}return n(f,[{key:"handle",value:function(){for(var p=this,m=arguments.length,w=new Array(m),y=0;y<m;y++)w[y]=arguments[y];w.forEach(function(g){if(Array.isArray(g))return g.forEach(function(_){return p._addHandler(_)});p._addHandler(g)}),this.catcher||(this.catcher=this._uncaughtException.bind(this),process.on("uncaughtException",this.catcher))}},{key:"unhandle",value:function(){var p=this;this.catcher&&(process.removeListener("uncaughtException",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach(function(m){return p.logger.unpipe(m)}))}},{key:"getAllInfo",value:function(p){var m=null;return p&&(m=typeof p=="string"?p:p.message),{error:p,level:"error",message:["uncaughtException: ".concat(m||"(no error message)"),p&&p.stack||" No stack trace"].join(`
36
- `),stack:p&&p.stack,exception:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(p)}}},{key:"getProcessInfo",value:function(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}},{key:"getOsInfo",value:function(){return{loadavg:a.loadavg(),uptime:a.uptime()}}},{key:"getTrace",value:function(p){var m=p?u.parse(p):u.get();return m.map(function(w){return{column:w.getColumnNumber(),file:w.getFileName(),function:w.getFunctionName(),line:w.getLineNumber(),method:w.getMethodName(),native:w.isNative()}})}},{key:"_addHandler",value:function(p){if(!this.handlers.has(p)){p.handleExceptions=!0;var m=new d(p);this.handlers.set(p,m),this.logger.pipe(m)}}},{key:"_uncaughtException",value:function(p){var m=this.getAllInfo(p),w=this._getExceptionHandlers(),y=typeof this.logger.exitOnError=="function"?this.logger.exitOnError(p):this.logger.exitOnError,g;!w.length&&y&&(console.warn("winston: exitOnError cannot be true with no exception handlers."),console.warn("winston: not exiting process."),y=!1);function _(){c("doExit",y),c("process._exiting",process._exiting),y&&!process._exiting&&(g&&clearTimeout(g),process.exit(1))}if(!w||w.length===0)return process.nextTick(_);o(w,function(b,A){var P=l(A),x=b.transport||b;function T(R){return function(){c(R),P()}}x._ending=!0,x.once("finish",T("finished")),x.once("error",T("error"))},function(){return y&&_()}),this.logger.log(m),y&&(g=setTimeout(_,3e3))}},{key:"_getExceptionHandlers",value:function(){return this.logger.transports.filter(function(p){var m=p.transport||p;return m.handleExceptions})}}])})(),ql}var Hl,Rm;function dC(){if(Rm)return Hl;Rm=1;function e(m){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w},e(m)}function t(m,w){if(!(m instanceof w))throw new TypeError("Cannot call a class as a function")}function r(m,w){for(var y=0;y<w.length;y++){var g=w[y];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(m,i(g.key),g)}}function n(m,w,y){return w&&r(m.prototype,w),Object.defineProperty(m,"prototype",{writable:!1}),m}function i(m){var w=s(m,"string");return e(w)=="symbol"?w:w+""}function s(m,w){if(e(m)!="object"||!m)return m;var y=m[Symbol.toPrimitive];if(y!==void 0){var g=y.call(m,w);if(e(g)!="object")return g;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(m)}function a(m,w,y){return w=u(w),o(m,l()?Reflect.construct(w,y||[],u(m).constructor):w.apply(m,y))}function o(m,w){if(w&&(e(w)=="object"||typeof w=="function"))return w;if(w!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return c(m)}function c(m){if(m===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m}function l(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(l=function(){return!!m})()}function u(m){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(w){return w.__proto__||Object.getPrototypeOf(w)},u(m)}function d(m,w){if(typeof w!="function"&&w!==null)throw new TypeError("Super expression must either be null or a function");m.prototype=Object.create(w&&w.prototype,{constructor:{value:m,writable:!0,configurable:!0}}),Object.defineProperty(m,"prototype",{writable:!1}),w&&f(m,w)}function f(m,w){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(y,g){return y.__proto__=g,y},f(m,w)}var h=rs(),p=h.Writable;return Hl=(function(m){function w(y){var g;if(t(this,w),g=a(this,w,[{objectMode:!0}]),!y)throw new Error("RejectionStream requires a TransportStream instance.");return g.handleRejections=!0,g.transport=y,g}return d(w,m),n(w,[{key:"_write",value:function(g,_,b){return g.rejection?this.transport.log(g,b):(b(),!0)}}])})(p),Hl}var Gl,Nm;function I_(){if(Nm)return Gl;Nm=1;function e(f){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(h){return typeof h}:function(h){return h&&typeof Symbol=="function"&&h.constructor===Symbol&&h!==Symbol.prototype?"symbol":typeof h},e(f)}function t(f,h){if(!(f instanceof h))throw new TypeError("Cannot call a class as a function")}function r(f,h){for(var p=0;p<h.length;p++){var m=h[p];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(f,i(m.key),m)}}function n(f,h,p){return h&&r(f.prototype,h),Object.defineProperty(f,"prototype",{writable:!1}),f}function i(f){var h=s(f,"string");return e(h)=="symbol"?h:h+""}function s(f,h){if(e(f)!="object"||!f)return f;var p=f[Symbol.toPrimitive];if(p!==void 0){var m=p.call(f,h);if(e(m)!="object")return m;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(f)}var a=br,o=hd(),c=cc()("winston:rejection"),l=x_(),u=P_(),d=dC();return Gl=(function(){function f(h){if(t(this,f),!h)throw new Error("Logger is required to handle rejections");this.logger=h,this.handlers=new Map}return n(f,[{key:"handle",value:function(){for(var p=this,m=arguments.length,w=new Array(m),y=0;y<m;y++)w[y]=arguments[y];w.forEach(function(g){if(Array.isArray(g))return g.forEach(function(_){return p._addHandler(_)});p._addHandler(g)}),this.catcher||(this.catcher=this._unhandledRejection.bind(this),process.on("unhandledRejection",this.catcher))}},{key:"unhandle",value:function(){var p=this;this.catcher&&(process.removeListener("unhandledRejection",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach(function(m){return p.logger.unpipe(m)}))}},{key:"getAllInfo",value:function(p){var m=null;return p&&(m=typeof p=="string"?p:p.message),{error:p,level:"error",message:["unhandledRejection: ".concat(m||"(no error message)"),p&&p.stack||" No stack trace"].join(`
37
- `),stack:p&&p.stack,rejection:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(p)}}},{key:"getProcessInfo",value:function(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}},{key:"getOsInfo",value:function(){return{loadavg:a.loadavg(),uptime:a.uptime()}}},{key:"getTrace",value:function(p){var m=p?u.parse(p):u.get();return m.map(function(w){return{column:w.getColumnNumber(),file:w.getFileName(),function:w.getFunctionName(),line:w.getLineNumber(),method:w.getMethodName(),native:w.isNative()}})}},{key:"_addHandler",value:function(p){if(!this.handlers.has(p)){p.handleRejections=!0;var m=new d(p);this.handlers.set(p,m),this.logger.pipe(m)}}},{key:"_unhandledRejection",value:function(p){var m=this.getAllInfo(p),w=this._getRejectionHandlers(),y=typeof this.logger.exitOnError=="function"?this.logger.exitOnError(p):this.logger.exitOnError,g;!w.length&&y&&(console.warn("winston: exitOnError cannot be true with no rejection handlers."),console.warn("winston: not exiting process."),y=!1);function _(){c("doExit",y),c("process._exiting",process._exiting),y&&!process._exiting&&(g&&clearTimeout(g),process.exit(1))}if(!w||w.length===0)return process.nextTick(_);o(w,function(b,A){var P=l(A),x=b.transport||b;function T(R){return function(){c(R),P()}}x._ending=!0,x.once("finish",T("finished")),x.once("error",T("error"))},function(){return y&&_()}),this.logger.log(m),y&&(g=setTimeout(_,3e3))}},{key:"_getRejectionHandlers",value:function(){return this.logger.transports.filter(function(p){var m=p.transport||p;return m.handleRejections})}}])})(),Gl}var Vl={exports:{}},Wl={exports:{}},$m;function hC(){if($m)return Wl.exports;$m=1;const e=Ar,t=oc(),{LEVEL:r}=Ge(),n=Wl.exports=function(s={}){t.call(this,{objectMode:!0,highWaterMark:s.highWaterMark}),this.format=s.format,this.level=s.level,this.handleExceptions=s.handleExceptions,this.handleRejections=s.handleRejections,this.silent=s.silent,s.log&&(this.log=s.log),s.logv&&(this.logv=s.logv),s.close&&(this.close=s.close),this.once("pipe",a=>{this.levels=a.levels,this.parent=a}),this.once("unpipe",a=>{a===this.parent&&(this.parent=null,this.close&&this.close())})};return e.inherits(n,t),n.prototype._write=function(s,a,o){if(this.silent||s.exception===!0&&!this.handleExceptions)return o(null);const c=this.level||this.parent&&this.parent.level;if(!c||this.levels[c]>=this.levels[s[r]]){if(s&&!this.format)return this.log(s,o);let l,u;try{u=this.format.transform(Object.assign({},s),this.format.options)}catch(d){l=d}if(l||!u){if(o(),l)throw l;return}return this.log(u,o)}return this._writableState.sync=!1,o(null)},n.prototype._writev=function(s,a){if(this.logv){const o=s.filter(this._accept,this);return o.length?this.logv(o,a):a(null)}for(let o=0;o<s.length;o++){if(!this._accept(s[o]))continue;if(s[o].chunk&&!this.format){this.log(s[o].chunk,s[o].callback);continue}let c,l;try{l=this.format.transform(Object.assign({},s[o].chunk),this.format.options)}catch(u){c=u}if(c||!l){if(s[o].callback(),c)throw a(null),c}else this.log(l,s[o].callback)}return a(null)},n.prototype._accept=function(s){const a=s.chunk;if(this.silent)return!1;const o=this.level||this.parent&&this.parent.level;return!!((a.exception===!0||!o||this.levels[o]>=this.levels[a[r]])&&(this.handleExceptions||a.exception!==!0))},n.prototype._nop=function(){},Wl.exports}var Lm;function pC(){if(Lm)return Vl.exports;Lm=1;const e=Ar,{LEVEL:t}=Ge(),r=hC(),n=Vl.exports=function(s={}){if(r.call(this,s),!s.transport||typeof s.transport.log!="function")throw new Error("Invalid transport, must be an object with a log method.");this.transport=s.transport,this.level=this.level||s.transport.level,this.handleExceptions=this.handleExceptions||s.transport.handleExceptions,this._deprecated();function a(o){this.emit("error",o,this.transport)}this.transport.__winstonError||(this.transport.__winstonError=a.bind(this),this.transport.on("error",this.transport.__winstonError))};return e.inherits(n,r),n.prototype._write=function(s,a,o){if(this.silent||s.exception===!0&&!this.handleExceptions)return o(null);(!this.level||this.levels[this.level]>=this.levels[s[t]])&&this.transport.log(s[t],s.message,s,this._nop),o(null)},n.prototype._writev=function(s,a){for(let o=0;o<s.length;o++)this._accept(s[o])&&(this.transport.log(s[o].chunk[t],s[o].chunk.message,s[o].chunk,this._nop),s[o].callback());return a(null)},n.prototype._deprecated=function(){console.error([`${this.transport.name} is a legacy winston transport. Consider upgrading: `,"- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md"].join(`
38
- `))},n.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)},Vl.exports}var Jl,jm;function mC(){if(jm)return Jl;jm=1;function e(o){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c},e(o)}function t(o,c){if(!(o instanceof c))throw new TypeError("Cannot call a class as a function")}function r(o,c){for(var l=0;l<c.length;l++){var u=c[l];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(o,i(u.key),u)}}function n(o,c,l){return c&&r(o.prototype,c),Object.defineProperty(o,"prototype",{writable:!1}),o}function i(o){var c=s(o,"string");return e(c)=="symbol"?c:c+""}function s(o,c){if(e(o)!="object"||!o)return o;var l=o[Symbol.toPrimitive];if(l!==void 0){var u=l.call(o,c);if(e(u)!="object")return u;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}var a=(function(){function o(c){t(this,o);var l=pd();if(e(c)!=="object"||Array.isArray(c)||!(c instanceof l))throw new Error("Logger is required for profiling");this.logger=c,this.start=Date.now()}return n(o,[{key:"done",value:function(){for(var l=arguments.length,u=new Array(l),d=0;d<l;d++)u[d]=arguments[d];typeof u[u.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),u.pop());var f=e(u[u.length-1])==="object"?u.pop():{};return f.level=f.level||"info",f.durationMs=Date.now()-this.start,this.logger.write(f)}}])})();return Jl=a,Jl}var Kl,Dm;function gC(){if(Dm)return Kl;Dm=1;class e extends Error{constructor(r){super(`Format functions must be synchronous taking a two arguments: (info, opts)
39
- Found: ${r.toString().split(`
40
- `)[0]}
41
- `),Error.captureStackTrace(this,e)}}return Kl=t=>{if(t.length>2)throw new e(t);function r(i={}){this.options=i}r.prototype.transform=t;function n(i){return new r(i)}return n.Format=r,n},Kl}var Zl,Fm;function yC(){if(Fm)return Zl;Fm=1;const e=gC(),{MESSAGE:t}=Ge(),r=Xs();function n(i,s){return typeof s=="bigint"?s.toString():s}return Zl=e((i,s)=>{const a=r.configure(s);return i[t]=a(i,s.replacer||n,s.space),i}),Zl}var Yl,Um;function pd(){if(Um)return Yl;Um=1;function e(L,z,W){return(z=s(z))in L?Object.defineProperty(L,z,{value:W,enumerable:!0,configurable:!0,writable:!0}):L[z]=W,L}function t(L){"@babel/helpers - typeof";return t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(z){return typeof z}:function(z){return z&&typeof Symbol=="function"&&z.constructor===Symbol&&z!==Symbol.prototype?"symbol":typeof z},t(L)}function r(L,z){if(!(L instanceof z))throw new TypeError("Cannot call a class as a function")}function n(L,z){for(var W=0;W<z.length;W++){var q=z[W];q.enumerable=q.enumerable||!1,q.configurable=!0,"value"in q&&(q.writable=!0),Object.defineProperty(L,s(q.key),q)}}function i(L,z,W){return z&&n(L.prototype,z),Object.defineProperty(L,"prototype",{writable:!1}),L}function s(L){var z=a(L,"string");return t(z)=="symbol"?z:z+""}function a(L,z){if(t(L)!="object"||!L)return L;var W=L[Symbol.toPrimitive];if(W!==void 0){var q=W.call(L,z);if(t(q)!="object")return q;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(L)}function o(L,z,W){return z=d(z),c(L,u()?Reflect.construct(z,W||[],d(L).constructor):z.apply(L,W))}function c(L,z){if(z&&(t(z)=="object"||typeof z=="function"))return z;if(z!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return l(L)}function l(L){if(L===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return L}function u(){try{var L=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(u=function(){return!!L})()}function d(L){return d=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(z){return z.__proto__||Object.getPrototypeOf(z)},d(L)}function f(L,z){if(typeof z!="function"&&z!==null)throw new TypeError("Super expression must either be null or a function");L.prototype=Object.create(z&&z.prototype,{constructor:{value:L,writable:!0,configurable:!0}}),Object.defineProperty(L,"prototype",{writable:!1}),z&&h(L,z)}function h(L,z){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(W,q){return W.__proto__=q,W},h(L,z)}var p=rs(),m=p.Stream,w=p.Transform,y=hd(),g=Ge(),_=g.LEVEL,b=g.SPLAT,A=O_(),P=k_(),x=I_(),T=pC(),R=mC(),M=u_(),U=M.warn,H=dd(),F=/%[scdjifoO%]/g,K=(function(L){function z(W){var q;return r(this,z),q=o(this,z,[{objectMode:!0}]),q.configure(W),q}return f(z,L),i(z,[{key:"child",value:function(q){var V=this;return Object.create(V,{write:{value:function(Q){var ae=Object.assign({},q,Q);Q instanceof Error&&(ae.stack=Q.stack,ae.message=Q.message),V.write(ae)}}})}},{key:"configure",value:function(){var q=this,V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Y=V.silent,Q=V.format,ae=V.defaultMeta,X=V.levels,se=V.level,C=se===void 0?"info":se,S=V.exitOnError,D=S===void 0?!0:S,j=V.transports,re=V.colors,k=V.emitErrs,I=V.formatters,J=V.padLevels,ne=V.rewriters,Te=V.stripColors,ue=V.exceptionHandlers,ye=V.rejectionHandlers;if(this.transports.length&&this.clear(),this.silent=Y,this.format=Q||this.format||yC()(),this.defaultMeta=ae||null,this.levels=X||this.levels||H.npm.levels,this.level=C,this.exceptions&&this.exceptions.unhandle(),this.rejections&&this.rejections.unhandle(),this.exceptions=new P(this),this.rejections=new x(this),this.profilers={},this.exitOnError=D,j&&(j=Array.isArray(j)?j:[j],j.forEach(function(Vt){return q.add(Vt)})),re||k||I||J||ne||Te)throw new Error(["{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.","Use a custom winston.format(function) instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join(`
42
- `));ue&&this.exceptions.handle(ue),ye&&this.rejections.handle(ye)}},{key:"getHighestLogLevel",value:function(){var q=this,V=ee(this.levels,this.level);return!this.transports||this.transports.length===0?V:this.transports.reduce(function(Y,Q){var ae=ee(q.levels,Q.level);return ae!==null&&ae>Y?ae:Y},V)}},{key:"isLevelEnabled",value:function(q){var V=this,Y=ee(this.levels,q);if(Y===null)return!1;var Q=ee(this.levels,this.level);if(Q===null)return!1;if(!this.transports||this.transports.length===0)return Q>=Y;var ae=this.transports.findIndex(function(X){var se=ee(V.levels,X.level);return se===null&&(se=Q),se>=Y});return ae!==-1}},{key:"log",value:function(q,V){for(var Y=arguments.length,Q=new Array(Y>2?Y-2:0),ae=2;ae<Y;ae++)Q[ae-2]=arguments[ae];if(arguments.length===1)return q[_]=q.level,this._addDefaultMeta(q),this.write(q),this;if(arguments.length===2)return V&&t(V)==="object"?(V[_]=V.level=q,this._addDefaultMeta(V),this.write(V),this):(V=e(e(e({},_,q),"level",q),"message",V),this._addDefaultMeta(V),this.write(V),this);var X=Q[0];if(t(X)==="object"&&X!==null){var se=V&&V.match&&V.match(F);if(!se){var C=Object.assign({},this.defaultMeta,X,e(e(e(e({},_,q),b,Q),"level",q),"message",V));return X.message&&(C.message="".concat(C.message," ").concat(X.message)),X.stack&&(C.stack=X.stack),X.cause&&(C.cause=X.cause),this.write(C),this}}return this.write(Object.assign({},this.defaultMeta,e(e(e(e({},_,q),b,Q),"level",q),"message",V))),this}},{key:"_transform",value:function(q,V,Y){if(this.silent)return Y();q[_]||(q[_]=q.level),!this.levels[q[_]]&&this.levels[q[_]]!==0&&console.error("[winston] Unknown logger level: %s",q[_]),this._readableState.pipes||console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j",q);try{this.push(this.format.transform(q,this.format.options))}finally{this._writableState.sync=!1,Y()}}},{key:"_final",value:function(q){var V=this.transports.slice();y(V,function(Y,Q){if(!Y||Y.finished)return setImmediate(Q);Y.once("finish",Q),Y.end()},q)}},{key:"add",value:function(q){var V=!A(q)||q.log.length>2?new T({transport:q}):q;if(!V._writableState||!V._writableState.objectMode)throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");return this._onEvent("error",V),this._onEvent("warn",V),this.pipe(V),q.handleExceptions&&this.exceptions.handle(),q.handleRejections&&this.rejections.handle(),this}},{key:"remove",value:function(q){if(!q)return this;var V=q;return(!A(q)||q.log.length>2)&&(V=this.transports.filter(function(Y){return Y.transport===q})[0]),V&&this.unpipe(V),this}},{key:"clear",value:function(){return this.unpipe(),this}},{key:"close",value:function(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit("close"),this}},{key:"setLevels",value:function(){U.deprecated("setLevels")}},{key:"query",value:function(q,V){typeof q=="function"&&(V=q,q={}),q=q||{};var Y={},Q=Object.assign({},q.query||{});function ae(se,C){q.query&&typeof se.formatQuery=="function"&&(q.query=se.formatQuery(Q)),se.query(q,function(S,D){if(S)return C(S);typeof se.formatResults=="function"&&(D=se.formatResults(D,q.format)),C(null,D)})}function X(se,C){ae(se,function(S,D){C&&(D=S||D,D&&(Y[se.name]=D),C()),C=null})}y(this.transports.filter(function(se){return!!se.query}),X,function(){return V(null,Y)})}},{key:"stream",value:function(){var q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},V=new m,Y=[];return V._streams=Y,V.destroy=function(){for(var Q=Y.length;Q--;)Y[Q].destroy()},this.transports.filter(function(Q){return!!Q.stream}).forEach(function(Q){var ae=Q.stream(q);ae&&(Y.push(ae),ae.on("log",function(X){X.transport=X.transport||[],X.transport.push(Q.name),V.emit("log",X)}),ae.on("error",function(X){X.transport=X.transport||[],X.transport.push(Q.name),V.emit("error",X)}))}),V}},{key:"startTimer",value:function(){return new R(this)}},{key:"profile",value:function(q){var V=Date.now();if(this.profilers[q]){var Y=this.profilers[q];delete this.profilers[q];for(var Q=arguments.length,ae=new Array(Q>1?Q-1:0),X=1;X<Q;X++)ae[X-1]=arguments[X];typeof ae[ae.length-2]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),ae.pop());var se=t(ae[ae.length-1])==="object"?ae.pop():{};return se.level=se.level||"info",se.durationMs=V-Y,se.message=se.message||q,this.write(se)}return this.profilers[q]=V,this}},{key:"handleExceptions",value:function(){var q;console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()"),(q=this.exceptions).handle.apply(q,arguments)}},{key:"unhandleExceptions",value:function(){var q;console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()"),(q=this.exceptions).unhandle.apply(q,arguments)}},{key:"cli",value:function(){throw new Error(["Logger.cli() was removed in winston@3.0.0","Use a custom winston.formats.cli() instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join(`
43
- `))}},{key:"_onEvent",value:function(q,V){function Y(Q){q==="error"&&!this.transports.includes(V)&&this.add(V),this.emit(q,Q,V)}V["__winston"+q]||(V["__winston"+q]=Y.bind(this),V.on(q,V["__winston"+q]))}},{key:"_addDefaultMeta",value:function(q){this.defaultMeta&&Object.assign(q,this.defaultMeta)}}])})(w);function ee(L,z){var W=L[z];return!W&&W!==0?null:W}return Object.defineProperty(K.prototype,"transports",{configurable:!1,enumerable:!0,get:function(){var z=this._readableState.pipes;return Array.isArray(z)?z:[z].filter(Boolean)}}),Yl=K,Yl}var Xl,Bm;function M_(){if(Bm)return Xl;Bm=1;function e(w){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y},e(w)}function t(w,y,g){return Object.defineProperty(w,"prototype",{writable:!1}),w}function r(w,y){if(!(w instanceof y))throw new TypeError("Cannot call a class as a function")}function n(w,y,g){return y=o(y),i(w,a()?Reflect.construct(y,g||[],o(w).constructor):y.apply(w,g))}function i(w,y){if(y&&(e(y)=="object"||typeof y=="function"))return y;if(y!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return s(w)}function s(w){if(w===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return w}function a(){try{var w=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(a=function(){return!!w})()}function o(w){return o=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(y){return y.__proto__||Object.getPrototypeOf(y)},o(w)}function c(w,y){if(typeof y!="function"&&y!==null)throw new TypeError("Super expression must either be null or a function");w.prototype=Object.create(y&&y.prototype,{constructor:{value:w,writable:!0,configurable:!0}}),Object.defineProperty(w,"prototype",{writable:!1}),y&&l(w,y)}function l(w,y){return l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(g,_){return g.__proto__=_,g},l(w,y)}var u=Ge(),d=u.LEVEL,f=dd(),h=pd(),p=cc()("winston:create-logger");function m(w){return"is"+w.charAt(0).toUpperCase()+w.slice(1)+"Enabled"}return Xl=function(){var w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};w.levels=w.levels||f.npm.levels;var y=(function(_){function b(A){return r(this,b),n(this,b,[A])}return c(b,_),t(b)})(h),g=new y(w);return Object.keys(w.levels).forEach(function(_){if(p('Define prototype method for "%s"',_),_==="log"){console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');return}y.prototype[_]=function(){for(var b=this||g,A=arguments.length,P=new Array(A),x=0;x<A;x++)P[x]=arguments[x];if(P.length===1){var T=P[0],R=T&&T.message&&T||{message:T};return R.level=R[d]=_,b._addDefaultMeta(R),b.write(R),this||g}return P.length===0?(b.log(_,""),b):b.log.apply(b,[_].concat(P))},y.prototype[m(_)]=function(){return(this||g).isLevelEnabled(_)}}),g},Xl}var Ql,zm;function _C(){if(zm)return Ql;zm=1;function e(o){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c},e(o)}function t(o,c){if(!(o instanceof c))throw new TypeError("Cannot call a class as a function")}function r(o,c){for(var l=0;l<c.length;l++){var u=c[l];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(o,i(u.key),u)}}function n(o,c,l){return c&&r(o.prototype,c),Object.defineProperty(o,"prototype",{writable:!1}),o}function i(o){var c=s(o,"string");return e(c)=="symbol"?c:c+""}function s(o,c){if(e(o)!="object"||!o)return o;var l=o[Symbol.toPrimitive];if(l!==void 0){var u=l.call(o,c);if(e(u)!="object")return u;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}var a=M_();return Ql=(function(){function o(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t(this,o),this.loggers=new Map,this.options=c}return n(o,[{key:"add",value:function(l,u){var d=this;if(!this.loggers.has(l)){u=Object.assign({},u||this.options);var f=u.transports||this.options.transports;f?u.transports=Array.isArray(f)?f.slice():[f]:u.transports=[];var h=a(u);h.on("close",function(){return d._delete(l)}),this.loggers.set(l,h)}return this.loggers.get(l)}},{key:"get",value:function(l,u){return this.add(l,u)}},{key:"has",value:function(l){return!!this.loggers.has(l)}},{key:"close",value:function(l){var u=this;if(l)return this._removeLogger(l);this.loggers.forEach(function(d,f){return u._removeLogger(f)})}},{key:"_removeLogger",value:function(l){if(this.loggers.has(l)){var u=this.loggers.get(l);u.close(),this._delete(l)}}},{key:"_delete",value:function(l){this.loggers.delete(l)}}])})(),Ql}var qm;function vC(){return qm||(qm=1,(function(e){var t=l_(),r=u_(),n=r.warn;e.version=MT.version,e.transports=oC(),e.config=dd(),e.addColors=t.levels,e.format=t.format,e.createLogger=M_(),e.Logger=pd(),e.ExceptionHandler=k_(),e.RejectionHandler=I_(),e.Container=_C(),e.Transport=ea(),e.loggers=new e.Container;var i=e.createLogger();Object.keys(e.config.npm.levels).concat(["log","query","stream","add","remove","clear","profile","startTimer","handleExceptions","unhandleExceptions","handleRejections","unhandleRejections","configure","child"]).forEach(function(s){return e[s]=function(){return i[s].apply(i,arguments)}}),Object.defineProperty(e,"level",{get:function(){return i.level},set:function(a){i.level=a}}),Object.defineProperty(e,"exceptions",{get:function(){return i.exceptions}}),Object.defineProperty(e,"rejections",{get:function(){return i.rejections}}),["exitOnError"].forEach(function(s){Object.defineProperty(e,s,{get:function(){return i[s]},set:function(o){i[s]=o}})}),Object.defineProperty(e,"default",{get:function(){return{exceptionHandlers:i.exceptionHandlers,rejectionHandlers:i.rejectionHandlers,transports:i.transports}}}),n.deprecated(e,"setLevels"),n.forFunctions(e,"useFormat",["cli"]),n.forProperties(e,"useFormat",["padLevels","stripColors"]),n.forFunctions(e,"deprecated",["addRewriter","addFilter","clone","extend"]),n.forProperties(e,"deprecated",["emitErrs","levelLength"])})(Nc)),Nc}var bs=vC(),Ue={};async function R_(){if(typeof process<"u")try{const e=await Di(()=>Promise.resolve().then(()=>Ps),void 0),t=await Di(()=>Promise.resolve().then(()=>S_),void 0);return{fs:e.default,path:t.default}}catch{return{fs:null,path:null}}return{fs:null,path:null}}le(R_,"getNodeModules");var{combine:Hm,timestamp:Gm,label:Vm,printf:md,colorize:Wm,splat:Jm}=bs.format,Ju="mcp-use";function Ro(){try{if(typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u")return!1;const e=typeof process<"u"&&!0&&typeof __dirname<"u",t=typeof bs.createLogger=="function";return e&&t}catch{return!1}}le(Ro,"isNodeJSEnvironment");var hi,wC=(hi=class{_level;name;constructor(t=Ju,r="info"){this.name=t,this._level=r}shouldLog(t){const r=["error","warn","info","http","verbose","debug","silly"],n=r.indexOf(this._level);return r.indexOf(t)<=n}formatMessage(t,r){return`${new Date().toLocaleTimeString("en-US",{hour12:!1})} [${this.name}] ${t}: ${r}`}error(t){this.shouldLog("error")&&console.error(this.formatMessage("error",t))}warn(t){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",t))}info(t){this.shouldLog("info")&&console.info(this.formatMessage("info",t))}debug(t){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",t))}http(t){this.shouldLog("http")&&console.log(this.formatMessage("http",t))}verbose(t){this.shouldLog("verbose")&&console.log(this.formatMessage("verbose",t))}silly(t){this.shouldLog("silly")&&console.log(this.formatMessage("silly",t))}get level(){return this._level}set level(t){this._level=t}},le(hi,"SimpleConsoleLogger"),hi);function oo(e){switch((typeof process<"u"&&Ue?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}le(oo,"resolveLevel");var Km=md(({level:e,message:t,label:r,timestamp:n})=>`${n} [${r}] ${e}: ${t}`),bC=md(({level:e,message:t,label:r,timestamp:n})=>`${n} [${r}] ${e.toUpperCase()}: ${t}`),SC=md(({level:e,message:t,label:r,timestamp:n})=>`${n} [${r}] ${e.toUpperCase()}: ${t}`),$r,No=($r=class{static get(t=Ju){if(!Ro()){if(!this.simpleInstances[t]){const r=typeof process<"u"&&Ue?.DEBUG||void 0;this.simpleInstances[t]=new wC(t,oo(r))}return this.simpleInstances[t]}return this.instances[t]||(this.instances[t]=bs.createLogger({level:oo(Ue.DEBUG),format:Hm(Wm(),Jm(),Vm({label:t}),Gm({format:"HH:mm:ss"}),this.getFormatter()),transports:[]})),this.instances[t]}static getFormatter(){switch(this.currentFormat){case"minimal":return Km;case"detailed":return bC;case"emoji":return SC;default:return Km}}static async configure(t={}){const{level:r,console:n=!0,file:i,format:s="minimal"}=t,a=typeof process<"u"&&Ue?.DEBUG||void 0,o=r??oo(a);this.currentFormat=s;const c=this.get();c.level=o;const l=c;if(!Ro()){Object.values(this.simpleInstances).forEach(u=>{u.level=o});return}if(l.clear(),n&&l.add(new bs.transports.Console),i){const{fs:u,path:d}=await R_();if(u&&d){const f=d.dirname(d.resolve(i));u.existsSync(f)||u.mkdirSync(f,{recursive:!0}),l.add(new bs.transports.File({filename:i}))}}Object.values(this.instances).forEach(u=>{u&&"format"in u&&(u.level=o,u.format=Hm(Wm(),Jm(),Vm({label:Ju}),Gm({format:"HH:mm:ss"}),this.getFormatter()))})}static setDebug(t){let r;t===2||t===!0?r="debug":r="info",Object.values(this.simpleInstances).forEach(n=>{n.level=r}),Object.values(this.instances).forEach(n=>{n&&(n.level=r)}),typeof process<"u"&&Ue&&(Ue.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},le($r,"Logger"),cs($r,"instances",{}),cs($r,"simpleInstances",{}),cs($r,"currentFormat","minimal"),$r);Ro()?No.configure():No.configure({console:!0});var $=No.get(),EC=Ue.MCP_USE_LANGFUSE?.toLowerCase()==="false",ks={handler:null,client:null,initPromise:null};async function N_(e,t,r,n){try{const i=await Di(()=>import("./index-WLUXcbDv.js"),__vite__mapDeps([0,1,2,3,4,5])).catch(()=>null);if(!i){$.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:s}=i,u=class u extends s{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(f,h,p,m,w){super(f),this.agentId=h,this.metadata=p,this.metadataProvider=m,this.tagsProvider=w,this.verbose=f?.verbose??!1}async handleChainStart(f,h,p,m,w,y,g,_){$.debug("Langfuse: Chain start intercepted");const b=this.getCustomTags(),A=this.getMetadata(),P=[...w||[],...b],x={...y||{},...A};return this.verbose&&($.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(P)}`),$.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(x)}`)),super.handleChainStart(f,h,p,m,P,x,g,_)}getCustomTags(){const f=[],h=this.getEnvironmentTag();if(h&&f.push(`env:${h}`),this.agentId&&f.push(`agent_id:${this.agentId}`),this.tagsProvider){const p=this.tagsProvider();p&&p.length>0&&f.push(...p)}return f}getMetadata(){const f={},h=this.getEnvironmentTag();if(h&&(f.env=h),this.agentId&&(f.agent_id=this.agentId),this.metadata&&Object.assign(f,this.metadata),this.metadataProvider){const p=this.metadataProvider();p&&Object.assign(f,p)}return f}getEnvironmentTag(){const f=Ue.MCP_USE_AGENT_ENV;if(!f)return"unknown";const h=f.toLowerCase();return h==="local"||h==="development"?"local":h==="production"||h==="prod"?"production":h==="staging"||h==="stage"?"staging":h==="hosted"||h==="cloud"?"hosted":h.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...f){return $.debug("Langfuse: LLM start intercepted"),this.verbose&&$.debug(`Langfuse: LLM start args: ${JSON.stringify(f)}`),super.handleLLMStart(...f)}async handleToolStart(...f){return $.debug("Langfuse: Tool start intercepted"),this.verbose&&$.debug(`Langfuse: Tool start args: ${JSON.stringify(f)}`),super.handleToolStart(...f)}async handleRetrieverStart(...f){return $.debug("Langfuse: Retriever start intercepted"),this.verbose&&$.debug(`Langfuse: Retriever start args: ${JSON.stringify(f)}`),super.handleRetrieverStart(...f)}async handleAgentAction(...f){return $.debug("Langfuse: Agent action intercepted"),this.verbose&&$.debug(`Langfuse: Agent action args: ${JSON.stringify(f)}`),super.handleAgentAction(...f)}async handleAgentEnd(...f){return $.debug("Langfuse: Agent end intercepted"),this.verbose&&$.debug(`Langfuse: Agent end args: ${JSON.stringify(f)}`),super.handleAgentEnd(...f)}};le(u,"LoggingCallbackHandler");let a=u;const o=t||(r?r():{}),c=n?n():[],l={publicKey:Ue.LANGFUSE_PUBLIC_KEY,secretKey:Ue.LANGFUSE_SECRET_KEY,baseUrl:Ue.LANGFUSE_HOST||Ue.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Ue.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Ue.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Ue.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Ue.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Ue.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Ue.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};$.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),ks.handler=new a(l,e,t,r,n),$.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await Di(()=>import("./index-CEkgKN2t.js"),__vite__mapDeps([1,2,3,4,5])).catch(()=>null);if(d){const{Langfuse:f}=d;ks.client=new f({publicKey:Ue.LANGFUSE_PUBLIC_KEY,secretKey:Ue.LANGFUSE_SECRET_KEY,baseUrl:Ue.LANGFUSE_HOST||"https://cloud.langfuse.com"}),$.debug("Langfuse client initialized")}}catch(d){$.debug(`Langfuse client initialization failed: ${d}`)}}catch(i){$.debug(`Langfuse initialization error: ${i}`)}}le(N_,"initializeLangfuse");EC?$.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Ue.LANGFUSE_PUBLIC_KEY||!Ue.LANGFUSE_SECRET_KEY?$.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):ks.initPromise=N_();var J2=le(()=>ks.handler,"langfuseHandler"),K2=le(()=>ks.initPromise,"langfuseInitPromise");class TC{static convert(t){return this.parseSchema(t)}static matchesCondition(t,r){if(!r.properties)return!0;if(typeof t!="object"||t===null||Array.isArray(t))return!1;const n=t;for(const[i,s]of Object.entries(r.properties)){if(!(i in n)){if("const"in s)return!1;continue}const a=n[i];if("const"in s&&a!==s.const||"minimum"in s&&typeof a=="number"&&a<s.minimum||"maximum"in s&&typeof a=="number"&&a>s.maximum)return!1}return!0}static validateConditionalSchema(t,r,n){this.validateRequiredProperties(t,r,n),this.validatePropertyPatterns(t,r,n),this.validateNestedConditions(t,r,n)}static validateRequiredProperties(t,r,n){if(r.required){if(typeof t!="object"||t===null){for(const i of r.required)n.addIssue({code:Rc.custom,message:`Required property '${i}' is missing`,path:[i]});return}for(const i of r.required)i in t||n.addIssue({code:Rc.custom,message:`Required property '${i}' is missing`,path:[i]})}}static validatePropertyPatterns(t,r,n){if(!r.properties||typeof t!="object"||t===null||Array.isArray(t))return;const i=t;for(const[s,a]of Object.entries(r.properties)){if(!(s in i))continue;const o=i[s];a.pattern&&typeof o=="string"&&(new RegExp(a.pattern).test(o)||n.addIssue({code:Rc.custom,message:`String '${o}' does not match pattern '${a.pattern}'`,path:[s]}))}}static validateNestedConditions(t,r,n){if(!r.if||!r.then)return;this.matchesCondition(t,r.if)?this.validateConditionalSchema(t,r.then,n):r.else&&this.validateConditionalSchema(t,r.else,n)}static parseSchema(t){return Array.isArray(t.type)?this.handleTypeArray(t):t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.if&&t.then?this.parseObject(t):t.properties&&(!t.type||t.type==="object")?this.parseObject(t):this.handleSingleType(t)}static handleTypeArray(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");return t.type.includes("null")?this.handleNullableType(t):this.createUnionFromTypes(t.type,t)}static handleNullableType(t){if(!Array.isArray(t.type))throw new Error("Expected schema.type to be an array");const r={...t};return r.type=t.type.filter(i=>i!=="null"),r.type.length===1?this.handleSingleType({...t,type:r.type[0]}).nullable():this.parseSchema(r).nullable()}static createUnionFromTypes(t,r){const n=t.map(i=>{const s={...r,type:i};return this.parseSchema(s)});return jr(n)}static handleSingleType(t){if(t.type===void 0)return t.oneOf||t.anyOf||t.allOf?this.parseCombinator(t):t.properties?this.parseObject(t):Ut();switch(t.type){case"string":return this.parseString(t);case"number":case"integer":return this.parseNumberSchema(t);case"boolean":return Qf();case"array":return this.parseArray(t);case"object":return this.parseObject(t);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(t){let r=Xt(),n=r;return n=this.applyNumberBounds(r,t),n=this.applyNumberMultipleOf(r,t),n=this.applyNumberEnum(r,t),n=this.applyIntegerConstraint(r,t),n}static applyNumberBounds(t,r){let n=t;return r.minimum!==void 0&&(n=r.exclusiveMinimum?n.gt(r.minimum):n.gte(r.minimum)),r.maximum!==void 0&&(n=r.exclusiveMaximum?n.lt(r.maximum):n.lte(r.maximum)),n}static applyNumberMultipleOf(t,r){return r.multipleOf===void 0?t:t.refine(n=>n%r.multipleOf===0,{message:`Number must be a multiple of ${r.multipleOf}`})}static applyNumberEnum(t,r){if(!r.enum)return t;const n=r.enum.filter(i=>typeof i=="number");return n.length===0?t:t.refine(i=>n.includes(i),{message:`Number must be one of: ${n.join(", ")}`})}static applyIntegerConstraint(t,r){return r.type!=="integer"?t:t.refine(n=>Number.isInteger(n),{message:"Number must be an integer"})}static parseString(t){let r=nt(),n=r;return t.format?this.applyStringFormat(r,t):(n=this.applyStringPattern(r,t),n=this.applyStringLength(r,t),n=this.applyStringEnum(r,t),n)}static applyStringFormat(t,r){if(!r.format)return t;switch(r.format){case"email":return t.email();case"date-time":return t.datetime();case"uri":return t.url();case"uuid":return t.uuid();case"date":return t.date();default:return t}}static applyStringPattern(t,r){if(!r.pattern)return t;const n=new RegExp(r.pattern);return t.regex(n,{message:`String must match pattern: ${r.pattern}`})}static applyStringLength(t,r){let n=t;return r.minLength!==void 0&&(t=t.min(r.minLength)),r.maxLength!==void 0&&(t=t.max(r.maxLength)),n}static applyStringEnum(t,r){return r.enum?t.refine(n=>r.enum?.includes(n),{message:`Value must be one of: ${r.enum?.join(", ")}`}):t}static parseArray(t){if(Array.isArray(t.items)){const s=t.items.map(a=>this.parseSchema(a));return jr(s)}const r=t.items?this.parseSchema(t.items):Ut();let n=yn(r),i=n;return i=this.applyArrayConstraints(n,t),i}static applyArrayConstraints(t,r){return r.minItems!==void 0&&(t=t.min(r.minItems)),r.maxItems!==void 0&&(t=t.max(r.maxItems)),r.uniqueItems?t.refine(n=>new Set(n).size===n.length,{message:"Array items must be unique"}):t}static parseObject(t){if(t.if&&t.then)return this.parseConditional(t);const r={};return this.processObjectProperties(t,r),this.processAdditionalProperties(t,Pe(r))}static processObjectProperties(t,r){const n=new Set(t.required||[]);if(t.properties)for(const[i,s]of Object.entries(t.properties)){const a=this.parseSchema(s);r[i]=n.has(i)?a:a.optional()}}static processAdditionalProperties(t,r){if(t.additionalProperties===!0)return r.passthrough();if(t.additionalProperties&&typeof t.additionalProperties=="object"){const n=this.parseSchema(t.additionalProperties);return r.catchall(n)}else return r.strict()}static parseConditional(t){const r=this.createBaseObjectSchema(t),n=t.if,i=t.then,s=t.else;return r.superRefine((a,o)=>{const c=this.applyDefaultValues(a,t);this.matchesCondition(c,n)?this.validateConditionalSchema(c,i,o):s&&this.validateConditionalSchema(c,s,o)})}static createBaseObjectSchema(t){const r={},n=new Set(t.required||[]);for(const[s,a]of Object.entries(t.properties||{})){const o=this.parseSchema(a);r[s]=n.has(s)?o:o.optional()}const i=Pe(r);return this.processAdditionalProperties(t,i)}static applyDefaultValues(t,r){if(typeof t!="object"||t===null||Array.isArray(t))return t;const i={...t};if(!r.properties)return i;for(const[s,a]of Object.entries(r.properties))!(s in i)&&"default"in a&&(i[s]=a.default);return i}static parseCombinator(t){if(t.oneOf)return this.parseOneOf(t.oneOf);if(t.anyOf)return this.parseAnyOf(t.anyOf);if(t.allOf)return this.parseAllOf(t.allOf);throw new Error("Unsupported schema type")}static parseOneOf(t){return this.createUnionFromSchemas(t)}static parseAnyOf(t){return this.createUnionFromSchemas(t)}static createUnionFromSchemas(t){if(t.length===0)return Ut();if(t.length===1)return this.parseSchema(t[0]);const r=[];for(const n of t)n.type==="null"?r.push(qS()):r.push(this.parseSchema(n));return r.length>=2?jr(r):r.length===1?r[0]:Ut()}static parseAllOf(t){if(t.length===0)return Ut();if(t.length===1)return this.parseSchema(t[0]);const r=t.reduce((n,i)=>this.mergeSchemas(n,i));return this.parseSchema(r)}static mergeSchemas(t,r){const n={...t,...r};if(t.properties&&r.properties){const i={...t.properties,...r.properties};n.properties=i}if(t.required&&r.required){const i=[...new Set([...t.required,...r.required])];n.required=i}return n}}var CC=Object.defineProperty,pe=(e,t)=>{for(var r in t)CC(e,r,{get:t[r],enumerable:!0})};function AC(e,t){return t?.[e]||QS(e)}function OC(e,t){return t?.[e]||XS(e)}function $_(e,t,r){const n={};for(const i in e)Object.hasOwn(e,i)&&(n[t(i,r)]=e[i]);return n}var L_={};pe(L_,{Serializable:()=>Qt,get_lc_unique_name:()=>lc});function Zm(e){return Array.isArray(e)?[...e]:{...e}}function xC(e,t){const r=Zm(e);for(const[n,i]of Object.entries(t)){const[s,...a]=n.split(".").reverse();let o=r;for(const c of a.reverse()){if(o[c]===void 0)break;o[c]=Zm(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[i]})}return r}function lc(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var Qt=class j_{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,lc(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof j_||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},r={},n=Object.keys(this.lc_kwargs).reduce((i,s)=>(i[s]=s in this?this[s]:this.lc_kwargs[s],i),{});for(let i=Object.getPrototypeOf(this);i;i=Object.getPrototypeOf(i))Object.assign(t,Reflect.get(i,"lc_aliases",this)),Object.assign(r,Reflect.get(i,"lc_secrets",this)),Object.assign(n,Reflect.get(i,"lc_attributes",this));return Object.keys(r).forEach(i=>{let s=this,a=n;const[o,...c]=i.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in a)||a[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?a[l]={}:Array.isArray(s[l])&&(a[l]=[])),s=s[l],a=a[l]}o in s&&s[o]!==void 0&&(a[o]=a[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:$_(Object.keys(r).length?xC(n,r):n,AC,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function hn(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function gd(e){return hn(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function yd(e){return hn(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function PC(e){return hn(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function D_(e){return hn(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function F_(e){if(hn(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function kC(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const r=t[0].trim(),n=t[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const i={};for(const s of e.split(";").slice(1)){const a=s.split("=");if(a.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=a[0].trim(),c=a[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);i[o]=c}return{type:r,subtype:n,parameters:i}}function Ku({dataUrl:e,asTypedArray:t=!1}){const r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();const i=t?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}function IC(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function he(e,t){return ge(e)&&e.type===t}function ge(e){return typeof e=="object"&&e!==null}function Sr(e){return Array.isArray(e)}function oe(e){return typeof e=="string"}function or(e){return typeof e=="number"}function _d(e){return e instanceof Uint8Array}function Ym(e){try{return JSON.parse(e)}catch{return}}const Is=e=>e();function MC(e){if(e.type==="char_location"&&oe(e.document_title)&&or(e.start_char_index)&&or(e.end_char_index)&&oe(e.cited_text)){const{document_title:t,start_char_index:r,end_char_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="page_location"&&oe(e.document_title)&&or(e.start_page_number)&&or(e.end_page_number)&&oe(e.cited_text)){const{document_title:t,start_page_number:r,end_page_number:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="content_block_location"&&oe(e.document_title)&&or(e.start_block_index)&&or(e.end_block_index)&&oe(e.cited_text)){const{document_title:t,start_block_index:r,end_block_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="web_search_result_location"&&oe(e.url)&&oe(e.title)&&oe(e.encrypted_index)&&oe(e.cited_text)){const{url:t,title:r,encrypted_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"url",url:t,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(e.type==="search_result_location"&&oe(e.source)&&oe(e.title)&&or(e.start_block_index)&&or(e.end_block_index)&&oe(e.cited_text)){const{source:t,title:r,start_block_index:n,end_block_index:i,cited_text:s,...a}=e;return{...a,type:"citation",source:"search",url:t,title:r??void 0,startIndex:n,endIndex:i,citedText:s}}}function U_(e){if(he(e,"document")&&ge(e.source)&&"type"in e.source){if(e.source.type==="base64"&&oe(e.source.media_type)&&oe(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&oe(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&oe(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&oe(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(he(e,"image")&&ge(e.source)&&"type"in e.source){if(e.source.type==="base64"&&oe(e.source.media_type)&&oe(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&oe(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&oe(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function RC(e){function*t(){for(const r of e){const n=U_(r);n?yield n:yield r}}return Array.from(t())}function Xm(e){function*t(){const r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const n of r){if(he(n,"text")&&oe(n.text)){const{text:i,citations:s,...a}=n;if(Sr(s)&&s.length){const o=s.reduce((c,l)=>{const u=MC(l);return u?[...c,u]:c},[]);yield{...a,type:"text",text:i,annotations:o};continue}else{yield{...a,type:"text",text:i};continue}}else if(he(n,"thinking")&&oe(n.thinking)){const{thinking:i,signature:s,...a}=n;yield{...a,type:"reasoning",reasoning:i,signature:s};continue}else if(he(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(he(n,"tool_use")&&oe(n.name)&&oe(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(he(n,"input_json_delta")){if($C(e)&&e.tool_call_chunks?.length){const i=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(he(n,"server_tool_use")&&oe(n.name)&&oe(n.id)){const{name:i,id:s}=n;if(i==="web_search"){const a=Is(()=>{if(typeof n.input=="string")return n.input;if(ge(n.input)&&oe(n.input.query))return n.input.query;if(oe(n.partial_json)){const o=Ym(n.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:a}};continue}else if(n.name==="code_execution"){const a=Is(()=>{if(typeof n.input=="string")return n.input;if(ge(n.input)&&oe(n.input.code))return n.input.code;if(oe(n.partial_json)){const o=Ym(n.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:a}};continue}}else if(he(n,"web_search_tool_result")&&oe(n.tool_use_id)&&Sr(n.content)){const{content:i,tool_use_id:s}=n,a=i.reduce((o,c)=>he(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:a}};continue}else if(he(n,"code_execution_tool_result")&&oe(n.tool_use_id)&&ge(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(he(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(he(n,"mcp_tool_result")&&oe(n.tool_use_id)&&ge(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(he(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(he(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(he(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{const i=U_(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}const NC={translateContent:Xm,translateContentChunk:Xm};function $C(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function LC(e){return gd(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:yd(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:D_(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function jC(e){return e.map(LC)}function DC(e){return!!(he(e,"image_url")&&ge(e.image_url)||he(e,"input_audio")&&ge(e.input_audio)||he(e,"file")&&ge(e.file))}function FC(e){if(he(e,"image_url")&&ge(e.image_url)&&oe(e.image_url.url)){const t=Ku({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(he(e,"input_audio")&&ge(e.input_audio)&&oe(e.input_audio.data)&&oe(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(he(e,"file")&&ge(e.file)&&oe(e.file.data)){const t=Ku({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(oe(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function UC(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...vd(e.content));for(const r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function BC(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...vd(e.content));for(const r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function vd(e){const t=[];for(const r of e)DC(r)?t.push(FC(r)):t.push(r);return t}function zC(e){if(e.type==="url_citation"){const{url:t,title:r,start_index:n,end_index:i}=e;return{type:"citation",url:t,title:r,startIndex:n,endIndex:i}}if(e.type==="file_citation"){const{file_id:t,filename:r,index:n}=e;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:t}}return e}function B_(e){function*t(){ge(e.additional_kwargs?.reasoning)&&Sr(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((i,s)=>ge(s)&&oe(s.text)?`${i}${s.text}`:i,"")});const r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const n of r)if(he(n,"text")){const{text:i,annotations:s,...a}=n;Array.isArray(s)?yield{...a,type:"text",text:String(i),annotations:s.map(zC)}:yield{...a,type:"text",text:String(i)}}for(const n of e.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(ge(e.additional_kwargs)&&Sr(e.additional_kwargs.tool_outputs))for(const n of e.additional_kwargs.tool_outputs){if(he(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(he(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(he(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(he(n,"code_interpreter_call")){if(oe(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),Sr(n.outputs)){const i=Is(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(const s of n.outputs)if(he(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:i??0,stderr:[0,void 0].includes(i)?void 0:String(s.logs),stdout:[0,void 0].includes(i)?String(s.logs):void 0}};continue}}continue}else if(he(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(he(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(he(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(he(n,"image_generation_call")){yield{type:"non_standard",value:n};continue}ge(n)&&(yield{type:"non_standard",value:n})}}return Array.from(t())}function qC(e){function*t(){yield*B_(e);for(const r of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(t())}const HC={translateContent:e=>typeof e.content=="string"?UC(e):B_(e),translateContentChunk:e=>typeof e.content=="string"?BC(e):qC(e)};function z_(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function GC(e,t="pretty"){return t==="pretty"?VC(e):JSON.stringify(e)}function VC(e){const t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),s=r.length%2===0?i:`${i}=`;if(t.push(`${i}${r}${s}`),e.type==="ai"){const a=e;if(a.tool_calls&&a.tool_calls.length>0){t.push("Tool Calls:");for(const o of a.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const a=e;a.name&&t.push(`Name: ${a.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
44
- `)}const eu=Symbol.for("langchain.message");function Bn(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(r=>hn(r))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?ra(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(r=>hn(r))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function q_(e,t){return e==="error"||t==="error"?"error":"success"}function WC(e,t){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=t)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,i+1));const s={};for(const a of Object.keys(n))s[a]=r(n[a],i+1);return s}return JSON.stringify(r(e,0),null,2)}var bt=class extends Qt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[eu]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[jC,vd,RC].reduce((n,i)=>i(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&eu in e&&e[eu]===!0&&z_(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=WC(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return GC(this,e)}};function JC(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function dt(e={},t={}){const r={...e};for(const[n,i]of Object.entries(t))if(r[n]==null)r[n]=i;else{if(i==null)continue;if(typeof r[n]!=typeof i||Array.isArray(r[n])!==Array.isArray(i))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?r[n]=i:r[n]+=i}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=dt(r[n],i);else if(Array.isArray(r[n]))r[n]=ra(r[n],i);else{if(r[n]===i)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function ra(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const r=[...e];for(const n of t)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){const i=r.findIndex(s=>{const a=typeof s=="object",o="index"in s&&s.index===n.index,c="id"in s&&"id"in n&&s?.id===n?.id,l=!("id"in s)||!s?.id||!("id"in n)||!n?.id;return a&&o&&(c||l)});i!==-1&&typeof r[i]=="object"&&r[i]!==null?r[i]=dt(r[i],n):r.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function H_(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
45
- Left ${typeof e}
46
- Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return ra(e,t);if(typeof e=="object"&&typeof t=="object")return dt(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
47
- Left ${e}
48
- Right ${t}`)}var _n=class extends bt{static isInstance(e){return super.isInstance(e)&&"concat"in e&&typeof e.concat=="function"}};function G_(e){return typeof e.role=="string"}function st(e){return typeof e?._getType=="function"}function Ms(e){return st(e)&&typeof e.concat=="function"}var V_={};pe(V_,{ToolMessage:()=>Ae,ToolMessageChunk:()=>na,defaultToolCallParser:()=>bd,isDirectToolOutput:()=>wd,isToolMessage:()=>Sd,isToolMessageChunk:()=>W_});function wd(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var Ae=class extends bt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,r){const n=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},na=class extends _n{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const t=this.constructor;return new t({content:Bn(this.content,e.content),additional_kwargs:dt(this.additional_kwargs,e.additional_kwargs),response_metadata:dt(this.response_metadata,e.response_metadata),artifact:H_(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:q_(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function bd(e){const t=[],r=[];for(const n of e)if(n.function){const i=n.function.name;try{const s=JSON.parse(n.function.arguments);t.push({name:i||"",args:s||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[t,r]}function Sd(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function W_(e){return e._getType()==="tool"}function Ss(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function KC(e){return!!(e&&typeof e=="object"&&"toolCall"in e&&e.toolCall!=null&&typeof e.toolCall=="object"&&"id"in e.toolCall&&typeof e.toolCall.id=="string")}var Rs=class extends Error{output;constructor(e,t){super(e),this.output=t}};function Zu(e,t=Bi){e=e.trim();const r=e.indexOf("```");if(r===-1)return t(e);let n=e.substring(r+3);n.startsWith(`json
49
- `)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
50
- `)&&(n=n.substring(1));const i=n.indexOf("```");let s=n;return i!==-1&&(s=n.substring(0,i)),t(s.trim())}function Bi(e){if(typeof e>"u")return null;try{return JSON.parse(e)}catch{}let t="";const r=[];let n=!1,i=!1;for(let s of e){if(n)s==='"'&&!i?n=!1:s===`
51
- `&&!i?s="\\n":s==="\\"?i=!i:i=!1;else if(s==='"')n=!0,i=!1;else if(s==="{")r.push("}");else if(s==="[")r.push("]");else if(s==="}"||s==="]")if(r&&r[r.length-1]===s)r.pop();else return null;t+=s}n&&(t+='"');for(let s=r.length-1;s>=0;s-=1)t+=r[s];try{return JSON.parse(t)}catch{return null}}function Ed(e){switch(e){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function ZC(e){if(ge(e.document)&&ge(e.document.source)){const t=ge(e.document)&&oe(e.document.format)?e.document.format:"",r=Ed(t);if(ge(e.document.source)){if(ge(e.document.source.s3Location)&&oe(e.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:e.document.source.s3Location.uri};if(_d(e.document.source.bytes))return{type:"file",mimeType:r,data:e.document.source.bytes};if(oe(e.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(e.document.source.text).toString("base64")};if(Sr(e.document.source.content)){const n=e.document.source.content.reduce((i,s)=>ge(s)&&oe(s.text)?i+s.text:i,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:e}}function YC(e){if(he(e,"image")&&ge(e.image)){const t=ge(e.image)&&oe(e.image.format)?e.image.format:"",r=Ed(t);if(ge(e.image.source)){if(ge(e.image.source.s3Location)&&oe(e.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:e.image.source.s3Location.uri};if(_d(e.image.source.bytes))return{type:"image",mimeType:r,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function XC(e){if(he(e,"video")&&ge(e.video)){const t=ge(e.video)&&oe(e.video.format)?e.video.format:"",r=Ed(t);if(ge(e.video.source)){if(ge(e.video.source.s3Location)&&oe(e.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:e.video.source.s3Location.uri};if(_d(e.video.source.bytes))return{type:"video",mimeType:r,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function Qm(e){function*t(){const r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const n of r){if(he(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(he(n,"citations_content")&&ge(n.citationsContent)){const i=Sr(n.citationsContent.content)?n.citationsContent.content.reduce((a,o)=>ge(o)&&oe(o.text)?a+o.text:a,""):"",s=Sr(n.citationsContent.citations)?n.citationsContent.citations.reduce((a,o)=>{if(ge(o)){const c=Sr(o.sourceContent)?o.sourceContent.reduce((u,d)=>ge(d)&&oe(d.text)?u+d.text:u,""):"",l=Is(()=>{if(ge(o.location)){const u=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(ge(u))return{source:or(u.documentIndex)?u.documentIndex.toString():void 0,startIndex:or(u.start)?u.start:void 0,endIndex:or(u.end)?u.end:void 0}}return{}});a.push({type:"citation",citedText:c,...l})}return a},[]):[];yield{type:"text",text:i,annotations:s};continue}else if(he(n,"document")&&ge(n.document)){yield ZC(n);continue}else if(he(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(he(n,"image")&&ge(n.image)){yield YC(n);continue}else if(he(n,"reasoning_content")&&oe(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(he(n,"text")&&oe(n.text)){yield{type:"text",text:n.text};continue}else if(he(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(he(n,"tool_call"))continue;if(he(n,"video")&&ge(n.video)){yield XC(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}const QC={translateContent:Qm,translateContentChunk:Qm};function eg(e){function*t(){const r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const n of r){if(he(n,"text")&&oe(n.text)){yield{type:"text",text:n.text};continue}else if(he(n,"inlineData")&&ge(n.inlineData)&&oe(n.inlineData.mimeType)&&oe(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(he(n,"functionCall")&&ge(n.functionCall)&&oe(n.functionCall.name)&&ge(n.functionCall.args)){yield{type:"tool_call",id:e.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(he(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(he(n,"fileData")&&ge(n.fileData)&&oe(n.fileData.mimeType)&&oe(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(he(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(he(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(t())}const eA={translateContent:eg,translateContentChunk:eg};function tg(e){function*t(){const r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const n of r){if(he(n,"reasoning")&&oe(n.reasoning)){const i=Is(()=>{const s=r.indexOf(n);if(Sr(e.additional_kwargs?.signatures)&&s>=0)return e.additional_kwargs.signatures.at(s)});oe(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(he(n,"text")&&oe(n.text)){yield{type:"text",text:n.text};continue}else if(he(n,"image_url")){if(oe(n.image_url))if(n.image_url.startsWith("data:")){const i=/^data:([^;]+);base64,(.+)$/,s=n.image_url.match(i);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(he(n,"media")&&oe(n.mimeType)&&oe(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(t())}const tA={translateContent:tg,translateContentChunk:tg};globalThis.lc_block_translators_registry??=new Map([["anthropic",NC],["bedrock-converse",QC],["google-genai",eA],["google-vertexai",tA],["openai",HC]]);function J_(e){return globalThis.lc_block_translators_registry.get(e)}function K_(e,t){return dt(e??{},t??{})}function Z_(e,t){const r={};return(e?.audio!==void 0||t?.audio!==void 0)&&(r.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(r.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(r.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(r.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(r.text=(e?.text??0)+(t?.text??0)),r}function rA(e,t){const r={...Z_(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(r.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(r.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),r}function nA(e,t){const r={...Z_(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(r.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),r}function Y_(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:rA(e?.input_token_details,t?.input_token_details),output_token_details:nA(e?.output_token_details,t?.output_token_details)}}var fe=class extends bt{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const r=t.additional_kwargs?.tool_calls,n=t.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
52
-
53
- Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){const[i,s]=bd(r);t.tool_calls=i??[],t.invalid_tool_calls=s??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){t.contentBlocks.push(...t.tool_calls.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));const i=t.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!t.tool_calls?.some(a=>a.id===s.id&&a.name===s.name));i.length>0&&(t.tool_calls=i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}}super(t),typeof t!="string"&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const t=J_(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const t=this.tool_calls.filter(r=>!e.some(n=>n.id===r.id&&n.name===r.name));e.push(...t.map(r=>({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function Td(e){return e._getType()==="ai"}function Yu(e){return e._getType()==="ai"}var qt=class extends _n{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const n=(e.tool_call_chunks??[]).reduce((a,o)=>{const c=a.findIndex(([l])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===l.id&&o.index===l.index:"id"in o&&o.id?o.id===l.id:"index"in o&&o.index!==void 0?o.index===l.index:!1);return c!==-1?a[c].push(o):a.push([o]),a},[]),i=[],s=[];for(const a of n){let o=null;const c=a[0]?.name??"",l=a.map(f=>f.args||"").join(""),u=l.length?l:"{}",d=a[0]?.id;try{if(o=Bi(u),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");i.push({name:c,args:o,id:d,type:"tool_call"})}catch{s.push({name:c,args:u,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:i,invalid_tool_calls:s,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const t=J_(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const t=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!t.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:Bn(this.content,e.content),additional_kwargs:dt(this.additional_kwargs,e.additional_kwargs),response_metadata:K_(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const n=ra(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Y_(this.usage_metadata,e.usage_metadata));const r=this.constructor;return new r(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},zn=class X_ extends bt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return X_}constructor(t,r){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:r}),super(t),this.role=t.role}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},uc=class extends _n{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){const t=this.constructor;return new t({content:Bn(this.content,e.content),additional_kwargs:dt(this.additional_kwargs,e.additional_kwargs),response_metadata:dt(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function iA(e){return e._getType()==="generic"}function sA(e){return e._getType()==="generic"}var fc=class extends bt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},dc=class extends _n{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){const t=this.constructor;return new t({content:Bn(this.content,e.content),additional_kwargs:dt(this.additional_kwargs,e.additional_kwargs),response_metadata:dt(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function aA(e){return e._getType()==="function"}function oA(e){return e._getType()==="function"}var je=class extends bt{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},ia=class extends _n{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Bn(this.content,e.content),additional_kwargs:dt(this.additional_kwargs,e.additional_kwargs),response_metadata:dt(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function cA(e){return e.getType()==="human"}function lA(e){return e.getType()==="human"}var He=class extends bt{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},jn=class extends _n{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Bn(this.content,e.content),additional_kwargs:dt(this.additional_kwargs,e.additional_kwargs),response_metadata:dt(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function uA(e){return e._getType()==="system"}function fA(e){return e._getType()==="system"}function hc(e,t){return e.lc_error_code=t,e.message=`${e.message}
54
-
55
- Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
56
- `,e}var sn=class extends bt{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}};const dA=e=>e();function hA(e){return Ss(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function pA(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function tu(e){let t,r;if(pA(e)){const n=e.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?t="user":n==="AIMessage"||n==="AIMessageChunk"?t="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?t="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?t="function":n==="ToolMessage"||n==="ToolMessageChunk"?t="tool":t="unknown",r=e.kwargs}else{const{type:n,...i}=e;t=n,r=i}if(t==="human"||t==="user")return new je(r);if(t==="ai"||t==="assistant"){const{tool_calls:n,...i}=r;if(!Array.isArray(n))return new fe(r);const s=n.map(hA);return new fe({...i,tool_calls:s})}else{if(t==="system")return new He(r);if(t==="developer")return new He({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in r)return new Ae({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(t==="remove"&&"id"in r&&typeof r.id=="string")return new sn({...r,id:r.id});throw hc(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
57
-
58
- Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Er(e){if(typeof e=="string")return new je(e);if(st(e))return e;if(Array.isArray(e)){const[t,r]=e;return tu({type:t,content:r})}else if(G_(e)){const{role:t,...r}=e;return tu({...r,type:t})}else return tu(e)}function Cd(e,t="Human",r="AI"){const n=[];for(const i of e){let s;if(i._getType()==="human")s=t;else if(i._getType()==="ai")s=r;else if(i._getType()==="system")s="System";else if(i._getType()==="tool")s="Tool";else if(i._getType()==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i._getType()}`);const a=i.name?`${i.name}, `:"",o=typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2);n.push(`${s}: ${a}${o}`)}return n.join(`
59
- `)}function mA(e){if(e.data!==void 0)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function Ad(e){const t=mA(e);switch(t.type){case"human":return new je(t.data);case"ai":return new fe(t.data);case"system":return new He(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new fc(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Ae(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new zn(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function gA(e){return e.map(Ad)}function yA(e){return e.map(t=>t.toDict())}function $o(e){const t=e._getType();if(t==="human")return new ia({...e});if(t==="ai"){let r={...e};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new qt({...r})}else{if(t==="system")return new jn({...e});if(t==="function")return new dc({...e});if(zn.isInstance(e))return new uc({...e});throw new Error("Unknown message type.")}}var _A={},Q_={};pe(Q_,{getEnv:()=>iv,getEnvironmentVariable:()=>Fr,getRuntimeEnvironment:()=>sv,isBrowser:()=>ev,isDeno:()=>pc,isJsDom:()=>rv,isNode:()=>nv,isWebWorker:()=>tv});const ev=()=>typeof window<"u"&&typeof window.document<"u",tv=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",rv=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),pc=()=>typeof Deno<"u",nv=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!pc(),iv=()=>{let e;return ev()?e="browser":nv()?e="node":tv()?e="webworker":rv()?e="jsdom":pc()?e="deno":e="other",e};let ru;function sv(){return ru===void 0&&(ru={library:"langchain-js",runtime:iv()}),ru}function Fr(e){try{return typeof process<"u"?_A?.[e]:pc()?Deno?.env.get(e):void 0}catch{return}}var nu,Ja,iu=0,su=0;function vA(e,t,r){var n=0,i=t||new Array(16);e=e||{};var s=e.node,a=e.clockseq;if(e._v6||(s||(s=nu),a==null&&(a=Ja)),s==null||a==null){var o=e.random||(e.rng||eE)();s==null&&(s=[o[0],o[1],o[2],o[3],o[4],o[5]],!nu&&!e._v6&&(s[0]|=1,nu=s)),a==null&&(a=(o[6]<<8|o[7])&16383,Ja===void 0&&!e._v6&&(Ja=a))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:su+1,u=c-iu+(l-su)/1e4;if(u<0&&e.clockseq===void 0&&(a=a+1&16383),(u<0||c>iu)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");iu=c,su=l,Ja=a,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;i[n++]=d>>>24&255,i[n++]=d>>>16&255,i[n++]=d>>>8&255,i[n++]=d&255;var f=c/4294967296*1e4&268435455;i[n++]=f>>>8&255,i[n++]=f&255,i[n++]=f>>>24&15|16,i[n++]=f>>>16&255,i[n++]=a>>>8|128,i[n++]=a&255;for(var h=0;h<6;++h)i[n+h]=s[h];return t||td(i)}function wA(e){var t=typeof e=="string"?tE(e):e,r=bA(t);return typeof e=="string"?td(r):r}function bA(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function rg(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function ng(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?rg(Object(r),!0).forEach(function(n){SA(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rg(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function SA(e,t,r){return(t=EA(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function EA(e){var t=TA(e,"string");return typeof t=="symbol"?t:t+""}function TA(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function CA(e={},t,r=0){var n=vA(ng(ng({},e),{},{_v6:!0}),new Uint8Array(16));return n=wA(n),td(n)}var av={};pe(av,{BaseCallbackHandler:()=>ns,callbackHandlerPrefersStreaming:()=>Od,isBaseCallbackHandler:()=>ov});var AA=class{};function Od(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var ns=class extends AA{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,lc(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Fr("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Qt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Qt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends ns{name=et();constructor(){super(),Object.assign(this,e)}}return new t}};const ov=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},OA="gen_ai.operation.name",xA="gen_ai.system",ig="gen_ai.request.model",PA="gen_ai.response.model",sg="gen_ai.usage.input_tokens",ag="gen_ai.usage.output_tokens",og="gen_ai.usage.total_tokens",kA="gen_ai.request.max_tokens",IA="gen_ai.request.temperature",MA="gen_ai.request.top_p",RA="gen_ai.request.frequency_penalty",NA="gen_ai.request.presence_penalty",$A="gen_ai.response.finish_reasons",LA="gen_ai.prompt",jA="gen_ai.completion",DA="gen_ai.request.extra_query",FA="gen_ai.request.extra_body",UA="gen_ai.serialized.name",BA="gen_ai.serialized.signature",zA="gen_ai.serialized.doc",qA="gen_ai.response.id",HA="gen_ai.response.service_tier",GA="gen_ai.response.system_fingerprint",VA="gen_ai.usage.input_token_details",WA="gen_ai.usage.output_token_details",JA="langsmith.trace.session_id",KA="langsmith.trace.session_name",ZA="langsmith.span.kind",YA="langsmith.trace.name",XA="langsmith.metadata",cg="langsmith.span.tags",QA="langsmith.request.streaming",eO="langsmith.request.headers",tO=(...e)=>fetch(...e),cv=Symbol.for("ls:fetch_implementation"),rO=()=>{const e=globalThis[cv];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},nO=e=>async(...t)=>{if(e||At("DEBUG")==="true"){const[n,i]=t;console.log(`→ ${i?.method||"GET"} ${n}`)}const r=await(globalThis[cv]??tO)(...t);return(e||At("DEBUG")==="true")&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},lv=()=>At("PROJECT")??Cr("LANGCHAIN_SESSION")??"default",uv="0.3.75";var Xu={};let mr;const iO=()=>typeof window<"u"&&typeof window.document<"u",sO=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",aO=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),fv=()=>typeof Deno<"u",oO=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!fv(),dv=()=>mr||(typeof Bun<"u"?mr="bun":iO()?mr="browser":oO()?mr="node":sO()?mr="webworker":aO()?mr="jsdom":fv()?mr="deno":mr="other",mr);let au;function hv(){if(au===void 0){const e=dv(),t=lO();au={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:uv,...t}}return au}function pv(){const e=cO(),t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,i]of Object.entries(e))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?t.revision_id=i:t[n]=i);return t}function cO(){const e={};try{if(typeof process<"u"&&Xu)for(const[t,r]of Object.entries(Xu))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&r!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof r=="string"?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch{}return e}function Cr(e){try{return typeof process<"u"?Xu?.[e]:void 0}catch{return}}function At(e){return Cr(`LANGSMITH_${e}`)||Cr(`LANGCHAIN_${e}`)}let ou;function lO(){if(ou!==void 0)return ou;const e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const r of e){const n=Cr(r);n!==void 0&&(t[r]=n)}return ou=t,t}function mv(){return Cr("OTEL_ENABLED")==="true"||At("OTEL_ENABLED")==="true"}class uO{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...r){!this.hasWarned&&mv()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}}class fO{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new uO})}getTracer(t,r){return this.mockTracer}getActiveSpan(){}setSpan(t,r){return t}getSpan(t){}setSpanContext(t,r){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}}class dO{active(){return{}}with(t,r){return r()}}const cu=Symbol.for("ls:otel_trace"),lu=Symbol.for("ls:otel_context"),lg=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),hO=new fO,pO=new dO;class mO{getTraceInstance(){return globalThis[cu]??hO}getContextInstance(){return globalThis[lu]??pO}initializeGlobalInstances(t){globalThis[cu]===void 0&&(globalThis[cu]=t.trace),globalThis[lu]===void 0&&(globalThis[lu]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[lg]=t}getDefaultOTLPTracerComponents(){return globalThis[lg]??void 0}}const xd=new mO;function gv(){return xd.getTraceInstance()}function gO(){return xd.getContextInstance()}function yO(){return xd.getDefaultOTLPTracerComponents()}const _O={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function vO(e){return _O[e]||e}class wO{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,r){for(const n of t)try{if(!n.run)continue;if(n.operation==="post"){const i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(t,r,n){const i=n&&gv().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,t)}catch(s){console.error(`Failed to create span for run ${t.id}:`,s);return}}finishSpanSetup(t,r,n){return this.setSpanAttributes(t,r,n),r.error?(t.setStatus({code:2}),t.recordException(new Error(r.error))):t.setStatus({code:1}),r.end_time&&t.end(new Date(r.end_time)),t}updateSpanForRun(t,r){try{const n=this.spans.get(t.id);if(!n){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(n,r,t),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});const i=r.end_time;i&&(n.end(new Date(i)),this.spans.delete(t.id))}catch(n){console.error(`Failed to update span for run ${t.id}:`,n)}}extractModelName(t){if(t.extra?.metadata){const r=t.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(t,r,n){if("run_type"in r&&r.run_type){t.setAttribute(ZA,r.run_type);const o=vO(r.run_type||"chain");t.setAttribute(OA,o)}"name"in r&&r.name&&t.setAttribute(YA,r.name),"session_id"in r&&r.session_id&&t.setAttribute(JA,r.session_id),"session_name"in r&&r.session_name&&t.setAttribute(KA,r.session_name),this.setGenAiSystem(t,r);const i=this.extractModelName(r);i&&t.setAttribute(ig,i),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&t.setAttribute(sg,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&t.setAttribute(ag,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&t.setAttribute(og,r.total_tokens),this.setInvocationParameters(t,r);const s=r.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&t.setAttribute(`${XA}.${o}`,String(c));const a=r.tags;if(a&&Array.isArray(a)?t.setAttribute(cg,a.join(", ")):a&&t.setAttribute(cg,String(a)),"serialized"in r&&typeof r.serialized=="object"){const o=r.serialized;o.name&&t.setAttribute(UA,String(o.name)),o.signature&&t.setAttribute(BA,String(o.signature)),o.doc&&t.setAttribute(zA,String(o.doc))}this.setIOAttributes(t,n)}setGenAiSystem(t,r){let n="langchain";const i=this.extractModelName(r);if(i){const s=i.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}t.setAttribute(xA,n)}setInvocationParameters(t,r){if(!r.extra?.metadata?.invocation_params)return;const n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&t.setAttribute(kA,n.max_tokens),n.temperature!==void 0&&t.setAttribute(IA,n.temperature),n.top_p!==void 0&&t.setAttribute(MA,n.top_p),n.frequency_penalty!==void 0&&t.setAttribute(RA,n.frequency_penalty),n.presence_penalty!==void 0&&t.setAttribute(NA,n.presence_penalty)}setIOAttributes(t,r){if(r.run.inputs)try{const n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&t.setAttribute(ig,n.model),n.stream!==void 0&&t.setAttribute(QA,n.stream),n.extra_headers&&t.setAttribute(eO,JSON.stringify(n.extra_headers)),n.extra_query&&t.setAttribute(DA,JSON.stringify(n.extra_query)),n.extra_body&&t.setAttribute(FA,JSON.stringify(n.extra_body))),t.setAttribute(LA,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{const n=r.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(t.setAttribute(sg,i[0]),t.setAttribute(ag,i[1]),t.setAttribute(og,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&t.setAttribute(PA,String(n.model)),n.id&&t.setAttribute(qA,n.id),n.choices&&Array.isArray(n.choices)){const s=n.choices.map(a=>a.finish_reason).filter(a=>a).map(String);s.length>0&&t.setAttribute($A,s.join(", "))}if(n.service_tier&&t.setAttribute(HA,n.service_tier),n.system_fingerprint&&t.setAttribute(GA,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const s=n.usage_metadata;s.input_token_details&&t.setAttribute(VA,JSON.stringify(s.input_token_details)),s.output_token_details&&t.setAttribute(WA,JSON.stringify(s.output_token_details))}}t.setAttribute(jA,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(t){if(!t)return null;let r=this.extractUnifiedRunTokens(t.usage_metadata);if(r)return r;const n=Object.keys(t);for(const a of n){const o=t[a];if(!(!o||typeof o!="object")&&(r=this.extractUnifiedRunTokens(o.usage_metadata),r||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),r)))return r}const i=t.generations||[];if(!Array.isArray(i))return null;const s=Array.isArray(i[0])?i.flat():i;for(const a of s)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}}const bO=[429,500,502,503,504];let ug=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in Dr?this.queue=new Dr.default({concurrency:this.maxConcurrency}):this.queue=new Dr({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...r){const n=this.onFailedResponseHook;return this.queue.add(()=>xo(()=>t(...r).catch(i=>{throw i instanceof Error?i:new Error(i)}),{async onFailedAttempt(i){if(i.message.startsWith("Cancel")||i.message.startsWith("TimeoutError")||i.name==="TimeoutError"||i.message.startsWith("AbortError")||i?.code==="ECONNABORTED")throw i;const s=i?.response;if(n&&await n(s))return;const a=s?.status??i?.status;if(a&&!bO.includes(+a))throw i},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,r,...n){return t.signal?Promise.race([this.call(r,...n),new Promise((i,s)=>{t.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(r,...n)}};function fg(e){return typeof e?._getType=="function"}function dg(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}const SO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _e(e,t){if(!SO.test(e)){const r=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(r)}return e}const hg={};function Qu(e){hg[e]||(console.warn(e),hg[e]=!0)}function Jr(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){const[i,s]=t.split("/",2);if(!i||!s)throw new Error(`Invalid identifier format: ${e}`);return[i,s,n]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}}class EO extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function de(e,t,r){let n;if(e.ok){r&&(n=await e.text());return}if(e.status===403)try{(await e.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${e.status} ${e.statusText}`);throw o.status=e?.status,o}if(n===void 0)try{n=await e.text()}catch{n=""}const i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${n}`;if(e.status===409)throw new EO(i);const s=new Error(i);throw s.status=e.status,s}const yv="ERR_CONFLICTING_ENDPOINTS";class TO extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:yv}),this.name="ConflictingEndpointsError"}}function CO(e){return typeof e=="object"&&e!==null&&e.code===yv}var pg="[...]",AO={result:"[Circular]"},Lo=[],ri=[];const OO=new TextEncoder;function xO(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Ka(e){return OO.encode(e)}function _v(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function PO(e){return function(t,r){return _v(r)}}function jt(e,t,r,n,i){try{const s=JSON.stringify(e,PO(r),n);return Ka(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
60
- Context: ${t}`:""}`),Ka("[Unserializable]");At("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
61
- Context: ${t}`:""}`),typeof i>"u"&&(i=xO()),ef(e,"",0,[],void 0,0,i);let a;try{ri.length===0?a=JSON.stringify(e,r,n):a=JSON.stringify(e,kO(r),n)}catch{return Ka("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Lo.length!==0;){const o=Lo.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Ka(a)}}function uu(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:e}),Lo.push([n,r,t,i])):ri.push([t,r,e]):(n[r]=e,Lo.push([n,r,t]))}function ef(e,t,r,n,i,s,a){s+=1;var o;if(typeof e=="object"&&e!==null){for(o=0;o<n.length;o++)if(n[o]===e){uu(AO,e,t,i);return}if(typeof a.depthLimit<"u"&&s>a.depthLimit){uu(pg,e,t,i);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){uu(pg,e,t,i);return}if(n.push(e),Array.isArray(e))for(o=0;o<e.length;o++)ef(e[o],o,o,n,e,s,a);else{e=_v(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];ef(e[l],l,o,n,e,s,a)}}n.pop()}}function kO(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(ri.length>0)for(var n=0;n<ri.length;n++){var i=ri[n];if(i[1]===t&&i[0]===r){r=i[2],ri.splice(n,1);break}}return e.call(this,t,r)}}function mg(e,t){const r=hv(),n=t??pv(),i=e.extra??{},s=i.metadata;return e.extra={...i,runtime:{...r,...i?.runtime},metadata:{...n,...n.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??n.revision_id}:{},...s}},e}const IO=e=>{const t=e?.toString()??At("TRACING_SAMPLING_RATE");if(t===void 0)return;const r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},MO=e=>{const r=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function RO(e){const t=[];for await(const r of e)t.push(r);return t}function Za(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const NO=async e=>{if(e?.status===429){const t=parseInt(e.headers.get("retry-after")??"10",10)*1e3;if(t>0)return await new Promise(r=>setTimeout(r,t)),!0}return!1};function gg(e){return typeof e=="number"?Number(e.toFixed(4)):e}class $O{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(t){let r;const n=new Promise(s=>{r=s}),i=jt(t.item,`Serializing run with id: ${t.item.id}`).length;return this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n}pop({upToSizeBytes:t,upToSize:r}){if(t<1)throw new Error("Number of bytes to pop off may not be less than 1.");const n=[];let i=0;for(;i+(this.peek()?.size??0)<t&&this.items.length>0&&n.length<r;){const s=this.items.shift();s&&(n.push(s),i+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){const s=this.items.shift();n.push(s),i+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl})),()=>n.forEach(s=>s.itemPromiseResolve())]}}const LO=24*1024*1024,jO=1e4,DO=100,yg="https://api.smith.langchain.com";class zi{get _fetch(){return this.fetchImplementation||nO(this.debug)}constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new $O}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Cr("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Cr("LANGSMITH_DEBUG")==="true"});const r=zi.getDefaultClientConfig();if(this.tracingSampleRate=IO(t.tracingSamplingRate),this.apiUrl=Za(t.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Za(t.apiKey??r.apiKey),this.webUrl=Za(t.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Za(t.workspaceId??At("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new ug({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.batchIngestCaller=new ug({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:NO,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??r.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??r.hideOutputs,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,mv()&&(this.langSmithToOTELTranslator=new wO),this.cachedLSEnvVarsForMetadata=pv()}static getDefaultClientConfig(){const t=At("API_KEY"),r=At("ENDPOINT")??yg,n=At("HIDE_INPUTS")==="true",i=At("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:t,webUrl:void 0,hideInputs:n,hideOutputs:i}}getHostUrl(){return this.webUrl?this.webUrl:MO(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const t={"User-Agent":`langsmith-js/${uv}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}_getPlatformEndpointPath(t){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${t}`:`/platform/${t}`}async processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}async processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}async prepareRunCreateOrUpdateInputs(t){const r={...t};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(t,r){const n=r?.toString()??"",i=`${this.apiUrl}${t}?${n}`;return await this.caller.call(async()=>{const a=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(a,`fetch ${t}`),a})}async _get(t,r){return(await this._getResponse(t,r)).json()}async*_getPaginated(t,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0;const s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(s));const a=`${this.apiUrl}${t}?${r}`,o=await this.caller.call(async()=>{const l=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(l,`fetch ${t}`),l}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<s))break;i+=c.length}}async*_getCursorPaginatedList(t,r=null,n="POST",i="runs"){const s=r?{...r}:{};for(;;){const a=JSON.stringify(s),c=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}${t}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(u,`fetch ${t}`),u})).json();if(!c||!c[i])break;yield c[i];const l=c.cursors;if(!l||!l.next)break;s.cursor=l.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(t,r=!1){if(this.tracingSampleRate===void 0)return t;if(r){const n=[];for(const i of t)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):n.push(i);return n}else{const n=[];for(const i of t){const s=i.trace_id??i.id;this.filteredPostUuids.has(s)||(i.id===s?this._shouldSample()?n.push(i):this.filteredPostUuids.add(s):n.push(i))}return n}}async _getBatchSizeLimitBytes(){const t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t.batch_ingest_config?.size_limit_bytes??LO}async _getBatchSizeLimit(){const t=await this._ensureServerInfo();return this.batchSizeLimit??t.batch_ingest_config?.size_limit??DO}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r}){const n=[];for(;this.autoBatchQueue.items.length>0;){const[i,s]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:r});if(!i.length){s();break}const a=i.reduce((l,u)=>{const d=u.apiUrl??this.apiUrl,f=u.apiKey??this.apiKey,p=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${d}|${f}`;return l[p]||(l[p]=[]),l[p].push(u),l},{}),o=[];for(const[l,u]of Object.entries(a)){const d=this._processBatch(u,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(s);n.push(c)}return Promise.all(n)}async _processBatch(t,r){if(t.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(t);else{const n={runCreates:t.filter(s=>s.action==="create").map(s=>s.item),runUpdates:t.filter(s=>s.action==="update").map(s=>s.item)},i=await this._ensureServerInfo();if(i?.batch_ingest_config?.use_multipart_endpoint){const s=i?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(n,{...r,useGzip:s})}else await this.batchIngestRuns(n,r)}}catch(n){console.error("Error exporting batch:",n)}}_sendBatchToOTELTranslator(t){if(this.langSmithToOTELTranslator!==void 0){const r=new Map,n=[];for(const i of t)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=mg(t.item,this.cachedLSEnvVarsForMetadata);const r=this.autoBatchQueue.push(t);if(this.manualFlushMode)return r;const n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){const r=await(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(jO),...this.fetchOptions});return await de(n,"get server info"),n})).json();return this.debug&&console.log(`
62
- === LangSmith Server Configuration ===
63
- `+JSON.stringify(r,null,2)+`
64
- `),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const t=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r})}_cloneCurrentOTELContext(){const t=gv(),r=gO();if(this.langSmithToOTELTranslator!==void 0){const n=t.getActiveSpan();if(n)return t.setSpan(r.active(),n)}}async createRun(t,r){if(!this._filterForSampling([t]).length)return;const n={...this.headers,"Content-Type":"application/json"},i=t.project_name;delete t.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:i,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const a=mg(s,this.cachedLSEnvVarsForMetadata);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);const o=jt(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await de(c,"create run",!0),c})}async batchIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;let i=await Promise.all(t?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(i.length>0&&s.length>0){const c=i.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),l=[];for(const u of s)u.id!==void 0&&c[u.id]?c[u.id]={...c[u.id],...u}:l.push(u);i=Object.values(c),s=l}const a={post:i,patch:s};if(!a.post.length&&!a.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const l=c,u=a[l].reverse();let d=u.pop();for(;d!==void 0;)o[l].push(d),d=u.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(l=>l.id).concat(o.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(jt(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(t,r){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.call(async()=>{const i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await de(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;const i={};let s=[];for(const d of t??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(i[f.id]=f.attachments),delete f.attachments,s.push(f)}let a=[];for(const d of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&a.length>0){const d=s.reduce((h,p)=>(p.id&&(h[p.id]=p),h),{}),f=[];for(const h of a)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);s=Object.values(d),a=f}if(s.length===0&&a.length===0)return;const l=[],u=[];for(const[d,f]of[["post",s],["patch",a]])for(const h of f){const{inputs:p,outputs:m,events:w,extra:y,error:g,serialized:_,attachments:b,...A}=h,P={inputs:p,outputs:m,events:w,extra:y,error:g,serialized:_},x=jt(A,`Serializing for multipart ingestion of run with id: ${A.id}`);u.push({name:`${d}.${A.id}`,payload:new Blob([x],{type:`application/json; length=${x.length}`})});for(const[T,R]of Object.entries(P)){if(R===void 0)continue;const M=jt(R,`Serializing ${T} for multipart ingestion of run with id: ${A.id}`);u.push({name:`${d}.${A.id}.${T}`,payload:new Blob([M],{type:`application/json; length=${M.length}`})})}if(A.id!==void 0){const T=i[A.id];if(T){delete i[A.id];for(const[R,M]of Object.entries(T)){let U,H;if(Array.isArray(M)?[U,H]=M:(U=M.mimeType,H=M.data),R.includes(".")){console.warn(`Skipping attachment '${R}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${A.id}.${R}`,payload:new Blob([H],{type:`${U}; length=${H.byteLength}`})})}}}l.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(u,l.join("; "),n)}async _createNodeFetchBody(t,r){const n=[];for(const a of t)n.push(new Blob([`--${r}\r
65
- `])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
66
- `,`Content-Type: ${a.payload.type}\r
67
- \r
68
- `])),n.push(a.payload),n.push(new Blob([`\r
69
- `]));return n.push(new Blob([`--${r}--\r
70
- `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(t,r){const n=new TextEncoder;return new ReadableStream({async start(s){const a=async o=>{typeof o=="string"?s.enqueue(n.encode(o)):s.enqueue(o)};for(const o of t){await a(`--${r}\r
71
- `),await a(`Content-Disposition: form-data; name="${o.name}"\r
72
- `),await a(`Content-Type: ${o.payload.type}\r
73
- \r
74
- `);const l=o.payload.stream().getReader();try{let u;for(;!(u=await l.read()).done;)s.enqueue(u.value)}finally{l.releaseLock()}await a(`\r
75
- `)}await a(`--${r}--\r
76
- `),s.close()}})}async _sendMultipartRequest(t,r,n){const i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=rO(),a=()=>this._createNodeFetchBody(t,i),o=()=>this._createMultipartStream(t,i),c=async l=>this.batchIngestCaller.call(async()=>{const u=await l(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(f=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const h=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(h,"Failed to send multipart request",!0),h});try{let l,u=!1;!s&&!this.multipartStreamingDisabled&&dv()!=="bun"?(u=!0,l=await c(o)):l=await c(a),(!this.multipartStreamingDisabled||u)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==yg&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=await c(a))}catch(l){console.warn(`${l.message.trim()}
77
-
78
- Context: ${r}`)}}async updateRun(t,r,n){_e(t),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));const i={...r,id:t};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const s={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);const a=jt(r,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{const o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(o,"update run",!0),o})}async readRun(t,{loadChildRuns:r}={loadChildRuns:!1}){_e(t);let n=await this._get(`/runs/${t}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:t,run:r,projectOpts:n}){if(r!==void 0){let i;r.session_id?i=r.session_id:n?.projectName?i=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?i=n?.projectId:i=(await this.readProject({projectName:At("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${i}/r/${r.id}?poll=true`}else if(t!==void 0){const i=await this.readRun(t);if(!i.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){const r=await RO(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),n={},i={};r.sort((s,a)=>(s?.dotted_order??"").localeCompare(a?.dotted_order??""));for(const s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(t.dotted_order??"")&&s.id!==t.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),i[s.id]=s)}t.child_runs=n[t.id]||[];for(const s in n)s!==t.id&&(i[s].child_runs=n[s]);return t}async*listRuns(t){const{projectId:r,projectName:n,parentRunId:i,traceId:s,referenceExampleId:a,startTime:o,executionOrder:c,isRoot:l,runType:u,error:d,id:f,query:h,filter:p,traceFilter:m,treeFilter:w,limit:y,select:g,order:_}=t;let b=[];if(r&&(b=Array.isArray(r)?r:[r]),n){const T=Array.isArray(n)?n:[n],R=await Promise.all(T.map(M=>this.readProject({projectName:M}).then(U=>U.id)));b.push(...R)}const A=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],P={session:b.length?b:null,run_type:u,reference_example:a,query:h,filter:p,trace_filter:m,tree_filter:w,execution_order:c,parent_run:i,start_time:o?o.toISOString():null,error:d,id:f,limit:y,trace:s,select:g||A,is_root:l,order:_};P.select.includes("child_run_ids")&&Qu("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let x=0;for await(const T of this._getCursorPaginatedList("/runs/query",P))if(y){if(x>=y)break;if(T.length+x>y){yield*T.slice(0,y-x);break}x+=T.length,yield*T}else yield*T}async*listGroupRuns(t){const{projectId:r,projectName:n,groupBy:i,filter:s,startTime:a,endTime:o,limit:c,offset:l}=t,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:s,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(l)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const m={...d,offset:f},w=Object.fromEntries(Object.entries(m).filter(([P,x])=>x!==void 0)),y=JSON.stringify(w),_=await(await this.caller.call(async()=>{const P=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await de(P,`Failed to fetch ${h}`),P})).json(),{groups:b,total:A}=_;if(b.length===0)break;for(const P of b)yield P;if(f+=b.length,f>=A)break}}async getRunStats({id:t,trace:r,parentRun:n,runType:i,projectNames:s,projectIds:a,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:d,filter:f,traceFilter:h,treeFilter:p,isRoot:m,dataSourceType:w}){let y=a||[];s&&(y=[...a||[],...await Promise.all(s.map(x=>this.readProject({projectName:x}).then(T=>T.id)))]);const _=Object.fromEntries(Object.entries({id:t,trace:r,parent_run:n,run_type:i,session:y,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:f,trace_filter:h,tree_filter:p,is_root:m,data_source_type:w}).filter(([x,T])=>T!==void 0)),b=JSON.stringify(_);return await(await this.caller.call(async()=>{const x=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await de(x,"get run stats"),x})).json()}async shareRun(t,{shareId:r}={}){const n={run_id:t,share_token:r||et()};_e(t);const i=JSON.stringify(n),a=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await de(o,"share run"),o})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(t){_e(t),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(r,"unshare run",!0),r})}async readRunSharedLink(t){_e(t);const n=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(t,{runIds:r}={}){const n=new URLSearchParams({share_token:t});if(r!==void 0)for(const a of r)n.append("id",a);return _e(t),await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${t}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(a,"list shared runs"),a})).json()}async readDatasetSharedSchema(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id),_e(t);const i=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id);const n={dataset_id:t};_e(t);const i=JSON.stringify(n),a=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await de(o,"share dataset"),o})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(t){_e(t),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(r,"unshare dataset",!0),r})}async readSharedDataset(t){return _e(t),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(i,"read shared dataset"),i})).json()}async listSharedExamples(t,r){const n={};r?.exampleIds&&(n.id=r.exampleIds);const i=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(l=>i.append(o,l)):i.append(o,c)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${t}/examples?${i.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(o,"list shared examples"),o}),a=await s.json();if(!s.ok)throw"detail"in a?new Error(`Failed to list shared examples.
79
- Status: ${s.status}
80
- Message: ${Array.isArray(a.detail)?a.detail.join(`
81
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return a.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:a=null}){const o=i?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,l=s||{};n&&(l.metadata=n);const u={name:t,extra:l,description:r};a!==null&&(u.reference_dataset_id=a);const d=JSON.stringify(u);return await(await this.caller.call(async()=>{const p=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await de(p,"create project"),p})).json()}async updateProject(t,{name:r=null,description:n=null,metadata:i=null,projectExtra:s=null,endTime:a=null}){const o=`${this.apiUrl}/sessions/${t}`;let c=s;i&&(c={...c||{},metadata:i});const l=JSON.stringify({name:r,extra:c,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await de(f,"update project"),f})).json()}async hasProject({projectId:t,projectName:r}){let n="/sessions";const i=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)_e(t),n+=`/${t}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(a,"has project"),a});try{const a=await s.json();return s.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:r,includeStats:n}){let i="/sessions";const s=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)_e(t),i+=`/${t}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());const a=await this._get(i,s);let o;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${t}, name=${r}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:t,projectName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:t,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:t,datasetName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:t,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const t=new URLSearchParams({limit:"1"});for await(const r of this._getPaginated("/sessions",t))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:s,includeStats:a,datasetVersion:o,referenceFree:c,metadata:l}={}){const u=new URLSearchParams;if(t!==void 0)for(const d of t)u.append("id",d);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),i!==void 0)u.append("reference_dataset",i);else if(s!==void 0){const d=await this.readDataset({datasetName:s});u.append("reference_dataset",d.id)}a!==void 0&&u.append("include_stats",a.toString()),o!==void 0&&u.append("dataset_version",o),c!==void 0&&u.append("reference_free",c.toString()),l!==void 0&&u.append("metadata",JSON.stringify(l));for await(const d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:t,projectName:r}){let n;if(t===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?n=(await this.readProject({projectName:r})).id:n=t,_e(n),await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:t,fileName:r,inputKeys:n,outputKeys:i,description:s,dataType:a,name:o}){const c=`${this.apiUrl}/datasets/upload`,l=new FormData;return l.append("file",t,r),n.forEach(f=>{l.append("input_keys",f)}),i.forEach(f=>{l.append("output_keys",f)}),s&&l.append("description",s),a&&l.append("data_type",a),o&&l.append("name",o),await(await this.caller.call(async()=>{const f=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await de(f,"upload CSV"),f})).json()}async createDataset(t,{description:r,dataType:n,inputsSchema:i,outputsSchema:s,metadata:a}={}){const o={name:t,description:r,extra:a?{metadata:a}:void 0};n&&(o.data_type=n),i&&(o.inputs_schema_definition=i),s&&(o.outputs_schema_definition=s);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await de(d,"create dataset"),d})).json()}async readDataset({datasetId:t,datasetName:r}){let n="/datasets";const i=new URLSearchParams({limit:"1"});if(t&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(t)_e(t),n+=`/${t}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(n,i);let a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${t}, name=${r}] not found`);a=s[0]}else a=s;return a}async hasDataset({datasetId:t,datasetName:r}){try{return await this.readDataset({datasetId:t,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:t,datasetName:r,fromVersion:n,toVersion:i}){let s=t;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);const a=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:r}){const n="/datasets";if(t===void 0)if(r!==void 0)t=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${t}/openai_ft`)).text()).trim().split(`
82
- `).map(o=>JSON.parse(o))}async*listDatasets({limit:t=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:s,metadata:a}={}){const o="/datasets",c=new URLSearchParams({limit:t.toString(),offset:r.toString()});if(n!==void 0)for(const l of n)c.append("id",l);i!==void 0&&c.append("name",i),s!==void 0&&c.append("name_contains",s),a!==void 0&&c.append("metadata",JSON.stringify(a));for await(const l of this._getPaginated(o,c))yield*l}async updateDataset(t){const{datasetId:r,datasetName:n,...i}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const s=r??(await this.readDataset({datasetName:n})).id;_e(s);const a=JSON.stringify(i);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(c,"update dataset"),c})).json()}async updateDatasetTag(t){const{datasetId:r,datasetName:n,asOf:i,tag:s}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const a=r??(await this.readDataset({datasetName:n})).id;_e(a);const o=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await de(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:t,datasetName:r}){let n="/datasets",i=t;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)_e(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:t,datasetName:r,tag:n}){let i=t;if(!i&&!r)throw new Error("Must provide either datasetName or datasetId");if(i&&r)throw new Error("Must provide either datasetName or datasetId, not both");i||(i=(await this.readDataset({datasetName:r})).id),_e(i);const a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(c,"index dataset"),c})).json()}async similarExamples(t,r,n,{filter:i}={}){const s={limit:n,inputs:t};i!==void 0&&(s.filter=i),_e(r);const a=JSON.stringify(s);return(await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await de(l,"fetch similar examples"),l})).json()).examples}async createExample(t,r,n){if(_g(t)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:t.dataset_id;const s=r?n?.datasetName:t.dataset_name;if(i===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:s})).id);const a=(r?n?.createdAt:t.created_at)||new Date;let o;_g(t)?o=t:o={inputs:t,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};const c=await this._uploadExamplesMultipart(i,[o]);return await this.readExample(c.example_ids?.[0]??et())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];const g=t;let _=g[0].dataset_id;const b=g[0].dataset_name;if(_===void 0&&b===void 0)throw new Error("Must provide either datasetName or datasetId");if(_!==void 0&&b!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");_===void 0&&(_=(await this.readDataset({datasetName:b})).id);const A=await this._uploadExamplesMultipart(_,g);return await Promise.all(A.example_ids.map(x=>this.readExample(x)))}const{inputs:r,outputs:n,metadata:i,splits:s,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:l,exampleIds:u,datasetId:d,datasetName:f}=t;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const p=f;if(h===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:p})).id);const m=r.map((g,_)=>({dataset_id:h,inputs:g,outputs:n?.[_],metadata:i?.[_],split:s?.[_],id:u?.[_],attachments:l?.[_],source_run_id:a?.[_],use_source_run_io:o?.[_],use_source_run_attachments:c?.[_]})),w=await this._uploadExamplesMultipart(h,m);return await Promise.all(w.example_ids.map(g=>this.readExample(g)))}async createLLMExample(t,r,n){return this.createExample({input:t},{output:r},n)}async createChatExample(t,r,n){const i=t.map(a=>fg(a)?dg(a):a),s=fg(r)?dg(r):r;return this.createExample({input:i},{output:s},n)}async readExample(t){_e(t);const r=`/examples/${t}`,n=await this._get(r),{attachment_urls:i,...s}=n,a=s;return i&&(a.attachments=Object.entries(i).reduce((o,[c,l])=>(o[c.slice(11)]={presigned_url:l.presigned_url,mime_type:l.mime_type},o),{})),a}async*listExamples({datasetId:t,datasetName:r,exampleIds:n,asOf:i,splits:s,inlineS3Urls:a,metadata:o,limit:c,offset:l,filter:u,includeAttachments:d}={}){let f;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)f=t;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),p=i?typeof i=="string"?i:i?.toISOString():void 0;p&&h.append("as_of",p);const m=a??!0;if(h.append("inline_s3_urls",m.toString()),n!==void 0)for(const y of n)h.append("id",y);if(s!==void 0)for(const y of s)h.append("splits",y);if(o!==void 0){const y=JSON.stringify(o);h.append("metadata",y)}c!==void 0&&h.append("limit",c.toString()),l!==void 0&&h.append("offset",l.toString()),u!==void 0&&h.append("filter",u),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>h.append("select",y));let w=0;for await(const y of this._getPaginated("/examples",h)){for(const g of y){const{attachment_urls:_,...b}=g,A=b;_&&(A.attachments=Object.entries(_).reduce((P,[x,T])=>(P[x.slice(11)]={presigned_url:T.presigned_url,mime_type:T.mime_type||void 0},P),{})),yield A,w++}if(c!==void 0&&w>=c)break}}async deleteExample(t){_e(t);const r=`/examples/${t}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(n,`delete ${r}`,!0),n})}async updateExample(t,r){let n;r?n=t:n=t.id,_e(n);let i;r?i={id:n,...r}:i=t;let s;return i.dataset_id!==void 0?s=i.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[i])}async updateExamples(t){let r;return t[0].dataset_id===void 0?r=(await this.readExample(t[0].id)).dataset_id:r=t[0].dataset_id,this._updateExamplesMultipart(r,t)}async readDatasetVersion({datasetId:t,datasetName:r,asOf:n,tag:i}){let s;if(t?s=t:s=(await this.readDataset({datasetName:r})).id,_e(s),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");const a=new URLSearchParams;return n!==void 0&&a.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&a.append("tag",i),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:t,datasetName:r,asOf:n}){let i;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?i=(await this.readDataset({datasetName:r})).id:i=t,_e(i);const s=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&s.append("as_of",a),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:t,datasetName:r,splitName:n,exampleIds:i,remove:s=!1}){let a;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?a=(await this.readDataset({datasetName:r})).id:a=t,_e(a);const o={split_name:n,examples:i.map(l=>(_e(l),l)),remove:s},c=JSON.stringify(o);await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await de(l,"update dataset splits",!0),l})}async evaluateRun(t,r,{sourceInfo:n,loadChildRuns:i,referenceExample:s}={loadChildRuns:!1}){Qu("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let a;if(typeof t=="string")a=await this.readRun(t,{loadChildRuns:i});else if(typeof t=="object"&&"id"in t)a=t;else throw new Error(`Invalid run type: ${typeof t}`);a.reference_example_id!==null&&a.reference_example_id!==void 0&&(s=await this.readExample(a.reference_example_id));const o=await r.evaluateRun(a,s),[c,l]=await this._logEvaluationFeedback(o,a,n);return l[0]}async createFeedback(t,r,{score:n,value:i,correction:s,comment:a,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:l,feedbackId:u,feedbackConfig:d,projectId:f,comparativeExperimentId:h}){if(!t&&!f)throw new Error("One of runId or projectId must be provided");if(t&&f)throw new Error("Only one of runId or projectId can be provided");const p={type:c??"api",metadata:o??{}};l!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:l}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&_e(p.metadata.__run.run_id);const m={id:u??et(),run_id:t,key:r,score:gg(n),value:i,correction:s,comment:a,feedback_source:p,comparative_experiment_id:h,feedbackConfig:d,session_id:f},w=JSON.stringify(m),y=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const g=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:w});return await de(g,"create feedback",!0),g}),m}async updateFeedback(t,{score:r,value:n,correction:i,comment:s}){const a={};r!=null&&(a.score=gg(r)),n!=null&&(a.value=n),i!=null&&(a.correction=i),s!=null&&(a.comment=s),_e(t);const o=JSON.stringify(a);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await de(c,"update feedback",!0),c})}async readFeedback(t){_e(t);const r=`/feedback/${t}`;return await this._get(r)}async deleteFeedback(t){_e(t);const r=`/feedback/${t}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:t,feedbackKeys:r,feedbackSourceTypes:n}={}){const i=new URLSearchParams;if(t)for(const s of t)_e(s),i.append("run",s);if(r)for(const s of r)i.append("key",s);if(n)for(const s of n)i.append("source",s);for await(const s of this._getPaginated("/feedback",i))yield*s}async createPresignedFeedbackToken(t,r,{expiration:n,feedbackConfig:i}={}){const s={run_id:t,feedback_key:r,feedback_config:i};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};const a=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:t,experimentIds:r,referenceDatasetId:n,createdAt:i,description:s,metadata:a,id:o}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");const c={id:o,name:t,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(i??new Date)?.toISOString(),extra:{}};a&&(c.extra.metadata=a);const l=JSON.stringify(c);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await de(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(t){_e(t);const r=new URLSearchParams({run_id:t});for await(const n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(t){let r;return"results"in t?r=t.results:Array.isArray(t)?r=t:r=[t],r}async _logEvaluationFeedback(t,r,n){const i=this._selectEvalResults(t),s=[];for(const a of i){let o=n||{};a.evaluatorInfo&&(o={...a.evaluatorInfo,...o});let c=null;a.targetRunId?c=a.targetRunId:r&&(c=r.id),s.push(await this.createFeedback(c,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:o,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model"}))}return[i,s]}async logEvaluationFeedback(t,r,n){const[i]=await this._logEvaluationFeedback(t,r,n);return i}async*listAnnotationQueues(t={}){const{queueIds:r,name:n,nameContains:i,limit:s}=t,a=new URLSearchParams;r&&r.forEach((c,l)=>{_e(c,`queueIds[${l}]`),a.append("ids",c)}),n&&a.append("name",n),i&&a.append("name_contains",i),a.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",a))if(yield*c,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(t){const{name:r,description:n,queueId:i,rubricInstructions:s}=t,a={name:r,description:n,id:i||et(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(a).filter(([l,u])=>u!==void 0)));return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await de(l,"create annotation queue"),l})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${_e(t,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(t,r){const{name:n,description:i,rubricInstructions:s}=r,a=JSON.stringify({name:n,description:i,rubric_instructions:s});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${_e(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${_e(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(t,r){const n=JSON.stringify(r.map((i,s)=>_e(i,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/annotation-queues/${_e(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await de(i,"add runs to annotation queue",!0),i})}async getRunFromAnnotationQueue(t,r){const n=`/annotation-queues/${_e(t,"queueId")}/run`;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(t,r){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${_e(t,"queueId")}/runs/${_e(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${_e(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(t){const r=await this._getSettings();return t=="-"||r.tenant_handle===t}async _ownerConflictError(t,r){const n=await this._getSettings();return new Error(`Cannot ${t} for another tenant.
83
-
84
- Current tenant: ${n.tenant_handle}
85
-
86
- Requested tenant: ${r}`)}async _getLatestCommitHash(t){const n=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(t,r){const[n,i,s]=Jr(t),a=JSON.stringify({like:r});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${n}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(t){const[r,n,i]=Jr(t);if(await this._currentTenantIsOwner(r)){const s=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(const r of this._getPaginated(`/commits/${t}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(t){const r=new URLSearchParams;r.append("sort_field",t?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query);for await(const n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(t){const[r,n,i]=Jr(t),a=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await de(o,"get prompt"),o)}))?.json();return a?.repo?a.repo:null}async createPrompt(t,r){const n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
87
-
88
- creating a LangChain Hub handle.
89
- You can add a handle by creating a public prompt at:
90
-
91
- https://smith.langchain.com/prompts`);const[i,s,a]=Jr(t);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);const o={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(o),l=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await de(d,"create prompt"),d}),{repo:u}=await l.json();return u}async createCommit(t,r,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[i,s,a]=Jr(t),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:o},l=JSON.stringify(c),d=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${i}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await de(f,"create commit"),f})).json();return this._getPromptUrl(`${i}/${s}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(t,r=[]){return this._updateExamplesMultipart(t,r)}async _updateExamplesMultipart(t,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const a of r){const o=a.id,c={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=jt(c,`Serializing body for example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(n.append(o,u),a.inputs){const d=jt(a.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(a.outputs){const d=jt(a.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(a.attachments)for(const[d,f]of Object.entries(a.attachments)){let h,p;Array.isArray(f)?[h,p]=f:(h=f.mimeType,p=f.data);const m=new Blob([p],{type:`${h}; length=${p.byteLength}`});n.append(`${o}.attachment.${d}`,m)}if(a.attachments_operations){const d=jt(a.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}const i=t??r[0]?.dataset_id;return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await de(a,"update examples"),a})).json()}async uploadExamplesMultipart(t,r=[]){return this._uploadExamplesMultipart(t,r)}async _uploadExamplesMultipart(t,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const s of r){const a=(s.id??et()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=jt(o,`Serializing body for uploaded example with id: ${a}`),l=new Blob([c],{type:"application/json"});if(n.append(a,l),s.inputs){const u=jt(s.inputs,`Serializing inputs for uploaded example with id: ${a}`),d=new Blob([u],{type:"application/json"});n.append(`${a}.inputs`,d)}if(s.outputs){const u=jt(s.outputs,`Serializing outputs for uploaded example with id: ${a}`),d=new Blob([u],{type:"application/json"});n.append(`${a}.outputs`,d)}if(s.attachments)for(const[u,d]of Object.entries(s.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const p=new Blob([h],{type:`${f}; length=${h.byteLength}`});n.append(`${a}.attachment.${u}`,p)}}return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${t}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await de(s,"upload examples"),s})).json()}async updatePrompt(t,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[n,i]=Jr(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const a=JSON.stringify(s);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${n}/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await de(c,"update prompt"),c})).json()}async deletePrompt(t){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[r,n,i]=Jr(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(a,"delete prompt"),a})).json()}async pullPromptCommit(t,r){const[n,i,s]=Jr(t),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await de(c,"pull prompt commit"),c})).json();return{owner:n,repo:i,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(t,r){const n=await this.pullPromptCommit(t,{includeModel:r?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(t,r){return await this.promptExists(t)?r&&Object.keys(r).some(i=>i!=="object")&&await this.updatePrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(t,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,r={}){const{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[s,a]=this.parseTokenOrUrl(t,n),o=new zi({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(a),l=i||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}const u=await o.listSharedExamples(a),d=await this.createDataset(l,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(f=>f.inputs),outputs:u.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),f}}parseTokenOrUrl(t,r,n=2,i="dataset"){try{return _e(t),[r,t]}catch{}try{const a=new URL(t).pathname.split("/").filter(o=>o!=="");if(a.length>=n){const o=a[a.length-n];return[r,o]}else throw new Error(`Invalid public ${i} URL: ${t}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${t}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await yO()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function _g(e){return"dataset_id"in e||"dataset_name"in e}const FO=e=>!!["TRACING_V2","TRACING"].find(r=>At(r)==="true"),fu=Symbol.for("lc:context_variables");function UO(e){return e.replace(/[-:.]/g,"")}function vv(e,t,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0"),i=`${new Date(e).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:UO(i)+t,microsecondPrecisionDatestring:i}}class jo{constructor(t,r,n,i){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=t,this.tags=r,this.project_name=n,this.replicas=i}static fromHeader(t){const r=t.split(",");let n={},i=[],s,a;for(const o of r){const[c,l]=o.split("="),u=decodeURIComponent(l);c==="langsmith-metadata"?n=JSON.parse(u):c==="langsmith-tags"?i=u.split(","):c==="langsmith-project"?s=u:c==="langsmith-replicas"&&(a=JSON.parse(u))}return new jo(n,i,s,a)}toHeader(){const t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&t.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),t.join(",")}}class vt{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),wv(t)){Object.assign(this,{...t});return}const r=vt.getDefaultConfig(),{metadata:n,...i}=t,s=i.client??vt.getSharedClient(),a={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:a},Object.assign(this,{...r,...i,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=GO(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=vv(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=c}}set metadata(t){this.extra={...this.extra,metadata:{...this.extra?.metadata,...t}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:et(),run_type:"chain",project_name:lv(),child_runs:[],api_url:Cr("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Cr("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return vt.sharedClient||(vt.sharedClient=new zi),vt.sharedClient}createChild(t){const r=this.child_execution_order+1,n=new vt({...t,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});fu in this&&(n[fu]=this[fu]);const i=Symbol.for("lc:child_config"),s=t.extra?.[i]??this.extra[i];if(zO(s)){const c={...s},l=BO(c.callbacks)?c.callbacks.copy?.():void 0;l&&(Object.assign(l,{_parentRunId:n.id}),l.handlers?.find(bv)?.updateFromRunTree?.(n),c.callbacks=l),n.extra[i]=c}const a=new Set;let o=this;for(;o!=null&&!a.has(o.id);)a.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,r),o=o.parent_run;return this.child_runs.push(n),n}async end(t,r,n=Date.now(),i){this.outputs=this.outputs??t,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(t,r,n=!0){const i=t.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(const[o,c]of Object.entries(r))i.runtime[o]||(i.runtime[o]=c);let s,a;return n?(a=t.parent_run?.id??t.parent_run_id,s=[]):(s=t.child_runs.map(o=>this._convertToCreate(o,r,n)),a=void 0),{id:t.id,name:t.name,start_time:t._serialized_start_time??t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:i,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:s,parent_run_id:a,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments,events:t.events}}_remapForProject(t,r,n=!0){const i=this._convertToCreate(this,r,n);if(t===this.project_name)return i;const s=d=>xs(`${d}:${t}`,xs.DNS),a=s(i.id),o=i.trace_id?s(i.trace_id):void 0,c=i.parent_run_id?s(i.parent_run_id):void 0;let l;if(i.dotted_order){const d=qO(i.dotted_order),f=[];for(let p=0;p<d.length-1;p++){const[m,w]=d[p],y=s(w);f.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+y)}const[h]=d[d.length-1];f.push(h.toISOString().replace(/[-:]/g,"").replace(".","")+a),l=f.join(".")}else l=void 0;return{...i,id:a,trace_id:o,parent_run_id:c,dotted_order:l,session_name:t}}async postRun(t=!0){try{const r=hv();if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:i,apiUrl:s,workspaceId:a}of this.replicas){const o=this._remapForProject(n??this.project_name,r,!0);await this.client.createRun(o,{apiKey:i,apiUrl:s,workspaceId:a})}else{const n=this._convertToCreate(this,r,t);await this.client.createRun(n)}if(!t){Qu("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const n of this.child_runs)await n.postRun(!1)}}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(t){if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:n,apiUrl:i,workspaceId:s,updates:a}of this.replicas){const o=this._remapForProject(r??this.project_name),c={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...a};t?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:n,apiUrl:i,workspaceId:s})}else try{const r={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};t?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(t){this.events||(this.events=[]),typeof t=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:t}):this.events.push({...t,time:t.time??new Date().toISOString()})}static fromRunnableConfig(t,r){const n=t?.callbacks;let i,s,a,o=FO();if(n){const l=n?.getParentRunId?.()??"",u=n?.handlers?.find(d=>d?.name=="langchain_tracer");i=u?.getRun?.(l),s=u?.projectName,a=u?.client,o=o||!!u}return i?new vt({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:a,tracingEnabled:o,project_name:s,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(r):new vt({...r,client:a,tracingEnabled:o,project_name:s})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,r){const n="get"in t&&typeof t.get=="function"?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,i=n["langsmith-trace"];if(!i||typeof i!="string")return;const s=i.trim(),a=s.split(".").map(l=>{const[u,d]=l.split("Z");return{strTime:u,time:Date.parse(u+"Z"),uuid:d}}),o=a[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:o,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){const l=jo.fromHeader(n.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}return new vt(c)}toHeaders(t){const r={"langsmith-trace":this.dotted_order,baggage:new jo(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(t)for(const[n,i]of Object.entries(r))t.set(n,i);return r}}Object.defineProperty(vt,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function wv(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function bv(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function vg(e){return Array.isArray(e)&&e.some(t=>bv(t))}function BO(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function zO(e){return e!=null&&typeof e.callbacks=="object"&&(vg(e.callbacks?.handlers)||vg(e.callbacks))}function qO(e){return e.split(".").map(r=>{const n=r.slice(0,-36),i=r.slice(-36),s=parseInt(n.slice(0,4)),a=parseInt(n.slice(4,6))-1,o=parseInt(n.slice(6,8)),c=parseInt(n.slice(9,11)),l=parseInt(n.slice(11,13)),u=parseInt(n.slice(13,15)),d=parseInt(n.slice(15,21));return[new Date(s,a,o,c,l,u,d/1e3),i]})}function HO(){const e=Cr("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{const t=JSON.parse(e);if(Array.isArray(t)){const r=[];for(const n of t){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof t=="object"&&t!==null){VO(t);const r=[];for(const[n,i]of Object.entries(t)){const s=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:s,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof t}`),[]}catch(t){if(CO(t))throw t;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function GO(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):HO()}function VO(e){if(Object.keys(e).length>0&&At("ENDPOINT"))throw new TO}var Sv={};pe(Sv,{BaseTracer:()=>Hr,isBaseTracer:()=>ti});const WO=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function tf(e,t){if(e)return new vt({...e,start_time:e._serialized_start_time??e.start_time,parent_run:tf(t),child_runs:e.child_runs.map(r=>tf(r)).filter(r=>r!==void 0),extra:{...e.extra,runtime:sv()},tracingEnabled:!1})}function du(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function ti(e){return typeof e._addRunToRunMap=="function"}var Hr=class extends ns{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?WO(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
92
-
93
- ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=vv(new Date(e.start_time).getTime(),e.id,e.execution_order),n={...e},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i&&(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.dotted_order,t].join("."),n._serialized_start_time=r)):(n.trace_id=n.id,n.dotted_order=t,n._serialized_start_time=r),this.usesRunTreeMap){const s=tf(n,i);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(e){const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,i,s,a,o){const c=this._getExecutionOrder(n),l=Date.now(),u=a?{...i,metadata:a}:i,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:s||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,r,n,i,s,a,o){const c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,n,i,s,a,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,n,i,s,a,o){const c=this._getExecutionOrder(n),l=Date.now(),u=a?{...i,metadata:a}:i,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:s||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,r,n,i,s,a,o){const c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,n,i,s,a,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,n,i){const s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,t,r,n,i){const s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,t,r,n,i,s,a,o){const c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:a??"chain",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,r,n,i,s,a,o){const c=this.getRunById(r)??this._createRunForChainStart(e,t,r,n,i,s,a,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,n,i){const s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=du(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=du(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,t,r,n,i){const s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=du(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,t,r,n,i,s,a){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,n,i,s,a){const o=this.getRunById(r)??this._createRunForToolStart(e,t,r,n,i,s,a);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="chain")return;const n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,n,i,s,a){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,n,i,s,a){const o=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,n,i,s,a);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,n,i,s){const a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:s?.chunk}}),await this.onLLMNewToken?.(a,e,{chunk:s?.chunk}),a}},Ev={};pe(Ev,{ConsoleCallbackHandler:()=>rf});function mt(e,t){return`${e.open}${t}${e.close}`}function Jt(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function wg(e){return typeof e=="string"?e.trim():e==null?e:Jt(e,e.toString())}function Kr(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:Ct}=zy;var rf=class extends Hr{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const n=this.runMap.get(r.parent_run_id);if(n)t.push(n),r=n;else break}return t}getBreadcrumbs(e){const r=[...this.getParents(e).reverse(),e].map((n,i,s)=>{const a=`${n.execution_order}:${n.run_type}:${n.name}`;return i===s.length-1?mt(zy.bold,a):a}).join(" > ");return mt(Ct.grey,r)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Jt(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.cyan,"[chain/end]")} [${t}] [${Kr(e)}] Exiting Chain run with output: ${Jt(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.red,"[chain/error]")} [${t}] [${Kr(e)}] Chain run errored with error: ${Jt(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(n=>n.trim())}:e.inputs;console.log(`${mt(Ct.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Jt(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.cyan,"[llm/end]")} [${t}] [${Kr(e)}] Exiting LLM run with output: ${Jt(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.red,"[llm/error]")} [${t}] [${Kr(e)}] LLM run errored with error: ${Jt(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.green,"[tool/start]")} [${t}] Entering Tool run with input: "${wg(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.cyan,"[tool/end]")} [${t}] [${Kr(e)}] Exiting Tool run with output: "${wg(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.red,"[tool/error]")} [${t}] [${Kr(e)}] Tool run errored with error: ${Jt(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Jt(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.cyan,"[retriever/end]")} [${t}] [${Kr(e)}] Exiting Retriever run with output: ${Jt(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${mt(Ct.red,"[retriever/error]")} [${t}] [${Kr(e)}] Retriever run errored with error: ${Jt(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${mt(Ct.blue,"[agent/action]")} [${r}] Agent selected action: ${Jt(t.actions[t.actions.length-1],"[action]")}`)}};let hu;const Tv=()=>{if(hu===void 0){const e=Fr("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};hu=new zi(e)}return hu};let JO=class{getStore(){}run(t,r){return r()}};const pu=Symbol.for("ls:tracing_async_local_storage"),KO=new JO;let ZO=class{getInstance(){return globalThis[pu]??KO}initializeGlobalInstance(t){globalThis[pu]===void 0&&(globalThis[pu]=t)}};const YO=new ZO;function XO(e=!1){const t=YO.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
94
-
95
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function Pd(e){return typeof e=="function"&&"langsmith:traceable"in e}var Cv={};pe(Cv,{LangChainTracer:()=>co});var co=class Av extends Hr{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:r,projectName:n,client:i,replicas:s}=t;this.projectName=n??lv(),this.replicas=s,this.exampleId=r,this.client=i??Tv();const a=Av.getTraceableRunTree();a&&this.updateFromRunTree(a)}async persistRun(t){}async onRunCreate(t){await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){await this.getRunTreeWithTracingConfig(t.id)?.patchRun()}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let r=t;const n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();const i=[r];for(;i.length>0;){const s=i.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){const r=this.runTreeMap.get(t);if(r)return new vt({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return XO(!0)}catch{return}}};const Ov=Symbol.for("ls:tracing_async_local_storage"),kn=Symbol.for("lc:context_variables"),QO=e=>{globalThis[Ov]=e},qi=()=>globalThis[Ov];let In;function ex(){const e="default"in Dr?Dr.default:Dr;return new e({autoStart:!0,concurrency:1})}function tx(){return typeof In>"u"&&(In=ex()),In}async function Ze(e,t){if(t===!0){const r=qi();r!==void 0?await r.run(void 0,async()=>e()):await e()}else In=tx(),In.add(async()=>{const r=qi();r!==void 0?await r.run(void 0,async()=>e()):await e()})}async function rx(){const e=Tv();await Promise.allSettled([typeof In<"u"?In.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var xv={};pe(xv,{awaitAllCallbacks:()=>rx,consumeCallback:()=>Ze});const nx=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>Fr(r)==="true");function ix(e,t){const r=qi();if(r===void 0)throw new Error("Internal error: Global shared async local storage instance has not been initialized.");const n=r.getStore(),i={...n?.[kn]};i[e]=t;let s={};wv(n)&&(s=new vt(n)),s[kn]=i,r.enterWith(s)}function kd(e){const t=qi();return t===void 0?void 0:t.getStore()?.[kn]?.[e]}const sx=Symbol("lc:configure_hooks"),ax=()=>kd(sx)||[];var Pv={};pe(Pv,{BaseCallbackManager:()=>kv,BaseRunManager:()=>aa,CallbackManager:()=>St,CallbackManagerForChainRun:()=>Mv,CallbackManagerForLLMRun:()=>nf,CallbackManagerForRetrieverRun:()=>Iv,CallbackManagerForToolRun:()=>Rv,ensureHandler:()=>Ns,parseCallbackConfigArg:()=>sa});function sa(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var kv=class{setHandler(e){return this.setHandlers([e])}},aa=class{constructor(e,t,r,n,i,s,a,o){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=s,this.inheritableMetadata=a,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>Ze(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(s=>Ze(async()=>{try{await s.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}},Iv=class extends aa{getChild(e){const t=new St(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>Ze(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw r}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>Ze(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}},nf=class extends aa{async handleLLMNewToken(e,t,r,n,i,s){await Promise.all(this.handlers.map(a=>Ze(async()=>{if(!a.ignoreLLM)try{await a.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleLLMError(e,t,r,n,i){await Promise.all(this.handlers.map(s=>Ze(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleLLMEnd(e,t,r,n,i){await Promise.all(this.handlers.map(s=>Ze(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}},Mv=class extends aa{getChild(e){const t=new St(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,n,i){await Promise.all(this.handlers.map(s=>Ze(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleChainEnd(e,t,r,n,i){await Promise.all(this.handlers.map(s=>Ze(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>Ze(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>Ze(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},Rv=class extends aa{getChild(e){const t=new St(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>Ze(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>Ze(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},St=class ps extends kv{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,r,n=void 0,i=void 0,s=void 0,a=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(l,u)=>{const d=u===0&&n?n:et();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ti(f)&&f._createRunForLLMStart(t,[l],d,this._parentRunId,s,this.tags,this.metadata,c),Ze(async()=>{try{await f.handleLLMStart?.(t,[l],d,this._parentRunId,s,this.tags,this.metadata,c)}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new nf(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,r,n=void 0,i=void 0,s=void 0,a=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(l,u)=>{const d=u===0&&n?n:et();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return ti(f)&&f._createRunForChatModelStart(t,[l],d,this._parentRunId,s,this.tags,this.metadata,c),Ze(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(t,[l],d,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){const h=Cd(l);await f.handleLLMStart?.(t,[h],d,this._parentRunId,s,this.tags,this.metadata,c)}}catch(h){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${h}`),f.raiseError)throw h}},f.awaitHandlers)})),new nf(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,r,n=et(),i=void 0,s=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return ti(c)&&c._createRunForChainStart(t,r,n,this._parentRunId,this.tags,this.metadata,i,o),Ze(async()=>{try{await c.handleChainStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,i,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new Mv(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,r,n=et(),i=void 0,s=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return ti(c)&&c._createRunForToolStart(t,r,n,this._parentRunId,this.tags,this.metadata,o),Ze(async()=>{try{await c.handleToolStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new Rv(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,r,n=et(),i=void 0,s=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return ti(c)&&c._createRunForRetrieverStart(t,r,n,this._parentRunId,this.tags,this.metadata,o),Ze(async()=>{try{await c.handleRetrieverStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new Iv(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,r,n,i,s){await Promise.all(this.handlers.map(a=>Ze(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(t,r,n,this.tags,this.metadata)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}addHandler(t,r=!0){this.handlers.push(t),r&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(r=>r!==t),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==t)}setHandlers(t,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of t)this.addHandler(n,r)}addTags(t,r=!0){this.removeTags(t),this.tags.push(...t),r&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(r=>!t.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!t.includes(r))}addMetadata(t,r=!0){this.metadata={...this.metadata,...t},r&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(const r of Object.keys(t))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(t=[],r=!0){const n=new ps(this._parentRunId);for(const i of this.handlers){const s=this.inheritableHandlers.includes(i);n.addHandler(i,s)}for(const i of this.tags){const s=this.inheritableTags.includes(i);n.addTags([i],s)}for(const i of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},s)}for(const i of t)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(t){class r extends ns{name=et();constructor(){super(),Object.assign(this,t)}}const n=new this;return n.addHandler(new r),n}static configure(t,r,n,i,s,a,o){return this._configureSync(t,r,n,i,s,a,o)}static _configureSync(t,r,n,i,s,a,o){let c;(t||r)&&(Array.isArray(t)||!t?(c=new ps,c.setHandlers(t?.map(Ns)??[],!0)):c=t,c=c.copy(Array.isArray(r)?r.map(Ns):r?.handlers,!1));const l=Fr("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=co.getTraceableRunTree()?.tracingEnabled||nx(),d=u||(Fr("LANGCHAIN_TRACING")??!1);if(l||d){if(c||(c=new ps),l&&!c.handlers.some(f=>f.name===rf.prototype.name)){const f=new rf;c.addHandler(f,!0)}if(d&&!c.handlers.some(f=>f.name==="langchain_tracer")&&u){const f=new co;c.addHandler(f,!0)}if(u){const f=co.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(f))}}for(const{contextVar:f,inheritable:h=!0,handlerClass:p,envVar:m}of ax()){const w=m&&Fr(m)==="true"&&p;let y;const g=f!==void 0?kd(f):void 0;g&&ov(g)?y=g:w&&(y=new p({})),y!==void 0&&(c||(c=new ps),c.handlers.some(_=>_.name===y.name)||c.addHandler(y,h))}return(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(s||a)&&c&&(c.addMetadata(s??{}),c.addMetadata(a??{},!1)),c}};function Ns(e){return"name"in e?e:ns.fromMethods(e)}var Nv=class{getStore(){}run(e,t){return t()}enterWith(e){}};const ox=new Nv,bg=Symbol.for("lc:child_config");var cx=class{getInstance(){return qi()??ox}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[bg]}runWithConfig(e,t,r){const n=St._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),s=i.getStore(),a=n?.getParentRunId(),o=n?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return o&&a?c=o.getRunTreeWithTracingConfig(a):r||(c=new vt({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[bg]:e}),s!==void 0&&s[kn]!==void 0&&(c===void 0&&(c={}),c[kn]=s[kn]),i.run(c,t)}initializeGlobalInstance(e){qi()===void 0&&QO(e)}};const Ve=new cx;var $v={};pe($v,{AsyncLocalStorageProviderSingleton:()=>Ve,MockAsyncLocalStorage:()=>Nv,_CONTEXT_VARIABLES_KEY:()=>kn});const mu=25;async function Pt(e){return St._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Bt(...e){const t={};for(const r of e.filter(n=>!!n))for(const n of Object.keys(r))if(n==="metadata")t[n]={...t[n],...r[n]};else if(n==="tags"){const i=t[n]??[];t[n]=[...new Set(i.concat(r[n]??[]))]}else if(n==="configurable")t[n]={...t[n],...r[n]};else if(n==="timeout")t.timeout===void 0?t.timeout=r.timeout:r.timeout!==void 0&&(t.timeout=Math.min(t.timeout,r.timeout));else if(n==="signal")t.signal===void 0?t.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if(n==="callbacks"){const i=t.callbacks,s=r.callbacks;if(Array.isArray(s))if(!i)t.callbacks=s;else if(Array.isArray(i))t.callbacks=i.concat(s);else{const a=i.copy();for(const o of s)a.addHandler(Ns(o),!0);t.callbacks=a}else if(s)if(!i)t.callbacks=s;else if(Array.isArray(i)){const a=s.copy();for(const o of i)a.addHandler(Ns(o),!0);t.callbacks=a}else t.callbacks=new St(s._parentRunId,{handlers:i.handlers.concat(s.handlers),inheritableHandlers:i.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(i.tags.concat(s.tags))),inheritableTags:Array.from(new Set(i.inheritableTags.concat(s.inheritableTags))),metadata:{...i.metadata,...s.metadata}})}else{const i=n;t[i]=r[i]??t[i]}return t}const lx=new Set(["string","number","boolean"]);function Se(e){const t=Ve.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:n,runName:i,...s}=t;r=Object.entries(s).reduce((a,[o,c])=>(c!==void 0&&(a[o]=c),a),r)}if(e&&(r=Object.entries(e).reduce((n,[i,s])=>(s!==void 0&&(n[i]=s),n),r)),r?.configurable)for(const n of Object.keys(r.configurable))lx.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const n=AbortSignal.timeout(r.timeout);r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,n])):r.signal=n,delete r.timeout}return r}function ke(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:s,runId:a}={}){const o=Se(e);return t!==void 0&&(delete o.runName,o.callbacks=t),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),i!==void 0&&(o.runName=i),s!==void 0&&(o.configurable={...o.configurable,...s}),a!==void 0&&delete o.runId,o}function qr(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function pn(e,t){if(t===void 0)return e;let r;return Promise.race([e.catch(n=>{if(!t?.aborted)throw n}),new Promise((n,i)=>{r=()=>{i($s(t))},t.addEventListener("abort",r),t.aborted&&i($s(t))})]).finally(()=>t.removeEventListener("abort",r))}function $s(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}function We(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_zod"in t))return!1;const r=t._zod;return typeof r=="object"&&r!==null&&"def"in r}function Qe(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_def"in t)||"_zod"in t)return!1;const r=t._def;return typeof r=="object"&&r!=null&&"typeName"in r}function ux(e){return We(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Qe(e)}function qn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(We(e)||Qe(e))}function Lv(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function jv(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function fx(e){return!!(Lv(e)||jv(e))}async function Id(e,t){if(We(e))try{return{success:!0,data:await qy(e,t)}}catch(r){return{success:!1,error:r}}if(Qe(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function mc(e,t){if(We(e))return await qy(e,t);if(Qe(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function dx(e,t){if(We(e))try{return{success:!0,data:nd(e,t)}}catch(r){return{success:!1,error:r}}if(Qe(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function an(e,t){if(We(e))return nd(e,t);if(Qe(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Hi(e){if(We(e))return ot.get(e)?.description;if(Qe(e)||"description"in e&&typeof e.description=="string")return e.description}function hx(e){if(!qn(e))return!1;if(Qe(e)){const t=e._def;if(t.typeName==="ZodObject"){const r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(We(e)){const t=e._zod.def;if(t.type==="object"){const r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Md(e){return qn(e)?Qe(e)?e._def.typeName==="ZodString":We(e)?e._zod.def.type==="string":!1:!1}function Rd(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function Tr(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function gc(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Ot(e){return!!(Rd(e)||Tr(e))}function Ls(e){if(Qe(e))return e.shape;if(We(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Dv(e,t){if(Qe(e))return e.extend(t);if(We(e))return rE(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Nd(e){if(Qe(e))return e.partial();if(We(e))return nE(rd,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Do(e,t=!1){if(Qe(e))return e.strict();if(Tr(e)){const r=e._zod.def.shape;if(t)for(const[s,a]of Object.entries(e._zod.def.shape)){if(Tr(a)){const c=Do(a,t);r[s]=c}else if(gc(a)){let c=a._zod.def.element;Tr(c)&&(c=Do(c,t)),r[s]=fn(a,{...a._zod.def,element:c})}else r[s]=a;const o=ot.get(a);o&&ot.add(r[s],o)}const n=fn(e,{...e._zod.def,shape:r,catchall:iE(sE)}),i=ot.get(e);return i&&ot.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function sf(e,t=!1){if(Rd(e))return e.passthrough();if(Tr(e)){const r=e._zod.def.shape;if(t)for(const[s,a]of Object.entries(e._zod.def.shape)){if(Tr(a)){const c=sf(a,t);r[s]=c}else if(gc(a)){let c=a._zod.def.element;Tr(c)&&(c=sf(c,t)),r[s]=fn(a,{...a._zod.def,element:c})}else r[s]=a;const o=ot.get(a);o&&ot.add(r[s],o)}const n=fn(e,{...e._zod.def,shape:r,catchall:aE(oE)}),i=ot.get(e);return i&&ot.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function yc(e){if(Qe(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(We(e))try{const t=nd(e,void 0);return()=>t}catch{return}}function px(e){return Qe(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function mx(e){return We(e)&&e._zod.def.type==="pipe"}function ni(e,t=!1){if(Qe(e))return px(e)?ni(e._def.schema,t):e;if(We(e)){let r=e;if(mx(e)&&(r=ni(e._zod.def.in,t)),t){if(Tr(r)){const i=r._zod.def.shape;for(const[s,a]of Object.entries(r._zod.def.shape))i[s]=ni(a,t);r=fn(r,{...r._zod.def,shape:i})}else if(gc(r)){const i=ni(r._zod.def.element,t);r=fn(r,{...r._zod.def,element:i})}}const n=ot.get(e);return n&&ot.add(r,n),r}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Fv(e,t){if(Qe(e)){const r=Ls(e),n={};for(const[i,s]of Object.entries(r))t(i,s)?n[i]=s.optional():n[i]=s;return e.extend(n)}if(We(e)){const r=Ls(e),n={...e._zod.def.shape};for(const[a,o]of Object.entries(r))t(a,o)&&(n[a]=new rd({type:"optional",innerType:o}));const i=fn(e,{...e._zod.def,shape:n}),s=ot.get(e);return s&&ot.add(i,s),i}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}const gx=Symbol("Let zodToJsonSchema decide on which parser to use"),yx={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},_x=e=>({...yx,...e}),vx=e=>{const t=_x(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},Uv=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function It(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Uv(t,e.currentPath):t.join("/")}}function Bv(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Ie(e,t,r,n,i){e[t]=r,Bv(e,t,n,i)}function wx(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ie.ZodAny&&(r.items=Oe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ie(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ie(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ie(r,"minItems",e.exactLength.value,e.exactLength.message,t),Ie(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function bx(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Ie(r,"minimum",n.value,n.message,t):Ie(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ie(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ie(r,"maximum",n.value,n.message,t):Ie(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ie(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ie(r,"multipleOf",n.value,n.message,t);break}return r}function Sx(){return{type:"boolean"}}function zv(e,t){return Oe(e.type._def,t)}const Ex=(e,t)=>Oe(e.innerType._def,t);function qv(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(i=>qv(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Tx(e,t)}}const Tx=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":Ie(r,"minimum",n.value,n.message,t);break;case"max":Ie(r,"maximum",n.value,n.message,t);break}return r};function Cx(e,t){return{...Oe(e.innerType._def,t),default:e.defaultValue()}}function Ax(e,t){return t.effectStrategy==="input"?Oe(e.schema._def,t):It(t)}function Ox(e){return{type:"string",enum:Array.from(e.values)}}const xx=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Px(e,t){const r=[Oe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Oe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach(s=>{if(xx(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...c}=s;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function kx(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}let gu;const rr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(gu===void 0&&(gu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gu),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Hv(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":Ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":nr(r,"email",n.message,t);break;case"format:idn-email":nr(r,"idn-email",n.message,t);break;case"pattern:zod":gt(r,rr.email,n.message,t);break}break;case"url":nr(r,"uri",n.message,t);break;case"uuid":nr(r,"uuid",n.message,t);break;case"regex":gt(r,n.regex,n.message,t);break;case"cuid":gt(r,rr.cuid,n.message,t);break;case"cuid2":gt(r,rr.cuid2,n.message,t);break;case"startsWith":gt(r,RegExp(`^${yu(n.value,t)}`),n.message,t);break;case"endsWith":gt(r,RegExp(`${yu(n.value,t)}$`),n.message,t);break;case"datetime":nr(r,"date-time",n.message,t);break;case"date":nr(r,"date",n.message,t);break;case"time":nr(r,"time",n.message,t);break;case"duration":nr(r,"duration",n.message,t);break;case"length":Ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":gt(r,RegExp(yu(n.value,t)),n.message,t);break;case"ip":n.version!=="v6"&&nr(r,"ipv4",n.message,t),n.version!=="v4"&&nr(r,"ipv6",n.message,t);break;case"base64url":gt(r,rr.base64url,n.message,t);break;case"jwt":gt(r,rr.jwt,n.message,t);break;case"cidr":n.version!=="v6"&&gt(r,rr.ipv4Cidr,n.message,t),n.version!=="v4"&&gt(r,rr.ipv6Cidr,n.message,t);break;case"emoji":gt(r,rr.emoji(),n.message,t);break;case"ulid":gt(r,rr.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":nr(r,"binary",n.message,t);break;case"contentEncoding:base64":Ie(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":gt(r,rr.base64,n.message,t);break}break;case"nanoid":gt(r,rr.nanoid,n.message,t);break}return r}function yu(e,t){return t.patternStrategy==="escape"?Mx(e):e}const Ix=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mx(e){let t="";for(let r=0;r<e.length;r++)Ix.has(e[r])||(t+="\\"),t+=e[r];return t}function nr(e,t,r,n){e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ie(e,"format",t,r,n)}function gt(e,t,r,n){e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Sg(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ie(e,"pattern",Sg(t,n),r,n)}function Sg(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let i="",s=!1,a=!1,o=!1;for(let c=0;c<n.length;c++){if(s){i+=n[c],s=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){o?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],o=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
96
- ]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
97
- ]))`;continue}}if(r.s&&n[c]==="."){i+=a?`${n[c]}\r
98
- `:`[${n[c]}\r
99
- ]`;continue}i+=n[c],n[c]==="\\"?s=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Gv(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===ie.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??It(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ie.ZodString&&e.keyType._def.checks?.length){const{type:n,...i}=Hv(e.keyType._def,t);return{...r,propertyNames:i}}else{if(e.keyType?._def.typeName===ie.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ie.ZodBranded&&e.keyType._def.type._def.typeName===ie.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...i}=zv(e.keyType._def,t);return{...r,propertyNames:i}}}return r}function Rx(e,t){if(t.mapStrategy==="record")return Gv(e,t);const r=Oe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||It(t),n=Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||It(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Nx(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function $x(e){return e.target==="openAi"?void 0:{not:It({...e,currentPath:[...e.currentPath,"not"]})}}function Lx(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Fo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function jx(e,t){if(t.target==="openApi3")return Eg(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Fo&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((i,s)=>{const a=Fo[s._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((i,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":return s._def.value===null?[...i,"null"]:i;case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){const i=n.filter((s,a,o)=>o.indexOf(s)===a);return{type:i.length>1?i:i[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return Eg(e,t)}const Eg=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>Oe(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Dx(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Fo[e.innerType._def.typeName],nullable:!0}:{type:[Fo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=Oe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Oe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Fx(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",Bv(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Ie(r,"minimum",n.value,n.message,t):Ie(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ie(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ie(r,"maximum",n.value,n.message,t):Ie(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ie(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ie(r,"multipleOf",n.value,n.message,t);break}return r}function Ux(e,t){const r=t.target==="openAi",n={type:"object",properties:{}},i=[],s=e.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let l=zx(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=Oe(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(n.properties[o]=u,l||i.push(o))}i.length&&(n.required=i);const a=Bx(e,t);return a!==void 0&&(n.additionalProperties=a),n}function Bx(e,t){if(e.catchall._def.typeName!=="ZodNever")return Oe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function zx(e){try{return e.isOptional()}catch{return!0}}const qx=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Oe(e.innerType._def,t);const r=Oe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:It(t)},r]}:It(t)},Hx=(e,t)=>{if(t.pipeStrategy==="input")return Oe(e.in._def,t);if(t.pipeStrategy==="output")return Oe(e.out._def,t);const r=Oe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Oe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function Gx(e,t){return Oe(e.type._def,t)}function Vx(e,t){const n={type:"array",uniqueItems:!0,items:Oe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ie(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ie(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Wx(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Oe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Oe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Oe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Jx(e){return{not:It(e)}}function Kx(e){return It(e)}const Zx=(e,t)=>Oe(e.innerType._def,t),Yx=(e,t,r)=>{switch(t){case ie.ZodString:return Hv(e,r);case ie.ZodNumber:return Fx(e,r);case ie.ZodObject:return Ux(e,r);case ie.ZodBigInt:return bx(e,r);case ie.ZodBoolean:return Sx();case ie.ZodDate:return qv(e,r);case ie.ZodUndefined:return Jx(r);case ie.ZodNull:return Lx(r);case ie.ZodArray:return wx(e,r);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return jx(e,r);case ie.ZodIntersection:return Px(e,r);case ie.ZodTuple:return Wx(e,r);case ie.ZodRecord:return Gv(e,r);case ie.ZodLiteral:return kx(e,r);case ie.ZodEnum:return Ox(e);case ie.ZodNativeEnum:return Nx(e);case ie.ZodNullable:return Dx(e,r);case ie.ZodOptional:return qx(e,r);case ie.ZodMap:return Rx(e,r);case ie.ZodSet:return Vx(e,r);case ie.ZodLazy:return()=>e.getter()._def;case ie.ZodPromise:return Gx(e,r);case ie.ZodNaN:case ie.ZodNever:return $x(r);case ie.ZodEffects:return Ax(e,r);case ie.ZodAny:return It(r);case ie.ZodUnknown:return Kx(r);case ie.ZodDefault:return Cx(e,r);case ie.ZodBranded:return zv(e,r);case ie.ZodReadonly:return Zx(e,r);case ie.ZodCatch:return Ex(e,r);case ie.ZodPipeline:return Hx(e,r);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return(n=>{})()}};function Oe(e,t,r=!1){const n=t.seen.get(e);if(t.override){const o=t.override?.(e,t,n,r);if(o!==gx)return o}if(n&&!r){const o=Xx(n,t);if(o!==void 0)return o}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const s=Yx(e,e.typeName,t),a=typeof s=="function"?Oe(s(),t):s;if(a&&Qx(e,t,a),t.postProcess){const o=t.postProcess(a,e,t);return i.jsonSchema=a,o}return i.jsonSchema=a,a}const Xx=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Uv(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),It(t)):t.$refStrategy==="seen"?It(t):void 0}},Qx=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),eP=(e,t)=>{const r=vx(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:Oe(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??It(r)}),{}):void 0;const i=typeof t=="string"?t:t?.name,s=Oe(e._def,r,!1)??It(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const a=i===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};var Vv={};pe(Vv,{Validator:()=>id,deepCompareStrict:()=>Hy,toJsonSchema:()=>zt,validatesOnlyStrings:()=>Es});function zt(e){if(We(e)){const t=ni(e,!0);if(Tr(t)){const r=Do(t,!0);return Mh(r)}else return Mh(e)}return Qe(e)?eP(e):e}function Es(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>Es(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(r=>Es(r))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){const t=e.$ref,r=cE(e);return r[t]?Es(r[t]):!1}return!1}var Wv={};pe(Wv,{AsyncCaller:()=>oa});const tP=[400,401,402,403,404,405,406,407,409],rP=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;const t=e?.response?.status??e?.status;if(t&&tP.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const r=new Error(e?.message);throw r.name="InsufficientQuotaError",r}};var oa=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??rP;const t="default"in Dr?Dr.default:Dr;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>xo(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((n,i)=>{e.signal?.addEventListener("abort",()=>{i($s(e.signal))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},Jv={};pe(Jv,{AsyncGeneratorWithSetup:()=>vn,IterableReadableStream:()=>ht,atee:()=>$d,concat:()=>mn,pipeGeneratorWithSetup:()=>Kv});var ht=class af extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const r=t.getReader();return new af({start(n){return i();function i(){return r.read().then(({done:s,value:a})=>{if(s){n.close();return}return n.enqueue(a),i()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new af({async pull(r){const{value:n,done:i}=await t.next();i&&r.close(),r.enqueue(n)},async cancel(r){await t.return(r)}})}};function $d(e,t=2){const r=Array.from({length:t},()=>[]);return r.map(async function*(i){for(;;)if(i.length===0){const s=await e.next();for(const a of r)a.push(s)}else{if(i[0].done)return;yield i.shift().value}})}function mn(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){const r={...e};for(const[n,i]of Object.entries(t))n in r&&!Array.isArray(r[n])?r[n]=mn(r[n],i):r[n]=i;return r}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var vn=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{Ve.runWithConfig(qr(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(n=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ve.runWithConfig(qr(this.config),this.signal?async()=>pn(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function Kv(e,t,r,n,...i){const s=new vn({generator:t,startSetup:r,signal:n}),a=await s.setup;return{output:e(s,a,...i),setup:a}}/*!
100
- * https://github.com/Starcounter-Jack/JSON-Patch
101
- * (c) 2017-2022 Joachim Wester
102
- * MIT licensed
103
- */const nP=Object.prototype.hasOwnProperty;function of(e,t){return nP.call(e,t)}function cf(e){if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)of(e,r)&&t.push(r);return t}function fr(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function lf(e){let t=0;const r=e.length;let n;for(;t<r;){if(n=e.charCodeAt(t),n>=48&&n<=57){t++;continue}return!1}return!0}function Xn(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function iP(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function uf(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(uf(e[r]))return!0}else if(typeof e=="object"){const r=cf(e),n=r.length;for(var t=0;t<n;t++)if(uf(e[r[t]]))return!0}}return!1}function Tg(e,t){const r=[e];for(const n in t){const i=typeof t[n]=="object"?JSON.stringify(t[n],null,2):t[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
104
- `)}var sP=class extends Error{constructor(e,t,r,n,i){super(Tg(e,{name:t,index:r,operation:n,tree:i})),this.name=t,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=Tg(e,{name:t,index:r,operation:n,tree:i})}},Zv={};pe(Zv,{JsonPatchError:()=>qe,_areEquals:()=>js,applyOperation:()=>Mn,applyPatch:()=>Gi,applyReducer:()=>cP,deepClone:()=>aP,getValueByPointer:()=>Uo,validate:()=>Yv,validator:()=>Bo});const qe=sP,aP=fr,ii={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=Uo(r,this.path);n&&(n=fr(n));const i=Mn(r,{op:"remove",path:this.from}).removed;return Mn(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){const n=Uo(r,this.from);return Mn(r,{op:"add",path:this.path,value:fr(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:js(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var oP={add:function(e,t,r){return lf(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){var n=e.splice(t,1);return{newDocument:r,removed:n[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:ii.move,copy:ii.copy,test:ii.test,_get:ii._get};function Uo(e,t){if(t=="")return e;var r={op:"_get",path:t};return Mn(e,r),r.value}function Mn(e,t,r=!1,n=!0,i=!0,s=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):Bo(t,0)),t.path===""){let a={newDocument:e};if(t.op==="add")return a.newDocument=t.value,a;if(t.op==="replace")return a.newDocument=t.value,a.removed=e,a;if(t.op==="move"||t.op==="copy")return a.newDocument=Uo(e,t.from),t.op==="move"&&(a.removed=e),a;if(t.op==="test"){if(a.test=js(e,t.value),a.test===!1)throw new qe("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return a.newDocument=e,a}else{if(t.op==="remove")return a.removed=e,a.newDocument=null,a;if(t.op==="_get")return t.value=e,a;if(r)throw new qe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return a}}else{n||(e=fr(e));const o=(t.path||"").split("/");let c=e,l=1,u=o.length,d,f,h;for(typeof r=="function"?h=r:h=Bo;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=iP(f)),i&&(f=="__proto__"||f=="prototype"&&l>0&&o[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(c[f]===void 0?d=o.slice(0,l).join("/"):l==u-1&&(d=t.path),d!==void 0&&h(t,0,e,d)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!lf(f))throw new qe("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);lf(f)&&(f=~~f)}if(l>=u){if(r&&t.op==="add"&&f>c.length)throw new qe("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);const p=oP[t.op].call(t,c,f,e);if(p.test===!1)throw new qe("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return p}}else if(l>=u){const p=ii[t.op].call(t,c,f,e);if(p.test===!1)throw new qe("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return p}if(c=c[f],r&&l<u&&(!c||typeof c!="object"))throw new qe("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function Gi(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new qe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=fr(e));const s=new Array(t.length);for(let a=0,o=t.length;a<o;a++)s[a]=Mn(e,t[a],r,!0,i,a),e=s[a].newDocument;return s.newDocument=e,s}function cP(e,t,r){const n=Mn(e,t);if(n.test===!1)throw new qe("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function Bo(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new qe("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(ii[e.op]){if(typeof e.path!="string")throw new qe("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new qe('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new qe("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new qe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&uf(e.value))throw new qe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r){if(e.op=="add"){var i=e.path.split("/").length,s=n.split("/").length;if(i!==s+1&&i!==s)throw new qe("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==n)throw new qe("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if(e.op==="move"||e.op==="copy"){var a={op:"_get",path:e.from,value:void 0},o=Yv([a],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new qe("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new qe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function Yv(e,t,r){try{if(!Array.isArray(e))throw new qe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Gi(fr(t),fr(e),r||!0);else{r=r||Bo;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(i){if(i instanceof qe)return i;throw i}}function js(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var r=Array.isArray(e),n=Array.isArray(t),i,s,a;if(r&&n){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!js(e[i],t[i]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(e);if(s=o.length,s!==Object.keys(t).length)return!1;for(i=s;i--!==0;)if(!t.hasOwnProperty(o[i]))return!1;for(i=s;i--!==0;)if(a=o[i],!js(e[a],t[a]))return!1;return!0}return e!==e&&t!==t}function Xv(e,t,r,n,i){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=cf(t),a=cf(e),o=!1,c=a.length-1;c>=0;c--){var l=a[c],u=e[l];if(of(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u=="object"&&u!=null&&typeof d=="object"&&d!=null&&Array.isArray(u)===Array.isArray(d)?Xv(u,d,r,n+"/"+Xn(l),i):u!==d&&(i&&r.push({op:"test",path:n+"/"+Xn(l),value:fr(u)}),r.push({op:"replace",path:n+"/"+Xn(l),value:fr(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&r.push({op:"test",path:n+"/"+Xn(l),value:fr(u)}),r.push({op:"remove",path:n+"/"+Xn(l)}),o=!0):(i&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}))}if(!(!o&&s.length==a.length))for(var c=0;c<s.length;c++){var l=s[c];!of(e,l)&&t[l]!==void 0&&r.push({op:"add",path:n+"/"+Xn(l),value:fr(t[l])})}}}function _c(e,t,r=!1){var n=[];return Xv(e,t,n,"",r),n}({...Zv});var Qv={};pe(Qv,{LogStreamCallbackHandler:()=>df,RunLog:()=>Ld,RunLogPatch:()=>Mr,isLogStreamHandler:()=>ew});var Mr=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=Gi({},t);return new Ld({ops:t,state:r[r.length-1].newDocument})}},Ld=class ff extends Mr{state;constructor(t){super(t),this.state=t.state}concat(t){const r=this.ops.concat(t.ops),n=Gi(this.state,t.ops);return new ff({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){const r=Gi({},t.ops);return new ff({ops:t.ops,state:r[r.length-1].newDocument})}};const ew=e=>e.name==="log_stream_tracer";async function Cg(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=e;if(["retriever","llm","prompt"].includes(e.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function Ag(e,t){const{outputs:r}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function lP(e){return e!==void 0&&e.message!==void 0}var df=class extends Hr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ht.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const n=this.keyMapByRunId[e];n&&await this.writer.write(new Mr({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Mr({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Cg(e,this._schemaFormat)),await this.writer.write(new Mr({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await Cg(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Ag(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const n=new Mr({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new Mr({ops:[{op:"replace",path:"/final_output",value:await Ag(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const n=this.keyMapByRunId[e.id];if(n===void 0)return;const i=e.inputs.messages!==void 0;let s;i?lP(r?.chunk)?s=r?.chunk:s=new qt({id:`run-${e.id}`,content:t}):s=t;const a=new Mr({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(a)}},tw={};pe(tw,{ChatGenerationChunk:()=>Wi,GenerationChunk:()=>Vi,RUN_KEY:()=>Ds});const Ds="__run";var Vi=class rw{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new rw({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Wi=class nw extends Vi{message;constructor(t){super(t),this.message=t.message}concat(t){return new nw({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function Ya({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const uP=e=>e.name==="event_stream_tracer";var fP=class extends Hr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ht.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const n=this.runInfoMap.get(e);if(n===void 0){yield r.value;return}function i(a,o){return a==="llm"&&typeof o=="string"?new Vi({text:o}):o}let s=this.tappedPromises.get(e);if(s===void 0){let a;s=new Promise(o=>{a=o}),this.tappedPromises.set(e,s);try{const o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:i(n.runType,r.value)}},n),yield r.value;for await(const c of t)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:i(n.runType,c)}},n),yield c}finally{a?.()}}else{yield r.value;for await(const a of t)yield a}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=Ya(e),r=e.inputs.messages!==void 0?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);const i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){const n=this.runInfoMap.get(e.id);let i,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?i=new qt({content:t,id:`run-${e.id}`}):i=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?i=new Vi({text:t}):i=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:i},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const n=e.outputs?.generations;let i;if(t.runType==="chat_model"){for(const s of n??[]){if(i!==void 0)break;i=s[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")i={generations:n?.map(s=>s.map(a=>({text:a.text,generationInfo:a.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=Ya(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let i={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(i={},n.inputs={}):e.inputs.input!==void 0?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:n};n.input&&Object.keys(n).length===1&&(s.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=Ya(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=Ya(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},iw=class extends Hr{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function jd(e){return e?e.lc_runnable:!1}var dP=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const n=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||n.some(i=>this.includeTags?.includes(i))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&n.every(i=>!this.excludeTags?.includes(i))),r}};function _u(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const hP=["*","_","`"];function pP(e){let t="";for(const[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
105
- `;return t}function mP(e,t,r){const{firstNode:n,lastNode:i,nodeColors:s,withStyles:a=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{};let l=a?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
106
- graph TD;
107
- `:`graph TD;
108
- `;if(a){const h="default",p={[h]:"{0}({1})"};n!==void 0&&(p[n]="{0}([{1}]):::first"),i!==void 0&&(p[i]="{0}([{1}]):::last");for(const[m,w]of Object.entries(e)){const y=w.name.split(":").pop()??"";let _=hP.some(A=>y.startsWith(A)&&y.endsWith(A))?`<p>${y}</p>`:y;Object.keys(w.metadata??{}).length&&(_+=`<hr/><small><em>${Object.entries(w.metadata??{}).map(([A,P])=>`${A} = ${P}`).join(`
109
- `)}</em></small>`);const b=(p[m]??p[h]).replace("{0}",_u(m)).replace("{1}",_);l+=` ${b}
110
- `}}const u={};for(const h of t){const p=h.source.split(":"),m=h.target.split(":"),w=p.filter((y,g)=>y===m[g]).join(":");u[w]||(u[w]=[]),u[w].push(h)}const d=new Set;function f(h,p){const m=h.length===1&&h[0].source===h[0].target;if(p&&!m){const w=p.split(":").pop();if(d.has(w))throw new Error(`Found duplicate subgraph '${w}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(w),l+=` subgraph ${w}
111
- `}for(const w of h){const{source:y,target:g,data:_,conditional:b}=w;let A="";if(_!==void 0){let P=_;const x=P.split(" ");x.length>c&&(P=Array.from({length:Math.ceil(x.length/c)},(T,R)=>x.slice(R*c,(R+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),A=b?` -. &nbsp;${P}&nbsp; .-> `:` -- &nbsp;${P}&nbsp; --> `}else A=b?" -.-> ":" --> ";l+=` ${_u(y)}${A}${_u(g)};
112
- `}for(const w in u)w.startsWith(`${p}:`)&&w!==p&&f(u[w],w);p&&!m&&(l+=` end
113
- `)}f(u[""]??[],"");for(const h in u)!h.includes(":")&&h!==""&&f(u[h],h);return a&&(l+=pP(s??{})),l}async function gP(e,t){let r=t?.backgroundColor??"white";const n=t?.imageType??"png",i=btoa(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const s=`https://mermaid.ink/img/${i}?bgColor=${r}&type=${n}`,a=await fetch(s);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join(`
114
- `));return await a.blob()}var sw={};pe(sw,{Graph:()=>Fs});function yP(e,t){if(e!==void 0&&!li(e))return e;if(jd(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function _P(e){return jd(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...zt(e.data.schema),title:e.data.name}}}var Fs=class aw{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){const t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=li(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],..._P(r)})),edges:this.edges.map(r=>{const n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);const i=r??et(),s={id:i,data:t,name:yP(r,t),metadata:n};return this.nodes[i]=s,s}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,i){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);const s={source:t.id,target:r.id,data:n,conditional:i};return this.edges.push(s),s}firstNode(){return Og(this)}lastNode(){return xg(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(l=>l.id).every(li)&&(n="");const s=l=>n?`${n}:${l}`:l;Object.entries(t.nodes).forEach(([l,u])=>{this.nodes[s(l)]={...u,id:s(l)}});const a=t.edges.map(l=>({...l,source:s(l.source),target:s(l.target)}));this.edges=[...this.edges,...a];const o=t.firstNode(),c=t.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){const t=this.firstNode();t&&Og(this,[t.id])&&this.removeNode(t)}trimLastNode(){const t=this.lastNode();t&&xg(this,[t.id])&&this.removeNode(t)}reid(){const t=Object.fromEntries(Object.values(this.nodes).map(i=>[i.id,i.name])),r=new Map;Object.values(t).forEach(i=>{r.set(i,(r.get(i)||0)+1)});const n=i=>{const s=t[i];return li(i)&&r.get(s)===1?s:i};return new aw({nodes:Object.fromEntries(Object.entries(this.nodes).map(([i,s])=>[n(i),{...s,id:n(i)}])),edges:this.edges.map(i=>({...i,source:n(i.source),target:n(i.target)}))})}drawMermaid(t){const{withStyles:r,curveStyle:n,nodeColors:i={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=t??{},a=this.reid(),o=a.firstNode(),c=a.lastNode();return mP(a.nodes,a.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:i,wrapLabelNWords:s})}async drawMermaidPng(t){const r=this.drawMermaid(t);return gP(r,{backgroundColor:t?.backgroundColor})}};function Og(e,t=[]){const r=new Set(e.edges.filter(i=>!t.includes(i.source)).map(i=>i.target)),n=[];for(const i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function xg(e,t=[]){const r=new Set(e.edges.filter(i=>!t.includes(i.target)).map(i=>i.source)),n=[];for(const i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function vP(e){const t=new TextEncoder,r=new ReadableStream({async start(n){for await(const i of e)n.enqueue(t.encode(`event: data
115
- data: ${JSON.stringify(i)}
116
-
117
- `));n.enqueue(t.encode(`event: end
118
-
119
- `)),n.close()}});return ht.fromReadableStream(r)}function Pg(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}const wP=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function hf(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*kg(e,t){for(;;){const{value:r,done:n}=Ve.runWithConfig(qr(e),t.next.bind(t),!0);if(n)break;yield r}}async function*pf(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:i}=await Ve.runWithConfig(qr(e),r.next.bind(t),!0);if(i)break;yield n}}function tt(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var we=class extends Qt{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new Dd({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new ft({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new dw({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Se);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runId"));return Array.from({length:t},(n,i)=>Se(i===0?e:r))}return Array.from({length:t},()=>Se(e))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),i=n[0]?.maxConcurrency??r?.maxConcurrency,s=new oa({maxConcurrency:i,onFailedAttempt:o=>{throw o}}),a=e.map((o,c)=>s.call(async()=>{try{return await this.invoke(o,n[c])}catch(l){if(r?.returnExceptions)return l;throw l}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=Se(t),n=new vn({generator:this._streamIterator(e,r),config:r});return await n.setup,ht.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=Se(e):t=Se({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){const n=Se(r),s=await(await Pt(n))?.handleChainStart(this.toJSON(),tt(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let a;try{const o=e.call(this,t,n,s);a=await pn(o,r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(tt(a,"output")),a}async _batchWithConfig(e,t,r,n){const i=this._getOptionsList(r??{},t.length),s=await Promise.all(i.map(Pt)),a=await Promise.all(s.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),tt(t[l],"input"),i[l].runId,i[l].runType,void 0,void 0,i[l].runName??this.getName());return delete i[l].runId,u}));let o;try{const c=e.call(this,t,i,a,n);o=await pn(c,i?.[0]?.signal)}catch(c){throw await Promise.all(a.map(l=>l?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(tt(o,"output")))),o}_concatOutputChunks(e,t){return mn(e,t)}async*_transformStreamWithConfig(e,t,r){let n,i=!0,s,a=!0;const o=Se(r),c=await Pt(o),l=this;async function*u(){for await(const f of e){if(i)if(n===void 0)n=f;else try{n=l._concatOutputChunks(n,f)}catch{n=void 0,i=!1}yield f}}let d;try{const f=await Kv(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),r?.signal,o);delete o.runId,d=f.setup;const h=d?.handlers.find(uP);let p=f.output;h!==void 0&&d!==void 0&&(p=h.tapOutputIterable(d.runId,p));const m=d?.handlers.find(ew);m!==void 0&&d!==void 0&&(p=m.tapOutputIterable(d.runId,p));for await(const w of p)if(yield w,a)if(s===void 0)s=w;else try{s=this._concatOutputChunks(s,w)}catch{s=void 0,a=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:tt(n,"input")}),f}await d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:tt(n,"input")})}getGraph(e){const t=new Fs,r=t.addNode({name:`${this.getName()}Input`,schema:Ut()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:Ut()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new er({first:this,last:ct(e)})}pick(e){return this.pipe(new hw(e))}assign(e){return this.pipe(new Fd(new is({steps:e})))}async*transform(e,t){let r;for await(const n of e)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,Se(t))}async*streamLog(e,t,r){const n=new df({...r,autoClose:!1,_schemaFormat:"original"}),i=Se(t);yield*this._streamLog(e,n,i)}async*_streamLog(e,t,r){const{callbacks:n}=r;if(n===void 0)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{const o=n.copy();o.addHandler(t,!0),r.callbacks=o}const i=this.stream(e,r);async function s(){try{const o=await i;for await(const c of o){const l=new Mr({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const a=s();try{for await(const o of t)yield o}finally{await a}}streamEvents(e,t,r){let n;if(t.version==="v1")n=this._streamEventsV1(e,t,r);else if(t.version==="v2")n=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?vP(n):ht.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new fP({...r,autoClose:!1}),i=Se(t),s=i.runId??et();i.runId=s;const a=i.callbacks;if(a===void 0)i.callbacks=[n];else if(Array.isArray(a))i.callbacks=a.concat(n);else{const h=a.copy();h.addHandler(n,!0),i.callbacks=h}const o=new AbortController,c=this;async function l(){let h,p=null;try{t?.signal?"any"in AbortSignal?h=AbortSignal.any([o.signal,t.signal]):(h=t.signal,p=()=>{o.abort()},t.signal.addEventListener("abort",p,{once:!0})):h=o.signal;const m=await c.stream(e,{...i,signal:h}),w=n.tapOutputIterable(s,m);for await(const y of w)if(o.signal.aborted)break}finally{await n.finish(),h&&p&&h.removeEventListener("abort",p)}}const u=l();let d=!1,f;try{for await(const h of n){if(!d){h.data.input=e,d=!0,f=h.run_id,yield h;continue}h.run_id===f&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{o.abort(),await u}}async*_streamEventsV1(e,t,r){let n,i=!1;const s=Se(t),a=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),l=new df({...r,autoClose:!1,_schemaFormat:"streaming_events"}),u=new dP({...r}),d=this._streamLog(e,l,s);for await(const h of d){if(n?n=n.concat(h):n=Ld.fromRunLogPatch(h),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;const y={...n.state},g={run_id:y.id,event:`on_${y.type}_start`,name:c,tags:a,metadata:o,data:{input:e}};u.includeEvent(g,y.type)&&(yield g)}const p=h.ops.filter(y=>y.path.startsWith("/logs/")).map(y=>y.path.split("/")[2]),m=[...new Set(p)];for(const y of m){let g,_={};const b=n.state.logs[y];if(b.end_time===void 0?b.streamed_output.length>0?g="stream":g="start":g="end",g==="start")b.inputs!==void 0&&(_.input=b.inputs);else if(g==="end")b.inputs!==void 0&&(_.input=b.inputs),_.output=b.final_output;else if(g==="stream"){const A=b.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${b.name}"`);_={chunk:b.streamed_output[0]},b.streamed_output=[]}yield{event:`on_${b.type}_${g}`,name:b.name,run_id:b.id,tags:b.tags,metadata:b.metadata,data:_}}const{state:w}=n;if(w.streamed_output.length>0){const y=w.streamed_output.length;if(y!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${y} instead. Encountered in: "${w.name}"`);const g={chunk:w.streamed_output[0]};w.streamed_output=[];const _={event:`on_${w.type}_stream`,run_id:w.id,tags:a,metadata:o,name:c,data:g};u.includeEvent(_,w.type)&&(yield _)}}const f=n?.state;if(f!==void 0){const h={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:a,metadata:o,data:{output:f.final_output}};u.includeEvent(h,f.type)&&(yield h)}}static isRunnable(e){return jd(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new ft({bound:this,config:{},configFactories:[n=>({callbacks:[new iw({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return CP(this,e)}},ft=class ow extends we{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const r=Bt(this.config,...t);return Bt(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new Dd({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(r,this.kwargs))}async batch(t,r,n){const i=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(Se(s),this.kwargs))):await this._mergeConfig(Se(r),this.kwargs);return this.bound.batch(t,i,n)}_concatOutputChunks(t,r){return this.bound._concatOutputChunks(t,r)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig(Se(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig(Se(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig(Se(r),this.kwargs))}streamEvents(t,r,n){const i=this,s=async function*(){yield*i.bound.streamEvents(t,{...await i._mergeConfig(Se(r),i.kwargs),version:r.version},n)};return ht.fromAsyncGenerator(s())}static isRunnableBinding(t){return t.bound&&we.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new ow({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new iw({config:i,onStart:t,onEnd:r,onError:n})]})]})}},bP=class cw extends we{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,n){return this.bound.batch(t,ke(r,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new cw({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},Dd=class extends ft{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const n=e>1?`retry:attempt:${e}`:void 0;return ke(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return xo(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:n=>this.onFailedAttempt(n,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){const i={};try{await xo(async s=>{const a=e.map((d,f)=>f).filter(d=>i[d.toString()]===void 0||i[d.toString()]instanceof Error),o=a.map(d=>e[d]),c=a.map(d=>this._patchConfigForRetry(s,t?.[d],r?.[d])),l=await super.batch(o,c,{...n,returnExceptions:!0});let u;for(let d=0;d<l.length;d+=1){const f=l[d],h=a[d];f instanceof Error&&u===void 0&&(u=f,u.input=o[d]),i[h.toString()]=f}if(u)throw u;return l},{onFailedAttempt:s=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(i).sort((s,a)=>parseInt(s,10)-parseInt(a,10)).map(s=>i[parseInt(s,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},er=class ms extends we{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){const n=Se(r),s=await(await Pt(n))?.handleChainStart(this.toJSON(),tt(t,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a=t,o;try{const c=[this.first,...this.middle];for(let l=0;l<c.length;l+=1){const d=c[l].invoke(a,ke(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`)}));a=await pn(d,r?.signal)}if(r?.signal?.aborted)throw $s(r.signal);o=await this.last.invoke(a,ke(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(tt(o,"output")),o}async batch(t,r,n){const i=this._getOptionsList(r??{},t.length),s=await Promise.all(i.map(Pt)),a=await Promise.all(s.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),tt(t[l],"input"),i[l].runId,void 0,void 0,void 0,i[l].runName);return delete i[l].runId,u}));let o=t;try{for(let c=0;c<this.steps.length;c+=1){const u=this.steps[c].batch(o,a.map((d,f)=>{const h=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return ke(i[f],{callbacks:h})}),n);o=await pn(u,i[0]?.signal)}}catch(c){throw await Promise.all(a.map(l=>l?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(tt(o,"output")))),o}_concatOutputChunks(t,r){return this.last._concatOutputChunks(t,r)}async*_streamIterator(t,r){const n=await Pt(r),{runId:i,...s}=r??{},a=await n?.handleChainStart(this.toJSON(),tt(t,"input"),i,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last];let c=!0,l;async function*u(){yield t}try{let d=o[0].transform(u(),ke(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,ke(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(const f of d)if(r?.signal?.throwIfAborted(),yield f,c)if(l===void 0)l=f;else try{l=this._concatOutputChunks(l,f)}catch{l=void 0,c=!1}}catch(d){throw await a?.handleChainError(d),d}await a?.handleChainEnd(tt(l,"output"))}getGraph(t){const r=new Fs;let n=null;return this.steps.forEach((i,s)=>{const a=i.getGraph(t);s!==0&&a.trimFirstNode(),s!==this.steps.length-1&&a.trimLastNode(),r.extend(a);const o=a.firstNode();if(!o)throw new Error(`Runnable ${i} has no first node`);n&&r.addEdge(n,o),n=a.lastNode()}),r}pipe(t){return ms.isRunnableSequence(t)?new ms({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new ms({first:this.first,middle:[...this.middle,this.last],last:ct(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&we.isRunnable(t)}static from([t,...r],n){let i={};return typeof n=="string"?i.name=n:n!==void 0&&(i=n),new ms({...i,first:ct(t),middle:r.slice(0,-1).map(ct),last:ct(r[r.length-1])})}},is=class lw extends we{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(const[r,n]of Object.entries(t.steps))this.steps[r]=ct(n)}static from(t){return new lw({steps:t})}async invoke(t,r){const n=Se(r),s=await(await Pt(n))?.handleChainStart(this.toJSON(),{input:t},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;const a={};try{const o=Object.entries(this.steps).map(async([c,l])=>{a[c]=await l.invoke(t,ke(n,{callbacks:s?.getChild(`map:key:${c}`)}))});await pn(Promise.all(o),r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(a),a}async*_transform(t,r,n){const i={...this.steps},s=$d(t,Object.keys(i).length),a=new Map(Object.entries(i).map(([o,c],l)=>{const u=c.transform(s[l],ke(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,u.next().then(d=>({key:o,gen:u,result:d}))]}));for(;a.size;){const o=Promise.race(a.values()),{key:c,result:l,gen:u}=await pn(o,n?.signal);a.delete(c),l.done||(yield{[c]:l.value},a.set(c,u.next().then(d=>({key:c,gen:u,result:d}))))}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}const i=Se(r),s=new vn({generator:this.transform(n(),i),config:i});return await s.setup,ht.fromAsyncGenerator(s)}},SP=class uw extends we{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Pd(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){const[n]=this._getOptionsList(r??{},1),i=await Pt(n),s=this.func(ke(n,{callbacks:i}),t);return pn(s,n?.signal)}async*_streamIterator(t,r){const[n]=this._getOptionsList(r??{},1),i=await this.invoke(t,r);if(hf(i)){for await(const s of i)n?.signal?.throwIfAborted(),yield s;return}if(wP(i)){for(;;){n?.signal?.throwIfAborted();const s=i.next();if(s.done)break;yield s.value}return}yield i}static from(t){return new uw({func:t})}};function EP(e){if(Pd(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Mt=class fw extends we{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Pd(t.func))return SP.from(t.func);super(t),EP(t.func),this.func=t.func}static from(t){return new fw({func:t})}async _invoke(t,r,n){return new Promise((i,s)=>{const a=ke(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??mu)-1});Ve.runWithConfig(qr(a),async()=>{try{let o=await this.func(t,{...a});if(o&&we.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...a,recursionLimit:(a.recursionLimit??mu)-1})}else if(hf(o)){let c;for await(const l of pf(a,o))if(r?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(Pg(o)){let c;for(const l of kg(a,o))if(r?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}i(o)}catch(o){s(o)}})})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,n){let i;for await(const o of t)if(i===void 0)i=o;else try{i=this._concatOutputChunks(i,o)}catch{i=o}const s=ke(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??mu)-1}),a=await new Promise((o,c)=>{Ve.runWithConfig(qr(s),async()=>{try{const l=await this.func(i,{...s,config:s});o(l)}catch(l){c(l)}})});if(a&&we.isRunnable(a)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await a.stream(i,s);for await(const c of o)yield c}else if(hf(a))for await(const o of pf(s,a))n?.signal?.throwIfAborted(),yield o;else if(Pg(a))for(const o of kg(s,a))n?.signal?.throwIfAborted(),yield o;else yield a}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}const i=Se(r),s=new vn({generator:this.transform(n(),i),config:i});return await s.setup,ht.fromAsyncGenerator(s)}},TP=class extends is{},dw=class extends we{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=Se(t),n=await Pt(r),{runId:i,...s}=r,a=await n?.handleChainStart(this.toJSON(),tt(e,"input"),i,void 0,void 0,void 0,s?.runName),o=ke(s,{callbacks:a?.getChild()});return await Ve.runWithConfig(o,async()=>{let l;for(const u of this.runnables()){r?.signal?.throwIfAborted();try{const d=await u.invoke(e,o);return await a?.handleChainEnd(tt(d,"output")),d}catch(d){l===void 0&&(l=d)}}throw l===void 0?new Error("No error stored at end of fallback."):(await a?.handleChainError(l),l)})}async*_streamIterator(e,t){const r=Se(t),n=await Pt(r),{runId:i,...s}=r,a=await n?.handleChainStart(this.toJSON(),tt(e,"input"),i,void 0,void 0,void 0,s?.runName);let o,c;for(const u of this.runnables()){r?.signal?.throwIfAborted();const d=ke(s,{callbacks:a?.getChild()});try{const f=await u.stream(e,d);c=pf(d,f);break}catch(f){o===void 0&&(o=f)}}if(c===void 0){const u=o??new Error("No error stored at end of fallback.");throw await a?.handleChainError(u),u}let l;try{for await(const u of c){yield u;try{l=l===void 0?l:this._concatOutputChunks(l,u)}catch{l=void 0}}}catch(u){throw await a?.handleChainError(u),u}await a?.handleChainEnd(tt(l,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(o=>Pt(o))),s=await Promise.all(i.map(async(o,c)=>{const l=await o?.handleChainStart(this.toJSON(),tt(e[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,l}));let a;for(const o of this.runnables()){n[0].signal?.throwIfAborted();try{const c=await o.batch(e,s.map((l,u)=>ke(n[u],{callbacks:l?.getChild()})),r);return await Promise.all(s.map((l,u)=>l?.handleChainEnd(tt(c[u],"output")))),c}catch(c){a===void 0&&(a=c)}}throw a?(await Promise.all(s.map(o=>o?.handleChainError(a))),a):new Error("No error stored at end of fallbacks.")}};function ct(e){if(typeof e=="function")return new Mt({func:e});if(we.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))t[r]=ct(n);return new is({steps:t})}else throw new Error(`Expected a Runnable, function or object.
120
- Instead got an unsupported type.`)}var Fd=class extends we{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof is&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const n=this.mapper.getStepsKeys(),[i,s]=$d(e),a=this.mapper.transform(s,ke(r,{callbacks:t?.getChild()})),o=a.next();for await(const c of i){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([u])=>!n.includes(u)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(const c of a)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const n=Se(t),i=new vn({generator:this.transform(r(),n),config:n});return await i.setup,ht.fromAsyncGenerator(i)}},hw=class extends we{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const n=Se(t),i=new vn({generator:this.transform(r(),n),config:n});return await i.setup,ht.fromAsyncGenerator(i)}},mf=class extends ft{name;description;schema;constructor(e){const t=er.from([Mt.from(async r=>{let n;if(Ss(r))try{n=await mc(this.schema,r.args)}catch{throw new Rs("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function CP(e,t){const r=t.name??e.getName(),n=t.description??Hi(t.schema);return Md(t.schema)?new mf({name:r,description:n,schema:Pe({input:nt()}).transform(i=>i.input),bound:e}):new mf({name:r,description:n,schema:t.schema,bound:e})}var pw={};pe(pw,{BasePromptValue:()=>vc,ChatPromptValue:()=>Bd,ImagePromptValue:()=>mw,StringPromptValue:()=>Ud});var vc=class extends Qt{},Ud=class extends vc{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new je(this.value)]}},Bd=class extends vc{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Cd(this.messages)}toChatMessages(){return this.messages}},mw=class extends vc{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new je({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},ce="0123456789abcdef".split(""),AP=[-2147483648,8388608,32768,128],ir=[24,16,8,0],Xa=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],it=[];function hr(e,t){t?(it[0]=it[16]=it[1]=it[2]=it[3]=it[4]=it[5]=it[6]=it[7]=it[8]=it[9]=it[10]=it[11]=it[12]=it[13]=it[14]=it[15]=0,this.blocks=it):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}hr.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if(r!=="string"){if(r==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var n,i=0,s,a=e.length,o=this.blocks;i<a;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(s=this.start;i<a&&s<64;++i)o[s>>>2]|=e[i]<<ir[s++&3];else for(s=this.start;i<a&&s<64;++i)n=e.charCodeAt(i),n<128?o[s>>>2]|=n<<ir[s++&3]:n<2048?(o[s>>>2]|=(192|n>>>6)<<ir[s++&3],o[s>>>2]|=(128|n&63)<<ir[s++&3]):n<55296||n>=57344?(o[s>>>2]|=(224|n>>>12)<<ir[s++&3],o[s>>>2]|=(128|n>>>6&63)<<ir[s++&3],o[s>>>2]|=(128|n&63)<<ir[s++&3]):(n=65536+((n&1023)<<10|e.charCodeAt(++i)&1023),o[s>>>2]|=(240|n>>>18)<<ir[s++&3],o[s>>>2]|=(128|n>>>12&63)<<ir[s++&3],o[s>>>2]|=(128|n>>>6&63)<<ir[s++&3],o[s>>>2]|=(128|n&63)<<ir[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};hr.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=AP[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};hr.prototype.hash=function(){var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,c=this.blocks,l,u,d,f,h,p,m,w,y,g,_;for(l=16;l<64;++l)h=c[l-15],u=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=c[l-2],d=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(_=t&r,l=0;l<64;l+=4)this.first?(this.is224?(w=300032,h=c[0]-1413257819,o=h-150054599<<0,n=h+24177077<<0):(w=704751109,h=c[0]-210244248,o=h-1521486534<<0,n=h+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),w=e&t,f=w^e&r^_,m=i&s^~i&a,h=o+d+m+Xa[l]+c[l],p=u+f,o=n+h<<0,n=h+p<<0),u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),y=n&e,f=y^n&t^w,m=a&o^~a&i,h=s+d+m+Xa[l+1]+c[l+1],p=u+f,a=r+h<<0,r=h+p<<0,u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),g=r&n,f=g^r&e^y,m=s&a^~s&o,h=i+d+m+Xa[l+2]+c[l+2],p=u+f,s=t+h<<0,t=h+p<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=t&r,f=_^t&n^g,m=s&a^~s&o,h=i+d+m+Xa[l+3]+c[l+3],p=u+f,i=e+h<<0,e=h+p<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+i<<0,this.h5=this.h5+s<<0,this.h6=this.h6+a<<0,this.h7=this.h7+o<<0};hr.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,c=ce[e>>>28&15]+ce[e>>>24&15]+ce[e>>>20&15]+ce[e>>>16&15]+ce[e>>>12&15]+ce[e>>>8&15]+ce[e>>>4&15]+ce[e&15]+ce[t>>>28&15]+ce[t>>>24&15]+ce[t>>>20&15]+ce[t>>>16&15]+ce[t>>>12&15]+ce[t>>>8&15]+ce[t>>>4&15]+ce[t&15]+ce[r>>>28&15]+ce[r>>>24&15]+ce[r>>>20&15]+ce[r>>>16&15]+ce[r>>>12&15]+ce[r>>>8&15]+ce[r>>>4&15]+ce[r&15]+ce[n>>>28&15]+ce[n>>>24&15]+ce[n>>>20&15]+ce[n>>>16&15]+ce[n>>>12&15]+ce[n>>>8&15]+ce[n>>>4&15]+ce[n&15]+ce[i>>>28&15]+ce[i>>>24&15]+ce[i>>>20&15]+ce[i>>>16&15]+ce[i>>>12&15]+ce[i>>>8&15]+ce[i>>>4&15]+ce[i&15]+ce[s>>>28&15]+ce[s>>>24&15]+ce[s>>>20&15]+ce[s>>>16&15]+ce[s>>>12&15]+ce[s>>>8&15]+ce[s>>>4&15]+ce[s&15]+ce[a>>>28&15]+ce[a>>>24&15]+ce[a>>>20&15]+ce[a>>>16&15]+ce[a>>>12&15]+ce[a>>>8&15]+ce[a>>>4&15]+ce[a&15];return this.is224||(c+=ce[o>>>28&15]+ce[o>>>24&15]+ce[o>>>20&15]+ce[o>>>16&15]+ce[o>>>12&15]+ce[o>>>8&15]+ce[o>>>4&15]+ce[o&15]),c};hr.prototype.toString=hr.prototype.hex;hr.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};hr.prototype.array=hr.prototype.digest;hr.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const zd=(...e)=>new hr(!1,!0).update(e.join("")).hex();var gw={};pe(gw,{sha256:()=>zd});var yw={};pe(yw,{BaseCache:()=>vw,InMemoryCache:()=>ww,defaultHashKeyEncoder:()=>_w,deserializeStoredGeneration:()=>OP,serializeGeneration:()=>xP});const _w=(...e)=>zd(e.join("_"));function OP(e){return e.message!==void 0?{text:e.text,message:Ad(e.message)}:{text:e.text}}function xP(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var vw=class{keyEncoder=_w;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const PP=new Map;var ww=class bw extends vw{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,n){this.cache.set(this.keyEncoder(t,r),n)}static global(){return new bw(PP)}},Sw={};pe(Sw,{encodingForModel:()=>qd,getEncoding:()=>Ew});const Qa={},kP=new oa({});async function Ew(e){return e in Qa||(Qa[e]=kP.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new uE(t)).catch(t=>{throw delete Qa[e],t})),await Qa[e]}async function qd(e){return Ew(lE(e))}var Tw={};pe(Tw,{BaseLangChain:()=>Hd,BaseLanguageModel:()=>bc,calculateMaxTokens:()=>RP,getEmbeddingContextSize:()=>IP,getModelContextSize:()=>Cw,getModelNameForTiktoken:()=>wc,isOpenAITool:()=>MP});const wc=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,IP=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},Cw=e=>{switch(wc(e)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};function MP(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const RP=async({prompt:e,modelName:t})=>{let r;try{r=(await qd(wc(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return Cw(t)-r},NP=()=>!1;var Hd=class extends we{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??NP(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},bc=class extends Hd{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){const{cache:n,...i}=r;super({callbacks:e??t,...i}),typeof n=="object"?this.cache=n:n?this.cache=ww.global():this.cache=void 0,this.caller=new oa(r??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await qd("modelName"in this?wc(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Ud(e):Array.isArray(e)?new Bd(e.map(Er)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([s,a])=>a!==void 0).map(([s,a])=>`${s}:${JSON.stringify(a)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}};function Gd(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function Vd(e){return e!==void 0&&we.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function Wd(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(qn(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function Jd(e){return Wd(e)||Vd(e)||Gd(e)}const $P=(e,t)=>{fE.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>hE(e,r)},flatten:{value:r=>dE(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},Sc=pt("ZodError",$P,{Parent:Error}),LP=pE(Sc),jP=gE(Sc),DP=mE(Sc),FP=yE(Sc),$t=pt("ZodType",(e,t)=>(wE.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>fn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>LP(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>DP(e,r,n),e.parseAsync=async(r,n)=>jP(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>FP(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(uk(r,n)),e.superRefine=r=>e.check(fk(r)),e.overwrite=r=>e.check(bE(r)),e.optional=()=>Ig(e),e.nullable=()=>Mg(e),e.nullish=()=>Ig(Mg(e)),e.nonoptional=r=>rk(e,r),e.array=()=>zP(e),e.or=r=>HP([e,r]),e.and=r=>VP(e,r),e.transform=r=>Rg(e,JP(r)),e.default=r=>XP(e,r),e.prefault=r=>ek(e,r),e.catch=r=>ik(e,r),e.pipe=r=>Rg(e,r),e.readonly=()=>ok(e),e.describe=r=>{const n=e.clone();return ot.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return ot.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ot.get(e);const n=e.clone();return ot.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),UP=pt("ZodAny",(e,t)=>{vE.init(e,t),$t.init(e,t)});function eo(){return _E(UP)}const BP=pt("ZodArray",(e,t)=>{$E.init(e,t),$t.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Rh(r,n)),e.nonempty=r=>e.check(Rh(1,r)),e.max=(r,n)=>e.check(LE(r,n)),e.length=(r,n)=>e.check(jE(r,n)),e.unwrap=()=>e.element});function zP(e,t){return EE(BP,e,t)}const qP=pt("ZodUnion",(e,t)=>{OE.init(e,t),$t.init(e,t),e.options=t.options});function HP(e,t){return new qP({type:"union",options:e,...Gy(t)})}const GP=pt("ZodIntersection",(e,t)=>{xE.init(e,t),$t.init(e,t)});function VP(e,t){return new GP({type:"intersection",left:e,right:t})}const WP=pt("ZodTransform",(e,t)=>{kE.init(e,t),$t.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Po(s,r.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(Po(a))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function JP(e){return new WP({type:"transform",transform:e})}const KP=pt("ZodOptional",(e,t)=>{rd.init(e,t),$t.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ig(e){return new KP({type:"optional",innerType:e})}const ZP=pt("ZodNullable",(e,t)=>{CE.init(e,t),$t.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Mg(e){return new ZP({type:"nullable",innerType:e})}const YP=pt("ZodDefault",(e,t)=>{IE.init(e,t),$t.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function XP(e,t){return new YP({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const QP=pt("ZodPrefault",(e,t)=>{ME.init(e,t),$t.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ek(e,t){return new QP({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const tk=pt("ZodNonOptional",(e,t)=>{AE.init(e,t),$t.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rk(e,t){return new tk({type:"nonoptional",innerType:e,...Gy(t)})}const nk=pt("ZodCatch",(e,t)=>{RE.init(e,t),$t.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ik(e,t){return new nk({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const sk=pt("ZodPipe",(e,t)=>{PE.init(e,t),$t.init(e,t),e.in=t.in,e.out=t.out});function Rg(e,t){return new sk({type:"pipe",in:e,out:t})}const ak=pt("ZodReadonly",(e,t)=>{NE.init(e,t),$t.init(e,t)});function ok(e){return new ak({type:"readonly",innerType:e})}const ck=pt("ZodCustom",(e,t)=>{DE.init(e,t),$t.init(e,t)});function lk(e){const t=new TE({check:"custom"});return t._zod.check=e,t}function uk(e,t={}){return SE(ck,e,t)}function fk(e){const t=lk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Po(n,r.value,t._zod.def));else{const i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(Po(i))}},e(r.value,r)));return t}var Aw={};pe(Aw,{BaseToolkit:()=>dk,DynamicStructuredTool:()=>Ec,DynamicTool:()=>Zd,StructuredTool:()=>Hn,Tool:()=>Kd,ToolInputParsingException:()=>Rs,isLangChainTool:()=>Jd,isRunnableToolLike:()=>Vd,isStructuredTool:()=>Gd,isStructuredToolParams:()=>Wd,tool:()=>Yd});var Hn=class extends Hd{returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata}async invoke(e,t){let r,n=Se(Bt(this.defaultConfig,t));return Ss(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){const n=Ss(e)?e.args:e;let i;if(qn(this.schema))try{i=await mc(this.schema,n)}catch(h){let p="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(p=`${p}
121
- Details: ${h.message}`),h instanceof Error&&h.constructor.name==="ZodError"&&(p=`${p}
122
-
123
- ${FE(h)}`),new Rs(p,JSON.stringify(e))}else{const h=UE(n,this.schema);if(!h.valid){let p="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(p=`${p}
124
- Details: ${h.errors.map(m=>`${m.keywordLocation}: ${m.error}`).join(`
125
- `)}`),new Rs(p,JSON.stringify(e))}i=n}const s=sa(t),o=await St.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName);delete s.runId;let c;try{c=await this._call(i,o,s)}catch(h){throw await o?.handleToolError(h),h}let l,u;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[l,u]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
126
- Result: ${JSON.stringify(c)}`);else l=c;let d;Ss(e)&&(d=e.id),!d&&KC(s)&&(d=s.toolCall.id);const f=hk({content:l,artifact:u,toolCallId:d,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(f),f}},Kd=class extends Hn{schema=Pe({input:nt().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){const r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},Zd=class extends Kd{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){const r=sa(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}async _call(e,t,r){return this.func(e,t,r)}},Ec=class extends Hn{static lc_name(){return"DynamicStructuredTool"}name;description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){const n=sa(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},dk=class{getTools(){return this.tools}};function Yd(e,t){const r=Md(t.schema),n=Es(t.schema);if(!t.schema||r||n)return new Zd({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(a,o,c)=>new Promise((l,u)=>{const d=ke(c,{callbacks:o?.getChild()});Ve.runWithConfig(qr(d),async()=>{try{l(e(a,d))}catch(f){u(f)}})})});const i=t.schema,s=t.description??t.schema.description??`${t.name} tool`;return new Ec({...t,description:s,schema:i,func:async(a,o,c)=>new Promise((l,u)=>{c?.signal&&c.signal.addEventListener("abort",()=>u($s(c.signal)));const d=ke(c,{callbacks:o?.getChild()});Ve.runWithConfig(qr(d),async()=>{try{const f=await e(a,d);if(c?.signal?.aborted)return;l(f)}catch(f){u(f)}})})})}function hk(e){const{content:t,artifact:r,toolCallId:n,metadata:i}=e;return n&&!wd(t)?typeof t=="string"||Array.isArray(t)&&t.every(s=>typeof s=="object")?new Ae({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:i}):new Ae({status:"success",content:pk(t),artifact:r,tool_call_id:n,name:e.name,metadata:i}):t}function pk(e){try{return JSON.stringify(e,null,2)??""}catch{return`${e}`}}var Ow=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,mk=typeof self=="object"&&self&&self.Object===Object&&self,Gr=Ow||mk||Function("return this")(),Ji=Gr.Symbol,xw=Object.prototype,gk=xw.hasOwnProperty,yk=xw.toString,ds=Ji?Ji.toStringTag:void 0;function _k(e){var t=gk.call(e,ds),r=e[ds];try{e[ds]=void 0;var n=!0}catch{}var i=yk.call(e);return n&&(t?e[ds]=r:delete e[ds]),i}var vk=Object.prototype,wk=vk.toString;function bk(e){return wk.call(e)}var Sk="[object Null]",Ek="[object Undefined]",Ng=Ji?Ji.toStringTag:void 0;function ca(e){return e==null?e===void 0?Ek:Sk:Ng&&Ng in Object(e)?_k(e):bk(e)}function Us(e){return e!=null&&typeof e=="object"}var zo=Array.isArray;function Pw(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Tk="[object AsyncFunction]",Ck="[object Function]",Ak="[object GeneratorFunction]",Ok="[object Proxy]";function kw(e){if(!Pw(e))return!1;var t=ca(e);return t==Ck||t==Ak||t==Tk||t==Ok}var vu=Gr["__core-js_shared__"],$g=(function(){var e=/[^.]+$/.exec(vu&&vu.keys&&vu.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function xk(e){return!!$g&&$g in e}var Pk=Function.prototype,kk=Pk.toString;function Gn(e){if(e!=null){try{return kk.call(e)}catch{}try{return e+""}catch{}}return""}var Ik=/[\\^$.*+?()[\]{}|]/g,Mk=/^\[object .+?Constructor\]$/,Rk=Function.prototype,Nk=Object.prototype,$k=Rk.toString,Lk=Nk.hasOwnProperty,jk=RegExp("^"+$k.call(Lk).replace(Ik,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Dk(e){if(!Pw(e)||xk(e))return!1;var t=kw(e)?jk:Mk;return t.test(Gn(e))}function Fk(e,t){return e?.[t]}function ss(e,t){var r=Fk(e,t);return Dk(r)?r:void 0}var gf=ss(Gr,"WeakMap"),Uk=9007199254740991,Bk=/^(?:0|[1-9]\d*)$/;function zk(e,t){var r=typeof e;return t=t??Uk,!!t&&(r=="number"||r!="symbol"&&Bk.test(e))&&e>-1&&e%1==0&&e<t}function Iw(e,t){return e===t||e!==e&&t!==t}var qk=9007199254740991;function Mw(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=qk}function Hk(e){return e!=null&&Mw(e.length)&&!kw(e)}var Gk=Object.prototype;function Vk(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Gk;return e===r}function Wk(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var Jk="[object Arguments]";function Lg(e){return Us(e)&&ca(e)==Jk}var Rw=Object.prototype,Kk=Rw.hasOwnProperty,Zk=Rw.propertyIsEnumerable,Yk=Lg((function(){return arguments})())?Lg:function(e){return Us(e)&&Kk.call(e,"callee")&&!Zk.call(e,"callee")};function Xk(){return!1}var Nw=typeof exports=="object"&&exports&&!exports.nodeType&&exports,jg=Nw&&typeof module=="object"&&module&&!module.nodeType&&module,Qk=jg&&jg.exports===Nw,Dg=Qk?Gr.Buffer:void 0,eI=Dg?Dg.isBuffer:void 0,yf=eI||Xk,tI="[object Arguments]",rI="[object Array]",nI="[object Boolean]",iI="[object Date]",sI="[object Error]",aI="[object Function]",oI="[object Map]",cI="[object Number]",lI="[object Object]",uI="[object RegExp]",fI="[object Set]",dI="[object String]",hI="[object WeakMap]",pI="[object ArrayBuffer]",mI="[object DataView]",gI="[object Float32Array]",yI="[object Float64Array]",_I="[object Int8Array]",vI="[object Int16Array]",wI="[object Int32Array]",bI="[object Uint8Array]",SI="[object Uint8ClampedArray]",EI="[object Uint16Array]",TI="[object Uint32Array]",Le={};Le[gI]=Le[yI]=Le[_I]=Le[vI]=Le[wI]=Le[bI]=Le[SI]=Le[EI]=Le[TI]=!0;Le[tI]=Le[rI]=Le[pI]=Le[nI]=Le[mI]=Le[iI]=Le[sI]=Le[aI]=Le[oI]=Le[cI]=Le[lI]=Le[uI]=Le[fI]=Le[dI]=Le[hI]=!1;function CI(e){return Us(e)&&Mw(e.length)&&!!Le[ca(e)]}function AI(e){return function(t){return e(t)}}var $w=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ts=$w&&typeof module=="object"&&module&&!module.nodeType&&module,OI=Ts&&Ts.exports===$w,wu=OI&&Ow.process,Fg=(function(){try{var e=Ts&&Ts.require&&Ts.require("util").types;return e||wu&&wu.binding&&wu.binding("util")}catch{}})(),Ug=Fg&&Fg.isTypedArray,Lw=Ug?AI(Ug):CI,xI=Object.prototype,PI=xI.hasOwnProperty;function kI(e,t){var r=zo(e),n=!r&&Yk(e),i=!r&&!n&&yf(e),s=!r&&!n&&!i&&Lw(e),a=r||n||i||s,o=a?Wk(e.length,String):[],c=o.length;for(var l in e)PI.call(e,l)&&!(a&&(l=="length"||i&&(l=="offset"||l=="parent")||s&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||zk(l,c)))&&o.push(l);return o}function II(e,t){return function(r){return e(t(r))}}var MI=II(Object.keys,Object),RI=Object.prototype,NI=RI.hasOwnProperty;function $I(e){if(!Vk(e))return MI(e);var t=[];for(var r in Object(e))NI.call(e,r)&&r!="constructor"&&t.push(r);return t}function LI(e){return Hk(e)?kI(e):$I(e)}var Bs=ss(Object,"create");function jI(){this.__data__=Bs?Bs(null):{},this.size=0}function DI(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var FI="__lodash_hash_undefined__",UI=Object.prototype,BI=UI.hasOwnProperty;function zI(e){var t=this.__data__;if(Bs){var r=t[e];return r===FI?void 0:r}return BI.call(t,e)?t[e]:void 0}var qI=Object.prototype,HI=qI.hasOwnProperty;function GI(e){var t=this.__data__;return Bs?t[e]!==void 0:HI.call(t,e)}var VI="__lodash_hash_undefined__";function WI(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Bs&&t===void 0?VI:t,this}function Dn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Dn.prototype.clear=jI;Dn.prototype.delete=DI;Dn.prototype.get=zI;Dn.prototype.has=GI;Dn.prototype.set=WI;function JI(){this.__data__=[],this.size=0}function Tc(e,t){for(var r=e.length;r--;)if(Iw(e[r][0],t))return r;return-1}var KI=Array.prototype,ZI=KI.splice;function YI(e){var t=this.__data__,r=Tc(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():ZI.call(t,r,1),--this.size,!0}function XI(e){var t=this.__data__,r=Tc(t,e);return r<0?void 0:t[r][1]}function QI(e){return Tc(this.__data__,e)>-1}function eM(e,t){var r=this.__data__,n=Tc(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}function Vr(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Vr.prototype.clear=JI;Vr.prototype.delete=YI;Vr.prototype.get=XI;Vr.prototype.has=QI;Vr.prototype.set=eM;var zs=ss(Gr,"Map");function tM(){this.size=0,this.__data__={hash:new Dn,map:new(zs||Vr),string:new Dn}}function rM(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Cc(e,t){var r=e.__data__;return rM(t)?r[typeof t=="string"?"string":"hash"]:r.map}function nM(e){var t=Cc(this,e).delete(e);return this.size-=t?1:0,t}function iM(e){return Cc(this,e).get(e)}function sM(e){return Cc(this,e).has(e)}function aM(e,t){var r=Cc(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}function Vn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Vn.prototype.clear=tM;Vn.prototype.delete=nM;Vn.prototype.get=iM;Vn.prototype.has=sM;Vn.prototype.set=aM;function oM(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}function cM(){this.__data__=new Vr,this.size=0}function lM(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}function uM(e){return this.__data__.get(e)}function fM(e){return this.__data__.has(e)}var dM=200;function hM(e,t){var r=this.__data__;if(r instanceof Vr){var n=r.__data__;if(!zs||n.length<dM-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Vn(n)}return r.set(e,t),this.size=r.size,this}function on(e){var t=this.__data__=new Vr(e);this.size=t.size}on.prototype.clear=cM;on.prototype.delete=lM;on.prototype.get=uM;on.prototype.has=fM;on.prototype.set=hM;function pM(e,t){for(var r=-1,n=e==null?0:e.length,i=0,s=[];++r<n;){var a=e[r];t(a,r,e)&&(s[i++]=a)}return s}function mM(){return[]}var gM=Object.prototype,yM=gM.propertyIsEnumerable,Bg=Object.getOwnPropertySymbols,_M=Bg?function(e){return e==null?[]:(e=Object(e),pM(Bg(e),function(t){return yM.call(e,t)}))}:mM;function vM(e,t,r){var n=t(e);return zo(e)?n:oM(n,r(e))}function zg(e){return vM(e,LI,_M)}var _f=ss(Gr,"DataView"),vf=ss(Gr,"Promise"),wf=ss(Gr,"Set"),qg="[object Map]",wM="[object Object]",Hg="[object Promise]",Gg="[object Set]",Vg="[object WeakMap]",Wg="[object DataView]",bM=Gn(_f),SM=Gn(zs),EM=Gn(vf),TM=Gn(wf),CM=Gn(gf),Xr=ca;(_f&&Xr(new _f(new ArrayBuffer(1)))!=Wg||zs&&Xr(new zs)!=qg||vf&&Xr(vf.resolve())!=Hg||wf&&Xr(new wf)!=Gg||gf&&Xr(new gf)!=Vg)&&(Xr=function(e){var t=ca(e),r=t==wM?e.constructor:void 0,n=r?Gn(r):"";if(n)switch(n){case bM:return Wg;case SM:return qg;case EM:return Hg;case TM:return Gg;case CM:return Vg}return t});var Jg=Gr.Uint8Array,AM="__lodash_hash_undefined__";function OM(e){return this.__data__.set(e,AM),this}function xM(e){return this.__data__.has(e)}function qo(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Vn;++t<r;)this.add(e[t])}qo.prototype.add=qo.prototype.push=OM;qo.prototype.has=xM;function PM(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}function kM(e,t){return e.has(t)}var IM=1,MM=2;function jw(e,t,r,n,i,s){var a=r&IM,o=e.length,c=t.length;if(o!=c&&!(a&&c>o))return!1;var l=s.get(e),u=s.get(t);if(l&&u)return l==t&&u==e;var d=-1,f=!0,h=r&MM?new qo:void 0;for(s.set(e,t),s.set(t,e);++d<o;){var p=e[d],m=t[d];if(n)var w=a?n(m,p,d,t,e,s):n(p,m,d,e,t,s);if(w!==void 0){if(w)continue;f=!1;break}if(h){if(!PM(t,function(y,g){if(!kM(h,g)&&(p===y||i(p,y,r,n,s)))return h.push(g)})){f=!1;break}}else if(!(p===m||i(p,m,r,n,s))){f=!1;break}}return s.delete(e),s.delete(t),f}function RM(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}function NM(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}var $M=1,LM=2,jM="[object Boolean]",DM="[object Date]",FM="[object Error]",UM="[object Map]",BM="[object Number]",zM="[object RegExp]",qM="[object Set]",HM="[object String]",GM="[object Symbol]",VM="[object ArrayBuffer]",WM="[object DataView]",Kg=Ji?Ji.prototype:void 0,bu=Kg?Kg.valueOf:void 0;function JM(e,t,r,n,i,s,a){switch(r){case WM:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case VM:return!(e.byteLength!=t.byteLength||!s(new Jg(e),new Jg(t)));case jM:case DM:case BM:return Iw(+e,+t);case FM:return e.name==t.name&&e.message==t.message;case zM:case HM:return e==t+"";case UM:var o=RM;case qM:var c=n&$M;if(o||(o=NM),e.size!=t.size&&!c)return!1;var l=a.get(e);if(l)return l==t;n|=LM,a.set(e,t);var u=jw(o(e),o(t),n,i,s,a);return a.delete(e),u;case GM:if(bu)return bu.call(e)==bu.call(t)}return!1}var KM=1,ZM=Object.prototype,YM=ZM.hasOwnProperty;function XM(e,t,r,n,i,s){var a=r&KM,o=zg(e),c=o.length,l=zg(t),u=l.length;if(c!=u&&!a)return!1;for(var d=c;d--;){var f=o[d];if(!(a?f in t:YM.call(t,f)))return!1}var h=s.get(e),p=s.get(t);if(h&&p)return h==t&&p==e;var m=!0;s.set(e,t),s.set(t,e);for(var w=a;++d<c;){f=o[d];var y=e[f],g=t[f];if(n)var _=a?n(g,y,f,t,e,s):n(y,g,f,e,t,s);if(!(_===void 0?y===g||i(y,g,r,n,s):_)){m=!1;break}w||(w=f=="constructor")}if(m&&!w){var b=e.constructor,A=t.constructor;b!=A&&"constructor"in e&&"constructor"in t&&!(typeof b=="function"&&b instanceof b&&typeof A=="function"&&A instanceof A)&&(m=!1)}return s.delete(e),s.delete(t),m}var QM=1,Zg="[object Arguments]",Yg="[object Array]",to="[object Object]",eR=Object.prototype,Xg=eR.hasOwnProperty;function tR(e,t,r,n,i,s){var a=zo(e),o=zo(t),c=a?Yg:Xr(e),l=o?Yg:Xr(t);c=c==Zg?to:c,l=l==Zg?to:l;var u=c==to,d=l==to,f=c==l;if(f&&yf(e)){if(!yf(t))return!1;a=!0,u=!1}if(f&&!u)return s||(s=new on),a||Lw(e)?jw(e,t,r,n,i,s):JM(e,t,c,r,n,i,s);if(!(r&QM)){var h=u&&Xg.call(e,"__wrapped__"),p=d&&Xg.call(t,"__wrapped__");if(h||p){var m=h?e.value():e,w=p?t.value():t;return s||(s=new on),i(m,w,r,n,s)}}return f?(s||(s=new on),XM(e,t,r,n,i,s)):!1}function Dw(e,t,r,n,i){return e===t?!0:e==null||t==null||!Us(e)&&!Us(t)?e!==e&&t!==t:tR(e,t,r,n,Dw,i)}function rR(e,t){return Dw(e,t)}class nR{capture(){}shutdown(){return Promise.resolve()}}const iR=Symbol("Let zodToJsonSchema decide on which parser to use"),sR={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},aR=e=>({...sR,...e}),oR=e=>{const t=aR(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function Fw(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Me(e,t,r,n,i){e[t]=r,Fw(e,t,n,i)}const Uw=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Rt(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Uw(t,e.currentPath):t.join("/")}}function cR(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ie.ZodAny&&(r.items=xe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Me(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Me(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Me(r,"minItems",e.exactLength.value,e.exactLength.message,t),Me(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function lR(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Me(r,"minimum",n.value,n.message,t):Me(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Me(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Me(r,"maximum",n.value,n.message,t):Me(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Me(r,"maximum",n.value,n.message,t));break;case"multipleOf":Me(r,"multipleOf",n.value,n.message,t);break}return r}function uR(){return{type:"boolean"}}function Bw(e,t){return xe(e.type._def,t)}const fR=(e,t)=>xe(e.innerType._def,t);function zw(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,s)=>zw(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return dR(e,t)}}const dR=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":Me(r,"minimum",n.value,n.message,t);break;case"max":Me(r,"maximum",n.value,n.message,t);break}return r};function hR(e,t){return{...xe(e.innerType._def,t),default:e.defaultValue()}}function pR(e,t){return t.effectStrategy==="input"?xe(e.schema._def,t):Rt(t)}function mR(e){return{type:"string",enum:Array.from(e.values)}}const gR=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function yR(e,t){const r=[xe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),xe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach(s=>{if(gR(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...c}=s;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function _R(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}let Su;const sr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Su===void 0&&(Su=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Su),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function qw(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":Me(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Me(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ar(r,"email",n.message,t);break;case"format:idn-email":ar(r,"idn-email",n.message,t);break;case"pattern:zod":yt(r,sr.email,n.message,t);break}break;case"url":ar(r,"uri",n.message,t);break;case"uuid":ar(r,"uuid",n.message,t);break;case"regex":yt(r,n.regex,n.message,t);break;case"cuid":yt(r,sr.cuid,n.message,t);break;case"cuid2":yt(r,sr.cuid2,n.message,t);break;case"startsWith":yt(r,RegExp(`^${Eu(n.value,t)}`),n.message,t);break;case"endsWith":yt(r,RegExp(`${Eu(n.value,t)}$`),n.message,t);break;case"datetime":ar(r,"date-time",n.message,t);break;case"date":ar(r,"date",n.message,t);break;case"time":ar(r,"time",n.message,t);break;case"duration":ar(r,"duration",n.message,t);break;case"length":Me(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Me(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{yt(r,RegExp(Eu(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&ar(r,"ipv4",n.message,t),n.version!=="v4"&&ar(r,"ipv6",n.message,t);break}case"base64url":yt(r,sr.base64url,n.message,t);break;case"jwt":yt(r,sr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&yt(r,sr.ipv4Cidr,n.message,t),n.version!=="v4"&&yt(r,sr.ipv6Cidr,n.message,t);break}case"emoji":yt(r,sr.emoji(),n.message,t);break;case"ulid":{yt(r,sr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ar(r,"binary",n.message,t);break}case"contentEncoding:base64":{Me(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{yt(r,sr.base64,n.message,t);break}}break}case"nanoid":yt(r,sr.nanoid,n.message,t)}return r}function Eu(e,t){return t.patternStrategy==="escape"?wR(e):e}const vR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function wR(e){let t="";for(let r=0;r<e.length;r++)vR.has(e[r])||(t+="\\"),t+=e[r];return t}function ar(e,t,r,n){e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Me(e,"format",t,r,n)}function yt(e,t,r,n){e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Qg(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Me(e,"pattern",Qg(t,n),r,n)}function Qg(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let i="",s=!1,a=!1,o=!1;for(let c=0;c<n.length;c++){if(s){i+=n[c],s=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){o?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],o=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
127
- ]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
128
- ]))`;continue}}if(r.s&&n[c]==="."){i+=a?`${n[c]}\r
129
- `:`[${n[c]}\r
130
- ]`;continue}i+=n[c],n[c]==="\\"?s=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Hw(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===ie.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??Rt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ie.ZodString&&e.keyType._def.checks?.length){const{type:n,...i}=qw(e.keyType._def,t);return{...r,propertyNames:i}}else{if(e.keyType?._def.typeName===ie.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ie.ZodBranded&&e.keyType._def.type._def.typeName===ie.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...i}=Bw(e.keyType._def,t);return{...r,propertyNames:i}}}return r}function bR(e,t){if(t.mapStrategy==="record")return Hw(e,t);const r=xe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Rt(t),n=xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Rt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function SR(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function ER(e){return e.target==="openAi"?void 0:{not:Rt({...e,currentPath:[...e.currentPath,"not"]})}}function TR(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ho={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function CR(e,t){if(t.target==="openApi3")return ey(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ho&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((i,s)=>{const a=Ho[s._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((i,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":if(s._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){const i=n.filter((s,a,o)=>o.indexOf(s)===a);return{type:i.length>1?i:i[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return ey(e,t)}const ey=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>xe(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function AR(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ho[e.innerType._def.typeName],nullable:!0}:{type:[Ho[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=xe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function OR(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",Fw(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Me(r,"minimum",n.value,n.message,t):Me(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Me(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Me(r,"maximum",n.value,n.message,t):Me(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Me(r,"maximum",n.value,n.message,t));break;case"multipleOf":Me(r,"multipleOf",n.value,n.message,t);break}return r}function xR(e,t){const r=t.target==="openAi",n={type:"object",properties:{}},i=[],s=e.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let l=kR(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=xe(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(n.properties[o]=u,l||i.push(o))}i.length&&(n.required=i);const a=PR(e,t);return a!==void 0&&(n.additionalProperties=a),n}function PR(e,t){if(e.catchall._def.typeName!=="ZodNever")return xe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function kR(e){try{return e.isOptional()}catch{return!0}}const IR=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return xe(e.innerType._def,t);const r=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Rt(t)},r]}:Rt(t)},MR=(e,t)=>{if(t.pipeStrategy==="input")return xe(e.in._def,t);if(t.pipeStrategy==="output")return xe(e.out._def,t);const r=xe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=xe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function RR(e,t){return xe(e.type._def,t)}function NR(e,t){const n={type:"array",uniqueItems:!0,items:xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Me(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Me(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function $R(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:xe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function LR(e){return{not:Rt(e)}}function jR(e){return Rt(e)}const DR=(e,t)=>xe(e.innerType._def,t),FR=(e,t,r)=>{switch(t){case ie.ZodString:return qw(e,r);case ie.ZodNumber:return OR(e,r);case ie.ZodObject:return xR(e,r);case ie.ZodBigInt:return lR(e,r);case ie.ZodBoolean:return uR();case ie.ZodDate:return zw(e,r);case ie.ZodUndefined:return LR(r);case ie.ZodNull:return TR(r);case ie.ZodArray:return cR(e,r);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return CR(e,r);case ie.ZodIntersection:return yR(e,r);case ie.ZodTuple:return $R(e,r);case ie.ZodRecord:return Hw(e,r);case ie.ZodLiteral:return _R(e,r);case ie.ZodEnum:return mR(e);case ie.ZodNativeEnum:return SR(e);case ie.ZodNullable:return AR(e,r);case ie.ZodOptional:return IR(e,r);case ie.ZodMap:return bR(e,r);case ie.ZodSet:return NR(e,r);case ie.ZodLazy:return()=>e.getter()._def;case ie.ZodPromise:return RR(e,r);case ie.ZodNaN:case ie.ZodNever:return ER(r);case ie.ZodEffects:return pR(e,r);case ie.ZodAny:return Rt(r);case ie.ZodUnknown:return jR(r);case ie.ZodDefault:return hR(e,r);case ie.ZodBranded:return Bw(e,r);case ie.ZodReadonly:return DR(e,r);case ie.ZodCatch:return fR(e,r);case ie.ZodPipeline:return MR(e,r);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return(n=>{})()}};function xe(e,t,r=!1){const n=t.seen.get(e);if(t.override){const o=t.override?.(e,t,n,r);if(o!==iR)return o}if(n&&!r){const o=UR(n,t);if(o!==void 0)return o}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const s=FR(e,e.typeName,t),a=typeof s=="function"?xe(s(),t):s;if(a&&BR(e,t,a),t.postProcess){const o=t.postProcess(a,e,t);return i.jsonSchema=a,o}return i.jsonSchema=a,a}const UR=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Uw(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Rt(t)):t.$refStrategy==="seen"?Rt(t):void 0}},BR=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),lo=(e,t)=>{const r=oR(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:xe(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Rt(r)}),{}):void 0;const i=typeof t=="string"?t:t?.name,s=xe(e._def,r,!1)??Rt(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const a=i===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};var zR=Object.defineProperty,Gw=(e,t)=>{for(var r in t)zR(e,r,{get:t[r],enumerable:!0})};const Go=(e,t)=>{const r=[...new Set(t?.map(i=>{if(typeof i=="string")return i;const s=new i({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=e.getType();return r.some(i=>i===n)};function Vw(e,t){return Array.isArray(e)?ty(e,t):Mt.from(r=>ty(r,e))}function ty(e,t={}){const{includeNames:r,excludeNames:n,includeTypes:i,excludeTypes:s,includeIds:a,excludeIds:o}=t,c=[];for(const l of e)if(!(n&&l.name&&n.includes(l.name))){{if(s&&Go(l,s))continue;if(o&&l.id&&o.includes(l.id))continue}i||a||r?(r&&l.name&&r.some(u=>u===l.name)||i&&Go(l,i)||a&&l.id&&a.some(u=>u===l.id))&&c.push(l):c.push(l)}return c}function qR(e){return Array.isArray(e)?ry(e):Mt.from(ry)}function ry(e){if(!e.length)return[];const t=[];for(const r of e){const n=r,i=t.pop();if(!i)t.push(n);else if(n.getType()==="tool"||n.getType()!==i.getType())t.push(i,n);else{const s=$o(i),a=$o(n),o=s.concat(a);typeof s.content=="string"&&typeof a.content=="string"&&(o.content=`${s.content}
131
- ${a.content}`),t.push(GR(o))}}return t}function Xd(e,t){if(Array.isArray(e)){const r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return ny(r,t)}else{const r=e;return Mt.from(n=>ny(n,r)).withConfig({runName:"trim_messages"})}}async function ny(e,t){const{maxTokens:r,tokenCounter:n,strategy:i="last",allowPartial:s=!1,endOn:a,startOn:o,includeSystem:c=!1,textSplitter:l}=t;if(o&&i==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&i==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let u;"getNumTokens"in n?u=async f=>(await Promise.all(f.map(p=>n.getNumTokens(p.content)))).reduce((p,m)=>p+m,0):u=async f=>n(f);let d=Jw;if(l&&("splitText"in l?d=l.splitText:d=async f=>l(f)),i==="first")return Ww(e,{maxTokens:r,tokenCounter:u,textSplitter:d,partialStrategy:s?"first":void 0,endOn:a});if(i==="last")return HR(e,{maxTokens:r,tokenCounter:u,textSplitter:d,allowPartial:s,includeSystem:c,startOn:o,endOn:a});throw new Error(`Unrecognized strategy: '${i}'. Must be one of 'first' or 'last'.`)}async function Ww(e,t){const{maxTokens:r,tokenCounter:n,textSplitter:i,partialStrategy:s,endOn:a}=t;let o=[...e],c=0;for(let l=0;l<o.length;l+=1){const u=l>0?o.slice(0,-l):o;if(await n(u)<=r){c=o.length-l;break}}if(c<o.length&&s){let l=!1;if(Array.isArray(o[c].content)){const u=o[c];if(typeof u.content=="string")throw new Error("Expected content to be an array.");const d=u.content.length,f=s==="last"?[...u.content].reverse():u.content;for(let h=1;h<=d;h+=1){const p=s==="first"?f.slice(0,h):f.slice(-h),m=Object.fromEntries(Object.entries(u).filter(([g])=>g!=="type"&&!g.startsWith("lc_"))),w=Qd(u.getType(),{...m,content:p}),y=[...o.slice(0,c),w];if(await n(y)<=r)o=y,c+=1,l=!0;else break}l&&s==="last"&&(u.content=[...f].reverse())}if(!l){const u=o[c];let d;if(Array.isArray(u.content)&&u.content.some(f=>typeof f=="string"||f.type==="text")?d=u.content.find(h=>h.type==="text"&&h.text)?.text:typeof u.content=="string"&&(d=u.content),d){const f=await i(d),h=f.length;s==="last"&&f.reverse();for(let p=0;p<h-1;p+=1)if(f.pop(),u.content=f.join(""),await n([...o.slice(0,c),u])<=r){s==="last"&&(u.content=[...f].reverse().join("")),o=[...o.slice(0,c),u],c+=1;break}}}}if(a){const l=Array.isArray(a)?a:[a];for(;c>0&&!Go(o[c-1],l);)c-=1}return o.slice(0,c)}async function HR(e,t){const{allowPartial:r=!1,includeSystem:n=!1,endOn:i,startOn:s,...a}=t;let o=e.map(u=>{const d=Object.fromEntries(Object.entries(u).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return Qd(u.getType(),d,Ms(u))});if(i){const u=Array.isArray(i)?i:[i];for(;o.length>0&&!Go(o[o.length-1],u);)o=o.slice(0,-1)}const c=n&&o[0]?.getType()==="system";let l=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return l=await Ww(l,{...a,partialStrategy:r?"last":void 0,endOn:s}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}const iy={human:{message:je,messageChunk:ia},ai:{message:fe,messageChunk:qt},system:{message:He,messageChunk:jn},developer:{message:He,messageChunk:jn},tool:{message:Ae,messageChunk:na},function:{message:fc,messageChunk:dc},generic:{message:zn,messageChunk:uc},remove:{message:sn,messageChunk:sn}};function Qd(e,t,r){let n,i;switch(e){case"human":r?n=new ia(t):i=new je(t);break;case"ai":if(r){let s={...t};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(a=>({...a,type:"tool_call_chunk",index:void 0,args:JSON.stringify(a.args)}))}),n=new qt(s)}else i=new fe(t);break;case"system":r?n=new jn(t):i=new He(t);break;case"developer":r?n=new jn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):i=new He({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)r?n=new na(t):i=new Ae(t);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new dc(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");i=new fc(t)}break;case"generic":if("role"in t)r?n=new uc(t):i=new zn(t);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&n)return n;if(i)return i;throw new Error(`Unrecognized message type ${e}`)}function GR(e){const t=e.getType();let r;const n=Object.fromEntries(Object.entries(e).filter(([i])=>!["type","tool_call_chunks"].includes(i)&&!i.startsWith("lc_")));if(t in iy&&(r=Qd(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(iy)}`);return r}function Jw(e){const t=e.split(`
132
- `);return Promise.resolve([...t.slice(0,-1).map(r=>`${r}
133
- `),t[t.length-1]])}const VR=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],WR=["image","video","audio","text-plain","file"],JR=["text","reasoning",...VR,...WR];var Kw={};pe(Kw,{AIMessage:()=>fe,AIMessageChunk:()=>qt,BaseMessage:()=>bt,BaseMessageChunk:()=>_n,ChatMessage:()=>zn,ChatMessageChunk:()=>uc,FunctionMessage:()=>fc,FunctionMessageChunk:()=>dc,HumanMessage:()=>je,HumanMessageChunk:()=>ia,KNOWN_BLOCK_TYPES:()=>JR,RemoveMessage:()=>sn,SystemMessage:()=>He,SystemMessageChunk:()=>jn,ToolMessage:()=>Ae,ToolMessageChunk:()=>na,_isMessageFieldWithRole:()=>G_,_mergeDicts:()=>dt,_mergeLists:()=>ra,_mergeObj:()=>H_,_mergeStatus:()=>q_,coerceMessageLikeToMessage:()=>Er,convertToChunk:()=>$o,convertToOpenAIImageBlock:()=>F_,convertToProviderContentBlock:()=>IC,defaultTextSplitter:()=>Jw,defaultToolCallParser:()=>bd,filterMessages:()=>Vw,getBufferString:()=>Cd,iife:()=>dA,isAIMessage:()=>Td,isAIMessageChunk:()=>Yu,isBase64ContentBlock:()=>yd,isBaseMessage:()=>st,isBaseMessageChunk:()=>Ms,isChatMessage:()=>iA,isChatMessageChunk:()=>sA,isDataContentBlock:()=>hn,isDirectToolOutput:()=>wd,isFunctionMessage:()=>aA,isFunctionMessageChunk:()=>oA,isHumanMessage:()=>cA,isHumanMessageChunk:()=>lA,isIDContentBlock:()=>D_,isMessage:()=>z_,isOpenAIToolCallArray:()=>JC,isPlainTextContentBlock:()=>PC,isSystemMessage:()=>uA,isSystemMessageChunk:()=>fA,isToolMessage:()=>Sd,isToolMessageChunk:()=>W_,isURLContentBlock:()=>gd,mapChatMessagesToStoredMessages:()=>yA,mapStoredMessageToChatMessage:()=>Ad,mapStoredMessagesToChatMessages:()=>gA,mergeContent:()=>Bn,mergeMessageRuns:()=>qR,mergeResponseMetadata:()=>K_,mergeUsageMetadata:()=>Y_,parseBase64DataUrl:()=>Ku,parseMimeType:()=>kC,trimMessages:()=>Xd});var qs=class extends we{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){const r=Se(t);return this.func&&await this.func(e,r),this._callWithConfig(n=>Promise.resolve(n),e,r)}async*transform(e,t){const r=Se(t);let n,i=!0;for await(const s of this._transformStreamWithConfig(e,a=>a,r))if(yield s,i)if(n===void 0)n=s;else try{n=mn(n,s)}catch{n=void 0,i=!1}this.func&&n!==void 0&&await this.func(n,r)}static assign(e){return new Fd(new is({steps:e}))}};const KR=e=>e();function Tu(e){const t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var Zw={};pe(Zw,{BaseChatModel:()=>Wn,SimpleChatModel:()=>ZR});function Cu(e){const t=[];for(const r of e){let n=r;if(Array.isArray(r.content))for(let i=0;i<r.content.length;i++){const s=r.content[i];(gd(s)||yd(s))&&n===r&&(n=new r.constructor({...n,content:[...r.content.slice(0,i),F_(s),...r.content.slice(i+1)]}))}t.push(n)}return t}var Wn=class En extends bc{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=KR(()=>{const r=t.outputVersion??Fr("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){const[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async invoke(t,r){const n=En._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}async*_streamIterator(t,r){if(this._streamResponseChunks===En.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,r);else{const i=En._convertInputToPromptValue(t).toChatMessages(),[s,a]=this._separateRunnableConfigFromCallOptionsCompat(r),o={...s.metadata,...this.getLsParams(a)},c=await St.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:a,invocation_params:this?.invocationParams(a),batch_size:1},u=a.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[Cu(i)],s.runId,void 0,l,void 0,void 0,s.runName);let f,h;try{for await(const p of this._streamResponseChunks(i,a,d?.[0])){if(p.message.id==null){const m=d?.at(0)?.runId;m!=null&&p.message._updateId(`run-${m}`)}p.message.response_metadata={...p.generationInfo,...p.message.response_metadata},u==="v1"?yield Tu(p.message):yield p.message,f?f=f.concat(p):f=p,Yu(p.message)&&p.message.usage_metadata!==void 0&&(h={tokenUsage:{promptTokens:p.message.usage_metadata.input_tokens,completionTokens:p.message.usage_metadata.output_tokens,totalTokens:p.message.usage_metadata.total_tokens}})}}catch(p){throw await Promise.all((d??[]).map(m=>m?.handleLLMError(p))),p}await Promise.all((d??[]).map(p=>p?.handleLLMEnd({generations:[[f]],llmOutput:h})))}}getLsParams(t){const r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:r}}async _generateUncached(t,r,n,i){const s=t.map(f=>f.map(Er));let a;if(i!==void 0&&i.length===s.length)a=i;else{const f={...n.metadata,...this.getLsParams(r)},h=await St.configure(n.callbacks,this.callbacks,n.tags,this.tags,f,this.metadata,{verbose:this.verbose}),p={options:r,invocation_params:this?.invocationParams(r),batch_size:1};a=await h?.handleChatModelStart(this.toJSON(),s.map(Cu),n.runId,void 0,p,void 0,void 0,n.runName)}const o=r.outputVersion??this.outputVersion,c=[],l=[];if(!!a?.[0].handlers.find(Od)&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==En.prototype._streamResponseChunks)try{const f=await this._streamResponseChunks(s[0],r,a?.[0]);let h,p;for await(const m of f){if(m.message.id==null){const w=a?.at(0)?.runId;w!=null&&m.message._updateId(`run-${w}`)}h===void 0?h=m:h=mn(h,m),Yu(m.message)&&m.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}if(h===void 0)throw new Error("Received empty response from chat model call.");c.push([h]),await a?.[0].handleLLMEnd({generations:c,llmOutput:p})}catch(f){throw await a?.[0].handleLLMError(f),f}else{const f=await Promise.allSettled(s.map(async(h,p)=>{const m=await this._generate(h,{...r,promptIndex:p},a?.[p]);if(o==="v1")for(const w of m.generations)w.message=Tu(w.message);return m}));await Promise.all(f.map(async(h,p)=>{if(h.status==="fulfilled"){const m=h.value;for(const w of m.generations){if(w.message.id==null){const y=a?.at(0)?.runId;y!=null&&w.message._updateId(`run-${y}`)}w.message.response_metadata={...w.generationInfo,...w.message.response_metadata}}return m.generations.length===1&&(m.generations[0].message.response_metadata={...m.llmOutput,...m.generations[0].message.response_metadata}),c[p]=m.generations,l[p]=m.llmOutput,a?.[p]?.handleLLMEnd({generations:[m.generations],llmOutput:m.llmOutput})}else return await a?.[p]?.handleLLMError(h.reason),Promise.reject(h.reason)}))}const d={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(d,Ds,{value:a?{runIds:a?.map(f=>f.runId)}:void 0,configurable:!0}),d}async _generateCached({messages:t,cache:r,llmStringKey:n,parsedOptions:i,handledOptions:s}){const a=t.map(y=>y.map(Er)),o={...s.metadata,...this.getLsParams(i)},c=await St.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:i,invocation_params:this?.invocationParams(i),batch_size:1},u=await c?.handleChatModelStart(this.toJSON(),a.map(Cu),s.runId,void 0,l,void 0,void 0,s.runName),d=[],h=(await Promise.allSettled(a.map(async(y,g)=>{const _=En._convertInputToPromptValue(y).toString(),b=await r.lookup(_,n);return b==null&&d.push(g),b}))).map((y,g)=>({result:y,runManager:u?.[g]})).filter(({result:y})=>y.status==="fulfilled"&&y.value!=null||y.status==="rejected"),p=i.outputVersion??this.outputVersion,m=[];await Promise.all(h.map(async({result:y,runManager:g},_)=>{if(y.status==="fulfilled"){const b=y.value;return m[_]=b.map(A=>("message"in A&&st(A.message)&&Td(A.message)&&(A.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},p==="v1"&&(A.message=Tu(A.message))),A.generationInfo={...A.generationInfo,tokenUsage:{}},A)),b.length&&await g?.handleLLMNewToken(b[0].text),g?.handleLLMEnd({generations:[b]},void 0,void 0,void 0,{cached:!0})}else return await g?.handleLLMError(y.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(y.reason)}));const w={generations:m,missingPromptIndices:d,startedRunManagers:u};return Object.defineProperty(w,Ds,{value:u?{runIds:u?.map(y=>y.runId)}:void 0,configurable:!0}),w}async generate(t,r,n){let i;Array.isArray(r)?i={stop:r}:i=r;const s=t.map(p=>p.map(Er)),[a,o]=this._separateRunnableConfigFromCallOptionsCompat(i);if(a.callbacks=a.callbacks??n,!this.cache)return this._generateUncached(s,o,a);const{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(o),{generations:u,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({messages:s,cache:c,llmStringKey:l,parsedOptions:o,handledOptions:a});let h={};if(d.length>0){const p=await this._generateUncached(d.map(m=>s[m]),o,a,f!==void 0?d.map(m=>f?.[m]):void 0);await Promise.all(p.generations.map(async(m,w)=>{const y=d[w];u[y]=m;const g=En._convertInputToPromptValue(s[y]).toString();return c.update(g,l,m)})),h=p.llmOutput??{}}return{generations:u,llmOutput:h}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,r,n){const i=t.map(s=>s.toChatMessages());return this.generate(i,r,n)}withStructuredOutput(t,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');const n=t,i=r?.name,s=Hi(n)??"A function available to call.",a=r?.method,o=r?.includeRaw;if(a==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=i??"extract",l;qn(n)?l=[{type:"function",function:{name:c,description:s,parameters:zt(n)}}]:("name"in n&&(c=n.name),l=[{type:"function",function:{name:c,description:s,parameters:n}}]);const u=this.bindTools(l),d=Mt.from(m=>{if(!qt.isInstance(m))throw new Error("Input is not an AIMessageChunk.");if(!m.tool_calls||m.tool_calls.length===0)throw new Error("No tool calls found in the response.");const w=m.tool_calls.find(y=>y.name===c);if(!w)throw new Error(`No tool call found with name ${c}.`);return w.args});if(!o)return u.pipe(d).withConfig({runName:"StructuredOutput"});const f=qs.assign({parsed:(m,w)=>d.invoke(m.raw,w)}),h=qs.assign({parsed:()=>null}),p=f.withFallbacks({fallbacks:[h]});return er.from([{raw:u},p]).withConfig({runName:"StructuredOutputRunnable"})}},ZR=class extends Wn{async _generate(e,t,r){const n=await this._call(e,t,r),i=new fe(n);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}},YR=class extends we{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){const{key:r,input:n}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.invoke(n,Se(t))}async batch(e,t,r){const n=e.map(d=>d.key),i=e.map(d=>d.input);if(n.find(d=>this.runnables[d]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const a=n.map(d=>this.runnables[d]),o=this._getOptionsList(t??{},e.length),c=o[0]?.maxConcurrency??r?.maxConcurrency,l=c&&c>0?c:e.length,u=[];for(let d=0;d<i.length;d+=l){const f=i.slice(d,d+l).map((p,m)=>a[m].invoke(p,o[m])),h=await Promise.all(f);u.push(h)}return u.flat()}async stream(e,t){const{key:r,input:n}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.stream(n,t)}},XR=class extends we{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const r=e.slice(0,-1).map(([i,s])=>[ct(i),ct(s)]),n=ct(e[e.length-1]);return new this({branches:r,default:n})}async _invoke(e,t,r){let n;for(let i=0;i<this.branches.length;i+=1){const[s,a]=this.branches[i];if(await s.invoke(e,ke(t,{callbacks:r?.getChild(`condition:${i+1}`)}))){n=await a.invoke(e,ke(t,{callbacks:r?.getChild(`branch:${i+1}`)}));break}}return n||(n=await this.default.invoke(e,ke(t,{callbacks:r?.getChild("branch:default")}))),n}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){const n=await(await Pt(t))?.handleChainStart(this.toJSON(),tt(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName);let i,s=!0,a;try{for(let o=0;o<this.branches.length;o+=1){const[c,l]=this.branches[o];if(await c.invoke(e,ke(t,{callbacks:n?.getChild(`condition:${o+1}`)}))){a=await l.stream(e,ke(t,{callbacks:n?.getChild(`branch:${o+1}`)}));for await(const d of a)if(yield d,s)if(i===void 0)i=d;else try{i=mn(i,d)}catch{i=void 0,s=!1}break}}if(a===void 0){a=await this.default.stream(e,ke(t,{callbacks:n?.getChild("branch:default")}));for await(const o of a)if(yield o,s)if(i===void 0)i=o;else try{i=mn(i,o)}catch{i=void 0,s=!1}}}catch(o){throw await n?.handleChainError(o),o}await n?.handleChainEnd(i??{})}},QR=class extends ft{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=Mt.from((s,a)=>this._enterHistory(s,a??{})).withConfig({runName:"loadHistory"});const r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=qs.assign({[r]:t}).withConfig({runName:"insertHistory"}));const n=t.pipe(e.runnable.withListeners({onEnd:(s,a)=>this._exitHistory(s,a??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:n}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!st(e)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="input",Array.isArray(e[r])&&Array.isArray(e[r][0])?t=e[r][0]:t=e[r]}else t=e;if(typeof t=="string")return[new je(t)];if(Array.isArray(t))return t;if(st(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
134
- Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!st(e)&&typeof e!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[r]}else t=e;if(typeof t=="string")return[new fe(t)];if(Array.isArray(t))return t;if(st(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){const n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){const r=t.configurable?.messageHistory;let n;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?n=e.inputs[0]:n=e.inputs;let i=this._getInputMessages(n);if(this.historyMessagesKey===void 0){const o=await r.getMessages();i=i.slice(o.length)}const s=e.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const a=this._getOutputMessages(s);await r.addMessages([...i,...a])}async _mergeConfig(...e){const t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){const n={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
135
- eg. chain.invoke(${JSON.stringify(n)}, ${JSON.stringify(i)})`)}const{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}},Yw={};pe(Yw,{RouterRunnable:()=>YR,Runnable:()=>we,RunnableAssign:()=>Fd,RunnableBinding:()=>ft,RunnableBranch:()=>XR,RunnableEach:()=>bP,RunnableLambda:()=>Mt,RunnableMap:()=>is,RunnableParallel:()=>TP,RunnablePassthrough:()=>qs,RunnablePick:()=>hw,RunnableRetry:()=>Dd,RunnableSequence:()=>er,RunnableToolLike:()=>mf,RunnableWithFallbacks:()=>dw,RunnableWithMessageHistory:()=>QR,_coerceToRunnable:()=>ct,ensureConfig:()=>Se,getCallbackManagerForConfig:()=>Pt,mergeConfigs:()=>Bt,patchConfig:()=>ke,pickRunnableConfigKeys:()=>qr});var e1={};Gw(e1,{ConfigurableModel:()=>bf,MODEL_PROVIDER_CONFIG:()=>Ac,_inferModelProvider:()=>eb,getChatModelByClassName:()=>Qw,initChatModel:()=>la});const Ac={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},fireworks:{package:"@langchain/community/chat_models/fireworks",className:"ChatFireworks",hasCircularDependency:!0},together:{package:"@langchain/community/chat_models/togetherai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/community/chat_models/perplexity",className:"ChatPerplexity",hasCircularDependency:!0}},Xw=Object.keys(Ac);async function Qw(e){const t=Object.entries(Ac).find(([,n])=>n.className===e);if(!t)return;const[,r]=t;try{return(await import(r.package))[r.className]}catch(n){const i=n;if("code"in i&&i.code?.toString().includes("ERR_MODULE_NOT_FOUND")){const s=i.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function t1(e,t,r={}){const n=t||eb(e);if(!n)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);const i=Ac[n];if(!i){const c=Xw.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
136
-
137
- Supported model providers are: ${c}`)}const{modelProvider:s,...a}=r,o=await Qw(i.className);return new o({model:e,...a})}function eb(e){return e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?"openai":e.startsWith("claude")?"anthropic":e.startsWith("command")?"cohere":e.startsWith("accounts/fireworks")?"fireworks":e.startsWith("gemini")?"google-vertexai":e.startsWith("amazon.")?"bedrock":e.startsWith("mistral")?"mistralai":e.startsWith("sonar")||e.startsWith("pplx")?"perplexity":void 0}var bf=class uo extends Wn{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};constructor(t){super(t),this._defaultConfig=t.defaultConfig??{},t.configurableFields==="any"?this._configurableFields="any":this._configurableFields=t.configurableFields??["model","modelProvider"],t.configPrefix?this._configPrefix=t.configPrefix.endsWith("_")?t.configPrefix:`${t.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=t.queuedMethodOperations??this._queuedMethodOperations}async _model(t){const r={...this._defaultConfig,...this._modelParams(t)};let n=await t1(r.model,r.modelProvider,r);const i=Object.entries(this._queuedMethodOperations);if(i.length>0)for(const[s,a]of i)s in n&&typeof n[s]=="function"&&(n=await n[s](...a));return n}async _generate(t,r,n){return(await this._model(r))._generate(t,r??{},n)}bindTools(t,r){const n={...this._queuedMethodOperations};return n.bindTools=[t,r],new uo({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(t,...r)=>{const n={...this._queuedMethodOperations};return n.withStructuredOutput=[t,...r],new uo({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(t){const r=t?.configurable??{};let n={};for(const[i,s]of Object.entries(r))if(i.startsWith(this._configPrefix)){const a=this._removePrefix(i,this._configPrefix);n[a]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([i])=>this._configurableFields.includes(i)))),n}_removePrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}withConfig(t){const r={...t||{}},n=this._modelParams(r),i=Object.fromEntries(Object.entries(r).filter(([a])=>a!=="configurable"));i.configurable=Object.fromEntries(Object.entries(r.configurable||{}).filter(([a])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(a,this._configPrefix))));const s=new uo({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new ft({config:r,bound:s})}async invoke(t,r){const n=await this._model(r),i=Se(r);return n.invoke(t,i)}async stream(t,r){const n=await this._model(r),i=new vn({generator:await n.stream(t,r),config:r});return await i.setup,ht.fromAsyncGenerator(i)}async batch(t,r,n){return super.batch(t,r,n)}async*transform(t,r){const n=await this._model(r),i=Se(r);yield*n.transform(t,i)}async*streamLog(t,r,n){const i=await this._model(r),s=Se(r);yield*i.streamLog(t,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(t,r,n){const i=this;async function*s(){const a=await i._model(r),o=Se(r),c=a.streamEvents(t,o,n);for await(const l of c)yield l}return ht.fromAsyncGenerator(s())}};async function la(e,t){let{configurableFields:r,configPrefix:n,modelProvider:i,...s}={configPrefix:"",...t??{}};if(i===void 0&&e?.includes(":")){const[c,...l]=e.split(":"),u=l.length===0?[c]:[c,l.join(":")];Xw.includes(u[0])&&([i,e]=u)}let a=Array.isArray(r)?[...r]:r;!e&&a===void 0&&(a=["model","modelProvider"]),n&&a===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);const o={...s};return a===void 0?new bf({defaultConfig:{...o,model:e,modelProvider:i},configPrefix:n}):(e&&(o.model=e),i&&(o.modelProvider=i),new bf({defaultConfig:o,configPrefix:n,configurableFields:a}))}var Sf=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},Ef=class extends Error{toolNames;constructor(e){super(`The model has called multiple tools: ${e.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=e}},tb=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(r=>`
138
- - ${r}`).join("")}.`),this.toolName=e,this.errors=t}},eh=class extends Error{toolCall;toolError;constructor(e,t){const r=e instanceof Error?e:new Error(String(e)),n=JSON.stringify(t.args);super(`Error invoking tool '${t.name}' with kwargs ${n} with error: ${r.stack}
139
- Please fix the error and try again.`),this.toolCall=t,this.toolError=r}};function th(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function Vo(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_model"in e&&typeof e._model=="function"}var rb={};pe(rb,{extendInteropZodObject:()=>Dv,getInteropZodDefaultGetter:()=>yc,getInteropZodObjectShape:()=>Ls,getSchemaDescription:()=>Hi,interopParse:()=>an,interopParseAsync:()=>mc,interopSafeParse:()=>dx,interopSafeParseAsync:()=>Id,interopZodObjectMakeFieldsOptional:()=>Fv,interopZodObjectPartial:()=>Nd,interopZodObjectPassthrough:()=>sf,interopZodObjectStrict:()=>Do,interopZodTransformInputSchema:()=>ni,isInteropZodLiteral:()=>fx,isInteropZodObject:()=>Ot,isInteropZodSchema:()=>qn,isShapelessZodSchema:()=>hx,isSimpleStringZodSchema:()=>Md,isZodArrayV4:()=>gc,isZodLiteralV3:()=>Lv,isZodLiteralV4:()=>jv,isZodObjectV3:()=>Rd,isZodObjectV4:()=>Tr,isZodSchema:()=>ux,isZodSchemaV3:()=>Qe,isZodSchemaV4:()=>We});let r1=0;var Qr=class Tf{constructor(t,r,n){this.schema=t,this.tool=r,this.options=n}get name(){return this.tool.function.name}static fromSchema(t,r){function n(o){return o??`extract-${++r1}`}if(qn(t)){const o=zt(t),c={type:"function",function:{name:n(),strict:!1,description:o.description??"Tool for extracting structured output from the model's response.",parameters:o}};return new Tf(o,c,r)}let i;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?i=t:i={name:n(t.title),description:t.description??"",parameters:t.schema||t};const s=zt(t),a={type:"function",function:i};return new Tf(s,a,r)}parse(t){const n=new id(this.schema).validate(t);if(!n.valid)throw new tb(this.name,n.errors.map(i=>i.error));return t}},On=class nb{_schemaType;constructor(t){this.schema=t}static fromSchema(t){const r=zt(t);return new nb(r)}parse(t){if(!(typeof t.content!="string"||t.content===""))try{const r=JSON.parse(t.content);return new id(this.schema).validate(r).valid?r:void 0}catch{}}};function ib(e,t,r){if(!e)return[];if(typeof e=="object"&&e!==null&&"__responseFormatUndefined"in e)return[];if(Array.isArray(e)){if(e.every(i=>i instanceof Qr||i instanceof On))return e;if(e.every(i=>Ot(i)))return e.map(i=>Qr.fromSchema(i,t));if(e.every(i=>typeof i=="object"&&i!==null&&!Ot(i)))return e.map(i=>Qr.fromSchema(i,t));throw new Error(`Invalid response format: list contains mixed types.
140
- All items must be either InteropZodObject or plain JSON schema objects.`)}if(e instanceof Qr||e instanceof On)return[e];const n=rh(r);if(Ot(e))return n?[On.fromSchema(e)]:[Qr.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return n?[On.fromSchema(e)]:[Qr.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function n1(e,t){return ib(e,t)}function i1(e){return On.fromSchema(e)}const s1=["ChatOpenAI","ChatXAI"],sy=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function rh(e){if(!e)return!1;if(typeof e=="string"){const r=e.split(":").pop();return sy.some(n=>r.includes(n))}if(Vo(e))return rh(e._defaultConfig.model);if(!th(e))return!1;const t=e.getName();return!!(t==="FakeToolCallingChatModel"||s1.includes(t)&&("model"in e&&sy.some(r=>typeof e.model=="string"&&e.model.includes(r))||t==="FakeToolCallingModel"&&"structuredResponse"in e))}function nh(e){let t=0;for(const r of e){let n;typeof r.content=="string"?n=r.content:Array.isArray(r.content)?n=r.content.map(i=>typeof i=="string"?i:i.type==="text"&&"text"in i?i.text:"").join(""):n="",t+=n.length}return Math.ceil(t/4)}function rn(e){if(!(!e||typeof e=="function"))return e.canJumpTo}function Oc(e){return typeof e=="function"?e:e.hook}function tr(e){return{name:e.name,stateSchema:e.stateSchema,contextSchema:e.contextSchema,wrapToolCall:e.wrapToolCall,wrapModelCall:e.wrapModelCall,beforeAgent:e.beforeAgent,beforeModel:e.beforeModel,afterModel:e.afterModel,afterAgent:e.afterAgent,tools:e.tools??[]}}function sb(e){return CA({clockseq:e})}function si(e,t){const r=t.replace(/-/g,"").match(/.{2}/g).map(n=>parseInt(n,16));return xs(e,new Uint8Array(r))}const a1="__error__",fo="__scheduled__",o1="__interrupt__",c1="__resume__";var ay="[...]",l1="[Circular]",Wo=[],ai=[];function u1(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function f1(e,t,r,n){typeof n>"u"&&(n=u1()),Cf(e,"",0,[],void 0,0,n);var i;try{ai.length===0?i=JSON.stringify(e,t,r):i=JSON.stringify(e,d1(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Wo.length!==0;){var s=Wo.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return i}function Au(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:e}),Wo.push([n,r,t,i])):ai.push([t,r,e]):(n[r]=e,Wo.push([n,r,t]))}function Cf(e,t,r,n,i,s,a){s+=1;var o;if(typeof e=="object"&&e!==null){for(o=0;o<n.length;o++)if(n[o]===e){Au(l1,e,t,i);return}if(typeof a.depthLimit<"u"&&s>a.depthLimit){Au(ay,e,t,i);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Au(ay,e,t,i);return}if(n.push(e),Array.isArray(e))for(o=0;o<e.length;o++)Cf(e[o],o,o,n,e,s,a);else{var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];Cf(e[l],l,o,n,e,s,a)}}n.pop()}}function d1(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(ai.length>0)for(var n=0;n<ai.length;n++){var i=ai[n];if(i[1]===t&&i[0]===r){r=i[2],ai.splice(n,1);break}}return e.call(this,t,r)}}const h1=[];var p1={},ab={};pe(ab,{BaseChatMessageHistory:()=>ob,BaseListChatMessageHistory:()=>ih,InMemoryChatMessageHistory:()=>m1});var ob=class extends Qt{async addMessages(e){for(const t of e)await this.addMessage(t)}},ih=class extends Qt{addUserMessage(e){return this.addMessage(new je(e))}addAIMessage(e){return this.addMessage(new fe(e))}async addMessages(e){for(const t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}},m1=class extends ih{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},cb={};pe(cb,{Embeddings:()=>sh});var sh=class{caller;constructor(e){this.caller=new oa(e??{})}},g1={},lb={};pe(lb,{BaseMemory:()=>y1,getInputValue:()=>_1,getOutputValue:()=>v1,getPromptInputKey:()=>w1});var y1=class{};const ub=(e,t)=>{if(t!==void 0)return e[t];const r=Object.keys(e);if(r.length===1)return e[r[0]]},_1=(e,t)=>{const r=ub(e,t);if(!r){const n=Object.keys(e);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},v1=(e,t)=>{const r=ub(e,t);if(!r&&r!==""){const n=Object.keys(e);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function w1(e,t){const r=Object.keys(e).filter(n=>!t.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var fb={};pe(fb,{BaseStore:()=>db,InMemoryStore:()=>hb});var db=class extends Qt{},hb=class extends db{lc_namespace=["langchain","storage"];store={};async mget(e){return e.map(t=>this.store[t])}async mset(e){for(const[t,r]of e)this.store[t]=r}async mdelete(e){for(const t of e)delete this.store[t]}async*yieldKeys(e){const t=Object.keys(this.store);for(const r of t)(e===void 0||r.startsWith(e))&&(yield r)}},pb={};pe(pb,{BaseRetriever:()=>ah});var ah=class extends we{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){const r=Se(sa(t)),i=await(await St.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{const s=await this._getRelevantDocuments(e,i);return await i?.handleRetrieverEnd(s),s}catch(s){throw await i?.handleRetrieverError(s),s}}},mb={};pe(mb,{SaveableVectorStore:()=>b1,VectorStore:()=>oh,VectorStoreRetriever:()=>ho});var ho=class extends ah{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},oh=class extends Qt{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(s=>s[0])}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,i,s){if(typeof e=="number")return new ho({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:i,verbose:s,callbacks:r});{const a={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new ho({...a,searchKwargs:e.searchKwargs}):new ho({...a})}}},b1=class extends oh{static load(e,t){throw new Error("Not implemented")}},gb={};pe(gb,{BaseDocumentLoader:()=>yb});var yb=class{},_b={};pe(_b,{LangSmithLoader:()=>S1});var S1=class extends yb{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new zi(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??E1,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){const e=[];for await(const t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let r=t.inputs;for(const s of this.contentKey)r=r[s];const n=this.formatContent(r),i=t;["created_at","modified_at"].forEach(s=>{s in i&&typeof i[s]=="object"&&(i[s]=i[s].toString())}),e.push({pageContent:n,metadata:i})}return e}};function E1(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Ur=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}},vb=class extends we{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},T1=class extends vb{async transformDocuments(e){const t=[];for(const r of e){const n=await this._transformDocument(r);t.push(n)}return t}},wb={};pe(wb,{BaseDocumentTransformer:()=>vb,Document:()=>Ur,MappingDocumentTransformer:()=>T1});var ch=class extends Qt{lc_namespace=["langchain_core","example_selectors","base"]},bb=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},C1=class extends bb{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(const[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}};function A1(e){return e._modelType()==="base_llm"}function O1(e){return e._modelType()==="base_chat_model"}function oy(e){return e.split(/\n| /).length}var x1=class Sb extends ch{examples=[];examplePrompt;getTextLength=oy;maxLength=2048;exampleTextLengths=[];constructor(t){super(t),this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??oy}async addExample(t){this.examples.push(t);const r=await this.examplePrompt.format(t);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(t,r){if(t.length>0)return t;const{examples:n,examplePrompt:i}=r;return(await Promise.all(n.map(a=>i.format(a)))).map(a=>this.getTextLength(a))}async selectExamples(t){const r=Object.values(t).join(" ");let n=this.maxLength-this.getTextLength(r),i=0;const s=[];for(;n>0&&i<this.examples.length;){const a=n-this.exampleTextLengths[i];if(a<0)break;s.push(this.examples[i]),n=a,i+=1}return s}static async fromExamples(t,r){const n=new Sb(r);return await Promise.all(t.map(i=>n.addExample(i))),n}};function Ou(e){return Object.keys(e).sort().map(t=>e[t])}var P1=class Eb extends ch{vectorStoreRetriever;exampleKeys;inputKeys;constructor(t){if(super(t),this.exampleKeys=t.exampleKeys,this.inputKeys=t.inputKeys,t.vectorStore!==void 0)this.vectorStoreRetriever=t.vectorStore.asRetriever({k:t.k??4,filter:t.filter});else if(t.vectorStoreRetriever)this.vectorStoreRetriever=t.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(t){const r=this.inputKeys??Object.keys(t),n=Ou(r.reduce((i,s)=>({...i,[s]:t[s]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Ur({pageContent:n,metadata:t})])}async selectExamples(t){const r=this.inputKeys??Object.keys(t),n=Ou(r.reduce((a,o)=>({...a,[o]:t[o]}),{})).join(" "),s=(await this.vectorStoreRetriever.invoke(n)).map(a=>a.metadata);return this.exampleKeys?s.map(a=>this.exampleKeys.reduce((o,c)=>({...o,[c]:a[c]}),{})):s}static async fromExamples(t,r,n,i={}){const s=i.inputKeys??null,a=t.map(c=>Ou(s?s.reduce((l,u)=>({...l,[u]:c[u]}),{}):c).join(" ")),o=await n.fromTexts(a,t,r,i);return new Eb({vectorStore:o,k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},Tb={};pe(Tb,{BaseExampleSelector:()=>ch,BasePromptSelector:()=>bb,ConditionalPromptSelector:()=>C1,LengthBasedExampleSelector:()=>x1,SemanticSimilarityExampleSelector:()=>P1,isChatModel:()=>O1,isLLM:()=>A1});var Cb={};pe(Cb,{BaseLLM:()=>Ab,LLM:()=>lh});var Ab=class gs extends bc{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,r){const n=gs._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){const[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async*_streamIterator(t,r){if(this._streamResponseChunks===gs.prototype._streamResponseChunks)yield this.invoke(t,r);else{const n=gs._convertInputToPromptValue(t),[i,s]=this._separateRunnableConfigFromCallOptionsCompat(r),a=await St.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),o={options:s,invocation_params:this?.invocationParams(s),batch_size:1},c=await a?.handleLLMStart(this.toJSON(),[n.toString()],i.runId,void 0,o,void 0,void 0,i.runName);let l=new Vi({text:""});try{for await(const u of this._streamResponseChunks(n.toString(),s,c?.[0]))l?l=l.concat(u):l=u,typeof u.text=="string"&&(yield u.text)}catch(u){throw await Promise.all((c??[]).map(d=>d?.handleLLMError(u))),u}await Promise.all((c??[]).map(u=>u?.handleLLMEnd({generations:[[l]]})))}}async generatePrompt(t,r,n){const i=t.map(s=>s.toString());return this.generate(i,r,n)}invocationParams(t){return{}}_flattenLLMResult(t){const r=[];for(let n=0;n<t.generations.length;n+=1){const i=t.generations[n];if(n===0)r.push({generations:[i],llmOutput:t.llmOutput});else{const s=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[i],llmOutput:s})}}return r}async _generateUncached(t,r,n,i){let s;if(i!==void 0&&i.length===t.length)s=i;else{const l=await St.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),u={options:r,invocation_params:this?.invocationParams(r),batch_size:t.length};s=await l?.handleLLMStart(this.toJSON(),t,n.runId,void 0,u,void 0,void 0,n?.runName)}const a=!!s?.[0].handlers.find(Od);let o;if(a&&t.length===1&&this._streamResponseChunks!==gs.prototype._streamResponseChunks)try{const l=await this._streamResponseChunks(t[0],r,s?.[0]);let u;for await(const d of l)u===void 0?u=d:u=mn(u,d);if(u===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[u]],llmOutput:{}},await s?.[0].handleLLMEnd(o)}catch(l){throw await s?.[0].handleLLMError(l),l}else{try{o=await this._generate(t,r,s?.[0])}catch(u){throw await Promise.all((s??[]).map(d=>d?.handleLLMError(u))),u}const l=this._flattenLLMResult(o);await Promise.all((s??[]).map((u,d)=>u?.handleLLMEnd(l[d])))}const c=s?.map(l=>l.runId)||void 0;return Object.defineProperty(o,Ds,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:t,cache:r,llmStringKey:n,parsedOptions:i,handledOptions:s,runId:a}){const o=await St.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this?.invocationParams(i),batch_size:t.length},l=await o?.handleLLMStart(this.toJSON(),t,a,void 0,c,void 0,void 0,s?.runName),u=[],f=(await Promise.allSettled(t.map(async(m,w)=>{const y=await r.lookup(m,n);return y==null&&u.push(w),y}))).map((m,w)=>({result:m,runManager:l?.[w]})).filter(({result:m})=>m.status==="fulfilled"&&m.value!=null||m.status==="rejected"),h=[];await Promise.all(f.map(async({result:m,runManager:w},y)=>{if(m.status==="fulfilled"){const g=m.value;return h[y]=g.map(_=>(_.generationInfo={..._.generationInfo,tokenUsage:{}},_)),g.length&&await w?.handleLLMNewToken(g[0].text),w?.handleLLMEnd({generations:[g]},void 0,void 0,void 0,{cached:!0})}else return await w?.handleLLMError(m.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(m.reason)}));const p={generations:h,missingPromptIndices:u,startedRunManagers:l};return Object.defineProperty(p,Ds,{value:l?{runIds:l?.map(m=>m.runId)}:void 0,configurable:!0}),p}async generate(t,r,n){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let i;Array.isArray(r)?i={stop:r}:i=r;const[s,a]=this._separateRunnableConfigFromCallOptionsCompat(i);if(s.callbacks=s.callbacks??n,!this.cache)return this._generateUncached(t,a,s);const{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(a),{generations:l,missingPromptIndices:u,startedRunManagers:d}=await this._generateCached({prompts:t,cache:o,llmStringKey:c,parsedOptions:a,handledOptions:s,runId:s.runId});let f={};if(u.length>0){const h=await this._generateUncached(u.map(p=>t[p]),a,s,d!==void 0?u.map(p=>d?.[p]):void 0);await Promise.all(h.generations.map(async(p,m)=>{const w=u[m];return l[w]=p,o.update(t[w],c,p)})),f=h.llmOutput??{}}return{generations:l,llmOutput:f}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},lh=class extends Ab{async _generate(e,t,r){return{generations:await Promise.all(e.map((i,s)=>this._call(i,{...t,promptIndex:s},r).then(a=>[{text:a}])))}}};const Af="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var k1=class extends Qt{lc_namespace=["langchain","recordmanagers"]},Ob=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=zd;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){const e=["hash_","content_hash","metadata_hash"];for(const r of e)if(r in this.metadata)throw new Error(`Metadata cannot contain key ${r} as it is reserved for internal use. Restricted keys: [${e.join(", ")}]`);const t=this._hashStringToUUID(this.pageContent);try{const r=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=r}catch(r){throw new Error(`Failed to hash metadata: ${r}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new Ur({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){const r=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return r.calculateHashes(),r}_hashStringToUUID(e){const t=this.keyEncoder(e);return xs(t,Af)}_hashNestedDictToUUID(e){const t=JSON.stringify(e,Object.keys(e).sort()),r=this.keyEncoder(t);return xs(r,Af)}};function xb(e,t){const r=[];let n=[];return t.forEach(i=>{n.push(i),n.length>=e&&(r.push(n),n=[])}),n.length>0&&r.push(n),r}function Pb(e){const t=new Set,r=[];for(const n of e){if(!n.hash_)throw new Error("Hashed document does not have a hash");t.has(n.hash_)||(t.add(n.hash_),r.push(n))}return r}function kb(e){if(e===null)return t=>null;if(typeof e=="string")return t=>t.metadata[e];if(typeof e=="function")return e;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}const Ib=e=>"load"in e&&typeof e.load=="function"&&"loadAndSplit"in e&&typeof e.loadAndSplit=="function";async function I1(e){const{docsSource:t,recordManager:r,vectorStore:n,options:i}=e,{batchSize:s=100,cleanup:a,sourceIdKey:o,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(a==="incremental"&&!o)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=Ib(t)?await t.load():t,d=kb(o??null),f=await r.getTime();let h=0,p=0,m=0,w=0;const y=xb(s??100,u);for(const g of y){const _=Pb(g.map(M=>Ob.fromDocument(M))),b=_.map(M=>d(M));a==="incremental"&&_.forEach((M,U)=>{if(b[U]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const A=await r.exists(_.map(M=>M.uid)),P=[],x=[],T=[],R=new Set;if(_.forEach((M,U)=>{if(A[U])if(l)R.add(M.uid);else{T.push(M.uid);return}P.push(M.uid),x.push(M.toDocument())}),T.length>0&&(await r.update(T,{timeAtLeast:f}),w+=T.length),x.length>0&&(await n.addDocuments(x,{ids:P}),h+=x.length-R.size,m+=R.size),await r.update(_.map(M=>M.uid),{timeAtLeast:f,groupIds:b}),a==="incremental"){b.forEach(U=>{if(!U)throw new Error("Source id cannot be null")});const M=await r.listKeys({before:f,groupIds:b});M.length>0&&(await n.delete({ids:M}),await r.deleteKeys(M),p+=M.length)}}if(a==="full"){let g=await r.listKeys({before:f,limit:c});for(;g.length>0;)await n.delete({ids:g}),await r.deleteKeys(g),p+=g.length,g=await r.listKeys({before:f,limit:c})}return{numAdded:h,numDeleted:p,numUpdated:m,numSkipped:w}}var Mb={};pe(Mb,{RecordManager:()=>k1,UUIDV5_NAMESPACE:()=>Af,_HashedDocument:()=>Ob,_batch:()=>xb,_deduplicateInOrder:()=>Pb,_getSourceIdAssigner:()=>kb,_isBaseDocumentLoader:()=>Ib,index:()=>I1});var Rb={};pe(Rb,{applyPatch:()=>Gi,compare:()=>_c});var xc=class extends we{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),e,{...t,runType:"parser"})}},ua=class extends xc{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}},Br=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,r,n=!1){if(super(e),this.llmOutput=t,this.observation=r,this.sendToLLM=n,n&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");hc(this,"OUTPUT_PARSING_FAILURE")}},fa=class extends ua{async*_transform(e){for await(const t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},da=class extends fa{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(const n of e){if(typeof n!="string"&&typeof n.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Ms(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");i=new Wi({message:n,text:n.content})}else if(st(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");i=new Wi({message:$o(n),text:n.content})}else i=new Vi({text:n});r===void 0?r=i:r=r.concat(i);const s=await this.parsePartialResult([r]);s!=null&&!Hy(s,t)&&(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}},M1=class extends fa{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},ha=class extends fa{re;async*_transform(e){let t="";for await(const r of e)if(typeof r=="string"?t+=r:t+=r.content,this.re){const n=[...t.matchAll(this.re)];if(n.length>1){let i=0;for(const s of n.slice(0,-1))yield[s[1]],i+=(s.index??0)+s[0].length;t=t.slice(i)}}else{const n=await this.parse(t);if(n.length>1){for(const i of n.slice(0,-1))yield[i];t=n[n.length-1]}}for(const r of await this.parse(t))yield[r]}},R1=class extends ha{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new Br(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},N1=class extends ha{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&t.length!==this.length)throw new Br(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===Br.prototype?t:new Br(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},$1=class extends ha{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
141
-
142
- 1. foo
143
-
144
- 2. bar
145
-
146
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},L1=class extends ha{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
147
-
148
- 1. foo
149
-
150
- 2. bar
151
-
152
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},j1=class extends fa{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,r)=>t+this._messageContentToString(r),"")}},Nb=class extends ua{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=Pe(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,nt().describe(n)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
153
-
154
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
155
-
156
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
157
- would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
158
- Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
159
-
160
- Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
161
-
162
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
163
- \`\`\`json
164
- ${JSON.stringify(zt(this.schema))}
165
- \`\`\`
166
- `}async parse(e){try{const t=e.trim(),n=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(i,s)=>`"${s.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await mc(this.schema,JSON.parse(n))}catch(t){throw new Br(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},$b=class extends Nb{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
167
- \`\`\`json
168
- ${this._schemaToInstruction(zt(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
169
- \`\`\``}_schemaToInstruction(e,t=2){const r=e;if("type"in r){let n=!1,i;if(Array.isArray(r.type)){const o=r.type.findIndex(c=>c==="null");o!==-1&&(n=!0,r.type.splice(o,1)),i=r.type.join(" | ")}else i=r.type;if(r.type==="object"&&r.properties){const o=r.description?` // ${r.description}`:"";return`{
170
- ${Object.entries(r.properties).map(([l,u])=>{const d=r.required?.includes(l)?"":" (optional)";return`${" ".repeat(t)}"${l}": ${this._schemaToInstruction(u,t+2)}${d}`}).join(`
171
- `)}
172
- ${" ".repeat(t-2)}}${o}`}if(r.type==="array"&&r.items){const o=r.description?` // ${r.description}`:"";return`array[
173
- ${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}
174
- ${" ".repeat(t-2)}] ${o}`}const s=n?" (nullable)":"",a=r.description?` // ${r.description}`:"";return`${i}${a}${s}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,t)).join(`
175
- ${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=Pe(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,nt().describe(n)])));return new this(t)}},D1=class extends ua{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new $b(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(r){throw new Br(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},F1=class extends da{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?_c(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Zu(e[0].text)}async parse(e){return Zu(e,JSON.parse)}getFormatInstructions(){return""}};const U1=function(){const e={};e.parser=function(C,S){return new r(C,S)},e.SAXParser=r,e.SAXStream=l,e.createStream=c,e.MAX_BUFFER_LENGTH=64*1024;const t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(C,S){if(!(this instanceof r))return new r(C,S);var D=this;i(D),D.q=D.c="",D.bufferCheckPosition=e.MAX_BUFFER_LENGTH,D.opt=S||{},D.opt.lowercase=D.opt.lowercase||D.opt.lowercasetags,D.looseCase=D.opt.lowercase?"toLowerCase":"toUpperCase",D.tags=[],D.closed=D.closedRoot=D.sawRoot=!1,D.tag=D.error=null,D.strict=!!C,D.noscript=!!(C||D.opt.noscript),D.state=T.BEGIN,D.strictEntities=D.opt.strictEntities,D.ENTITIES=D.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),D.attribList=[],D.opt.xmlns&&(D.ns=Object.create(p)),D.trackPosition=D.opt.position!==!1,D.trackPosition&&(D.position=D.line=D.column=0),M(D,"onready")}Object.create||(Object.create=function(C){function S(){}S.prototype=C;var D=new S;return D}),Object.keys||(Object.keys=function(C){var S=[];for(var D in C)C.hasOwnProperty(D)&&S.push(D);return S});function n(C){for(var S=Math.max(e.MAX_BUFFER_LENGTH,10),D=0,j=0,re=t.length;j<re;j++){var k=C[t[j]].length;if(k>S)switch(t[j]){case"textNode":H(C);break;case"cdata":U(C,"oncdata",C.cdata),C.cdata="";break;case"script":U(C,"onscript",C.script),C.script="";break;default:K(C,"Max buffer length exceeded: "+t[j])}D=Math.max(D,k)}var I=e.MAX_BUFFER_LENGTH-D;C.bufferCheckPosition=I+C.position}function i(C){for(var S=0,D=t.length;S<D;S++)C[t[S]]=""}function s(C){H(C),C.cdata!==""&&(U(C,"oncdata",C.cdata),C.cdata=""),C.script!==""&&(U(C,"onscript",C.script),C.script="")}r.prototype={end:function(){ee(this)},write:se,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var a=ReadableStream;a||(a=function(){});var o=e.EVENTS.filter(function(C){return C!=="error"&&C!=="end"});function c(C,S){return new l(C,S)}function l(C,S){if(!(this instanceof l))return new l(C,S);a.apply(this),this._parser=new r(C,S),this.writable=!0,this.readable=!0;var D=this;this._parser.onend=function(){D.emit("end")},this._parser.onerror=function(j){D.emit("error",j),D._parser.error=null},this._decoder=null,o.forEach(function(j){Object.defineProperty(D,"on"+j,{get:function(){return D._parser["on"+j]},set:function(re){if(!re)return D.removeAllListeners(j),D._parser["on"+j]=re,re;D.on(j,re)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(a.prototype,{constructor:{value:l}}),l.prototype.write=function(C){return this._parser.write(C.toString()),this.emit("data",C),!0},l.prototype.end=function(C){return C&&C.length&&this.write(C),this._parser.end(),!0},l.prototype.on=function(C,S){var D=this;return!D._parser["on"+C]&&o.indexOf(C)!==-1&&(D._parser["on"+C]=function(){var j=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);j.splice(0,0,C),D.emit.apply(D,j)}),a.prototype.on.call(D,C,S)};var u="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",p={xml:f,xmlns:h},m=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,w=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,g=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function _(C){return C===" "||C===`
176
- `||C==="\r"||C===" "}function b(C){return C==='"'||C==="'"}function A(C){return C===">"||_(C)}function P(C,S){return C.test(S)}function x(C,S){return!P(C,S)}var T=0;e.STATE={BEGIN:T++,BEGIN_WHITESPACE:T++,TEXT:T++,TEXT_ENTITY:T++,OPEN_WAKA:T++,SGML_DECL:T++,SGML_DECL_QUOTED:T++,DOCTYPE:T++,DOCTYPE_QUOTED:T++,DOCTYPE_DTD:T++,DOCTYPE_DTD_QUOTED:T++,COMMENT_STARTING:T++,COMMENT:T++,COMMENT_ENDING:T++,COMMENT_ENDED:T++,CDATA:T++,CDATA_ENDING:T++,CDATA_ENDING_2:T++,PROC_INST:T++,PROC_INST_BODY:T++,PROC_INST_ENDING:T++,OPEN_TAG:T++,OPEN_TAG_SLASH:T++,ATTRIB:T++,ATTRIB_NAME:T++,ATTRIB_NAME_SAW_WHITE:T++,ATTRIB_VALUE:T++,ATTRIB_VALUE_QUOTED:T++,ATTRIB_VALUE_CLOSED:T++,ATTRIB_VALUE_UNQUOTED:T++,ATTRIB_VALUE_ENTITY_Q:T++,ATTRIB_VALUE_ENTITY_U:T++,CLOSE_TAG:T++,CLOSE_TAG_SAW_WHITE:T++,SCRIPT:T++,SCRIPT_ENDING:T++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(C){var S=e.ENTITIES[C],D=typeof S=="number"?String.fromCharCode(S):S;e.ENTITIES[C]=D});for(var R in e.STATE)e.STATE[e.STATE[R]]=R;T=e.STATE;function M(C,S,D){C[S]&&C[S](D)}function U(C,S,D){C.textNode&&H(C),M(C,S,D)}function H(C){C.textNode=F(C.opt,C.textNode),C.textNode&&M(C,"ontext",C.textNode),C.textNode=""}function F(C,S){return C.trim&&(S=S.trim()),C.normalize&&(S=S.replace(/\s+/g," ")),S}function K(C,S){return H(C),C.trackPosition&&(S+=`
177
- Line: `+C.line+`
178
- Column: `+C.column+`
179
- Char: `+C.c),S=new Error(S),C.error=S,M(C,"onerror",S),C}function ee(C){return C.sawRoot&&!C.closedRoot&&L(C,"Unclosed root tag"),C.state!==T.BEGIN&&C.state!==T.BEGIN_WHITESPACE&&C.state!==T.TEXT&&K(C,"Unexpected end"),H(C),C.c="",C.closed=!0,M(C,"onend"),r.call(C,C.strict,C.opt),C}function L(C,S){if(typeof C!="object"||!(C instanceof r))throw new Error("bad call to strictFail");C.strict&&K(C,S)}function z(C){C.strict||(C.tagName=C.tagName[C.looseCase]());var S=C.tags[C.tags.length-1]||C,D=C.tag={name:C.tagName,attributes:{}};C.opt.xmlns&&(D.ns=S.ns),C.attribList.length=0,U(C,"onopentagstart",D)}function W(C,S){var D=C.indexOf(":"),j=D<0?["",C]:C.split(":"),re=j[0],k=j[1];return S&&C==="xmlns"&&(re="xmlns",k=""),{prefix:re,local:k}}function q(C){if(C.strict||(C.attribName=C.attribName[C.looseCase]()),C.attribList.indexOf(C.attribName)!==-1||C.tag.attributes.hasOwnProperty(C.attribName)){C.attribName=C.attribValue="";return}if(C.opt.xmlns){var S=W(C.attribName,!0),D=S.prefix,j=S.local;if(D==="xmlns")if(j==="xml"&&C.attribValue!==f)L(C,"xml: prefix must be bound to "+f+`
180
- Actual: `+C.attribValue);else if(j==="xmlns"&&C.attribValue!==h)L(C,"xmlns: prefix must be bound to "+h+`
181
- Actual: `+C.attribValue);else{var re=C.tag,k=C.tags[C.tags.length-1]||C;re.ns===k.ns&&(re.ns=Object.create(k.ns)),re.ns[j]=C.attribValue}C.attribList.push([C.attribName,C.attribValue])}else C.tag.attributes[C.attribName]=C.attribValue,U(C,"onattribute",{name:C.attribName,value:C.attribValue});C.attribName=C.attribValue=""}function V(C,S){if(C.opt.xmlns){var D=C.tag,j=W(C.tagName);D.prefix=j.prefix,D.local=j.local,D.uri=D.ns[j.prefix]||"",D.prefix&&!D.uri&&(L(C,"Unbound namespace prefix: "+JSON.stringify(C.tagName)),D.uri=j.prefix);var re=C.tags[C.tags.length-1]||C;D.ns&&re.ns!==D.ns&&Object.keys(D.ns).forEach(function(Pr){U(C,"onopennamespace",{prefix:Pr,uri:D.ns[Pr]})});for(var k=0,I=C.attribList.length;k<I;k++){var J=C.attribList[k],ne=J[0],Te=J[1],ue=W(ne,!0),ye=ue.prefix,Vt=ue.local,Or=ye===""?"":D.ns[ye]||"",xr={name:ne,value:Te,prefix:ye,local:Vt,uri:Or};ye&&ye!=="xmlns"&&!Or&&(L(C,"Unbound namespace prefix: "+JSON.stringify(ye)),xr.uri=ye),C.tag.attributes[ne]=xr,U(C,"onattribute",xr)}C.attribList.length=0}C.tag.isSelfClosing=!!S,C.sawRoot=!0,C.tags.push(C.tag),U(C,"onopentag",C.tag),S||(!C.noscript&&C.tagName.toLowerCase()==="script"?C.state=T.SCRIPT:C.state=T.TEXT,C.tag=null,C.tagName=""),C.attribName=C.attribValue="",C.attribList.length=0}function Y(C){if(!C.tagName){L(C,"Weird empty close tag."),C.textNode+="</>",C.state=T.TEXT;return}if(C.script){if(C.tagName!=="script"){C.script+="</"+C.tagName+">",C.tagName="",C.state=T.SCRIPT;return}U(C,"onscript",C.script),C.script=""}var S=C.tags.length,D=C.tagName;C.strict||(D=D[C.looseCase]());for(var j=D;S--;){var re=C.tags[S];if(re.name!==j)L(C,"Unexpected close tag");else break}if(S<0){L(C,"Unmatched closing tag: "+C.tagName),C.textNode+="</"+C.tagName+">",C.state=T.TEXT;return}C.tagName=D;for(var k=C.tags.length;k-- >S;){var I=C.tag=C.tags.pop();C.tagName=C.tag.name,U(C,"onclosetag",C.tagName);var J={};for(var ne in I.ns)J[ne]=I.ns[ne];var Te=C.tags[C.tags.length-1]||C;C.opt.xmlns&&I.ns!==Te.ns&&Object.keys(I.ns).forEach(function(ue){var ye=I.ns[ue];U(C,"onclosenamespace",{prefix:ue,uri:ye})})}S===0&&(C.closedRoot=!0),C.tagName=C.attribValue=C.attribName="",C.attribList.length=0,C.state=T.TEXT}function Q(C){var S=C.entity,D=S.toLowerCase(),j,re="";return C.ENTITIES[S]?C.ENTITIES[S]:C.ENTITIES[D]?C.ENTITIES[D]:(S=D,S.charAt(0)==="#"&&(S.charAt(1)==="x"?(S=S.slice(2),j=parseInt(S,16),re=j.toString(16)):(S=S.slice(1),j=parseInt(S,10),re=j.toString(10))),S=S.replace(/^0+/,""),isNaN(j)||re.toLowerCase()!==S?(L(C,"Invalid character entity"),"&"+C.entity+";"):String.fromCodePoint(j))}function ae(C,S){S==="<"?(C.state=T.OPEN_WAKA,C.startTagPosition=C.position):_(S)||(L(C,"Non-whitespace before first tag."),C.textNode=S,C.state=T.TEXT)}function X(C,S){var D="";return S<C.length&&(D=C.charAt(S)),D}function se(C){var S=this;if(this.error)throw this.error;if(S.closed)return K(S,"Cannot write after close. Assign an onready handler.");if(C===null)return ee(S);typeof C=="object"&&(C=C.toString());for(var D=0,j="";j=X(C,D++),S.c=j,!!j;)switch(S.trackPosition&&(S.position++,j===`
182
- `?(S.line++,S.column=0):S.column++),S.state){case T.BEGIN:if(S.state=T.BEGIN_WHITESPACE,j==="\uFEFF")continue;ae(S,j);continue;case T.BEGIN_WHITESPACE:ae(S,j);continue;case T.TEXT:if(S.sawRoot&&!S.closedRoot){for(var re=D-1;j&&j!=="<"&&j!=="&";)j=X(C,D++),j&&S.trackPosition&&(S.position++,j===`
183
- `?(S.line++,S.column=0):S.column++);S.textNode+=C.substring(re,D-1)}j==="<"&&!(S.sawRoot&&S.closedRoot&&!S.strict)?(S.state=T.OPEN_WAKA,S.startTagPosition=S.position):(!_(j)&&(!S.sawRoot||S.closedRoot)&&L(S,"Text data outside of root node."),j==="&"?S.state=T.TEXT_ENTITY:S.textNode+=j);continue;case T.SCRIPT:j==="<"?S.state=T.SCRIPT_ENDING:S.script+=j;continue;case T.SCRIPT_ENDING:j==="/"?S.state=T.CLOSE_TAG:(S.script+="<"+j,S.state=T.SCRIPT);continue;case T.OPEN_WAKA:if(j==="!")S.state=T.SGML_DECL,S.sgmlDecl="";else if(!_(j))if(P(m,j))S.state=T.OPEN_TAG,S.tagName=j;else if(j==="/")S.state=T.CLOSE_TAG,S.tagName="";else if(j==="?")S.state=T.PROC_INST,S.procInstName=S.procInstBody="";else{if(L(S,"Unencoded <"),S.startTagPosition+1<S.position){var k=S.position-S.startTagPosition;j=new Array(k).join(" ")+j}S.textNode+="<"+j,S.state=T.TEXT}continue;case T.SGML_DECL:(S.sgmlDecl+j).toUpperCase()===u?(U(S,"onopencdata"),S.state=T.CDATA,S.sgmlDecl="",S.cdata=""):S.sgmlDecl+j==="--"?(S.state=T.COMMENT,S.comment="",S.sgmlDecl=""):(S.sgmlDecl+j).toUpperCase()===d?(S.state=T.DOCTYPE,(S.doctype||S.sawRoot)&&L(S,"Inappropriately located doctype declaration"),S.doctype="",S.sgmlDecl=""):j===">"?(U(S,"onsgmldeclaration",S.sgmlDecl),S.sgmlDecl="",S.state=T.TEXT):(b(j)&&(S.state=T.SGML_DECL_QUOTED),S.sgmlDecl+=j);continue;case T.SGML_DECL_QUOTED:j===S.q&&(S.state=T.SGML_DECL,S.q=""),S.sgmlDecl+=j;continue;case T.DOCTYPE:j===">"?(S.state=T.TEXT,U(S,"ondoctype",S.doctype),S.doctype=!0):(S.doctype+=j,j==="["?S.state=T.DOCTYPE_DTD:b(j)&&(S.state=T.DOCTYPE_QUOTED,S.q=j));continue;case T.DOCTYPE_QUOTED:S.doctype+=j,j===S.q&&(S.q="",S.state=T.DOCTYPE);continue;case T.DOCTYPE_DTD:S.doctype+=j,j==="]"?S.state=T.DOCTYPE:b(j)&&(S.state=T.DOCTYPE_DTD_QUOTED,S.q=j);continue;case T.DOCTYPE_DTD_QUOTED:S.doctype+=j,j===S.q&&(S.state=T.DOCTYPE_DTD,S.q="");continue;case T.COMMENT:j==="-"?S.state=T.COMMENT_ENDING:S.comment+=j;continue;case T.COMMENT_ENDING:j==="-"?(S.state=T.COMMENT_ENDED,S.comment=F(S.opt,S.comment),S.comment&&U(S,"oncomment",S.comment),S.comment=""):(S.comment+="-"+j,S.state=T.COMMENT);continue;case T.COMMENT_ENDED:j!==">"?(L(S,"Malformed comment"),S.comment+="--"+j,S.state=T.COMMENT):S.state=T.TEXT;continue;case T.CDATA:j==="]"?S.state=T.CDATA_ENDING:S.cdata+=j;continue;case T.CDATA_ENDING:j==="]"?S.state=T.CDATA_ENDING_2:(S.cdata+="]"+j,S.state=T.CDATA);continue;case T.CDATA_ENDING_2:j===">"?(S.cdata&&U(S,"oncdata",S.cdata),U(S,"onclosecdata"),S.cdata="",S.state=T.TEXT):j==="]"?S.cdata+="]":(S.cdata+="]]"+j,S.state=T.CDATA);continue;case T.PROC_INST:j==="?"?S.state=T.PROC_INST_ENDING:_(j)?S.state=T.PROC_INST_BODY:S.procInstName+=j;continue;case T.PROC_INST_BODY:if(!S.procInstBody&&_(j))continue;j==="?"?S.state=T.PROC_INST_ENDING:S.procInstBody+=j;continue;case T.PROC_INST_ENDING:j===">"?(U(S,"onprocessinginstruction",{name:S.procInstName,body:S.procInstBody}),S.procInstName=S.procInstBody="",S.state=T.TEXT):(S.procInstBody+="?"+j,S.state=T.PROC_INST_BODY);continue;case T.OPEN_TAG:P(w,j)?S.tagName+=j:(z(S),j===">"?V(S):j==="/"?S.state=T.OPEN_TAG_SLASH:(_(j)||L(S,"Invalid character in tag name"),S.state=T.ATTRIB));continue;case T.OPEN_TAG_SLASH:j===">"?(V(S,!0),Y(S)):(L(S,"Forward-slash in opening tag not followed by >"),S.state=T.ATTRIB);continue;case T.ATTRIB:if(_(j))continue;j===">"?V(S):j==="/"?S.state=T.OPEN_TAG_SLASH:P(m,j)?(S.attribName=j,S.attribValue="",S.state=T.ATTRIB_NAME):L(S,"Invalid attribute name");continue;case T.ATTRIB_NAME:j==="="?S.state=T.ATTRIB_VALUE:j===">"?(L(S,"Attribute without value"),S.attribValue=S.attribName,q(S),V(S)):_(j)?S.state=T.ATTRIB_NAME_SAW_WHITE:P(w,j)?S.attribName+=j:L(S,"Invalid attribute name");continue;case T.ATTRIB_NAME_SAW_WHITE:if(j==="=")S.state=T.ATTRIB_VALUE;else{if(_(j))continue;L(S,"Attribute without value"),S.tag.attributes[S.attribName]="",S.attribValue="",U(S,"onattribute",{name:S.attribName,value:""}),S.attribName="",j===">"?V(S):P(m,j)?(S.attribName=j,S.state=T.ATTRIB_NAME):(L(S,"Invalid attribute name"),S.state=T.ATTRIB)}continue;case T.ATTRIB_VALUE:if(_(j))continue;b(j)?(S.q=j,S.state=T.ATTRIB_VALUE_QUOTED):(L(S,"Unquoted attribute value"),S.state=T.ATTRIB_VALUE_UNQUOTED,S.attribValue=j);continue;case T.ATTRIB_VALUE_QUOTED:if(j!==S.q){j==="&"?S.state=T.ATTRIB_VALUE_ENTITY_Q:S.attribValue+=j;continue}q(S),S.q="",S.state=T.ATTRIB_VALUE_CLOSED;continue;case T.ATTRIB_VALUE_CLOSED:_(j)?S.state=T.ATTRIB:j===">"?V(S):j==="/"?S.state=T.OPEN_TAG_SLASH:P(m,j)?(L(S,"No whitespace between attributes"),S.attribName=j,S.attribValue="",S.state=T.ATTRIB_NAME):L(S,"Invalid attribute name");continue;case T.ATTRIB_VALUE_UNQUOTED:if(!A(j)){j==="&"?S.state=T.ATTRIB_VALUE_ENTITY_U:S.attribValue+=j;continue}q(S),j===">"?V(S):S.state=T.ATTRIB;continue;case T.CLOSE_TAG:if(S.tagName)j===">"?Y(S):P(w,j)?S.tagName+=j:S.script?(S.script+="</"+S.tagName,S.tagName="",S.state=T.SCRIPT):(_(j)||L(S,"Invalid tagname in closing tag"),S.state=T.CLOSE_TAG_SAW_WHITE);else{if(_(j))continue;x(m,j)?S.script?(S.script+="</"+j,S.state=T.SCRIPT):L(S,"Invalid tagname in closing tag."):S.tagName=j}continue;case T.CLOSE_TAG_SAW_WHITE:if(_(j))continue;j===">"?Y(S):L(S,"Invalid characters in closing tag");continue;case T.TEXT_ENTITY:case T.ATTRIB_VALUE_ENTITY_Q:case T.ATTRIB_VALUE_ENTITY_U:var I,J;switch(S.state){case T.TEXT_ENTITY:I=T.TEXT,J="textNode";break;case T.ATTRIB_VALUE_ENTITY_Q:I=T.ATTRIB_VALUE_QUOTED,J="attribValue";break;case T.ATTRIB_VALUE_ENTITY_U:I=T.ATTRIB_VALUE_UNQUOTED,J="attribValue";break}if(j===";")if(S.opt.unparsedEntities){var ne=Q(S);S.entity="",S.state=I,S.write(ne)}else S[J]+=Q(S),S.entity="",S.state=I;else P(S.entity.length?g:y,j)?S.entity+=j:(L(S,"Invalid character in entity name"),S[J]+="&"+S.entity+j,S.entity="",S.state=I);continue;default:throw new Error(S,"Unknown state: "+S.state)}return S.position>=S.bufferCheckPosition&&n(S),S}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||(function(){var C=String.fromCharCode,S=Math.floor,D=function(){var j=16384,re=[],k,I,J=-1,ne=arguments.length;if(!ne)return"";for(var Te="";++J<ne;){var ue=Number(arguments[J]);if(!isFinite(ue)||ue<0||ue>1114111||S(ue)!==ue)throw RangeError("Invalid code point: "+ue);ue<=65535?re.push(ue):(ue-=65536,k=(ue>>10)+55296,I=ue%1024+56320,re.push(k,I)),(J+1===ne||re.length>j)&&(Te+=C.apply(null,re),re.length=0)}return Te};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:D,configurable:!0,writable:!0}):String.fromCodePoint=D})(),e},B1=U1(),Of=`The output should be formatted as a XML file.
184
- 1. Output should conform to the tags below.
185
- 2. If tags are not given, make them on your own.
186
- 3. Remember to always open and close all the tags.
187
-
188
- As an example, for the tags ["foo", "bar", "baz"]:
189
- 1. String "<foo>
190
- <bar>
191
- <baz></baz>
192
- </bar>
193
- </foo>" is a well-formatted instance of the schema.
194
- 2. String "<foo>
195
- <bar>
196
- </foo>" is a badly-formatted instance.
197
- 3. String "<foo>
198
- <tag>
199
- </tag>
200
- </foo>" is a badly-formatted instance.
201
-
202
- Here are the output tags:
203
- \`\`\`
204
- {tags}
205
- \`\`\``;var z1=class extends da{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?_c(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return xf(e[0].text)}async parse(e){return xf(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Of.replace("{tags}",this.tags?.join(", ")??""):Of}};const q1=e=>e.split(`
206
- `).map(t=>t.replace(/^\s+/,"")).join(`
207
- `).trim(),Lb=e=>{if(Object.keys(e).length===0)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(Lb),t):(t[e.name]=e.text??void 0,t)};function xf(e){const t=q1(e),r=B1.parser(!0);let n={};const i=[];r.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};i.length>0?i[i.length-1].children.push(c):n=c,o.isSelfClosing||i.push(c)},r.onclosetag=()=>{if(i.length>0){const o=i.pop();i.length===0&&o&&(n=o)}},r.ontext=o=>{if(i.length>0){const c=i[i.length-1];c.text+=o}},r.onattribute=o=>{if(i.length>0){const c=i[i.length-1];c.attributes[o.name]=o.value}};const s=/```(xml)?(.*)```/s.exec(t),a=s?s[2]:t;return r.write(a).close(),n&&n.name==="?xml"&&(n=n.children[0]),Lb(n)}var jb={};pe(jb,{AsymmetricStructuredOutputParser:()=>D1,BaseCumulativeTransformOutputParser:()=>da,BaseLLMOutputParser:()=>xc,BaseOutputParser:()=>ua,BaseTransformOutputParser:()=>fa,BytesOutputParser:()=>M1,CommaSeparatedListOutputParser:()=>R1,CustomListOutputParser:()=>N1,JsonMarkdownStructuredOutputParser:()=>$b,JsonOutputParser:()=>F1,ListOutputParser:()=>ha,MarkdownListOutputParser:()=>L1,NumberedListOutputParser:()=>$1,OutputParserException:()=>Br,StringOutputParser:()=>j1,StructuredOutputParser:()=>Nb,XMLOutputParser:()=>z1,XML_FORMAT_INSTRUCTIONS:()=>Of,parseJsonMarkdown:()=>Zu,parsePartialJson:()=>Bi,parseXMLMarkdown:()=>xf});function Db(e,t){if(e.function===void 0)return;let r;if(t?.partial)try{r=Bi(e.function.arguments??"{}")}catch{return}else try{r=JSON.parse(e.function.arguments)}catch(i){throw new Br([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${i.message}`].join(`
208
- `))}const n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function H1(e){if(e.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function G1(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var Fb=class extends da{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){const r=e[0].message;let n;if(Td(r)&&r.tool_calls?.length?n=r.tool_calls.map(s=>{const{id:a,...o}=s;return this.returnId?{id:a,...o}:o}):r.additional_kwargs.tool_calls!==void 0&&(n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(a=>Db(a,{returnId:this.returnId,partial:t}))),!n)return[];const i=[];for(const s of n)if(s!==void 0){const a={type:s.name,args:s.args,id:s.id};i.push(a)}return i}},V1=class extends Fb{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const t=await Id(this.zodSchema,e);if(t.success)return t.data;throw new Br(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const r=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName);let n=r;if(r.length)return this.returnId||(n=r.map(i=>i.args)),this.returnSingle?n[0]:n}async parseResult(e){const r=(await super.parsePartialResult(e,!1)).filter(s=>s.type===this.keyName);let n=r;return r.length?(this.returnId||(n=r.map(s=>s.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(s=>this._validateResult(s)))):void 0}},Ub={};pe(Ub,{JsonOutputKeyToolsParser:()=>V1,JsonOutputToolsParser:()=>Fb,convertLangChainToolCallToOpenAI:()=>H1,makeInvalidToolCall:()=>G1,parseToolCall:()=>Db});var Bb=class extends xc{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if("message"in e[0]){const r=e[0].message.additional_kwargs.function_call;if(!r)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!r.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?r.arguments:JSON.stringify(r)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},zb=class extends da{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new Bb(e)}_diff(e,t){return t?_c(e??{},t):void 0}async parsePartialResult(e){const t=e[0];if(!t.message)return;const{message:r}=t,n=r.additional_kwargs.function_call;if(n)return this.argsOnly?Bi(n.arguments):{...n,arguments:Bi(n.arguments)}}async parseResult(e){const t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){const t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},W1=class extends xc{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new zb;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},qb={};pe(qb,{JsonKeyOutputFunctionsParser:()=>W1,JsonOutputFunctionsParser:()=>zb,OutputFunctionsParser:()=>Bb});var pa=class extends we{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);const{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){const t=this.partialVariables??{},r={};for(const[i,s]of Object.entries(t))typeof s=="string"?r[i]=s:r[i]=await s();return{...r,...e}}async invoke(e,t){const r={...this.metadata,...t?.metadata},n=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...t,tags:n,metadata:r,runType:"prompt"})}},Hs=class extends pa{async formatPromptValue(e){const t=await this.format(e);return new Ud(t)}};/*!
209
- * mustache.js - Logic-less {{mustache}} templates with JavaScript
210
- * http://github.com/janl/mustache.js
211
- */var J1=Object.prototype.toString,as=Array.isArray||function(t){return J1.call(t)==="[object Array]"};function uh(e){return typeof e=="function"}function K1(e){return as(e)?"array":typeof e}function xu(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function cy(e,t){return e!=null&&typeof e=="object"&&t in e}function Z1(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Y1=RegExp.prototype.test;function X1(e,t){return Y1.call(e,t)}var Q1=/\S/;function eN(e){return!X1(Q1,e)}var tN={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function rN(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return tN[r]})}var nN=/\s*/,iN=/\s+/,ly=/\s*=/,sN=/\s*\}/,aN=/#|\^|\/|>|\{|&|=|!/;function oN(e,t){if(!e)return[];var r=!1,n=[],i=[],s=[],a=!1,o=!1,c="",l=0;function u(){if(a&&!o)for(;s.length;)delete i[s.pop()];else s=[];a=!1,o=!1}var d,f,h;function p(T){if(typeof T=="string"&&(T=T.split(iN,2)),!as(T)||T.length!==2)throw new Error("Invalid tags: "+T);d=new RegExp(xu(T[0])+"\\s*"),f=new RegExp("\\s*"+xu(T[1])),h=new RegExp("\\s*"+xu("}"+T[1]))}p(t||Nt.tags);for(var m=new ma(e),w,y,g,_,b,A;!m.eos();){if(w=m.pos,g=m.scanUntil(d),g)for(var P=0,x=g.length;P<x;++P)_=g.charAt(P),eN(_)?(s.push(i.length),c+=_):(o=!0,r=!0,c+=" "),i.push(["text",_,w,w+1]),w+=1,_===`
212
- `&&(u(),c="",l=0,r=!1);if(!m.scan(d))break;if(a=!0,y=m.scan(aN)||"name",m.scan(nN),y==="="?(g=m.scanUntil(ly),m.scan(ly),m.scanUntil(f)):y==="{"?(g=m.scanUntil(h),m.scan(sN),m.scanUntil(f),y="&"):g=m.scanUntil(f),!m.scan(f))throw new Error("Unclosed tag at "+m.pos);if(y==">"?b=[y,g,w,m.pos,c,l,r]:b=[y,g,w,m.pos],l++,i.push(b),y==="#"||y==="^")n.push(b);else if(y==="/"){if(A=n.pop(),!A)throw new Error('Unopened section "'+g+'" at '+w);if(A[1]!==g)throw new Error('Unclosed section "'+A[1]+'" at '+w)}else y==="name"||y==="{"||y==="&"?o=!0:y==="="&&p(g)}if(u(),A=n.pop(),A)throw new Error('Unclosed section "'+A[1]+'" at '+m.pos);return lN(cN(i))}function cN(e){for(var t=[],r,n,i=0,s=e.length;i<s;++i)r=e[i],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function lN(e){for(var t=[],r=t,n=[],i,s,a=0,o=e.length;a<o;++a)switch(i=e[a],i[0]){case"#":case"^":r.push(i),n.push(i),r=i[4]=[];break;case"/":s=n.pop(),s[5]=i[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(i)}return t}function ma(e){this.string=e,this.tail=e,this.pos=0}ma.prototype.eos=function(){return this.tail===""};ma.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};ma.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function Ki(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ki.prototype.push=function(t){return new Ki(t,this)};Ki.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var i=this,s,a,o,c=!1;i;){if(t.indexOf(".")>0)for(s=i.view,a=t.split("."),o=0;s!=null&&o<a.length;)o===a.length-1&&(c=cy(s,a[o])||Z1(s,a[o])),s=s[a[o++]];else s=i.view[t],c=cy(i.view,t);if(c){n=s;break}i=i.parent}r[t]=n}return uh(n)&&(n=n.call(this.view)),n};function Et(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}Et.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Et.prototype.parse=function(t,r){var n=this.templateCache,i=t+":"+(r||Nt.tags).join(":"),s=typeof n<"u",a=s?n.get(i):void 0;return a==null&&(a=oN(t,r),s&&n.set(i,a)),a};Et.prototype.render=function(t,r,n,i){var s=this.getConfigTags(i),a=this.parse(t,s),o=r instanceof Ki?r:new Ki(r,void 0);return this.renderTokens(a,o,n,t,i)};Et.prototype.renderTokens=function(t,r,n,i,s){for(var a="",o,c,l,u=0,d=t.length;u<d;++u)l=void 0,o=t[u],c=o[0],c==="#"?l=this.renderSection(o,r,n,i,s):c==="^"?l=this.renderInverted(o,r,n,i,s):c===">"?l=this.renderPartial(o,r,n,s):c==="&"?l=this.unescapedValue(o,r):c==="name"?l=this.escapedValue(o,r,s):c==="text"&&(l=this.rawValue(o)),l!==void 0&&(a+=l);return a};Et.prototype.renderSection=function(t,r,n,i,s){var a=this,o="",c=r.lookup(t[1]);function l(f){return a.render(f,r,n,s)}if(c){if(as(c))for(var u=0,d=c.length;u<d;++u)o+=this.renderTokens(t[4],r.push(c[u]),n,i,s);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")o+=this.renderTokens(t[4],r.push(c),n,i,s);else if(uh(c)){if(typeof i!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(r.view,i.slice(t[3],t[5]),l),c!=null&&(o+=c)}else o+=this.renderTokens(t[4],r,n,i,s);return o}};Et.prototype.renderInverted=function(t,r,n,i,s){var a=r.lookup(t[1]);if(!a||as(a)&&a.length===0)return this.renderTokens(t[4],r,n,i,s)};Et.prototype.indentPartial=function(t,r,n){for(var i=r.replace(/[^ \t]/g,""),s=t.split(`
213
- `),a=0;a<s.length;a++)s[a].length&&(a>0||!n)&&(s[a]=i+s[a]);return s.join(`
214
- `)};Et.prototype.renderPartial=function(t,r,n,i){if(n){var s=this.getConfigTags(i),a=uh(n)?n(t[1]):n[t[1]];if(a!=null){var o=t[6],c=t[5],l=t[4],u=a;c==0&&l&&(u=this.indentPartial(a,l,o));var d=this.parse(u,s);return this.renderTokens(d,r,n,u,i)}}};Et.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};Et.prototype.escapedValue=function(t,r,n){var i=this.getConfigEscape(n)||Nt.escape,s=r.lookup(t[1]);if(s!=null)return typeof s=="number"&&i===Nt.escape?String(s):i(s)};Et.prototype.rawValue=function(t){return t[1]};Et.prototype.getConfigTags=function(t){return as(t)?t:t&&typeof t=="object"?t.tags:void 0};Et.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!as(t))return t.escape};var Nt={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Gs.templateCache=e},get templateCache(){return Gs.templateCache}},Gs=new Et;Nt.clearCache=function(){return Gs.clearCache()};Nt.parse=function(t,r){return Gs.parse(t,r)};Nt.render=function(t,r,n,i){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+K1(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Gs.render(t,r,n,i)};Nt.escape=rN;Nt.Scanner=ma;Nt.Context=Ki;Nt.Writer=Et;function Hb(){Nt.escape=e=>e}const Vs=e=>{const t=e.split(""),r=[],n=(s,a)=>{for(let o=a;o<t.length;o+=1)if(s.includes(t[o]))return o;return-1};let i=0;for(;i<t.length;)if(t[i]==="{"&&i+1<t.length&&t[i+1]==="{")r.push({type:"literal",text:"{"}),i+=2;else if(t[i]==="}"&&i+1<t.length&&t[i+1]==="}")r.push({type:"literal",text:"}"}),i+=2;else if(t[i]==="{"){const s=n("}",i);if(s<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(i+1,s).join("")}),i=s+1}else{if(t[i]==="}")throw new Error("Single '}' in template.");{const s=n("{}",i),a=(s<0?t.slice(i):t.slice(i,s)).join("");r.push({type:"literal",text:a}),i=s<0?t.length:s}}return r},Gb=(e,t=[])=>{const r=[];for(const n of e)if(n[0]==="name"){const i=n[1].includes(".")?n[1].split(".")[0]:n[1];r.push({type:"variable",name:i})}else if(["#","&","^",">"].includes(n[0])){if(r.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){const i=[...t,n[1]],s=Gb(n[4],i);r.push(...s)}}else r.push({type:"literal",text:n[1]});return r},Jo=e=>{Hb();const t=Nt.parse(e);return Gb(t)},Vb=(e,t)=>Vs(e).reduce((r,n)=>{if(n.type==="variable"){if(n.name in t){const i=typeof t[n.name]=="string"?t[n.name]:JSON.stringify(t[n.name]);return r+i}throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),Wb=(e,t)=>(Hb(),Nt.render(e,t)),Ko={"f-string":Vb,mustache:Wb},Jb={"f-string":Vs,mustache:Jo},dr=(e,t,r)=>{try{return Ko[t](e,r)}catch(n){throw hc(n,"INVALID_PROMPT_INPUT")}},Zo=(e,t)=>Jb[t](e),ga=(e,t,r)=>{if(!(t in Ko)){const n=Object.keys(Ko);throw new Error(`Invalid template format. Got \`${t}\`;
215
- should be one of ${n}`)}try{const n=r.reduce((i,s)=>(i[s]="foo",i),{});Array.isArray(e)?e.forEach(i=>{if(i.type==="text"&&"text"in i&&typeof i.text=="string")dr(i.text,t,n);else if(i.type==="image_url"){if(typeof i.image_url=="string")dr(i.image_url,t,n);else if(typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"){const s=i.image_url.url;dr(s,t,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(i,null,2)}`)}):dr(e,t,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}};var cn=class ys extends Hs{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ga(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(t){const r=await this.mergePartialAndUserVariables(t);return dr(this.template,this.templateFormat,r)}static fromExamples(t,r,n,i=`
216
-
217
- `,s=""){const a=[s,...t,r].join(i);return new ys({inputVariables:n,template:a})}static fromTemplate(t,r){const{templateFormat:n="f-string",...i}=r??{},s=new Set;return Zo(t,n).forEach(a=>{a.type==="variable"&&s.add(a.name)}),new ys({inputVariables:[...s],templateFormat:n,template:t,...i})}async partial(t){const r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new ys(i)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(t){if(!t.template)throw new Error("Prompt template must have a template");return new ys({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}},po=class Kb extends pa{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ga([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(t){const r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new Kb(i)}async format(t){const r={};for(const[a,o]of Object.entries(this.template))typeof o=="string"?r[a]=dr(o,this.templateFormat,t):r[a]=o;const n=t.url||r.url,i=t.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");const s={url:n};return i&&(s.detail=i),s}async formatPromptValue(t){const r=await this.format(t);return new mw(r)}},Pf=class extends we{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(e){const t=e.templateFormat??"f-string",r=kf(e.template,t);super({inputVariables:r,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=r}async format(e){return If(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function kf(e,t){const r=[];for(const n of Object.values(e))if(typeof n=="string")Zo(n,t).forEach(i=>{i.type==="variable"&&r.push(i.name)});else if(Array.isArray(n))for(const i of n)typeof i=="string"?Zo(i,t).forEach(s=>{s.type==="variable"&&r.push(s.name)}):typeof i=="object"&&r.push(...kf(i,t));else typeof n=="object"&&n!==null&&r.push(...kf(n,t));return Array.from(new Set(r))}function If(e,t,r){const n={};for(const[i,s]of Object.entries(e))if(typeof s=="string")n[i]=dr(s,r,t);else if(Array.isArray(s)){const a=[];for(const o of s)typeof o=="string"?a.push(dr(o,r,t)):typeof o=="object"&&a.push(If(o,t,r));n[i]=a}else typeof s=="object"&&s!==null?n[i]=If(s,t,r):n[i]=s;return n}var Pc=class extends we{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(r=>this.formatMessages(r),e,{...t,runType:"prompt"})}},Mf=class extends Pc{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(e){typeof e=="string"&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){const t=e[this.variableName];if(this.optional&&!t)return[];if(!t){const n=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw n.name="InputFormatError",n}let r;try{Array.isArray(t)?r=t.map(Er):r=[Er(t)]}catch(n){const i=typeof t=="string"?t:JSON.stringify(t,null,2),s=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${i}`,`Additional message: ${n.message}`].join(`
218
-
219
- `));throw s.name="InputFormatError",s.lc_error_code=n.lc_error_code,s}return r}},Zb=class extends Pc{prompt;constructor(e){"prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},fh=class extends pa{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){const t=await this.formatMessages(e);return new Bd(t)}},Yb=class extends Zb{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new zn(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(cn.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}};function uN(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).length===1&&"text"in e&&typeof e.text=="string"}function fN(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:"image_url"in e&&(typeof e.image_url=="string"||typeof e.image_url=="object"&&e.image_url!==null&&"url"in e.image_url&&typeof e.image_url.url=="string")}var dh=class extends Pc{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(n=>{"inputVariables"in n&&(r=r.concat(n.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){const t=this.constructor;if(t._messageClass()){const r=t._messageClass();return new r({content:e})}else if(t.chatMessageClass){const r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,t){if(typeof e=="string")return new this(cn.fromTemplate(e,t));const r=[];for(const n of e)if(typeof n=="string")r.push(cn.fromTemplate(n,t));else if(n!==null)if(uN(n)){let i="";typeof n.text=="string"&&(i=n.text??"");const s={...t,additionalContentFields:n};r.push(cn.fromTemplate(i,s))}else if(fN(n)){let i=n.image_url??"",s,a=[];if(typeof i=="string"){let o;t?.templateFormat==="mustache"?o=Jo(i):o=Vs(i);const c=o.flatMap(l=>l.type==="variable"?[l.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
220
- Got: ${c}
221
- From: ${i}`);a=[c[0]]}else a=[];i={url:i},s=new po({template:i,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:n})}else if(typeof i=="object"){if("url"in i){let o;t?.templateFormat==="mustache"?o=Jo(i.url):o=Vs(i.url),a=o.flatMap(c=>c.type==="variable"?[c.name]:[])}else a=[];s=new po({template:i,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:n})}else throw new Error("Invalid image template");r.push(s)}else typeof n=="object"&&r.push(new Pf({template:n,templateFormat:t?.templateFormat}));return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof Hs){const t=await this.prompt.format(e);return this.createMessage(t)}else{const t=[];for(const r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(const i of r.inputVariables)n||(n={[i]:e[i]}),n={...n,[i]:e[i]};if(r instanceof Hs){const i=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),i!==""&&t.push({...s,type:"text",text:i})}else if(r instanceof po){const i=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,type:"image_url",image_url:i})}else if(r instanceof Pf){const i=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,...i})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},hh=class extends dh{static _messageClass(){return je}static lc_name(){return"HumanMessagePromptTemplate"}},Xb=class extends dh{static _messageClass(){return fe}static lc_name(){return"AIMessagePromptTemplate"}},Qb=class extends dh{static _messageClass(){return He}static lc_name(){return"SystemMessagePromptTemplate"}};function dN(e){return typeof e.formatMessages=="function"}function hN(e,t){if(dN(e)||st(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){const i=e[1];if(t?.templateFormat==="mustache"&&typeof i=="string"&&i.slice(0,2)==="{{"&&i.slice(-2)==="}}"){const s=i.slice(2,-2);return new Mf({variableName:s,optional:!0})}else if(typeof i=="string"&&i[0]==="{"&&i[i.length-1]==="}"){const s=i.slice(1,-1);return new Mf({variableName:s,optional:!0})}throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const r=Er(e);let n;if(typeof r.content=="string"?n=r.content:n=r.content.map(i=>"text"in i?{...i,text:i.text}:"image_url"in i?{...i,image_url:i.image_url}:i),r._getType()==="human")return hh.fromTemplate(n,t);if(r._getType()==="ai")return Xb.fromTemplate(n,t);if(r._getType()==="system")return Qb.fromTemplate(n,t);if(zn.isInstance(r))return Yb.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}function pN(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var ph=class mo extends fh{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){const r=new Set;for(const o of this.promptMessages)if(!(o instanceof bt))for(const c of o.inputVariables)r.add(c);const n=this.inputVariables,i=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),s=new Set([...i].filter(o=>!r.has(o)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);const a=new Set([...r].filter(o=>!i.has(o)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(t,r){if(typeof t.content=="string")return t;const n=await Promise.all(t.content.map(async i=>{if(i.type!=="image_url")return i;let s="";typeof i.image_url=="string"?s=i.image_url:typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"&&(s=i.image_url.url);const o=await cn.fromTemplate(s,{templateFormat:this.templateFormat}).format(r);return typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url?i.image_url.url=o:i.image_url=o,i}));return t.content=n,t}async formatMessages(t){const r=await this.mergePartialAndUserVariables(t);let n=[];for(const i of this.promptMessages)if(i instanceof bt)n.push(await this._parseImagePrompts(i,r));else{let s;this.templateFormat==="mustache"?s={...r}:s=i.inputVariables.reduce((o,c)=>{if(!(c in r)&&!(pN(i)&&i.optional))throw hc(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return o[c]=r[c],o},{});const a=await i.formatMessages(s);n=n.concat(a)}return n}async partial(t){const r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new mo(i)}static fromTemplate(t,r){const n=cn.fromTemplate(t,r),i=new hh({prompt:n});return this.fromMessages([i])}static fromMessages(t,r){const n=t.reduce((a,o)=>a.concat(o instanceof mo?o.promptMessages:[hN(o,r)]),[]),i=t.reduce((a,o)=>o instanceof mo?Object.assign(a,o.partialVariables):a,Object.create(null)),s=new Set;for(const a of n)if(!(a instanceof bt))for(const o of a.inputVariables)o in i||s.add(o);return new this({...r,inputVariables:[...s],promptMessages:n,partialVariables:i,templateFormat:r?.templateFormat})}},mN=class Rf extends Hs{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
222
-
223
- `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(t){if(super(t),Object.assign(this,t),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ga(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){const r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new Rf(i)}async format(t){const r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),i=await Promise.all(n.map(a=>this.examplePrompt.format(a))),s=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return dr(s,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(t){const{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");const n=await cn.deserialize(r);let i;if(Array.isArray(t.examples))i=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new Rf({inputVariables:t.input_variables,examplePrompt:n,examples:i,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},gN=class e0 extends fh{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
224
-
225
- `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
226
-
227
- `,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ga(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){const r=await this.mergePartialAndUserVariables(t);let n=await this.getExamples(r);n=n.map(s=>{const a={};return this.examplePrompt.inputVariables.forEach(o=>{a[o]=s[o]}),a});const i=[];for(const s of n){const a=await this.examplePrompt.formatMessages(s);i.push(...a)}return i}async format(t){const r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),s=(await Promise.all(n.map(o=>this.examplePrompt.formatMessages(o)))).flat().map(o=>o.content),a=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return dr(a,this.templateFormat,r)}async partial(t){const r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new e0(i)}},yN=class go extends pa{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(t){super({...t,inputVariables:[]}),this.pipelinePrompts=t.pipelinePrompts,this.finalPrompt=t.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const t=this.pipelinePrompts.map(n=>n.name),r=this.pipelinePrompts.map(n=>n.prompt.inputVariables.filter(i=>!t.includes(i))).flat();return[...new Set(r)]}static extractRequiredInputValues(t,r){return r.reduce((n,i)=>(n[i]=t[i],n),{})}async formatPipelinePrompts(t){const r=await this.mergePartialAndUserVariables(t);for(const{name:n,prompt:i}of this.pipelinePrompts){const s=go.extractRequiredInputValues(r,i.inputVariables);i instanceof ph?r[n]=await i.formatMessages(s):r[n]=await i.format(s)}return go.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(t){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(t))}async format(t){return this.finalPrompt.format(await this.formatPipelinePrompts(t))}async partial(t){const r={...this};return r.inputVariables=this.inputVariables.filter(n=>!(n in t)),r.partialVariables={...this.partialVariables??{},...t},new go(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function uy(e){return typeof e=="object"&&e!=null&&"withStructuredOutput"in e&&typeof e.withStructuredOutput=="function"}function _N(e){return typeof e=="object"&&e!=null&&"lc_id"in e&&Array.isArray(e.lc_id)&&e.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var vN=class t0 extends ph{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(t){super(t),this.schema=t.schema,this.method=t.method}pipe(t){if(uy(t))return super.pipe(t.withStructuredOutput(this.schema));if(_N(t)&&uy(t.bound))return super.pipe(new ft({bound:t.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:t.kwargs??{},config:t.config,configFactories:t.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(t,r,n){return t0.fromMessages(t,{schema:r,method:n})}},r0={};pe(r0,{AIMessagePromptTemplate:()=>Xb,BaseChatPromptTemplate:()=>fh,BaseMessagePromptTemplate:()=>Pc,BaseMessageStringPromptTemplate:()=>Zb,BasePromptTemplate:()=>pa,BaseStringPromptTemplate:()=>Hs,ChatMessagePromptTemplate:()=>Yb,ChatPromptTemplate:()=>ph,DEFAULT_FORMATTER_MAPPING:()=>Ko,DEFAULT_PARSER_MAPPING:()=>Jb,DictPromptTemplate:()=>Pf,FewShotChatMessagePromptTemplate:()=>gN,FewShotPromptTemplate:()=>mN,HumanMessagePromptTemplate:()=>hh,ImagePromptTemplate:()=>po,MessagesPlaceholder:()=>Mf,PipelinePromptTemplate:()=>yN,PromptTemplate:()=>cn,StructuredPrompt:()=>vN,SystemMessagePromptTemplate:()=>Qb,checkValidTemplate:()=>ga,interpolateFString:()=>Vb,interpolateMustache:()=>Wb,parseFString:()=>Vs,parseMustache:()=>Jo,parseTemplate:()=>Zo,renderTemplate:()=>dr});var n0={};pe(n0,{BaseDocumentCompressor:()=>wN});var wN=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}};const nn={and:"and",or:"or",not:"not"},Ee={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var i0=class{},mh=class{accept(e){if(this.exprName==="Operation")return e.visitOperation(this);if(this.exprName==="Comparison")return e.visitComparison(this);if(this.exprName==="StructuredQuery")return e.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},gh=class extends mh{},bN=class extends gh{exprName="Comparison";constructor(e,t,r){super(),this.comparator=e,this.attribute=t,this.value=r}},SN=class extends gh{exprName="Operation";constructor(e,t){super(),this.operator=e,this.args=t}},EN=class extends mh{exprName="StructuredQuery";constructor(e,t){super(),this.query=e,this.filter=t}};function s0(e){return e&&typeof e=="object"&&!Array.isArray(e)}function lr(e){return e?typeof e=="string"&&e.length>0||typeof e=="function"?!1:s0(e)&&Object.keys(e).length===0:!0}function a0(e){if(typeof e=="number")return e%1===0;if(typeof e=="string"){const t=parseInt(e,10);return!Number.isNaN(t)&&t%1===0&&t.toString()===e}return!1}function o0(e){if(typeof e=="number")return e%1!==0;if(typeof e=="string"){const t=parseFloat(e);return!Number.isNaN(t)&&t%1!==0&&t.toString()===e}return!1}function c0(e){return typeof e=="string"&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function l0(e){return typeof e=="boolean"}function yh(e){let t;if(c0(e))t=e;else if(a0(e))t=parseInt(e,10);else if(o0(e))t=parseFloat(e);else if(l0(e))t=!!e;else throw new Error("Unsupported value type");return t}var _h=class extends i0{},TN=class extends _h{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[nn.and,nn.or],this.allowedComparators=e?.allowedComparators??[Ee.eq,Ee.ne,Ee.gt,Ee.gte,Ee.lt,Ee.lte]}formatFunction(e){if(e in Ee){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in nn){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){const t=e.args?.map(r=>r.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:yh(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,r="and",n=!1){if(!(lr(e)&&lr(t))){if(lr(e)||r==="replace")return lr(t)?void 0:t;if(lr(t))return n?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,t]};if(r==="or")return{$or:[e,t]};throw new Error("Unknown merge type")}}},CN=class extends _h{allowedOperators=[nn.and,nn.or];allowedComparators=[Ee.eq,Ee.ne,Ee.gt,Ee.gte,Ee.lt,Ee.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[Ee.eq,Ee.ne,Ee.gt,Ee.gte,Ee.lt,Ee.lte];case"number":return[Ee.eq,Ee.ne,Ee.gt,Ee.gte,Ee.lt,Ee.lte];case"boolean":return[Ee.eq,Ee.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case Ee.eq:return(t,r)=>t===r;case Ee.ne:return(t,r)=>t!==r;case Ee.gt:return(t,r)=>t>r;case Ee.gte:return(t,r)=>t>=r;case Ee.lt:return(t,r)=>t<r;case Ee.lte:return(t,r)=>t<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case nn.and:return(t,r)=>t&&r;case nn.or:return(t,r)=>t||r;default:throw new Error("Unknown operator")}}visitOperation(e){const{operator:t,args:r}=e;if(this.allowedOperators.includes(t)){const n=this.getOperatorFunction(t);return i=>r?r.reduce((s,a)=>{const o=a.accept(this);if(typeof o=="function")return n(s,o(i));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){const{comparator:t,attribute:r,value:n}=e,i=[Ee.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof n).includes(t))throw new Error(`'${t}' comparator not allowed to be used with ${typeof n}`);const s=this.getComparatorFunction(t);return a=>{const o=a.metadata[r];return o===void 0?!!i.includes(t):s(o,yh(n))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};const t=e.filter?.accept(this);if(typeof t!="function")throw new Error("Structured query filter is not a function");return{filter:t}}mergeFilters(e,t,r="and"){if(!(lr(e)&&lr(t))){if(lr(e)||r==="replace")return lr(t)?void 0:t;if(lr(t))return r==="and"?void 0:e;if(r==="and")return n=>e(n)&&t(n);if(r==="or")return n=>e(n)||t(n);throw new Error("Unknown merge type")}}},u0={};pe(u0,{BaseTranslator:()=>_h,BasicTranslator:()=>TN,Comparators:()=>Ee,Comparison:()=>bN,Expression:()=>mh,FilterDirective:()=>gh,FunctionalTranslator:()=>CN,Operation:()=>SN,Operators:()=>nn,StructuredQuery:()=>EN,Visitor:()=>i0,castValue:()=>yh,isBoolean:()=>l0,isFilterEmpty:()=>lr,isFloat:()=>o0,isInt:()=>a0,isObject:()=>s0,isString:()=>c0});var f0={};pe(f0,{RunCollectorCallbackHandler:()=>AN});var AN=class extends Hr{name="run_collector";exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}},ON={},d0={};pe(d0,{chunkArray:()=>xN});const xN=(e,t)=>e.reduce((r,n,i)=>{const s=Math.floor(i/t),a=r[s]||[];return r[s]=a.concat([n]),r},[]);var h0={};pe(h0,{EventStreamContentType:()=>PN,convertEventStreamToIterableReadableDataStream:()=>IN,getBytes:()=>p0,getLines:()=>m0,getMessages:()=>g0});const PN="text/event-stream";async function p0(e,t){if(e instanceof ReadableStream){const r=e.getReader();for(;;){const n=await r.read();if(n.done){t(new Uint8Array,!0);break}t(n.value)}}else try{for await(const r of e)t(new Uint8Array(r));t(new Uint8Array,!0)}catch(r){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${r.message}`].join(`
228
- `))}}var oi=(function(e){return e[e.NewLine=10]="NewLine",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.Colon=58]="Colon",e})(oi||{});function m0(e){let t,r,n,i=!1;return function(a,o){if(o){e(a,0,!0);return}t===void 0?(t=a,r=0,n=-1):t=kN(t,a);const c=t.length;let l=0;for(;r<c;){i&&(t[r]===oi.NewLine&&(l=++r),i=!1);let u=-1;for(;r<c&&u===-1;++r)switch(t[r]){case oi.Colon:n===-1&&(n=r-l);break;case oi.CarriageReturn:i=!0;case oi.NewLine:u=r;break}if(u===-1)break;e(t.subarray(l,u),n),l=r,n=-1}l===c?t=void 0:l!==0&&(t=t.subarray(l),r-=l)}}function g0(e,t,r){let n=Pu();const i=new TextDecoder;return function(a,o,c){if(c){MN(n)||(e?.(n),n=Pu());return}if(a.length===0)e?.(n),n=Pu();else if(o>0){const l=i.decode(a.subarray(0,o)),u=o+(a[o+1]===oi.Space?2:1),d=i.decode(a.subarray(u));switch(l){case"data":n.data=n.data?n.data+`
229
- `+d:d;break;case"event":n.event=d;break;case"id":t?.(n.id=d);break;case"retry":{const f=parseInt(d,10);Number.isNaN(f)||r?.(n.retry=f);break}}}}}function kN(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Pu(){return{data:"",event:"",id:"",retry:void 0}}function IN(e,t){const r=new ReadableStream({async start(n){const i=g0(a=>{if(a.event==="error")throw new Error(a.data??"Unspecified event streaming error.");a.event==="metadata"?t?.(a):a.data&&n.enqueue(a.data)});await p0(e,m0((a,o,c)=>{i(a,o,c),c&&n.close()}))}});return ht.fromReadableStream(r)}function MN(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var y0={};pe(y0,{convertToOpenAIFunction:()=>_0,convertToOpenAITool:()=>RN,isLangChainTool:()=>Jd,isRunnableToolLike:()=>Vd,isStructuredTool:()=>Gd,isStructuredToolParams:()=>Wd});function _0(e,t){const r=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:zt(e.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function RN(e,t){const r=typeof t=="number"?void 0:t;let n;return Jd(e)?n={type:"function",function:_0(e)}:n=e,r?.strict!==void 0&&(n.function.strict=r.strict),n}function v0(e,t){let r=0,n=0,i=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s],n+=e[s]*e[s],i+=t[s]*t[s];return r/(Math.sqrt(n)*Math.sqrt(i))}function NN(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function $N(e,t){let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])*(e[n]-t[n]);return r}function LN(e,t){return Math.sqrt($N(e,t))}var w0={};pe(w0,{cosineSimilarity:()=>Nf,euclideanDistance:()=>FN,innerProduct:()=>DN,matrixFunc:()=>kc,maximalMarginalRelevance:()=>UN,normalize:()=>jN});function kc(e,t,r){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(n=>t.map(i=>r(n,i)).map(i=>Number.isNaN(i)?0:i))}function jN(e,t=!1){const r=BN(e);return e.map(n=>n.map(i=>t?1-i/r:i/r))}function Nf(e,t){return kc(e,t,v0)}function DN(e,t){return kc(e,t,NN)}function FN(e,t){return kc(e,t,LN)}function UN(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];const i=Array.isArray(e[0])?e:[e],s=Nf(i,t)[0],a=b0(s).maxIndex,o=[t[a]],c=[a];for(;c.length<Math.min(n,t.length);){let l=-1/0,u=-1;const d=Nf(t,o);s.forEach((f,h)=>{if(c.includes(h))return;const p=Math.max(...d[h]),m=r*f-(1-r)*p;m>l&&(l=m,u=h)}),o.push(t[u]),c.push(u)}return c}function b0(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;n<e.length;n+=1)e[n]>t&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}function BN(e){return e.reduce((t,r)=>Math.max(t,b0(r).maxValue),0)}var zN=class extends Wn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,r){if(t?.stop?.length)return{generations:[{message:new fe(t.stop[0]),text:t.stop[0]}]};const n=e.map(i=>typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2)).join(`
230
- `);return await r?.handleLLMNewToken(n),{generations:[{message:new fe(n),text:n}],llmOutput:{}}}},qN=class S0 extends Wn{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:r=[],chunks:n=[],toolStyle:i="openai",thrownErrorString:s,...a}){super(a),this.sleep=t,this.responses=r,this.chunks=n,this.toolStyle=i,this.thrownErrorString=s}_llmType(){return"fake"}bindTools(t){const r=[...this.tools,...t],n=r.map(a=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:a.name,description:a.description,parameters:zt(a.schema)}};case"anthropic":return{name:a.name,description:a.description,input_schema:zt(a.schema)};case"bedrock":return{toolSpec:{name:a.name,description:a.description,inputSchema:zt(a.schema)}};case"google":return{name:a.name,description:a.description,parameters:zt(a.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:n}]:n,s=new S0({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return s.tools=r,s.withConfig({tools:i})}async _generate(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const i=this.responses?.[0]?.content??t[0].content??"";return{generations:[{text:"",message:new fe({content:i,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const a of this.chunks){const o=new Wi({message:new qt({content:a.content,tool_calls:a.tool_calls,additional_kwargs:a.additional_kwargs??{}}),text:a.content?.toString()??""});yield o,await n?.handleLLMNewToken(a.content,void 0,void 0,void 0,void 0,{chunk:o})}return}const i=this.responses?.[0]??new fe(typeof t[0].content=="string"?t[0].content:""),s=typeof i.content=="string"?i.content:"";for(const a of s){await new Promise(c=>setTimeout(c,this.sleep));const o=new Wi({message:new qt({content:a}),text:a});yield o,await n?.handleLLMNewToken(a,void 0,void 0,void 0,void 0,{chunk:o})}}},HN=class extends Wn{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;constructor(e){super(e);const{responses:t,sleep:r,emitCustomEvent:n}=e;this.responses=t,this.sleep=r,this.emitCustomEvent=n??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,t,r){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{const n=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(n)],llmOutput:{}}}}_formatGeneration(e){return{message:new fe(e),text:e}}async*_streamResponseChunks(e,t,r){const n=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});for await(const i of n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);yield this._createResponseChunk(i),r?.handleLLMNewToken(i)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e){return new Wi({message:new qt({content:e}),text:e})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}withStructuredOutput(e,t){return Mt.from(async r=>{const n=await this.invoke(r);if(n.tool_calls?.[0]?.args)return n.tool_calls[0].args;if(typeof n.content=="string")return JSON.parse(n.content);throw new Error("No structured output found")})}},GN=class extends sh{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");const r=t.length%this.vectorSize,n=r===0?0:this.vectorSize-r,i=t.length+n;t=t.padEnd(i," ");const s=t.length/this.vectorSize,a=[];for(let c=0;c<t.length;c+=s)a.push(t.slice(c,c+s));return a.map(c=>{let l=0;for(let d=0;d<c.length;d+=1)l+=c===" "?0:c.charCodeAt(d);return l%26/26})}},VN=class extends sh{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},WN=class extends lh{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.response??e;return await r?.handleLLMNewToken(n),n}},JN=class extends lh{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.responses?.[0];this.responses=this.responses?.slice(1);for(const i of n??e)await new Promise(s=>setTimeout(s,this.sleep)),yield{text:i,generationInfo:{}},await r?.handleLLMNewToken(i)}},KN=class extends ob{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new je(e))}async addAIMessage(e){this.messages.push(new fe(e))}async clear(){this.messages=[]}},ZN=class extends ih{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},YN=class extends Hr{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},XN=class extends ua{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}},QN=class extends ah{lc_namespace=["test","fake"];output=[new Ur({pageContent:"foo"}),new Ur({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},e$=class extends we{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},t$=class extends Hn{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},r$=class extends Hr{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},n$=class E0 extends oh{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:r,...n}={}){super(t,n),this.similarity=r??v0}async addDocuments(t){const r=t.map(({pageContent:n})=>n);return this.addVectors(await this.embeddings.embedDocuments(r),t)}async addVectors(t,r){const n=t.map((i,s)=>({content:r[s].pageContent,embedding:i,metadata:r[s].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(t,r,n){const i=c=>{if(!n)return!0;const l=new Ur({metadata:c.metadata,pageContent:c.content});return n(l)},s=this.memoryVectors.filter(i);return s.map((c,l)=>({similarity:this.similarity(t,c.embedding),index:l})).sort((c,l)=>c.similarity>l.similarity?-1:0).slice(0,r).map(c=>[new Ur({metadata:s[c.index].metadata,pageContent:s[c.index].content}),c.similarity])}static async fromTexts(t,r,n,i){const s=[];for(let a=0;a<t.length;a+=1){const o=Array.isArray(r)?r[a]:r,c=new Ur({pageContent:t[a],metadata:o});s.push(c)}return E0.fromDocuments(s,n,i)}static async fromDocuments(t,r,n){const i=new this(r,n);return await i.addDocuments(t),i}static async fromExistingIndex(t,r){return new this(t,r)}},T0={};pe(T0,{FakeChatMessageHistory:()=>KN,FakeChatModel:()=>zN,FakeEmbeddings:()=>VN,FakeLLM:()=>WN,FakeListChatMessageHistory:()=>ZN,FakeListChatModel:()=>HN,FakeRetriever:()=>QN,FakeRunnable:()=>e$,FakeSplitIntoListParser:()=>XN,FakeStreamingChatModel:()=>qN,FakeStreamingLLM:()=>JN,FakeTool:()=>t$,FakeTracer:()=>YN,FakeVectorStore:()=>n$,SingleRunExtractor:()=>r$,SyntheticEmbeddings:()=>GN});var C0={};pe(C0,{agents:()=>p1,caches:()=>yw,callbacks__base:()=>av,callbacks__manager:()=>Pv,callbacks__promises:()=>xv,chat_history:()=>ab,document_loaders__base:()=>gb,document_loaders__langsmith:()=>_b,documents:()=>wb,embeddings:()=>cb,example_selectors:()=>Tb,index:()=>g1,indexing:()=>Mb,language_models__base:()=>Tw,language_models__chat_models:()=>Zw,language_models__llms:()=>Cb,load__serializable:()=>L_,memory:()=>lb,messages:()=>Kw,messages__tool:()=>V_,output_parsers:()=>jb,output_parsers__openai_functions:()=>qb,output_parsers__openai_tools:()=>Ub,outputs:()=>tw,prompt_values:()=>pw,prompts:()=>r0,retrievers:()=>pb,retrievers__document_compressors:()=>n0,runnables:()=>Yw,runnables__graph:()=>sw,singletons:()=>$v,stores:()=>fb,structured_query:()=>u0,tools:()=>Aw,tracers__base:()=>Sv,tracers__console:()=>Ev,tracers__log_stream:()=>Qv,tracers__run_collector:()=>f0,tracers__tracer_langchain:()=>Cv,types__stream:()=>ON,utils__async_caller:()=>Wv,utils__chunk_array:()=>d0,utils__env:()=>Q_,utils__event_source_parse:()=>h0,utils__function_calling:()=>y0,utils__hash:()=>gw,utils__json_patch:()=>Rb,utils__json_schema:()=>Vv,utils__math:()=>w0,utils__stream:()=>Jv,utils__testing:()=>T0,utils__tiktoken:()=>Sw,utils__types:()=>rb,vectorstores:()=>mb});function i$(e){const t={};for(let r=e;r&&r.prototype;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r.prototype,"lc_aliases"));return Object.entries(t).reduce((r,[n,i])=>(r[i]=n,r),{})}async function yo(e){const{optionalImportsMap:t={},optionalImportEntrypoints:r=[],importMap:n={},secretsMap:i={},path:s=["$"]}=this,a=s.join(".");if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&"lc"in e&&"type"in e&&"id"in e&&e.lc===1&&e.type==="secret"){const o=e,[c]=o.id;if(c in i)return i[c];{const l=Fr(c);if(l)return l;throw new Error(`Missing key "${c}" for ${a} in load(secretsMap={})`)}}else if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&"lc"in e&&"type"in e&&"id"in e&&e.lc===1&&e.type==="not_implemented"){const c=JSON.stringify(e);throw new Error(`Trying to load an object that doesn't implement serialization: ${a} -> ${c}`)}else if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&"lc"in e&&"type"in e&&"id"in e&&"kwargs"in e&&e.lc===1){const o=e,c=JSON.stringify(o),[l,...u]=o.id.slice().reverse(),d=u.reverse(),f={langchain_core:C0,langchain:n};let h=null;const p=[d.join("/")];d[0]==="langchain_community"&&p.push(["langchain",...d.slice(1)].join("/"));const m=p.find(g=>g in t);if(h1.concat(r).includes(d.join("/"))||m)if(m!==void 0)h=await t[m];else throw new Error(`Missing key "${d.join("/")}" for ${a} in load(optionalImportsMap={})`);else{let g;if(d[0]==="langchain"||d[0]==="langchain_core")g=f[d[0]],d.shift();else throw new Error(`Invalid namespace: ${a} -> ${c}`);if(d.length===0)throw new Error(`Invalid namespace: ${a} -> ${c}`);let _;do{if(_=d.join("__"),_ in g)break;d.pop()}while(d.length>0);_ in g&&(h=g[_])}if(typeof h!="object"||h===null)throw new Error(`Invalid namespace: ${a} -> ${c}`);const w=h[l]??Object.values(h).find(g=>typeof g=="function"&&lc(g)===l);if(typeof w!="function")throw new Error(`Invalid identifer: ${a} -> ${c}`);const y=await yo.call({...this,path:[...s,"kwargs"]},o.kwargs);if(o.type==="constructor"){const g=new w($_(y,OC,i$(w)));return Object.defineProperty(g.constructor,"name",{value:l}),g}else throw new Error(`Invalid type: ${a} -> ${c}`)}else if(typeof e=="object"&&e!==null)return Array.isArray(e)?Promise.all(e.map((o,c)=>yo.call({...this,path:[...s,`${c}`]},o))):Object.fromEntries(await Promise.all(Object.entries(e).map(async([o,c])=>[o,await yo.call({...this,path:[...s,o]},c)])));return e}async function s$(e,t){const r=JSON.parse(e);return yo.call({...t},r)}function a$(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}async function $f(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(r=>$f(r)));{const t={};for(const[r,n]of Object.entries(e))t[r]=await $f(n);if(t.lc===2&&t.type==="undefined")return;if(t.lc===2&&t.type==="constructor"&&Array.isArray(t.id))try{const r=t.id[t.id.length-1];let n;switch(r){case"Set":n=Set;break;case"Map":n=Map;break;case"RegExp":n=RegExp;break;case"Error":n=Error;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(a$(t))return s$(JSON.stringify(t));return t}}return e}function ku(e,t,r,n){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:r??[],kwargs:n??{}}}function o$(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Set||e instanceof Map?ku(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?ku(RegExp,void 0,[e.source,e.flags]):e instanceof Error?ku(e.constructor,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args}:e}var c$=class{_dumps(e){return new TextEncoder().encode(f1(e,(r,n)=>o$(n)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){const t=JSON.parse(e);return $f(t)}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function A0(e){if(typeof e!="object"||e===null)return e;const t=Array.isArray(e)?[]:{};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=A0(e[r]));return t}function O0(){return{v:4,id:sb(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Yo(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:A0(e.versions_seen)}}function x0(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function l$(...e){return e.reduce((t,r,n)=>n===0?r:x0(t,r)>=0?t:r)}const u$={[a1]:-1,[fo]:-2,[o1]:-3,[c1]:-4};var hs=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function f$(e){if(e.length===0)throw new hs("Namespace cannot be empty.");for(const t of e){if(typeof t!="string")throw new hs(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new hs(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new hs(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new hs(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var d$=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){const{filter:r,limit:n=10,offset:i=0,query:s}=t;return(await this.batch([{namespacePrefix:e,filter:r,limit:n,offset:i,query:s}]))[0]}async put(e,t,r,n){f$(e),await this.batch([{namespace:e,key:t,value:r,index:n}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){const{prefix:t,suffix:r,maxDepth:n,limit:i=100,offset:s=0}=e,a=[];return t&&a.push({matchType:"prefix",path:t}),r&&a.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:a.length?a:void 0,maxDepth:n,limit:i,offset:s}]))[0]}start(){}stop(){}};const h$=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e;var p$=class extends d${lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=h$(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){const{filter:r,limit:n=10,offset:i=0,query:s}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:n,offset:i,query:s})}async put(e,t,r){return this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,r)=>{const n=this.nextKey;this.nextKey+=1,this.queue.set(n,{operation:e,resolve:t,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;const e=new Map(this.queue);this.queue.clear();try{const t=Array.from(e.values()).map(({operation:n})=>n),r=await this.store.batch(t);e.forEach(({resolve:n},i)=>{const s=Array.from(e.keys()).indexOf(i);n(r[s])})}catch(t){e.forEach(({reject:r})=>{r(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},m$=class{serde=new c$;constructor(e){this.serde=e||this.serde}},g$=class P0 extends Wn{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:t=[],toolStyle:r="openai",index:n=0,structuredResponse:i,indexRef:s,...a}={}){super(a),this.toolCalls=t,this.toolStyle=r,this.indexRef=s??{current:n},this.structuredResponse=i}get index(){return this.indexRef.current}set index(t){this.indexRef.current=t}_llmType(){return"fake-tool-calling"}_combineLLMOutput(){return[]}bindTools(t){const r=new P0({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return r.tools=[...this.tools,...t],r}withStructuredOutput(t){return new Mt({func:async()=>this.structuredResponse})}async _generate(t,r,n){let s=t[t.length-1].content;t.length>1&&(s=t.map(d=>d.content).filter(Boolean).join("-")),(t.length===1||t.length===2&&t.every(je.isInstance))&&this.index!==0&&(this.index=0);const o=this.toolCalls[this.index]||[],c=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const l=new fe({content:s,id:c,tool_calls:o.length>0?o.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:s,message:l}],llmOutput:{}}}};function y$(){Ve.initializeGlobalInstance(new Vy)}var Jn=class extends Error{lc_error_code;constructor(e,t){let r=e??"";t?.lc_error_code&&(r=`${r}
231
-
232
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
233
- `),super(r),this.lc_error_code=t?.lc_error_code}},k0=class extends Jn{get is_bubble_up(){return!0}},_$=class extends Jn{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},_o=class extends Jn{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},ui=class extends k0{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},I0=class extends ui{constructor(e,t){super([{value:e}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},M0=class extends k0{command;constructor(e){super(),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function v$(e){return e!==void 0&&e.name===M0.unminifiable_name}function vo(e){return e!==void 0&&e.is_bubble_up===!0}function xn(e){return e!==void 0&&[ui.unminifiable_name,I0.unminifiable_name].includes(e.name)}var fy=class extends Jn{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},lt=class extends Jn{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},Fe=class extends Jn{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},w$=class extends Jn{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function R0(e){return e!=null&&e.lg_is_channel===!0}var Kn=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===lt.unminifiable_name)return!1;throw e}}};const Lf=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function vh(e){if(e[Lf]===!0)return e;const t={};for(const r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;const n=e[r];R0(n)&&(t[r]=n)}return Object.assign(t,{[Lf]:!0}),t}function Xo(e,t){const r=vh(e),n={};for(const i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;const s=t.channel_values[i];n[i]=r[i].fromCheckpoint(s)}return Object.assign(n,{[Lf]:!0}),n}function An(e,t,r,n){let i;if(t===void 0)i=e.channel_values;else{i={};for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s))try{i[s]=t[s].checkpoint()}catch(a){if(a.name!==lt.unminifiable_name)throw a}}return{v:4,id:n?.id??sb(r),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var jf=class N0 extends Kn{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,r){super(),this.operator=t,this.initialValueFactory=r,this.value=r?.()}fromCheckpoint(t){const r=new N0(this.operator,this.initialValueFactory);return typeof t<"u"&&(r.value=t),r}update(t){let r=t;if(!r.length)return!1;this.value===void 0&&([this.value]=r,r=r.slice(1));for(const n of r)this.value!==void 0&&(this.value=this.operator(this.value,n));return!0}get(){if(this.value===void 0)throw new lt;return this.value}checkpoint(){if(this.value===void 0)throw new lt;return this.value}isAvailable(){return this.value!==void 0}},wh=class $0 extends Kn{lc_graph_name="LastValue";value=[];fromCheckpoint(t){const r=new $0;return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0)return!1;if(t.length!==1)throw new Fe("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new lt;return this.value[0]}checkpoint(){if(this.value.length===0)throw new lt;return this.value[0]}isAvailable(){return this.value.length!==0}},b$=class L0 extends Kn{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){const r=new L0;if(typeof t<"u"){const[n,i]=t;r.value=[n],r.finished=i}return r}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new lt;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},S$=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}};const Df=function(e){return e?Ff(e):new wh};Df.Root=e=>new S$(e);function Ff(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new jf(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new jf(e.value,e.default):new wh}const Re="__start__",me="__end__",Rr="__input__",E$="__copy__",xt="__error__",Iu="__pregel_ns_writes",ln="__pregel_send",bh="__pregel_call",Rn="__pregel_read",Ke="__pregel_checkpointer",en="__pregel_resuming",Cs="__pregel_task_id",Qo="__pregel_stream",T$="__pregel_resume_value",wo="__pregel_resume_map",un="__pregel_scratchpad",bo="__pregel_previous",j0="__pregel_durability",Uf="checkpoint_id",_r="checkpoint_ns",C$="__pregel_node_finished",Kt="checkpoint_map",dy="__pregel_abort_signals",Ce="__interrupt__",kt="__resume__",Sh="__no_writes__",Zi="__return__",Mu="__previous__",Ye="langsmith:hidden",A$="langsmith:nostream",hy="__self__",Zt="__pregel_tasks",Ft="__pregel_push",So="__pregel_pull",Yt="00000000-0000-0000-0000-000000000000",O$=[Ye,Rr,Ce,kt,xt,Sh,ln,Rn,Ke,j0,Qo,en,Cs,bh,T$,un,bo,Kt,_r,Uf],rt="|",zr=":",py=Symbol.for("langgraph.command");var x$=class{[py];constructor(e){this[py]=e}};function Bf(e){const t=e;return t!=null&&typeof t.node=="string"&&t.args!==void 0}var _t=class{lg_name="Send";node;args;constructor(e,t){this.node=e,this.args=Ws(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function Ht(e){return e instanceof _t}function D0(e){return!e||typeof e!="object"||!(Ce in e)?!1:Array.isArray(e[Ce])}var Xe=class extends x${lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?Ws(e.goto):[Ws(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let e;return typeof this.goto=="string"?e=this.goto:Ht(this.goto)?e=this.goto.toJSON():e=this.goto?.map(t=>typeof t=="string"?t:t.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function at(e){return typeof e!="object"||e==null?!1:"lg_name"in e&&e.lg_name==="Command"}function Ws(e,t=new Map){if(e!=null&&typeof e=="object"){if(t.has(e))return t.get(e);let r;if(Array.isArray(e))r=[],t.set(e,r),e.forEach((n,i)=>{r[i]=Ws(n,t)});else if(at(e)&&!(e instanceof Xe))r=new Xe(e),t.set(e,r);else if(Bf(e)&&!(e instanceof _t))r=new _t(e.node,e.args),t.set(e,r);else if(at(e)||Ht(e))r=e,t.set(e,r);else if("lc_serializable"in e&&e.lc_serializable)r=e,t.set(e,r);else{r={},t.set(e,r);for(const[n,i]of Object.entries(e))r[n]=Ws(i,t)}return r}return e}const P$=["tags","metadata","callbacks","configurable"],k$=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],I$=25;function F0(...e){const t={tags:[],metadata:{},callbacks:void 0,recursionLimit:I$,configurable:{}},r=Ve.getRunnableConfig();if(r!==void 0){for(const[n,i]of Object.entries(r))if(i!==void 0)if(P$.includes(n)){let s;Array.isArray(i)?s=[...i]:typeof i=="object"?n==="callbacks"&&"copy"in i&&typeof i.copy=="function"?s=i.copy():s={...i}:s=i,t[n]=s}else t[n]=i}for(const n of e)if(n!==void 0)for(const[i,s]of Object.entries(n))s!==void 0&&k$.includes(i)&&(t[i]=s);for(const[n,i]of Object.entries(t.configurable))t.metadata=t.metadata??{},!n.startsWith("__")&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&!(n in t.metadata)&&(t.metadata[n]=i);return t}function M$(){return Ve.getRunnableConfig()}function Ru(e){return e.split(rt).filter(t=>!t.match(/^\d+$/)).map(t=>t.split(zr)[0]).join(rt)}function R$(e){const t=e.split(rt);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(rt)}const te=e=>BigInt(e),Ne=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),U0=te("0x9E3779B1"),B0=te("0x85EBCA77"),N$=te("0xC2B2AE3D"),gn=te("0x9E3779B185EBCA87"),Fn=te("0xC2B2AE3D27D4EB4F"),z0=te("0x165667B19E3779F9"),Eh=te("0x85EBCA77C2B2AE63"),$$=te("0x27D4EB2F165667C5"),L$=te("0x165667919E3779F9"),j$=te("0x9FB21C651E98DF25"),D$=e=>{const t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");const r=t/2,n=new Uint8Array(r);let i=0,s=0;for(;s<r;){const a=e.slice(i,i+=2);n[s]=Number.parseInt(a,16),s+=1}return Ne(n)},yr=D$("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),fi=(te(1)<<te(128))-te(1),ve=(te(1)<<te(64))-te(1),ec=(te(1)<<te(32))-te(1),Nr=64,q0=Nr/8,F$=8,ro=4;function Yi(e){if(!e)throw new Error("Assert failed")}function U$(e){const t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function B$(e){let t=e;return t=(t&te(65535))<<te(16)|(t&te(4294901760))>>te(16),t=(t&te(16711935))<<te(8)|(t&te(4278255360))>>te(8),t}function z$(e,t){return(e&ec)*(t&ec)&ve}function q$(e,t){return(e<<t|e>>te(32)-t)&ec}function H0(e,t,r){for(let n=0;n<q0;n+=1){const i=t.getBigUint64(n*8,!0),s=i^r.getBigUint64(n*8,!0);e[n^1]+=i,e[n]+=z$(s,s>>te(32))}return e}function my(e,t,r,n){for(let i=0;i<n;i+=1)H0(e,Ne(t,i*Nr),Ne(r,i*8));return e}function H$(e,t){for(let r=0;r<q0;r+=1){const n=t.getBigUint64(r*8,!0);let i=e[r];i=zf(i,te(47)),i^=n,i*=U0,e[r]=i&ve}return e}function no(e,t){return G0(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(F$,!0))}function gy(e,t,r){let n=r;return n+=no(e.slice(0),Ne(t,0*ro)),n+=no(e.slice(2),Ne(t,4*ro)),n+=no(e.slice(4),Ne(t,8*ro)),n+=no(e.slice(6),Ne(t,12*ro)),vr(n&ve)}function G$(e,t,r,n,i){let s=e;const a=Math.floor((r.byteLength-Nr)/8),o=Nr*a,c=Math.floor((t.byteLength-1)/o);for(let l=0;l<c;l+=1)s=my(s,Ne(t,l*o),r,a),s=i(s,Ne(r,r.byteLength-Nr));{const l=Math.floor((t.byteLength-1-o*c)/Nr);s=my(s,Ne(t,c*o),r,l),s=n(s,Ne(t,t.byteLength-Nr),Ne(r,r.byteLength-Nr-7))}return s}function V$(e,t){let r=new BigUint64Array([N$,gn,Fn,z0,Eh,B0,$$,U0]);Yi(e.byteLength>128),r=G$(r,e,t,H0,H$),Yi(r.length*8===64);{const n=gy(r,Ne(t,11),te(e.byteLength)*gn&ve);return gy(r,Ne(t,t.byteLength-Nr-11),~(te(e.byteLength)*Fn)&ve)<<te(64)|n}}function G0(e,t){const r=e*t&fi;return r&ve^r>>te(64)}function yy(e,t,r){return G0((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+r)&ve,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-r)&ve)}function Eo(e,t,r,n,i){let s=e&ve,a=e>>te(64)&ve;return s+=yy(t,n,i),s^=r.getBigUint64(0,!0)+r.getBigUint64(8,!0),s&=ve,a+=yy(r,Ne(n,16),i),a^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),a&=ve,a<<te(64)|s}function vr(e){let t=e;return t^=t>>te(37),t*=L$,t&=ve,t^=t>>te(32),t}function tc(e){let t=e;return t^=t>>te(33),t*=Fn,t&=ve,t^=t>>te(29),t*=z0,t&=ve,t^=t>>te(32),t}function W$(e,t,r){const n=e.byteLength;Yi(n>0&&n<=3);const i=te(e.getUint8(n-1))|te(n<<8)|te(e.getUint8(0)<<16)|te(e.getUint8(n>>1)<<24),s=(te(t.getUint32(0,!0))^te(t.getUint32(4,!0)))+r,a=(i^s)&ve,o=(te(t.getUint32(8,!0))^te(t.getUint32(12,!0)))-r,c=(q$(B$(i),te(13))^o)&ve;return(tc(c)&ve)<<te(64)|tc(a)}function zf(e,t){return e^e>>t}function J$(e,t,r){const n=e.byteLength;Yi(n>=4&&n<=8);{const i=e.getUint32(0,!0),s=e.getUint32(n-4,!0),a=te(i)|te(s)<<te(32),o=(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+r&ve;let l=(a^o)*(gn+(te(n)<<te(2)))&fi;return l+=(l&ve)<<te(65),l&=fi,l^=l>>te(67),zf(zf(l&ve,te(35))*j$&ve,te(28))|vr(l>>te(64))<<te(64)}}function K$(e,t,r){const n=e.byteLength;Yi(n>=9&&n<=16);{const i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+r&ve,s=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-r&ve,a=e.getBigUint64(0,!0);let o=e.getBigUint64(n-8,!0),c=(a^o^i)*gn;const l=(c&ve)+(te(n-1)<<te(54));c=c&(fi^ve)|l,o^=s,c+=o+(o&ec)*(B0-te(1))<<te(64),c&=fi,c^=U$(c>>te(64));let u=(c&ve)*Fn;return u+=(c>>te(64))*Fn<<te(64),u&=fi,vr(u&ve)|vr(u>>te(64))<<te(64)}}function Z$(e,t){const r=e.byteLength;return Yi(r<=16),r>8?K$(e,yr,t):r>=4?J$(e,yr,t):r>0?W$(e,yr,t):tc(t^yr.getBigUint64(64,!0)^yr.getBigUint64(72,!0))|tc(t^yr.getBigUint64(80,!0)^yr.getBigUint64(88,!0))<<te(64)}function qf(e){return~e+te(1)&ve}function Y$(e,t,r){let n=te(e.byteLength)*gn&ve,i=te(e.byteLength-1)/te(32);for(;i>=0;){const o=Number(i);n=Eo(n,Ne(e,16*o),Ne(e,e.byteLength-16*(o+1)),Ne(t,32*o),r),i-=te(1)}let s=n+(n>>te(64))&ve;s=vr(s);let a=(n&ve)*gn+(n>>te(64))*Eh+(te(e.byteLength)-r&ve)*Fn;return a&=ve,a=qf(vr(a)),s|a<<te(64)}function X$(e,t,r){let n=te(e.byteLength)*gn&ve;for(let a=32;a<160;a+=32)n=Eo(n,Ne(e,a-32),Ne(e,a-16),Ne(t,a-32),r);n=vr(n&ve)|vr(n>>te(64))<<te(64);for(let a=160;a<=e.byteLength;a+=32)n=Eo(n,Ne(e,a-32),Ne(e,a-16),Ne(t,3+a-160),r);n=Eo(n,Ne(e,e.byteLength-16),Ne(e,e.byteLength-32),Ne(t,103),qf(r));let i=n+(n>>te(64))&ve;i=vr(i);let s=(n&ve)*gn+(n>>te(64))*Eh+(te(e.byteLength)-r&ve)*Fn;return s&=ve,s=qf(vr(s)),i|s<<te(64)}function Tn(e,t=te(0)){const r=new TextEncoder,n=Ne(typeof e=="string"?r.encode(e):e),i=n.byteLength,s=a=>a.toString(16).padStart(32,"0");return i<=16?s(Z$(n,t)):i<=128?s(Y$(n,yr,t)):i<=240?s(X$(n,yr,t)):s(V$(n,yr))}function V0(e){return/^[0-9a-f]{32}$/.test(e)}function W0(e){const t=Ve.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");const r=t.configurable;if(!r)throw new Error("No configurable found in config");if(!r[Ke])throw new _o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const i=r[un];i.interruptCounter+=1;const s=i.interruptCounter;if(i.resume.length>0&&s<i.resume.length)return r[ln]?.([[kt,i.resume]]),i.resume[s];if(i.nullResume!==void 0){if(i.resume.length!==s)throw new Error(`Resume length mismatch: ${i.resume.length} !== ${s}`);const c=i.consumeNullResume();return i.resume.push(c),r[ln]?.([[kt,i.resume]]),c}const a=r[_r]?.split(rt),o=a?Tn(a.join(rt)):void 0;throw new ui([{id:o,value:e}])}var Zn=class extends we{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.trace=t.trace??this.trace,this.recurse=t.recurse??this.recurse}async _tracedInvoke(t,r,n){return new Promise((i,s)=>{const a=ke(r,{callbacks:n?.getChild()});Ve.runWithConfig(a,async()=>{try{const o=await this.func(t,a);i(o)}catch(o){s(o)}})})}async invoke(t,r){let n;const i=F0(r),s=Bt(this.config,i);return this.trace?n=await this._callWithConfig(this._tracedInvoke,t,s):n=await Ve.runWithConfig(s,async()=>this.func(t,s)),we.isRunnable(n)&&this.recurse?await Ve.runWithConfig(s,async()=>n.invoke(t,s)):n}};function*Zr(e,t){if(t===void 0)yield*e;else for(const r of e)yield[t,r]}async function tn(e){const t=[];for await(const r of await e)t.push(r);return t}function _s(e){const t=[];for(const r of e)t.push(r);return t}function Qn(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function Q$(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const Nn={[Symbol.for("LG_PASSTHROUGH")]:!0};function io(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Nu=Symbol("IS_WRITER");var wt=class Hf extends Zn{writes;constructor(t,r){const n=`ChannelWrite<${t.map(i=>Ht(i)?i.node:"channel"in i?i.channel:"...").join(",")}>`;super({writes:t,name:n,tags:r,func:async(i,s)=>this._write(i,s??{})}),this.writes=t}async _write(t,r){const n=this.writes.map(i=>$u(i)&&io(i.value)?{mapper:i.mapper,value:t}:To(i)&&io(i.value)?{channel:i.channel,value:t,skipNone:i.skipNone,mapper:i.mapper}:i);return await Hf.doWrite(r,n),t}static async doWrite(t,r){for(const s of r){if(To(s)){if(s.channel===Zt)throw new Fe("Cannot write to the reserved channel TASKS");if(io(s.value))throw new Fe("PASSTHROUGH value must be replaced")}if($u(s)&&io(s.value))throw new Fe("PASSTHROUGH value must be replaced")}const n=[];for(const s of r)if(Ht(s))n.push([Zt,s]);else if($u(s)){const a=await s.mapper.invoke(s.value,t);a!=null&&a.length>0&&n.push(...a)}else if(To(s)){const a=s.mapper!==void 0?await s.mapper.invoke(s.value,t):s.value;if(Q$(a)||s.skipNone&&a===void 0)continue;n.push([s.channel,a])}else throw new Error(`Invalid write entry: ${JSON.stringify(s)}`);const i=t.configurable?.[ln];i(n)}static isWriter(t){return t instanceof Hf||Nu in t&&!!t[Nu]}static registerWriter(t){return Object.defineProperty(t,Nu,{value:!0})}};function To(e){return e!==void 0&&typeof e.channel=="string"}function $u(e){return e!==void 0&&!To(e)&&we.isRunnable(e.mapper)}var eL=class J0 extends Zn{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,r,n=!1){super({func:(i,s)=>J0.doRead(s,this.channel,this.fresh,this.mapper)}),this.fresh=n,this.mapper=r,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,r,n,i){const s=t.configurable?.[Rn];if(!s)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return i?i(s(r,n)):s(r,n)}};const ei=new qs;var Js=class vs extends ft{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=ei;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(t){const{channels:r,triggers:n,mapper:i,writers:s,bound:a,kwargs:o,metadata:c,retryPolicy:l,cachePolicy:u,tags:d,subgraphs:f,ends:h}=t,p=[...t.config?.tags?t.config.tags:[],...d??[]];super({...t,bound:t.bound??ei,config:{...t.config?t.config:{},tags:p}}),this.channels=r,this.triggers=n,this.mapper=i,this.writers=s??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=c??this.metadata,this.tags=p,this.retryPolicy=l,this.cachePolicy=u,this.subgraphs=f,this.ends=h}getWriters(){const t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof wt&&t[t.length-2]instanceof wt;){const r=t.slice(-2),n=r[0].writes.concat(r[1].writes);t[t.length-2]=new wt(n,r[0].config?.tags),t.pop()}return t}getNode(){const t=this.getWriters();if(!(this.bound===ei&&t.length===0))return this.bound===ei&&t.length===1?t[0]:this.bound===ei?new er({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new er({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new vs({channels:{...this.channels,...Object.fromEntries(t.map(r=>[r,r]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return wt.isWriter(t)?new vs({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===ei?new vs({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:ct(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new vs({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function tL(e){return"steps"in e&&Array.isArray(e.steps)}function Th(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function K0(e){const t=[e];for(const r of t){if(Th(r))return r;tL(r)&&t.push(...r.steps)}}function di(e,t,r=!0,n=!1){try{return e[t].get()}catch(i){if(i.name===lt.unminifiable_name){if(n)return i;if(r)return null}throw i}}function Un(e,t,r=!0){if(Array.isArray(t)){const n={};for(const i of t)try{n[i]=di(e,i,!r)}catch(s){if(s.name===lt.unminifiable_name)continue}return n}else return di(e,t)}function*rL(e,t){if(e.graph===Xe.PARENT)throw new Fe("There is no parent graph.");if(e.goto){let r;Array.isArray(e.goto)?r=e.goto:r=[e.goto];for(const n of r)if(Ht(n))yield[Yt,Zt,n];else if(typeof n=="string")yield[Yt,`branch:to:${n}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof n}`)}if(e.resume)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(V0))for(const[r,n]of Object.entries(e.resume)){const i=t.filter(s=>s[0]===r&&s[1]===kt).map(s=>s[2]).slice(0,1)??[];i.push(n),yield[r,kt,i]}else yield[Yt,kt,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(const[r,n]of e.update)yield[Yt,r,n];else for(const[r,n]of Object.entries(e.update))yield[Yt,r,n]}}function*Z0(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(const r in t)e.includes(r)&&(yield[r,t[r]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Lu(e,t,r){Array.isArray(e)?(t===!0||t.find(([n,i])=>e.includes(n)))&&(yield Un(r,e)):(t===!0||t.some(([n,i])=>n===e))&&(yield di(r,e))}function*nL(e,t,r){const n=t.filter(([o,c])=>(o.config===void 0||!o.config.tags?.includes(Ye))&&c[0][0]!==xt&&c[0][0]!==Ce);if(!n.length)return;let i;n.some(([o])=>o.writes.some(([c,l])=>c===Zi))?i=n.flatMap(([o])=>o.writes.filter(([c,l])=>c===Zi).map(([c,l])=>[o.name,l])):Array.isArray(e)?i=n.flatMap(([o])=>{const{writes:c}=o,l={};for(const[u]of c)e.includes(u)&&(l[u]=(l[u]||0)+1);return Object.values(l).some(u=>u>1)?c.filter(([u])=>e.includes(u)).map(([u,d])=>[o.name,{[u]:d}]):[[o.name,Object.fromEntries(c.filter(([u])=>e.includes(u)))]]}):i=n.flatMap(([o])=>o.writes.filter(([c,l])=>c===e).map(([c,l])=>[o.name,l]));const s={};for(const[o,c]of i)o in s||(s[o]=[]),s[o].push(c);const a={};for(const o in s)if(s[o].length===1){const[c]=s[o];a[o]=c}else a[o]=s[o];r&&(a.__metadata__={cached:r}),yield a}function Ch(e){const t=typeof e[Re];if(t==="number")return 0;if(t==="string")return"";for(const r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;const n=typeof e[r];if(n==="number")return 0;if(n==="string")return"";break}}function Co(e,t){if(Object.keys(e).length>0){const r=Ch(t);return Object.fromEntries(Object.entries(t).filter(([n,i])=>i>(e[n]??r)))}else return t}function iL(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function cr(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function Sn(e,t){const r=t?.parents??{};return Object.keys(r).length>0?cr(e,{[Kt]:{...r,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function rc(...e){const t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};const r=new AbortController,n=()=>{const s=t.find(a=>a.aborted)?.reason;r.abort(s),t.forEach(a=>a.removeEventListener("abort",n))};t.forEach(s=>s.addEventListener("abort",n,{once:!0}));const i=t.find(s=>s.aborted);return i&&r.abort(i.reason),{signal:r.signal,dispose:()=>{t.forEach(s=>s.removeEventListener("abort",n))}}}const sL=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t};var aL=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:e,name:t,input:r,retry:n,cache:i,callbacks:s}){this.func=e,this.name=t,this.input=r,this.retry=n,this.cache=i,this.callbacks=s}};function oL(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function cL(e,t){const r=new Zn({func:n=>t(...n),name:e,trace:!1,recurse:!1});return new er({name:e,first:r,last:new wt([{channel:Zi,value:Nn}],[Ye])})}const lL=e=>e!==void 0?e+1:1;function uL(e,t){if(t==null)return!1;for(const r of e)if(t[r])return!0;return!1}function fL(e){let t;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t==null?t=e[r]:t=l$(t,e[r]));return t}function so(e,t,r){const n=Ch(e.channel_versions),i=e.versions_seen[Ce]??{};let s=!1;if((e.channel_versions[Re]??n)>(i[Re]??n))s=!0;else for(const o in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,o)&&e.channel_versions[o]>(i[o]??n)){s=!0;break}const a=r.some(o=>t==="*"?!o.config?.tags?.includes(Ye):t.includes(o.name));return s&&a}function Ao(e,t,r,n,i=!1){let s=new Set;if(Array.isArray(n))s=new Set(n.filter(o=>r.writes.some(([c,l])=>c===o)));else{for(const[o]of r.writes)if(o===n){s=new Set([o]);break}s=s||new Set}let a;if(i&&s.size>0){const o=Object.fromEntries(Object.entries(t).filter(([u,d])=>s.has(u))),c=An(e,o,-1),l=Xo(o,c);Dt(Yo(c),l,[r],void 0,void 0),a=Un({...t,...l},n)}else a=Un(t,n);return a}function ju(e,t,r){for(const[n,i]of r)if([Ft,Zt].includes(n)&&i!=null){if(!Ht(i))throw new Fe(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(i)}`);if(!(i.node in t))throw new Fe(`Invalid node name "${i.node}" in Send packet`)}e(r)}const dL=new Set([Sh,Ft,kt,Ce,Zi,xt]);function Dt(e,t,r,n,i){r.sort((f,h)=>{const p=f.path?.slice(0,3)||[],m=h.path?.slice(0,3)||[];for(let w=0;w<Math.min(p.length,m.length);w+=1){if(p[w]<m[w])return-1;if(p[w]>m[w])return 1}return p.length-m.length});const s=r.some(f=>f.triggers.length>0),a=vh(t);for(const f of r){e.versions_seen[f.name]??={};for(const h of f.triggers)h in e.channel_versions&&(e.versions_seen[f.name][h]=e.channel_versions[h])}let o=fL(e.channel_versions);const c=new Set(r.flatMap(f=>f.triggers).filter(f=>!O$.includes(f)));let l=!1;for(const f of c)f in a&&a[f].consume()&&n!==void 0&&(e.channel_versions[f]=n(o),l=!0);const u={};for(const f of r)for(const[h,p]of f.writes)dL.has(h)||h in a&&(u[h]??=[],u[h].push(p));o!=null&&n!=null&&(o=l?n(o):o);const d=new Set;for(const[f,h]of Object.entries(u))if(f in a){const p=a[f];let m;try{m=p.update(h)}catch(w){if(w.name===Fe.unminifiable_name){const y=new Fe(`Invalid update for channel "${f}" with values ${JSON.stringify(h)}: ${w.message}`);throw y.lc_error_code=w.lc_error_code,y}else throw w}m&&n!==void 0&&(e.channel_versions[f]=n(o),p.isAvailable()&&d.add(f))}if(s)for(const f in a){if(!Object.prototype.hasOwnProperty.call(a,f))continue;const h=a[f];h.isAvailable()&&!d.has(f)&&h.update([])&&n!==void 0&&(e.channel_versions[f]=n(o),h.isAvailable()&&d.add(f))}if(s&&!uL(d,i))for(const f in a){if(!Object.prototype.hasOwnProperty.call(a,f))continue;const h=a[f];h.finish()&&n!==void 0&&(e.channel_versions[f]=n(o),h.isAvailable()&&d.add(f))}return d}function*hL(e,t,r){if(r.updatedChannels!=null&&r.triggerToNodes!=null){const i=new Set;for(const s of r.updatedChannels){const a=r.triggerToNodes[s];for(const o of a??[])i.add(o)}yield*[...i].sort();return}if(!(()=>{for(const i in e.channel_versions)if(e.channel_versions[i]!==null)return!1;return!0})())for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(yield i)}function ci(e,t,r,n,i,s,a){const o={},c=n[Zt];if(c?.isAvailable()){const l=c.get().length;for(let u=0;u<l;u+=1){const d=Gf([Ft,u],e,t,r,n,i,s,a);d!==void 0&&(o[d.id]=d)}}for(const l of hL(e,r,a)){const u=Gf([So,l],e,t,r,n,i,s,a);u!==void 0&&(o[u.id]=u)}return o}function Gf(e,t,r,n,i,s,a,o){const{step:c,checkpointer:l,manager:u}=o,d=s.configurable??{},f=d.checkpoint_ns??"";if(e[0]===Ft&&oL(e[e.length-1])){const h=e[e.length-1],p=cL(h.name,h.func),m=[Ft],w=f===""?h.name:`${f}${rt}${h.name}`,y=si(JSON.stringify([w,c.toString(),h.name,Ft,e[1],e[2]]),t.id),g=`${w}${zr}${y}`,_=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:h.name,langgraph_triggers:m,langgraph_path:_,langgraph_checkpoint_ns:g};if(a){const A=[];return{name:h.name,input:h.input,proc:p,writes:A,config:ke(Bt(s,{metadata:b,store:o.store??s.store}),{runName:h.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Cs]:y,[ln]:x=>ju(T=>A.push(...T),n,x),[Rn]:(x,T=!1)=>Ao(t,i,{name:h.name,writes:A,triggers:m,path:_},x,T),[Ke]:l??d[Ke],[Kt]:{...d[Kt],[f]:t.id},[un]:Du({pendingWrites:r??[],taskId:y,currentTaskInput:h.input,resumeMap:s.configurable?.[wo],namespaceHash:Tn(g)}),[bo]:t.channel_values[Mu],checkpoint_id:void 0,checkpoint_ns:g}}),triggers:m,retry_policy:h.retry,cache_key:h.cache?{key:Tn((h.cache.keyFunc??JSON.stringify)([h.input])),ns:[Iu,h.name??"__dynamic__"],ttl:h.cache.ttl}:void 0,id:y,path:_,writers:[]}}else return{id:y,name:h.name,interrupts:[],path:_}}else if(e[0]===Ft){const h=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!i[Zt]?.isAvailable())return;const p=i[Zt].get();if(h<0||h>=p.length)return;const m=Bf(p[h])&&!Ht(p[h])?new _t(p[h].node,p[h].args):p[h];if(!Bf(m)){console.warn(`Ignoring invalid packet ${JSON.stringify(m)} in pending sends.`);return}if(!(m.node in n)){console.warn(`Ignoring unknown node name ${m.node} in pending sends.`);return}const w=[Ft],y=f===""?m.node:`${f}${rt}${m.node}`,g=si(JSON.stringify([y,c.toString(),m.node,Ft,h.toString()]),t.id),_=`${y}${zr}${g}`;let b={langgraph_step:c,langgraph_node:m.node,langgraph_triggers:w,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:_};if(a){const A=n[m.node],P=A.getNode();if(P!==void 0){A.metadata!==void 0&&(b={...b,...A.metadata});const x=[];return{name:m.node,input:m.args,proc:P,subgraphs:A.subgraphs,writes:x,config:ke(Bt(s,{metadata:b,tags:A.tags,store:o.store??s.store}),{runName:m.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Cs]:g,[ln]:T=>ju(R=>x.push(...R),n,T),[Rn]:(T,R=!1)=>Ao(t,i,{name:m.node,writes:x,triggers:w,path:e},T,R),[Ke]:l??d[Ke],[Kt]:{...d[Kt],[f]:t.id},[un]:Du({pendingWrites:r??[],taskId:g,currentTaskInput:m.args,resumeMap:s.configurable?.[wo],namespaceHash:Tn(_)}),[bo]:t.channel_values[Mu],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:w,retry_policy:A.retryPolicy,cache_key:A.cachePolicy?{key:Tn((A.cachePolicy.keyFunc??JSON.stringify)([m.args])),ns:[Iu,A.name??"__dynamic__",m.node],ttl:A.cachePolicy.ttl}:void 0,id:g,path:e,writers:A.getWriters()}}}else return{id:g,name:m.node,interrupts:[],path:e}}else if(e[0]===So){const h=e[1].toString(),p=n[h];if(p===void 0)return;if(r?.length){const g=f===""?h:`${f}${rt}${h}`,_=si(JSON.stringify([g,c.toString(),h,So,h]),t.id);if(r.some(A=>A[0]===_&&A[1]!==xt))return}const m=Ch(t.channel_versions);if(m===void 0)return;const w=t.versions_seen[h]??{},y=p.triggers.find(g=>i[g].isAvailable()?(t.channel_versions[g]??m)>(w[g]??m):!1);if(y!==void 0){const g=pL(p,i,a);if(g===void 0)return;const _=f===""?h:`${f}${rt}${h}`,b=si(JSON.stringify([_,c.toString(),h,So,[y]]),t.id),A=`${_}${zr}${b}`;let P={langgraph_step:c,langgraph_node:h,langgraph_triggers:[y],langgraph_path:e,langgraph_checkpoint_ns:A};if(a){const x=p.getNode();if(x!==void 0){p.metadata!==void 0&&(P={...P,...p.metadata});const T=[];return{name:h,input:g,proc:x,subgraphs:p.subgraphs,writes:T,config:ke(Bt(s,{metadata:P,tags:p.tags,store:o.store??s.store}),{runName:h,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Cs]:b,[ln]:R=>ju(M=>{T.push(...M)},n,R),[Rn]:(R,M=!1)=>Ao(t,i,{name:h,writes:T,triggers:[y],path:e},R,M),[Ke]:l??d[Ke],[Kt]:{...d[Kt],[f]:t.id},[un]:Du({pendingWrites:r??[],taskId:b,currentTaskInput:g,resumeMap:s.configurable?.[wo],namespaceHash:Tn(A)}),[bo]:t.channel_values[Mu],checkpoint_id:void 0,checkpoint_ns:A}}),triggers:[y],retry_policy:p.retryPolicy,cache_key:p.cachePolicy?{key:Tn((p.cachePolicy.keyFunc??JSON.stringify)([g])),ns:[Iu,p.name??"__dynamic__",h],ttl:p.cachePolicy.ttl}:void 0,id:b,path:e,writers:p.getWriters()}}}else return{id:b,name:h,interrupts:[],path:e}}}}function pL(e,t,r){let n;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){n={};for(const[i,s]of Object.entries(e.channels))if(e.triggers.includes(s))try{n[i]=di(t,s,!1)}catch(a){if(a.name===lt.unminifiable_name)return;throw a}else if(s in t)try{n[i]=di(t,s,!1)}catch(a){if(a.name===lt.unminifiable_name)continue;throw a}}else if(Array.isArray(e.channels)){let i=!1;for(const s of e.channels)try{n=di(t,s,!1),i=!0;break}catch(a){if(a.name===lt.unminifiable_name)continue;throw a}if(!i)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return r&&e.mapper!==void 0&&(n=e.mapper(n)),n}function Du({pendingWrites:e,taskId:t,currentTaskInput:r,resumeMap:n,namespaceHash:i}){const s=e.find(([c,l])=>c===Yt&&l===kt)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{const c=e.filter(([l,u])=>l===t&&u===kt).flatMap(([l,u,d])=>d);if(n!=null&&i in n){const l=n[i];c.push(l)}return c})(),nullResume:s,subgraphCounter:0,currentTaskInput:r,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,e.splice(e.findIndex(([c,l])=>c===Yt&&l===kt),1),s}};return o}const Ks={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Zs=(e,t)=>`${e.start}${t}${e.end}`;function*_y(e){for(const{id:t,name:r,input:n,config:i,triggers:s,writes:a}of e){if(i?.tags?.includes(Ye))continue;const o=a.filter(([c,l])=>c===t&&l===Ce).map(([,c])=>c);yield{id:t,name:r,input:n,triggers:s,interrupts:o}}}function mL(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function Y0(e){const t={};for(const[r,n]of e){const i=String(r);if(i in t){const s=mL(t[i])?t[i].$writes:[t[i]];s.push(n),t[i]={$writes:s}}else t[i]=n}return t}function*gL(e,t){for(const[{id:r,name:n,config:i},s]of e)i?.tags?.includes(Ye)||(yield{id:r,name:n,result:Y0(s.filter(([a])=>Array.isArray(t)?t.includes(a):a===t)),interrupts:s.filter(a=>a[0]===Ce).map(a=>a[1])})}function*yL(e,t,r,n,i,s,a,o){function c(d){const f={};return d.callbacks!=null&&(f.callbacks=d.callbacks),d.configurable!=null&&(f.configurable=d.configurable),d.maxConcurrency!=null&&(f.max_concurrency=d.maxConcurrency),d.metadata!=null&&(f.metadata=d.metadata),d.recursionLimit!=null&&(f.recursion_limit=d.recursionLimit),d.runId!=null&&(f.run_id=d.runId),d.runName!=null&&(f.run_name=d.runName),d.tags!=null&&(f.tags=d.tags),f}const l=e.configurable?.checkpoint_ns,u={};for(const d of i){if(!(d.subgraphs?.length?d.subgraphs:[d.proc]).find(K0))continue;let h=`${d.name}:${d.id}`;l&&(h=`${l}|${h}`),u[d.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:h}}}yield{config:c(e),values:Un(t,r),metadata:n,next:i.map(d=>d.name),tasks:X0(i,s,u,o),parentConfig:a?c(a):void 0}}function X0(e,t,r,n){return e.map(i=>{const s=t.find(([l,u])=>l===i.id&&u===xt)?.[2],a=t.filter(([l,u])=>l===i.id&&u===Ce).map(([,,l])=>l),o=(()=>{if(s||a.length||!t.length)return;const l=t.findIndex(([u,d])=>u===i.id&&d===Zi);if(l>=0)return t[l][2];if(typeof n=="string")return t.find(([u,d])=>u===i.id&&d===n)?.[2];if(Array.isArray(n)){const u=t.filter(([d,f])=>d===i.id&&n.includes(f)).map(([,d,f])=>[d,f]);return u.length?Y0(u):void 0}})();if(s)return{id:i.id,name:i.name,path:i.path,error:s,interrupts:a,result:o};const c=r?.[i.id];return{id:i.id,name:i.name,path:i.path,interrupts:a,...c!==void 0?{state:c}:{},result:o}})}function _L(e,t,r){console.log([`${Zs(Ks.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
234
- `,JSON.stringify(Un(t,r),null,2)].join(""))}function Q0(e,t){const r=t.length;console.log([`${Zs(Ks.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${r} task${r===1?"":"s"}:\x1B[0m
235
- `,t.map(n=>`- ${Zs(Ks.green,String(n.name))} -> ${JSON.stringify(n.input,null,2)}`).join(`
236
- `)].join(""))}function vL(e,t,r){const n={};for(const[i,s]of t)r.includes(i)&&(n[i]||(n[i]=[]),n[i].push(s));console.log([`${Zs(Ks.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(n).length} channel${Object.keys(n).length!==1?"s":""}:\x1B[0m
237
- `,Object.entries(n).map(([i,s])=>`- ${Zs(Ks.yellow,i)} -> ${s.map(a=>JSON.stringify(a)).join(", ")}`).join(`
238
- `)].join(""))}var vy=class extends ht{_abortController;_innerReader;constructor(e,t){const r=e.getReader(),n=t??new AbortController;super({start(i){return s();function s(){return r.read().then(({done:a,value:o})=>{if(a){i.close();return}return i.enqueue(o),s()})}}}),this._abortController=n,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},eS=class extends ht{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t;const r=new Promise(n=>{t=n});super({start:n=>{t(n)}}),r.then(n=>{this.controller=n}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){this.controller.error(e)}};function wL(e){return JSON.stringify(e,function(t,r){const n=this[t];if(n!=null&&typeof n=="object"&&"toDict"in n&&typeof n.toDict=="function"){const{type:i,data:s}=n.toDict();return{...s,type:i}}return r})}function bL(e){return e instanceof Error?{error:e.name,message:e.message}:{error:"Error",message:JSON.stringify(e)}}function Ah(e){return typeof e!="object"||e==null?!1:"configurable"in e&&typeof e.configurable=="object"&&e.configurable!=null}function Fu(e){return!Ah(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||"",checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function wy(e){if(Ah(e)){const t=Object.fromEntries(Object.entries(e.configurable).filter(([n])=>!n.startsWith("__"))),r={...e,configurable:t};return delete r.callbacks,r}return e}function by(e){const t={...e,checkpoint:Fu(e.config),parent_checkpoint:Fu(e.parentConfig),config:wy(e.config),parent_config:wy(e.parentConfig),tasks:e.tasks.map(r=>{if(Ah(r.state)){const n=Fu(r.state);if(n!=null){const i={...r,checkpoint:n};return delete i.state,i}}return r})};return delete t.parentConfig,t}function SL(e){const t=new TextEncoder;return new ReadableStream({async start(r){const n=i=>{r.enqueue(t.encode(`event: ${i.event}
239
- data: ${wL(i.data)}
240
-
241
- `))};try{for await(const i of e){const[s,a,o]=i;let c=o;if(a==="debug"){const u=o;u.type==="checkpoint"&&(c={...u,payload:by(u.payload)})}a==="checkpoints"&&(c=by(o));const l=s?.length?`${a}|${s.join("|")}`:a;n({event:l,data:c})}}catch(i){n({event:"error",data:bL(i)})}r.close()}})}const ao=Symbol.for("INPUT_DONE"),Uu=Symbol.for("INPUT_RESUMING"),EL=25;function TL(...e){return new eS({passthroughFn:t=>{for(const r of e)r.modes.has(t[1])&&r.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var CL=class extends m${cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){const r=this.queue.then(()=>this.cache[e](...t));return this.queue=r.then(()=>{},()=>{}),r}},AL=class tS{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if(Re in this.checkpoint.channel_versions)t=!0;else for(const c in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,c)){t=!0;break}const n=this.config.configurable?.[en]!==void 0&&this.config.configurable?.[en],i=this.input===null||this.input===void 0,s=at(this.input)&&this.input.resume!=null,a=this.input===Uu,o=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return t&&(n||i||s||a||o)}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=lL,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites,this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.manager=t.manager,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.skipDoneTasks=t.skipDoneTasks,this.store=t.store,this.cache=t.cache?new CL(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes}static async initialize(t){let{config:r,stream:n}=t;n!==void 0&&r.configurable?.[Qo]!==void 0&&(n=TL(n,r.configurable[Qo]));const i=r.configurable?!("checkpoint_id"in r.configurable):!0,s=r.configurable?.[un];r.configurable&&s&&(s.subgraphCounter>0&&(r=cr(r,{[_r]:[r.configurable[_r],s.subgraphCounter.toString()].join(rt)})),s.subgraphCounter+=1);const a=Rn in(r.configurable??{});!a&&r.configurable?.checkpoint_ns!==void 0&&r.configurable?.checkpoint_ns!==""&&(r=cr(r,{checkpoint_ns:"",checkpoint_id:void 0}));let o=r;r.configurable?.[Kt]!==void 0&&r.configurable?.[Kt]?.[r.configurable?.checkpoint_ns]&&(o=cr(r,{checkpoint_id:r.configurable[Kt][r.configurable?.checkpoint_ns]}));const c=r.configurable?.checkpoint_ns?.split(rt)??[],l=await t.checkpointer?.getTuple(o)??{config:r,checkpoint:O0(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};o={...r,...l.config,configurable:{checkpoint_ns:"",...r.configurable,...l.config.configurable}};const u=l.parentConfig,d=Yo(l.checkpoint),f={...l.metadata},h=l.pendingWrites??[],p=Xo(t.channelSpecs,d),m=(f.step??0)+1,w=m+(r.recursionLimit??EL)+1,y={...d.channel_versions},g=t.store?new p$(t.store):void 0;return g&&await g.start(),new tS({input:t.input,config:r,checkpointer:t.checkpointer,checkpoint:d,checkpointMetadata:f,checkpointConfig:o,prevCheckpointConfig:u,checkpointNamespace:c,channels:p,isNested:a,manager:t.manager,skipDoneTasks:i,step:m,stop:w,checkpointPreviousVersions:y,checkpointPendingWrites:h,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:n,store:g,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(t){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(t,r){let n=r;if(n.length===0)return;n.every(([a])=>a in u$)&&(n=Array.from(new Map(n.map(a=>[a[0],a])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(a=>a[0]!==t);for(const[a,o]of n)this.checkpointPendingWrites.push([t,a,o]);const i=cr(this.checkpointConfig,{[_r]:this.config.configurable?.checkpoint_ns??"",[Uf]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(i,n,t)),this.tasks&&this._outputWrites(t,n),!r.length||!this.cache||!this.tasks)return;const s=this.tasks[t];s==null||s.cache_key==null||r[0][0]===xt||r[0][0]===Ce||this.cache.set([{key:[s.cache_key.ns,s.cache_key.key],value:s.writes,ttl:s.cache_key.ttl}])}_outputWrites(t,r,n=!1){const i=this.tasks[t];if(i!==void 0){if(i.config!==void 0&&(i.config.tags??[]).includes(Ye))return;if(r.length>0)if(r[0][0]===Ce){if(i.path?.[0]===Ft&&i.path?.at(-1)===!0)return;const s=r.filter(a=>a[0]===Ce).flatMap(a=>a[1]);this._emit([["updates",{[Ce]:s}],["values",{[Ce]:s}]])}else r[0][0]!==xt&&this._emit(_s(Zr(nL(this.outputKeys,[[i,r]],n),"updates")));n||this._emit(_s(Zr(gL([[i,r]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const t=[],r=([a,o])=>`ns:${a.join(",")}|key:${o}`,n=[],i={};for(const a of Object.values(this.tasks))a.cache_key!=null&&!a.writes.length&&(n.push([a.cache_key.ns,a.cache_key.key]),i[r([a.cache_key.ns,a.cache_key.key])]=a);if(n.length===0)return[];const s=await this.cache.get(n);for(const{key:a,value:o}of s){const c=i[r(a)];c!=null&&(c.writes.push(...o),t.push({task:c,result:o}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:r=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![ao,Uu].includes(this.input))await this._first(r);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new ui;if(Object.values(this.tasks).every(s=>s.writes.length>0)){const s=Object.values(this.tasks).flatMap(o=>o.writes);this.updatedChannels=Dt(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const a=await tn(Zr(Lu(this.outputKeys,s,this.channels),"values"));if(this._emit(a),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),so(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new ui;this.config.configurable?.[en]!==void 0&&delete this.config.configurable?.[en]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const n=ci(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels});if(this.tasks=n,this.checkpointer&&this._emit(await tn(Zr(yL(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[s,a,o]of this.checkpointPendingWrites){if(a===xt||a===Ce||a===kt)continue;const c=Object.values(this.tasks).find(l=>l.id===s);c&&c.writes.push([a,o])}for(const s of Object.values(this.tasks))s.writes.length>0&&this._outputWrites(s.id,s.writes,!0)}if(Object.values(this.tasks).every(s=>s.writes.length>0))return this.tick({inputKeys:r});if(so(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new ui;const i=await tn(Zr(_y(Object.values(this.tasks)),"tasks"));return this._emit(i),!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(n=>!n.includes(zr)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const r=this._suppressInterrupt(t);return(r||t===void 0)&&(this.output=Un(this.channels,this.outputKeys)),r&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(n=>n.writes.length>0)&&(this.updatedChannels=Dt(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(_s(Zr(Lu(this.outputKeys,Object.values(this.tasks).flatMap(n=>n.writes),this.channels),"values")))),xn(t)&&!t.interrupts.length&&this._emit([["updates",{[Ce]:[]}],["values",{[Ce]:[]}]])),r}async acceptPush(t,r,n){if(this.interruptAfter?.length>0&&so(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}const i=Gf([Ft,t.path??[],r,t.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!i)return;if(this.interruptBefore?.length>0&&so(this.checkpoint,this.interruptBefore,[i])){this.toInterrupt.push(i);return}this._emit(_s(Zr(_y([i]),"tasks"))),this.debug&&Q0(this.step,[i]),this.tasks[i.id]=i,this.skipDoneTasks&&this._matchWrites({[i.id]:i});const s=await this._matchCachedWrites();for(const{task:a}of s)this._outputWrites(a.id,a.writes,!0);return i}_suppressInterrupt(t){return xn(t)&&!this.isNested}async _first(t){const{configurable:r}=this.config,n=r?.[un];if(n&&n.nullResume!==void 0&&this.putWrites(Yt,[[kt,n.nullResume]]),at(this.input)){const a=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(V0)&&(this.config.configurable??={},this.config.configurable[wo]=this.input.resume),a&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const o={};for(const[c,l,u]of rL(this.input,this.checkpointPendingWrites))o[c]??=[],o[c].push([l,u]);if(Object.keys(o).length===0)throw new fy("Received empty Command input");for(const[c,l]of Object.entries(o))this.putWrites(c,l)}const i=(this.checkpointPendingWrites??[]).filter(a=>a[0]===Yt).map(a=>a.slice(1));i.length>0&&Dt(this.checkpoint,this.channels,[{name:Rr,writes:i,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const s=at(this.input)&&i.length>0;if(this.isResuming||s){for(const o in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,o)&&this.checkpoint.channel_versions[o]!==void 0){const c=this.checkpoint.channel_versions[o];this.checkpoint.versions_seen[Ce]={...this.checkpoint.versions_seen[Ce],[o]:c}}const a=await tn(Zr(Lu(this.outputKeys,!0,this.channels),"values"));this._emit(a)}if(this.isResuming)this.input=Uu;else if(s)await this._putCheckpoint({source:"input"}),this.input=ao;else{const a=await tn(Z0(t,this.input));if(a.length>0){const o=ci(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Dt(this.checkpoint,this.channels,Object.values(o).concat([{name:Rr,writes:a,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=ao}else if(en in(this.config.configurable??{}))this.input=ao;else throw new fy(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=cr(this.config,{[en]:this.isResuming}))}_emit(t){for(const[r,n]of t)if(this.stream.modes.has(r)&&this.stream.push([this.checkpointNamespace,r,n]),(r==="checkpoints"||r==="tasks")&&this.stream.modes.has("debug")){const i=r==="checkpoints"?this.step-1:this.step,s=new Date().toISOString(),a=r==="checkpoints"?"checkpoint":typeof n=="object"&&n!=null&&"result"in n?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:i,type:a,timestamp:s,payload:n}])}}_putCheckpoint(t){const r=this.checkpointMetadata===t,n=this.checkpointer!=null&&(this.durability!=="exit"||r),i=s=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=cr(this.checkpointConfig,{[_r]:this.config.configurable?.checkpoint_ns??""});const a={...this.checkpoint.channel_versions},o=Co(this.checkpointPreviousVersions,a);this.checkpointPreviousVersions=a,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Yo(s),metadata:{...this.checkpointMetadata},newVersions:o}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};r||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.[Kt]??{}}),this.checkpoint=An(this.checkpoint,n?this.channels:void 0,this.step,r?{id:this.checkpoint.id}:void 0),n&&i(this.checkpoint),r||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const t=cr(this.checkpointConfig,{[_r]:this.config.configurable?.checkpoint_ns??"",[Uf]:this.checkpoint.id}),r={};for(const[n,i,s]of this.checkpointPendingWrites)r[n]??=[],r[n].push([i,s]);for(const[n,i]of Object.entries(r))this.checkpointerPromises.push(this.checkpointer.putWrites(t,i,n))}_matchWrites(t){for(const[r,n,i]of this.checkpointPendingWrites){if(n===xt||n===Ce||n===kt)continue;const s=Object.values(t).find(a=>a.id===r);s&&s.writes.push([n,i])}for(const r of Object.values(t))r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}};function OL(e){return st(e?.message)}var xL=class extends ns{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,r,n=!1){if(n&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;r!=null&&(Sd(t)?i??=`run-${r}-tool-${t.tool_call_id}`:((i==null||i===`run-${r}`)&&(i=this.stableMessageIdMap[r]??i??`run-${r}`),this.stableMessageIdMap[r]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,i,s,a,o){a&&(!s||!s.includes(A$)&&!s.includes("nostream"))&&(this.metadatas[r]=[a.langgraph_checkpoint_ns.split("|"),{tags:s,name:o,...a}])}handleLLMNewToken(e,t,r,n,i,s){const a=s?.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(OL(a)?this._emit(this.metadatas[r],a.message,r):this._emit(this.metadatas[r],new qt({content:e}),r))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){const r=e.generations?.[0]?.[0];st(r?.message)&&this._emit(this.metadatas[t],r?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,n,i,s,a,o){if(s!==void 0&&o===s.langgraph_node&&(i===void 0||!i.includes(Ye))&&(this.metadatas[r]=[s.langgraph_checkpoint_ns.split("|"),{tags:i,name:o,...s}],typeof t=="object")){for(const c of Object.values(t))if((st(c)||Ms(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(const l of c)(st(l)||Ms(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){const r=this.metadatas[t];if(delete this.metadatas[t],r!==void 0){if(st(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(const n of e)st(n)&&this._emit(r,n,t,!0);else if(e!=null&&typeof e=="object"){for(const n of Object.values(e))if(st(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(const i of n)st(i)&&this._emit(r,i,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};const PL=500,kL=2,IL=128e3,ML=3,RL=[400,401,402,403,404,405,406,407,409],NL=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;const t=e?.response?.status??e?.status;return!(t&&RL.includes(+t)||e?.error?.code==="insufficient_quota")};async function rS(e,t,r,n){const i=e.retry_policy??t;let s=i!==void 0?i.initialInterval??PL:0,a=0,o,c,{config:l}=e;for(r&&(l=cr(l,r)),l={...l,signal:n};!n?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{c=await e.proc.invoke(e.input,l);break}catch(u){if(o=u,o.pregelTaskId=e.id,v$(o)){const p=l?.configurable?.checkpoint_ns,m=o.command;if(m.graph===p){for(const w of e.writers)await w.invoke(m,l);o=void 0;break}else if(m.graph===Xe.PARENT){const w=R$(p);o.command=new Xe({...o.command,graph:w})}}if(vo(o)||i===void 0||(a+=1,a>=(i.maxAttempts??ML))||!(i.retryOn??NL)(o))break;s=Math.min(i.maxInterval??IL,s*(i.backoffFactor??kL));const f=i.jitter?Math.floor(s+Math.random()*1e3):s;await new Promise(p=>setTimeout(p,f));const h=o.name??o.constructor.unminifiable_name??o.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${a}) after ${h}: ${o}`),l=cr(l,{[en]:!0})}}return{task:e,result:c,error:o,signalAborted:n?.aborted}}const Vf=Symbol.for("promiseAdded");function $L(){const e={next:()=>{},wait:Promise.resolve(Vf)};function t(r){e.next=()=>{e.wait=new Promise(t),r(Vf)}}return e.wait=new Promise(t),e}var LL=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){const{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:i}=e,s=new Set;let a;const o=new AbortController,c=o.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks).filter(p=>p.writes.length===0),{signals:d,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),h=this._executeTasksWithRetry(u,{signals:d,retryPolicy:r,maxConcurrency:i});for await(const{task:p,error:m,signalAborted:w}of h)this._commit(p,m),xn(m)||vo(m)&&!xn(a)?a=m:m&&(s.size===0||!w)&&(o.abort(),s.add(m));if(f?.(),n?.(this.loop.step,Object.values(this.loop.tasks).map(p=>p.writes).flat()),s.size===1)throw Array.from(s)[0];if(s.size>1)throw new AggregateError(Array.from(s),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(xn(a)||vo(a)&&this.loop.isNested)throw a}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:r}){const n=this.loop.config.configurable?.[dy]??{},i=n.externalAbortSignal??r,s=t??n.timeoutAbortSignal,{signal:a,dispose:o}=rc(i,s,e),c={externalAbortSignal:i,timeoutAbortSignal:s,composedAbortSignal:a};return this.loop.config=cr(this.loop.config,{[dy]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(e,t){const{retryPolicy:r,maxConcurrency:n,signals:i}=t??{},s=$L(),a={},o={executingTasksMap:a,barrier:s,retryPolicy:r,scheduleTask:async(f,h,p)=>this.loop.acceptPush(f,h,p)};if(i?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,l;const u=rc(i?.externalAbortSignal,i?.timeoutAbortSignal),d=u.signal?new Promise((f,h)=>{l=()=>h(new Error("Abort")),u.signal?.addEventListener("abort",l,{once:!0})}):void 0;for(;(c===0||Object.keys(a).length>0)&&e.length;){for(;Object.values(a).length<(n??e.length)&&c<e.length;c+=1){const h=e[c];a[h.id]=rS(h,r,{[bh]:nS?.bind(o,this,h)},i?.composedAbortSignal).catch(p=>({task:h,error:p,signalAborted:i?.composedAbortSignal?.aborted}))}const f=await Promise.race([...Object.values(a),...d?[d]:[],s.wait]);f!==Vf&&(yield f,l!=null&&(u.signal?.removeEventListener("abort",l),u.dispose?.()),delete a[f.task.id])}}_commit(e,t){if(t!==void 0)if(xn(t)){if(t.interrupts.length){const r=t.interrupts.map(i=>[Ce,i]),n=e.writes.filter(i=>i[0]===kt);n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else vo(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[xt,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(Ye))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([Sh,null]),this.loop.putWrites(e.id,e.writes)}};async function nS(e,t,r,n,i,s={}){const a=t.config?.configurable?.[un];if(!a)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);const o=a.callCounter;a.callCounter+=1;const c=new aL({func:r,name:n,input:i,cache:s.cache,retry:s.retry,callbacks:s.callbacks}),l=await this.scheduleTask(t,o,c);if(!l)return;const u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){const d=l.writes.filter(([h])=>h===Zi),f=l.writes.filter(([h])=>h===xt);if(d.length>0){if(d.length===1)return Promise.resolve(d[0][1]);throw new Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(f.length>0){if(f.length===1){const h=f[0][1],p=h instanceof Error?h:new Error(String(h));return Promise.reject(p)}throw new Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{const d=rS(l,s.retry,{[bh]:nS.bind(this,e,l)});return this.executingTasksMap[l.id]=d,this.barrier.next(),d.then(({result:f,error:h})=>h?Promise.reject(h):f)}}var Ir=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function jL({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:i,interruptAfterNodes:s,interruptBeforeNodes:a}){if(!t)throw new Ir("Channels not provided");const o=new Set,c=new Set;for(const[l,u]of Object.entries(e)){if(l===Ce)throw new Ir(`"Node name ${Ce} is reserved"`);if(u.constructor===Js)u.triggers.forEach(d=>o.add(d));else throw new Ir(`Invalid node type ${typeof u}, expected PregelNode`)}for(const l of o)if(!(l in t))throw new Ir(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(r)){if(r.every(l=>!o.has(l)))throw new Ir(`None of the input channels ${r} are subscribed to by any node`)}else if(!o.has(r))throw new Ir(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach(l=>c.add(l)):c.add(n),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(l=>c.add(l));for(const l of c)if(!(l in t))throw new Ir(`Output channel '${String(l)}' not in channels`);if(s&&s!=="*"){for(const l of s)if(!(l in e))throw new Ir(`Node ${String(l)} not in nodes`)}if(a&&a!=="*"){for(const l of a)if(!(l in e))throw new Ir(`Node ${String(l)} not in nodes`)}}function Sy(e,t){if(Array.isArray(e)){for(const r of e)if(!(r in t))throw new Error(`Key ${String(r)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}var DL=class iS extends Kn{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){const r=new iS({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(r.seen=new Set(t[0]),r.values=t[1]),r}update(t){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);const n=t.flat();if(n.length>0)if(this.unique)for(const i of n)this.seen.has(i)||(r=!0,this.seen.add(i),this.values.push(i));else r=!0,this.values.push(...n);return r}get(){if(this.values.length===0)throw new lt;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},FL=class{static subscribeTo(e,t){const{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&r!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let i;typeof e=="string"?r?i={[r]:e}:i=[e]:i=Object.fromEntries(e.map(a=>[a,a]));const s=Array.isArray(e)?e:[e];return new Js({channels:i,triggers:s,tags:n})}static writeTo(e,t){const r=[];for(const n of e)r.push({channel:n,value:Nn,skipNone:!1});for(const[n,i]of Object.entries(t??{}))we.isRunnable(i)||typeof i=="function"?r.push({channel:n,value:Nn,skipNone:!0,mapper:ct(i)}):r.push({channel:n,value:i,skipNone:!1});return new wt(r)}},UL=class extends we{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},BL=class extends UL{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,Zt in this.channels&&"lc_graph_name"in this.channels[Zt]&&this.channels[Zt].lc_graph_name!=="Topic")throw new Error(`Channel '${Zt}' is reserved and cannot be used in the graph.`);this.channels[Zt]=new DL({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}withConfig(e){const t=Bt(this.config,e);return new this.constructor({...this,config:t})}validate(){jL({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[e,t]of Object.entries(this.nodes))for(const r of t.triggers)this.triggerToNodes[r]??=[],this.triggerToNodes[r].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(const[r,n]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(r))continue;const i=n.subgraphs?.length?n.subgraphs:[n.bound];for(const s of i){const a=K0(s);if(a!==void 0){if(r===e){yield[r,a];return}if(e===void 0&&(yield[r,a]),t){let o=e;e!==void 0&&(o=e.slice(r.length+1));for(const[c,l]of a.getSubgraphs(o,t))yield[`${r}${rt}${c}`,l]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:n=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};const i=Xo(this.channels,t.checkpoint);if(t.pendingWrites?.length){const d=t.pendingWrites.filter(([f,h])=>f===Yt).map(([f,h,p])=>[String(h),p]);d.length>0&&Dt(t.checkpoint,i,[{name:Rr,writes:d,triggers:[]}],void 0,this.triggerToNodes)}const s=Object.values(ci(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),a=await tn(this.getSubgraphsAsync()),o=t.config.configurable?.checkpoint_ns??"",c={};for(const d of s){const f=a.find(([p])=>p===d.name);if(!f)continue;let h=`${String(d.name)}${zr}${d.id}`;if(o&&(h=`${o}${rt}${h}`),r===void 0){const p={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:h}};c[d.id]=p}else{const p={configurable:{[Ke]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:h}},m=f[1];c[d.id]=await m.getState(p,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){const d=Object.fromEntries(s.map(h=>[h.id,h]));for(const[h,p,m]of t.pendingWrites)[xt,Ce,fo].includes(p)||h in d&&d[h].writes.push([String(p),m]);const f=s.filter(h=>h.writes.length>0);f.length>0&&Dt(t.checkpoint,i,f,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});const u=s.filter(d=>d.writes.length===0).map(d=>d.name);return{values:Un(i,this.streamChannelsAsIs),next:u,tasks:X0(s,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:Sn(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){const r=e.configurable?.[Ke]??this.checkpointer;if(!r)throw new _o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[Ke]===void 0){const o=Ru(n);for await(const[c,l]of this.getSubgraphsAsync(o,!0))if(c===o)return await l.getState(Qn(e,{[Ke]:r}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${o}" not found.`)}const i=Bt(this.config,e),s=await r.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:s,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){const r=e.configurable?.[Ke]??this.checkpointer;if(!r)throw new _o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[Ke]===void 0){const s=Ru(n);for await(const[a,o]of this.getSubgraphsAsync(s,!0))if(a===s){yield*o.getStateHistory(Qn(e,{[Ke]:r}),t);return}throw new Error(`Subgraph with namespace "${s}" not found.`)}const i=Bt(this.config,e,{configurable:{checkpoint_ns:n}});for await(const s of r.list(i,t))yield this._prepareStateSnapshot({config:s.config,saved:s})}async bulkUpdateState(e,t){const r=e.configurable?.[Ke]??this.checkpointer;if(!r)throw new _o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(a=>a.updates.length===0))throw new Error("No updates provided");const n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[Ke]===void 0){const a=Ru(n);for await(const[,o]of this.getSubgraphsAsync(a,!0))return await o.bulkUpdateState(Qn(e,{[Ke]:r}),t);throw new Error(`Subgraph "${a}" not found`)}const i=async(a,o)=>{const c=this.config?Bt(this.config,a):a,l=await r.getTuple(c),u=l!==void 0?Yo(l.checkpoint):O0(),d={...l?.checkpoint.channel_versions},f=l?.metadata?.step??-1;let h=Qn(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),p=c.metadata??{};l?.config.configurable&&(h=Qn(c,l.config.configurable),p={...l.metadata,...p});const{values:m,asNode:w}=o[0];if(m==null&&w===void 0){if(o.length>1)throw new Fe("Cannot create empty checkpoint with multiple updates");const x=await r.put(h,An(u,void 0,f),{source:"update",step:f+1,parents:l?.metadata?.parents??{}},{});return Sn(x,l?l.metadata:void 0)}const y=Xo(this.channels,u);if(m===null&&w===me){if(o.length>1)throw new Fe("Cannot apply multiple updates when clearing state");if(l){const T=ci(u,l.pendingWrites||[],this.nodes,y,l.config,!0,{step:(l.metadata?.step??-1)+1,checkpointer:r,store:this.store}),R=(l.pendingWrites||[]).filter(M=>M[0]===Yt).map(M=>M.slice(1));R.length>0&&Dt(u,y,[{name:Rr,writes:R,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(const[M,U,H]of l.pendingWrites||[])[xt,Ce,fo].includes(U)||M in T&&T[M].writes.push([U,H]);Dt(u,y,Object.values(T),r.getNextVersion.bind(r),this.triggerToNodes)}const x=await r.put(h,An(u,y,f),{...p,source:"update",step:f+1,parents:l?.metadata?.parents??{}},Co(d,u.channel_versions));return Sn(x,l?l.metadata:void 0)}if(w===E$){if(o.length>1)throw new Fe("Cannot copy checkpoint with multiple updates");if(l==null)throw new Fe("Cannot copy a non-existent checkpoint");const x=M=>!Array.isArray(M)||M.length===0?!1:M.every(U=>Array.isArray(U)&&U.length===2),T=An(u,void 0,f),R=await r.put(l.parentConfig??Qn(l.config,{checkpoint_id:void 0}),T,{source:"fork",step:f+1,parents:l.metadata?.parents??{}},{});if(x(m)){const M=ci(T,l.pendingWrites,this.nodes,y,R,!1,{step:f+2}),U=Object.values(M).reduce((F,{name:K,id:ee})=>(F[K]??=[],F[K].push({id:ee}),F),{}),H=m.reduce((F,K)=>{const[ee,L]=K;F[L]??=[];const z=F[L].length,W=U[L]?.[z]?.id;return F[L].push({values:ee,asNode:L,taskId:W}),F},{});return i(Sn(R,l.metadata),Object.values(H).flat())}return Sn(R,l.metadata)}if(w===Rr){if(o.length>1)throw new Fe("Cannot apply multiple updates when updating as input");const x=await tn(Z0(this.inputChannels,m));if(x.length===0)throw new Fe(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Dt(u,y,[{name:Rr,writes:x,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const T=l?.metadata?.step!=null?l.metadata.step+1:-1,R=await r.put(h,An(u,y,T),{source:"input",step:T,parents:l?.metadata?.parents??{}},Co(d,u.channel_versions));return await r.putWrites(R,x,si(Rr,u.id)),Sn(R,l?l.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&l?.pendingWrites!==void 0&&l.pendingWrites.length>0){const x=ci(u,l.pendingWrites,this.nodes,y,l.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(l.metadata?.step??-1)+1}),T=(l.pendingWrites??[]).filter(M=>M[0]===Yt).map(M=>M.slice(1));T.length>0&&Dt(l.checkpoint,y,[{name:Rr,writes:T,triggers:[]}],void 0,this.triggerToNodes);for(const[M,U,H]of l.pendingWrites)[xt,Ce,fo].includes(U)||x[M]===void 0||x[M].writes.push([U,H]);const R=Object.values(x).filter(M=>M.writes.length>0);R.length>0&&Dt(u,y,R,void 0,this.triggerToNodes)}const g=Object.values(u.versions_seen).map(x=>Object.values(x)).flat().find(x=>!!x),_=[];if(o.length===1){let{values:x,asNode:T,taskId:R}=o[0];if(T===void 0&&Object.keys(this.nodes).length===1)[T]=Object.keys(this.nodes);else if(T===void 0&&g===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(T=this.inputChannels);else if(T===void 0){const M=Object.entries(u.versions_seen).map(([U,H])=>Object.values(H).map(F=>[F,U])).flat().filter(([U,H])=>H!==Ce).sort(([U],[H])=>x0(U,H));M&&(M.length===1?T=M[0][1]:M[M.length-1][0]!==M[M.length-2][0]&&(T=M[M.length-1][1]))}if(T===void 0)throw new Fe('Ambiguous update, specify "asNode"');_.push({values:x,asNode:T,taskId:R})}else for(const{asNode:x,values:T,taskId:R}of o){if(x==null)throw new Fe('"asNode" is required when applying multiple updates');_.push({values:T,asNode:x,taskId:R})}const b=[];for(const{asNode:x,values:T,taskId:R}of _){if(this.nodes[x]===void 0)throw new Fe(`Node "${x.toString()}" does not exist`);const M=this.nodes[x].getWriters();if(!M.length)throw new Fe(`No writers found for node "${x.toString()}"`);b.push({name:x,input:T,proc:M.length>1?er.from(M,{omitSequenceTags:!0}):M[0],writes:[],triggers:[Ce],id:R??si(Ce,u.id),writers:[]})}for(const x of b)await x.proc.invoke(x.input,ke({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[ln]:T=>x.writes.push(...T),[Rn]:(T,R=!1)=>Ao(u,y,x,T,R)}}));for(const x of b){const T=x.writes.filter(R=>R[0]!==Ft);l!==void 0&&T.length>0&&await r.putWrites(h,T,x.id)}Dt(u,y,b,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const A=Co(d,u.channel_versions),P=await r.put(h,An(u,y,f+1),{source:"update",step:f+1,parents:l?.metadata?.parents??{}},A);for(const x of b){const T=x.writes.filter(R=>R[0]===Ft);T.length>0&&await r.putWrites(P,T,x.id)}return Sn(P,l?l.metadata:void 0)};let s=e;for(const{updates:a}of t)s=await i(s,a);return s}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){const{debug:t,streamMode:r,inputKeys:n,outputKeys:i,interruptAfter:s,interruptBefore:a,...o}=e;let c=!0;const l=t!==void 0?t:this.debug;let u=i;u===void 0?u=this.streamChannelsAsIs:Sy(u,this.channels);let d=n;d===void 0?d=this.inputChannels:Sy(d,this.channels);const f=a??this.interruptBefore??[],h=s??this.interruptAfter??[];let p;r!==void 0?(p=Array.isArray(r)?r:[r],c=typeof r=="string"):(e.configurable?.[Cs]!==void 0?p=["values"]:p=this.streamMode,c=!0);let m;if(this.checkpointer===!1)m=void 0;else if(e!==void 0&&e.configurable?.[Ke]!==void 0)m=e.configurable[Ke];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");m=this.checkpointer}const w=e.store??this.store,y=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const g=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),_=e.durability??g??e?.configurable?.[j0]??"async";return[l,p,d,u,o,f,h,m,w,c,y,_]}async stream(e,t){const r=new AbortController,n={recursionLimit:this.config?.recursionLimit,...t,signal:rc(t?.signal,r.signal).signal},i=await super.stream(e,n);return new vy(t?.encoding==="text/event-stream"?SL(i):i,r)}streamEvents(e,t,r){const n=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:sL(this.config?.callbacks,t?.callbacks),signal:rc(t?.signal,n.signal).signal};return new vy(super.streamEvents(e,i,r),n)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){const r="version"in(t??{})?void 0:t?.encoding??void 0,n=t?.subgraphs,i=F0(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const s=await this._validateInput(e),{runId:a,...o}=i,[c,l,,u,d,f,h,p,m,w,y,g]=this._defaults(o);typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);const _=new eS({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};const U=d.configurable[_r]??"";d.configurable[_r]=U.split(rt).map(H=>H.split(zr)[0]).join(rt)}if(l.includes("messages")){const U=new xL(F=>_.push(F)),{callbacks:H}=d;if(H===void 0)d.callbacks=[U];else if(Array.isArray(H))d.callbacks=H.concat(U);else{const F=H.copy();F.addHandler(U,!0),d.callbacks=F}}d.writer??=U=>{if(!l.includes("custom"))return;const H=M$()?.configurable?.[_r]?.split(rt).slice(0,-1);_.push([H??[],"custom",U])},d.interrupt??=this.userInterrupt??W0;const A=await(await Pt(d))?.handleChainStart(this.toJSON(),iL(e,"input"),a,void 0,void 0,void 0,d?.runName??this.getName()),P=vh(this.channels);let x,T;const M=(async()=>{try{x=await AL.initialize({input:s,config:d,checkpointer:p,nodes:this.nodes,channelSpecs:P,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:m,cache:y,stream:_,interruptAfter:h,interruptBefore:f,manager:A,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:g});const U=new LL({loop:x,nodeFinished:d.configurable?.[C$]});t?.subgraphs&&(x.config.configurable={...x.config.configurable,[Qo]:x.stream}),await this._runLoop({loop:x,runner:U,debug:c,config:d}),g==="sync"&&await Promise.all(x?.checkpointerPromises??[])}catch(U){T=U}finally{try{x&&(await x.store?.stop(),await x.cache?.stop()),await Promise.all(x?.checkpointerPromises??[])}catch(U){T=T??U}T?_.error(T):_.close()}})();try{for await(const U of _){if(U===void 0)throw new Error("Data structure error.");const[H,F,K]=U;if(l.includes(F)){if(r==="text/event-stream"){n?yield[H,F,K]:yield[null,F,K];continue}n&&!w?yield[H,F,K]:w?n?yield[H,K]:yield K:yield[F,K]}}}catch(U){throw await A?.handleChainError(T),U}finally{await M}await A?.handleChainEnd(x?.output??{},a,void 0,void 0,void 0)}async invoke(e,t){const r=t?.streamMode??"values",n={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:r,encoding:void 0},i=[],s=await this.stream(e,n),a=[];let o;for await(const c of s)r==="values"?D0(c)?a.push(c[Ce]):o=c:i.push(c);if(r==="values"){if(a.length>0){const c=a.flat(1);if(o==null)return{[Ce]:c};if(typeof o=="object")return{...o,[Ce]:c}}return o}return i}async _runLoop(e){const{loop:t,runner:r,debug:n,config:i}=e;let s;try{for(;await t.tick({inputKeys:this.inputChannels});){for(const{task:a}of await t._matchCachedWrites())t._outputWrites(a.id,a.writes,!0);n&&_L(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&Q0(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(a,o)=>{n&&vL(a,o,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status==="out_of_steps")throw new _$([`Recursion limit of ${i.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(a){if(s=a,!await t.finishAndHandleError(s))throw a}finally{s===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Xi=class sS extends Kn{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){const r=new sS(this.guard);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0){const r=this.value.length>0;return this.value=[],r}if(t.length!==1&&this.guard)throw new Fe("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new lt;return this.value[0]}checkpoint(){if(this.value.length===0)throw new lt;return this.value[0]}isAvailable(){return this.value.length!==0}},aS=class{path;ends;constructor(e){we.isRunnable(e.path)?this.path=e.path:this.path=ct(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return wt.registerWriter(new Zn({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(i){throw i.name===I0.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
242
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}}))}async _route(e,t,r,n){let i=await this.path.invoke(n?n(t):e,t);Array.isArray(i)||(i=[i]);let s;if(this.ends?s=i.map(o=>Ht(o)?o:this.ends[o]):s=i,s.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(s.filter(Ht).some(o=>o.node===me))throw new Fe("Cannot send a packet to the END node");return await r(s,t)??e}},zL=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}const r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(const[n,i,s]of r){for(const o of[rt,zr])if(n.includes(o))throw new Error(`"${o}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n===me)throw new Error(`Node \`${n}\` is reserved.`);const a=ct(i);this.nodes[n]={runnable:a,metadata:s?.metadata,subgraphs:Th(a)?[a]:s?.subgraphs,ends:s?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===me)throw new Error("END cannot be a start node");if(t===Re)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([r])=>r===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){const n=typeof e=="object"?e:{source:e,path:t,pathMap:r};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!we.isRunnable(n.path)){const s=Array.isArray(n.pathMap)?n.pathMap.join(","):Object.keys(n.pathMap??{}).join(",");n.path=ct(n.path).withConfig({runName:`Branch<${n.source}${s!==""?`,${s}`:""}>`.slice(0,63)})}const i=n.path.getName()==="RunnableLambda"?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][i])throw new Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[n.source]??={},this.branches[n.source][i]=new aS(n),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(Re,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,me)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);const i=new oS({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Re]:new Xi,[me]:new Xi},inputChannels:Re,outputChannels:me,streamChannels:[],streamMode:"values",name:n});for(const[s,a]of Object.entries(this.nodes))i.attachNode(s,a);for(const[s,a]of this.edges)i.attachEdge(s,a);for(const[s,a]of Object.entries(this.branches))for(const[o,c]of Object.entries(a))i.attachBranch(s,o,c);return i.validate()}validate(e){const t=new Set([...this.allEdges].map(([n,i])=>n));for(const[n]of Object.entries(this.branches))t.add(n);for(const n of t)if(n!==Re&&!(n in this.nodes))throw new Error(`Found edge starting at unknown node \`${n}\``);const r=new Set([...this.allEdges].map(([n,i])=>i));for(const[n,i]of Object.entries(this.branches))for(const s of Object.values(i))if(s.ends!=null)for(const a of Object.values(s.ends))r.add(a);else{r.add(me);for(const a of Object.keys(this.nodes))a!==n&&r.add(a)}for(const n of Object.values(this.nodes))for(const i of n.ends??[])r.add(i);for(const n of Object.keys(this.nodes))if(!r.has(n))throw new w$([`Node \`${n}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
243
- `),{lc_error_code:"UNREACHABLE_NODE"});for(const n of r)if(n!==me&&!(n in this.nodes))throw new Error(`Found edge ending at unknown node \`${n}\``);if(e){for(const n of e)if(!(n in this.nodes))throw new Error(`Interrupt node \`${n}\` is not present`)}this.compiled=!0}},oS=class extends BL{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Xi,this.nodes[e]=new Js({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new wt([{channel:e,value:Nn}],[Ye])),this.streamChannels.push(e)}attachEdge(e,t){if(t===me){if(e===Re)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new wt([{channel:me,value:Nn}],[Ye]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e===Re&&!this.nodes[Re]&&(this.nodes[Re]=FL.subscribeTo(Re,{tags:[Ye]})),this.nodes[e].pipe(r.run(i=>{const s=i.map(a=>Ht(a)?a:{channel:a===me?me:`branch:${e}:${t}:${a}`,value:Nn});return new wt(s,[Ye])}));const n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(const i of n)if(i!==me){const s=`branch:${e}:${t}:${i}`;this.channels[s]=new Xi,this.nodes[i].triggers.push(s),this.nodes[i].channels.push(s)}}async getGraphAsync(e){const t=e?.xray,r=new Fs,n={[Re]:r.addNode({schema:eo()},Re)},i={};let s={};t&&(s=Object.fromEntries((await tn(this.getSubgraphsAsync())).filter(c=>Ey(c[1]))));function a(c,l,u,d=!1){if(l===me&&i[me]===void 0&&(i[me]=r.addNode({schema:eo()},me)),n[c]!==void 0){if(i[l]===void 0)throw new Error(`End node ${l} not found!`);return r.addEdge(n[c],i[l],u!==l?u:void 0,d)}}for(const[c,l]of Object.entries(this.builder.nodes)){const u=ut(c),d=l.runnable,f=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){const h=typeof t=="number"?t-1:t,p=s[c]!==void 0?await s[c].getGraphAsync({...e,xray:h}):d.getGraph(e);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let y=function(_){return _?_.lc_runnable:!1},g=function(_,b){if(_!==void 0&&!li(_))return _;if(y(b))try{let A=b.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return b.getName()}else return b.name??"UnknownSchema"};const[m,w]=r.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);w!==void 0&&(n[u]={name:g(w.id,w.data),...w}),i[u]={name:g(m.id,m.data),...m}}else{const m=r.addNode(d,u,f);n[u]=m,i[u]=m}}else{const h=r.addNode(d,u,f);n[u]=h,i[u]=h}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)a(ut(c),ut(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[ut(d),ut(d)])),[me]:me};for(const d of Object.values(l)){let f;d.ends!==void 0?f=d.ends:f=u;for(const[h,p]of Object.entries(f))a(ut(c),ut(p),h,!0)}}for(const[c,l]of Object.entries(this.builder.nodes))if(l.ends!==void 0)for(const u of l.ends)a(ut(c),ut(u),void 0,!0);return r}getGraph(e){const t=e?.xray,r=new Fs,n={[Re]:r.addNode({schema:eo()},Re)},i={};let s={};t&&(s=Object.fromEntries(_s(this.getSubgraphs()).filter(c=>Ey(c[1]))));function a(c,l,u,d=!1){return l===me&&i[me]===void 0&&(i[me]=r.addNode({schema:eo()},me)),r.addEdge(n[c],i[l],u!==l?u:void 0,d)}for(const[c,l]of Object.entries(this.builder.nodes)){const u=ut(c),d=l.runnable,f=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){const h=typeof t=="number"?t-1:t,p=s[c]!==void 0?s[c].getGraph({...e,xray:h}):d.getGraph(e);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let y=function(_){return _?_.lc_runnable:!1},g=function(_,b){if(_!==void 0&&!li(_))return _;if(y(b))try{let A=b.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return b.getName()}else return b.name??"UnknownSchema"};const[m,w]=r.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);w!==void 0&&(n[u]={name:g(w.id,w.data),...w}),i[u]={name:g(m.id,m.data),...m}}else{const m=r.addNode(d,u,f);n[u]=m,i[u]=m}}else{const h=r.addNode(d,u,f);n[u]=h,i[u]=h}}const o=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of o)a(ut(c),ut(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[ut(d),ut(d)])),[me]:me};for(const d of Object.values(l)){let f;d.ends!==void 0?f=d.ends:f=u;for(const[h,p]of Object.entries(f))a(ut(c),ut(p),h,!0)}}return r}};function Ey(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function ut(e){return e==="subgraph"?`"${e}"`:e}const Pn=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r));var qL=class cS extends Kn{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){const r=new cS(this.names);return typeof t<"u"&&(r.seen=new Set(t)),r}update(t){let r=!1;for(const n of t)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),r=!0);else throw new Fe(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!Pn(this.names,this.seen))throw new lt}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&Pn(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&Pn(this.names,this.seen)}},HL=class lS extends Kn{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){const r=new lS(this.names);if(typeof t<"u"){const[n,i]=t;r.seen=new Set(n),r.finished=i}return r}update(t){let r=!1;for(const n of t)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),r=!0;else if(!this.names.has(n))throw new Fe(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!Pn(this.names,this.seen))throw new lt}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&Pn(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&Pn(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&Pn(this.names,this.seen)}};const GL="lg:";var VL=class{_map=new WeakMap;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){const r=this.get(e);this._map.set(e,t(r))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){const t={},r=Ls(e);for(const[n,i]of Object.entries(r)){const s=this.get(i);s?.reducer?t[n]=new jf(s.reducer.fn,s.default):t[n]=new wh}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;const r=Object.entries(t).filter(([,s])=>s===!0).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}:${a}`).join("|"),n=this._extensionCache.get(r)??new WeakMap;if(n.has(e))return n.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){const s=Object.entries(Ls(e)).map(([a,o])=>{const c=this.get(o);let l=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){const u=Hi(l)??Hi(o),d=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`${GL}${d}`)}return[a,l]});i=Dv(e,Object.fromEntries(s)),Qe(i)&&(i._def.unknownKeys="strip")}return t.asPartial&&(i=Nd(i)),n.set(e,i),this._extensionCache.set(r,n),i}};const Ys=new VL;function Qi(e,t){if(t.reducer&&!t.default){const r=yc(e);r!=null&&(t.default=r)}if(t.reducer){const r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return Ys.extend(r,()=>t),r}else return Ys.extend(e,()=>t),e}const Lr="__root__",Wf=Symbol.for("langgraph.state.partial");var WL=class extends zL{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Ys;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){if(super(),ej(e)){const n=this._metaRegistry.getChannelsForSchema(e.state),i=e.input!=null?this._metaRegistry.getChannelsForSchema(e.input):n,s=e.output!=null?this._metaRegistry.getChannelsForSchema(e.output):n;this._schemaDefinition=n,this._schemaRuntimeDefinition=e.state,this._inputDefinition=i,this._inputRuntimeDefinition=e.input??Wf,this._outputDefinition=s,this._outputRuntimeDefinition=e.output??e.state}else if(Ot(e)){const n=this._metaRegistry.getChannelsForSchema(e);this._schemaDefinition=n,this._schemaRuntimeDefinition=e,this._inputDefinition=n,this._inputRuntimeDefinition=Wf,this._outputDefinition=n,this._outputRuntimeDefinition=e}else if(QL(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(XL(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(ZL(e)||Ty(e)){const n=Ty(e)?e.spec:e;this._schemaDefinition=n}else if(YL(e)){const n=JL(e.channels);this._schemaDefinition=n}else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.");this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition);function r(n){return typeof n=="object"&&n!=null&&!("spec"in n)&&!Ot(n)}r(t)?(Ot(t.context)&&(this._configRuntimeSchema=t.context),this._interrupt=t.interrupt,this._writer=t.writer):Ot(t)&&(this._configRuntimeSchema=t)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,r]of Object.entries(e)){let n;if(typeof r=="function"?n=r():n=r,this.channels[t]!==void 0){if(this.channels[t]!==n&&n.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=n}}}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}const r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([n,i])=>[n,i]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(const[n,i,s]of r){if(n in this.channels)throw new Error(`${n} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[rt,zr])if(n.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n===me||n===Re)throw new Error(`Node \`${n}\` is reserved.`);let a=this._schemaDefinition;s?.input!==void 0&&(Ot(s.input)?a=this._metaRegistry.getChannelsForSchema(s.input):s.input.spec!==void 0&&(a=s.input.spec)),a!==void 0&&this._addSchema(a);let o;we.isRunnable(i)?o=i:typeof i=="function"?o=new Zn({func:i,name:n,trace:!1}):o=ct(i);let c=s?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);const l={runnable:o,retryPolicy:s?.retryPolicy,cachePolicy:c,metadata:s?.metadata,input:a??this._schemaDefinition,subgraphs:Th(o)?[o]:s?.subgraphs,ends:s?.ends,defer:s?.defer};this.nodes[n]=l}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const r of e){if(r===me)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(n=>n===r))throw new Error(`Need to add a node named "${r}" first`)}if(t===me)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){const t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(const[n,i,s]of t){if(n in this.nodes)throw new Error(`Node names must be unique: node with the name "${n}" already exists.`);const a=n;this.addNode(a,i,s),r!=null&&this.addEdge(r,a),r=a}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:i,name:s,description:a}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(i)?i:[]]);const o=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=o.length===1&&o[0]===Lr?Lr:o,l=Object.keys(this.channels),u=l.length===1&&l[0]===Lr?Lr:l,d=this._interrupt,f=new KL({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Re]:new Xi},inputChannels:Re,outputChannels:c,streamChannels:u,streamMode:"updates",store:t,cache:r,name:s,description:a,userInterrupt:d});f.attachNode(Re);for(const[h,p]of Object.entries(this.nodes))f.attachNode(h,p);f.attachBranch(Re,hy,Cy(),{withReader:!1});for(const[h]of Object.entries(this.nodes))f.attachBranch(h,hy,Cy(),{withReader:!1});for(const[h,p]of this.edges)f.attachEdge(h,p);for(const[h,p]of this.waitingEdges)f.attachEdge(h,p);for(const[h,p]of Object.entries(this.branches))for(const[m,w]of Object.entries(p))f.attachBranch(h,m,w);return f.validate()}};function JL(e){const t={};for(const[r,n]of Object.entries(e))t[r]=Ff(n);return t}var KL=class extends oS{description;_metaRegistry=Ys;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e===Re?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([o])=>o):r=Object.keys(this.builder.channels);function n(o){if(at(o))return o.graph===Xe.PARENT?null:o._updateAsTuples();if(Array.isArray(o)&&o.length>0&&o.some(c=>at(c))){const c=[];for(const l of o)if(at(l)){if(l.graph===Xe.PARENT)continue;c.push(...l._updateAsTuples())}else c.push([Lr,l]);return c}else if(o!=null)return[[Lr,o]];return null}const i=e;function s(o){if(o){if(at(o))return o.graph===Xe.PARENT?null:o._updateAsTuples().filter(([c])=>r.includes(c));if(Array.isArray(o)&&o.length>0&&o.some(at)){const c=[];for(const l of o)if(at(l)){if(l.graph===Xe.PARENT)continue;c.push(...l._updateAsTuples().filter(([u])=>r.includes(u)))}else{const u=s(l);u&&c.push(...u??[])}return c}else{if(typeof o=="object"&&!Array.isArray(o))return Object.entries(o).filter(([c])=>r.includes(c));{const c=Array.isArray(o)?"array":typeof o;throw new Fe(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const a=[{value:Nn,mapper:new Zn({func:r.length&&r[0]===Lr?n:s,trace:!1,recurse:!1})}];if(e===Re)this.nodes[e]=new Js({tags:[Ye],triggers:[Re],channels:[Re],writers:[new wt(a,[Ye])]});else{const o=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(o)).map(d=>[d,d])),l=Object.keys(c).length===1&&Lr in c,u=`branch:to:${e}`;this.channels[u]=t?.defer?new b$:new Xi(!1),this.nodes[e]=new Js({triggers:[u],channels:l?Object.keys(c):c,writers:[new wt(a,[Ye])],mapper:l?void 0:d=>Object.fromEntries(Object.entries(d).filter(([f])=>f in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==me){if(typeof e=="string")this.nodes[e].writers.push(new wt([{channel:`branch:to:${t}`,value:null}],[Ye]));else if(Array.isArray(e)){const r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new HL(new Set(e)):new qL(new Set(e)),this.nodes[t].triggers.push(r);for(const n of e)this.nodes[n].writers.push(new wt([{channel:r,value:n}],[Ye]))}}}attachBranch(e,t,r,n={withReader:!0}){const i=async(s,a)=>{const o=s.filter(l=>l!==me);if(!o.length)return;const c=o.map(l=>Ht(l)?l:{channel:l===me?l:`branch:to:${l}`,value:e});await wt.doWrite({...a,tags:(a.tags??[]).concat([Ye])},c)};this.nodes[e].writers.push(r.run(i,n.withReader?s=>eL.doRead(s,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;const t=(()=>{const r=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition,i=s=>{if(s!=null)return this._metaRegistry.getExtendedChannelSchemas(s,{withReducerSchema:!0})};if(Ot(r))return i(r);if(r===Wf)return Nd(i(n))})();if(at(e)){const r=e;return e.update&&t!=null&&(r.update=an(t,e.update)),r}return t!=null?an(t,e):e}isInterrupted(e){return D0(e)}async _validateContext(e){const t=this.builder._configRuntimeSchema;return Ot(t)&&an(t,e),e}};function ZL(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||R0(t))}function Ty(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}function YL(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function XL(e){return typeof e=="object"&&e!==null&&e.stateSchema!==void 0}function QL(e){return typeof e=="object"&&e!==null&&e.stateSchema===void 0&&e.input!==void 0&&e.output!==void 0}function ej(e){return!(typeof e!="object"||e==null||!("state"in e)||!Ot(e.state)||"input"in e&&!Ot(e.input)||"output"in e&&!Ot(e.output))}function tj(e){if(Ht(e))return[e];const t=[];at(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(at));const r=[];for(const n of t){if(n.graph===Xe.PARENT)throw new M0(n);Ht(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function Cy(){const e=new Zn({func:tj,tags:[Ye],trace:!1,recurse:!1,name:"<control_branch>"});return new aS({path:e})}const uS="__remove_all__";function fS(e,t){const r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],i=r.map(Er),s=n.map(Er);for(const u of i)(u.id===null||u.id===void 0)&&(u.id=et(),u.lc_kwargs.id=u.id);let a;for(let u=0;u<s.length;u+=1){const d=s[u];(d.id===null||d.id===void 0)&&(d.id=et(),d.lc_kwargs.id=d.id),d.getType()==="remove"&&d.id===uS&&(a=u)}if(a!=null)return s.slice(a+1);const o=[...i],c=new Map(o.map((u,d)=>[u.id,d])),l=new Set;for(const u of s){const d=c.get(u.id);if(d!==void 0)u.getType()==="remove"?l.add(u.id):(l.delete(u.id),o[d]=u);else{if(u.getType()==="remove")throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,o.length),o.push(u)}}return o.filter(u=>!l.has(u.id))}Df.Root({messages:Df({reducer:fS,default:()=>[]})});const nc={reducer:{fn:fS},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};Pe({messages:Qi(wr(),nc)});y$();const Jf=Symbol.for("langgraph-zod");Jf in globalThis||(globalThis[Jf]=new WeakSet);function Ay(e){const t=globalThis[Jf];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){const r=this;return{metadata(n){return Qi(r,{jsonSchemaExtra:n})},reducer(n,i){const s=yc(r);return Qi(r,{default:s,reducer:{schema:i,fn:n}})}}}}),t.add(e))}try{Ay(kh.prototype),Ay(kh.prototype)}catch(e){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}var rj=class extends BE{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){const r=t[0];if(r&&!r?.default){const n=yc(e);n!=null&&(r.default=n)}return super.add(e,...t)}};new rj(Ys);function nj(e=!0,t,r=[]){const n={messages:Qi(wr(),nc),jumpTo:jr([Vu("model_request"),Vu("tools"),HS()]).optional()},i=s=>{const{shape:a}=s;for(const[o,c]of Object.entries(a))o.startsWith("_")||o in n||(n[o]=c)};t&&"shape"in t&&i(t);for(const s of r)s.stateSchema&&i(s.stateSchema);return e&&(n.structuredResponse=Ut().optional()),Pe(n)}Pe({llmInputMessages:Qi(wr(),{reducer:{fn:(e,t)=>nc.reducer.fn([],t)},default:()=>[]}),messages:Qi(wr(),nc)});const Oy="prompt",Bu=/<name>(.*?)<\/name>/s,zu=/<content>(.*?)<\/content>/s;function ij(e){if(!fe.isInstance(e)||qt.isInstance(e)||!e.name)return e;const{name:t}=e;if(typeof e.content=="string")return new fe({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});const r=[];let n=0;for(const i of e.content)typeof i=="string"?(n+=1,r.push(`<name>${t}</name><content>${i}</content>`)):typeof i=="object"&&"type"in i&&i.type==="text"?(n+=1,r.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):r.push(i);return n||r.unshift({type:"text",text:`<name>${t}</name><content></content>`}),new fe({...e.lc_kwargs,content:r,name:void 0})}function sj(e){if(!fe.isInstance(e)||!e.content)return e;let t=[],r;if(Array.isArray(e.content))t=e.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){const i=n.text.match(Bu),s=n.text.match(zu);return i&&(!s||s[1]==="")?(r=i[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){const i=n.text.match(Bu),s=n.text.match(zu);return!i||!s?n:(r=i[1],{...n,text:s[1]})}return n});else{const n=e.content,i=n.match(Bu),s=n.match(zu);if(!i||!s)return e;r=i[1],t=s[1]}return new fe({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:r})}function Je(e){return we.isRunnable(e)}function xy(e){return th(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}const qu=(e,t,r={})=>{if(xy(e))return e.bindTools(t,r);if(ft.isRunnableBinding(e)&&xy(e.bound)){const n=e.bound.bindTools(t,r);return ft.isRunnableBinding(n)?new ft({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new ft({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function dS(e){if(typeof e=="function")return;let t=e;if(er.isRunnableSequence(t)&&(t=t.steps.find(r=>ft.isRunnableBinding(r))||t),!Vo(t)){if(ft.isRunnableBinding(t)){const r=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,n=t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(r||n)throw new Sf}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new Sf}}function hS(e){return!!(fe.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function aj(e){let t;if(e==null)t=Mt.from(r=>r.messages).withConfig({runName:Oy});else if(typeof e=="string"){const r=new He(e);t=Mt.from(n=>[r,...n.messages??[]]).withConfig({runName:Oy})}else throw new Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}async function oj(e,t,r={}){const n=qu(e,t,r);if(n)return n;if(Vo(e)){const i=qu(await e._model(),t,r);if(i)return i}if(er.isRunnableSequence(e)){const i=e.steps.findIndex(s=>ft.isRunnableBinding(s)||th(s)||Vo(s));if(i>=0){const s=qu(e.steps[i],t,r);if(s){const a=e.steps.slice();return a.splice(i,1,s),er.from(a)}}}throw new Error(`llm ${e} must define bindTools method.`)}function cj(e){if(e.length===0)return;if(e.length===1)return e[0];function t(n,i){return async(s,a)=>n(s,async c=>i(c,async l=>a(l)))}let r=e[e.length-1];for(let n=e.length-2;n>=0;n--)r=t(e[n],r);return r}function lj(e){const t=e.filter(r=>r.wrapToolCall);if(t.length!==0)return cj(t.map(r=>{const n=r.wrapToolCall;return async(s,a)=>{try{const o=await n(s,a);if(!Ae.isInstance(o)&&!at(o))throw new Error(`Invalid response from "wrapToolCall" in middleware "${r.name}": expected ToolMessage or Command, got ${typeof o}`);return o}catch(o){throw o instanceof Error&&!o.message.includes(`middleware "${r.name}"`)&&(o.message=`Error in middleware "${r.name}": ${o.message}`),o}}}))}async function uj(e,t){const r={};for(const n of e)if(n.stateSchema){const i=Fv(n.stateSchema,o=>o.startsWith("_")),s=await Id(i,t);if(s.success){Object.assign(r,s.data);continue}const a=s.error.issues.filter(o=>o.code==="invalid_type"&&o.message==="Required").map(o=>` - ${o.path.join(".")}: ${o.message}`).join(`
244
- `);throw new Error(`Middleware "${n.name}" has required state fields that must be initialized:
245
- ${a}
246
-
247
- To fix this, either:
248
- 1. Provide default values in your middleware's state schema using .default():
249
- stateSchema: z.object({
250
- myField: z.string().default("default value")
251
- })
252
-
253
- 2. Or make the fields optional using .optional():
254
- stateSchema: z.object({
255
- myField: z.string().optional()
256
- })
257
-
258
- 3. Or ensure you pass these values when invoking the agent:
259
- agent.invoke({
260
- messages: [...],
261
- ${s.error.issues[0]?.path.join(".")}: "value"
262
- })`)}return r}function fj(e){const t={messages:wr(()=>[]),structuredResponse:Ut().optional()};if(!e)return Pe(t);const{shape:r}=e,n={...t};for(const[i,s]of Object.entries(r))i.startsWith("_")?n[i]=s.optional():n[i]=s;return Pe(n)}function gr(e){if(e){if(["model_request","tools",me].includes(e))return e;if(e==="model")return"model_request";if(e==="tools")return"tools";if(e==="end")return me;throw new Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function pS(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}var Oh=class extends we{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.recurse=e.recurse??this.recurse}getState(){return this.#e}setState(e){this.#e={...this.#e,...e}}async invoke(e,t){const r=Bt(this.config,t),n=await Ve.runWithConfig(r,async()=>this.func(e,r));return we.isRunnable(n)&&this.recurse?await Ve.runWithConfig(r,async()=>n.invoke(e,r)):(this.#e=n,n)}};function dj(e,t){let r,n;if(t==="inline")r=ij,n=sj;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(s){return s.map(r)}return er.from([Mt.from(i),e,Mt.from(n)])}var Py=class extends Oh{#e;#r={runModelCallCount:0};constructor(e){super({name:e.name??"model",func:(t,r)=>this.#i(t,r)}),this.#e=e}#t(e){if(!this.#e.responseFormat)return;const t=ib(this.#e.responseFormat,void 0,e);return t.every(n=>n instanceof On)?{type:"native",strategy:t[0]}:{type:"tool",tools:t.filter(n=>n instanceof Qr).reduce((n,i)=>(n[i.name]=i,n),{})}}async#i(e,t){const r=e.messages.at(-1);if(r&&Ae.isInstance(r)&&r.name&&this.#e.shouldReturnDirect.has(r.name))return{messages:[],_privateState:this.getState()._privateState};const n=this.getState()._privateState,i=await this.#c(e,t);this.#r.runModelCallCount++;const s={...n,threadLevelCallCount:n.threadLevelCallCount+1};return"structuredResponse"in i?{messages:[...e.messages,...i.messages||[]],structuredResponse:i.structuredResponse,_privateState:s}:i instanceof Xe?i:(i.name=this.name,i.lc_kwargs.name=this.name,this.#u(e,i)?{messages:[new fe({content:"Sorry, need more steps to process this request.",name:this.name,id:i.id})],_privateState:s}:{messages:[i],_privateState:s})}#o(){if(typeof this.#e.model=="string")return la(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#c(e,t,r={}){const n=await this.#o(),i=t,s=async l=>{dS(l.model);const u=this.#t(l.model),d=await this.#f(l.model,l,u);let f=this.#a(e);f={...f,messages:l.messages};const h=pS(this.#e.signal,t.signal),p={...t,signal:h},m=await d.invoke(f,p);if(u?.type==="native"){const _=u.strategy.parse(m);return _?{structuredResponse:_,messages:[m]}:m}if(!u||!m.tool_calls)return m;const w=m.tool_calls.filter(_=>_.name in u.tools);if(w.length===0)return m;if(w.length>1)return this.#l(m,w,u);const g=u.tools[w[0].name]?.options?.toolMessageContent;return this.#n(m,w[0],u,g??r.lastMessage)},a=this.#e.wrapModelCallHookMiddleware??[];let o=s;for(let l=a.length-1;l>=0;l--){const[u,d]=a[l];if(u.wrapModelCall){const f=o,h=u,p=d;o=async m=>{const w=h.contextSchema?an(h.contextSchema,i?.context||{}):i?.context,y=this.getState()._privateState,g=Object.freeze({...y,context:w,writer:i.writer,interrupt:i.interrupt,signal:i.signal}),_={...m,state:{...p(),messages:e.messages},runtime:g},b=async A=>{const P=A.tools??[],x=P.filter(R=>Je(R)&&!this.#e.toolClasses.some(M=>M.name===R.name));if(x.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${h.name}": ${x.map(R=>R.name).join(", ")}. This is not supported.`);const T=P.filter(R=>Je(R)&&this.#e.toolClasses.every(M=>M!==R));if(T.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${h.name}": ${T.map(R=>R.name).join(", ")}. This is not supported.`);return f(A)};if(!h.wrapModelCall)return b(_);try{const A=await h.wrapModelCall(_,b);if(!fe.isInstance(A))throw new Error(`Invalid response from "wrapModelCall" in middleware "${h.name}": expected AIMessage, got ${typeof A}`);return A}catch(A){throw A instanceof Error&&!A.message.includes(`middleware "${h.name}"`)&&(A.message=`Error in middleware "${h.name}": ${A.message}`),A}}}}const c={model:n,systemPrompt:this.#e.systemPrompt,messages:e.messages,tools:this.#e.toolClasses,state:{messages:e.messages},runtime:Object.freeze({...this.getState()._privateState,context:i?.context,writer:i.writer,interrupt:i.interrupt,signal:i.signal})};return o(c)}#l(e,t,r){const n=new Ef(t.map(i=>i.name));return this.#s(n,e,t[0],r)}#n(e,t,r,n){const i=r.tools[t.name];try{const s=i.parse(t.args);return{structuredResponse:s,messages:[e,new fe(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#s(s,e,t,r)}}async#s(e,t,r,n){const i=Object.values(n.tools).at(0)?.options?.handleError,s=r.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(typeof i=="boolean"&&i||Array.isArray(i)&&i.some(a=>a instanceof Ef))return new Xe({update:{messages:[t,new Ae({content:e.message,tool_call_id:s})]},goto:"model"});if(typeof i=="string")return new Xe({update:{messages:[t,new Ae({content:i,tool_call_id:s})]},goto:"model"});if(typeof i=="function"){const a=await i(e);if(typeof a!="string")throw new Error("Error handler must return a string.");return new Xe({update:{messages:[t,new Ae({content:a,tool_call_id:s})]},goto:"model"})}throw e}#u(e,t){const r=fe.isInstance(t)&&t.tool_calls?.every(i=>this.#e.shouldReturnDirect.has(i.name)),n="remainingSteps"in e?e.remainingSteps:void 0;return!!(n&&(n<1&&r||n<2&&hS(e.messages.at(-1))))}#a(e){const{messages:t,llmInputMessages:r,...n}=e;return r&&r.length>0?{messages:r,...n}:{messages:t,...n}}async#f(e,t,r){const n={},i=Object.values(r&&"tools"in r?r.tools:{}),s=[...t?.tools??this.#e.toolClasses,...i.map(l=>l.tool)],a=t?.toolChoice||(i.length>0?"any":void 0);if(r?.type==="native"){if(!rh(e))throw new Error("Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.");const l={name:r.strategy.schema?.name??"extract",description:Hi(r.strategy.schema),schema:r.strategy.schema,strict:!0};Object.assign(n,{response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:r.strategy.schema},strict:!0})}const o=await oj(e,s,{...n,...t?.modelSettings??{},tool_choice:a});return aj(t?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?dj(o,this.#e.includeAgentName):o)}static get nodeOptions(){return{input:Pe({messages:yn(wr()),_privateState:Pe({threadLevelCallCount:Xt()})})}}getState(){const e=super.getState(),t=e&&!(e instanceof Xe)?e:{_privateState:{threadLevelCallCount:0,runModelCallCount:0}};return{messages:[],...t,_privateState:{threadLevelCallCount:0,...t._privateState??{},...this.#r}}}};const mS=e=>Array.isArray(e)&&e.every(bt.isInstance),hj=e=>typeof e=="object"&&e!=null&&"messages"in e&&mS(e.messages),pj=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function mj(e,t){return e instanceof eh?new Ae({content:e.message,tool_call_id:t.id,name:t.name}):new Ae({content:`${e}
263
- Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var gj=class extends Oh{tools;trace=!1;signal;handleToolErrors=mj;wrapToolCall;getPrivateState;constructor(e,t){const{name:r,tags:n,handleToolErrors:i,wrapToolCall:s,getPrivateState:a}=t??{};super({name:r,tags:n,func:(o,c)=>this.run(o,c)}),this.options=t,this.tools=e,this.handleToolErrors=i??this.handleToolErrors,this.wrapToolCall=s,this.getPrivateState=a,this.signal=t?.signal}#e(e,t,r){if(xn(e)||this.signal?.aborted||r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw e;if(typeof this.handleToolErrors=="function"){const n=this.handleToolErrors(e,t);if(n&&Ae.isInstance(n))return n;throw e}else if(this.handleToolErrors)return new Ae({name:t.name,content:`${e}
264
- Please fix your mistakes.`,tool_call_id:t.id});throw e}async runTool(e,t,r){const n=async l=>{const{toolCall:u}=l,d=this.tools.find(f=>f.name===u.name);if(d===void 0)throw new Error(`Tool "${u.name}" not found.`);try{const f=await d.invoke({...u,type:"tool_call"},{...t,signal:pS(this.signal,t.signal)});return Ae.isInstance(f)||at(f)?f:new Ae({name:d.name,content:typeof f=="string"?f:JSON.stringify(f),tool_call_id:u.id})}catch(f){throw f instanceof Rs?new eh(f,u):f}},i=t,s=this.getPrivateState?.()||{threadLevelCallCount:0,runModelCallCount:0},a={context:i?.context,writer:i?.writer,interrupt:i?.interrupt,signal:i?.signal,threadLevelCallCount:s.threadLevelCallCount,runModelCallCount:s.runModelCallCount},o=this.tools.find(l=>l.name===e.name);if(!o)throw new Error(`Tool "${e.name}" not found.`);const c={toolCall:e,tool:o,state:r||{},runtime:a};if(this.wrapToolCall&&r)try{return await this.wrapToolCall(c,n)}catch(l){return this.#e(l,e,!0)}try{return await n(c)}catch(l){return this.#e(l,e,!1)}}async run(e,t){let r;if(pj(e))r=[await this.runTool(e.lg_tool_call,t,e)];else{let s;if(mS(e))s=e;else if(hj(e))s=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const a=new Set(s.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id));let o;for(let c=s.length-1;c>=0;c-=1){const l=s[c];if(fe.isInstance(l)){o=l;break}}if(!fe.isInstance(o))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(o.tool_calls?.filter(c=>c.id==null||!a.has(c.id)).map(c=>this.runTool(c,t,e))??[])}if(!r.some(at))return Array.isArray(e)?r:{messages:r};const n=[];let i=null;for(const s of r)at(s)?s.graph===Xe.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>yj(a))?i?i.goto.push(...s.goto):i=new Xe({graph:Xe.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(e)?[s]:{messages:[s]});return i&&n.push(i),n}};function yj(e){return e instanceof _t}var _j=class{},vj=class{},Ic=class extends Oh{#e;constructor(e,t){super(e),this.#e=t}async invokeMiddleware(e,t){let r={};if(this.middleware.contextSchema){const c=this.middleware.contextSchema?.shape;if(c){const l={},u=t?.context||{};for(const d of Object.keys(c))d in u&&(l[d]=u[d]);r=an(this.middleware.contextSchema,l)}}const n={context:r,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal,...this.#e.getPrivateState()},i=await this.runHook(e,Object.freeze(Object.assign(new vj,{...n,context:Object.freeze(Object.assign(new _j,r))})));if(delete i?._privateState,!i)return{...e,jumpTo:void 0};let s,a;if(this.name?.startsWith("BeforeAgentNode_")?(s=rn(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(s=rn(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(s=rn(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(s=rn(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof i.jumpTo=="string"&&!s?.includes(i.jumpTo)){const c=s&&s.length>0?`must be one of: ${s?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${i.jumpTo}, ${c}.`)}const o=gr(i.jumpTo);if(typeof i=="object"&&"type"in i){if(i.type==="terminate"){if(i.error)throw i.error;return{...e,...i.result||{},jumpTo:o}}throw new Error(`Invalid control action: ${JSON.stringify(i)}`)}return{...e,...i,jumpTo:o}}get nodeOptions(){return{input:fj(this.middleware.stateSchema)}}},wj=class extends Ic{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(e,t){super({name:`BeforeAgentNode_${e.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},t),this.middleware=e}runHook(e,t){return Oc(this.middleware.beforeAgent)(e,t)}},bj=class extends Ic{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(e,t){super({name:`BeforeModelNode_${e.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},t),this.middleware=e}runHook(e,t){return Oc(this.middleware.beforeModel)(e,t)}},Sj=class extends Ic{lc_namespace=["langchain","agents","afterModelNodes"];constructor(e,t){super({name:`AfterModelNode_${e.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},t),this.middleware=e}runHook(e,t){return Oc(this.middleware.afterModel)(e,t)}},Ej=class extends Ic{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(e,t){super({name:`AfterAgentNode_${e.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},t),this.middleware=e}runHook(e,t){return Oc(this.middleware.afterAgent)(e,t)}},Tj=class{#e;#r="v2";#t;constructor(e){if(this.options=e,this.#r=e.version??this.#r,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&dS(e.model);const t=this.options.middleware?.filter(_=>_.tools).flatMap(_=>_.tools)??[],r=[...e.tools??[],...t],n=new Set(r.filter(Je).filter(_=>"returnDirect"in _&&_.returnDirect).map(_=>_.name)),i=nj(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),a=new WL(i,this.options.contextSchema),o=[],c=[],l=[],u=[],d=[];this.#t=new Py({model:this.options.model,systemPrompt:this.options.systemPrompt,includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:r,shouldReturnDirect:n,signal:this.options.signal,wrapModelCallHookMiddleware:d});const f=new Set,h=this.options.middleware??[];for(let _=0;_<h.length;_++){let b,A,P,x;const T=h[_];if(f.has(T.name))throw new Error(`Middleware ${T.name} is defined multiple times`);if(f.add(T.name),T.beforeAgent){b=new wj(T,{getPrivateState:()=>this.#t.getState()._privateState});const R=`${T.name}.before_agent`;o.push({index:_,name:R,allowed:rn(T.beforeAgent)}),a.addNode(R,b,b.nodeOptions)}if(T.beforeModel){A=new bj(T,{getPrivateState:()=>this.#t.getState()._privateState});const R=`${T.name}.before_model`;c.push({index:_,name:R,allowed:rn(T.beforeModel)}),a.addNode(R,A,A.nodeOptions)}if(T.afterModel){P=new Sj(T,{getPrivateState:()=>this.#t.getState()._privateState});const R=`${T.name}.after_model`;l.push({index:_,name:R,allowed:rn(T.afterModel)}),a.addNode(R,P,P.nodeOptions)}if(T.afterAgent){x=new Ej(T,{getPrivateState:()=>this.#t.getState()._privateState});const R=`${T.name}.after_agent`;u.push({index:_,name:R,allowed:rn(T.afterAgent)}),a.addNode(R,x,x.nodeOptions)}T.wrapModelCall&&d.push([T,()=>({...b?.getState(),...A?.getState(),...P?.getState(),...x?.getState()})])}a.addNode("model_request",this.#t,Py.nodeOptions);const p=lj(h);if(r.filter(Je).length>0){const _=new gj(r.filter(Je),{signal:this.options.signal,wrapToolCall:p,getPrivateState:()=>this.#t.getState()._privateState});a.addNode("tools",_)}let m;o.length>0?m=o[0].name:c.length>0?m=c[0].name:m="model_request";const w=c.length>0?c[0].name:"model_request",y=u.length>0?u[u.length-1].name:me;a.addEdge(Re,m);for(let _=0;_<o.length;_++){const b=o[_],A=b.name,x=_===o.length-1?w:o[_+1].name;if(b.allowed&&b.allowed.length>0){const T=r.filter(Je).length>0,R=b.allowed.map(U=>gr(U)).filter(U=>U!=="tools"||T),M=Array.from(new Set([x,...R.map(U=>U===me?y:U)]));a.addConditionalEdges(A,this.#s(r.filter(Je),x,y),M)}else a.addEdge(A,x)}for(let _=0;_<c.length;_++){const b=c[_],A=b.name,x=_===c.length-1?"model_request":c[_+1].name;if(b.allowed&&b.allowed.length>0){const T=r.filter(Je).length>0,R=b.allowed.map(U=>gr(U)).filter(U=>U!=="tools"||T),M=Array.from(new Set([x,...R]));a.addConditionalEdges(A,this.#u(r.filter(Je),x),M)}else a.addEdge(A,x)}const g=l.at(-1);if(l.length>0&&g)a.addEdge("model_request",g.name);else{const b=this.#i(r.filter(Je)).map(A=>A===me?y:A);b.length===1?a.addEdge("model_request",b[0]):a.addConditionalEdges("model_request",this.#c(y),b)}for(let _=l.length-1;_>0;_--){const b=l[_],A=b.name,P=l[_-1].name;if(b.allowed&&b.allowed.length>0){const x=r.filter(Je).length>0,T=b.allowed.map(M=>gr(M)).filter(M=>M!=="tools"||x),R=Array.from(new Set([P,...T]));a.addConditionalEdges(A,this.#n(r.filter(Je),b.allowed,P),R)}else a.addEdge(A,P)}if(l.length>0){const _=l[0],b=_.name,A=this.#i(r.filter(Je),!0).filter(T=>T!=="tools"||r.filter(Je).length>0),P=!!(_.allowed&&_.allowed.length>0),x=A.map(T=>T===me?y:T);a.addConditionalEdges(b,this.#l(r.filter(Je),P,y),x)}for(let _=u.length-1;_>0;_--){const b=u[_],A=b.name,P=u[_-1].name;if(b.allowed&&b.allowed.length>0){const x=r.filter(Je).length>0,T=b.allowed.map(M=>gr(M)).filter(M=>M!=="tools"||x),R=Array.from(new Set([P,...T]));a.addConditionalEdges(A,this.#n(r.filter(Je),b.allowed,P),R)}else a.addEdge(A,P)}if(u.length>0){const _=u[0],b=_.name;if(_.allowed&&_.allowed.length>0){const A=r.filter(Je).length>0,P=_.allowed.map(T=>gr(T)).filter(T=>T!=="tools"||A),x=Array.from(new Set([me,...P]));a.addConditionalEdges(b,this.#n(r.filter(Je),_.allowed,me),x)}else a.addEdge(b,me)}if(r.filter(Je).length>0){const _=w;n.size>0?a.addConditionalEdges("tools",this.#o(n,y),[_,y]):a.addEdge("tools",_)}this.#e=a.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#i(e,t=!1){const r=[];return e.length>0&&r.push("tools"),t&&r.push("model_request"),r.push(me),r}#o(e,t){return r=>{const n=r.messages,i=n[n.length-1];return Ae.isInstance(i)&&i.name&&e.has(i.name)?this.options.responseFormat?"model_request":t:"model_request"}}#c(e=me){return t=>{const n=t.messages.at(-1);if(!fe.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(a=>a.name.startsWith("extract-")))return e;if(this.#r==="v1")return"tools";const s=n.tool_calls.filter(a=>!a.name.startsWith("extract-"));return s.length===0?e:s.map(a=>new _t("tools",{...t,lg_tool_call:a}))}}#l(e,t,r){const n=!!this.options.responseFormat;return i=>{const s=i.messages,a=s.at(-1);if(fe.isInstance(a)&&(!a.tool_calls||a.tool_calls.length===0))return r;if(t&&i.jumpTo)return i.jumpTo===me?r:i.jumpTo==="tools"?e.length===0?r:new _t("tools",{...i,jumpTo:void 0}):new _t("model_request",{...i,jumpTo:void 0});const o=s.filter(Ae.isInstance),c=s.filter(fe.isInstance).at(-1),l=c?.tool_calls?.filter(h=>!o.some(p=>p.tool_call_id===h.id));if(l&&l.length>0)return l.map(h=>new _t("tools",{...i,lg_tool_call:h}));const u=c?.tool_calls?.some(h=>h.name.startsWith("extract-"));if(l&&l.length===0&&!u&&n)return"model_request";if(!fe.isInstance(a)||!a.tool_calls||a.tool_calls.length===0)return r;const d=a.tool_calls.every(h=>h.name.startsWith("extract-")),f=a.tool_calls.some(h=>!h.name.startsWith("extract-"));return d||!f?r:"tools"}}#n(e,t,r){const n=new Set(t.map(i=>gr(i)));return i=>{if(i.jumpTo){const s=gr(i.jumpTo);if(s===me&&n.has(me))return me;if(s==="tools"&&n.has("tools"))return e.length===0?me:new _t("tools",{...i,jumpTo:void 0});if(s==="model_request"&&n.has("model_request"))return new _t("model_request",{...i,jumpTo:void 0})}return r}}#s(e,t,r){return n=>{if(!n.jumpTo)return t;const i=gr(n.jumpTo);return i===me?r:i==="tools"?e.length===0?r:new _t("tools",{...n,jumpTo:void 0}):new _t("model_request",{...n,jumpTo:void 0})}}#u(e,t){return r=>{if(!r.jumpTo)return t;const n=gr(r.jumpTo);return n===me?me:n==="tools"?e.length===0?me:new _t("tools",{...r,jumpTo:void 0}):new _t("model_request",{...r,jumpTo:void 0})}}async#a(e){if(!this.options.middleware||this.options.middleware.length===0||e instanceof Xe||!e)return e;const t=await uj(this.options.middleware,e),r={...e};if(!r)return r;for(const[n,i]of Object.entries(t))n in r||(r[n]=i);return r}async#f(e){if(!e?.configurable?.thread_id)return;const t=await this.#e.getState(e);t.values._privateState&&this.#t.setState({structuredResponse:void 0,_privateState:t.values._privateState})}async invoke(e,t){const r=await this.#a(e);return await this.#f(t),this.#e.invoke(r,t)}async stream(e,t){const r=await this.#a(e);return this.#e.stream(r,t)}async drawMermaidPng(e){const n=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(n)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,t,r){return this.#e.streamEvents(e,{...t,version:t?.version??"v2"},r)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,t){return this.#e.getState(e,t)}getStateHistory(e,t){return this.#e.getStateHistory(e,t)}getSubgraphs(e,t){return this.#e.getSubgraphs(e,t)}getSubgraphAsync(e,t){return this.#e.getSubgraphsAsync(e,t)}updateState(e,t,r){return this.#e.updateState(e,t,r)}};function gS(e){return new Tj(e)}const yS=`<role>
265
- Context Extraction Assistant
266
- </role>
267
-
268
- <primary_objective>
269
- Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
270
- </primary_objective>
271
-
272
- <objective_information>
273
- You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
274
- This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
275
- </objective_information>
276
-
277
- <instructions>
278
- The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
279
- You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
280
- </instructions>
281
-
282
- The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
283
-
284
- With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
285
- Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
286
-
287
- <messages>
288
- Messages to summarize:
289
- {messages}
290
- </messages>`,_S="## Previous conversation summary:",vS=20,Cj=4e3,ky=5,Iy=Pe({model:wr(),maxTokensBeforeSummary:Xt().optional(),messagesToKeep:Xt().default(vS),tokenCounter:Fy().args(yn(Ut())).returns(jr([Xt(),Uy(Xt())])).optional(),summaryPrompt:nt().default(yS),summaryPrefix:nt().default(_S)});function Aj(e){return tr({name:"SummarizationMiddleware",contextSchema:Iy,beforeModel:async(t,r)=>{const n=an(Iy,e),i={model:n.model,maxTokensBeforeSummary:r.context.maxTokensBeforeSummary!==void 0?r.context.maxTokensBeforeSummary:n.maxTokensBeforeSummary,messagesToKeep:r.context.messagesToKeep===vS?n.messagesToKeep:r.context.messagesToKeep??n.messagesToKeep,tokenCounter:r.context.tokenCounter!==void 0?r.context.tokenCounter:n.tokenCounter,summaryPrompt:r.context.summaryPrompt===yS?n.summaryPrompt:r.context.summaryPrompt??n.summaryPrompt,summaryPrefix:r.context.summaryPrefix===_S?n.summaryPrefix:r.context.summaryPrefix??n.summaryPrefix},{messages:s}=t;Oj(s);const a=i.tokenCounter||nh,o=await a(s);if(i.maxTokensBeforeSummary==null||o<i.maxTokensBeforeSummary)return;const{systemPrompt:c,conversationMessages:l}=xj(s),u=Ij(l,i.messagesToKeep);if(u<=0)return;const{messagesToSummarize:d,preservedMessages:f}=Pj(c,l,u),h=await $j(d,i.model,i.summaryPrompt,a),p=kj(c,h,i.summaryPrefix);return{messages:[new sn({id:uS}),p,...f]}}})}function Oj(e){for(const t of e)t.id||(t.id=et())}function xj(e){return e.length>0&&He.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{systemPrompt:null,conversationMessages:e}}function Pj(e,t,r){const n=t.slice(0,r),i=t.slice(r);return e&&n.unshift(e),{messagesToSummarize:n,preservedMessages:i}}function kj(e,t,r){let n="";if(e){const{content:s}=e;typeof s=="string"&&(n=s.split(r)[0].trim())}const i=n?`${n}
291
- ${r}
292
- ${t}`:`${r}
293
- ${t}`;return new He({content:i,id:e?.id||et()})}function Ij(e,t){if(e.length<=t)return 0;const r=e.length-t;for(let n=r;n>=0;n--)if(Mj(e,n))return n;return 0}function Mj(e,t){if(t>=e.length)return!0;const r=Math.max(0,t-ky),n=Math.min(e.length,t+ky);for(let i=r;i<n;i++){if(!hS(e[i]))continue;const s=Rj(e[i]);if(Nj(e,i,t,s))return!1}return!0}function Rj(e){const t=new Set;if(e.tool_calls)for(const r of e.tool_calls){const n=typeof r=="object"&&"id"in r?r.id:null;n&&t.add(n)}return t}function Nj(e,t,r,n){for(let i=t+1;i<e.length;i++){const s=e[i];if(Ae.isInstance(s)&&n.has(s.tool_call_id)){const a=t<r,o=i<r;if(a!==o)return!0}}return!1}async function $j(e,t,r,n){if(!e.length)return"No previous conversation history.";const i=await Lj(e,n);if(!i.length)return"Previous conversation was too long to summarize.";try{const s=r.replace("{messages}",JSON.stringify(i,null,2)),a=await t.invoke(s),{content:o}=a;return typeof o=="string"?o.trim():"Error generating summary: Invalid response format"}catch(s){return`Error generating summary: ${s}`}}async function Lj(e,t){try{return await Xd(e,{maxTokens:Cj,tokenCounter:async r=>Promise.resolve(t(r)),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-15)}}const jj=Fy().args(wr(),wr(),wr()).returns(jr([nt(),Uy(nt())])),wS=["approve","edit","reject"],Dj=Fi(wS),Fj=Pe({allowedDecisions:yn(Dj),description:jr([nt(),jj]).optional(),argsSchema:ed(Ut()).optional()}),My=Pe({interruptOn:ed(jr([Qf(),Fj])).optional(),descriptionPrefix:nt().default("Tool execution requires approval")});function Uj(e){const t=async(n,i,s,a)=>{const o=n.name,c=n.args,l=i.description;let u;typeof l=="function"?u=await l(n,s,a):l!==void 0?u=l:u=`${e.descriptionPrefix??"Tool execution requires approval"}
294
-
295
- Tool: ${o}
296
- Args: ${JSON.stringify(c,null,2)}`;const d={name:o,args:c,description:u},f={actionName:o,allowedDecisions:i.allowedDecisions};return i.argsSchema&&(f.argsSchema=i.argsSchema),{actionRequest:d,reviewConfig:f}},r=(n,i,s)=>{const a=s.allowedDecisions;if(n.type==="approve"&&a.includes("approve"))return{revisedToolCall:i,toolMessage:null};if(n.type==="edit"&&a.includes("edit")){const c=n.editedAction;if(!c||typeof c.name!="string")throw new Error(`Invalid edited action for tool "${i.name}": name must be a string`);if(!c.args||typeof c.args!="object")throw new Error(`Invalid edited action for tool "${i.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:c.name,args:c.args,id:i.id},toolMessage:null}}if(n.type==="reject"&&a.includes("reject")){if(n.message!==void 0&&typeof n.message!="string")throw new Error(`Tool call response for "${i.name}" must be a string, got ${typeof n.message}`);const c=n.message??`User rejected the tool call for \`${i.name}\` with id ${i.id}`,l=new Ae({content:c,name:i.name,tool_call_id:i.id,status:"error"});return{revisedToolCall:i,toolMessage:l}}const o=`Unexpected human decision: ${JSON.stringify(n)}. Decision type '${n.type}' is not allowed for tool '${i.name}'. Expected one of ${JSON.stringify(a)} based on the tool's configuration.`;throw new Error(o)};return tr({name:"HumanInTheLoopMiddleware",contextSchema:My,afterModel:{canJumpTo:["model"],hook:async(n,i)=>{const s=an(My,{...e,...i.context||{}});if(!s)return;const{messages:a}=n;if(!a.length)return;const o=[...a].reverse().find(g=>fe.isInstance(g));if(!o||!o.tool_calls?.length||!s.interruptOn)return;const c={};for(const[g,_]of Object.entries(s.interruptOn))typeof _=="boolean"?_===!0&&(c[g]={allowedDecisions:[...wS]}):_.allowedDecisions&&(c[g]=_);const l=[],u=[];for(const g of o.tool_calls)g.name in c?l.push(g):u.push(g);if(!l.length)return;const d=[],f=[];for(const g of l){const _=c[g.name],{actionRequest:b,reviewConfig:A}=await t(g,_,n,i);d.push(b),f.push(A)}const m=(await W0({actionRequests:d,reviewConfigs:f})).decisions;if(!m||!Array.isArray(m))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(m.length!==l.length)throw new Error(`Number of human decisions (${m.length}) does not match number of hanging tool calls (${l.length}).`);const w=[...u],y=[];for(let g=0;g<m.length;g++){const _=m[g],b=l[g],A=c[b.name],{revisedToolCall:P,toolMessage:x}=r(_,b,A);P&&w.push(P),x&&y.push(x)}return fe.isInstance(o)&&(o.tool_calls=w),{messages:[o,...y]}}}})}const Bj=!0,zj="5m",qj=3,Hj="warn",Gj=Pe({enableCaching:Qf().optional(),ttl:Fi(["5m","1h"]).optional(),minMessagesToCache:Xt().optional(),unsupportedModelBehavior:Fi(["ignore","warn","raise"]).optional()});var Ry=class extends Error{constructor(e){super(e),this.name="PromptCachingMiddlewareError"}};function Vj(e){return tr({name:"PromptCachingMiddleware",contextSchema:Gj,wrapModelCall:(t,r)=>{const n=t.runtime.context.enableCaching??e?.enableCaching??Bj,i=t.runtime.context.ttl??e?.ttl??zj,s=t.runtime.context.minMessagesToCache??e?.minMessagesToCache??qj,a=t.runtime.context.unsupportedModelBehavior??e?.unsupportedModelBehavior??Hj;if(!n||!t.model)return r(t);if(!(t.model.getName()==="ChatAnthropic"||t.model.getName()==="ConfigurableModel"&&t.model._defaultConfig?.modelProvider==="anthropic")){const d=t.model.getName(),h=`Unsupported model '${t.model.getName()==="ConfigurableModel"?`${d} (${t.model._defaultConfig?.modelProvider})`:d}'. Prompt caching requires an Anthropic model`;if(a==="raise")throw new Ry(`${h} (e.g., 'anthropic:claude-4-0-sonnet').`);return a==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${d}. Consider switching to an Anthropic model for caching benefits.`),r(t)}if(t.state.messages.length+(t.systemPrompt?1:0)<s)return r(t);const l=t.messages.at(-1);if(!l)return r(t);const u=Object.getPrototypeOf(l).constructor;if(Array.isArray(l.content)){const d=new u({...l,content:[...l.content.slice(0,-1),{...l.content.at(-1),cache_control:{type:"ephemeral",ttl:i}}]});return r({...t,messages:[...t.messages.slice(0,-1),d]})}else if(typeof l.content=="string"){const d=new u({...l,content:[{type:"text",text:l.content,cache_control:{type:"ephemeral",ttl:i}}]});return r({...t,messages:[...t.messages.slice(0,-1),d]})}throw new Ry("Last message content is not a string or array")}})}function Wj(e){return tr({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(t,r)=>{const n=await e(t.state,t.runtime);if(typeof n!="string")throw new Error("dynamicSystemPromptMiddleware function must return a string");return r({...t,systemPrompt:n})}})}const Jj="Your goal is to select the most relevant tools for answering the user's query.";function Kj(e){if(!e||e.length===0)throw new Error("Invalid usage: tools must be non-empty");const t=e.map(n=>Vu(n.name)),r=jr(t);return Pe({tools:yn(r).describe("Tools to use. Place the most relevant tools first.")})}const Zj=Pe({model:nt().or(By(bc)).optional(),systemPrompt:nt().optional(),maxTools:Xt().optional(),alwaysInclude:yn(nt()).optional()});function Yj(e){return tr({name:"LLMToolSelector",contextSchema:Zj,async wrapModelCall(t,r){const n=await Xj(t,e,t.runtime);if(!n)return r(t);const i=Kj(n.availableTools),a=await(await n.model.withStructuredOutput?.(i))?.invoke([{role:"system",content:n.systemMessage},n.lastUserMessage]);if(!a||typeof a!="object"||!("tools"in a))throw new Error(`Expected object response with tools array, got ${typeof a}`);return r(Qj(a,n.availableTools,n.validToolNames,t,e))}})}async function Xj(e,t,r){const n=r.context.model??t.model,i=r.context.maxTools??t.maxTools,s=r.context.alwaysInclude??t.alwaysInclude??[],a=r.context.systemPrompt??t.systemPrompt??Jj;if(!e.tools||e.tools.length===0)return;const o=e.tools.filter(h=>typeof h=="object"&&"name"in h&&"description"in h&&typeof h.name=="string");if(s.length>0){const h=new Set(o.map(m=>m.name)),p=s.filter(m=>!h.has(m));if(p.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${p.join(", ")}. Available tools: ${Array.from(h).sort().join(", ")}`)}const c=o.filter(h=>!s.includes(h.name));if(c.length===0)return;let l=a;i!==void 0&&(l+=`
297
- IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${i} will be used.`);let u;for(const h of e.messages)je.isInstance(h)&&(u=h);if(!u)throw new Error("No user message found in request messages");const d=n?typeof n=="string"?await la(n):n:e.model,f=c.map(h=>h.name);return{availableTools:c,systemMessage:l,lastUserMessage:u,model:d,validToolNames:f}}function Qj(e,t,r,n,i){const s=i.maxTools,a=i.alwaysInclude??[],o=[],c=[];for(const f of e.tools){if(!r.includes(f)){c.push(f);continue}!o.includes(f)&&(s===void 0||o.length<s)&&o.push(f)}if(c.length>0)throw new Error(`Model selected invalid tools: ${c.join(", ")}`);const l=t.filter(f=>o.includes(f.name)),u=(n.tools??[]).filter(f=>typeof f=="object"&&"name"in f&&typeof f.name=="string"&&a.includes(f.name));l.push(...u);const d=(n.tools??[]).filter(f=>!(typeof f=="object"&&"name"in f&&"description"in f&&typeof f.name=="string"));return{...n,tools:[...l,...d]}}const e2=Pe({rules:ed(nt(),By(RegExp).describe("Regular expression pattern to match PII")).optional()});function t2(){return Math.random().toString(36).substring(2,11)}function Hu(e,t,r){let n=e;for(const[i,s]of Object.entries(t)){const a=i.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");n=n.replace(s,o=>{const c=t2();return r[c]=o,`[REDACTED_${a}_${c}]`})}return n}async function r2(e,t){if(je.isInstance(e)||Ae.isInstance(e)||He.isInstance(e)){const r=e.content,n=await Hu(r,t.rules,t.redactionMap);if(n!==r){const i=Object.getPrototypeOf(e).constructor;return new i({...e,content:n})}return e}if(fe.isInstance(e)){const r=typeof e.content=="string"?e.content:JSON.stringify(e.content),n=JSON.stringify(e.tool_calls),i=await Hu(r,t.rules,t.redactionMap),s=await Hu(n,t.rules,t.redactionMap);return i!==r||s!==n?new fe({...e,content:typeof e.content=="string"?i:JSON.parse(i),tool_calls:JSON.parse(s)}):e}throw new Error(`Unsupported message type: ${e.type}`)}function As(e,t){let r=e;const n=/\[REDACTED_[A-Z_]+_(\w+)\]/g;return r=r.replace(n,(i,s)=>t[s]?t[s]:i),r}function Ny(e,t){if(je.isInstance(e)||Ae.isInstance(e)||He.isInstance(e)){const r=e.content,n=As(r,t);if(n!==r){const i=Object.getPrototypeOf(e).constructor;return{message:new i({...e,content:n}),changed:!0}}return{message:e,changed:!1}}if(fe.isInstance(e)){const r=typeof e.content=="string"?e.content:JSON.stringify(e.content),n=JSON.stringify(e.tool_calls),i=As(r,t),s=As(n,t);return i!==r||s!==n?{message:new fe({...e,content:typeof e.content=="string"?i:JSON.parse(i),tool_calls:JSON.parse(s)}),changed:!0}:{message:e,changed:!1}}throw new Error(`Unsupported message type: ${e.type}`)}function n2(e={}){const t={};return tr({name:"PIIRedactionMiddleware",contextSchema:e2,wrapModelCall:async(r,n)=>{const i=r.runtime.context.rules??e.rules??{};if(Object.keys(i).length===0)return n(r);const s=await Promise.all(r.state.messages.map(a=>r2(a,{rules:i,redactionMap:t})));return n({...r,messages:s})},afterModel:async r=>{if(Object.keys(t).length===0)return;const n=r.messages.at(-1);if(!fe.isInstance(n))return;const i=r.messages.at(-2),{message:s,changed:a}=Ny(n,t);if(!a)return;let o;if(fe.isInstance(n)&&n?.tool_calls?.length===0&&typeof n.content=="string"&&n.content.startsWith("{")&&n.content.endsWith("}"))try{o=JSON.parse(As(n.content,t))}catch{}if(fe.isInstance(i)&&i?.tool_calls?.length!==0&&i?.tool_calls?.some(l=>l.name.startsWith("extract-"))){const{message:l,changed:u}=Ny(i,t),d=i.tool_calls?.find(h=>h.name.startsWith("extract-"))?.args,f=d?JSON.parse(As(JSON.stringify(d),t)):void 0;if(a||u)return{...r,...f?{structuredResponse:f}:{},messages:[new sn({id:i.id}),new sn({id:n.id}),l,s]}}return{...r,...o?{structuredResponse:o}:{},messages:[new sn({id:n.id}),s]}}})}const i2="[cleared]";var bS=class{triggerTokens;clearAtLeast;keep;clearToolInputs;excludeTools;placeholder;constructor(e={}){this.triggerTokens=e.triggerTokens??1e5,this.clearAtLeast=e.clearAtLeast??0,this.keep=e.keep??3,this.clearToolInputs=e.clearToolInputs??!1,this.excludeTools=new Set(e.excludeTools??[]),this.placeholder=e.placeholder??i2}async apply(e){const{tokens:t,messages:r,countTokens:n}=e;if(t<=this.triggerTokens)return t;const i=[];for(let o=0;o<r.length;o++){const c=r[o];Ae.isInstance(c)&&i.push({idx:o,msg:c})}const s=this.keep>=i.length?[]:this.keep>0?i.slice(0,-this.keep):i;let a=0;for(const{idx:o,msg:c}of s){if(this.clearAtLeast>0&&a>=this.clearAtLeast)break;if(c.response_metadata?.context_editing?.cleared)continue;const u=this.#e(r.slice(0,o),c.tool_call_id);if(!u)continue;const d=u.tool_calls?.find(p=>p.id===c.tool_call_id);if(!d)continue;const f=c.name||d.name;if(this.excludeTools.has(f))continue;if(r[o]=new Ae({tool_call_id:c.tool_call_id,content:this.placeholder,name:c.name,artifact:void 0,response_metadata:{...c.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const p=r.indexOf(u);p>=0&&(r[p]=this.#r(u,c.tool_call_id))}const h=await n(r);a=Math.max(0,t-h)}return t-a}#e(e,t){for(let r=e.length-1;r>=0;r--){const n=e[r];if(fe.isInstance(n)&&n.tool_calls?.some(s=>s.id===t))return n}return null}#r(e,t){const r=e.tool_calls?.map(a=>a.id===t?{...a,args:{}}:a),n={...e.response_metadata},i={...n.context_editing},s=new Set(i.cleared_tool_inputs);return s.add(t),i.cleared_tool_inputs=Array.from(s).sort(),n.context_editing=i,new fe({content:e.content,tool_calls:r,response_metadata:n,id:e.id,name:e.name,additional_kwargs:e.additional_kwargs})}};function s2(e={}){const t=e.edits??[new bS],r=e.tokenCountMethod??"approx";return tr({name:"ContextEditingMiddleware",wrapModelCall:async(n,i)=>{if(!n.messages||n.messages.length===0)return i(n);const s=n.systemPrompt?[new He(n.systemPrompt)]:[],a=r==="approx"?nh:async c=>{const l=[...s,...c];if("getNumTokensFromMessages"in n.model)return n.model.getNumTokensFromMessages(l).then(({totalCount:u})=>u);throw new Error(`Model "${n.model.getName()}" does not support token counting`)};let o=await a(n.messages);for(const c of t)o=await c.apply({tokens:o,messages:n.messages,countTokens:a});return i(n)}})}function $y(e,t){let r=0;for(const n of e)fe.isInstance(n)&&n.tool_calls&&(t===void 0?r+=n.tool_calls.length:r+=n.tool_calls.filter(i=>i.name===t).length);return r}function a2(e){let t=-1;for(let r=e.length-1;r>=0;r--)if(je.isInstance(e[r])){t=r;break}return t===-1?e:e.slice(t+1)}function SS(e,t,r,n,i){const s=i?`'${i}' tool call`:"Tool call",a=[];return r!==void 0&&e>=r&&a.push(`thread limit reached (${e}/${r})`),n!==void 0&&t>=n&&a.push(`run limit reached (${t}/${n})`),`${s} limit${a.length>1?"s":""}: ${a.join(", ")}. Stopping to prevent further tool calls.`}var ES=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(e,t,r,n,i=void 0){const s=SS(e,t,r,n,i);super(s),this.name="ToolCallLimitExceededError",this.threadCount=e,this.runCount=t,this.threadLimit=r,this.runLimit=n,this.toolName=i}};Pe({toolName:nt().optional(),threadLimit:Xt().optional(),runLimit:Xt().optional(),exitBehavior:Fi(["end","error"]).default("end")});function o2(e){if(e.threadLimit===void 0&&e.runLimit===void 0)throw new Error("At least one limit must be specified (threadLimit or runLimit)");const t=e.exitBehavior??"end";if(t!=="end"&&t!=="error")throw new Error(`Invalid exit behavior: ${t}. Must be 'end' or 'error'`);const r=e.toolName?`ToolCallLimitMiddleware[${e.toolName}]`:"ToolCallLimitMiddleware";return tr({name:r,beforeModel:{canJumpTo:["end"],hook:n=>{const i=n.messages,s=$y(i,e.toolName),a=a2(i),o=$y(a,e.toolName),c=e.threadLimit!==void 0&&s>=e.threadLimit,l=e.runLimit!==void 0&&o>=e.runLimit;if(!c&&!l)return;if(t==="error")throw new ES(s,o,e.threadLimit,e.runLimit,e.toolName);const u=SS(s,o,e.threadLimit,e.runLimit,e.toolName);return{jumpTo:"end",messages:[new fe(u)]}}}})}const c2=`Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
298
- It also helps the user understand the progress of the task and overall progress of their requests.
299
- Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
300
-
301
- ## When to Use This Tool
302
- Use this tool in these scenarios:
303
-
304
- 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
305
- 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
306
- 3. User explicitly requests todo list - When the user directly asks you to use the todo list
307
- 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
308
- 5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful.
309
-
310
- ## How to Use This Tool
311
- 1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
312
- 2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
313
- 3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.
314
- 4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.
315
-
316
- ## When NOT to Use This Tool
317
- It is important to skip using this tool when:
318
- 1. There is only a single, straightforward task
319
- 2. The task is trivial and tracking it provides no benefit
320
- 3. The task can be completed in less than 3 trivial steps
321
- 4. The task is purely conversational or informational
322
-
323
- ## Examples of When to Use the Todo List
324
-
325
- <example>
326
- User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
327
- Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
328
- *Creates todo list with the following items:*
329
- 1. Create dark mode toggle component in Settings page
330
- 2. Add dark mode state management (context/store)
331
- 3. Implement CSS-in-JS styles for dark theme
332
- 4. Update existing components to support theme switching
333
- 5. Run tests and build process, addressing any failures or errors that occur
334
- *Begins working on the first task*
335
-
336
- <reasoning>
337
- The assistant used the todo list because:
338
- 1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
339
- 2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
340
- 3. Both of the user's requests are complex and require multiple steps to complete.
341
- </reasoning>
342
- </example>
343
-
344
- <example>
345
- User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
346
- Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.
347
- *Creates todo list with the following items:*
348
- 1. Define target audience and key messaging
349
- 2. Create social media content calendar and posting schedule
350
- 3. Design email marketing sequence and automation flows
351
- 4. Draft press release and identify media contacts
352
- 5. Set up tracking and analytics for campaign performance
353
- 6. Create visual assets and brand materials
354
- 7. Coordinate launch timeline and deliverables
355
- *Begins working on the first task*
356
-
357
- <reasoning>
358
- The assistant used the todo list because:
359
- 1. Marketing campaign planning involves multiple distinct channels and activities
360
- 2. Each component requires careful coordination and planning
361
- 3. The systematic approach ensures all aspects of the launch are covered
362
- </reasoning>
363
- </example>
364
-
365
- <example>
366
- User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
367
- Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
368
- *Uses search tools to locate all instances of getCwd in the codebase*
369
- Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
370
- *Creates todo list with specific items for each file that needs updating*
371
-
372
- <reasoning>
373
- The assistant used the todo list because:
374
- 1. The assistant searched to understand the scope of the task
375
- 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
376
- 3. The todo list helps ensure every instance is tracked and updated systematically
377
- 4. This approach prevents missing any occurrences and maintains consistency.
378
- </reasoning>
379
- </example>
380
-
381
- <example>
382
- User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
383
- Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
384
- *Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines*
385
- Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
386
-
387
- <reasoning>
388
- The assistant used the todo list because:
389
- 1. The user provided multiple distinct organizational tasks
390
- 2. Each area requires different approaches and careful planning
391
- 3. Home organization benefits from systematic, step-by-step completion
392
- 4. Progress tracking ensures all areas are addressed thoroughly
393
- </reasoning>
394
- </example>
395
-
396
- ## Examples of When NOT to Use the Todo List
397
-
398
- <example>
399
- User: How do I print 'Hello World' in Python?
400
- Assistant: In Python, you can print "Hello World" with this simple code:
401
-
402
- \`\`\`python
403
- print("Hello World")
404
- \`\`\`
405
-
406
- This will output the text "Hello World" to the console when executed.</assistant>
407
-
408
- <reasoning>
409
- The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
410
- </reasoning>
411
- </example>
412
-
413
- <example>
414
- User: What's the best way to water houseplants?
415
- Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
416
-
417
- - Check soil moisture by inserting your finger about 1-2 inches into the soil
418
- - Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
419
- - Use room temperature water and water in the morning when possible
420
- - Avoid overwatering, which is more harmful than underwatering for most plants
421
-
422
- Different plants have different needs, so it's important to research your specific varieties for optimal care.
423
-
424
- <reasoning>
425
- The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities.
426
- </reasoning>
427
- </example>
428
-
429
- <example>
430
- User: Can you add a comment to the calculateTotal function to explain what it does?
431
- Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
432
- * Uses the Edit tool to add a comment to the calculateTotal function *
433
-
434
- <reasoning>
435
- The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization.
436
- </reasoning>
437
- </example>
438
-
439
- <example>
440
- User: What time is it in Tokyo right now?
441
- Assistant: I'll check the current time in Tokyo for you.
442
-
443
- *Searches for current time in Tokyo*
444
-
445
- The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
446
-
447
- <reasoning>
448
- The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request.
449
- </reasoning>
450
- </example>
451
-
452
- <example>
453
- User: I need to write a function that checks if a number is prime and then test it out.
454
- Assistant: I'll help you write a function that checks if a number is prime and then test it out.
455
- *Writes function that checks if a number is prime*
456
- *Tests the function*
457
-
458
- <reasoning>
459
- Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens.
460
- </reasoning>
461
- </example>
462
-
463
- <example>
464
- User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
465
- Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
466
- *Orders a pizza from Dominos*
467
- *Orders a burger from McDonald's*
468
- *Orders a salad from Subway*
469
-
470
- <reasoning>
471
- Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls.
472
- Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
473
- </reasoning>
474
- </example>
475
-
476
-
477
- ## Task States and Management
478
-
479
- 1. **Task States**: Use these states to track progress:
480
- - pending: Task not yet started
481
- - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)
482
- - completed: Task finished successfully
483
-
484
- 2. **Task Management**:
485
- - Update task status in real-time as you work
486
- - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
487
- - Complete current tasks before starting new ones
488
- - Remove tasks that are no longer relevant from the list entirely
489
- - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
490
- - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something.
491
-
492
- 3. **Task Completion Requirements**:
493
- - ONLY mark a task as completed when you have FULLY accomplished it
494
- - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
495
- - When blocked, create a new task describing what needs to be resolved
496
- - Never mark a task as completed if:
497
- - There are unresolved issues or errors
498
- - Work is partial or incomplete
499
- - You encountered blockers that prevent completion
500
- - You couldn't find necessary resources or dependencies
501
- - Quality standards haven't been met
502
-
503
- 4. **Task Breakdown**:
504
- - Create specific, actionable items
505
- - Break complex tasks into smaller, manageable steps
506
- - Use clear, descriptive task names
507
-
508
- Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
509
- Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`,TS=`## \`write_todos\`
510
-
511
- You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
512
- Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
513
- This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
514
-
515
- It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.
516
- For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.
517
- Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.
518
-
519
- ## Important To-Do List Usage Notes to Remember
520
- - The \`write_todos\` tool should never be called multiple times in parallel.
521
- - Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`,l2=Fi(["pending","in_progress","completed"]).describe("Status of the todo"),CS=Pe({content:nt().describe("Content of the todo item"),status:l2}),u2=Pe({todos:yn(CS).default([])});function f2(e){const t=Yd(({todos:r},n)=>new Xe({update:{todos:r,messages:[new Ae({content:`Updated todo list to ${JSON.stringify(r)}`,tool_call_id:n.toolCall?.id})]}}),{name:"write_todos",description:e?.toolDescription??c2,schema:Pe({todos:yn(CS).describe("List of todo items to update")})});return tr({name:"todoListMiddleware",stateSchema:u2,tools:[t],wrapModelCall:(r,n)=>n({...r,systemPrompt:(r.systemPrompt?`${r.systemPrompt}
522
-
523
- `:"")+(e?.systemPrompt??TS)})})}const d2="end",h2=Pe({threadLimit:Xt().optional(),runLimit:Xt().optional(),exitBehavior:Fi(["throw","end"]).optional()});var Ly=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:r,runCount:n}){const i=[];typeof e=="number"&&typeof r=="number"&&i.push(`thread level call limit reached with ${r} model calls`),typeof t=="number"&&typeof n=="number"&&i.push(`run level call limit reached with ${n} model calls`),super(`Model call limits exceeded${i.length>0?`: ${i.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function AS(e){return tr({name:"ModelCallLimitMiddleware",contextSchema:h2,beforeModel:{canJumpTo:["end"],hook:(t,r)=>{const n=r.context.exitBehavior??e?.exitBehavior??d2,i=r.context.threadLimit??e?.threadLimit,s=r.context.runLimit??e?.runLimit;if(typeof i=="number"&&i<=r.threadLevelCallCount){const a=new Ly({threadLimit:i,threadCount:r.threadLevelCallCount});if(n==="end")return{jumpTo:"end",messages:[new fe(a.message)]};throw a}if(typeof s=="number"&&s<=r.runModelCallCount){const a=new Ly({runLimit:s,runCount:r.runModelCallCount});if(n==="end")return{jumpTo:"end",messages:[new fe(a.message)]};throw a}return t}}})}function p2(...e){return tr({name:"modelFallbackMiddleware",wrapModelCall:async(t,r)=>{try{return await r(t)}catch(n){for(let i=0;i<e.length;i++)try{const s=e[i],a=typeof s=="string"?await la(s):s;return await r({...t,model:a})}catch(s){if(i===e.length-1)throw s}throw n}}})}Ve.initializeGlobalInstance(new Vy);var m2={};Gw(m2,{AIMessage:()=>fe,AIMessageChunk:()=>qt,BaseMessage:()=>bt,BaseMessageChunk:()=>_n,ClearToolUsesEdit:()=>bS,Document:()=>Ur,DynamicStructuredTool:()=>Ec,DynamicTool:()=>Zd,FakeToolCallingModel:()=>g$,HumanMessage:()=>je,HumanMessageChunk:()=>ia,InMemoryStore:()=>hb,MultipleStructuredOutputsError:()=>Ef,MultipleToolsBoundError:()=>Sf,ProviderStrategy:()=>On,StructuredOutputParsingError:()=>tb,StructuredTool:()=>Hn,SystemMessage:()=>He,SystemMessageChunk:()=>jn,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>TS,Tool:()=>Kd,ToolCallLimitExceededError:()=>ES,ToolInvocationError:()=>eh,ToolMessage:()=>Ae,ToolMessageChunk:()=>na,ToolStrategy:()=>Qr,anthropicPromptCachingMiddleware:()=>Vj,contextEditingMiddleware:()=>s2,countTokensApproximately:()=>nh,createAgent:()=>gS,createMiddleware:()=>tr,dynamicSystemPromptMiddleware:()=>Wj,filterMessages:()=>Vw,getContextVariable:()=>kd,humanInTheLoopMiddleware:()=>Uj,initChatModel:()=>la,llmToolSelectorMiddleware:()=>Yj,modelCallLimitMiddleware:()=>AS,modelFallbackMiddleware:()=>p2,piiRedactionMiddleware:()=>n2,providerStrategy:()=>i1,setContextVariable:()=>ix,summarizationMiddleware:()=>Aj,todoListMiddleware:()=>f2,tool:()=>Yd,toolCallLimitMiddleware:()=>o2,toolStrategy:()=>n1,trimMessages:()=>Xd});var Gu,jy;function g2(){return jy||(jy=1,Gu=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),Gu}var y2=g2();const Dy=GS(y2);var ic={},pi,OS=(pi=class{disallowedTools;connectorToolMap=new Map;constructor(t){this.disallowedTools=t??[]}static async createTools(t,r){const n=new this(r);(!t.activeSessions||Object.keys(t.activeSessions).length===0)&&($.info("No active sessions found, creating new ones..."),await t.createAllSessions());const i=t.getAllActiveSessions(),s=Object.values(i).map(a=>a.connector);return n.createToolsFromConnectors(s)}async loadToolsForConnector(t){if(this.connectorToolMap.has(t)){const i=this.connectorToolMap.get(t);return $.debug(`Returning ${i.length} existing tools for connector`),i}const r=[];if(!await this.ensureConnectorInitialized(t))return[];for(const i of t.tools){const s=this.convertTool(i,t);s&&r.push(s)}return this.connectorToolMap.set(t,r),$.debug(`Loaded ${r.length} new tools for connector: ${r.map(i=>i?.name??String(i)).join(", ")}`),r}async createToolsFromConnectors(t){const r=[];for(const n of t){const i=await this.loadToolsForConnector(n);r.push(...i)}return $.debug(`Available tools: ${r.length}`),r}checkConnectorInitialized(t){return!!(t.tools&&t.tools.length)}async ensureConnectorInitialized(t){if(!this.checkConnectorInitialized(t)){$.debug("Connector doesn't have tools, initializing it");try{return await t.initialize(),!0}catch(r){return $.error(`Error initializing connector: ${r}`),!1}}return!0}},le(pi,"BaseAdapter"),pi);function xS(e){try{return TC.convert(e)}catch(t){return $.warn(`Failed to convert JSON schema to Zod: ${t}`),Ut()}}le(xS,"schemaToZod");var mi,Cn=(mi=class extends OS{constructor(t=[]){super(t)}convertTool(t,r){if(this.disallowedTools.includes(t.name))return null;const n=t.inputSchema?xS(t.inputSchema):Pe({}).optional();return new Ec({name:t.name??"NO NAME",description:t.description??"",schema:n,func:le(async s=>{$.debug(`MCP tool "${t.name}" received input: ${JSON.stringify(s)}`);try{const a=await r.callTool(t.name,s);return JSON.stringify(a)}catch(a){return $.error(`Error executing MCP tool: ${a.message}`),`Error executing MCP tool: ${String(a)}`}},"func")})}},le(mi,"LangChainAdapter"),mi),gi,Mc=(gi=class extends Hn{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(t){super(),this._manager=t}async _call(t,r,n){throw new Error("Method not implemented.")}get manager(){return this._manager}},le(gi,"MCPServerTool"),gi),_2=Pe({}),yi,v2=(yi=class extends Mc{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=_2;constructor(t){super(t)}async _call(){return this.manager.activeServer?`Currently active MCP server: ${this.manager.activeServer}`:"No MCP server is currently active. Use connect_to_mcp_server to connect to a server."}},le(yi,"AcquireActiveMCPServerTool"),yi),_i,w2=(_i=class extends Hn{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=Pe({serverName:nt().describe("The name for the new MCP server."),serverConfig:Ut().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(t){super(),this.manager=t}async _call({serverName:t,serverConfig:r}){try{this.manager.client.addServer(t,r);let n=`Server '${t}' added to the client.`;$.debug(`Connecting to new server '${t}' and discovering tools.`);const s=(await this.manager.client.createSession(t)).connector,a=await this.manager.adapter.createToolsFromConnectors([s]);this.manager.serverTools[t]=a,this.manager.initializedServers[t]=!0,this.manager.activeServer=t;const o=a.length;return n+=` Session created and connected. '${t}' is now the active server with ${o} tools available.`,n+=`
524
-
525
- ${a.map(c=>c.name).join(`
526
- `)}`,$.info(n),n}catch(n){return $.error(`Failed to add or connect to server '${t}': ${n.message}`),`Failed to add or connect to server '${t}': ${n.message}`}}},le(_i,"AddMCPServerFromConfigTool"),_i),b2=Pe({serverName:nt().describe("The name of the MCP server.")}),vi,S2=(vi=class extends Mc{name="connect_to_mcp_server";description="Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";schema=b2;constructor(t){super(t)}async _call({serverName:t}){const r=this.manager.client.getServerNames();if(!r.includes(t)){const n=r.length>0?r.join(", "):"none";return`Server '${t}' not found. Available servers: ${n}`}if(this.manager.activeServer===t)return`Already connected to MCP server '${t}'`;try{let n=this.manager.client.getSession(t);if($.debug(`Using existing session for server '${t}'`),n||($.debug(`Creating new session for server '${t}'`),n=await this.manager.client.createSession(t)),this.manager.activeServer=t,this.manager.serverTools[t]){const a=n.connector,o=await this.manager.adapter.createToolsFromConnectors([a]);this.manager.serverTools[t]=o,this.manager.initializedServers[t]=!0}const s=(this.manager.serverTools[t]||[]).length;return`Connected to MCP server '${t}'. ${s} tools are now available.`}catch(n){return $.error(`Error connecting to server '${t}': ${String(n)}`),`Failed to connect to server '${t}': ${String(n)}`}}},le(vi,"ConnectMCPServerTool"),vi),E2=Pe({}),wi,T2=(wi=class extends Mc{name="list_mcp_servers";description="Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.";schema=E2;constructor(t){super(t)}async _call(){const t=this.manager.client.getServerNames();if(t.length===0)return"No MCP servers are currently defined.";const r=["Available MCP servers:"];for(const n of t){const s=n===this.manager.activeServer?" (ACTIVE)":"";r.push(`- ${n}${s}`);try{const a=this.manager.serverTools?.[n]??[],o=Array.isArray(a)?a.length:0;r.push(`${o} tools available for this server
527
- `)}catch(a){$.error(`Unexpected error listing tools for server '${n}': ${String(a)}`)}}return r.join(`
528
- `)}},le(wi,"ListMCPServersTool"),wi),C2=Pe({}),bi,A2=(bi=class extends Mc{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=C2;constructor(t){super(t)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const t=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${t}'.`}},le(bi,"ReleaseMCPServerConnectionTool"),bi),Si,O2=(Si=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(t,r,n){this.client=t,this.adapter=r,this.overrideManagementTools=n}setManagementTools(t){this.overrideManagementTools=t,$.info(`Overriding default management tools with a new set of ${t.length} tools.`)}logState(t){const r=this.client.getServerNames(),n=Object.keys(this.client.getAllActiveSessions());if(r.length===0){$.info("Server Manager State: No servers configured.");return}const i=r.map(s=>({"Server Name":s,Connected:n.includes(s)?"✅":"❌",Initialized:this.initializedServers[s]?"✅":"❌","Tool Count":this.serverTools[s]?.length??0,Active:this.activeServer===s?"✅":"❌"}));$.info(`Server Manager State: [${t}]`),console.table(i)}initialize(){(this.client.getServerNames?.()).length===0&&$.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const t=this.client.getServerNames();for(const r of t)try{let n=null;if(n=this.client.getSession(r),$.debug(`Using existing session for server '${r}' to prefetch tools.`),n||(n=await this.client.createSession(r).catch(i=>($.warn(`Could not create session for '${r}' during prefetch: ${i}`),null)),$.debug(`Temporarily created session for '${r}' to prefetch tools.`)),n){const i=n.connector;let s=[];try{s=await this.adapter.createToolsFromConnectors([i])}catch(c){$.error(`Failed to create tools from connector for server '${r}': ${c}`);continue}const a=this.serverTools[r];!a||!rR(a,s)?(this.serverTools[r]=s,this.initializedServers[r]=!0,$.debug(`Prefetched ${s.length} tools for server '${r}'.`)):$.debug(`Tools for server '${r}' unchanged, using cached version.`)}}catch(n){$.error(`Error prefetching tools for server '${r}': ${n}`)}}get tools(){$.level==="debug"&&this.logState("Providing tools to agent");const t=this.overrideManagementTools??[new w2(this),new T2(this),new S2(this),new v2(this),new A2(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const r=this.serverTools[this.activeServer];return $.debug(`Adding ${r.length} tools from active server '${this.activeServer}'`),[...t,...r]}return t}},le(Si,"ServerManager"),Si),Ei,Kf=(Ei=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(t={}){this.customCallbacks=t.customCallbacks,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.agentId=t.agentId,this.metadata=t.metadata,this.metadataProvider=t.metadataProvider,this.tagsProvider=t.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:t,langfuseInitPromise:r}=await Di(async()=>{const{langfuseHandler:i,langfuseInitPromise:s}=await import("./langfuse-6AJGHMAV-QljN0jPu.js");return{langfuseHandler:i,langfuseInitPromise:s}},__vite__mapDeps([6,2,3,4,5]));if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:i}=await Di(async()=>{const{initializeLangfuse:s}=await import("./langfuse-6AJGHMAV-QljN0jPu.js");return{initializeLangfuse:s}},__vite__mapDeps([6,2,3,4,5]));await i(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),$.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const i=r();i&&await i}const n=t();n&&(this.availableHandlers.push(n),this.handlerNames.push("Langfuse"),$.debug("ObservabilityManager: Langfuse handler available"))}catch{$.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?($.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?$.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):$.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):($.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(t=>t.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const t=await this.getCallbacks(),r=await this.getHandlerNames(),n=this.metadataProvider?this.metadataProvider():this.metadata||{},i=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&t.length>0,callbackCount:t.length,handlerNames:r,metadata:n,tags:i}}addCallback(t){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(t),$.debug(`ObservabilityManager: Added custom callback: ${t.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],$.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const t=await this.getCallbacks();for(const r of t)"flushAsync"in r&&typeof r.flushAsync=="function"&&await r.flushAsync();$.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const t=await this.getCallbacks();for(const r of t)"shutdownAsync"in r&&typeof r.shutdownAsync=="function"?await r.shutdownAsync():"shutdown"in r&&typeof r.shutdown=="function"&&await r.shutdown();$.debug("ObservabilityManager: All handlers shutdown")}toString(){const t=this.handlerNames;return t.length>0?`ObservabilityManager(handlers=${t.join(", ")})`:"ObservabilityManager(no handlers)"}},le(Ei,"ObservabilityManager"),Ei),Ti,x2=(Ti=class{},le(Ti,"BaseTelemetryEvent"),Ti),Ci,P2=(Ci=class extends x2{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},le(Ci,"MCPAgentExecutionEvent"),Ci);function Oo(){try{if(typeof __dirname>"u"||typeof Ps>"u")return"unknown";const e=Ln(__dirname,"../../package.json");return JSON.parse((void 0)(e,"utf-8")).version||"unknown"}catch{return"unknown"}}le(Oo,"getPackageVersion");function PS(e){return e._llm_type||e.constructor.name.toLowerCase()}le(PS,"getModelProvider");function kS(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const r of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(r in t)return String(t[r])}}return e.model||e.modelName||e.constructor.name}le(kS,"getModelName");function IS(e){return[PS(e),kS(e)]}le(IS,"extractModelInfo");function Os(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"&&(typeof Ps<"u"&&typeof Ps<"u"&&!1)}catch{return!1}}le(Os,"isNodeJSEnvironment");var Ai,k2=(Ai=class{endpoint;timeout;constructor(t,r=3e3){this.endpoint=t,this.timeout=r}async logEvent(t){try{const r=new AbortController,n=setTimeout(()=>r.abort(),this.timeout),i=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:r.signal});if(clearTimeout(n),!i.ok)throw new Error(`HTTP error! status: ${i.status}`)}catch(r){$.debug(`Failed to send Scarf event: ${r}`)}}},le(Ai,"ScarfEventLogger"),Ai);function Zf(){if(!Os())return"/tmp/mcp_use_cache";const e=ic.XDG_CACHE_HOME;if(e&&ld(e))return e;const t=(void 0)();return Ln(t,".cache")}le(Zf,"getCacheHome");var ur,Yf=(ur=class{USER_ID_PATH=Ln(Zf(),"mcp_use_3","telemetry_user_id");VERSION_DOWNLOAD_PATH=Ln(Zf(),"mcp_use","download_version");PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="typescript";constructor(){const t=Os(),r=typeof process<"u"&&ic?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||!1;if(this._source=typeof process<"u"&&ic?.MCP_USE_TELEMETRY_SOURCE||"typescript",r)this._posthogClient=null,this._scarfClient=null,$.debug("Telemetry disabled via environment variable");else if(!t)this._posthogClient=null,this._scarfClient=null,$.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");else{$.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");try{this._posthogClient=new nR(this.PROJECT_API_KEY,{host:this.HOST,disableGeoip:!1})}catch(n){$.warn(`Failed to initialize PostHog telemetry: ${n}`),this._posthogClient=null}try{this._scarfClient=new k2(this.SCARF_GATEWAY_URL,3e3)}catch(n){$.warn(`Failed to initialize Scarf telemetry: ${n}`),this._scarfClient=null}}}static getInstance(){return ur.instance||(ur.instance=new ur),ur.instance}setSource(t){this._source=t,$.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!Os())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{if(!(void 0)(this.USER_ID_PATH)){$.debug(`Creating user ID path: ${this.USER_ID_PATH}`),(void 0)(Mo(this.USER_ID_PATH),{recursive:!0});const r=Wy();(void 0)(this.USER_ID_PATH,r),this._currUserId=r,$.debug(`User ID path created: ${this.USER_ID_PATH}`)}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(r=>$.debug(`Failed to track package download: ${r}`))}catch(t){$.debug(`Failed to get/create user ID: ${t}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const r={...t.properties};r.mcp_use_version=Oo(),r.language="typescript",r.source=this._source,this._posthogClient.capture({distinctId:this.userId,event:t.name,properties:r})}catch(r){$.debug(`Failed to track PostHog event ${t.name}: ${r}`)}if(this._scarfClient)try{const r={};r.mcp_use_version=Oo(),r.user_id=this.userId,r.event=t.name,r.language="typescript",r.source=this._source,await this._scarfClient.logEvent(r)}catch(r){$.debug(`Failed to track Scarf event ${t.name}: ${r}`)}}}async trackPackageDownload(t){if(this._scarfClient&&Os())try{const r=Oo();let n=!1,i=!1;if((void 0)(this.VERSION_DOWNLOAD_PATH)||(n=!0,i=!0,(void 0)(Mo(this.VERSION_DOWNLOAD_PATH),{recursive:!0}),(void 0)(this.VERSION_DOWNLOAD_PATH,r)),n){$.debug(`Tracking package download event with properties: ${JSON.stringify(t)}`);const s={...t||{}};s.mcp_use_version=r,s.user_id=this.userId,s.event="package_download",s.first_download=i,s.language="typescript",s.source=this._source,await this._scarfClient.logEvent(s)}}catch(r){$.debug(`Failed to track Scarf package_download event: ${r}`)}}async trackAgentExecution(t){const r=new P2(t);await this.capture(r)}flush(){if(this._posthogClient)try{this._posthogClient.flush(),$.debug("PostHog client telemetry queue flushed")}catch(t){$.debug(`Failed to flush PostHog client: ${t}`)}this._scarfClient&&$.debug("Scarf telemetry events sent immediately (no flush needed)")}shutdown(){if(this._posthogClient)try{this._posthogClient.shutdown(),$.debug("PostHog client shutdown successfully")}catch(t){$.debug(`Error shutting down PostHog client: ${t}`)}this._scarfClient&&$.debug("Scarf telemetry client shutdown (no action needed)")}},le(ur,"Telemetry"),cs(ur,"instance",null),ur);function I2(e){Yf.getInstance().setSource(e)}le(I2,"setTelemetrySource");var M2="/api/v1/chats",R2="/api/v1/chats/{chat_id}/execute",Oi,MS=(Oi=class{agentId;apiKey;baseUrl;chatId=null;constructor(t){this.agentId=t.agentId,this.baseUrl=t.baseUrl??"https://cloud.mcp-use.com";const r=t.apiKey??ic.MCP_USE_API_KEY;if(!r)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=r}pydanticToJsonSchema(t){return lo(t)}parseStructuredResponse(t,r){let n;if(typeof t=="object"&&t!==null)if("result"in t){const i=t.result;typeof i=="object"&&i!==null&&"result"in i?n=i.result:n=i}else n=t;else if(typeof t=="string")try{n=JSON.parse(t)}catch{n={content:t}}else n=t;try{return r.parse(n)}catch(i){$.warn(`Failed to parse structured output: ${i}`);const s=r._def?.shape();if(s&&"content"in s)return r.parse({content:String(n)});throw i}}async createChatSession(){const t={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},r={"Content-Type":"application/json","x-api-key":this.apiKey},n=`${this.baseUrl}${M2}`;$.info(`📝 Creating chat session for agent ${this.agentId}`);try{const i=await fetch(n,{method:"POST",headers:r,body:JSON.stringify(t)});if(!i.ok){const o=await i.text(),c=i.status;throw c===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${c} - ${o}`)}const a=(await i.json()).id;return $.info(`✅ Chat session created: ${a}`),a}catch(i){throw i instanceof Error?new TypeError(`Failed to create chat session: ${i.message}`):new Error(`Failed to create chat session: ${String(i)}`)}}async run(t,r,n,i,s){i!==void 0&&$.warn("External history is not yet supported for remote execution");try{$.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const a=this.chatId,o={query:t,max_steps:r??10};s&&(o.output_schema=this.pydanticToJsonSchema(s),$.info("🔧 Using structured output with schema"));const c={"Content-Type":"application/json","x-api-key":this.apiKey},l=`${this.baseUrl}${R2.replace("{chat_id}",a)}`;$.info(`🚀 Executing agent in chat ${a}`);const u=await fetch(l,{method:"POST",headers:c,body:JSON.stringify(o),signal:AbortSignal.timeout(3e5)});if(!u.ok){const f=await u.text(),h=u.status;throw h===401?($.error(`❌ Authentication failed: ${f}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):h===403?($.error(`❌ Access forbidden: ${f}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):h===404?($.error(`❌ Agent not found: ${f}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):h===422?($.error(`❌ Validation error: ${f}`),new Error(`Request validation failed: ${f}. Please check your query parameters and output schema format.`)):h===500?($.error(`❌ Server error: ${f}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):($.error(`❌ Remote execution failed with status ${h}: ${f}`),new Error(`Remote agent execution failed: ${h} - ${f}`))}const d=await u.json();if($.info(`🔧 Response: ${JSON.stringify(d)}`),$.info("✅ Remote execution completed successfully"),typeof d=="object"&&d!==null){if(d.status==="error"||d.error!==null){const f=d.error??String(d);throw $.error(`❌ Remote agent execution failed: ${f}`),new Error(`Remote agent execution failed: ${f}`)}if(String(d).includes("failed to initialize"))throw $.error(`❌ Agent initialization failed: ${d}`),new Error(`Agent initialization failed on remote server. This usually indicates:
529
- • Invalid agent configuration (LLM model, system prompt)
530
- • Missing or invalid MCP server configurations
531
- • Network connectivity issues with MCP servers
532
- • Missing environment variables or credentials
533
- Raw error: ${d}`)}return s?this.parseStructuredResponse(d,s):typeof d=="object"&&d!==null&&"result"in d?d.result:typeof d=="string"?d:String(d)}catch(a){throw a instanceof Error?a.name==="AbortError"?($.error(`❌ Remote execution timed out: ${a}`),new Error("Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.")):($.error(`❌ Remote execution error: ${a}`),new Error(`Remote agent execution failed: ${a.message}`)):($.error(`❌ Remote execution error: ${a}`),new Error(`Remote agent execution failed: ${String(a)}`))}}async*stream(t,r,n,i,s){return await this.run(t,r,n,i,s)}async close(){$.info("🔌 Remote agent client closed")}},le(Oi,"RemoteAgent"),Oi);function RS(e,t){const r=new Set(t??[]),n=[];for(const i of e){if(r.has(i.name))continue;const s=i.description.replace(/\{/g,"{{").replace(/\}/g,"}}");n.push(`- ${i.name}: ${s}`)}return n}le(RS,"generateToolDescriptions");function NS(e,t,r){const n=t.join(`
534
- `);let i;return e.includes("{tool_descriptions}")?i=e.replace("{tool_descriptions}",n):(console.warn("`{tool_descriptions}` placeholder not found; appending at end."),i=`${e}
535
-
536
- Available tools:
537
- ${n}`),r&&(i+=`
538
-
539
- ${r}`),i}le(NS,"buildSystemPromptContent");function $S(e,t,r,n,i,s,a){if(s)return new He({content:s});const o=n?r:t,c=RS(e,i),l=NS(o,c,a);return new He({content:l})}le($S,"createSystemMessage");var N2=`You are a helpful AI assistant.
540
- You have access to the following tools:
541
-
542
- {tool_descriptions}
543
-
544
- Use the following format:
545
-
546
- Question: the input question you must answer
547
- Thought: you should always think about what to do
548
- Action: the action to take, should be one of the available tools
549
- Action Input: the input to the action
550
- Observation: the result of the action
551
- ... (this Thought/Action/Action Input/Observation can repeat N times)
552
- Thought: I now know the final answer
553
- Final Answer: the final answer to the original input question`,$2=`You are a helpful assistant designed to interact with MCP
554
- (Model Context Protocol) servers. You can manage connections to different servers and use the tools
555
- provided by the currently active server.
556
-
557
- Important: The available tools change depending on which server is active.
558
- If a request requires tools not listed below (e.g., file operations, web browsing,
559
- image manipulation), you MUST first connect to the appropriate server using
560
- 'connect_to_mcp_server'.
561
- Use 'list_mcp_servers' to find the relevant server if you are unsure.
562
- Only after successfully connecting and seeing the new tools listed in
563
- the response should you attempt to use those server-specific tools.
564
- Before attempting a task that requires specific tools, you should
565
- ensure you are connected to the correct server and aware of its
566
- available tools. If unsure, use 'list_mcp_servers' to see options
567
- or 'get_active_mcp_server' to check the current connection.
568
-
569
- When you connect to a server using 'connect_to_mcp_server',
570
- you will be informed about the new tools that become available.
571
- You can then use these server-specific tools in subsequent steps.
572
-
573
- Here are the tools *currently* available to you (this list includes server management tools and will
574
- change when you connect to a server):
575
- {tool_descriptions}
576
- `,xi,L2=(xi=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(t){if(t.agentId){this.isRemote=!0,this.remoteAgent=new MS({agentId:t.agentId,apiKey:t.apiKey,baseUrl:t.baseUrl}),this.maxSteps=t.maxSteps??5,this.memoryEnabled=t.memoryEnabled??!0,this.autoInitialize=t.autoInitialize??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Cn,this.telemetry=Yf.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Kf({customCallbacks:t.callbacks,agentId:t.agentId}),this.callbacks=[];return}if(!t.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=t.llm,this.client=t.client,this.connectors=t.connectors??[],this.maxSteps=t.maxSteps??5,this.autoInitialize=t.autoInitialize??!1,this.memoryEnabled=t.memoryEnabled??!0,this.systemPrompt=t.systemPrompt??null,this.systemPromptTemplateOverride=t.systemPromptTemplate??null,this.additionalInstructions=t.additionalInstructions??null,this.disallowedTools=t.disallowedTools??[],this.additionalTools=t.additionalTools??[],this.toolsUsedNames=t.toolsUsedNames??[],this.useServerManager=t.useServerManager??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=t.adapter??new Cn(this.disallowedTools),this.serverManager=t.serverManagerFactory?.(this.client)??new O2(this.client,this.adapter)}else this.adapter=t.adapter??new Cn(this.disallowedTools);if(this.telemetry=Yf.getInstance(),this.llm){const[r,n]=IS(this.llm);this.modelProvider=r,this.modelName=n}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Kf({customCallbacks:t.callbacks,verbose:this.verbose,observe:this.observe,agentId:t.agentId,metadataProvider:le(()=>this.getMetadata(),"metadataProvider"),tagsProvider:le(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:le(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:le(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:le(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}$.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const t=await this.observabilityManager.getHandlerNames();if(t.length>0&&$.info(`📊 Observability enabled with: ${t.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const n=this.serverManager.tools;this._tools=n,this._tools.push(...this.additionalTools),$.info(`🔧 Server manager mode active with ${n.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client)this.sessions=this.client.getAllActiveSessions(),$.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).length===0&&($.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),$.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this._tools=await Cn.createTools(this.client),this._tools.push(...this.additionalTools),$.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);else{$.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const n of this.connectors)n.isClientConnected||await n.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),$.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}$.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const r=this.getMCPServerInfo();Object.keys(r).length>0&&(this.setMetadata(r),$.debug(`MCP server info added to metadata: ${JSON.stringify(r)}`)),$.info("✨ Agent initialization complete")}async createSystemMessageFromTools(t){const r=this.systemPromptTemplateOverride??N2;this.systemMessage=$S(t,r,$2,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(n=>!(n instanceof He))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const t=this.systemMessage?.content??"You are a helpful assistant.",r=this._tools.map(s=>s.name);$.info(`🧠 Agent ready with tools: ${r.join(", ")}`);const n=[AS({runLimit:this.maxSteps})],i=gS({model:this.llm,tools:this._tools,systemPrompt:t,middleware:n});return $.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),i}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(t){this.memoryEnabled&&this.conversationHistory.push(t)}getSystemMessage(){return this.systemMessage}setSystemMessage(t){this.systemMessage=new He(t),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(r=>!(r instanceof He)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),$.debug("Agent recreated with new system message"))}setDisallowedTools(t){this.disallowedTools=t,this.adapter=new Cn(this.disallowedTools),this._initialized&&$.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(t){const r=this.sanitizeMetadata(t);this.metadata={...this.metadata,...r},$.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(t){const r=this.sanitizeTags(t);this.tags=[...new Set([...this.tags,...r])],$.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(t){const r={};for(const[n,i]of Object.entries(t)){if(typeof n!="string"||n.length===0){$.warn(`Invalid metadata key: ${n}. Skipping.`);continue}const s=n.replace(/[^\w-]/g,"_");if(i==null)r[s]=i;else if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")r[s]=i;else if(Array.isArray(i)){const a=i.filter(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean");a.length>0&&(r[s]=a)}else if(typeof i=="object")try{const a=JSON.stringify(i);a.length>1e3?($.warn(`Metadata value for key '${s}' is too large. Truncating.`),r[s]=`${a.substring(0,1e3)}...`):r[s]=i}catch(a){$.warn(`Failed to serialize metadata value for key '${s}': ${a}. Skipping.`)}else $.warn(`Unsupported metadata value type for key '${s}': ${typeof i}. Skipping.`)}return r}sanitizeTags(t){return t.filter(r=>typeof r=="string"&&r.length>0).map(r=>r.replace(/[^\w:-]/g,"_")).filter(r=>r.length<=50)}getMCPServerInfo(){const t={};try{if(this.client){const r=this.client.getServerNames();t.mcp_servers_count=r.length,t.mcp_server_names=r;const n={};for(const i of r)try{const s=this.client.getServerConfig(i);if(s){let a="unknown";s.command?a="command":s.url?a="http":s.ws_url&&(a="websocket"),n[i]={type:a,has_args:!!s.args,has_env:!!s.env,has_headers:!!s.headers,url:s.url||null,command:s.command||null}}}catch(s){$.warn(`Failed to get config for server '${i}': ${s}`),n[i]={type:"error",error:"config_unavailable"}}t.mcp_server_configs=n}else this.connectors&&this.connectors.length>0&&(t.mcp_servers_count=this.connectors.length,t.mcp_server_names=this.connectors.map(r=>r.publicIdentifier),t.mcp_server_types=this.connectors.map(r=>r.constructor.name))}catch(r){$.warn(`Failed to collect MCP server info: ${r}`),t.error="collection_failed"}return t}_normalizeOutput(t){try{if(typeof t=="string")return t;if(t&&typeof t=="object"&&"content"in t)return this._normalizeOutput(t.content);if(Array.isArray(t)){const r=[];for(const n of t)if(typeof n=="object"&&n!==null)"text"in n&&typeof n.text=="string"?r.push(n.text):"content"in n?r.push(this._normalizeOutput(n.content)):r.push(String(n));else{const i=n&&typeof n=="object"&&"text"in n?n.text:null;if(typeof i=="string")r.push(i);else{const s=n&&typeof n=="object"&&"content"in n?n.content:n;r.push(this._normalizeOutput(s))}}return r.join("")}return String(t)}catch{return String(t)}}async _consumeAndReturn(t){for(;;){const{done:r,value:n}=await t.next();if(r)return n}}async run(t,r,n,i,s){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(t,r,n,i,s);const a=this.stream(t,r,n,i,s);return this._consumeAndReturn(a)}async*stream(t,r,n=!0,i,s){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(t,r,n,i,s);let a=!1;const o=Date.now();let c=!1,l=null,u=0;try{if(n&&!this._initialized?(await this.initialize(),a=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),a=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const y=this.serverManager.tools,g=new Set(y.map(b=>b.name)),_=new Set(this._tools.map(b=>b.name));(g.size!==_.size||[...g].some(b=>!_.has(b)))&&($.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...g].join(", ")}`),this._tools=y,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const d=i??this.conversationHistory,f=[];for(const y of d)(y instanceof je||y instanceof fe)&&f.push(y);const h=t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:t.replace(/\n/g," ");$.info(`💬 Received query: '${h}'`),$.info("🏁 Starting agent execution");const p=3;let m=0;const w=[...f,new je(t)];for(;m<=p;){const y={messages:w};let g=!1;const _=await this._agentExecutor.stream(y,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const b of _){for(const[A,P]of Object.entries(b))if($.debug(`📦 Node '${A}' output: ${JSON.stringify(P)}`),P&&typeof P=="object"&&"messages"in P){let x=P.messages;Array.isArray(x)||(x=[x]);for(const T of x)w.includes(T)||w.push(T);for(const T of x){if("tool_calls"in T&&Array.isArray(T.tool_calls)&&T.tool_calls.length>0)for(const R of T.tool_calls){const M=R.name||"unknown",U=R.args||{};this.toolsUsedNames.push(M),u++;let H=JSON.stringify(U);H.length>100&&(H=`${H.slice(0,97)}...`),$.info(`🔧 Tool call: ${M} with input: ${H}`),yield{action:{tool:M,toolInput:U,log:`Calling tool ${M}`},observation:""}}if(T instanceof Ae||T&&"type"in T&&T.type==="tool"){const R=T.content;let M=String(R);if(M.length>100&&(M=`${M.slice(0,97)}...`),M=M.replace(/\n/g," "),$.info(`📄 Tool result: ${M}`),this.useServerManager&&this.serverManager){const U=this.serverManager.tools,H=new Set(U.map(K=>K.name)),F=new Set(this._tools.map(K=>K.name));if(H.size!==F.size||[...H].some(K=>!F.has(K))){$.info(`🔄 Tools changed during execution. New tools: ${[...H].join(", ")}`),this._tools=U,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),g=!0,m++,$.info(`🔃 Restarting execution with updated tools (restart ${m}/${p})`);break}}}T instanceof fe&&!("tool_calls"in T&&Array.isArray(T.tool_calls)&&T.tool_calls.length>0)&&(l=this._normalizeOutput(T.content),$.info("✅ Agent finished with output"))}if(g)break}if(g)break}if(!g)break;if(m>p){$.warn(`⚠️ Max restarts (${p}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new je(t)),l&&this.addToHistory(new fe(l))),s&&l)try{$.info("🔧 Attempting structured output...");const y=await this._attemptStructuredOutput(l,this.llm,s);return this.memoryEnabled&&this.addToHistory(new fe(`Structured result: ${JSON.stringify(y)}`)),$.info("✅ Structured output successful"),c=!0,y}catch(y){throw $.error(`❌ Structured output failed: ${y}`),new Error(`Failed to generate structured output: ${y instanceof Error?y.message:String(y)}`)}return $.info(`🎉 Agent execution complete in ${((Date.now()-o)/1e3).toFixed(2)} seconds`),c=!0,l||"No output generated"}catch(d){throw $.error(`❌ Error running query: ${d}`),a&&n&&($.info("🧹 Cleaning up resources after error"),await this.close()),d}finally{const d=Date.now()-o;let f=0;this.client?f=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(f=this.connectors.length);const h=this.memoryEnabled?this.conversationHistory.length:0,p=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:t,success:c,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:f,serverIdentifiers:this.connectors.map(m=>m.publicIdentifier),totalToolsAvailable:p.length,toolsAvailableNames:p.map(m=>m.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:r??null,manageConnector:n,externalHistoryUsed:i!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:l||"",executionTimeMs:d,errorType:c?null:"execution_error",conversationHistoryLength:h}),n&&!this.client&&a&&($.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||($.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}$.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)$.info("🔄 Closing sessions through client"),await this.client.closeAllSessions(),this.sessions={};else for(const t of this.connectors)$.info("🔄 Disconnecting connector"),await t.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new Cn)}finally{this._initialized=!1,$.info("👋 Agent closed successfully")}}async*streamEvents(t,r,n=!0,i,s){let a=!1;const o=Date.now();let c=!1,l=0,u=0,d="";s&&(t=this._enhanceQueryWithSchema(t,s));try{n&&!this._initialized?(await this.initialize(),a=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),a=!0);const f=this._agentExecutor;if(!f)throw new Error("MCP agent failed to initialize");this.maxSteps=r??this.maxSteps;const h=t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:t.replace(/\n/g," ");$.info(`💬 Received query for streamEvents: '${h}'`),this.memoryEnabled&&($.info(`🔄 Adding user message to history: ${t}`),this.addToHistory(new je(t)));const p=i??this.conversationHistory,m=[];for(const g of p)g instanceof je||g instanceof fe||g instanceof Ae?m.push(g):$.info(`⚠️ Skipped message of type: ${g.constructor.name}`);const w=[...m,new je(t)];$.info("callbacks",this.callbacks);const y=f.streamEvents({messages:w},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const g of y)if(l++,!(!g||typeof g!="object")){if(g.event==="on_chat_model_stream"&&g.data?.chunk?.content&&(u+=g.data.chunk.content.length),g.event==="on_chat_model_stream"&&g.data?.chunk){const _=g.data.chunk;if(_.content){d||(d="");const b=this._normalizeOutput(_.content);d+=b,$.debug(`📝 Accumulated response length: ${d.length}`)}}if(yield g,g.event==="on_chain_end"&&g.data?.output&&!d){const _=g.data.output;Array.isArray(_)&&_.length>0&&_[0]?.text?d=_[0].text:typeof _=="string"?d=_:_&&typeof _=="object"&&"output"in _&&(d=_.output)}}if(s&&d){$.info("🔧 Attempting structured output conversion...");try{let g=!1,_=null,b=null;this._attemptStructuredOutput(d,this.llm,s).then(P=>(g=!0,_=P,P)).catch(P=>{throw g=!0,b=P,P});let A=0;for(;!g;)await new Promise(P=>setTimeout(P,2e3)),g||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(b)throw b;_&&(yield{event:"on_structured_output",data:{output:_}},this.memoryEnabled&&this.addToHistory(new fe(`Structured result: ${JSON.stringify(_)}`)),$.info("✅ Structured output successful"))}catch(g){$.warn(`⚠️ Structured output failed: ${g}`),yield{event:"on_structured_output_error",data:{error:g instanceof Error?g.message:String(g)}}}}else this.memoryEnabled&&d&&this.addToHistory(new fe(d));$.info(`🎉 StreamEvents complete - ${l} events emitted`),c=!0}catch(f){throw $.error(`❌ Error during streamEvents: ${f}`),a&&n&&($.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),f}finally{const f=Date.now()-o;let h=0;this.client?h=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(h=this.connectors.length);const p=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:t,success:c,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:h,serverIdentifiers:this.connectors.map(m=>m.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(m=>m.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:r??null,manageConnector:n,externalHistoryUsed:i!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:f,errorType:c?null:"streaming_error",conversationHistoryLength:p}),n&&!this.client&&a&&($.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(t,r,n){$.info(`🔄 Attempting structured output with schema: ${JSON.stringify(n,null,2)}`),$.info(`🔄 Raw result: ${JSON.stringify(t,null,2)}`);let i=null,s="";if($.debug(`🔄 Structured output requested, schema: ${JSON.stringify(lo(n),null,2)}`),r&&"withStructuredOutput"in r&&typeof r.withStructuredOutput=="function")i=r.withStructuredOutput(n);else if(r)i=r;else throw new Error("LLM is required for structured output");const a=lo(n),{$schema:o,additionalProperties:c,...l}=a;s=JSON.stringify(l,null,2),$.info(`🔄 Schema description: ${s}`);let u="";typeof t=="string"?u=t:t&&typeof t=="object"&&(u=JSON.stringify(t)),$.info("rawResult",t),u||(u=JSON.stringify(t));const d=3;let f="";for(let h=1;h<=d;h++){$.info(`🔄 Structured output attempt ${h}/${d}`);let p=`
577
- Please format the following information according to the EXACT schema specified below.
578
- You must use the exact field names and types as shown in the schema.
579
-
580
- Required schema format:
581
- ${s}
582
-
583
- Content to extract from:
584
- ${u}
585
-
586
- IMPORTANT:
587
- - Use ONLY the field names specified in the schema
588
- - Match the data types exactly (string, number, boolean, array, etc.)
589
- - Include ALL required fields
590
- - Return valid JSON that matches the schema structure exactly
591
- - For missing data: use null for nullable fields, omit optional fields entirely
592
- - Do NOT use empty strings ("") or zero (0) as placeholders for missing data
593
- `;h>1&&(p+=`
594
-
595
- PREVIOUS ATTEMPT FAILED with error: ${f}
596
- Please fix the issues mentioned above and ensure the output matches the schema exactly.
597
- `);try{$.info(`🔄 Structured output attempt ${h} - using streaming approach`);const m=u.length>300?`${u.slice(0,300)}...`:u;$.info(`🔄 Content being formatted (${u.length} chars): ${m}`),$.info(`🔄 Full format prompt (${p.length} chars):
598
- ${p}`);const w=await i.stream(p);let y=null,g=0;for await(const b of w){if(g++,$.info(`Chunk ${g}: ${JSON.stringify(b,null,2)}`),typeof b=="string")try{y=JSON.parse(b)}catch{$.warn(`🔄 Failed to parse string chunk as JSON: ${b}`)}else if(b&&typeof b=="object")y=b;else try{y=JSON.parse(String(b))}catch{$.warn(`🔄 Failed to parse chunk as JSON: ${b}`)}g%10===0&&$.info(`🔄 Structured output streaming: ${g} chunks`)}if($.info(`🔄 Structured result attempt ${h}: ${JSON.stringify(y,null,2)}`),!y)throw new Error("No structured result received from stream");const _=this._validateStructuredResult(y,n);return $.info(`✅ Structured output successful on attempt ${h}`),_}catch(m){if(f=m instanceof Error?m.message:String(m),$.warn(`⚠️ Structured output attempt ${h} failed: ${f}`),h===d)throw $.error(`❌ All ${d} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${d} attempts. Last error: ${f}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(t,r){try{const n=r.parse(t),i=r;if(i._def&&i._def.shape)for(const[s,a]of Object.entries(i._def.shape)){const o=a,c=o.isOptional?.()??o._def?.typeName==="ZodOptional",l=o.isNullable?.()??o._def?.typeName==="ZodNullable";if(!c&&!l){const u=n[s];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${s}' is missing or empty`)}}return n}catch(n){throw $.debug(`Validation details: ${n}`),n}}_enhanceQueryWithSchema(t,r){try{const n=lo(r),{$schema:i,additionalProperties:s,...a}=n,o=JSON.stringify(a,null,2);return`
599
- ${t}
600
-
601
- IMPORTANT: Your response must include sufficient information to populate the following structured output:
602
-
603
- ${o}
604
-
605
- Make sure you gather ALL the required information during your task execution.
606
- If any required information is missing, continue working to find it.
607
- `}catch(n){return $.warn(`Could not extract schema details: ${n}`),t}}},le(xi,"MCPAgent"),xi),Pi,LS=(Pi=class{connector;autoConnect;constructor(t,r=!0){this.connector=t,this.autoConnect=r}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}},le(Pi,"MCPSession"),Pi),ki,xh=(ki=class{client=null;connectionManager=null;toolsCache=null;connected=!1;opts;constructor(t={}){this.opts=t}async disconnect(){if(!this.connected){$.debug("Not connected to MCP implementation");return}$.debug("Disconnecting from MCP implementation"),await this.cleanupResources(),this.connected=!1,$.debug("Disconnected from MCP implementation")}get isClientConnected(){return this.client!=null}async initialize(t=this.opts.defaultRequestOptions??{}){if(!this.client)throw new Error("MCP client is not connected");$.debug("Caching server capabilities & tools");const r=this.client.getServerCapabilities(),n=await this.client.listTools(void 0,t);return this.toolsCache=n.tools??[],$.debug(`Fetched ${this.toolsCache.length} tools from server`),r}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized; call initialize() first");return this.toolsCache}async callTool(t,r,n){if(!this.client)throw new Error("MCP client is not connected");$.debug(`Calling tool '${t}' with args`,r);const i=await this.client.callTool({name:t,arguments:r},void 0,n);return $.debug(`Tool '${t}' returned`,i),i}async listResources(t,r){if(!this.client)throw new Error("MCP client is not connected");return $.debug("Listing resources",t?`with cursor: ${t}`:""),await this.client.listResources({cursor:t},r)}async listAllResources(t){if(!this.client)throw new Error("MCP client is not connected");$.debug("Listing all resources (with auto-pagination)");const r=[];let n;do{const i=await this.client.listResources({cursor:n},t);r.push(...i.resources||[]),n=i.nextCursor}while(n);return{resources:r}}async listResourceTemplates(t){if(!this.client)throw new Error("MCP client is not connected");return $.debug("Listing resource templates"),await this.client.listResourceTemplates(void 0,t)}async readResource(t,r){if(!this.client)throw new Error("MCP client is not connected");$.debug(`Reading resource ${t}`);const n=await this.client.readResource({uri:t},r);return{content:n.content,mimeType:n.mimeType}}async subscribeToResource(t,r){if(!this.client)throw new Error("MCP client is not connected");return $.debug(`Subscribing to resource: ${t}`),await this.client.subscribeResource({uri:t},r)}async unsubscribeFromResource(t,r){if(!this.client)throw new Error("MCP client is not connected");return $.debug(`Unsubscribing from resource: ${t}`),await this.client.unsubscribeResource({uri:t},r)}async listPrompts(){if(!this.client)throw new Error("MCP client is not connected");return $.debug("Listing prompt"),await this.client.listPrompts()}async getPrompt(t,r){if(!this.client)throw new Error("MCP client is not connected");return $.debug(`Getting prompt ${t}`),await this.client.getPrompt({name:t,arguments:r})}async request(t,r=null,n){if(!this.client)throw new Error("MCP client is not connected");return $.debug(`Sending raw request '${t}' with params`,r),await this.client.request({method:t,params:r??{}},void 0,n)}async cleanupResources(){const t=[];if(this.client)try{typeof this.client.close=="function"&&await this.client.close()}catch(r){const n=`Error closing client: ${r}`;$.warn(n),t.push(n)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(r){const n=`Error stopping connection manager: ${r}`;$.warn(n),t.push(n)}finally{this.connectionManager=null}this.toolsCache=null,t.length&&$.warn(`Resource cleanup finished with ${t.length} issue(s)`)}},le(ki,"BaseConnector"),ki),Ii,Ph=(Ii=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),$.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw new Error("Connection was not established");return this._connection}async stop(){if(this._task&&this._abortController){$.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?$.debug(`${this.constructor.name} task aborted successfully`):$.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,$.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(t=>this._readyResolver=t),this._donePromise=new Promise(t=>this._doneResolver=t),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){$.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),$.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,$.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){$.warn(`Error closing connection in ${this.constructor.name}: ${t}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((t,r)=>{if(!this._abortController)return;const n=this._abortController.signal;if(n.aborted){t();return}const i=le(()=>{n.removeEventListener("abort",i),t()},"onAbort");n.addEventListener("abort",i)})}},le(Ii,"ConnectionManager"),Ii),Mi,j2=(Mi=class extends Ph{url;opts;_transport=null;constructor(t,r){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=r}async establishConnection(){return this._transport=new JS(this.url,this.opts),$.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(r){$.warn(`Error closing SSE transport: ${r}`)}finally{this._transport=null}}},le(Mi,"SseConnectionManager"),Mi),Ri,D2=(Ri=class extends Ph{url;opts;_transport=null;constructor(t,r){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=r}async establishConnection(){return this._transport=new WS(this.url,this.opts),$.debug(`${this.constructor.name} created successfully`),this._transport}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(r){$.warn(`Error closing Streamable HTTP transport: ${r}`)}finally{this._transport=null}}get sessionId(){return this._transport?.sessionId}},le(Ri,"StreamableHttpConnectionManager"),Ri),Ni,Xf=(Ni=class extends xh{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;transportType=null;constructor(t,r={}){super(r),this.baseUrl=t.replace(/\/$/,""),this.headers={...r.headers??{}},r.authToken&&(this.headers.Authorization=`Bearer ${r.authToken}`),this.timeout=r.timeout??3e4,this.sseReadTimeout=r.sseReadTimeout??3e5,this.clientInfo=r.clientInfo??{name:"http-connector",version:"1.0.0"},this.preferSse=r.preferSse??!1}async connect(){if(this.connected){$.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){$.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}$.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{$.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),$.info("✅ Successfully connected via streamable HTTP")}catch(r){let n="Unknown error";if(r instanceof VS)r.code===400&&r.message.includes("Missing session ID")?(n="Server requires session ID (FastMCP compatibility) - using SSE transport",$.warn(`⚠️ ${n}`)):r.code===404||r.code===405?(n=`Server returned ${r.code} - server likely doesn't support streamable HTTP`,$.debug(n)):(n=`Server returned ${r.code}: ${r.message}`,$.debug(n));else if(r instanceof Error){const i=r.toString(),s=r.message||"";i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||s.includes("FastMCP session ID error")?(n="Server requires session ID (FastMCP compatibility) - using SSE transport",$.warn(`⚠️ ${n}`)):i.includes("405 Method Not Allowed")||i.includes("404 Not Found")?(n="Server doesn't support streamable HTTP (405/404)",$.debug(n)):(n=`Streamable HTTP failed: ${r.message}`,$.debug(n))}$.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(i){throw $.error("Failed to connect with both transports:"),$.error(` Streamable HTTP: ${n}`),$.error(` SSE: ${i}`),await this.cleanupResources(),new Error("Could not connect to server with any available transport")}}}async connectWithStreamableHttp(t){try{this.connectionManager=new D2(t,{requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});const r=await this.connectionManager.start();this.client=new Ih(this.clientInfo,this.opts.clientOptions);try{await this.client.connect(r)}catch(n){if(n instanceof Error){const i=n.message||n.toString();if(i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")){const s=new Error(`FastMCP session ID error: ${i}`);throw s.cause=n,s}}throw n}this.connected=!0,this.transportType="streamable-http",$.debug(`Successfully connected to MCP implementation via streamable HTTP: ${t}`)}catch(r){throw await this.cleanupResources(),r}}async connectWithSse(t){try{this.connectionManager=new j2(t,{requestInit:{headers:this.headers}});const r=await this.connectionManager.start();this.client=new Ih(this.clientInfo,this.opts.clientOptions),await this.client.connect(r),this.connected=!0,this.transportType="sse",$.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${t}`)}catch(r){throw await this.cleanupResources(),r}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown"}}getTransportType(){return this.transportType}},le(Ni,"HttpConnector"),Ni),$i,F2=($i=class extends Ph{url;headers;_ws=null;constructor(t,r={}){super(),this.url=t,this.headers=r}async establishConnection(){return $.debug(`Connecting to WebSocket: ${this.url}`),new Promise((t,r)=>{const n=new Dy(this.url,{headers:this.headers});this._ws=n;const i=le(()=>{a(),$.debug("WebSocket connected successfully"),t(n)},"onOpen"),s=le(o=>{a(),$.error(`Failed to connect to WebSocket: ${o}`),r(o)},"onError"),a=le(()=>{n.off("open",i),n.off("error",s)},"cleanup");n.on("open",i),n.on("error",s)})}async closeConnection(t){return $.debug("Closing WebSocket connection"),new Promise(r=>{const n=le(()=>{t.off("close",n),this._ws=null,r()},"onClose");if(t.readyState===Dy.CLOSED){n();return}t.on("close",n);try{t.close()}catch(i){$.warn(`Error closing WebSocket connection: ${i}`),n()}})}},le($i,"WebSocketConnectionManager"),$i),Li,jS=(Li=class extends xh{url;headers;connectionManager=null;ws=null;receiverTask=null;pending=new Map;toolsCache=null;constructor(t,r={}){super(),this.url=t,this.headers={...r.headers??{}},r.authToken&&(this.headers.Authorization=`Bearer ${r.authToken}`)}async connect(){if(this.connected){$.debug("Already connected to MCP implementation");return}$.debug(`Connecting via WebSocket: ${this.url}`);try{this.connectionManager=new F2(this.url,this.headers),this.ws=await this.connectionManager.start(),this.receiverTask=this.receiveLoop(),this.connected=!0,$.debug("WebSocket connected successfully")}catch(t){throw $.error(`Failed to connect: ${t}`),await this.cleanupResources(),t}}async disconnect(){if(!this.connected){$.debug("Not connected to MCP implementation");return}$.debug("Disconnecting …"),await this.cleanupResources(),this.connected=!1}sendRequest(t,r=null){if(!this.ws)throw new Error("WebSocket is not connected");const n=Wy(),i=JSON.stringify({id:n,method:t,params:r??{}});return new Promise((s,a)=>{this.pending.set(n,{resolve:s,reject:a}),this.ws.send(i,o=>{o&&(this.pending.delete(n),a(o))})})}async receiveLoop(){if(!this.ws)return;const t=this.ws,r=le(n=>{let i;try{i=JSON.parse(n.data??n)}catch(a){$.warn("Received non‑JSON frame",a);return}const s=i.id;if(s&&this.pending.has(s)){const{resolve:a,reject:o}=this.pending.get(s);this.pending.delete(s),"result"in i?a(i.result):"error"in i&&o(i.error)}else $.debug("Received unsolicited message",i)},"onMessage");return t.addEventListener?t.addEventListener("message",r):t.on("message",r),new Promise(n=>{const i=le(()=>{t.removeEventListener?t.removeEventListener("message",r):t.off("message",r),this.rejectAll(new Error("WebSocket closed")),n()},"onClose");t.addEventListener?t.addEventListener("close",i):t.on("close",i)})}rejectAll(t){for(const{reject:r}of this.pending.values())r(t);this.pending.clear()}async initialize(){$.debug("Initializing MCP session over WebSocket");const t=await this.sendRequest("initialize"),r=await this.listTools();return this.toolsCache=r.map(n=>n),$.debug(`Initialized with ${this.toolsCache.length} tools`),t}async listTools(){return(await this.sendRequest("tools/list")).tools??[]}async callTool(t,r){return await this.sendRequest("tools/call",{name:t,arguments:r})}async listResources(){const t=await this.sendRequest("resources/list");return{resources:Array.isArray(t)?t:[]}}async readResource(t){const r=await this.sendRequest("resources/read",{uri:t});return{content:r.content,mimeType:r.mimeType}}async request(t,r=null){return await this.sendRequest(t,r)}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized");return this.toolsCache}async cleanupResources(){this.receiverTask&&await this.receiverTask.catch(()=>{}),this.receiverTask=null,this.rejectAll(new Error("WebSocket disconnected")),this.connectionManager&&(await this.connectionManager.stop(),this.connectionManager=null,this.ws=null),this.toolsCache=null}get publicIdentifier(){return{type:"websocket",url:this.url}}},le(Li,"WebSocketConnector"),Li);async function*DS(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const r=t.data.chunk.text;typeof r=="string"&&r.length>0&&(yield r)}}le(DS,"streamEventsToAISDK");function FS(e){return new ReadableStream({async start(t){try{for await(const r of e)t.enqueue(r);t.close()}catch(r){t.error(r)}}})}le(FS,"createReadableStreamFromGenerator");async function*US(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const r=t.data.chunk.text;typeof r=="string"&&r.length>0&&(yield r)}break;case"on_tool_start":yield`
608
- 🔧 Using tool: ${t.name}
609
- `;break;case"on_tool_end":yield`
610
- ✅ Tool completed: ${t.name}
611
- `;break}}le(US,"streamEventsToAISDKWithTools");var ji,U2=(ji=class{config={};sessions={};activeSessions=[];constructor(t){t&&(this.config=t)}static fromDict(t){throw new Error("fromDict must be implemented by concrete class")}addServer(t,r){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[t]=r}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(r=>r!==t))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(t){return this.config.mcpServers?.[t]}getConfig(){return this.config??{}}async createSession(t,r=!0){const n=this.config.mcpServers??{};if(Object.keys(n).length===0&&$.warn("No MCP servers defined in config"),!n[t])throw new Error(`Server '${t}' not found in config`);const i=this.createConnectorFromConfig(n[t]),s=new LS(i);return r&&await s.initialize(),this.sessions[t]=s,this.activeSessions.includes(t)||this.activeSessions.push(t),s}async createAllSessions(t=!0){const r=this.config.mcpServers??{};Object.keys(r).length===0&&$.warn("No MCP servers defined in config");for(const n of Object.keys(r))await this.createSession(n,t);return this.sessions}getSession(t){const r=this.sessions[t];return r||null}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const r=this.sessions[t];if(!r){$.warn(`No session exists for server ${t}, nothing to close`);return}try{$.debug(`Closing session for server ${t}`),await r.disconnect()}catch(n){$.error(`Error closing session for server '${t}': ${n}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(n=>n!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),r=[];for(const n of t)try{$.debug(`Closing session for server ${n}`),await this.closeSession(n)}catch(i){const s=`Failed to close session for server '${n}': ${i}`;$.error(s),r.push(s)}r.length?$.error(`Encountered ${r.length} errors while closing sessions`):$.debug("All sessions closed successfully")}},le(ji,"BaseMCPClient"),ji),$n,B2=($n=class extends U2{constructor(t){super(t)}static fromDict(t){return new $n(t)}createConnectorFromConfig(t){const{url:r,transport:n,headers:i,authToken:s}=t;if(!r)throw new Error("Server URL is required");const a={headers:i,authToken:s};return n==="websocket"||r.startsWith("ws://")||r.startsWith("wss://")?new jS(r,a):n==="http"||r.startsWith("http://")||r.startsWith("https://")?new Xf(r,a):new Xf(r,a)}},le($n,"BrowserMCPClient"),$n);const rD=Object.freeze(Object.defineProperty({__proto__:null,AIMessage:fe,BaseAdapter:OS,BaseConnector:xh,BaseMessage:bt,BrowserOAuthClientProvider:KS,HttpConnector:Xf,HumanMessage:je,LangChainAdapter:Cn,Logger:No,MCPAgent:L2,MCPClient:B2,MCPSession:LS,ObservabilityManager:Kf,RemoteAgent:MS,SystemMessage:He,ToolMessage:Ae,WebSocketConnector:jS,createReadableStreamFromGenerator:FS,logger:$,onMcpAuthorization:ZS,streamEventsToAISDK:DS,streamEventsToAISDKWithTools:US},Symbol.toStringTag,{value:"Module"}));export{fe as A,ns as B,zn as C,fc as F,je as H,He as S,Ae as T,K2 as a,bt as b,qt as c,rD as d,N_ as i,J2 as l,Nt as m};