@mcp-use/inspector 0.4.9-canary.7 → 0.4.10-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.
- package/dist/client/assets/{browser-Cv1pVOBI.js → browser-Y5YX6R0e.js} +4 -4
- package/dist/client/assets/{chunk-VL2OQCWN-Dagm7hXn.js → chunk-VL2OQCWN-DaETIuKw.js} +1 -1
- package/dist/client/assets/{embeddings-DfwDnoJu.js → embeddings-DZfzFZKi.js} +1 -1
- package/dist/client/assets/{index-WftRH2DX.js → index-BAM9P4Uc.js} +1 -1
- package/dist/client/assets/{index-CI80UkuW.js → index-BqTUQboh.js} +3 -3
- package/dist/client/assets/{index-B7_0VDBC.js → index-CJMvA7xZ.js} +1 -1
- package/dist/client/assets/{index-CUQTjqHW.js → index-DW4-Iver.js} +1 -1
- package/dist/client/assets/{index-D9prgrkP.js → index-gpTuSssg.js} +1 -1
- package/dist/client/assets/{index-rTnUeY2h.js → index-qwzg_gy0.js} +1 -1
- package/dist/client/assets/{index-DWwivu0I.js → index-wxWaBB5s.js} +1 -1
- package/dist/client/assets/langfuse-6AJGHMAV-s-Hx_MjO.js +1 -0
- package/dist/client/index.html +2 -2
- package/package.json +6 -6
- package/dist/client/assets/langfuse-6AJGHMAV-l0zIYhwv.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
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-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-gpTuSssg.js","assets/index-qwzg_gy0.js","assets/index-BqTUQboh.js","assets/index-Ba21hizt.css","assets/chunk-VL2OQCWN-DaETIuKw.js","assets/v4-BKrj-4V8.js","assets/langfuse-6AJGHMAV-s-Hx_MjO.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-BqTUQboh.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-DaETIuKw.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
3
|
Found: `.concat(w.toString().split(`
|
|
4
4
|
`)[0],`
|
|
5
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(`
|
|
@@ -40,7 +40,7 @@ Found: ${r.toString().split(`
|
|
|
40
40
|
`)[0]}
|
|
41
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
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-D9prgrkP.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-rTnUeY2h.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(`
|
|
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-gpTuSssg.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-qwzg_gy0.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
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
45
|
Left ${typeof e}
|
|
46
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.
|
|
@@ -525,7 +525,7 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
|
|
|
525
525
|
${a.map(c=>c.name).join(`
|
|
526
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
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-l0zIYhwv.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-l0zIYhwv.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:
|
|
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-s-Hx_MjO.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-s-Hx_MjO.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
529
|
• Invalid agent configuration (LLM model, system prompt)
|
|
530
530
|
• Missing or invalid MCP server configurations
|
|
531
531
|
• Network connectivity issues with MCP servers
|