@mcp-use/inspector 0.12.6 → 0.13.0-canary.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cli.js +11 -3
  2. package/dist/client/assets/browser-C4F-osqk.js +501 -0
  3. package/dist/client/assets/{display-A5IEINAP-CKX4vEt9.js → display-A5IEINAP-H3Q2-YX2.js} +2 -2
  4. package/dist/client/assets/{embeddings-_gd8Ybda.js → embeddings-7yD5FP5W.js} +1 -1
  5. package/dist/client/assets/{index-C9gKZsxC.js → index-BCGobKCz.js} +1 -1
  6. package/dist/client/assets/{index-36UnVi7B.js → index-BKkxSJZC.js} +1 -1
  7. package/dist/client/assets/{index-BOguzv_X.js → index-BVRlDOe5.js} +1 -1
  8. package/dist/client/assets/{index-B8valPom.js → index-Baw2JzBf.js} +1 -1
  9. package/dist/client/assets/{index-BKbSGlCI.js → index-Bdz9XpGY.js} +1 -1
  10. package/dist/client/assets/{index-Bftz7hAD.js → index-CVHM2qPt.js} +1 -1
  11. package/dist/client/assets/index-CcXsZ4ms.js +1707 -0
  12. package/dist/client/assets/index-Cfg3RZ-z.js +7 -0
  13. package/dist/client/assets/index-D-zrynRj.css +1 -0
  14. package/dist/client/assets/{index-BZVDzI3u.js → index-DxljWnJH.js} +2 -2
  15. package/dist/client/assets/langfuse-74RGPTAH-CzkBGeHI.js +1 -0
  16. package/dist/client/assets/path-BzkNY3AW.js +1 -0
  17. package/dist/client/assets/path-MNZaYwxc.js +1 -0
  18. package/dist/client/assets/{winston-BFsqNemi.js → winston-mndsjLRM.js} +15 -15
  19. package/dist/client/index.html +3 -3
  20. package/dist/server/{chunk-V5FEV5SU.js → chunk-67ROKQZG.js} +36 -4
  21. package/dist/server/{chunk-PBQJCPZX.js → chunk-OS2WTNLR.js} +3 -3
  22. package/dist/server/{chunk-XU7SXB3C.js → chunk-WLIY2SQG.js} +1 -1
  23. package/dist/server/{chunk-LNMQYGXR.js → chunk-YLX7JQDX.js} +1 -1
  24. package/dist/server/{chunk-KW44WB52.js → chunk-Z5QIR3IS.js} +11 -3
  25. package/dist/server/cli.js +4 -4
  26. package/dist/server/index.js +5 -5
  27. package/dist/server/middleware.js +5 -5
  28. package/dist/server/server.js +4 -4
  29. package/dist/server/shared-routes.js +2 -2
  30. package/dist/server/shared-static.js +2 -2
  31. package/dist/server/shared-utils-browser.d.ts +1 -0
  32. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  33. package/dist/server/shared-utils-browser.js +1 -1
  34. package/dist/server/shared-utils.d.ts +1 -0
  35. package/dist/server/shared-utils.d.ts.map +1 -1
  36. package/dist/server/shared-utils.js +1 -1
  37. package/package.json +13 -7
  38. package/dist/client/assets/__vite-browser-external-D7Ct-6yo.js +0 -1
  39. package/dist/client/assets/browser-Bok5DFD8.js +0 -408
  40. package/dist/client/assets/index-beDRbW3x.css +0 -1
  41. package/dist/client/assets/index-ubmd7JRV.js +0 -1676
  42. package/dist/client/assets/index-ulBkaOKp.js +0 -40
  43. package/dist/client/assets/path-C2bN6h38.js +0 -1
@@ -0,0 +1,501 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-74RGPTAH-CzkBGeHI.js","assets/index-CcXsZ4ms.js","assets/index-D-zrynRj.css","assets/path-MNZaYwxc.js","assets/path-BzkNY3AW.js","assets/index-DxljWnJH.js","assets/index-BCGobKCz.js","assets/index-Baw2JzBf.js","assets/index-DRz5BQNA.js","assets/embeddings-7yD5FP5W.js","assets/display-A5IEINAP-H3Q2-YX2.js"])))=>i.map(i=>d[i]);
2
+ import{_ as A,bj as eo,bg as Pl,bk as Ol,bl as Nl,bm as to,bn as _s,bo as m,bp as Fi,bq as Di,a as Jt,br as Il,bs as Lo,bt as $l,bu as we,bv as Nr,bw as Ee,bx as zr,by as Hr,bz as Rl,bA as jl,bB as Ll,bC as Fl,bD as Dl,bE as Ul,p as Ui,bF as Wn,bG as Fo,bh as qn,bH as Vl,bI as Bl,bJ as zl,bK as Hl,bL as Wl,bM as Do}from"./index-CcXsZ4ms.js";import gn,{readFileSync as ql}from"fs";import{a as Kl}from"./path-MNZaYwxc.js";import Gl from"child_process";import{r as Vi}from"./path-BzkNY3AW.js";import Ir from"node:process";import{PassThrough as Jl}from"node:stream";import{D as Kn,L as Bi,S as $r,t as Yl,o as Xl,l as Zl,a as zi,T as Ql,b as eu}from"./index-DxljWnJH.js";import{h as In,s as tu,g as Hi,B as nu,k as ru,l as su,I as ou,C as iu,m as au,t as cu,n as lu,o as uu,p as hu,q as du,r as fu,u as pu,v as mu,w as gu,x as yu,y as wu,R as vu,z as _u,a as bu}from"./index-Baw2JzBf.js";import{aO as Su,aP as no,aQ as Cu,at as Pe,e as dn,aR as Eu,aS as bn,a0 as fe,x as ct,aT as Wi,g as Tu,aU as bs,_ as J,ag as an,ae as pe,z as N,ad as Q,d as xu,C as ku,aV as Mu,p as Uo,aA as qi,aW as be,ai as Sn,aX as yn,E as Ki,y as Re,aY as ro,B as Ss,D as Yt,am as Xt,aZ as Au,a_ as Pu,a$ as Ou,b0 as Nu,b1 as Iu,b2 as $u,b3 as Ru,b4 as ju,b5 as Lu,b6 as Fu,b7 as Du,b8 as Uu,b9 as Vu,ba as Bu,bb as zu,bc as Hu,bd as Wu,K as qu,be as Ku,bf as Gu,bg as Ju,t as Ue,r as wn,m as Fe,L as nt,aq as Zt,bh as Yu,F as Xu,aB as Vo,ar as Zu,bi as Bo,bj as zo,ab as so,aa as Ho,a9 as Cs,ac as Qu,S as eh,a5 as oo,a8 as Ye,bk as fr,o as z,bl as ce,bm as th,bn as Ne,bo as xt,bp as nh,bq as io,l as U,a6 as rh,i as sh,T as oh,br as pr,bs as ze,bt as V,bu as Gi,s as ne,a7 as ih,bv as Gn,bw as Ji,bx as Qt,by as Cn,bz as mr,bA as gr,bB as ah,aK as ch,aI as lh,aH as uh,bC as hh}from"./index-BCGobKCz.js";import{E as Yi,c as dh,e as fh}from"./embeddings-7yD5FP5W.js";var Wr,Fn,qr=0,Kr=0;function ph(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Wr),i==null&&(i=Fn)),o==null||i==null){var a=t.random||(t.rng||Su)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Wr&&!t._v6&&(o[0]|=1,Wr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Fn===void 0&&!t._v6&&(Fn=i))}var c=t.msecs!==void 0?t.msecs:Date.now(),l=t.nsecs!==void 0?t.nsecs:Kr+1,u=c-qr+(l-Kr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||c>qr)&&t.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");qr=c,Kr=l,Fn=i,c+=122192928e5;var h=((c&268435455)*1e4+l)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=c/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||no(s)}function mh(t){var e=typeof t=="string"?Cu(t):t,n=gh(e);return typeof t=="string"?no(n):n}function gh(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function Wo(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function qo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Wo(Object(n),!0).forEach(function(r){yh(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Wo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function yh(t,e,n){return(e=wh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function wh(t){var e=vh(t,"string");return typeof e=="symbol"?e:e+""}function vh(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function _h(t={},e,n=0){var r=ph(qo(qo({},t),{},{_v6:!0}),new Uint8Array(16));return r=mh(r),no(r)}async function*Xi(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}A(Xi,"streamEventsToAISDK");function Zi(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}A(Zi,"createReadableStreamFromGenerator");async function*Qi(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
+ 🔧 Using tool: ${e.name}
4
+ `;break;case"on_tool_end":yield`
5
+ ✅ Tool completed: ${e.name}
6
+ `;break}}A(Qi,"streamEventsToAISDKWithTools");var Pt,bh=(Pt=class extends eo{mcpClient;_tools;constructor(e){super(),this.mcpClient=e,this.connected=!0,this._tools=this._createToolsList()}async connect(){this.connected=!0}async disconnect(){this.connected=!1}get publicIdentifier(){return{name:"code_mode",version:"1.0.0"}}_createToolsList(){return[{name:"execute_code",description:"Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.",inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces"},timeout:{type:"number",description:"Execution timeout in milliseconds",default:3e4}},required:["code"]}},{name:"search_tools",description:"Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query to filter tools by name or description",default:""},detail_level:{type:"string",description:"Detail level: 'names', 'descriptions', or 'full'",enum:["names","descriptions","full"],default:"full"}}}}]}get tools(){return this._tools}async initialize(){return this.toolsCache=this._tools,{capabilities:{},version:"1.0.0"}}async callTool(e,n){if(e==="execute_code"){const r=n.code,s=n.timeout||3e4,o=await this.mcpClient.executeCode(r,s);return{content:[{type:"text",text:JSON.stringify(o)}]}}else if(e==="search_tools"){const r=n.query||"",s=n.detail_level,o=await this.mcpClient.searchTools(r,s&&s in["names","descriptions","full"]?s:"full");return{content:[{type:"text",text:JSON.stringify(o)}]}}throw new Error(`Unknown tool: ${e}`)}},A(Pt,"CodeModeConnector"),Pt);const Sh={},Ch="browser",Eh="v18.0.0",Th={node:"18.0.0"},xh=()=>"/",kh=(t,...e)=>queueMicrotask(()=>t(...e)),Mh=!0,Ko={env:Sh,platform:Ch,version:Eh,versions:Th,cwd:xh,nextTick:kh,browser:Mh};var st={exports:{}},Gr,Go;function Ah(){if(Go)return Gr;Go=1;var t={};Gr=s,s.sync=o;var e=gn;function n(i,a){var c=a.pathExt!==void 0?a.pathExt:t.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&i.substr(-u.length).toLowerCase()===u)return!0}return!1}function r(i,a,c){return!i.isSymbolicLink()&&!i.isFile()?!1:n(a,c)}function s(i,a,c){e.stat(i,function(l,u){c(l,l?!1:r(u,i,a))})}function o(i,a){return r(e.statSync(i),i,a)}return Gr}var Jr,Jo;function Ph(){if(Jo)return Jr;Jo=1,Jr=e,e.sync=n;var t=gn;function e(o,i,a){t.stat(o,function(c,l){a(c,c?!1:r(l,i))})}function n(o,i){return r(t.statSync(o),i)}function r(o,i){return o.isFile()&&s(o,i)}function s(o,i){var a=o.mode,c=o.uid,l=o.gid,u=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),h=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),f=parseInt("010",8),g=parseInt("001",8),p=d|f,b=a&g||a&f&&l===h||a&d&&c===u||a&p&&u===0;return b}return Jr}var Yr,Yo;function Oh(){if(Yo)return Yr;Yo=1;var t;globalThis.TESTING_WINDOWS?t=Ah():t=Ph(),Yr=e,e.sync=n;function e(r,s,o){if(typeof s=="function"&&(o=s,s={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,a){e(r,s||{},function(c,l){c?a(c):i(l)})})}t(r,s||{},function(i,a){i&&(i.code==="EACCES"||s&&s.ignoreErrors)&&(i=null,a=!1),o(i,a)})}function n(r,s){try{return t.sync(r,s||{})}catch(o){if(s&&s.ignoreErrors||o.code==="EACCES")return!1;throw o}}return Yr}var Xr,Xo;function Nh(){if(Xo)return Xr;Xo=1;var t={};const e=t.OSTYPE==="cygwin"||t.OSTYPE==="msys",n=Vi,r=e?";":":",s=Oh(),o=l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),i=(l,u)=>{const h=u.colon||r,d=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(u.path||t.PATH||"").split(h)],f=e?u.pathExt||t.PATHEXT||".EXE;.CMD;.BAT;.COM":"",g=e?f.split(h):[""];return e&&l.indexOf(".")!==-1&&g[0]!==""&&g.unshift(""),{pathEnv:d,pathExt:g,pathExtExe:f}},a=(l,u,h)=>{typeof u=="function"&&(h=u,u={}),u||(u={});const{pathEnv:d,pathExt:f,pathExtExe:g}=i(l,u),p=[],b=y=>new Promise((_,w)=>{if(y===d.length)return u.all&&p.length?_(p):w(o(l));const E=d[y],T=/^".*"$/.test(E)?E.slice(1,-1):E,v=n.join(T,l),S=!T&&/^\.[\\\/]/.test(l)?l.slice(0,2)+v:v;_(C(S,y,0))}),C=(y,_,w)=>new Promise((E,T)=>{if(w===f.length)return E(b(_+1));const v=f[w];s(y+v,{pathExt:g},(S,x)=>{if(!S&&x)if(u.all)p.push(y+v);else return E(y+v);return E(C(y,_,w+1))})});return h?b(0).then(y=>h(null,y),h):b(0)},c=(l,u)=>{u=u||{};const{pathEnv:h,pathExt:d,pathExtExe:f}=i(l,u),g=[];for(let p=0;p<h.length;p++){const b=h[p],C=/^".*"$/.test(b)?b.slice(1,-1):b,y=n.join(C,l),_=!C&&/^\.[\\\/]/.test(l)?l.slice(0,2)+y:y;for(let w=0;w<d.length;w++){const E=_+d[w];try{if(s.sync(E,{pathExt:f}))if(u.all)g.push(E);else return E}catch{}}}if(u.all&&g.length)return g;if(u.nothrow)return null;throw o(l)};return Xr=a,a.sync=c,Xr}var Dn={exports:{}},Zo;function Ih(){if(Zo)return Dn.exports;Zo=1;var t={};const e=(n={})=>{const r=n.env||t;return(n.platform||"browser")!=="win32"?"PATH":Object.keys(r).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};return Dn.exports=e,Dn.exports.default=e,Dn.exports}var Zr,Qo;function $h(){if(Qo)return Zr;Qo=1;var t={};const e=Vi,n=Nh(),r=Ih();function s(i,a){const c=i.options.env||t,l=process.cwd(),u=i.options.cwd!=null,h=u&&process.chdir!==void 0&&!process.chdir.disabled;if(h)try{process.chdir(i.options.cwd)}catch{}let d;try{d=n.sync(i.command,{path:c[r({env:c})],pathExt:a?e.delimiter:void 0})}catch{}finally{h&&process.chdir(l)}return d&&(d=e.resolve(u?i.options.cwd:"",d)),d}function o(i){return s(i)||s(i,!0)}return Zr=o,Zr}var Qr,ei;function Rh(){if(ei)return Qr;ei=1,$h();function t(n){return n}function e(n,r,s){r&&!Array.isArray(r)&&(s=r,r=null),r=r?r.slice(0):[],s=Object.assign({},s);const o={command:n,args:r,options:s,file:void 0,original:{command:n,args:r}};return s.shell?o:o}return Qr=e,Qr}var es,ti;function jh(){if(ti)return es;ti=1;function t(s,o){return Object.assign(new Error(`${o} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${s.command}`,path:s.command,spawnargs:s.args})}function e(s,o){}function n(s,o){return null}function r(s,o){return null}return es={hookChildProcess:e,verifyENOENT:n,verifyENOENTSync:r,notFoundError:t},es}var ni;function Lh(){if(ni)return st.exports;ni=1;const t=Gl,e=Rh(),n=jh();function r(o,i,a){const c=e(o,i,a),l=t.spawn(c.command,c.args,c.options);return n.hookChildProcess(l,c),l}function s(o,i,a){const c=e(o,i,a),l=t.spawnSync(c.command,c.args,c.options);return l.error=l.error||n.verifyENOENTSync(l.status,c),l}return st.exports=r,st.exports.spawn=r,st.exports.sync=s,st.exports._parse=e,st.exports._enoent=n,st.exports}var Fh=Lh();const Dh=Pl(Fh);class Uh{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
7
+ `);if(e===-1)return null;const n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Vh(n)}clear(){this._buffer=void 0}}function Vh(t){return Ol.parse(JSON.parse(t))}function Bh(t){return JSON.stringify(t)+`
8
+ `}const zh=Ir.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Hh(){const t={};for(const e of zh){const n=Ir.env[e];n!==void 0&&(n.startsWith("()")||(t[e]=n))}return t}class Wh{constructor(e){this._readBuffer=new Uh,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Jl)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,n)=>{var r,s,o,i,a;this._process=Dh(this._serverParams.command,(r=this._serverParams.args)!==null&&r!==void 0?r:[],{env:{...Hh(),...this._serverParams.env},stdio:["pipe","pipe",(s=this._serverParams.stderr)!==null&&s!==void 0?s:"inherit"],shell:!1,windowsHide:Ir.platform==="win32"&&qh(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var l;n(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var l;this._process=void 0,(l=this.onclose)===null||l===void 0||l.call(this)}),(o=this._process.stdin)===null||o===void 0||o.on("error",c=>{var l;(l=this.onerror)===null||l===void 0||l.call(this,c)}),(i=this._process.stdout)===null||i===void 0||i.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(a=this._process.stdout)===null||a===void 0||a.on("error",c=>{var l;(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,n;return this._stderrStream?this._stderrStream:(n=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&n!==void 0?n:null}get pid(){var e,n;return(n=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&n!==void 0?n:null}processReadBuffer(){for(var e,n;;)try{const r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(n=this.onerror)===null||n===void 0||n.call(this,r)}}async close(){var e;if(this._process){const n=this._process;this._process=void 0;const r=new Promise(s=>{n.once("close",()=>{s()})});try{(e=n.stdin)===null||e===void 0||e.end()}catch{}if(await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())]),n.exitCode===null){try{n.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())])}if(n.exitCode===null)try{n.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(n=>{var r;if(!(!((r=this._process)===null||r===void 0)&&r.stdin))throw new Error("Not connected");const s=Bh(e);this._process.stdin.write(s)?n():this._process.stdin.once("drain",n)})}}function qh(){return"type"in Ir}var Kh={},Ot,ao=(Ot=class{client;_connecting=!1;constructor(e){this.client=e}async ensureServersConnected(){const e=this.client.getServerNames(),n=Object.keys(this.client.getAllActiveSessions()),r=e.filter(s=>!n.includes(s));if(r.length>0&&!this._connecting){this._connecting=!0;try{m.debug(`Connecting to configured servers for code execution: ${r.join(", ")}`),await this.client.createAllSessions()}finally{this._connecting=!1}}else if(r.length>0&&this._connecting){m.debug("Waiting for ongoing server connection...");const s=Date.now();for(;this._connecting&&Date.now()-s<5e3;)await new Promise(o=>setTimeout(o,100))}}getToolNamespaces(){const e=[],n=this.client.getAllActiveSessions();for(const[r,s]of Object.entries(n))if(r!=="code_mode")try{const o=s.connector;let i;try{i=o.tools}catch(a){m.warn(`Tools not available for server ${r}: ${a}`);continue}if(!i||i.length===0)continue;e.push({serverName:r,tools:i,session:s})}catch(o){m.warn(`Failed to load tools for server ${r}: ${o}`)}return e}createSearchToolsFunction(){return async(e="",n="full")=>{const r=[],s=new Set,o=e.toLowerCase(),i=this.client.getAllActiveSessions();for(const[c,l]of Object.entries(i))if(c!=="code_mode")try{const u=l.connector.tools;u&&u.length>0&&s.add(c);for(const h of u)n==="names"?r.push({name:h.name,server:c}):n==="descriptions"?r.push({name:h.name,server:c,description:h.description}):r.push({name:h.name,server:c,description:h.description,input_schema:h.inputSchema})}catch(u){m.warn(`Failed to search tools in server ${c}: ${u}`)}let a=r;return e&&(a=r.filter(c=>{const l=c.name.toLowerCase().includes(o),u=c.description?.toLowerCase().includes(o),h=c.server.toLowerCase().includes(o);return l||u||h})),{meta:{total_tools:r.length,namespaces:Array.from(s).sort(),result_count:a.length},results:a}}}},A(Ot,"BaseCodeExecutor"),Ot),Nt,ri=(Nt=class extends ao{e2bApiKey;codeExecSandbox=null;SandboxClass=null;timeoutMs;constructor(e,n){super(e),this.e2bApiKey=n.apiKey,this.timeoutMs=n.timeoutMs??3e5}async ensureSandboxClass(){if(!this.SandboxClass)try{const e=await Jt(()=>import("@e2b/code-interpreter"),[]);this.SandboxClass=e.Sandbox}catch{throw new Error("@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter")}}async getOrCreateCodeExecSandbox(){return this.codeExecSandbox?this.codeExecSandbox:(await this.ensureSandboxClass(),m.debug("Starting E2B sandbox for code execution..."),this.codeExecSandbox=await this.SandboxClass.create("base",{apiKey:this.e2bApiKey,timeoutMs:this.timeoutMs}),this.codeExecSandbox)}generateShim(e){let n=`
9
+ // MCP Bridge Shim
10
+ global.__callMcpTool = async (server, tool, args) => {
11
+ const id = Math.random().toString(36).substring(7);
12
+ console.log(JSON.stringify({
13
+ type: '__MCP_TOOL_CALL__',
14
+ id,
15
+ server,
16
+ tool,
17
+ args
18
+ }));
19
+
20
+ const resultPath = \`/tmp/mcp_result_\${id}.json\`;
21
+ const fs = require('fs');
22
+
23
+ // Poll for result file
24
+ let attempts = 0;
25
+ while (attempts < 300) { // 30 seconds timeout
26
+ if (fs.existsSync(resultPath)) {
27
+ const content = fs.readFileSync(resultPath, 'utf8');
28
+ const result = JSON.parse(content);
29
+ fs.unlinkSync(resultPath); // Clean up
30
+
31
+ if (result.error) {
32
+ throw new Error(result.error);
33
+ }
34
+ return result.data;
35
+ }
36
+ await new Promise(resolve => setTimeout(resolve, 100));
37
+ attempts++;
38
+ }
39
+ throw new Error('Tool execution timed out');
40
+ };
41
+
42
+ // Global search_tools helper
43
+ global.search_tools = async (query, detailLevel = 'full') => {
44
+ const allTools = ${JSON.stringify(Object.entries(e).flatMap(([r,s])=>s.map(o=>({name:o.name,description:o.description,server:r,input_schema:o.inputSchema}))))};
45
+
46
+ const filtered = allTools.filter(tool => {
47
+ if (!query) return true;
48
+ const q = query.toLowerCase();
49
+ return tool.name.toLowerCase().includes(q) ||
50
+ (tool.description && tool.description.toLowerCase().includes(q));
51
+ });
52
+
53
+ if (detailLevel === 'names') {
54
+ return filtered.map(t => ({ name: t.name, server: t.server }));
55
+ } else if (detailLevel === 'descriptions') {
56
+ return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
57
+ }
58
+ return filtered;
59
+ };
60
+ `;for(const[r,s]of Object.entries(e)){if(!s||s.length===0)continue;const o=r.replace(/[^a-zA-Z0-9_]/g,"_");n+=`
61
+ global['${r}'] = {`;for(const i of s)n+=`
62
+ '${i.name}': async (args) => await global.__callMcpTool('${r}', '${i.name}', args),`;n+=`
63
+ };
64
+
65
+ // Also expose as safe name if different
66
+ if ('${o}' !== '${r}') {
67
+ global['${o}'] = global['${r}'];
68
+ }
69
+ `}return n}buildToolCatalog(){const e={},n=this.getToolNamespaces();for(const{serverName:r,tools:s}of n)e[r]=s;return e}async execute(e,n=3e4){const r=Date.now();let s=null,o=null,i=[];try{await this.ensureServersConnected();const a=await this.getOrCreateCodeExecSandbox(),c=this.buildToolCatalog(),u=`
70
+ ${this.generateShim(c)}
71
+
72
+ (async () => {
73
+ try {
74
+ const func = async () => {
75
+ ${e}
76
+ };
77
+ const result = await func();
78
+ console.log('__MCP_RESULT_START__');
79
+ console.log(JSON.stringify(result));
80
+ console.log('__MCP_RESULT_END__');
81
+ } catch (e) {
82
+ console.error(e);
83
+ process.exit(1);
84
+ }
85
+ })();
86
+ `,h=`exec_${Date.now()}.js`;await a.files.write(h,u);const d=await a.commands.run(`node ${h}`,{timeoutMs:n,onStdout:A(async f=>{try{const g=f.split(`
87
+ `);for(const p of g)if(p.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')){const b=JSON.parse(p);if(b.type==="__MCP_TOOL_CALL__")try{m.debug(`[E2B Bridge] Calling tool ${b.server}.${b.tool}`);const y=this.client.getAllActiveSessions()[b.server];if(!y)throw new Error(`Server ${b.server} not found`);const _=await y.connector.callTool(b.tool,b.args);let w=_;if(_.content&&_.content.length>0){const T=_.content[0];if(T.type==="text")try{w=JSON.parse(T.text)}catch{w=T.text}else w=T}const E=`/tmp/mcp_result_${b.id}.json`;await a.files.write(E,JSON.stringify({data:w}))}catch(C){m.error(`[E2B Bridge] Tool execution failed: ${C.message}`);const y=`/tmp/mcp_result_${b.id}.json`;await a.files.write(y,JSON.stringify({error:C.message||String(C)}))}}}catch{}},"onStdout")});if(i=[d.stdout,d.stderr].filter(Boolean),d.exitCode!==0)o=d.stderr||"Execution failed";else{const f=d.stdout,g="__MCP_RESULT_START__",p="__MCP_RESULT_END__",b=f.indexOf(g),C=f.indexOf(p);if(b!==-1&&C!==-1){const y=f.substring(b+g.length,C).trim();try{s=JSON.parse(y)}catch{s=y}i=i.map(_=>{let w=_.replace(new RegExp(g+"[\\s\\S]*?"+p),"[Result captured]");return w=w.split(`
88
+ `).filter(E=>!E.includes("__MCP_TOOL_CALL__")).join(`
89
+ `),w})}}}catch(a){o=a.message||String(a),o&&(o.includes("timeout")||o.includes("timed out"))&&(o="Script execution timed out")}return{result:s,logs:i,error:o,execution_time:(Date.now()-r)/1e3}}async cleanup(){if(this.codeExecSandbox)try{await this.codeExecSandbox.kill(),this.codeExecSandbox=null,m.debug("E2B code execution sandbox stopped")}catch(e){m.error("Failed to stop E2B code execution sandbox:",e)}}},A(Nt,"E2BCodeExecutor"),Nt),Xe=null,Es=!1;function co(){return["node","vm"].join(":")}A(co,"getVMModuleName");function Rr(){if(Es)return Xe!==null;Es=!0;try{const t=typeof Lo<"u"?Lo:null;if(t)return Xe=t(co()),!0}catch{m.debug("node:vm module not available via require")}return!1}A(Rr,"tryLoadVM");async function ea(){if(Xe!==null||!Es&&Rr())return!0;try{return Xe=await import(co()),!0}catch{return m.debug("node:vm module not available in this environment (e.g., Deno)"),!1}}A(ea,"tryLoadVMAsync");function Gh(){return Rr(),Xe!==null}A(Gh,"isVMAvailable");var It,si=(It=class extends ao{defaultTimeout;memoryLimitMb;constructor(e,n){super(e),this.defaultTimeout=n?.timeoutMs??3e4,this.memoryLimitMb=n?.memoryLimitMb,Rr()}async ensureVMLoaded(){if(Xe!==null)return;if(!await ea())throw new Error("node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment.")}async execute(e,n){const r=n??this.defaultTimeout;await this.ensureVMLoaded(),await this.ensureServersConnected();const s=[],o=Date.now();let i=null,a=null;try{const l=await this._buildContext(s),u=`
90
+ (async () => {
91
+ try {
92
+ ${e}
93
+ } catch (e) {
94
+ throw e;
95
+ }
96
+ })()
97
+ `;i=await new Xe.Script(u,{filename:"agent_code.js"}).runInNewContext(l,{timeout:r,displayErrors:!0})}catch(l){a=l.message||String(l),(l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"||l.message==="Script execution timed out."||typeof a=="string"&&(a.includes("timed out")||a.includes("timeout")))&&(a="Script execution timed out"),l.stack&&m.debug(`Code execution error stack: ${l.stack}`)}const c=(Date.now()-o)/1e3;return{result:i,logs:s,error:a,execution_time:c}}async _buildContext(e){const n=A((...i)=>{e.push(i.map(a=>typeof a=="object"?JSON.stringify(a,null,2):String(a)).join(" "))},"logHandler"),r={console:{log:n,error:A((...i)=>{n("[ERROR]",...i)},"error"),warn:A((...i)=>{n("[WARN]",...i)},"warn"),info:n,debug:n},Object,Array,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise,parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,setTimeout,clearTimeout,search_tools:this.createSearchToolsFunction(),__tool_namespaces:[]},s={},o=this.getToolNamespaces();for(const{serverName:i,tools:a,session:c}of o){const l={};for(const u of a){const h=u.name;l[h]=async d=>{const f=await c.connector.callTool(h,d||{});if(f.content&&f.content.length>0){const g=f.content[0];if(g.type==="text")try{return JSON.parse(g.text)}catch{return g.text}return g}return f}}r[i]=l,s[i]=!0}return r.__tool_namespaces=Object.keys(s),Xe.createContext(r)}async cleanup(){}},A(It,"VMCodeExecutor"),It),$t,Jh=($t=class extends $l{serverParams;errlog;_transport=null;constructor(e,n=process.stderr){super(),this.serverParams=e,this.errlog=n}async establishConnection(){return this._transport=new Wh(this.serverParams),this._transport.stderr&&typeof this._transport.stderr.pipe=="function"&&this._transport.stderr.pipe(this.errlog),m.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(e){if(this._transport)try{await this._transport.close()}catch(n){m.warn(`Error closing stdio transport: ${n}`)}finally{this._transport=null}}},A($t,"StdioConnectionManager"),$t),Rt,Yh=(Rt=class extends eo{command;args;env;errlog;clientInfo;constructor({command:e="npx",args:n=[],env:r,errlog:s=Ko.stderr,...o}={}){super(o),this.command=e,this.args=n,this.env=r,this.errlog=s,this.clientInfo=o.clientInfo??{name:"stdio-connector",version:"1.0.0"}}async connect(){if(this.connected){m.debug("Already connected to MCP implementation");return}m.debug(`Connecting to MCP implementation via stdio: ${this.command}`);try{let e;if(this.env){e={};for(const[o,i]of Object.entries(Ko.env))i!==void 0&&(e[o]=i);Object.assign(e,this.env)}const n={command:this.command,args:this.args,env:e};this.connectionManager=new Jh(n,this.errlog);const r=await this.connectionManager.start(),s={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};this.client=new Il(this.clientInfo,s),await this.client.connect(r),this.connected=!0,this.setupNotificationHandler(),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),m.debug(`Successfully connected to MCP implementation: ${this.command}`),this.trackConnectorInit({serverCommand:this.command,serverArgs:this.args,publicIdentifier:`${this.command} ${this.args.join(" ")}`})}catch(e){throw m.error(`Failed to connect to MCP implementation: ${e}`),await this.cleanupResources(),e}}get publicIdentifier(){return{type:"stdio","command&args":`${this.command} ${this.args.join(" ")}`}}},A(Rt,"StdioConnector"),Rt);function Ts(t){const e=ql(t,"utf-8");return JSON.parse(e)}A(Ts,"loadConfigFile");function ta(t,e){if("command"in t&&"args"in t)return new Yh({command:t.command,args:t.args,env:t.env,...e});if("url"in t){const n=t.transport||"http";return new Di(t.url,{headers:t.headers,authToken:t.auth_token||t.authToken,preferSse:t.preferSse||n==="sse",...e})}throw new Error("Cannot determine connector type from config")}A(ta,"createConnectorFromConfig");var tt,Xh=(tt=class extends Nl{static getPackageVersion(){return to()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig="vm";_executorOptions;_samplingCallback;_elicitationCallback;constructor(e,n){e?typeof e=="string"?super(Ts(e)):super(e):super();let r=!1,s="vm",o;n?.codeMode&&(typeof n.codeMode=="boolean"?r=n.codeMode:(r=n.codeMode.enabled,s=n.codeMode.executor??"vm",o=n.codeMode.executorOptions)),this.codeMode=r,this._codeExecutorConfig=s,this._executorOptions=o,this._samplingCallback=n?.samplingCallback,this._elicitationCallback=n?.elicitationCallback,this.codeMode&&this._setupCodeModeConnector(),this._trackClientInit()}_trackClientInit(){const e=Object.keys(this.config.mcpServers??{}),n=!!this._samplingCallback,r=!!this._elicitationCallback;_s.getInstance().trackMCPClientInit({codeMode:this.codeMode,sandbox:!1,allCallbacks:n&&r,verify:!1,servers:e,numServers:e.length,isBrowser:!1}).catch(s=>m.debug(`Failed to track MCPClient init: ${s}`))}static fromDict(e,n){return new tt(e,n)}static fromConfigFile(e,n){return new tt(Ts(e),n)}saveConfig(e){const n=Kl.dirname(e);gn.existsSync(n)||gn.mkdirSync(n,{recursive:!0}),gn.writeFileSync(e,JSON.stringify(this.config,null,2),"utf-8")}createConnectorFromConfig(e){return ta(e,{samplingCallback:this._samplingCallback,elicitationCallback:this._elicitationCallback})}_setupCodeModeConnector(){m.debug("Code mode connector initialized as internal meta server");const e=new bh(this),n=new Fi(e);this.sessions.code_mode=n,this.activeSessions.push("code_mode")}_ensureCodeExecutor(){if(!this._codeExecutor){const e=this._codeExecutorConfig;if(e instanceof ao)this._codeExecutor=e;else{if(typeof e=="function")throw this._customCodeExecutor=e,new Error("Custom executor function should be handled in executeCode");if(e==="e2b"){const n=this._executorOptions;if(n?.apiKey)this._codeExecutor=new ri(this,n);else{m.warn("E2B executor requires apiKey. Falling back to VM.");try{this._codeExecutor=new si(this,this._executorOptions)}catch{throw new Error("VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment.")}}}else try{this._codeExecutor=new si(this,this._executorOptions)}catch{const r=this._executorOptions,s=r?.apiKey||Kh.E2B_API_KEY;if(s)m.info("VM executor not available in this environment. Falling back to E2B."),this._codeExecutor=new ri(this,{...r,apiKey:s});else throw new Error("VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment.")}}}return this._codeExecutor}async executeCode(e,n){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._customCodeExecutor?this._customCodeExecutor(e,n):this._ensureCodeExecutor().execute(e,n)}async searchTools(e="",n="full"){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._ensureCodeExecutor().createSearchToolsFunction()(e,n)}getServerNames(){const e=this.codeMode;return super.getServerNames().filter(n=>!e||n!=="code_mode")}async close(){this._codeExecutor&&(await this._codeExecutor.cleanup(),this._codeExecutor=null),await this.closeAllSessions()}},A(tt,"MCPClient"),tt),jt,na=(jt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(m.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return m.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),m.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return m.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return m.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return m.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){m.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return m.error(`Error initializing connector: ${n}`),!1}}return!0}},A(jt,"BaseAdapter"),jt),Lt,Zh=(Lt=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,n){if(!n.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[s,o]of Object.entries(n.properties)){if(!(s in r)){if("const"in o)return!1;continue}const i=r[s];if("const"in o&&i!==o.const||"minimum"in o&&typeof i=="number"&&i<o.minimum||"maximum"in o&&typeof i=="number"&&i>o.maximum)return!1}return!0}static validateConditionalSchema(e,n,r){this.validateRequiredProperties(e,n,r),this.validatePropertyPatterns(e,n,r),this.validateNestedConditions(e,n,r)}static validateRequiredProperties(e,n,r){if(n.required){if(typeof e!="object"||e===null){for(const s of n.required)r.addIssue({code:zr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:zr.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[o,i]of Object.entries(n.properties)){if(!(o in s))continue;const a=s[o];i.pattern&&typeof a=="string"&&(new RegExp(i.pattern).test(a)||r.addIssue({code:zr.custom,message:`String '${a}' does not match pattern '${i.pattern}'`,path:[o]}))}}static validateNestedConditions(e,n,r){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,r):n.else&&this.validateConditionalSchema(e,n.else,r)}static parseSchema(e){return Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then?this.parseObject(e):e.properties&&(!e.type||e.type==="object")?this.parseObject(e):this.handleSingleType(e)}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const n={...e};return n.type=e.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const r=e.map(s=>{const o={...n,type:s};return this.parseSchema(o)});return Hr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):Ee();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Rl();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=jl();let r=n;return r=this.applyNumberBounds(n,e),r=this.applyNumberMultipleOf(n,e),r=this.applyNumberEnum(n,e),r=this.applyIntegerConstraint(n,e),r}static applyNumberBounds(e,n){let r=e;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(e,n){return n.multipleOf===void 0?e:e.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(e,n){if(!n.enum)return e;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?e:e.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,n){return n.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const n=Nr();let r=n;return e.format?this.applyStringFormat(n,e):(r=this.applyStringPattern(n,e),r=this.applyStringLength(n,e),r=this.applyStringEnum(n,e),r)}static applyStringFormat(e,n){if(!n.format)return e;switch(n.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,n){if(!n.pattern)return e;const r=new RegExp(n.pattern);return e.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const r=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),r}static applyStringEnum(e,n){return n.enum?e.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const o=e.items.map(i=>this.parseSchema(i));return Hr(o)}const n=e.items?this.parseSchema(e.items):Ee(),r=Ll(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,we(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const c=this.applyDefaultValues(i,e);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,a):o&&this.validateConditionalSchema(c,o,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[o,i]of Object.entries(e.properties||{})){const a=this.parseSchema(i);n[o]=r.has(o)?a:a.optional()}const s=we(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return Ee();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Fl()):n.push(this.parseSchema(r));return n.length>=2?Hr(n):n.length===1?n[0]:Ee()}static parseAllOf(e){if(e.length===0)return Ee();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(e,n){const r={...e,...n};if(e.properties&&n.properties){const s={...e.properties,...n.properties};r.properties=s}if(e.required&&n.required){const s=[...new Set([...e.required,...n.required])];r.required=s}return r}},A(Lt,"JSONSchemaToZod"),Lt);function ra(t){try{return Zh.convert(t)}catch(e){return m.warn(`Failed to convert JSON schema to Zod: ${e}`),Ee()}}A(ra,"schemaToZod");var Ft,vt=(Ft=class extends na{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?ra(e.inputSchema):we({}).optional();return new Kn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:A(async o=>{m.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return m.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=A(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Kn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:we({}).optional(),func:A(async()=>{m.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(c=>typeof c=="string"?c:c.text?c.text:c.uri?c.uri:JSON.stringify(c)).join(`
98
+ `):"Resource is empty or unavailable"}catch(a){return m.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=we({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=Nr();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?we(o):we({}).optional()}return new Kn({name:e.name,description:e.description||"",schema:r,func:A(async o=>{m.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
99
+ `):"Prompt returned no messages"}catch(i){return m.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},A(Ft,"LangChainAdapter"),Ft),Qh=Object.defineProperty,sa=(t,e)=>{for(var n in e)Qh(t,n,{get:e[n],enumerable:!0})},ed={};sa(ed,{ConfigurableModel:()=>xs,MODEL_PROVIDER_CONFIG:()=>jr,_inferModelProvider:()=>aa,getChatModelByClassName:()=>ia,initChatModel:()=>cn});const jr={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},fireworks:{package:"@langchain/community/chat_models/fireworks",className:"ChatFireworks",hasCircularDependency:!0},together:{package:"@langchain/community/chat_models/togetherai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/community/chat_models/perplexity",className:"ChatPerplexity",hasCircularDependency:!0}},oa=Object.keys(jr);async function ia(t){const e=Object.entries(jr).find(([,r])=>r.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s){const o=s.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${o}. Please install with \`npm install ${o}\` or \`pnpm install ${o}\``)}throw r}}async function td(t,e,n={}){const r=e||aa(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=jr[r];if(!s){const c=oa.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
100
+
101
+ Supported model providers are: ${c}`)}const{modelProvider:o,...i}=n,a=await ia(s.className);return new a({model:t,...i})}function aa(t){return t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("gpt-5")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?"openai":t.startsWith("claude")?"anthropic":t.startsWith("command")?"cohere":t.startsWith("accounts/fireworks")?"fireworks":t.startsWith("gemini")?"google-vertexai":t.startsWith("amazon.")?"bedrock":t.startsWith("mistral")?"mistralai":t.startsWith("sonar")||t.startsWith("pplx")?"perplexity":void 0}var xs=class Jn extends In{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations}async _model(e){const n={...this._defaultConfig,...this._modelParams(e)};let r=await td(n.model,n.modelProvider,n);const s=Object.entries(this._queuedMethodOperations);if(s.length>0)for(const[o,i]of s)o in r&&typeof r[o]=="function"&&(r=await r[o](...i));return r}async _generate(e,n,r){return(await this._model(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new Jn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new Jn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){const n=e?.configurable??{};let r={};for(const[s,o]of Object.entries(n))if(s.startsWith(this._configPrefix)){const i=this._removePrefix(s,this._configPrefix);r[i]=o}return this._configurableFields!=="any"&&(r=Object.fromEntries(Object.entries(r).filter(([s])=>this._configurableFields.includes(s)))),r}_removePrefix(e,n){return e.startsWith(n)?e.slice(n.length):e}withConfig(e){const n={...e||{}},r=this._modelParams(n),s=Object.fromEntries(Object.entries(n).filter(([i])=>i!=="configurable"));s.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([i])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(i,this._configPrefix))));const o=new Jn({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new Pe({config:n,bound:o})}async invoke(e,n){const r=await this._model(n),s=dn(n);return r.invoke(e,s)}async stream(e,n){const r=await this._model(n),s=new Eu({generator:await r.stream(e,n),config:n});return await s.setup,bn.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._model(n),s=dn(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._model(n),o=dn(n);yield*s.streamLog(e,o,{...r,_schemaFormat:"original",includeNames:r?.includeNames,includeTypes:r?.includeTypes,includeTags:r?.includeTags,excludeNames:r?.excludeNames,excludeTypes:r?.excludeTypes,excludeTags:r?.excludeTags})}streamEvents(e,n,r){const s=this;async function*o(){const i=await s._model(n),a=dn(n),c=i.streamEvents(e,a,r);for await(const l of c)yield l}return bn.fromAsyncGenerator(o())}};async function cn(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,...o}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[c,...l]=t.split(":"),u=l.length===0?[c]:[c,l.join(":")];oa.includes(u[0])&&([s,t]=u)}let i=Array.isArray(n)?[...n]:n;!t&&i===void 0&&(i=["model","modelProvider"]),r&&i===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);const a={...o};return i===void 0?new xs({defaultConfig:{...a,model:t,modelProvider:s},configPrefix:r}):(t&&(a.model=t),s&&(a.modelProvider=s),new xs({defaultConfig:a,configPrefix:r,configurableFields:i}))}var ks=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},Ms=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},ca=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
102
+ - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},lo=class extends Error{toolCall;toolError;constructor(t,e){const n=t instanceof Error?t:new Error(String(t)),r=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${r} with error: ${n.stack}
103
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function uo(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function yr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}let nd=0;var We=class As{constructor(e,n,r){this.schema=e,this.tool=n,this.options=r}get name(){return this.tool.function.name}static fromSchema(e,n){function r(a){return a??`extract-${++nd}`}if(Tu(e)){const a=ct(e),c={type:"function",function:{name:r(),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new As(a,c,n)}let s;typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?s=e:s={name:r(e.title),description:e.description??"",parameters:e.schema||e};const o=ct(e),i={type:"function",function:s};return new As(o,i,n)}parse(e){const r=new Wi(this.schema).validate(e);if(!r.valid)throw new ca(this.name,r.errors.map(s=>s.error));return e}},lt=class la{_schemaType;constructor(e){this.schema=e}static fromSchema(e){const n=ct(e);return new la(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new Wi(this.schema).validate(n).valid?n:void 0}catch{}}};function ua(t,e,n){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(s=>s instanceof We||s instanceof lt))return t;if(t.every(s=>fe(s)))return t.map(s=>We.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!fe(s)))return t.map(s=>We.fromSchema(s,e));throw new Error(`Invalid response format: list contains mixed types.
104
+ All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof We||t instanceof lt)return[t];const r=ha(n);if(fe(t))return r?[lt.fromSchema(t)]:[We.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[lt.fromSchema(t)]:[We.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function rd(t,e){return ua(t,e)}function sd(t){return lt.fromSchema(t)}const od=["ChatOpenAI","ChatXAI"],oi=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function ha(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return oi.some(r=>n.includes(r))}if(yr(t))return ha(t._defaultConfig.model);if(!uo(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||od.includes(e)&&("model"in t&&oi.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function ho(t){let e=0;for(const n of t){let r;typeof n.content=="string"?r=n.content:Array.isArray(n.content)?r=n.content.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join(""):r="",e+=r.length}return Math.ceil(e/4)}function Ge(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Lr(t){return typeof t=="function"?t:t.hook}function id(t){return new Promise(e=>setTimeout(e,t))}function ge(t){return{name:t.name,stateSchema:t.stateSchema,contextSchema:t.contextSchema,wrapToolCall:t.wrapToolCall,wrapModelCall:t.wrapModelCall,beforeAgent:t.beforeAgent,beforeModel:t.beforeModel,afterModel:t.afterModel,afterAgent:t.afterAgent,tools:t.tools??[]}}function da(t){return _h({clockseq:t})}function St(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return bs(t,new Uint8Array(n))}const ad="__error__",Yn="__scheduled__",cd="__interrupt__",ld="__resume__";var ii="[...]",ud="[Circular]",wr=[],Ct=[];function hd(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function dd(t,e,n,r){typeof r>"u"&&(r=hd()),Ps(t,"",0,[],void 0,0,r);var s;try{Ct.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,fd(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;wr.length!==0;){var o=wr.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function ts(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),wr.push([r,n,e,s])):Ct.push([e,n,t]):(r[n]=t,wr.push([r,n,e]))}function Ps(t,e,n,r,s,o,i){o+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){ts(ud,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){ts(ii,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){ts(ii,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)Ps(t[a],a,a,r,t,o,i);else{var c=Object.keys(t);for(a=0;a<c.length;a++){var l=c[a];Ps(t[l],l,a,r,t,o,i)}}r.pop()}}function fd(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Ct.length>0)for(var r=0;r<Ct.length;r++){var s=Ct[r];if(s[1]===e&&s[0]===n){n=s[2],Ct.splice(r,1);break}}return t.call(this,e,n)}}const pd=[];var md={},fa={};J(fa,{BaseChatMessageHistory:()=>pa,BaseListChatMessageHistory:()=>fo,InMemoryChatMessageHistory:()=>gd});var pa=class extends an{async addMessages(t){for(const e of t)await this.addMessage(e)}},fo=class extends an{addUserMessage(t){return this.addMessage(new pe(t))}addAIMessage(t){return this.addMessage(new N(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},gd=class extends fo{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(t){super(...arguments),this.messages=t??[]}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async clear(){this.messages=[]}},yd={},ma={};J(ma,{BaseMemory:()=>wd,getInputValue:()=>vd,getOutputValue:()=>_d,getPromptInputKey:()=>bd});var wd=class{};const ga=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},vd=(t,e)=>{const n=ga(t,e);if(!n){const r=Object.keys(t);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},_d=(t,e)=>{const n=ga(t,e);if(!n&&n!==""){const r=Object.keys(t);throw new Error(`output values have ${r.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function bd(t,e){const n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var ya={};J(ya,{BaseStore:()=>wa,InMemoryStore:()=>va});var wa=class extends an{},va=class extends wa{lc_namespace=["langchain","storage"];store={};async mget(t){return t.map(e=>this.store[e])}async mset(t){for(const[e,n]of t)this.store[e]=n}async mdelete(t){for(const e of t)delete this.store[e]}async*yieldKeys(t){const e=Object.keys(this.store);for(const n of e)(t===void 0||n.startsWith(t))&&(yield n)}},_a={};J(_a,{BaseRetriever:()=>po});var po=class extends Q{callbacks;tags;metadata;verbose;constructor(t){super(t),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){const n=dn(xu(e)),s=await(await ku.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),t,n.runId,void 0,void 0,void 0,n.runName);try{const o=await this._getRelevantDocuments(t,s);return await s?.handleRetrieverEnd(o),o}catch(o){throw await s?.handleRetrieverError(o),o}}},ba={};J(ba,{SaveableVectorStore:()=>Sd,VectorStore:()=>mo,VectorStoreRetriever:()=>Xn});var Xn=class extends po{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(t){super(t),this.vectorStore=t.vectorStore,this.k=t.k??this.k,this.searchType=t.searchType??this.searchType,this.filter=t.filter,t.searchType==="mmr"&&(this.searchKwargs=t.searchKwargs)}async _getRelevantDocuments(t,e){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(t,{k:this.k,filter:this.filter,...this.searchKwargs},e?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(t,this.k,this.filter,e?.getChild("vectorstore"))}async addDocuments(t,e){return this.vectorStore.addDocuments(t,e)}},mo=class extends an{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(t,e){super(e),this.embeddings=t}async delete(t){throw new Error("Not implemented.")}async similaritySearch(t,e=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)).map(o=>o[0])}async similaritySearchWithScore(t,e=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)}static fromTexts(t,e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(t,e,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(t,e,n,r,s,o){if(typeof t=="number")return new Xn({vectorStore:this,k:t,filter:e,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:o,callbacks:n});{const i={vectorStore:this,k:t?.k,filter:t?.filter,tags:[...t?.tags??[],this._vectorstoreType()],metadata:t?.metadata,verbose:t?.verbose,callbacks:t?.callbacks,searchType:t?.searchType};return t?.searchType==="mmr"?new Xn({...i,searchKwargs:t.searchKwargs}):new Xn({...i})}}},Sd=class extends mo{static load(t,e){throw new Error("Not implemented")}},Sa={};J(Sa,{BaseDocumentLoader:()=>Ca});var Ca=class{},Ea={};J(Ea,{LangSmithLoader:()=>Cd});var Cd=class extends Ca{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(t){if(super(),t.client&&t.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=t.client??new Mu(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Ed,this.datasetId=t.datasetId,this.datasetName=t.datasetName,this.exampleIds=t.exampleIds,this.asOf=t.asOf,this.splits=t.splits,this.inlineS3Urls=t.inlineS3Urls,this.offset=t.offset,this.limit=t.limit,this.metadata=t.metadata,this.filter=t.filter}async load(){const t=[];for await(const e of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=e.inputs;for(const o of this.contentKey)n=n[o];const r=this.formatContent(n),s=e;["created_at","modified_at"].forEach(o=>{o in s&&typeof s[o]=="object"&&(s[o]=s[o].toString())}),t.push({pageContent:r,metadata:s})}return t}};function Ed(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var Ve=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},Ta=class extends Q{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Td=class extends Ta{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},xa={};J(xa,{BaseDocumentTransformer:()=>Ta,Document:()=>Ve,MappingDocumentTransformer:()=>Td});var go=class extends an{lc_namespace=["langchain_core","example_selectors","base"]},ka=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},xd=class extends ka{defaultPrompt;conditionals;constructor(t,e=[]){super(),this.defaultPrompt=t,this.conditionals=e}getPrompt(t){for(const[e,n]of this.conditionals)if(e(t))return n;return this.defaultPrompt}};function kd(t){return t._modelType()==="base_llm"}function Md(t){return t._modelType()==="base_chat_model"}function ai(t){return t.split(/\n| /).length}var Ad=class Ma extends go{examples=[];examplePrompt;getTextLength=ai;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??ai}async addExample(e){this.examples.push(e);const n=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(n))}async calculateExampleTextLengths(e,n){if(e.length>0)return e;const{examples:r,examplePrompt:s}=n;return(await Promise.all(r.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(e){const n=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(n),s=0;const o=[];for(;r>0&&s<this.examples.length;){const i=r-this.exampleTextLengths[s];if(i<0)break;o.push(this.examples[s]),r=i,s+=1}return o}static async fromExamples(e,n){const r=new Ma(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function ns(t){return Object.keys(t).sort().map(e=>t[e])}var Pd=class Aa extends go{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(e){const n=this.inputKeys??Object.keys(e),r=ns(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Ve({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=ns(n.reduce((i,a)=>({...i,[a]:e[a]}),{})).join(" "),o=(await this.vectorStoreRetriever.invoke(r)).map(i=>i.metadata);return this.exampleKeys?o.map(i=>this.exampleKeys.reduce((a,c)=>({...a,[c]:i[c]}),{})):o}static async fromExamples(e,n,r,s={}){const o=s.inputKeys??null,i=e.map(c=>ns(o?o.reduce((l,u)=>({...l,[u]:c[u]}),{}):c).join(" ")),a=await r.fromTexts(i,e,n,s);return new Aa({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Pa={};J(Pa,{BaseExampleSelector:()=>go,BasePromptSelector:()=>ka,ConditionalPromptSelector:()=>xd,LengthBasedExampleSelector:()=>Ad,SemanticSimilarityExampleSelector:()=>Pd,isChatModel:()=>Md,isLLM:()=>kd});const Os="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Od=class extends an{lc_namespace=["langchain","recordmanagers"]},Oa=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=tu;constructor(t){this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new Ve({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){const e=this.keyEncoder(t);return bs(e,Os)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return bs(n,Os)}};function Na(t,e){const n=[];let r=[];return e.forEach(s=>{r.push(s),r.length>=t&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function Ia(t){const e=new Set,n=[];for(const r of t){if(!r.hash_)throw new Error("Hashed document does not have a hash");e.has(r.hash_)||(e.add(r.hash_),n.push(r))}return n}function $a(t){if(t===null)return e=>null;if(typeof t=="string")return e=>e.metadata[t];if(typeof t=="function")return t;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof t}`)}const Ra=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function Nd(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:o=100,cleanup:i,sourceIdKey:a,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=s??{};if(i==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=Ra(e)?await e.load():e,h=$a(a??null),d=await n.getTime();let f=0,g=0,p=0,b=0;const C=Na(o??100,u);for(const y of C){const _=Ia(y.map(M=>Oa.fromDocument(M))),w=_.map(M=>h(M));i==="incremental"&&_.forEach((M,P)=>{if(w[P]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const E=await n.exists(_.map(M=>M.uid)),T=[],v=[],S=[],x=new Set;if(_.forEach((M,P)=>{if(E[P])if(l)x.add(M.uid);else{S.push(M.uid);return}T.push(M.uid),v.push(M.toDocument())}),S.length>0&&(await n.update(S,{timeAtLeast:d}),b+=S.length),v.length>0&&(await r.addDocuments(v,{ids:T}),f+=v.length-x.size,p+=x.size),await n.update(_.map(M=>M.uid),{timeAtLeast:d,groupIds:w}),i==="incremental"){w.forEach(P=>{if(!P)throw new Error("Source id cannot be null")});const M=await n.listKeys({before:d,groupIds:w});M.length>0&&(await r.delete({ids:M}),await n.deleteKeys(M),g+=M.length)}}if(i==="full"){let y=await n.listKeys({before:d,limit:c});for(;y.length>0;)await r.delete({ids:y}),await n.deleteKeys(y),g+=y.length,y=await n.listKeys({before:d,limit:c})}return{numAdded:f,numDeleted:g,numUpdated:p,numSkipped:b}}var ja={};J(ja,{RecordManager:()=>Od,UUIDV5_NAMESPACE:()=>Os,_HashedDocument:()=>Oa,_batch:()=>Na,_deduplicateInOrder:()=>Ia,_getSourceIdAssigner:()=>$a,_isBaseDocumentLoader:()=>Ra,index:()=>Nd});var La=class extends Hi{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(t){super(),this.argsOnly=t?.argsOnly??this.argsOnly}async parseResult(t){if("message"in t[0]){const n=t[0].message.additional_kwargs.function_call;if(!n)throw new Error(`No function_call in message ${JSON.stringify(t)}`);if(!n.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(t)}`);return this.argsOnly?n.arguments:JSON.stringify(n)}else throw new Error(`No message in generations ${JSON.stringify(t)}`)}},Fa=class extends nu{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(t){super(t),this.argsOnly=t?.argsOnly??this.argsOnly,this.outputParser=new La(t)}_diff(t,e){return e?ru(t??{},e):void 0}async parsePartialResult(t){const e=t[0];if(!e.message)return;const{message:n}=e,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?Uo(r.arguments):{...r,arguments:Uo(r.arguments)}}async parseResult(t){const e=await this.outputParser.parseResult(t);if(!e)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(t)}`);return this.parse(e)}async parse(t){const e=JSON.parse(t);return this.argsOnly||(e.arguments=JSON.parse(e.arguments)),e}getFormatInstructions(){return""}},Id=class extends Hi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Fa;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(t){super(t),this.attrName=t.attrName}async parseResult(t){return(await this.outputParser.parseResult(t))[this.attrName]}},Da={};J(Da,{JsonKeyOutputFunctionsParser:()=>Id,JsonOutputFunctionsParser:()=>Fa,OutputFunctionsParser:()=>La});var $n=class extends Q{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(t){super(t);const{inputVariables:e}=t;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){const e=this.partialVariables??{},n={};for(const[s,o]of Object.entries(e))typeof o=="string"?n[s]=o:n[s]=await o();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},En=class extends $n{async formatPromptValue(t){const e=await this.format(t);return new su(e)}};var $d=Object.prototype.toString,ln=Array.isArray||function(e){return $d.call(e)==="[object Array]"};function yo(t){return typeof t=="function"}function Rd(t){return ln(t)?"array":typeof t}function rs(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function ci(t,e){return t!=null&&typeof t=="object"&&e in t}function jd(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Ld=RegExp.prototype.test;function Fd(t,e){return Ld.call(t,e)}var Dd=/\S/;function Ud(t){return!Fd(Dd,t)}var Vd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Bd(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Vd[n]})}var zd=/\s*/,Hd=/\s+/,li=/\s*=/,Wd=/\s*\}/,qd=/#|\^|\/|>|\{|&|=|!/;function Kd(t,e){if(!t)return[];var n=!1,r=[],s=[],o=[],i=!1,a=!1,c="",l=0;function u(){if(i&&!a)for(;o.length;)delete s[o.pop()];else o=[];i=!1,a=!1}var h,d,f;function g(S){if(typeof S=="string"&&(S=S.split(Hd,2)),!ln(S)||S.length!==2)throw new Error("Invalid tags: "+S);h=new RegExp(rs(S[0])+"\\s*"),d=new RegExp("\\s*"+rs(S[1])),f=new RegExp("\\s*"+rs("}"+S[1]))}g(e||ue.tags);for(var p=new Rn(t),b,C,y,_,w,E;!p.eos();){if(b=p.pos,y=p.scanUntil(h),y)for(var T=0,v=y.length;T<v;++T)_=y.charAt(T),Ud(_)?(o.push(s.length),c+=_):(a=!0,n=!0,c+=" "),s.push(["text",_,b,b+1]),b+=1,_===`
105
+ `&&(u(),c="",l=0,n=!1);if(!p.scan(h))break;if(i=!0,C=p.scan(qd)||"name",p.scan(zd),C==="="?(y=p.scanUntil(li),p.scan(li),p.scanUntil(d)):C==="{"?(y=p.scanUntil(f),p.scan(Wd),p.scanUntil(d),C="&"):y=p.scanUntil(d),!p.scan(d))throw new Error("Unclosed tag at "+p.pos);if(C==">"?w=[C,y,b,p.pos,c,l,n]:w=[C,y,b,p.pos],l++,s.push(w),C==="#"||C==="^")r.push(w);else if(C==="/"){if(E=r.pop(),!E)throw new Error('Unopened section "'+y+'" at '+b);if(E[1]!==y)throw new Error('Unclosed section "'+E[1]+'" at '+b)}else C==="name"||C==="{"||C==="&"?a=!0:C==="="&&g(y)}if(u(),E=r.pop(),E)throw new Error('Unclosed section "'+E[1]+'" at '+p.pos);return Jd(Gd(s))}function Gd(t){for(var e=[],n,r,s=0,o=t.length;s<o;++s)n=t[s],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function Jd(t){for(var e=[],n=e,r=[],s,o,i=0,a=t.length;i<a;++i)switch(s=t[i],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":o=r.pop(),o[5]=s[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(s)}return e}function Rn(t){this.string=t,this.tail=t,this.pos=0}Rn.prototype.eos=function(){return this.tail===""};Rn.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};Rn.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};function en(t,e){this.view=t,this.cache={".":this.view},this.parent=e}en.prototype.push=function(e){return new en(e,this)};en.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,o,i,a,c=!1;s;){if(e.indexOf(".")>0)for(o=s.view,i=e.split("."),a=0;o!=null&&a<i.length;)a===i.length-1&&(c=ci(o,i[a])||jd(o,i[a])),o=o[i[a++]];else o=s.view[e],c=ci(s.view,e);if(c){r=o;break}s=s.parent}n[e]=r}return yo(r)&&(r=r.call(this.view)),r};function ie(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}ie.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ie.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||ue.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=Kd(e,n),o&&r.set(s,i)),i};ie.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof en?n:new en(n,void 0);return this.renderTokens(i,a,r,e,s)};ie.prototype.renderTokens=function(e,n,r,s,o){for(var i="",a,c,l,u=0,h=e.length;u<h;++u)l=void 0,a=e[u],c=a[0],c==="#"?l=this.renderSection(a,n,r,s,o):c==="^"?l=this.renderInverted(a,n,r,s,o):c===">"?l=this.renderPartial(a,n,r,o):c==="&"?l=this.unescapedValue(a,n):c==="name"?l=this.escapedValue(a,n,o):c==="text"&&(l=this.rawValue(a)),l!==void 0&&(i+=l);return i};ie.prototype.renderSection=function(e,n,r,s,o){var i=this,a="",c=n.lookup(e[1]);function l(d){return i.render(d,n,r,o)}if(c){if(ln(c))for(var u=0,h=c.length;u<h;++u)a+=this.renderTokens(e[4],n.push(c[u]),r,s,o);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")a+=this.renderTokens(e[4],n.push(c),r,s,o);else if(yo(c)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(n.view,s.slice(e[3],e[5]),l),c!=null&&(a+=c)}else a+=this.renderTokens(e[4],n,r,s,o);return a}};ie.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||ln(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};ie.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
106
+ `),i=0;i<o.length;i++)o[i].length&&(i>0||!r)&&(o[i]=s+o[i]);return o.join(`
107
+ `)};ie.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=yo(r)?r(e[1]):r[e[1]];if(i!=null){var a=e[6],c=e[5],l=e[4],u=i;c==0&&l&&(u=this.indentPartial(i,l,a));var h=this.parse(u,o);return this.renderTokens(h,n,r,u,s)}}};ie.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ie.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||ue.escape,o=n.lookup(e[1]);if(o!=null)return typeof o=="number"&&s===ue.escape?String(o):s(o)};ie.prototype.rawValue=function(e){return e[1]};ie.prototype.getConfigTags=function(e){return ln(e)?e:e&&typeof e=="object"?e.tags:void 0};ie.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!ln(e))return e.escape};var ue={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){Tn.templateCache=t},get templateCache(){return Tn.templateCache}},Tn=new ie;ue.clearCache=function(){return Tn.clearCache()};ue.parse=function(e,n){return Tn.parse(e,n)};ue.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Rd(e)+'" was given as the first argument for mustache#render(template, view, partials)');return Tn.render(e,n,r,s)};ue.escape=Bd;ue.Scanner=Rn;ue.Context=en;ue.Writer=ie;function Ua(){ue.escape=t=>t}const xn=t=>{const e=t.split(""),n=[],r=(o,i)=>{for(let a=i;a<e.length;a+=1)if(o.includes(e[a]))return a;return-1};let s=0;for(;s<e.length;)if(e[s]==="{"&&s+1<e.length&&e[s+1]==="{")n.push({type:"literal",text:"{"}),s+=2;else if(e[s]==="}"&&s+1<e.length&&e[s+1]==="}")n.push({type:"literal",text:"}"}),s+=2;else if(e[s]==="{"){const o=r("}",s);if(o<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,o).join("")}),s=o+1}else{if(e[s]==="}")throw new Error("Single '}' in template.");{const o=r("{}",s),i=(o<0?e.slice(s):e.slice(s,o)).join("");n.push({type:"literal",text:i}),s=o<0?e.length:o}}return n},Va=(t,e=[])=>{const n=[];for(const r of t)if(r[0]==="name"){const s=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){const s=[...e,r[1]],o=Va(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},vr=t=>{Ua();const e=ue.parse(t);return Va(e)},Ba=(t,e)=>xn(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e){const s=typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]);return n+s}throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),za=(t,e)=>(Ua(),ue.render(t,e)),_r={"f-string":Ba,mustache:za},Ha={"f-string":xn,mustache:vr},xe=(t,e,n)=>{try{return _r[e](t,n)}catch(r){throw qi(r,"INVALID_PROMPT_INPUT")}},br=(t,e)=>Ha[e](t),jn=(t,e,n)=>{if(!(e in _r)){const r=Object.keys(_r);throw new Error(`Invalid template format. Got \`${e}\`;
108
+ should be one of ${r}`)}try{const r=n.reduce((s,o)=>(s[o]="foo",s),{});Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")xe(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")xe(s.image_url,e,r);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){const o=s.image_url.url;xe(o,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):xe(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Ze=class fn extends En{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),jn(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return xe(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
109
+
110
+ `,o=""){const i=[o,...e,n].join(s);return new fn({inputVariables:r,template:i})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},o=new Set;return br(e,r).forEach(i=>{i.type==="variable"&&o.add(i.name)}),new fn({inputVariables:[...o],templateFormat:r,template:e,...s})}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new fn(s)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new fn({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},Zn=class Wa extends $n{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),jn([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}_getPromptType(){return"prompt"}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Wa(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=xe(a,this.templateFormat,e):n[i]=a;const r=e.url||n.url,s=e.detail||n.detail;if(!r)throw new Error("Must provide either an image URL.");if(typeof r!="string")throw new Error("url must be a string.");const o={url:r};return s&&(o.detail=s),o}async formatPromptValue(e){const n=await this.format(e);return new ou(n)}},Ns=class extends Q{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(t){const e=t.templateFormat??"f-string",n=Is(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return $s(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function Is(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")br(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?br(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...Is(s,e));else typeof r=="object"&&r!==null&&n.push(...Is(r,e));return Array.from(new Set(n))}function $s(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=xe(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(xe(a,n,e)):typeof a=="object"&&i.push($s(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=$s(o,e,n):r[s]=o;return r}var Fr=class extends Q{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},Rs=class extends Fr{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(t){typeof t=="string"&&(t={variableName:t}),super(t),this.variableName=t.variableName,this.optional=t.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(t){const e=t[this.variableName];if(this.optional&&!e)return[];if(!e){const r=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw r.name="InputFormatError",r}let n;try{Array.isArray(e)?n=e.map(Sn):n=[Sn(e)]}catch(r){const s=typeof e=="string"?e:JSON.stringify(e,null,2),o=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${s}`,`Additional message: ${r.message}`].join(`
111
+
112
+ `));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},qa=class extends Fr{prompt;constructor(t){"prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(t){return[await this.format(t)]}},wo=class extends $n{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new iu(e)}},Ka=class extends qa{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(t,e){"prompt"in t||(t={prompt:t,role:e}),super(t),this.role=t.role}async format(t){return new Ki(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Ze.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function Yd(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Xd(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}var vo=class extends Fr{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(t,e){if("prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(r=>{"inputVariables"in r&&(n=n.concat(r.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=e??this.additionalOptions}createMessage(t){const e=this.constructor;if(e._messageClass()){const n=e._messageClass();return new n({content:t})}else if(e.chatMessageClass){const n=e.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(t,e){if(typeof t=="string")return new this(Ze.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(Ze.fromTemplate(r,e));else if(r!==null)if(Yd(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(Ze.fromTemplate(s,o))}else if(Xd(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=vr(s):a=xn(s);const c=a.flatMap(l=>l.type==="variable"?[l.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
113
+ Got: ${c}
114
+ From: ${s}`);i=[c[0]]}else i=[];s={url:s},o=new Zn({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=vr(s.url):a=xn(s.url),i=a.flatMap(c=>c.type==="variable"?[c.name]:[])}else i=[];o=new Zn({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else throw new Error("Invalid image template");n.push(o)}else typeof r=="object"&&n.push(new Ns({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof En){const e=await this.prompt.format(t);return this.createMessage(e)}else{const e=[];for(const n of this.prompt){let r={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(const s of n.inputVariables)r||(r={[s]:t[s]}),r={...r,[s]:t[s]};if(n instanceof En){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),s!==""&&e.push({...o,type:"text",text:s})}else if(n instanceof Zn){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,type:"image_url",image_url:s})}else if(n instanceof Ns){const s=await n.format(r);let o;"additionalContentFields"in n&&(o=n.additionalContentFields),e.push({...o,...s})}}return this.createMessage(e)}}async formatMessages(t){return[await this.format(t)]}},_o=class extends vo{static _messageClass(){return pe}static lc_name(){return"HumanMessagePromptTemplate"}},Ga=class extends vo{static _messageClass(){return N}static lc_name(){return"AIMessagePromptTemplate"}},Ja=class extends vo{static _messageClass(){return be}static lc_name(){return"SystemMessagePromptTemplate"}};function Zd(t){return typeof t.formatMessages=="function"}function Qd(t,e){if(Zd(t)||Re(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if(e?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){const o=s.slice(2,-2);return new Rs({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new Rs({variableName:o,optional:!0})}throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const n=Sn(t);let r;if(typeof n.content=="string"?r=n.content:r=n.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),n._getType()==="human")return _o.fromTemplate(r,e);if(n._getType()==="ai")return Ga.fromTemplate(r,e);if(n._getType()==="system")return Ja.fromTemplate(r,e);if(Ki.isInstance(n))return Ka.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function ef(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var bo=class Qn extends wo{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){const n=new Set;for(const a of this.promptMessages)if(!(a instanceof yn))for(const c of a.inputVariables)n.add(c);const r=this.inputVariables,s=new Set(this.partialVariables?r.concat(Object.keys(this.partialVariables)):r),o=new Set([...s].filter(a=>!n.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are not used in any of the prompt messages.`);const i=new Set([...n].filter(a=>!s.has(a)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,n){if(typeof e.content=="string")return e;const r=await Promise.all(e.content.map(async s=>{if(s.type!=="image_url")return s;let o="";typeof s.image_url=="string"?o=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(o=s.image_url.url);const a=await Ze.fromTemplate(o,{templateFormat:this.templateFormat}).format(n);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=a:s.image_url=a,s}));return e.content=r,e}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=[];for(const s of this.promptMessages)if(s instanceof yn)r.push(await this._parseImagePrompts(s,n));else{let o;this.templateFormat==="mustache"?o={...n}:o=s.inputVariables.reduce((a,c)=>{if(!(c in n)&&!(ef(s)&&s.optional))throw qi(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return a[c]=n[c],a},{});const i=await s.formatMessages(o);r=r.concat(i)}return r}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Qn(s)}static fromTemplate(e,n){const r=Ze.fromTemplate(e,n),s=new _o({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof Qn?a.promptMessages:[Qd(a,n)]),[]),s=e.reduce((i,a)=>a instanceof Qn?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof yn))for(const a of i.inputVariables)a in s||o.add(a);return new this({...n,inputVariables:[...o],promptMessages:r,partialVariables:s,templateFormat:n?.templateFormat})}},tf=class js extends En{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
115
+
116
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(e){if(super(e),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),jn(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new js(s)}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),s=await Promise.all(r.map(i=>this.examplePrompt.format(i))),o=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return xe(o,this.templateFormat,n)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:n}=e;if(!n)throw new Error("Missing example prompt");const r=await Ze.deserialize(n);let s;if(Array.isArray(e.examples))s=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new js({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},nf=class Ya extends wo{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
117
+
118
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
119
+
120
+ `,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),jn(this.prefix+this.suffix,this.templateFormat,n)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=await this.getExamples(n);r=r.map(o=>{const i={};return this.examplePrompt.inputVariables.forEach(a=>{i[a]=o[a]}),i});const s=[];for(const o of r){const i=await this.examplePrompt.formatMessages(o);s.push(...i)}return s}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),o=(await Promise.all(r.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return xe(i,this.templateFormat,n)}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Ya(s)}},rf=class er extends $n{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const e=this.pipelinePrompts.map(r=>r.name),n=this.pipelinePrompts.map(r=>r.prompt.inputVariables.filter(s=>!e.includes(s))).flat();return[...new Set(n)]}static extractRequiredInputValues(e,n){return n.reduce((r,s)=>(r[s]=e[s],r),{})}async formatPipelinePrompts(e){const n=await this.mergePartialAndUserVariables(e);for(const{name:r,prompt:s}of this.pipelinePrompts){const o=er.extractRequiredInputValues(n,s.inputVariables);s instanceof bo?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return er.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){const n={...this};return n.inputVariables=this.inputVariables.filter(r=>!(r in e)),n.partialVariables={...this.partialVariables??{},...e},new er(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function ui(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function sf(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var of=class Xa extends bo{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if(ui(e))return super.pipe(e.withStructuredOutput(this.schema));if(sf(e)&&ui(e.bound))return super.pipe(new Pe({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,n,r){return Xa.fromMessages(e,{schema:n,method:r})}},Za={};J(Za,{AIMessagePromptTemplate:()=>Ga,BaseChatPromptTemplate:()=>wo,BaseMessagePromptTemplate:()=>Fr,BaseMessageStringPromptTemplate:()=>qa,BasePromptTemplate:()=>$n,BaseStringPromptTemplate:()=>En,ChatMessagePromptTemplate:()=>Ka,ChatPromptTemplate:()=>bo,DEFAULT_FORMATTER_MAPPING:()=>_r,DEFAULT_PARSER_MAPPING:()=>Ha,DictPromptTemplate:()=>Ns,FewShotChatMessagePromptTemplate:()=>nf,FewShotPromptTemplate:()=>tf,HumanMessagePromptTemplate:()=>_o,ImagePromptTemplate:()=>Zn,MessagesPlaceholder:()=>Rs,PipelinePromptTemplate:()=>rf,PromptTemplate:()=>Ze,StructuredPrompt:()=>of,SystemMessagePromptTemplate:()=>Ja,checkValidTemplate:()=>jn,interpolateFString:()=>Ba,interpolateMustache:()=>za,parseFString:()=>xn,parseMustache:()=>vr,parseTemplate:()=>br,renderTemplate:()=>xe});var Qa={};J(Qa,{BaseDocumentCompressor:()=>af});var af=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const Je={and:"and",or:"or",not:"not"},R={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var ec=class{},So=class{accept(t){if(this.exprName==="Operation")return t.visitOperation(this);if(this.exprName==="Comparison")return t.visitComparison(this);if(this.exprName==="StructuredQuery")return t.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},Co=class extends So{},cf=class extends Co{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},lf=class extends Co{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},uf=class extends So{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function tc(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Te(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:tc(t)&&Object.keys(t).length===0:!0}function nc(t){if(typeof t=="number")return t%1===0;if(typeof t=="string"){const e=parseInt(t,10);return!Number.isNaN(e)&&e%1===0&&e.toString()===t}return!1}function rc(t){if(typeof t=="number")return t%1!==0;if(typeof t=="string"){const e=parseFloat(t);return!Number.isNaN(e)&&e%1!==0&&e.toString()===t}return!1}function sc(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function oc(t){return typeof t=="boolean"}function Eo(t){let e;if(sc(t))e=t;else if(nc(t))e=parseInt(t,10);else if(rc(t))e=parseFloat(t);else if(oc(t))e=!!t;else throw new Error("Unsupported value type");return e}var To=class extends ec{},hf=class extends To{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Je.and,Je.or],this.allowedComparators=t?.allowedComparators??[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte]}formatFunction(t){if(t in R){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(t)===-1)throw new Error(`Comparator ${t} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(t in Je){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(t)===-1)throw new Error(`Operator ${t} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${t}`}visitOperation(t){const e=t.args?.map(n=>n.accept(this));return{[this.formatFunction(t.operator)]:e}}visitComparison(t){return{[t.attribute]:{[this.formatFunction(t.comparator)]:Eo(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Te(t)&&Te(e))){if(Te(t)||n==="replace")return Te(e)?void 0:e;if(Te(e))return r?t:n==="and"?void 0:t;if(n==="and")return{$and:[t,e]};if(n==="or")return{$or:[t,e]};throw new Error("Unknown merge type")}}},df=class extends To{allowedOperators=[Je.and,Je.or];allowedComparators=[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"number":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"boolean":return[R.eq,R.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case R.eq:return(e,n)=>e===n;case R.ne:return(e,n)=>e!==n;case R.gt:return(e,n)=>e>n;case R.gte:return(e,n)=>e>=n;case R.lt:return(e,n)=>e<n;case R.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case Je.and:return(e,n)=>e&&n;case Je.or:return(e,n)=>e||n;default:throw new Error("Unknown operator")}}visitOperation(t){const{operator:e,args:n}=t;if(this.allowedOperators.includes(e)){const r=this.getOperatorFunction(e);return s=>n?n.reduce((o,i)=>{const a=i.accept(this);if(typeof a=="function")return r(o,a(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(t){const{comparator:e,attribute:n,value:r}=t,s=[R.ne];if(this.allowedComparators.includes(e)){if(!this.getAllowedComparatorsForType(typeof r).includes(e))throw new Error(`'${e}' comparator not allowed to be used with ${typeof r}`);const o=this.getComparatorFunction(e);return i=>{const a=i.metadata[n];return a===void 0?!!s.includes(e):o(a,Eo(r))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(t){if(!t.filter)return{};const e=t.filter?.accept(this);if(typeof e!="function")throw new Error("Structured query filter is not a function");return{filter:e}}mergeFilters(t,e,n="and"){if(!(Te(t)&&Te(e))){if(Te(t)||n==="replace")return Te(e)?void 0:e;if(Te(e))return n==="and"?void 0:t;if(n==="and")return r=>t(r)&&e(r);if(n==="or")return r=>t(r)||e(r);throw new Error("Unknown merge type")}}},ic={};J(ic,{BaseTranslator:()=>To,BasicTranslator:()=>hf,Comparators:()=>R,Comparison:()=>cf,Expression:()=>So,FilterDirective:()=>Co,FunctionalTranslator:()=>df,Operation:()=>lf,Operators:()=>Je,StructuredQuery:()=>uf,Visitor:()=>ec,castValue:()=>Eo,isBoolean:()=>oc,isFilterEmpty:()=>Te,isFloat:()=>rc,isInt:()=>nc,isObject:()=>tc,isString:()=>sc});var ac={};J(ac,{RunCollectorCallbackHandler:()=>ff});var ff=class extends ro{name="run_collector";exampleId;tracedRuns;constructor({exampleId:t}={}){super({_awaitHandler:!0}),this.exampleId=t,this.tracedRuns=[]}async persistRun(t){const e={...t};e.reference_example_id=this.exampleId,this.tracedRuns.push(e)}},pf={},cc={};J(cc,{EventStreamContentType:()=>mf,convertEventStreamToIterableReadableDataStream:()=>yf,getBytes:()=>lc,getLines:()=>uc,getMessages:()=>hc});const mf="text/event-stream";async function lc(t,e){if(t instanceof ReadableStream){const n=t.getReader();for(;;){const r=await n.read();if(r.done){e(new Uint8Array,!0);break}e(r.value)}}else try{for await(const n of t)e(new Uint8Array(n));e(new Uint8Array,!0)}catch(n){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${n.message}`].join(`
121
+ `))}}var Et=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})(Et||{});function uc(t){let e,n,r,s=!1;return function(i,a){if(a){t(i,0,!0);return}e===void 0?(e=i,n=0,r=-1):e=gf(e,i);const c=e.length;let l=0;for(;n<c;){s&&(e[n]===Et.NewLine&&(l=++n),s=!1);let u=-1;for(;n<c&&u===-1;++n)switch(e[n]){case Et.Colon:r===-1&&(r=n-l);break;case Et.CarriageReturn:s=!0;case Et.NewLine:u=n;break}if(u===-1)break;t(e.subarray(l,u),r),l=n,r=-1}l===c?e=void 0:l!==0&&(e=e.subarray(l),n-=l)}}function hc(t,e,n){let r=ss();const s=new TextDecoder;return function(i,a,c){if(c){wf(r)||(t?.(r),r=ss());return}if(i.length===0)t?.(r),r=ss();else if(a>0){const l=s.decode(i.subarray(0,a)),u=a+(i[a+1]===Et.Space?2:1),h=s.decode(i.subarray(u));switch(l){case"data":r.data=r.data?r.data+`
122
+ `+h:h;break;case"event":r.event=h;break;case"id":e?.(r.id=h);break;case"retry":{const d=parseInt(h,10);Number.isNaN(d)||n?.(r.retry=d);break}}}}}function gf(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function ss(){return{data:"",event:"",id:"",retry:void 0}}function yf(t,e){const n=new ReadableStream({async start(r){const s=hc(i=>{if(i.event==="error")throw new Error(i.data??"Unspecified event streaming error.");i.event==="metadata"?e?.(i):i.data&&r.enqueue(i.data)});await lc(t,uc((i,a,c)=>{s(i,a,c),c&&r.close()}))}});return bn.fromReadableStream(n)}function wf(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var vf={};function dc(t,e){let n=0,r=0,s=0;for(let o=0;o<t.length;o++)n+=t[o]*e[o],r+=t[o]*t[o],s+=e[o]*e[o];return n/(Math.sqrt(r)*Math.sqrt(s))}function _f(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function bf(t,e){let n=0;for(let r=0;r<t.length;r++)n+=(t[r]-e[r])*(t[r]-e[r]);return n}function Sf(t,e){return Math.sqrt(bf(t,e))}var fc={};J(fc,{cosineSimilarity:()=>Ls,euclideanDistance:()=>Tf,innerProduct:()=>Ef,matrixFunc:()=>Dr,maximalMarginalRelevance:()=>xf,normalize:()=>Cf});function Dr(t,e,n){if(t.length===0||t[0].length===0||e.length===0||e[0].length===0)return[[]];if(t[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[t.length,t[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return t.map(r=>e.map(s=>n(r,s)).map(s=>Number.isNaN(s)?0:s))}function Cf(t,e=!1){const n=kf(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Ls(t,e){return Dr(t,e,dc)}function Ef(t,e){return Dr(t,e,_f)}function Tf(t,e){return Dr(t,e,Sf)}function xf(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=Ls(s,e)[0],i=pc(o).maxIndex,a=[e[i]],c=[i];for(;c.length<Math.min(r,e.length);){let l=-1/0,u=-1;const h=Ls(e,a);o.forEach((d,f)=>{if(c.includes(f))return;const g=Math.max(...h[f]),p=n*d-(1-n)*g;p>l&&(l=p,u=f)}),a.push(e[u]),c.push(u)}return c}function pc(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let r=1;r<t.length;r+=1)t[r]>e&&(n=r,e=t[r]);return{maxIndex:n,maxValue:e}}function kf(t){return t.reduce((e,n)=>Math.max(e,pc(n).maxValue),0)}var Mf=class extends In{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new N(e.stop[0]),text:e.stop[0]}]};const r=t.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
123
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new N(r),text:r}],llmOutput:{}}}},Af=class mc extends In{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:e=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:o,...i}){super(i),this.sleep=e,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=o}_llmType(){return"fake"}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:ct(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:ct(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:ct(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:ct(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new mc({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return o.tools=n,o.withConfig({tools:s})}async _generate(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new N({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const i of this.chunks){const a=new Ss({message:new Yt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new N(typeof e[0].content=="string"?e[0].content:""),o=typeof s.content=="string"?s.content:"";for(const i of o){await new Promise(c=>setTimeout(c,this.sleep));const a=new Ss({message:new Yt({content:i}),text:i});yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},Pf=class extends In{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;constructor(t){super(t);const{responses:e,sleep:n,emitCustomEvent:r}=t;this.responses=e,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,e,n){if(await this._sleepIfRequested(),e?.thrownErrorString)throw new Error(e.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),e?.stop?.length)return{generations:[this._formatGeneration(e.stop[0])]};{const r=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(r)],llmOutput:{}}}}_formatGeneration(t){return{message:new N(t),text:t}}async*_streamResponseChunks(t,e,n){const r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});for await(const s of r){if(await this._sleepIfRequested(),e?.thrownErrorString)throw new Error(e.thrownErrorString);yield this._createResponseChunk(s),n?.handleLLMNewToken(s)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t){return new Ss({message:new Yt({content:t}),text:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}withStructuredOutput(t,e){return Xt.from(async n=>{const r=await this.invoke(n);if(r.tool_calls?.[0]?.args)return r.tool_calls[0].args;if(typeof r.content=="string")return JSON.parse(r.content);throw new Error("No structured output found")})}},Of=class extends Yi{vectorSize;constructor(t){super(t??{}),this.vectorSize=t?.vectorSize??4}async embedDocuments(t){return Promise.all(t.map(e=>this.embedQuery(e)))}async embedQuery(t){let e=t;e=e.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=e.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=e.length+r;e=e.padEnd(s," ");const o=e.length/this.vectorSize,i=[];for(let c=0;c<e.length;c+=o)i.push(e.slice(c,c+o));return i.map(c=>{let l=0;for(let h=0;h<c.length;h+=1)l+=c===" "?0:c.charCodeAt(h);return l%26/26})}},Nf=class extends Yi{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},If=class extends Bi{response;thrownErrorString;constructor(t){super(t),this.response=t.response,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.response??t;return await n?.handleLLMNewToken(r),r}},$f=class extends Bi{sleep=50;responses;thrownErrorString;constructor(t){super(t),this.sleep=t.sleep??this.sleep,this.responses=t.responses,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const e=this.responses?.[0];return this.responses=this.responses?.slice(1),e??t}async*_streamResponseChunks(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0];this.responses=this.responses?.slice(1);for(const s of r??t)await new Promise(o=>setTimeout(o,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},Rf=class extends pa{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async addUserMessage(t){this.messages.push(new pe(t))}async addAIMessage(t){this.messages.push(new N(t))}async clear(){this.messages=[]}},jf=class extends fo{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},Lf=class extends ro{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Ff=class extends au{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Df=class extends po{lc_namespace=["test","fake"];output=[new Ve({pageContent:"foo"}),new Ve({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Uf=class extends Q{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},Vf=class extends $r{name;description;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.schema=t.schema}async _call(t,e){return JSON.stringify(t)}},Bf=class extends ro{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(t=>{this.runPromiseResolver=t})}async persistRun(t){this.runPromiseResolver(t)}async extract(){return this.runPromise}},zf=class gc extends mo{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??dc}async addDocuments(e){const n=e.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),e)}async addVectors(e,n){const r=e.map((s,o)=>({content:n[o].pageContent,embedding:s,metadata:n[o].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,n,r){const s=c=>{if(!r)return!0;const l=new Ve({metadata:c.metadata,pageContent:c.content});return r(l)},o=this.memoryVectors.filter(s);return o.map((c,l)=>({similarity:this.similarity(e,c.embedding),index:l})).sort((c,l)=>c.similarity>l.similarity?-1:0).slice(0,n).map(c=>[new Ve({metadata:o[c.index].metadata,pageContent:o[c.index].content}),c.similarity])}static async fromTexts(e,n,r,s){const o=[];for(let i=0;i<e.length;i+=1){const a=Array.isArray(n)?n[i]:n,c=new Ve({pageContent:e[i],metadata:a});o.push(c)}return gc.fromDocuments(o,r,s)}static async fromDocuments(e,n,r){const s=new this(n,r);return await s.addDocuments(e),s}static async fromExistingIndex(e,n){return new this(e,n)}},yc={};J(yc,{FakeChatMessageHistory:()=>Rf,FakeChatModel:()=>Mf,FakeEmbeddings:()=>Nf,FakeLLM:()=>If,FakeListChatMessageHistory:()=>jf,FakeListChatModel:()=>Pf,FakeRetriever:()=>Df,FakeRunnable:()=>Uf,FakeSplitIntoListParser:()=>Ff,FakeStreamingChatModel:()=>Af,FakeStreamingLLM:()=>$f,FakeTool:()=>Vf,FakeTracer:()=>Lf,FakeVectorStore:()=>zf,SingleRunExtractor:()=>Bf,SyntheticEmbeddings:()=>Of});var wc={};J(wc,{agents:()=>md,caches:()=>wu,callbacks__base:()=>Wu,callbacks__manager:()=>Hu,callbacks__promises:()=>zu,chat_history:()=>fa,document_loaders__base:()=>Sa,document_loaders__langsmith:()=>Ea,documents:()=>xa,embeddings:()=>fh,example_selectors:()=>Pa,index:()=>yd,indexing:()=>ja,language_models__base:()=>yu,language_models__chat_models:()=>gu,language_models__llms:()=>Zl,load__serializable:()=>Bu,memory:()=>ma,messages:()=>Vu,messages__tool:()=>Uu,output_parsers:()=>mu,output_parsers__openai_functions:()=>Da,output_parsers__openai_tools:()=>Xl,outputs:()=>Du,prompt_values:()=>pu,prompts:()=>Za,retrievers:()=>_a,retrievers__document_compressors:()=>Qa,runnables:()=>fu,runnables__graph:()=>Fu,singletons:()=>Lu,stores:()=>ya,structured_query:()=>ic,tools:()=>Yl,tracers__base:()=>ju,tracers__console:()=>Ru,tracers__log_stream:()=>$u,tracers__run_collector:()=>ac,tracers__tracer_langchain:()=>Iu,types__stream:()=>pf,utils__async_caller:()=>Nu,utils__chunk_array:()=>dh,utils__env:()=>Ou,utils__event_source_parse:()=>cc,utils__format:()=>vf,utils__function_calling:()=>du,utils__hash:()=>hu,utils__json_patch:()=>uu,utils__json_schema:()=>Pu,utils__math:()=>fc,utils__stream:()=>Au,utils__testing:()=>yc,utils__tiktoken:()=>lu,utils__types:()=>cu,vectorstores:()=>ba});function Hf(t){const e={};for(let n=t;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(e).reduce((n,[r,s])=>(n[s]=r,n),{})}async function tr(t){const{optionalImportsMap:e={},optionalImportEntrypoints:n=[],importMap:r={},secretsMap:s={},path:o=["$"]}=this,i=o.join(".");if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="secret"){const a=t,[c]=a.id;if(c in s)return s[c];{const l=qu(c);if(l)return l;throw new Error(`Missing key "${c}" for ${i} in load(secretsMap={})`)}}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="not_implemented"){const c=JSON.stringify(t);throw new Error(`Trying to load an object that doesn't implement serialization: ${i} -> ${c}`)}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&"kwargs"in t&&t.lc===1){const a=t,c=JSON.stringify(a),[l,...u]=a.id.slice().reverse(),h=u.reverse(),d={langchain_core:wc,langchain:r};let f=null;const g=[h.join("/")];h[0]==="langchain_community"&&g.push(["langchain",...h.slice(1)].join("/"));const p=g.find(y=>y in e);if(pd.concat(n).includes(h.join("/"))||p)if(p!==void 0)f=await e[p];else throw new Error(`Missing key "${h.join("/")}" for ${i} in load(optionalImportsMap={})`);else{let y;if(h[0]==="langchain"||h[0]==="langchain_core")y=d[h[0]],h.shift();else throw new Error(`Invalid namespace: ${i} -> ${c}`);if(h.length===0)throw new Error(`Invalid namespace: ${i} -> ${c}`);let _;do{if(_=h.join("__"),_ in y)break;h.pop()}while(h.length>0);_ in y&&(f=y[_])}if(typeof f!="object"||f===null)throw new Error(`Invalid namespace: ${i} -> ${c}`);const b=f[l]??Object.values(f).find(y=>typeof y=="function"&&Ku(y)===l);if(typeof b!="function")throw new Error(`Invalid identifer: ${i} -> ${c}`);const C=await tr.call({...this,path:[...o,"kwargs"]},a.kwargs);if(a.type==="constructor"){const y=new b(Gu(C,Ju,Hf(b)));return Object.defineProperty(y.constructor,"name",{value:l}),y}else throw new Error(`Invalid type: ${i} -> ${c}`)}else if(typeof t=="object"&&t!==null)return Array.isArray(t)?Promise.all(t.map((a,c)=>tr.call({...this,path:[...o,`${c}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,c])=>[a,await tr.call({...this,path:[...o,a]},c)])));return t}async function Wf(t,e){const n=JSON.parse(t);return tr.call({...e},n)}function qf(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function Fs(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>Fs(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await Fs(r);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{const n=e.id[e.id.length-1];let r;switch(n){case"Set":r=Set;break;case"Map":r=Map;break;case"RegExp":r=RegExp;break;case"Error":r=Error;break;default:return e}return e.method?r[e.method](...e.args||[]):new r(...e.args||[])}catch{return e}else if(qf(e))return Wf(JSON.stringify(e));return e}}return t}function os(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function Kf(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?os(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?os(RegExp,void 0,[t.source,t.flags]):t instanceof Error?os(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var Gf=class{_dumps(t){return new TextEncoder().encode(dd(t,(n,r)=>Kf(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return Fs(e)}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function vc(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=vc(t[n]));return e}function _c(){return{v:4,id:da(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Sr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:vc(t.versions_seen)}}function bc(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function Jf(...t){return t.reduce((e,n,r)=>r===0?n:bc(e,n)>=0?e:n)}const Yf={[ad]:-1,[Yn]:-2,[cd]:-3,[ld]:-4};var hn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function Xf(t){if(t.length===0)throw new hn("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new hn(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new hn(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new hn(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new hn(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var Zf=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:r=10,offset:s=0,query:o}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:o}]))[0]}async put(t,e,n,r){Xf(t),await this.batch([{namespace:t,key:e,value:n,index:r}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:r,limit:s=100,offset:o=0}=t,i=[];return e&&i.push({matchType:"prefix",path:e}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:o}]))[0]}start(){}stop(){}};const Qf=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var ep=class extends Zf{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=Qf(t)}get isRunning(){return this.running}async batch(t){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(t,e){return this.enqueueOperation({namespace:t,key:e})}async search(t,e){const{filter:n,limit:r=10,offset:s=0,query:o}=e||{};return this.enqueueOperation({namespacePrefix:t,filter:n,limit:r,offset:s,query:o})}async put(t,e,n){return this.enqueueOperation({namespace:t,key:e,value:n})}async delete(t,e){return this.enqueueOperation({namespace:t,key:e,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(t){return new Promise((e,n)=>{const r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:t,resolve:e,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;const t=new Map(this.queue);this.queue.clear();try{const e=Array.from(t.values()).map(({operation:r})=>r),n=await this.store.batch(e);t.forEach(({resolve:r},s)=>{const o=Array.from(t.keys()).indexOf(s);r(n[o])})}catch(e){t.forEach(({reject:n})=>{n(e)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},tp=class{serde=new Gf;constructor(t){this.serde=t||this.serde}},np=class Sc extends In{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:n="openai",index:r=0,structuredResponse:s,indexRef:o,...i}={}){super(i),this.toolCalls=e,this.toolStyle=n,this.indexRef=o??{current:r},this.structuredResponse=s}get index(){return this.indexRef.current}set index(e){this.indexRef.current=e}_llmType(){return"fake-tool-calling"}_combineLLMOutput(){return[]}bindTools(e){const n=new Sc({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new Xt({func:async()=>this.structuredResponse})}async _generate(e,n,r){let o=e[e.length-1].content;e.length>1&&(o=e.map(h=>h.content).filter(Boolean).join("-")),(e.length===1||e.length===2&&e.every(pe.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],c=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const l=new N({content:o,id:c,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:o,message:l}],llmOutput:{}}}};class rp{constructor(){this.store=void 0}getStore(){return this.store}run(e,n,...r){this.store=e;try{return n(...r)}finally{this.store=void 0}}exit(e,...n){const r=this.store;this.store=void 0;try{return e(...n)}finally{this.store=r}}enterWith(e){this.store=e}disable(){this.store=void 0}}function sp(){Ue.initializeGlobalInstance(new rp)}var gt=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
124
+
125
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${e.lc_error_code}/
126
+ `),super(n),this.lc_error_code=e?.lc_error_code}},Cc=class extends gt{get is_bubble_up(){return!0}},op=class extends gt{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},nr=class extends gt{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},kt=class extends Cc{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Ec=class extends kt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Tc=class extends Cc{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function ip(t){return t!==void 0&&t.name===Tc.unminifiable_name}function rr(t){return t!==void 0&&t.is_bubble_up===!0}function ut(t){return t!==void 0&&[kt.unminifiable_name,Ec.unminifiable_name].includes(t.name)}var hi=class extends gt{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Z=class extends gt{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends gt{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},ap=class extends gt{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function xc(t){return t!=null&&t.lg_is_channel===!0}var yt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===Z.unminifiable_name)return!1;throw t}}};const Ds=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function xo(t){if(t[Ds]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];xc(r)&&(e[n]=r)}return Object.assign(e,{[Ds]:!0}),e}function Cr(t,e){const n=xo(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=e.channel_values[s];r[s]=n[s].fromCheckpoint(o)}return Object.assign(r,{[Ds]:!0}),r}function at(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{s[o]=e[o].checkpoint()}catch(i){if(i.name!==Z.unminifiable_name)throw i}}return{v:4,id:r?.id??da(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var Us=class kc extends yt{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(e,n){super(),this.operator=e,this.initialValueFactory=n,this.value=n?.()}fromCheckpoint(e){const n=new kc(this.operator,this.initialValueFactory);return typeof e<"u"&&(n.value=e),n}update(e){let n=e;if(!n.length)return!1;this.value===void 0&&([this.value]=n,n=n.slice(1));for(const r of n)this.value!==void 0&&(this.value=this.operator(this.value,r));return!0}get(){if(this.value===void 0)throw new Z;return this.value}checkpoint(){if(this.value===void 0)throw new Z;return this.value}isAvailable(){return this.value!==void 0}},ko=class Mc extends yt{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new Mc;return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new B("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Z;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Z;return this.value[0]}isAvailable(){return this.value.length!==0}},cp=class Ac extends yt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new Ac;if(typeof e<"u"){const[r,s]=e;n.value=[r],n.finished=s}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Z;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},lp=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const Vs=function(t){return t?Bs(t):new ko};Vs.Root=t=>new lp(t);function Bs(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new Us(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new Us(t.value,t.default):new ko}const F="__start__",O="__end__",je="__input__",up="__copy__",ae="__error__",is="__pregel_ns_writes",Qe="__pregel_send",Mo="__pregel_call",dt="__pregel_read",W="__pregel_checkpointer",qe="__pregel_resuming",vn="__pregel_task_id",Er="__pregel_stream",hp="__pregel_resume_value",sr="__pregel_resume_map",et="__pregel_scratchpad",or="__pregel_previous",Pc="__pregel_durability",zs="checkpoint_id",Ae="checkpoint_ns",dp="__pregel_node_finished",ye="checkpoint_map",di="__pregel_abort_signals",L="__interrupt__",le="__resume__",Ao="__no_writes__",tn="__return__",as="__previous__",q="langsmith:hidden",fp="langsmith:nostream",fi="__self__",ve="__pregel_tasks",de="__pregel_push",ir="__pregel_pull",_e="00000000-0000-0000-0000-000000000000",pp=[q,je,L,le,ae,Ao,Qe,dt,W,Pc,Er,qe,vn,Mo,hp,et,or,ye,Ae,zs],G="|",Be=":",pi=Symbol.for("langgraph.command");var mp=class{[pi];constructor(t){this[pi]=t}};function Hs(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var se=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=kn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function me(t){return t instanceof se}function Oc(t){return!t||typeof t!="object"||!(L in t)?!1:Array.isArray(t[L])}var K=class extends mp{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(t){super(t),this.resume=t.resume,this.graph=t.graph,this.update=t.update,t.goto&&(this.goto=Array.isArray(t.goto)?kn(t.goto):[kn(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:me(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function Y(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function kn(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((r,s)=>{n[s]=kn(r,e)});else if(Y(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(Hs(t)&&!(t instanceof se))n=new se(t.node,t.args),e.set(t,n);else if(Y(t)||me(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=kn(s,e)}return n}return t}const gp=["tags","metadata","callbacks","configurable"],yp=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],wp=25;function Nc(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:wp,configurable:{}},n=Ue.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(gp.includes(r)){let o;Array.isArray(s)?o=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?o=s.copy():o={...s}:o=s,e[r]=o}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,o]of Object.entries(r))o!==void 0&&yp.includes(s)&&(e[s]=o);for(const[r,s]of Object.entries(e.configurable))e.metadata=e.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in e.metadata)&&(e.metadata[r]=s);return e}function vp(){return Ue.getRunnableConfig()}function cs(t){return t.split(G).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(Be)[0]).join(G)}function _p(t){const e=t.split(G);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(G)}const k=t=>BigInt(t),D=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Ic=k("0x9E3779B1"),$c=k("0x85EBCA77"),bp=k("0xC2B2AE3D"),rt=k("0x9E3779B185EBCA87"),pt=k("0xC2B2AE3D27D4EB4F"),Rc=k("0x165667B19E3779F9"),Po=k("0x85EBCA77C2B2AE63"),Sp=k("0x27D4EB2F165667C5"),Cp=k("0x165667919E3779F9"),Ep=k("0x9FB21C651E98DF25"),Tp=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,r=new Uint8Array(n);let s=0,o=0;for(;o<n;){const i=t.slice(s,s+=2);r[o]=Number.parseInt(i,16),o+=1}return D(r)},Me=Tp("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Mt=(k(1)<<k(128))-k(1),$=(k(1)<<k(64))-k(1),Tr=(k(1)<<k(32))-k(1),Le=64,jc=Le/8,xp=8,Un=4;function nn(t){if(!t)throw new Error("Assert failed")}function kp(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Mp(t){let e=t;return e=(e&k(65535))<<k(16)|(e&k(4294901760))>>k(16),e=(e&k(16711935))<<k(8)|(e&k(4278255360))>>k(8),e}function Ap(t,e){return(t&Tr)*(e&Tr)&$}function Pp(t,e){return(t<<e|t>>k(32)-e)&Tr}function Lc(t,e,n){for(let r=0;r<jc;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Ap(o,o>>k(32))}return t}function mi(t,e,n,r){for(let s=0;s<r;s+=1)Lc(t,D(e,s*Le),D(n,s*8));return t}function Op(t,e){for(let n=0;n<jc;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Ws(s,k(47)),s^=r,s*=Ic,t[n]=s&$}return t}function Vn(t,e){return Fc(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(xp,!0))}function gi(t,e,n){let r=n;return r+=Vn(t.slice(0),D(e,0*Un)),r+=Vn(t.slice(2),D(e,4*Un)),r+=Vn(t.slice(4),D(e,8*Un)),r+=Vn(t.slice(6),D(e,12*Un)),Oe(r&$)}function Np(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Le)/8),a=Le*i,c=Math.floor((e.byteLength-1)/a);for(let l=0;l<c;l+=1)o=mi(o,D(e,l*a),n,i),o=s(o,D(n,n.byteLength-Le));{const l=Math.floor((e.byteLength-1-a*c)/Le);o=mi(o,D(e,c*a),n,l),o=r(o,D(e,e.byteLength-Le),D(n,n.byteLength-Le-7))}return o}function Ip(t,e){let n=new BigUint64Array([bp,rt,pt,Rc,Po,$c,Sp,Ic]);nn(t.byteLength>128),n=Np(n,t,e,Lc,Op),nn(n.length*8===64);{const r=gi(n,D(e,11),k(t.byteLength)*rt&$);return gi(n,D(e,e.byteLength-Le-11),~(k(t.byteLength)*pt)&$)<<k(64)|r}}function Fc(t,e){const n=t*e&Mt;return n&$^n>>k(64)}function yi(t,e,n){return Fc((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&$,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&$)}function ar(t,e,n,r,s){let o=t&$,i=t>>k(64)&$;return o+=yi(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=$,i+=yi(n,D(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=$,i<<k(64)|o}function Oe(t){let e=t;return e^=e>>k(37),e*=Cp,e&=$,e^=e>>k(32),e}function xr(t){let e=t;return e^=e>>k(33),e*=pt,e&=$,e^=e>>k(29),e*=Rc,e&=$,e^=e>>k(32),e}function $p(t,e,n){const r=t.byteLength;nn(r>0&&r<=3);const s=k(t.getUint8(r-1))|k(r<<8)|k(t.getUint8(0)<<16)|k(t.getUint8(r>>1)<<24),o=(k(e.getUint32(0,!0))^k(e.getUint32(4,!0)))+n,i=(s^o)&$,a=(k(e.getUint32(8,!0))^k(e.getUint32(12,!0)))-n,c=(Pp(Mp(s),k(13))^a)&$;return(xr(c)&$)<<k(64)|xr(i)}function Ws(t,e){return t^t>>e}function Rp(t,e,n){const r=t.byteLength;nn(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0),i=k(s)|k(o)<<k(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&$;let l=(i^a)*(rt+(k(r)<<k(2)))&Mt;return l+=(l&$)<<k(65),l&=Mt,l^=l>>k(67),Ws(Ws(l&$,k(35))*Ep&$,k(28))|Oe(l>>k(64))<<k(64)}}function jp(t,e,n){const r=t.byteLength;nn(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&$,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&$,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),c=(i^a^s)*rt;const l=(c&$)+(k(r-1)<<k(54));c=c&(Mt^$)|l,a^=o,c+=a+(a&Tr)*($c-k(1))<<k(64),c&=Mt,c^=kp(c>>k(64));let u=(c&$)*pt;return u+=(c>>k(64))*pt<<k(64),u&=Mt,Oe(u&$)|Oe(u>>k(64))<<k(64)}}function Lp(t,e){const n=t.byteLength;return nn(n<=16),n>8?jp(t,Me,e):n>=4?Rp(t,Me,e):n>0?$p(t,Me,e):xr(e^Me.getBigUint64(64,!0)^Me.getBigUint64(72,!0))|xr(e^Me.getBigUint64(80,!0)^Me.getBigUint64(88,!0))<<k(64)}function qs(t){return~t+k(1)&$}function Fp(t,e,n){let r=k(t.byteLength)*rt&$,s=k(t.byteLength-1)/k(32);for(;s>=0;){const a=Number(s);r=ar(r,D(t,16*a),D(t,t.byteLength-16*(a+1)),D(e,32*a),n),s-=k(1)}let o=r+(r>>k(64))&$;o=Oe(o);let i=(r&$)*rt+(r>>k(64))*Po+(k(t.byteLength)-n&$)*pt;return i&=$,i=qs(Oe(i)),o|i<<k(64)}function Dp(t,e,n){let r=k(t.byteLength)*rt&$;for(let i=32;i<160;i+=32)r=ar(r,D(t,i-32),D(t,i-16),D(e,i-32),n);r=Oe(r&$)|Oe(r>>k(64))<<k(64);for(let i=160;i<=t.byteLength;i+=32)r=ar(r,D(t,i-32),D(t,i-16),D(e,3+i-160),n);r=ar(r,D(t,t.byteLength-16),D(t,t.byteLength-32),D(e,103),qs(n));let s=r+(r>>k(64))&$;s=Oe(s);let o=(r&$)*rt+(r>>k(64))*Po+(k(t.byteLength)-n&$)*pt;return o&=$,o=qs(Oe(o)),s|o<<k(64)}function it(t,e=k(0)){const n=new TextEncoder,r=D(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(Lp(r,e)):s<=128?o(Fp(r,Me,e)):s<=240?o(Dp(r,Me,e)):o(Ip(r,Me))}function Dc(t){return/^[0-9a-f]{32}$/.test(t)}function Uc(t){const e=Ue.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n[W])throw new nr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[et];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[Qe]?.([[le,s.resume]]),s.resume[o];if(s.nullResume!==void 0){if(s.resume.length!==o)throw new Error(`Resume length mismatch: ${s.resume.length} !== ${o}`);const c=s.consumeNullResume();return s.resume.push(c),n[Qe]?.([[le,s.resume]]),c}const i=n[Ae]?.split(G),a=i?it(i.join(G)):void 0;throw new kt([{id:a,value:t}])}var wt=class extends Q{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,o)=>{const i=wn(n,{callbacks:r?.getChild()});Ue.runWithConfig(i,async()=>{try{const a=await this.func(e,i);s(a)}catch(a){o(a)}})})}async invoke(e,n){let r;const s=Nc(n),o=Fe(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await Ue.runWithConfig(o,async()=>this.func(e,o)),Q.isRunnable(r)&&this.recurse?await Ue.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*He(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ke(t){const e=[];for await(const n of await t)e.push(n);return e}function pn(t){const e=[];for(const n of t)e.push(n);return e}function _t(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function Up(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const ft={[Symbol.for("LG_PASSTHROUGH")]:!0};function Bn(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const ls=Symbol("IS_WRITER");var oe=class Ks extends wt{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>me(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:e,name:r,tags:n,func:async(s,o)=>this._write(s,o??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>us(s)&&Bn(s.value)?{mapper:s.mapper,value:e}:cr(s)&&Bn(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Ks.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(cr(o)){if(o.channel===ve)throw new B("Cannot write to the reserved channel TASKS");if(Bn(o.value))throw new B("PASSTHROUGH value must be replaced")}if(us(o)&&Bn(o.value))throw new B("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(me(o))r.push([ve,o]);else if(us(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(cr(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(Up(i)||o.skipNone&&i===void 0)continue;r.push([o.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);const s=e.configurable?.[Qe];s(r)}static isWriter(e){return e instanceof Ks||ls in e&&!!e[ls]}static registerWriter(e){return Object.defineProperty(e,ls,{value:!0})}};function cr(t){return t!==void 0&&typeof t.channel=="string"}function us(t){return t!==void 0&&!cr(t)&&Q.isRunnable(t.mapper)}var Vp=class Vc extends wt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Vc.doRead(o,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,n,r,s){const o=e.configurable?.[dt];if(!o)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return s?s(o(n,r)):o(n,r)}};const bt=new vu;var Mn=class mn extends Pe{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=bt;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:o,bound:i,kwargs:a,metadata:c,retryPolicy:l,cachePolicy:u,tags:h,subgraphs:d,ends:f}=e,g=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??bt,config:{...e.config?e.config:{},tags:g}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=o??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=c??this.metadata,this.tags=g,this.retryPolicy=l,this.cachePolicy=u,this.subgraphs=d,this.ends=f}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof oe&&e[e.length-2]instanceof oe;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new oe(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===bt&&e.length===0))return this.bound===bt&&e.length===1?e[0]:this.bound===bt?new nt({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new nt({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(e){if(!Array.isArray(e))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new mn({channels:{...this.channels,...Object.fromEntries(e.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(e){return oe.isWriter(e)?new mn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,e],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===bt?new mn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Zt(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new mn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function Bp(t){return"steps"in t&&Array.isArray(t.steps)}function Oo(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Bc(t){const e=[t];for(const n of e){if(Oo(n))return n;Bp(n)&&e.push(...n.steps)}}function At(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===Z.unminifiable_name){if(r)return s;if(n)return null}throw s}}function mt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=At(t,s,!n)}catch(o){if(o.name===Z.unminifiable_name)continue}return r}else return At(t,e)}function*zp(t,e){if(t.graph===K.PARENT)throw new B("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(me(r))yield[_e,ve,r];else if(typeof r=="string")yield[_e,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(Dc))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===le).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,le,s]}else yield[_e,le,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[_e,n,r];else for(const[n,r]of Object.entries(t.update))yield[_e,n,r]}}function*zc(t,e){if(e!=null)if(Array.isArray(t)&&typeof e=="object"&&!Array.isArray(e))for(const n in e)t.includes(n)&&(yield[n,e[n]]);else{if(Array.isArray(t))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[t,e]}}function*hs(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield mt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield At(n,t))}function*Hp(t,e,n){const r=e.filter(([a,c])=>(a.config===void 0||!a.config.tags?.includes(q))&&c[0][0]!==ae&&c[0][0]!==L);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([c,l])=>c===tn))?s=r.flatMap(([a])=>a.writes.filter(([c,l])=>c===tn).map(([c,l])=>[a.name,l])):Array.isArray(t)?s=r.flatMap(([a])=>{const{writes:c}=a,l={};for(const[u]of c)t.includes(u)&&(l[u]=(l[u]||0)+1);return Object.values(l).some(u=>u>1)?c.filter(([u])=>t.includes(u)).map(([u,h])=>[a.name,{[u]:h}]):[[a.name,Object.fromEntries(c.filter(([u])=>t.includes(u)))]]}):s=r.flatMap(([a])=>a.writes.filter(([c,l])=>c===t).map(([c,l])=>[a.name,l]));const o={};for(const[a,c]of s)a in o||(o[a]=[]),o[a].push(c);const i={};for(const a in o)if(o[a].length===1){const[c]=o[a];i[a]=c}else i[a]=o[a];n&&(i.__metadata__={cached:n}),yield i}function No(t){const e=typeof t[F];if(e==="number")return 0;if(e==="string")return"";for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=typeof t[n];if(r==="number")return 0;if(r==="string")return"";break}}function lr(t,e){if(Object.keys(t).length>0){const n=No(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function Wp(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Ce(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function ot(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Ce(t,{[ye]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function kr(...t){const e=[...new Set(t.filter(Boolean))];if(e.length===0)return{signal:void 0,dispose:void 0};if(e.length===1)return{signal:e[0],dispose:void 0};const n=new AbortController,r=()=>{const o=e.find(i=>i.aborted)?.reason;n.abort(o),e.forEach(i=>i.removeEventListener("abort",r))};e.forEach(o=>o.addEventListener("abort",r,{once:!0}));const s=e.find(o=>o.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(o=>o.removeEventListener("abort",r))}}}const qp=(t,e)=>{if(!(!t&&!e))return t?e?Array.isArray(t)&&Array.isArray(e)?[...t,...e]:Array.isArray(t)?[...t,e]:Array.isArray(e)?[t,...e]:[t,e]:t:e};var Kp=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:t,name:e,input:n,retry:r,cache:s,callbacks:o}){this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.callbacks=o}};function Gp(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Jp(t,e){const n=new wt({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new nt({name:t,first:n,last:new oe([{channel:tn,value:ft}],[q])})}const Yp=t=>t!==void 0?t+1:1;function Xp(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function Zp(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=Jf(e,t[n]));return e}function zn(t,e,n){const r=No(t.channel_versions),s=t.versions_seen[L]??{};let o=!1;if((t.channel_versions[F]??r)>(s[F]??r))o=!0;else for(const a in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,a)&&t.channel_versions[a]>(s[a]??r)){o=!0;break}const i=n.some(a=>e==="*"?!a.config?.tags?.includes(q):e.includes(a.name));return o&&i}function ur(t,e,n,r,s=!1){let o=new Set;if(Array.isArray(r))o=new Set(r.filter(a=>n.writes.some(([c,l])=>c===a)));else{for(const[a]of n.writes)if(a===r){o=new Set([a]);break}o=o||new Set}let i;if(s&&o.size>0){const a=Object.fromEntries(Object.entries(e).filter(([u,h])=>o.has(u))),c=at(t,a,-1),l=Cr(a,c);he(Sr(c),l,[n],void 0,void 0),i=mt({...e,...l},r)}else i=mt(e,r);return i}function ds(t,e,n){for(const[r,s]of n)if([de,ve].includes(r)&&s!=null){if(!me(s))throw new B(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new B(`Invalid node name "${s.node}" in Send packet`)}t(n)}const Qp=new Set([Ao,de,le,L,tn,ae]);function he(t,e,n,r,s){n.sort((d,f)=>{const g=d.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let b=0;b<Math.min(g.length,p.length);b+=1){if(g[b]<p[b])return-1;if(g[b]>p[b])return 1}return g.length-p.length});const o=n.some(d=>d.triggers.length>0),i=xo(e);for(const d of n){t.versions_seen[d.name]??={};for(const f of d.triggers)f in t.channel_versions&&(t.versions_seen[d.name][f]=t.channel_versions[f])}let a=Zp(t.channel_versions);const c=new Set(n.flatMap(d=>d.triggers).filter(d=>!pp.includes(d)));let l=!1;for(const d of c)d in i&&i[d].consume()&&r!==void 0&&(t.channel_versions[d]=r(a),l=!0);const u={};for(const d of n)for(const[f,g]of d.writes)Qp.has(f)||f in i&&(u[f]??=[],u[f].push(g));a!=null&&r!=null&&(a=l?r(a):a);const h=new Set;for(const[d,f]of Object.entries(u))if(d in i){const g=i[d];let p;try{p=g.update(f)}catch(b){if(b.name===B.unminifiable_name){const C=new B(`Invalid update for channel "${d}" with values ${JSON.stringify(f)}: ${b.message}`);throw C.lc_error_code=b.lc_error_code,C}else throw b}p&&r!==void 0&&(t.channel_versions[d]=r(a),g.isAvailable()&&h.add(d))}if(o)for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.isAvailable()&&!h.has(d)&&f.update([])&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}if(o&&!Xp(h,s))for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.finish()&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}return h}function*em(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const s=new Set;for(const o of n.updatedChannels){const i=n.triggerToNodes[o];for(const a of i??[])s.add(a)}yield*[...s].sort();return}if(!(()=>{for(const s in t.channel_versions)if(t.channel_versions[s]!==null)return!1;return!0})())for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(yield s)}function Tt(t,e,n,r,s,o,i){const a={},c=r[ve];if(c?.isAvailable()){const l=c.get().length;for(let u=0;u<l;u+=1){const h=Gs([de,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const l of em(t,n,i)){const u=Gs([ir,l],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function Gs(t,e,n,r,s,o,i,a){const{step:c,checkpointer:l,manager:u}=a,h=o.configurable??{},d=h.checkpoint_ns??"";if(t[0]===de&&Gp(t[t.length-1])){const f=t[t.length-1],g=Jp(f.name,f.func),p=[de],b=d===""?f.name:`${d}${G}${f.name}`,C=St(JSON.stringify([b,c.toString(),f.name,de,t[1],t[2]]),e.id),y=`${b}${Be}${C}`,_=[...t.slice(0,3),!0],w={langgraph_step:c,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:_,langgraph_checkpoint_ns:y};if(i){const E=[];return{name:f.name,input:f.input,proc:g,writes:E,config:wn(Fe(o,{metadata:w,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[vn]:C,[Qe]:v=>ds(S=>E.push(...S),r,v),[dt]:(v,S=!1)=>ur(e,s,{name:f.name,writes:E,triggers:p,path:_},v,S),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[et]:fs({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:o.configurable?.[sr],namespaceHash:it(y)}),[or]:e.channel_values[as],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:it((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[is,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:C,path:_,writers:[]}}else return{id:C,name:f.name,interrupts:[],path:_}}else if(t[0]===de){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[ve]?.isAvailable())return;const g=s[ve].get();if(f<0||f>=g.length)return;const p=Hs(g[f])&&!me(g[f])?new se(g[f].node,g[f].args):g[f];if(!Hs(p)){console.warn(`Ignoring invalid packet ${JSON.stringify(p)} in pending sends.`);return}if(!(p.node in r)){console.warn(`Ignoring unknown node name ${p.node} in pending sends.`);return}const b=[de],C=d===""?p.node:`${d}${G}${p.node}`,y=St(JSON.stringify([C,c.toString(),p.node,de,f.toString()]),e.id),_=`${C}${Be}${y}`;let w={langgraph_step:c,langgraph_node:p.node,langgraph_triggers:b,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:_};if(i){const E=r[p.node],T=E.getNode();if(T!==void 0){E.metadata!==void 0&&(w={...w,...E.metadata});const v=[];return{name:p.node,input:p.args,proc:T,subgraphs:E.subgraphs,writes:v,config:wn(Fe(o,{metadata:w,tags:E.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[vn]:y,[Qe]:S=>ds(x=>v.push(...x),r,S),[dt]:(S,x=!1)=>ur(e,s,{name:p.node,writes:v,triggers:b,path:t},S,x),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[et]:fs({pendingWrites:n??[],taskId:y,currentTaskInput:p.args,resumeMap:o.configurable?.[sr],namespaceHash:it(_)}),[or]:e.channel_values[as],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:b,retry_policy:E.retryPolicy,cache_key:E.cachePolicy?{key:it((E.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[is,E.name??"__dynamic__",p.node],ttl:E.cachePolicy.ttl}:void 0,id:y,path:t,writers:E.getWriters()}}}else return{id:y,name:p.node,interrupts:[],path:t}}else if(t[0]===ir){const f=t[1].toString(),g=r[f];if(g===void 0)return;if(n?.length){const y=d===""?f:`${d}${G}${f}`,_=St(JSON.stringify([y,c.toString(),f,ir,f]),e.id);if(n.some(E=>E[0]===_&&E[1]!==ae))return}const p=No(e.channel_versions);if(p===void 0)return;const b=e.versions_seen[f]??{},C=g.triggers.find(y=>s[y].isAvailable()?(e.channel_versions[y]??p)>(b[y]??p):!1);if(C!==void 0){const y=tm(g,s,i);if(y===void 0)return;const _=d===""?f:`${d}${G}${f}`,w=St(JSON.stringify([_,c.toString(),f,ir,[C]]),e.id),E=`${_}${Be}${w}`;let T={langgraph_step:c,langgraph_node:f,langgraph_triggers:[C],langgraph_path:t,langgraph_checkpoint_ns:E};if(i){const v=g.getNode();if(v!==void 0){g.metadata!==void 0&&(T={...T,...g.metadata});const S=[];return{name:f,input:y,proc:v,subgraphs:g.subgraphs,writes:S,config:wn(Fe(o,{metadata:T,tags:g.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[vn]:w,[Qe]:x=>ds(M=>{S.push(...M)},r,x),[dt]:(x,M=!1)=>ur(e,s,{name:f,writes:S,triggers:[C],path:t},x,M),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[et]:fs({pendingWrites:n??[],taskId:w,currentTaskInput:y,resumeMap:o.configurable?.[sr],namespaceHash:it(E)}),[or]:e.channel_values[as],checkpoint_id:void 0,checkpoint_ns:E}}),triggers:[C],retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:it((g.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[is,g.name??"__dynamic__",f],ttl:g.cachePolicy.ttl}:void 0,id:w,path:t,writers:g.getWriters()}}}else return{id:w,name:f,interrupts:[],path:t}}}}function tm(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,o]of Object.entries(t.channels))if(t.triggers.includes(o))try{r[s]=At(e,o,!1)}catch(i){if(i.name===Z.unminifiable_name)return;throw i}else if(o in e)try{r[s]=At(e,o,!1)}catch(i){if(i.name===Z.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=At(e,o,!1),s=!0;break}catch(i){if(i.name===Z.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function fs({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([c,l])=>c===_e&&l===le)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const c=t.filter(([l,u])=>l===e&&u===le).flatMap(([l,u,h])=>h);if(r!=null&&s in r){const l=r[s];c.push(l)}return c})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,t.splice(t.findIndex(([c,l])=>c===_e&&l===le),1),o}};return a}const An={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Pn=(t,e)=>`${t.start}${e}${t.end}`;function*wi(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t){if(s?.tags?.includes(q))continue;const a=i.filter(([c,l])=>c===e&&l===L).map(([,c])=>c);yield{id:e,name:n,input:r,triggers:o,interrupts:a}}}function nm(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Hc(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=nm(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*rm(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(q)||(yield{id:n,name:r,result:Hc(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===L).map(i=>i[1])})}function*sm(t,e,n,r,s,o,i,a){function c(h){const d={};return h.callbacks!=null&&(d.callbacks=h.callbacks),h.configurable!=null&&(d.configurable=h.configurable),h.maxConcurrency!=null&&(d.max_concurrency=h.maxConcurrency),h.metadata!=null&&(d.metadata=h.metadata),h.recursionLimit!=null&&(d.recursion_limit=h.recursionLimit),h.runId!=null&&(d.run_id=h.runId),h.runName!=null&&(d.run_name=h.runName),h.tags!=null&&(d.tags=h.tags),d}const l=t.configurable?.checkpoint_ns,u={};for(const h of s){if(!(h.subgraphs?.length?h.subgraphs:[h.proc]).find(Bc))continue;let f=`${h.name}:${h.id}`;l&&(f=`${l}|${f}`),u[h.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:f}}}yield{config:c(t),values:mt(e,n),metadata:r,next:s.map(h=>h.name),tasks:Wc(s,o,u,a),parentConfig:i?c(i):void 0}}function Wc(t,e,n,r){return t.map(s=>{const o=e.find(([l,u])=>l===s.id&&u===ae)?.[2],i=e.filter(([l,u])=>l===s.id&&u===L).map(([,,l])=>l),a=(()=>{if(o||i.length||!e.length)return;const l=e.findIndex(([u,h])=>u===s.id&&h===tn);if(l>=0)return e[l][2];if(typeof r=="string")return e.find(([u,h])=>u===s.id&&h===r)?.[2];if(Array.isArray(r)){const u=e.filter(([h,d])=>h===s.id&&r.includes(d)).map(([,h,d])=>[h,d]);return u.length?Hc(u):void 0}})();if(o)return{id:s.id,name:s.name,path:s.path,error:o,interrupts:i,result:a};const c=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...c!==void 0?{state:c}:{},result:a}})}function om(t,e,n){console.log([`${Pn(An.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
127
+ `,JSON.stringify(mt(e,n),null,2)].join(""))}function qc(t,e){const n=e.length;console.log([`${Pn(An.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
128
+ `,e.map(r=>`- ${Pn(An.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
129
+ `)].join(""))}function im(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${Pn(An.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
130
+ `,Object.entries(r).map(([s,o])=>`- ${Pn(An.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
131
+ `)].join(""))}var vi=class extends bn{_abortController;_innerReader;constructor(t,e){const n=t.getReader(),r=e??new AbortController;super({start(s){return o();function o(){return n.read().then(({done:i,value:a})=>{if(i){s.close();return}return s.enqueue(a),o()})}}}),this._abortController=r,this._innerReader=n}async cancel(t){this._abortController.abort(t),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},Kc=class extends bn{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(t){let e;const n=new Promise(r=>{e=r});super({start:r=>{e(r)}}),n.then(r=>{this.controller=r}),this.passthroughFn=t.passthroughFn,this.modes=t.modes}push(t){this.passthroughFn?.(t),this.controller.enqueue(t)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(t){this.controller.error(t)}};function am(t){return JSON.stringify(t,function(e,n){const r=this[e];if(r!=null&&typeof r=="object"&&"toDict"in r&&typeof r.toDict=="function"){const{type:s,data:o}=r.toDict();return{...o,type:s}}return n})}function cm(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function Io(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function ps(t){return!Io(t)||!t.configurable.thread_id?null:{thread_id:t.configurable.thread_id,checkpoint_ns:t.configurable.checkpoint_ns||"",checkpoint_id:t.configurable.checkpoint_id||null,checkpoint_map:t.configurable.checkpoint_map||null}}function _i(t){if(Io(t)){const e=Object.fromEntries(Object.entries(t.configurable).filter(([r])=>!r.startsWith("__"))),n={...t,configurable:e};return delete n.callbacks,n}return t}function bi(t){const e={...t,checkpoint:ps(t.config),parent_checkpoint:ps(t.parentConfig),config:_i(t.config),parent_config:_i(t.parentConfig),tasks:t.tasks.map(n=>{if(Io(n.state)){const r=ps(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function lm(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
132
+ data: ${am(s.data)}
133
+
134
+ `))};try{for await(const s of t){const[o,i,a]=s;let c=a;if(i==="debug"){const u=a;u.type==="checkpoint"&&(c={...u,payload:bi(u.payload)})}i==="checkpoints"&&(c=bi(a));const l=o?.length?`${i}|${o.join("|")}`:i;r({event:l,data:c})}}catch(s){r({event:"error",data:cm(s)})}n.close()}})}const Hn=Symbol.for("INPUT_DONE"),ms=Symbol.for("INPUT_RESUMING"),um=25;function hm(...t){return new Kc({passthroughFn:e=>{for(const n of t)n.modes.has(e[1])&&n.push(e)},modes:new Set(t.flatMap(e=>Array.from(e.modes)))})}var dm=class extends tp{cache;queue=Promise.resolve();constructor(t){super(),this.cache=t}async get(t){return this.enqueueOperation("get",t)}async set(t){return this.enqueueOperation("set",t)}async clear(t){return this.enqueueOperation("clear",t)}async stop(){await this.queue}enqueueOperation(t,...e){const n=this.queue.then(()=>this.cache[t](...e));return this.queue=n.then(()=>{},()=>{}),n}},fm=class Gc{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(F in this.checkpoint.channel_versions)e=!0;else for(const c in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,c)){e=!0;break}const r=this.config.configurable?.[qe]!==void 0&&this.config.configurable?.[qe],s=this.input===null||this.input===void 0,o=Y(this.input)&&this.input.resume!=null,i=this.input===ms,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(r||s||o||i||a)}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=Yp,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new dm(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes}static async initialize(e){let{config:n,stream:r}=e;r!==void 0&&n.configurable?.[Er]!==void 0&&(r=hm(r,n.configurable[Er]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[et];n.configurable&&o&&(o.subgraphCounter>0&&(n=Ce(n,{[Ae]:[n.configurable[Ae],o.subgraphCounter.toString()].join(G)})),o.subgraphCounter+=1);const i=dt in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Ce(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ye]!==void 0&&n.configurable?.[ye]?.[n.configurable?.checkpoint_ns]&&(a=Ce(n,{checkpoint_id:n.configurable[ye][n.configurable?.checkpoint_ns]}));const c=n.configurable?.checkpoint_ns?.split(G)??[],l=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:_c(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...l.config,configurable:{checkpoint_ns:"",...n.configurable,...l.config.configurable}};const u=l.parentConfig,h=Sr(l.checkpoint),d={...l.metadata},f=l.pendingWrites??[],g=Cr(e.channelSpecs,h),p=(d.step??0)+1,b=p+(n.recursionLimit??um)+1,C={...h.channel_versions},y=e.store?new ep(e.store):void 0;return y&&await y.start(),new Gc({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:c,channels:g,isNested:i,manager:e.manager,skipDoneTasks:s,step:p,stop:b,checkpointPreviousVersions:C,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:y,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(e,n){let r=n;if(r.length===0)return;r.every(([i])=>i in Yf)&&(r=Array.from(new Map(r.map(i=>[i[0],i])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(i=>i[0]!==e);for(const[i,a]of r)this.checkpointPendingWrites.push([e,i,a]);const s=Ce(this.checkpointConfig,{[Ae]:this.config.configurable?.checkpoint_ns??"",[zs]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(s,r,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||n[0][0]===ae||n[0][0]===L||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,n,r=!1){const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(q))return;if(n.length>0)if(n[0][0]===L){if(s.path?.[0]===de&&s.path?.at(-1)===!0)return;const o=n.filter(i=>i[0]===L).flatMap(i=>i[1]);this._emit([["updates",{[L]:o}],["values",{[L]:o}]])}else n[0][0]!==ae&&this._emit(pn(He(Hp(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(pn(He(rm([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([i,a])=>`ns:${i.join(",")}|key:${a}`,r=[],s={};for(const i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];const o=await this.cache.get(r);for(const{key:i,value:a}of o){const c=s[n(i)];c!=null&&(c.writes.push(...a),e.push({task:c,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:n=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Hn,ms].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new kt;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await Ke(He(hs(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),zn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new kt;this.config.configurable?.[qe]!==void 0&&delete this.config.configurable?.[qe]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=Tt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels});if(this.tasks=r,this.checkpointer&&this._emit(await Ke(He(sm(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[o,i,a]of this.checkpointPendingWrites){if(i===ae||i===L||i===le)continue;const c=Object.values(this.tasks).find(l=>l.id===o);c&&c.writes.push([i,a])}for(const o of Object.values(this.tasks))o.writes.length>0&&this._outputWrites(o.id,o.writes,!0)}if(Object.values(this.tasks).every(o=>o.writes.length>0))return this.tick({inputKeys:n});if(zn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new kt;const s=await Ke(He(wi(Object.values(this.tasks)),"tasks"));return this._emit(s),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(Be)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=mt(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(pn(He(hs(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),ut(e)&&!e.interrupts.length&&this._emit([["updates",{[L]:[]}],["values",{[L]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&zn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=Gs([de,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&zn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(pn(He(wi([s]),"tasks"))),this.debug&&qc(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const o=await this._matchCachedWrites();for(const{task:i}of o)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(e){return ut(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[et];if(r&&r.nullResume!==void 0&&this.putWrites(_e,[[le,r.nullResume]]),Y(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Dc)&&(this.config.configurable??={},this.config.configurable[sr]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[c,l,u]of zp(this.input,this.checkpointPendingWrites))a[c]??=[],a[c].push([l,u]);if(Object.keys(a).length===0)throw new hi("Received empty Command input");for(const[c,l]of Object.entries(a))this.putWrites(c,l)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===_e).map(i=>i.slice(1));s.length>0&&he(this.checkpoint,this.channels,[{name:je,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=Y(this.input)&&s.length>0;if(this.isResuming||o){for(const a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){const c=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[L]={...this.checkpoint.versions_seen[L],[a]:c}}const i=await Ke(He(hs(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=ms;else if(o)await this._putCheckpoint({source:"input"}),this.input=Hn;else{const i=await Ke(zc(e,this.input));if(i.length>0){const a=Tt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=he(this.checkpoint,this.channels,Object.values(a).concat([{name:je,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Hn}else if(qe in(this.config.configurable??{}))this.input=Hn;else throw new hi(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Ce(this.config,{[qe]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Ce(this.checkpointConfig,{[Ae]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=lr(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Sr(o),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.[ye]??{}}),this.checkpoint=at(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=Ce(this.checkpointConfig,{[Ae]:this.config.configurable?.checkpoint_ns??"",[zs]:this.checkpoint.id}),n={};for(const[r,s,o]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,o]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,s,r))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r===ae||r===L||r===le)continue;const o=Object.values(e).find(i=>i.id===n);o&&o.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function pm(t){return Re(t?.message)}var mm=class extends Yu{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(t){super(),this.streamFn=t}_emit(t,e,n,r=!1){if(r&&e.id!==void 0&&this.seen[e.id]!==void 0)return;let s=e.id;n!=null&&(Xu(e)?s??=`run-${n}-tool-${e.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==e.id&&(e.id=s,e.lc_kwargs.id=s),e.id!=null&&(this.seen[e.id]=e),this.streamFn([t[0],"messages",[e,t[1]]])}handleChatModelStart(t,e,n,r,s,o,i,a){i&&(!o||!o.includes(fp)&&!o.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:o,name:a,...i}])}handleLLMNewToken(t,e,n,r,s,o){const i=o?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(pm(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Yt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];Re(n?.message)&&this._emit(this.metadatas[e],n?.message,e,!0),delete this.emittedChatModelRunIds[e]}delete this.metadatas[e],delete this.stableMessageIdMap[e]}}handleLLMError(t,e){delete this.metadatas[e]}handleChainStart(t,e,n,r,s,o,i,a){if(o!==void 0&&a===o.langgraph_node&&(s===void 0||!s.includes(q))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const c of Object.values(e))if((Re(c)||Vo(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(const l of c)(Re(l)||Vo(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(t,e){const n=this.metadatas[e];if(delete this.metadatas[e],n!==void 0){if(Re(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)Re(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(Re(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)Re(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const gm=500,ym=2,wm=128e3,vm=3,_m=[400,401,402,403,404,405,406,407,409],bm=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t.name==="GraphValueError"||t?.code==="ECONNABORTED")return!1;const e=t?.response?.status??t?.status;return!(e&&_m.includes(+e)||t?.error?.code==="insufficient_quota")};async function Jc(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??gm:0,i=0,a,c,{config:l}=t;for(n&&(l=Ce(l,n)),l={...l,signal:r};!r?.aborted;){t.writes.splice(0,t.writes.length),a=void 0;try{c=await t.proc.invoke(t.input,l);break}catch(u){if(a=u,a.pregelTaskId=t.id,ip(a)){const g=l?.configurable?.checkpoint_ns,p=a.command;if(p.graph===g){for(const b of t.writers)await b.invoke(p,l);a=void 0;break}else if(p.graph===K.PARENT){const b=_p(g);a.command=new K({...a.command,graph:b})}}if(rr(a)||s===void 0||(i+=1,i>=(s.maxAttempts??vm))||!(s.retryOn??bm)(a))break;o=Math.min(s.maxInterval??wm,o*(s.backoffFactor??ym));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(g=>setTimeout(g,d));const f=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${o.toFixed(2)}ms (attempt ${i}) after ${f}: ${a}`),l=Ce(l,{[qe]:!0})}}return{task:t,result:c,error:a,signalAborted:r?.aborted}}const Js=Symbol.for("promiseAdded");function Sm(){const t={next:()=>{},wait:Promise.resolve(Js)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Js)}}return t.wait=new Promise(e),t}var Cm=class{nodeFinished;loop;constructor({loop:t,nodeFinished:e}){this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=t,o=new Set;let i;const a=new AbortController,c=a.signal,l=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(g=>g.writes.length===0),{signals:h,disposeCombinedSignal:d}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:t.signal}),f=this._executeTasksWithRetry(u,{signals:h,retryPolicy:n,maxConcurrency:s});for await(const{task:g,error:p,signalAborted:b}of f)this._commit(g,p),ut(p)||rr(p)&&!ut(i)?i=p:p&&(o.size===0||!b)&&(a.abort(),o.add(p));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(g=>g.writes).flat()),o.size===1)throw Array.from(o)[0];if(o.size>1)throw new AggregateError(Array.from(o),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(ut(i)||rr(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[di]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=kr(s,o,t),c={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Ce(this.loop.config,{[di]:c}),{signals:c,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Sm(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(d,f,g)=>this.loop.acceptPush(d,f,g)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,l;const u=kr(s?.externalAbortSignal,s?.timeoutAbortSignal),h=u.signal?new Promise((d,f)=>{l=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",l,{once:!0})}):void 0;for(;(c===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&c<t.length;c+=1){const f=t[c];i[f.id]=Jc(f,n,{[Mo]:Yc?.bind(a,this,f)},s?.composedAbortSignal).catch(g=>({task:f,error:g,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(i),...h?[h]:[],o.wait]);d!==Js&&(yield d,l!=null&&(u.signal?.removeEventListener("abort",l),u.dispose?.()),delete i[d.task.id])}}_commit(t,e){if(e!==void 0)if(ut(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[L,s]),r=t.writes.filter(s=>s[0]===le);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else rr(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[ae,{message:e.message,name:e.name}]]);else this.nodeFinished&&(t.config?.tags==null||!t.config.tags.includes(q))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([Ao,null]),this.loop.putWrites(t.id,t.writes)}};async function Yc(t,e,n,r,s,o={}){const i=e.config?.configurable?.[et];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const c=new Kp({func:n,name:r,input:s,cache:o.cache,retry:o.retry,callbacks:o.callbacks}),l=await this.scheduleTask(e,a,c);if(!l)return;const u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){const h=l.writes.filter(([f])=>f===tn),d=l.writes.filter(([f])=>f===ae);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(d.length>0){if(d.length===1){const f=d[0][1],g=f instanceof Error?f:new Error(String(f));return Promise.reject(g)}throw new Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{const h=Jc(l,o.retry,{[Mo]:Yc.bind(this,t,l)});return this.executingTasksMap[l.id]=h,this.barrier.next(),h.then(({result:d,error:f})=>f?Promise.reject(f):d)}}var Ie=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function Em({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new Ie("Channels not provided");const a=new Set,c=new Set;for(const[l,u]of Object.entries(t)){if(l===L)throw new Ie(`"Node name ${L} is reserved"`);if(u.constructor===Mn)u.triggers.forEach(h=>a.add(h));else throw new Ie(`Invalid node type ${typeof u}, expected PregelNode`)}for(const l of a)if(!(l in e))throw new Ie(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(n)){if(n.every(l=>!a.has(l)))throw new Ie(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Ie(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(l=>c.add(l)):c.add(r),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(l=>c.add(l));for(const l of c)if(!(l in e))throw new Ie(`Output channel '${String(l)}' not in channels`);if(o&&o!=="*"){for(const l of o)if(!(l in t))throw new Ie(`Node ${String(l)} not in nodes`)}if(i&&i!=="*"){for(const l of i)if(!(l in t))throw new Ie(`Node ${String(l)} not in nodes`)}}function Si(t,e){if(Array.isArray(t)){for(const n of t)if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}var Tm=class Xc extends yt{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(e){const n=new Xc({unique:this.unique,accumulate:this.accumulate});return typeof e<"u"&&(n.seen=new Set(e[0]),n.values=e[1]),n}update(e){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=e.flat();if(r.length>0)if(this.unique)for(const s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new Z;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},xm=class{static subscribeTo(t,e){const{key:n,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(t)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;typeof t=="string"?n?s={[n]:t}:s=[t]:s=Object.fromEntries(t.map(i=>[i,i]));const o=Array.isArray(t)?t:[t];return new Mn({channels:s,triggers:o,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:ft,skipNone:!1});for(const[r,s]of Object.entries(e??{}))Q.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:ft,skipNone:!0,mapper:Zt(s)}):n.push({channel:r,value:s,skipNone:!1});return new oe(n)}},km=class extends Q{lc_namespace=["langgraph","pregel"];invoke(t,e){throw new Error("Not implemented")}withConfig(t){return super.withConfig(t)}stream(t,e){return super.stream(t,e)}},Mm=class extends km{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(t){super(t);let{streamMode:e}=t;if(e!=null&&!Array.isArray(e)&&(e=[e]),this.nodes=t.nodes,this.channels=t.channels,ve in this.channels&&"lc_graph_name"in this.channels[ve]&&this.channels[ve].lc_graph_name!=="Topic")throw new Error(`Channel '${ve}' is reserved and cannot be used in the graph.`);this.channels[ve]=new Tm({accumulate:!1}),this.autoValidate=t.autoValidate??this.autoValidate,this.streamMode=e??this.streamMode,this.inputChannels=t.inputChannels,this.outputChannels=t.outputChannels,this.streamChannels=t.streamChannels??this.streamChannels,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.stepTimeout=t.stepTimeout??this.stepTimeout,this.debug=t.debug??this.debug,this.checkpointer=t.checkpointer,this.retryPolicy=t.retryPolicy,this.config=t.config,this.store=t.store,this.cache=t.cache,this.name=t.name,this.triggerToNodes=t.triggerToNodes??this.triggerToNodes,this.userInterrupt=t.userInterrupt,this.autoValidate&&this.validate()}withConfig(t){const e=Fe(this.config,t);return new this.constructor({...this,config:e})}validate(){Em({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[t,e]of Object.entries(this.nodes))for(const n of e.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(t);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(t){return this.getGraph(t)}*getSubgraphs(t,e){for(const[n,r]of Object.entries(this.nodes)){if(t!==void 0&&!t.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const o of s){const i=Bc(o);if(i!==void 0){if(n===t){yield[n,i];return}if(t===void 0&&(yield[n,i]),e){let a=t;t!==void 0&&(a=t.slice(n.length+1));for(const[c,l]of i.getSubgraphs(a,e))yield[`${n}${G}${c}`,l]}}}}}async*getSubgraphsAsync(t,e){yield*this.getSubgraphs(t,e)}async _prepareStateSnapshot({config:t,saved:e,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(e===void 0)return{values:{},next:[],config:t,tasks:[]};const s=Cr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===_e).map(([d,f,g])=>[String(f),g]);h.length>0&&he(e.checkpoint,s,[{name:je,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(Tt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await Ke(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",c={};for(const h of o){const d=i.find(([g])=>g===h.name);if(!d)continue;let f=`${String(h.name)}${Be}${h.id}`;if(a&&(f=`${a}${G}${f}`),n===void 0){const g={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};c[h.id]=g}else{const g={configurable:{[W]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=d[1];c[h.id]=await p.getState(g,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,g,p]of e.pendingWrites)[ae,L,Yn].includes(g)||f in h&&h[f].writes.push([String(g),p]);const d=o.filter(f=>f.writes.length>0);d.length>0&&he(e.checkpoint,s,d,void 0,this.triggerToNodes)}let l=e?.metadata;l&&e?.config?.configurable?.thread_id&&(l={...l,thread_id:e.config.configurable.thread_id});const u=o.filter(h=>h.writes.length===0).map(h=>h.name);return{values:mt(s,this.streamChannelsAsIs),next:u,tasks:Wc(o,e?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:ot(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[W]??this.checkpointer;if(!n)throw new nr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const a=cs(r);for await(const[c,l]of this.getSubgraphsAsync(a,!0))if(c===a)return await l.getState(_t(t,{[W]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Fe(this.config,t),o=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:o,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[W]??this.checkpointer;if(!n)throw new nr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const o=cs(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(_t(t,{[W]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=Fe(this.config,t,{configurable:{checkpoint_ns:r}});for await(const o of n.list(s,e))yield this._prepareStateSnapshot({config:o.config,saved:o})}async bulkUpdateState(t,e){const n=t.configurable?.[W]??this.checkpointer;if(!n)throw new nr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(e.length===0)throw new Error("No supersteps provided");if(e.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const i=cs(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(_t(t,{[W]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const c=this.config?Fe(this.config,i):i,l=await n.getTuple(c),u=l!==void 0?Sr(l.checkpoint):_c(),h={...l?.checkpoint.channel_versions},d=l?.metadata?.step??-1;let f=_t(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),g=c.metadata??{};l?.config.configurable&&(f=_t(c,l.config.configurable),g={...l.metadata,...g});const{values:p,asNode:b}=a[0];if(p==null&&b===void 0){if(a.length>1)throw new B("Cannot create empty checkpoint with multiple updates");const v=await n.put(f,at(u,void 0,d),{source:"update",step:d+1,parents:l?.metadata?.parents??{}},{});return ot(v,l?l.metadata:void 0)}const C=Cr(this.channels,u);if(p===null&&b===O){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(l){const S=Tt(u,l.pendingWrites||[],this.nodes,C,l.config,!0,{step:(l.metadata?.step??-1)+1,checkpointer:n,store:this.store}),x=(l.pendingWrites||[]).filter(M=>M[0]===_e).map(M=>M.slice(1));x.length>0&&he(u,C,[{name:je,writes:x,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[M,P,I]of l.pendingWrites||[])[ae,L,Yn].includes(P)||M in S&&S[M].writes.push([P,I]);he(u,C,Object.values(S),n.getNextVersion.bind(n),this.triggerToNodes)}const v=await n.put(f,at(u,C,d),{...g,source:"update",step:d+1,parents:l?.metadata?.parents??{}},lr(h,u.channel_versions));return ot(v,l?l.metadata:void 0)}if(b===up){if(a.length>1)throw new B("Cannot copy checkpoint with multiple updates");if(l==null)throw new B("Cannot copy a non-existent checkpoint");const v=M=>!Array.isArray(M)||M.length===0?!1:M.every(P=>Array.isArray(P)&&P.length===2),S=at(u,void 0,d),x=await n.put(l.parentConfig??_t(l.config,{checkpoint_id:void 0}),S,{source:"fork",step:d+1,parents:l.metadata?.parents??{}},{});if(v(p)){const M=Tt(S,l.pendingWrites,this.nodes,C,x,!1,{step:d+2}),P=Object.values(M).reduce((j,{name:ee,id:re})=>(j[ee]??=[],j[ee].push({id:re}),j),{}),I=p.reduce((j,ee)=>{const[re,Se]=ee;j[Se]??=[];const ke=j[Se].length,Ln=P[Se]?.[ke]?.id;return j[Se].push({values:re,asNode:Se,taskId:Ln}),j},{});return s(ot(x,l.metadata),Object.values(I).flat())}return ot(x,l.metadata)}if(b===je){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const v=await Ke(zc(this.inputChannels,p));if(v.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);he(u,C,[{name:je,writes:v,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const S=l?.metadata?.step!=null?l.metadata.step+1:-1,x=await n.put(f,at(u,C,S),{source:"input",step:S,parents:l?.metadata?.parents??{}},lr(h,u.channel_versions));return await n.putWrites(x,v,St(je,u.id)),ot(x,l?l.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&l?.pendingWrites!==void 0&&l.pendingWrites.length>0){const v=Tt(u,l.pendingWrites,this.nodes,C,l.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(l.metadata?.step??-1)+1}),S=(l.pendingWrites??[]).filter(M=>M[0]===_e).map(M=>M.slice(1));S.length>0&&he(l.checkpoint,C,[{name:je,writes:S,triggers:[]}],void 0,this.triggerToNodes);for(const[M,P,I]of l.pendingWrites)[ae,L,Yn].includes(P)||v[M]===void 0||v[M].writes.push([P,I]);const x=Object.values(v).filter(M=>M.writes.length>0);x.length>0&&he(u,C,x,void 0,this.triggerToNodes)}const y=Object.values(u.versions_seen).map(v=>Object.values(v)).flat().find(v=>!!v),_=[];if(a.length===1){let{values:v,asNode:S,taskId:x}=a[0];if(S===void 0&&Object.keys(this.nodes).length===1)[S]=Object.keys(this.nodes);else if(S===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(S=this.inputChannels);else if(S===void 0){const M=Object.entries(u.versions_seen).map(([P,I])=>Object.values(I).map(j=>[j,P])).flat().filter(([P,I])=>I!==L).sort(([P],[I])=>bc(P,I));M&&(M.length===1?S=M[0][1]:M[M.length-1][0]!==M[M.length-2][0]&&(S=M[M.length-1][1]))}if(S===void 0)throw new B('Ambiguous update, specify "asNode"');_.push({values:v,asNode:S,taskId:x})}else for(const{asNode:v,values:S,taskId:x}of a){if(v==null)throw new B('"asNode" is required when applying multiple updates');_.push({values:S,asNode:v,taskId:x})}const w=[];for(const{asNode:v,values:S,taskId:x}of _){if(this.nodes[v]===void 0)throw new B(`Node "${v.toString()}" does not exist`);const M=this.nodes[v].getWriters();if(!M.length)throw new B(`No writers found for node "${v.toString()}"`);w.push({name:v,input:S,proc:M.length>1?nt.from(M,{omitSequenceTags:!0}):M[0],writes:[],triggers:[L],id:x??St(L,u.id),writers:[]})}for(const v of w)await v.proc.invoke(v.input,wn({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[Qe]:S=>v.writes.push(...S),[dt]:(S,x=!1)=>ur(u,C,v,S,x)}}));for(const v of w){const S=v.writes.filter(x=>x[0]!==de);l!==void 0&&S.length>0&&await n.putWrites(f,S,v.id)}he(u,C,w,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const E=lr(h,u.channel_versions),T=await n.put(f,at(u,C,d+1),{source:"update",step:d+1,parents:l?.metadata?.parents??{}},E);for(const v of w){const S=v.writes.filter(x=>x[0]===de);S.length>0&&await n.putWrites(T,S,v.id)}return ot(T,l?l.metadata:void 0)};let o=t;for(const{updates:i}of e)o=await s(o,i);return o}async updateState(t,e,n){return this.bulkUpdateState(t,[{updates:[{values:e,asNode:n}]}])}_defaults(t){const{debug:e,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:o,interruptBefore:i,...a}=t;let c=!0;const l=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:Si(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Si(h,this.channels);const d=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let g;n!==void 0?(g=Array.isArray(n)?n:[n],c=typeof n=="string"):(t.configurable?.[vn]!==void 0?g=["values"]:g=this.streamMode,c=!0);let p;if(this.checkpointer===!1)p=void 0;else if(t!==void 0&&t.configurable?.[W]!==void 0)p=t.configurable[W];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");p=this.checkpointer}const b=t.store??this.store,C=t.cache??this.cache;if(t.durability!=null&&t.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");const y=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),_=t.durability??y??t?.configurable?.[Pc]??"async";return[l,g,h,u,a,d,f,p,b,c,C,_]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:kr(e?.signal,n.signal).signal},s=await super.stream(t,r);return new vi(e?.encoding==="text/event-stream"?lm(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:qp(this.config?.callbacks,e?.callbacks),signal:kr(e?.signal,r.signal).signal};return new vi(super.streamEvents(t,s,n),r)}async _validateInput(t){return t}async _validateContext(t){return t}async*_streamIterator(t,e){const n="version"in(e??{})?void 0:e?.encoding??void 0,r=e?.subgraphs,s=Nc(this.config,e);if(s.recursionLimit===void 0||s.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&s.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const o=await this._validateInput(t),{runId:i,...a}=s,[c,l,,u,h,d,f,g,p,b,C,y]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const _=new Kc({modes:new Set(l)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[Ae]??"";h.configurable[Ae]=P.split(G).map(I=>I.split(Be)[0]).join(G)}if(l.includes("messages")){const P=new mm(j=>_.push(j)),{callbacks:I}=h;if(I===void 0)h.callbacks=[P];else if(Array.isArray(I))h.callbacks=I.concat(P);else{const j=I.copy();j.addHandler(P,!0),h.callbacks=j}}h.writer??=P=>{if(!l.includes("custom"))return;const I=vp()?.configurable?.[Ae]?.split(G).slice(0,-1);_.push([I??[],"custom",P])},h.interrupt??=this.userInterrupt??Uc;const E=await(await Zu(h))?.handleChainStart(this.toJSON(),Wp(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),T=xo(this.channels);let v,S;const M=(async()=>{try{v=await fm.initialize({input:o,config:h,checkpointer:g,nodes:this.nodes,channelSpecs:T,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:C,stream:_,interruptAfter:f,interruptBefore:d,manager:E,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});const P=new Cm({loop:v,nodeFinished:h.configurable?.[dp]});e?.subgraphs&&(v.config.configurable={...v.config.configurable,[Er]:v.stream}),await this._runLoop({loop:v,runner:P,debug:c,config:h}),y==="sync"&&await Promise.all(v?.checkpointerPromises??[])}catch(P){S=P}finally{try{v&&(await v.store?.stop(),await v.cache?.stop()),await Promise.all(v?.checkpointerPromises??[])}catch(P){S=S??P}S?_.error(S):_.close()}})();try{for await(const P of _){if(P===void 0)throw new Error("Data structure error.");const[I,j,ee]=P;if(l.includes(j)){if(n==="text/event-stream"){r?yield[I,j,ee]:yield[null,j,ee];continue}r&&!b?yield[I,j,ee]:b?r?yield[I,ee]:yield ee:yield[j,ee]}}}catch(P){throw await E?.handleChainError(S),P}finally{await M}await E?.handleChainEnd(v?.output??{},i,void 0,void 0,void 0)}async invoke(t,e){const n=e?.streamMode??"values",r={...e,outputKeys:e?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],o=await this.stream(t,r),i=[];let a;for await(const c of o)n==="values"?Oc(c)?i.push(c[L]):a=c:s.push(c);if(n==="values"){if(i.length>0){const c=i.flat(1);if(a==null)return{[L]:c};if(typeof a=="object")return{...a,[L]:c}}return a}return s}async _runLoop(t){const{loop:e,runner:n,debug:r,config:s}=t;let o;try{for(;await e.tick({inputKeys:this.inputChannels});){for(const{task:i}of await e._matchCachedWrites())e._outputWrites(i.id,i.writes,!0);r&&om(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&qc(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&im(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new op([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(i){if(o=i,!await e.finishAndHandleError(o))throw i}finally{o===void 0&&await e.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},rn=class Zc extends yt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Zc(this.guard);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0){const n=this.value.length>0;return this.value=[],n}if(e.length!==1&&this.guard)throw new B("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Z;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Z;return this.value[0]}isAvailable(){return this.value.length!==0}},Qc=class{path;ends;constructor(t){Q.isRunnable(t.path)?this.path=t.path:this.path=Zt(t.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return oe.registerWriter(new wt({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===Ec.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
135
+ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let o;if(this.ends?o=s.map(a=>me(a)?a:this.ends[a]):o=s,o.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(o.filter(me).some(a=>a.node===O))throw new B("Cannot send a packet to the END node");return await n(o,e)??t}},Am=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(t){this.compiled&&console.warn(t)}get allEdges(){return this.edges}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){for(const a of[G,Be])if(r.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===O)throw new Error(`Node \`${r}\` is reserved.`);const i=Zt(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:Oo(i)?[i]:o?.subgraphs,ends:o?.ends}}return this}addEdge(t,e){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),t===O)throw new Error("END cannot be a start node");if(e===F)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){const r=typeof t=="object"?t:{source:t,path:e,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!Q.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=Zt(r.path).withConfig({runName:`Branch<${r.source}${o!==""?`,${o}`:""}>`.slice(0,63)})}const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${t}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new Qc(r),this}setEntryPoint(t){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(F,t)}setFinishPoint(t){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(t,O)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new el({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[F]:new rn,[O]:new rn},inputChannels:F,outputChannels:O,streamChannels:[],streamMode:"values",name:r});for(const[o,i]of Object.entries(this.nodes))s.attachNode(o,i);for(const[o,i]of this.edges)s.attachEdge(o,i);for(const[o,i]of Object.entries(this.branches))for(const[a,c]of Object.entries(i))s.attachBranch(o,a,c);return s.validate()}validate(t){const e=new Set([...this.allEdges].map(([r,s])=>r));for(const[r]of Object.entries(this.branches))e.add(r);for(const r of e)if(r!==F&&!(r in this.nodes))throw new Error(`Found edge starting at unknown node \`${r}\``);const n=new Set([...this.allEdges].map(([r,s])=>s));for(const[r,s]of Object.entries(this.branches))for(const o of Object.values(s))if(o.ends!=null)for(const i of Object.values(o.ends))n.add(i);else{n.add(O);for(const i of Object.keys(this.nodes))i!==r&&n.add(i)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])n.add(s);for(const r of Object.keys(this.nodes))if(!n.has(r))throw new ap([`Node \`${r}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
136
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==O&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(t){for(const r of t)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},el=class extends Mm{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new rn,this.nodes[t]=new Mn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new oe([{channel:t,value:ft}],[q])),this.streamChannels.push(t)}attachEdge(t,e){if(e===O){if(t===F)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new oe([{channel:O,value:ft}],[q]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===F&&!this.nodes[F]&&(this.nodes[F]=xm.subscribeTo(F,{tags:[q]})),this.nodes[t].pipe(n.run(s=>{const o=s.map(i=>me(i)?i:{channel:i===O?O:`branch:${t}:${e}:${i}`,value:ft});return new oe(o,[q])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==O){const o=`branch:${t}:${e}:${s}`;this.channels[o]=new rn,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new Bo,r={[F]:n.addNode({schema:Ee()},F)},s={};let o={};e&&(o=Object.fromEntries((await Ke(this.getSubgraphsAsync())).filter(c=>Ci(c[1]))));function i(c,l,u,h=!1){if(l===O&&s[O]===void 0&&(s[O]=n.addNode({schema:Ee()},O)),r[c]!==void 0){if(s[l]===void 0)throw new Error(`End node ${l} not found!`);return n.addEdge(r[c],s[l],u!==l?u:void 0,h)}}for(const[c,l]of Object.entries(this.builder.nodes)){const u=te(c),h=l.runnable,d=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?d.__interrupt="before,after":this.interruptBefore?.includes(c)?d.__interrupt="before":this.interruptAfter?.includes(c)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,g=o[c]!==void 0?await o[c].getGraphAsync({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let C=function(_){return _?_.lc_runnable:!1},y=function(_,w){if(_!==void 0&&!zo(_))return _;if(C(w))try{let E=w.getName();return E=E.startsWith("Runnable")?E.slice(8):E,E}catch{return w.getName()}else return w.name??"UnknownSchema"};const[p,b]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(r[u]={name:y(b.id,b.data),...b}),s[u]={name:y(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);r[u]=p,s[u]=p}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of a)i(te(c),te(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==c).map(h=>[te(h),te(h)])),[O]:O};for(const h of Object.values(l)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))i(te(c),te(g),f,!0)}}for(const[c,l]of Object.entries(this.builder.nodes))if(l.ends!==void 0)for(const u of l.ends)i(te(c),te(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new Bo,r={[F]:n.addNode({schema:Ee()},F)},s={};let o={};e&&(o=Object.fromEntries(pn(this.getSubgraphs()).filter(c=>Ci(c[1]))));function i(c,l,u,h=!1){return l===O&&s[O]===void 0&&(s[O]=n.addNode({schema:Ee()},O)),n.addEdge(r[c],s[l],u!==l?u:void 0,h)}for(const[c,l]of Object.entries(this.builder.nodes)){const u=te(c),h=l.runnable,d=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?d.__interrupt="before,after":this.interruptBefore?.includes(c)?d.__interrupt="before":this.interruptAfter?.includes(c)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,g=o[c]!==void 0?o[c].getGraph({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let C=function(_){return _?_.lc_runnable:!1},y=function(_,w){if(_!==void 0&&!zo(_))return _;if(C(w))try{let E=w.getName();return E=E.startsWith("Runnable")?E.slice(8):E,E}catch{return w.getName()}else return w.name??"UnknownSchema"};const[p,b]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(r[u]={name:y(b.id,b.data),...b}),s[u]={name:y(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);r[u]=p,s[u]=p}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([c],[l])=>c<l?-1:l>c?1:0);for(const[c,l]of a)i(te(c),te(l));for(const[c,l]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==c).map(h=>[te(h),te(h)])),[O]:O};for(const h of Object.values(l)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))i(te(c),te(g),f,!0)}}return n}};function Ci(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function te(t){return t==="subgraph"?`"${t}"`:t}const ht=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Pm=class tl extends yt{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new tl(this.names);return typeof e<"u"&&(n.seen=new Set(e)),n}update(e){let n=!1;for(const r of e)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!ht(this.names,this.seen))throw new Z}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&ht(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&ht(this.names,this.seen)}},Om=class nl extends yt{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(e){const n=new nl(this.names);if(typeof e<"u"){const[r,s]=e;n.seen=new Set(r),n.finished=s}return n}update(e){let n=!1;for(const r of e)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!ht(this.names,this.seen))throw new Z}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&ht(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&ht(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&ht(this.names,this.seen)}};const Nm="lg:";var Im=class{_map=new WeakMap;_extensionCache=new Map;get(t){return this._map.get(t)}extend(t,e){const n=this.get(t);this._map.set(t,e(n))}remove(t){return this._map.delete(t),this}has(t){return this._map.has(t)}getChannelsForSchema(t){const e={},n=Ho(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new Us(o.reducer.fn,o.default):e[r]=new ko}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,o])=>o===!0).sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>`${o}:${i}`).join("|"),r=this._extensionCache.get(n)??new WeakMap;if(r.has(t))return r.get(t);let s=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const o=Object.entries(Ho(t)).map(([i,a])=>{const c=this.get(a);let l=e.withReducerSchema?c?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){const u=Cs(l)??Cs(a),h=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`${Nm}${h}`)}return[i,l]});s=Qu(t,Object.fromEntries(o)),eh(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=oo(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const sn=new Im;function on(t,e){if(e.reducer&&!e.default){const n=so(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return sn.extend(n,()=>e),n}else return sn.extend(t,()=>e),t}const De="__root__",Ys=Symbol.for("langgraph.state.partial");var $m=class extends Am{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=sn;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Vm(t)){const r=this._metaRegistry.getChannelsForSchema(t.state),s=t.input!=null?this._metaRegistry.getChannelsForSchema(t.input):r,o=t.output!=null?this._metaRegistry.getChannelsForSchema(t.output):r;this._schemaDefinition=r,this._schemaRuntimeDefinition=t.state,this._inputDefinition=s,this._inputRuntimeDefinition=t.input??Ys,this._outputDefinition=o,this._outputRuntimeDefinition=t.output??t.state}else if(fe(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=Ys,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(Um(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Dm(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Lm(t)||Ei(t)){const r=Ei(t)?t.spec:t;this._schemaDefinition=r}else if(Fm(t)){const r=Rm(t.channels);this._schemaDefinition=r}else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.");this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition);function n(r){return typeof r=="object"&&r!=null&&!("spec"in r)&&!fe(r)}n(e)?(fe(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):fe(e)&&(this._configRuntimeSchema=e)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([t,e])=>t.map(n=>[n,e]))])}_addSchema(t){if(!this._schemaDefinitions.has(t)){this._schemaDefinitions.set(t,t);for(const[e,n]of Object.entries(t)){let r;if(typeof n=="function"?r=n():r=n,this.channels[e]!==void 0){if(this.channels[e]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=r}}}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([r,s])=>[r,s]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[G,Be])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===O||r===F)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;o?.input!==void 0&&(fe(o.input)?i=this._metaRegistry.getChannelsForSchema(o.input):o.input.spec!==void 0&&(i=o.input.spec)),i!==void 0&&this._addSchema(i);let a;Q.isRunnable(s)?a=s:typeof s=="function"?a=new wt({func:s,name:r,trace:!1}):a=Zt(s);let c=o?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);const l={runnable:a,retryPolicy:o?.retryPolicy,cachePolicy:c,metadata:o?.metadata,input:i??this._schemaDefinition,subgraphs:Oo(a)?[a]:o?.subgraphs,ends:o?.ends,defer:o?.defer};this.nodes[r]=l}return this}addEdge(t,e){if(typeof t=="string")return super.addEdge(t,e);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const n of t){if(n===O)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(r=>r===n))throw new Error(`Need to add a node named "${n}" first`)}if(e===O)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===e))throw new Error(`Need to add a node named "${e}" first`);return this.waitingEdges.add([t,e]),this}addSequence(t){const e=Array.isArray(t)?t:Object.entries(t);if(e.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,o]of e){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const i=r;this.addNode(i,s,o),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:t,store:e,cache:n,interruptBefore:r,interruptAfter:s,name:o,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=a.length===1&&a[0]===De?De:a,l=Object.keys(this.channels),u=l.length===1&&l[0]===De?De:l,h=this._interrupt,d=new jm({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[F]:new rn},inputChannels:F,outputChannels:c,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:h});d.attachNode(F);for(const[f,g]of Object.entries(this.nodes))d.attachNode(f,g);d.attachBranch(F,fi,Ti(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,fi,Ti(),{withReader:!1});for(const[f,g]of this.edges)d.attachEdge(f,g);for(const[f,g]of this.waitingEdges)d.attachEdge(f,g);for(const[f,g]of Object.entries(this.branches))for(const[p,b]of Object.entries(g))d.attachBranch(f,p,b);return d.validate()}};function Rm(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Bs(r);return e}var jm=class extends el{description;_metaRegistry=sn;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===F?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function r(a){if(Y(a))return a.graph===K.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(c=>Y(c))){const c=[];for(const l of a)if(Y(l)){if(l.graph===K.PARENT)continue;c.push(...l._updateAsTuples())}else c.push([De,l]);return c}else if(a!=null)return[[De,a]];return null}const s=t;function o(a){if(a){if(Y(a))return a.graph===K.PARENT?null:a._updateAsTuples().filter(([c])=>n.includes(c));if(Array.isArray(a)&&a.length>0&&a.some(Y)){const c=[];for(const l of a)if(Y(l)){if(l.graph===K.PARENT)continue;c.push(...l._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=o(l);u&&c.push(...u??[])}return c}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([c])=>n.includes(c));{const c=Array.isArray(a)?"array":typeof a;throw new B(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:ft,mapper:new wt({func:n.length&&n[0]===De?r:o,trace:!1,recurse:!1})}];if(t===F)this.nodes[t]=new Mn({tags:[q],triggers:[F],channels:[F],writers:[new oe(i,[q])]});else{const a=e?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(h=>[h,h])),l=Object.keys(c).length===1&&De in c,u=`branch:to:${t}`;this.channels[u]=e?.defer?new cp:new rn(!1),this.nodes[t]=new Mn({triggers:[u],channels:l?Object.keys(c):c,writers:[new oe(i,[q])],mapper:l?void 0:h=>Object.fromEntries(Object.entries(h).filter(([d])=>d in c)),bound:e?.runnable,metadata:e?.metadata,retryPolicy:e?.retryPolicy,cachePolicy:e?.cachePolicy,subgraphs:e?.subgraphs,ends:e?.ends})}}attachEdge(t,e){if(e!==O){if(typeof t=="string")this.nodes[t].writers.push(new oe([{channel:`branch:to:${e}`,value:null}],[q]));else if(Array.isArray(t)){const n=`join:${t.join("+")}:${e}`;this.channels[n]=this.builder.nodes[e].defer?new Om(new Set(t)):new Pm(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new oe([{channel:n,value:r}],[q]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(l=>l!==O);if(!a.length)return;const c=a.map(l=>me(l)?l:{channel:l===O?l:`branch:to:${l}`,value:t});await oe.doWrite({...i,tags:(i.tags??[]).concat([q])},c)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>Vp.doRead(o,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=o=>{if(o!=null)return this._metaRegistry.getExtendedChannelSchemas(o,{withReducerSchema:!0})};if(fe(n))return s(n);if(n===Ys)return oo(s(r))})();if(Y(t)){const n=t;return t.update&&e!=null&&(n.update=Ye(e,t.update)),n}return e!=null?Ye(e,t):t}isInterrupted(t){return Oc(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return fe(e)&&Ye(e,t),t}};function Lm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||xc(e))}function Ei(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function Fm(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Dm(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function Um(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Vm(t){return!(typeof t!="object"||t==null||!("state"in t)||!fe(t.state)||"input"in t&&!fe(t.input)||"output"in t&&!fe(t.output))}function Bm(t){if(me(t))return[t];const e=[];Y(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Y));const n=[];for(const r of e){if(r.graph===K.PARENT)throw new Tc(r);me(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Ti(){const t=new wt({func:Bm,tags:[q],trace:!1,recurse:!1,name:"<control_branch>"});return new Qc({path:t})}const rl="__remove_all__";function sl(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(Sn),o=r.map(Sn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=fr(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<o.length;u+=1){const h=o[u];(h.id===null||h.id===void 0)&&(h.id=fr(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===rl&&(i=u)}if(i!=null)return o.slice(i+1);const a=[...s],c=new Map(a.map((u,h)=>[u.id,h])),l=new Set;for(const u of o){const h=c.get(u.id);if(h!==void 0)u.getType()==="remove"?l.add(u.id):(l.delete(u.id),a[h]=u);else{if(u.getType()==="remove")throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,a.length),a.push(u)}}return a.filter(u=>!l.has(u.id))}Vs.Root({messages:Vs({reducer:sl,default:()=>[]})});const Mr={reducer:{fn:sl},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:on(ce(),Mr)});sp();const Xs=Symbol.for("langgraph-zod");Xs in globalThis||(globalThis[Xs]=new WeakSet);function xi(t){const e=globalThis[Xs];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return on(n,{jsonSchemaExtra:r})},reducer(r,s){const o=so(n);return on(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{xi(th.prototype),xi(Dl.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var zm=class extends Ul{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=so(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new zm(sn);function Hm(t=!0,e,n=[]){const r={messages:on(ce(),Mr),jumpTo:Ne([xt("model_request"),xt("tools"),xt("end"),nh()]).optional()},s=a=>{const{shape:c}=a;for(const[l,u]of Object.entries(c))l.startsWith("_")||l in r||(r[l]=u)};e&&"shape"in e&&s(e);for(const a of n)a.stateSchema&&s(a.stateSchema);t&&(r.structuredResponse=io().optional());const o=z(r);return sn.getChannelsForSchema(o)}z({llmInputMessages:on(ce(),{reducer:{fn:(t,e)=>Mr.reducer.fn([],e)},default:()=>[]}),messages:on(ce(),Mr)});const ki="prompt",gs=/<name>(.*?)<\/name>/s,ys=/<content>(.*?)<\/content>/s;function Wm(t){if(!N.isInstance(t)||Yt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new N({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new N({...t.lc_kwargs,content:n,name:void 0})}function qm(t){if(!N.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(gs),o=r.text.match(ys);return s&&(!o||o[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(gs),o=r.text.match(ys);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(gs),o=r.match(ys);if(!s||!o)return t;n=s[1],e=o[1]}return new N({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function H(t){return Q.isRunnable(t)}function Mi(t){return uo(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const ws=(t,e,n={})=>{if(Mi(t))return t.bindTools(e,n);if(Pe.isRunnableBinding(t)&&Mi(t.bound)){const r=t.bound.bindTools(e,n);return Pe.isRunnableBinding(r)?new Pe({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Pe({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function ol(t){if(typeof t=="function")return;let e=t;if(nt.isRunnableSequence(e)&&(e=e.steps.find(n=>Pe.isRunnableBinding(n))||e),!yr(e)){if(Pe.isRunnableBinding(e)){const n=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,r=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(n||r)throw new ks}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new ks}}function Zs(t){return!!(N.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Km(t){let e;if(t==null)e=Xt.from(n=>n.messages).withConfig({runName:ki});else if(typeof t=="string"){const n=new be(t);e=Xt.from(r=>[n,...r.messages??[]]).withConfig({runName:ki})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function Gm(t,e,n={}){const r=ws(t,e,n);if(r)return r;if(yr(t)){const s=ws(await t._model(),e,n);if(s)return s}if(nt.isRunnableSequence(t)){const s=t.steps.findIndex(o=>Pe.isRunnableBinding(o)||uo(o)||yr(o));if(s>=0){const o=ws(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),nt.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Jm(t){if(t.length===0)return;if(t.length===1)return t[0];function e(r,s){return async(o,i)=>r(o,async()=>s(o,async()=>i(o)))}let n=t[t.length-1];for(let r=t.length-2;r>=0;r--)n=e(t[r],n);return n}function Ym(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Jm(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?Ye(n.stateSchema,{...o.state}):{}}},i);if(!U.isInstance(a)&&!Y(a))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof a}`);return a}catch(a){throw a instanceof Error&&!a.message.includes(`middleware "${n.name}"`)&&(a.message=`Error in middleware "${n.name}": ${a.message}`),a}}}))}async function Xm(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=rh(r.stateSchema,a=>a.startsWith("_")),o=await sh(s,e);if(o.success){Object.assign(n,o.data);continue}const i=o.error.issues.filter(a=>a.code==="invalid_type"&&a.message==="Required").map(a=>` - ${a.path.join(".")}: ${a.message}`).join(`
137
+ `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
138
+ ${i}
139
+
140
+ To fix this, either:
141
+ 1. Provide default values in your middleware's state schema using .default():
142
+ stateSchema: z.object({
143
+ myField: z.string().default("default value")
144
+ })
145
+
146
+ 2. Or make the fields optional using .optional():
147
+ stateSchema: z.object({
148
+ myField: z.string().optional()
149
+ })
150
+
151
+ 3. Or ensure you pass these values when invoking the agent:
152
+ agent.invoke({
153
+ messages: [...],
154
+ ${o.error.issues[0]?.path.join(".")}: "value"
155
+ })`)}return n}function Zm(t){const e={messages:ce(()=>[]),structuredResponse:io().optional()};if(!t)return z(e);const{shape:n}=t,r={...e};for(const[s,o]of Object.entries(n))s.startsWith("_")?r[s]=o.optional():r[s]=o;return z(r)}function $e(t){if(t){if(["model_request","tools",O].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return O;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function il(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var $o=class extends Q{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){const n=Fe(this.config,e),r=await Ue.runWithConfig(n,async()=>this.func(t,n));return Q.isRunnable(r)&&this.recurse?await Ue.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function Qm(t,e){let n,r;if(e==="inline")n=Wm,r=qm;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return nt.from([Xt.from(s),t,Xt.from(r)])}var eg=class extends $o{#e;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t}#n(t){if(!this.#e.responseFormat)return;const e=ua(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof lt)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof We).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(t,e){const n=t.messages.at(-1);if(n&&U.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#o(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof K?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#r(t,r)?{messages:[new N({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#t(){if(typeof this.#e.model=="string")return cn(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#o(t,e,n={}){const r=await this.#t(),s=e,o=async l=>{ol(l.model);const u=this.#n(l.model),h=await this.#u(l.model,l,u);let d=this.#l(t);d={...d,messages:l.messages};const f=il(this.#e.signal,e.signal),g={...e,signal:f},p=await h.invoke(d,g);if(u?.type==="native"){const _=u.strategy.parse(p);return _?{structuredResponse:_,messages:[p]}:p}if(!u||!p.tool_calls)return p;const b=p.tool_calls.filter(_=>_.name in u.tools);if(b.length===0)return p;if(b.length>1)return this.#a(p,b,u);const y=u.tools[b[0].name]?.options?.toolMessageContent;return this.#c(p,b[0],u,y??n.lastMessage)},i=this.#e.wrapModelCallHookMiddleware??[];let a=o;for(let l=i.length-1;l>=0;l--){const[u,h]=i[l];if(u.wrapModelCall){const d=a,f=u,g=h;a=async p=>{const b=f.contextSchema?Ye(f.contextSchema,s?.context||{}):s?.context,C=Object.freeze({context:b,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),y={...p,state:{...u.stateSchema?Ye(oo(u.stateSchema),t):{},...g(),messages:t.messages},runtime:C},_=async w=>{const E=w.tools??[],T=E.filter(S=>H(S)&&!this.#e.toolClasses.some(x=>x.name===S.name));if(T.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${T.map(S=>S.name).join(", ")}. This is not supported.`);const v=E.filter(S=>H(S)&&this.#e.toolClasses.every(x=>x!==S));if(v.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${v.map(S=>S.name).join(", ")}. This is not supported.`);return d(w)};if(!f.wrapModelCall)return _(y);try{const w=await f.wrapModelCall(y,_);if(!N.isInstance(w))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof w}`);return w}catch(w){throw w instanceof Error&&!w.message.includes(`middleware "${f.name}"`)&&(w.message=`Error in middleware "${f.name}": ${w.message}`),w}}}}const c={model:r,systemPrompt:this.#e.systemPrompt,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return a(c)}#a(t,e,n){const r=new Ms(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#c(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new U({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new N(r??`Returning structured response: ${JSON.stringify(o)}`)]}}catch(o){return this.#i(o,t,e,n)}}async#i(t,e,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,o=n.id;if(!o)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof Ms))return new K({update:{messages:[e,new U({content:t.message,tool_call_id:o})]},goto:"model"});if(typeof s=="string")return new K({update:{messages:[e,new U({content:s,tool_call_id:o})]},goto:"model"});if(typeof s=="function"){const i=await s(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new K({update:{messages:[e,new U({content:i,tool_call_id:o})]},goto:"model"})}throw t}#r(t,e){const n=N.isInstance(e)&&e.tool_calls?.every(s=>this.#e.shouldReturnDirect.has(s.name)),r="remainingSteps"in t?t.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&Zs(t.messages.at(-1))))}#l(t){const{messages:e,llmInputMessages:n,...r}=t;return n&&n.length>0?{messages:n,...r}:{messages:e,...r}}async#u(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(l=>l.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const l={name:n.strategy.schema?.name??"extract",description:Cs(n.strategy.schema),schema:n.strategy.schema,strict:!0};Object.assign(r,{response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:!0})}const a=await Gm(t,o,{...r,...e?.modelSettings??{},tool_choice:i});return Km(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?Qm(a,this.#e.includeAgentName):a)}getState(){const t=super.getState(),e=t&&!(t instanceof K)?t:{};return{messages:[],...e}}};const al=t=>Array.isArray(t)&&t.every(yn.isInstance),tg=t=>typeof t=="object"&&t!=null&&"messages"in t&&al(t.messages),ng=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function rg(t,e){return t instanceof lo?new U({content:t.message,tool_call_id:e.id,name:e.name}):new U({content:`${t}
156
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var sg=class extends $o{tools;trace=!1;signal;handleToolErrors=rg;wrapToolCall;constructor(t,e){const{name:n,tags:r,handleToolErrors:s,signal:o,wrapToolCall:i}=e??{};super({name:n,tags:r,func:(a,c)=>this.run(a,c)}),this.options=e,this.tools=t,this.handleToolErrors=s??this.handleToolErrors,this.signal=o,this.wrapToolCall=i}#e(t,e,n){if(ut(t)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){const r=this.handleToolErrors(t,e);if(r&&U.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new U({name:e.name,content:`${t}
157
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,n){const r=async c=>{const{toolCall:l}=c,u=this.tools.find(h=>h.name===l.name);if(u===void 0)throw new Error(`Tool "${l.name}" not found.`);try{const h=await u.invoke({...l,type:"tool_call"},{...e,config:e,toolCallId:l.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:il(this.signal,e.signal)});return U.isInstance(h)||Y(h)?h:new U({name:u.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:l.id})}catch(h){throw h instanceof oh?new lo(h,l):h}},s=e,o={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal},i=this.tools.find(c=>c.name===t.name);if(!i)throw new Error(`Tool "${t.name}" not found.`);const a={toolCall:t,tool:i,state:n,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(a,r)}catch(c){return this.#e(c,t,!0)}try{return await r(a)}catch(c){return this.#e(c,t,!1)}}async run(t,e){let n;if(ng(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(al(t))o=t;else if(tg(t))o=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(o.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id));let a;for(let c=o.length-1;c>=0;c-=1){const l=o[c];if(N.isInstance(l)){a=l;break}}if(!N.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(c=>c.id==null||!i.has(c.id)).map(c=>this.runTool(c,e,t))??[])}if(!n.some(Y))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)Y(o)?o.graph===K.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>og(i))?s?s.goto.push(...o.goto):s=new K({graph:K.PARENT,goto:o.goto}):r.push(o):r.push(Array.isArray(t)?[o]:{messages:[o]});return s&&r.push(s),r}};function og(t){return t instanceof se}var ig=class{},ag=class{},Ur=class extends $o{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let n={};if(this.middleware.contextSchema){const c=this.middleware.contextSchema?.shape;if(c){const l={},u=e?.context||{};for(const h of Object.keys(c))h in u&&(l[h]=u[h]);n=Ye(this.middleware.contextSchema,l)}}const r={...this.#e.getState(),...t,messages:t.messages},s={context:n,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},o=await this.runHook(r,Object.freeze(Object.assign(new ag,{...s,context:Object.freeze(Object.assign(new ig,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Ge(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Ge(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Ge(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Ge(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const c=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${o.jumpTo}, ${c}.`)}if(typeof o=="object"&&"type"in o){if(o.type==="terminate"){if(o.error)throw o.error;return{...r,...o.result||{},jumpTo:o.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(o)}`)}return{...r,...o,jumpTo:o.jumpTo}}get nodeOptions(){return{input:Zm(this.middleware.stateSchema)}}},cg=class extends Ur{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Lr(this.middleware.beforeAgent)(t,e)}},lg=class extends Ur{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Lr(this.middleware.beforeModel)(t,e)}},ug=class extends Ur{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Lr(this.middleware.afterModel)(t,e)}},hg=class extends Ur{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return Lr(this.middleware.afterAgent)(t,e)}},dg=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){const n=(this.#e.get(t)??[]).reduce((r,s)=>({...r,...s.getState()??{}}),{});return delete n.jumpTo,n}},fg=class{#e;#n="v2";#s;#t=new dg;constructor(t){if(this.options=t,this.#n=t.version??this.#n,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&ol(t.model);const e=this.options.middleware?.filter(y=>y.tools).flatMap(y=>y.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(H).filter(y=>"returnDirect"in y&&y.returnDirect).map(y=>y.name)),s=Hm(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new $m(s,this.options.contextSchema),a=[],c=[],l=[],u=[],h=[];this.#s=new eg({model:this.options.model,systemPrompt:this.options.systemPrompt,includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:h});const d=new Set,f=this.options.middleware??[];for(let y=0;y<f.length;y++){let _,w,E,T;const v=f[y];if(d.has(v.name))throw new Error(`Middleware ${v.name} is defined multiple times`);if(d.add(v.name),v.beforeAgent){_=new cg(v,{getState:()=>this.#t.getState(v.name)}),this.#t.addNode(v,_);const S=`${v.name}.before_agent`;a.push({index:y,name:S,allowed:Ge(v.beforeAgent)}),i.addNode(S,_,_.nodeOptions)}if(v.beforeModel){w=new lg(v,{getState:()=>this.#t.getState(v.name)}),this.#t.addNode(v,w);const S=`${v.name}.before_model`;c.push({index:y,name:S,allowed:Ge(v.beforeModel)}),i.addNode(S,w,w.nodeOptions)}if(v.afterModel){E=new ug(v,{getState:()=>this.#t.getState(v.name)}),this.#t.addNode(v,E);const S=`${v.name}.after_model`;l.push({index:y,name:S,allowed:Ge(v.afterModel)}),i.addNode(S,E,E.nodeOptions)}if(v.afterAgent){T=new hg(v,{getState:()=>this.#t.getState(v.name)}),this.#t.addNode(v,T);const S=`${v.name}.after_agent`;u.push({index:y,name:S,allowed:Ge(v.afterAgent)}),i.addNode(S,T,T.nodeOptions)}v.wrapModelCall&&h.push([v,()=>this.#t.getState(v.name)])}if(i.addNode("model_request",this.#s),n.filter(H).length>0){const y=new sg(n.filter(H),{signal:this.options.signal,wrapToolCall:Ym(f)});i.addNode("tools",y)}let g;a.length>0?g=a[0].name:c.length>0?g=c[0].name:g="model_request";const p=c.length>0?c[0].name:"model_request",b=u.length>0?u[u.length-1].name:O;i.addEdge(F,g);for(let y=0;y<a.length;y++){const _=a[y],w=_.name,T=y===a.length-1?p:a[y+1].name;if(_.allowed&&_.allowed.length>0){const v=n.filter(H).length>0,S=_.allowed.map(M=>$e(M)).filter(M=>M!=="tools"||v),x=Array.from(new Set([T,...S.map(M=>M===O?b:M)]));i.addConditionalEdges(w,this.#l(n.filter(H),T,b),x)}else i.addEdge(w,T)}for(let y=0;y<c.length;y++){const _=c[y],w=_.name,T=y===c.length-1?"model_request":c[y+1].name;if(_.allowed&&_.allowed.length>0){const v=n.filter(H).length>0,S=_.allowed.map(M=>$e(M)).filter(M=>M!=="tools"||v),x=Array.from(new Set([T,...S]));i.addConditionalEdges(w,this.#u(n.filter(H),T),x)}else i.addEdge(w,T)}const C=l.at(-1);if(l.length>0&&C)i.addEdge("model_request",C.name);else{const _=this.#o(n.filter(H)).map(w=>w===O?b:w);_.length===1?i.addEdge("model_request",_[0]):i.addConditionalEdges("model_request",this.#c(b),_)}for(let y=l.length-1;y>0;y--){const _=l[y],w=_.name,E=l[y-1].name;if(_.allowed&&_.allowed.length>0){const T=n.filter(H).length>0,v=_.allowed.map(x=>$e(x)).filter(x=>x!=="tools"||T),S=Array.from(new Set([E,...v]));i.addConditionalEdges(w,this.#r(n.filter(H),_.allowed,E),S)}else i.addEdge(w,E)}if(l.length>0){const y=l[0],_=y.name,w=this.#o(n.filter(H),!0).filter(v=>v!=="tools"||n.filter(H).length>0),E=!!(y.allowed&&y.allowed.length>0),T=w.map(v=>v===O?b:v);i.addConditionalEdges(_,this.#i(n.filter(H),E,b),T)}for(let y=u.length-1;y>0;y--){const _=u[y],w=_.name,E=u[y-1].name;if(_.allowed&&_.allowed.length>0){const T=n.filter(H).length>0,v=_.allowed.map(x=>$e(x)).filter(x=>x!=="tools"||T),S=Array.from(new Set([E,...v]));i.addConditionalEdges(w,this.#r(n.filter(H),_.allowed,E),S)}else i.addEdge(w,E)}if(u.length>0){const y=u[0],_=y.name;if(y.allowed&&y.allowed.length>0){const w=n.filter(H).length>0,E=y.allowed.map(v=>$e(v)).filter(v=>v!=="tools"||w),T=Array.from(new Set([O,...E]));i.addConditionalEdges(_,this.#r(n.filter(H),y.allowed,O),T)}else i.addEdge(_,O)}if(n.filter(H).length>0){const y=p;r.size>0?i.addConditionalEdges("tools",this.#a(r,b),[y,b]):i.addEdge("tools",y)}this.#e=i.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#o(t,e=!1){const n=[];return t.length>0&&n.push("tools"),e&&n.push("model_request"),n.push(O),n}#a(t,e){return n=>{const r=n.messages,s=r[r.length-1];return U.isInstance(s)&&s.name&&t.has(s.name)?this.options.responseFormat?"model_request":e:"model_request"}}#c(t=O){return e=>{const r=e.messages.at(-1);if(!N.isInstance(r)||!r.tool_calls||r.tool_calls.length===0||r.tool_calls.every(i=>i.name.startsWith("extract-")))return t;if(this.#n==="v1")return"tools";const o=r.tool_calls.filter(i=>!i.name.startsWith("extract-"));return o.length===0?t:o.map(i=>new se("tools",{...e,lg_tool_call:i}))}}#i(t,e,n){const r=!!this.options.responseFormat;return s=>{const o=s.messages,i=o.at(-1);if(N.isInstance(i)&&(!i.tool_calls||i.tool_calls.length===0))return n;if(e&&s.jumpTo)return s.jumpTo===O?n:s.jumpTo==="tools"?t.length===0?n:new se("tools",{...s,jumpTo:void 0}):new se("model_request",{...s,jumpTo:void 0});const a=o.filter(U.isInstance),c=o.filter(N.isInstance).at(-1),l=c?.tool_calls?.filter(f=>!a.some(g=>g.tool_call_id===f.id));if(l&&l.length>0)return l.map(f=>new se("tools",{...s,lg_tool_call:f}));const u=c?.tool_calls?.some(f=>f.name.startsWith("extract-"));if(l&&l.length===0&&!u&&r)return"model_request";if(!N.isInstance(i)||!i.tool_calls||i.tool_calls.length===0)return n;const h=i.tool_calls.every(f=>f.name.startsWith("extract-")),d=i.tool_calls.some(f=>!f.name.startsWith("extract-"));return h||!d?n:"tools"}}#r(t,e,n){const r=new Set(e.map(s=>$e(s)));return s=>{if(s.jumpTo){const o=$e(s.jumpTo);if(o===O&&r.has(O))return O;if(o==="tools"&&r.has("tools"))return t.length===0?O:new se("tools",{...s,jumpTo:void 0});if(o==="model_request"&&r.has("model_request"))return new se("model_request",{...s,jumpTo:void 0})}return n}}#l(t,e,n){return r=>{if(!r.jumpTo)return e;const s=$e(r.jumpTo);return s===O?n:s==="tools"?t.length===0?n:new se("tools",{...r,jumpTo:void 0}):new se("model_request",{...r,jumpTo:void 0})}}#u(t,e){return n=>{if(!n.jumpTo)return e;const r=$e(n.jumpTo);return r===O?O:r==="tools"?t.length===0?O:new se("tools",{...n,jumpTo:void 0}):new se("model_request",{...n,jumpTo:void 0})}}async#h(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof K||!t)return t;const n=await Xm(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[o,i]of Object.entries(n))o in s||(s[o]=i);return s}async invoke(t,e){const n=await this.#h(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#h(t,e);return this.#e.stream(n,e)}async drawMermaidPng(t){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,e,n){return this.#e.streamEvents(t,{...e,version:e?.version??"v2"},n)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,e){return this.#e.getState(t,e)}getStateHistory(t,e){return this.#e.getStateHistory(t,e)}getSubgraphs(t,e){return this.#e.getSubgraphs(t,e)}getSubgraphAsync(t,e){return this.#e.getSubgraphsAsync(t,e)}updateState(t,e,n){return this.#e.updateState(t,e,n)}};function cl(t){return new fg(t)}const hr=`<role>
158
+ Context Extraction Assistant
159
+ </role>
160
+
161
+ <primary_objective>
162
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
163
+ </primary_objective>
164
+
165
+ <objective_information>
166
+ You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
167
+ This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
168
+ </objective_information>
169
+
170
+ <instructions>
171
+ The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
172
+ You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
173
+ </instructions>
174
+
175
+ The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
176
+
177
+ With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
178
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
179
+
180
+ <messages>
181
+ Messages to summarize:
182
+ {messages}
183
+ </messages>`,Ar=20,pg=4e3,Ai=5,mg=pr().args(ze(ce())).returns(Ne([V(),Gi(V())])),Pr=z({fraction:V().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().positive("Tokens must be greater than 0").optional(),messages:V().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),ll=z({fraction:V().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().positive("Tokens must be greater than 0").optional(),messages:V().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),Pi=z({model:ce(),trigger:Ne([Pr,ze(Pr)]).optional(),keep:ll.optional(),tokenCounter:mg.optional(),summaryPrompt:ne().default(hr),trimTokensToSummarize:V().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:V().optional(),messagesToKeep:V().optional()});function Ro(t){try{const e=t;if(e.profile&&typeof e.profile.max_input_tokens=="number")return e.profile.max_input_tokens}catch{}try{const e=t,n=e.model||e.modelName;if(typeof n=="string")return _u(n)}catch{}}function gg(t){const{data:e,error:n}=ih(Pi,t);if(n)throw new Error(`Invalid summarization middleware options: ${Ui(n)}`);return ge({name:"SummarizationMiddleware",contextSchema:Pi.extend({model:ce().optional()}),beforeModel:async(r,s)=>{let o=e.trigger,i=e.keep;e.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),o===void 0&&(o={tokens:e.maxTokensBeforeSummary})),e.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===Ar)&&(i={messages:e.messagesToKeep}));const a=s.context.trigger!==void 0?s.context.trigger:o,c=s.context.keep!==void 0?s.context.keep:i??{messages:Ar},l=ll.parse(c);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(x=>Pr.parse(x)):u=[Pr.parse(a)];const h=u.some(x=>"fraction"in x)||"fraction"in l,d=typeof e.model=="string"?await cn(e.model):e.model;if(h&&!Ro(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context.summaryPrompt===hr?e.summaryPrompt??hr:s.context.summaryPrompt??e.summaryPrompt??hr,g=s.context.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??pg;yg(r.messages);const p=s.context.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??ho,b=await p(r.messages);if(!await _g(r.messages,b,u,d))return;const{systemPrompt:y,conversationMessages:_}=wg(r.messages),w=await bg(_,l,p,d);if(w<=0)return;const{messagesToSummarize:E,preservedMessages:T}=vg(y,_,w),v=await Tg(E,d,f,p,g),S=new pe({content:`Here is a summary of the conversation to date:
184
+
185
+ ${v}`,id:fr()});return{messages:[new Gn({id:rl}),S,...T]}}})}function yg(t){for(const e of t)e.id||(e.id=fr())}function wg(t){return t.length>0&&be.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function vg(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function _g(t,e,n,r){if(n.length===0)return!1;for(const s of n){let o=!0,i=!1;if(s.messages!==void 0&&(i=!0,t.length<s.messages&&(o=!1)),s.tokens!==void 0&&(i=!0,e<s.tokens&&(o=!1)),s.fraction!==void 0){i=!0;const a=Ro(r);if(typeof a=="number"){const c=Math.floor(a*s.fraction);e<c&&(o=!1)}else o=!1}if(i&&o)return!0}return!1}async function bg(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Sg(t,e,n,r);return typeof s=="number"?s:Oi(t,Ar)}return Oi(t,e.messages??Ar)}async function Sg(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const u=Ro(r);if(typeof u!="number")return;s=Math.floor(u*e.fraction)}else if("tokens"in e&&e.tokens!==void 0)s=Math.floor(e.tokens);else return;if(s<=0&&(s=1),await n(t)<=s)return 0;let i=0,a=t.length,c=t.length;const l=Math.floor(Math.log2(t.length))+1;for(let u=0;u<l&&!(i>=a);u++){const h=Math.floor((i+a)/2);await n(t.slice(h))<=s?(c=h,a=h):i=h+1}if(c===t.length&&(c=i),c>=t.length){if(t.length===1)return 0;c=t.length-1}for(let u=c;u>=0;u--)if(ul(t,u))return u;return 0}function Oi(t,e){if(t.length<=e)return 0;const n=t.length-e;for(let r=n;r>=0;r--)if(ul(t,r))return r;return 0}function ul(t,e){if(e>=t.length)return!0;if(e<t.length&&N.isInstance(t[e])&&Zs(t[e]))return!1;const n=Math.max(0,e-Ai),r=Math.min(t.length,e+Ai);for(let s=n;s<r;s++){if(!Zs(t[s]))continue;const o=Cg(t[s]);if(Eg(t,s,e,o))return!1}return!0}function Cg(t){const e=new Set;if(t.tool_calls)for(const n of t.tool_calls){const r=typeof n=="object"&&"id"in n?n.id:null;r&&e.add(r)}return e}function Eg(t,e,n,r){for(let s=e+1;s<t.length;s++){const o=t[s];if(U.isInstance(o)&&r.has(o.tool_call_id)){const i=e<n,a=s<n;if(i!==a)return!0}}return!1}async function Tg(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const o=await xg(t,r,s);if(!o.length)return"Previous conversation was too long to summarize.";try{const i=n.replace("{messages}",JSON.stringify(o,null,2)),c=(await e.invoke(i)).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(u=>typeof u=="string"?u:typeof u=="object"&&u!==null&&"text"in u?u.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(i){return`Error generating summary: ${i}`}}async function xg(t,e,n){if(n===void 0)return t;try{return await Ji(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const kg=pr().args(ce(),ce(),ce()).returns(Ne([ne(),Gi(ne())])),hl=["approve","edit","reject"],Mg=Qt(hl),Ag=z({allowedDecisions:ze(Mg),description:Ne([ne(),kg]).optional(),argsSchema:Cn(io()).optional()}),Ni=z({interruptOn:Cn(Ne([mr(),Ag])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function Pg(t){const e=async(r,s,o,i)=>{const a=r.name,c=r.args,l=s.description;let u;typeof l=="function"?u=await l(r,o,i):l!==void 0?u=l:u=`${t.descriptionPrefix??"Tool execution requires approval"}
186
+
187
+ Tool: ${a}
188
+ Args: ${JSON.stringify(c,null,2)}`;const h={name:a,args:c,description:u},d={actionName:a,allowedDecisions:s.allowedDecisions};return s.argsSchema&&(d.argsSchema=s.argsSchema),{actionRequest:h,reviewConfig:d}},n=(r,s,o)=>{const i=o.allowedDecisions;if(r.type==="approve"&&i.includes("approve"))return{revisedToolCall:s,toolMessage:null};if(r.type==="edit"&&i.includes("edit")){const c=r.editedAction;if(!c||typeof c.name!="string")throw new Error(`Invalid edited action for tool "${s.name}": name must be a string`);if(!c.args||typeof c.args!="object")throw new Error(`Invalid edited action for tool "${s.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:c.name,args:c.args,id:s.id},toolMessage:null}}if(r.type==="reject"&&i.includes("reject")){if(r.message!==void 0&&typeof r.message!="string")throw new Error(`Tool call response for "${s.name}" must be a string, got ${typeof r.message}`);const c=r.message??`User rejected the tool call for \`${s.name}\` with id ${s.id}`,l=new U({content:c,name:s.name,tool_call_id:s.id,status:"error"});return{revisedToolCall:s,toolMessage:l}}const a=`Unexpected human decision: ${JSON.stringify(r)}. Decision type '${r.type}' is not allowed for tool '${s.name}'. Expected one of ${JSON.stringify(i)} based on the tool's configuration.`;throw new Error(a)};return ge({name:"HumanInTheLoopMiddleware",contextSchema:Ni,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=Ye(Ni,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(w=>N.isInstance(w));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const c={};for(const[w,E]of Object.entries(o.interruptOn))typeof E=="boolean"?E===!0&&(c[w]={allowedDecisions:[...hl]}):E.allowedDecisions&&(c[w]=E);const l=[],u=[];for(const w of a.tool_calls)w.name in c?l.push(w):u.push(w);if(!l.length)return;const h=[],d=[];for(const w of l){const E=c[w.name],{actionRequest:T,reviewConfig:v}=await e(w,E,r,s);h.push(T),d.push(v)}const p=(await Uc({actionRequests:h,reviewConfigs:d})).decisions;if(!p||!Array.isArray(p))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(p.length!==l.length)throw new Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${l.length}).`);const b=[...u],C=[],y=p.some(w=>w.type==="reject");for(let w=0;w<p.length;w++){const E=p[w],T=l[w],v=c[T.name],{revisedToolCall:S,toolMessage:x}=n(E,T,v);S&&(!y||E.type==="reject")&&b.push(S),x&&C.push(x)}N.isInstance(a)&&(a.tool_calls=b);const _=y?"model":void 0;return{messages:[a,...C],jumpTo:_}}}})}const Og=!0,Ng="5m",Ig=3,$g="warn",Rg=z({enableCaching:mr().optional(),ttl:Qt(["5m","1h"]).optional(),minMessagesToCache:V().optional(),unsupportedModelBehavior:Qt(["ignore","warn","raise"]).optional()});var Ii=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function jg(t){return ge({name:"PromptCachingMiddleware",contextSchema:Rg,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??Og,s=e.runtime.context.ttl??t?.ttl??Ng,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??Ig,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??$g;if(!r||!e.model)return n(e);if(!(e.model.getName()==="ChatAnthropic"||e.model.getName()==="ConfigurableModel"&&e.model._defaultConfig?.modelProvider==="anthropic")){const h=e.model.getName(),f=`Unsupported model '${e.model.getName()==="ConfigurableModel"?`${h} (${e.model._defaultConfig?.modelProvider})`:h}'. Prompt caching requires an Anthropic model`;if(i==="raise")throw new Ii(`${f} (e.g., 'anthropic:claude-4-0-sonnet').`);return i==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${h}. Consider switching to an Anthropic model for caching benefits.`),n(e)}if(e.state.messages.length+(e.systemPrompt?1:0)<o)return n(e);const l=e.messages.at(-1);if(!l)return n(e);const u=Object.getPrototypeOf(l).constructor;if(Array.isArray(l.content)){const h=new u({...l,content:[...l.content.slice(0,-1),{...l.content.at(-1),cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}else if(typeof l.content=="string"){const h=new u({...l,content:[{type:"text",text:l.content,cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}throw new Ii("Last message content is not a string or array")}})}function Lg(t){return ge({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const r=await t(e.state,e.runtime);if(typeof r!="string")throw new Error("dynamicSystemPromptMiddleware function must return a string");return n({...e,systemPrompt:r})}})}const Fg="Your goal is to select the most relevant tools for answering the user's query.";function Dg(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>xt(r.name)),n=Ne(e);return z({tools:ze(n).describe("Tools to use. Place the most relevant tools first.")})}const Ug=z({model:ne().or(gr(bu)).optional(),systemPrompt:ne().optional(),maxTools:V().optional(),alwaysInclude:ze(ne()).optional()});function Vg(t){return ge({name:"LLMToolSelector",contextSchema:Ug,async wrapModelCall(e,n){const r=await Bg(e,t,e.runtime);if(!r)return n(e);const s=Dg(r.availableTools),i=await(await r.model.withStructuredOutput?.(s))?.invoke([{role:"system",content:r.systemMessage},r.lastUserMessage]);if(!i||typeof i!="object"||!("tools"in i))throw new Error(`Expected object response with tools array, got ${typeof i}`);return n(zg(i,r.availableTools,r.validToolNames,e,t))}})}async function Bg(t,e,n){const r=n.context.model??e.model,s=n.context.maxTools??e.maxTools,o=n.context.alwaysInclude??e.alwaysInclude??[],i=n.context.systemPrompt??e.systemPrompt??Fg;if(!t.tools||t.tools.length===0)return;const a=t.tools.filter(f=>typeof f=="object"&&"name"in f&&"description"in f&&typeof f.name=="string");if(o.length>0){const f=new Set(a.map(p=>p.name)),g=o.filter(p=>!f.has(p));if(g.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${g.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const c=a.filter(f=>!o.includes(f.name));if(c.length===0)return;let l=i;s!==void 0&&(l+=`
189
+ IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${s} will be used.`);let u;for(const f of t.messages)pe.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await cn(r):r:t.model,d=c.map(f=>f.name);return{availableTools:c,systemMessage:l,lastUserMessage:u,model:h,validToolNames:d}}function zg(t,e,n,r,s){const o=s.maxTools,i=s.alwaysInclude??[],a=[],c=[];for(const d of t.tools){if(!n.includes(d)){c.push(d);continue}!a.includes(d)&&(o===void 0||a.length<o)&&a.push(d)}if(c.length>0)throw new Error(`Model selected invalid tools: ${c.join(", ")}`);const l=e.filter(d=>a.includes(d.name)),u=(r.tools??[]).filter(d=>typeof d=="object"&&"name"in d&&typeof d.name=="string"&&i.includes(d.name));l.push(...u);const h=(r.tools??[]).filter(d=>!(typeof d=="object"&&"name"in d&&"description"in d&&typeof d.name=="string"));return{...r,tools:[...l,...h]}}const Hg=z({rules:Cn(ne(),gr(RegExp).describe("Regular expression pattern to match PII")).optional()});function Wg(){return Math.random().toString(36).substring(2,11)}function vs(t,e,n){let r=t;for(const[s,o]of Object.entries(e)){const i=s.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");r=r.replace(o,a=>{const c=Wg();return n[c]=a,`[REDACTED_${i}_${c}]`})}return r}async function qg(t,e){if(pe.isInstance(t)||U.isInstance(t)||be.isInstance(t)){const n=t.content,r=await vs(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(N.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await vs(n,e.rules,e.redactionMap),o=await vs(r,e.rules,e.redactionMap);return s!==n||o!==r?new N({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}):t}throw new Error(`Unsupported message type: ${t.type}`)}function _n(t,e){let n=t;const r=/\[REDACTED_[A-Z_]+_(\w+)\]/g;return n=n.replace(r,(s,o)=>e[o]?e[o]:s),n}function $i(t,e){if(pe.isInstance(t)||U.isInstance(t)||be.isInstance(t)){const n=t.content,r=_n(n,e);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return{message:new s({...t,content:r}),changed:!0}}return{message:t,changed:!1}}if(N.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=_n(n,e),o=_n(r,e);return s!==n||o!==r?{message:new N({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(o)}),changed:!0}:{message:t,changed:!1}}throw new Error(`Unsupported message type: ${t.type}`)}function Kg(t={}){const e={};return ge({name:"PIIRedactionMiddleware",contextSchema:Hg,wrapModelCall:async(n,r)=>{const s=n.runtime.context.rules??t.rules??{};if(Object.keys(s).length===0)return r(n);const o=await Promise.all(n.state.messages.map(i=>qg(i,{rules:s,redactionMap:e})));return r({...n,messages:o})},afterModel:async n=>{if(Object.keys(e).length===0)return;const r=n.messages.at(-1);if(!N.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=$i(r,e);if(!i)return;let a;if(N.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(_n(r.content,e))}catch{}if(N.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(l=>l.name.startsWith("extract-"))){const{message:l,changed:u}=$i(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(_n(JSON.stringify(h),e)):void 0;if(i||u)return{...n,...d?{structuredResponse:d}:{},messages:[new Gn({id:s.id}),new Gn({id:r.id}),l,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new Gn({id:r.id}),o]}}})}const Gg="[cleared]";var dl=class{triggerTokens;clearAtLeast;keep;clearToolInputs;excludeTools;placeholder;constructor(t={}){this.triggerTokens=t.triggerTokens??1e5,this.clearAtLeast=t.clearAtLeast??0,this.keep=t.keep??3,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??Gg}async apply(t){const{tokens:e,messages:n,countTokens:r}=t;if(e<=this.triggerTokens)return e;const s=[];for(let a=0;a<n.length;a++){const c=n[a];U.isInstance(c)&&s.push({idx:a,msg:c})}const o=this.keep>=s.length?[]:this.keep>0?s.slice(0,-this.keep):s;let i=0;for(const{idx:a,msg:c}of o){if(this.clearAtLeast>0&&i>=this.clearAtLeast)break;if(c.response_metadata?.context_editing?.cleared)continue;const u=this.#e(n.slice(0,a),c.tool_call_id);if(!u)continue;const h=u.tool_calls?.find(g=>g.id===c.tool_call_id);if(!h)continue;const d=c.name||h.name;if(this.excludeTools.has(d))continue;if(n[a]=new U({tool_call_id:c.tool_call_id,content:this.placeholder,name:c.name,artifact:void 0,response_metadata:{...c.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const g=n.indexOf(u);g>=0&&(n[g]=this.#n(u,c.tool_call_id))}const f=await r(n);i=Math.max(0,e-f)}return e-i}#e(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(N.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#n(t,e){const n=t.tool_calls?.map(i=>i.id===e?{...i,args:{}}:i),r={...t.response_metadata},s={...r.context_editing},o=new Set(s.cleared_tool_inputs);return o.add(e),s.cleared_tool_inputs=Array.from(o).sort(),r.context_editing=s,new N({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function Jg(t={}){const e=t.edits??[new dl],n=t.tokenCountMethod??"approx";return ge({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new be(r.systemPrompt)]:[],i=n==="approx"?ho:async c=>{const l=[...o,...c];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(l).then(({totalCount:u})=>u);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};let a=await i(r.messages);for(const c of e)a=await c.apply({tokens:a,messages:r.messages,countTokens:i});return s(r)}})}function Yg(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const Xg=["continue","error","end"],fl="continue";function pl(t,e,n,r,s){const o=s?`'${s}' tool`:"Tool",i=[];n!==void 0&&t>n&&i.push(`thread limit exceeded (${t}/${n} calls)`),r!==void 0&&e>r&&i.push(`run limit exceeded (${e}/${r} calls)`);const a=i.join(" and ");return`${o} call limit reached: ${a}.`}const ml=Qt(Xg).default(fl);var gl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=pl(t,e,n,r,s);super(o),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=r,this.toolName=s}};z({toolName:ne().optional(),threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:ml});const Zg=z({threadToolCallCount:Cn(ne(),V()).default({}),runToolCallCount:Cn(ne(),V()).default({})}),Qg="__all__";function ey(t){if(t.threadLimit===void 0&&t.runLimit===void 0)throw new Error("At least one limit must be specified (threadLimit or runLimit)");const e=t.exitBehavior??fl,n=ml.safeParse(e);if(!n.success)throw new Error(Ui(n.error).slice(2));if(t.threadLimit!==void 0&&t.runLimit!==void 0&&t.runLimit>t.threadLimit)throw new Error(`runLimit (${t.runLimit}) cannot exceed threadLimit (${t.threadLimit}). The run limit should be less than or equal to the thread limit.`);const r=t.toolName?`ToolCallLimitMiddleware[${t.toolName}]`:"ToolCallLimitMiddleware";return ge({name:r,stateSchema:Zg,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(N.isInstance);if(!o||!o.tool_calls)return;const i=(w,E)=>t.threadLimit!==void 0&&w+1>t.threadLimit||t.runLimit!==void 0&&E+1>t.runLimit,a=w=>t.toolName===void 0||w.name===t.toolName,c=(w,E,T)=>{const v=[],S=[];let x=E,M=T;for(const P of w)a(P)&&(i(x,M)?S.push(P):(v.push(P),x+=1,M+=1));return{allowed:v,blocked:S,finalThreadCount:x,finalRunCount:M+S.length}},l=t.toolName??Qg,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[l]??0,f=h[l]??0,{allowed:g,blocked:p,finalThreadCount:b,finalRunCount:C}=c(o.tool_calls,d,f);if(u[l]=b,h[l]=C,p.length===0)return g.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const w=b+p.length;throw new gl(w,C,t.threadLimit,t.runLimit,t.toolName)}const y=Yg(t.toolName),_=p.map(w=>new U({content:y,tool_call_id:w.id,name:w.name,status:"error"}));if(e==="end"){let w=[];if(t.toolName!==void 0?w=o.tool_calls.filter(v=>v.name!==t.toolName):new Set(o.tool_calls.map(S=>S.name).filter(Boolean)).size>1&&(w=g.length>0?g:o.tool_calls),w.length>0){const v=Array.from(new Set(w.map(S=>S.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${v}. Use 'continue' or 'error' behavior instead.`)}const E=b+p.length,T=pl(E,C,t.threadLimit,t.runLimit,t.toolName);return _.push(new N(T)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:_}}return{threadToolCallCount:u,runToolCallCount:h,messages:_}}},afterAgent:()=>({runToolCallCount:{}})})}const ty=`Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
190
+ It also helps the user understand the progress of the task and overall progress of their requests.
191
+ Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
192
+
193
+ ## When to Use This Tool
194
+ Use this tool in these scenarios:
195
+
196
+ 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
197
+ 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
198
+ 3. User explicitly requests todo list - When the user directly asks you to use the todo list
199
+ 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
200
+ 5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful.
201
+
202
+ ## How to Use This Tool
203
+ 1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
204
+ 2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
205
+ 3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.
206
+ 4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.
207
+
208
+ ## When NOT to Use This Tool
209
+ It is important to skip using this tool when:
210
+ 1. There is only a single, straightforward task
211
+ 2. The task is trivial and tracking it provides no benefit
212
+ 3. The task can be completed in less than 3 trivial steps
213
+ 4. The task is purely conversational or informational
214
+
215
+ ## Examples of When to Use the Todo List
216
+
217
+ <example>
218
+ User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
219
+ Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
220
+ *Creates todo list with the following items:*
221
+ 1. Create dark mode toggle component in Settings page
222
+ 2. Add dark mode state management (context/store)
223
+ 3. Implement CSS-in-JS styles for dark theme
224
+ 4. Update existing components to support theme switching
225
+ 5. Run tests and build process, addressing any failures or errors that occur
226
+ *Begins working on the first task*
227
+
228
+ <reasoning>
229
+ The assistant used the todo list because:
230
+ 1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
231
+ 2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
232
+ 3. Both of the user's requests are complex and require multiple steps to complete.
233
+ </reasoning>
234
+ </example>
235
+
236
+ <example>
237
+ User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
238
+ Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.
239
+ *Creates todo list with the following items:*
240
+ 1. Define target audience and key messaging
241
+ 2. Create social media content calendar and posting schedule
242
+ 3. Design email marketing sequence and automation flows
243
+ 4. Draft press release and identify media contacts
244
+ 5. Set up tracking and analytics for campaign performance
245
+ 6. Create visual assets and brand materials
246
+ 7. Coordinate launch timeline and deliverables
247
+ *Begins working on the first task*
248
+
249
+ <reasoning>
250
+ The assistant used the todo list because:
251
+ 1. Marketing campaign planning involves multiple distinct channels and activities
252
+ 2. Each component requires careful coordination and planning
253
+ 3. The systematic approach ensures all aspects of the launch are covered
254
+ </reasoning>
255
+ </example>
256
+
257
+ <example>
258
+ User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
259
+ Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
260
+ *Uses search tools to locate all instances of getCwd in the codebase*
261
+ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
262
+ *Creates todo list with specific items for each file that needs updating*
263
+
264
+ <reasoning>
265
+ The assistant used the todo list because:
266
+ 1. The assistant searched to understand the scope of the task
267
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
268
+ 3. The todo list helps ensure every instance is tracked and updated systematically
269
+ 4. This approach prevents missing any occurrences and maintains consistency.
270
+ </reasoning>
271
+ </example>
272
+
273
+ <example>
274
+ User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
275
+ Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
276
+ *Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines*
277
+ Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
278
+
279
+ <reasoning>
280
+ The assistant used the todo list because:
281
+ 1. The user provided multiple distinct organizational tasks
282
+ 2. Each area requires different approaches and careful planning
283
+ 3. Home organization benefits from systematic, step-by-step completion
284
+ 4. Progress tracking ensures all areas are addressed thoroughly
285
+ </reasoning>
286
+ </example>
287
+
288
+ ## Examples of When NOT to Use the Todo List
289
+
290
+ <example>
291
+ User: How do I print 'Hello World' in Python?
292
+ Assistant: In Python, you can print "Hello World" with this simple code:
293
+
294
+ \`\`\`python
295
+ print("Hello World")
296
+ \`\`\`
297
+
298
+ This will output the text "Hello World" to the console when executed.</assistant>
299
+
300
+ <reasoning>
301
+ The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
302
+ </reasoning>
303
+ </example>
304
+
305
+ <example>
306
+ User: What's the best way to water houseplants?
307
+ Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
308
+
309
+ - Check soil moisture by inserting your finger about 1-2 inches into the soil
310
+ - Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
311
+ - Use room temperature water and water in the morning when possible
312
+ - Avoid overwatering, which is more harmful than underwatering for most plants
313
+
314
+ Different plants have different needs, so it's important to research your specific varieties for optimal care.
315
+
316
+ <reasoning>
317
+ The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities.
318
+ </reasoning>
319
+ </example>
320
+
321
+ <example>
322
+ User: Can you add a comment to the calculateTotal function to explain what it does?
323
+ Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
324
+ * Uses the Edit tool to add a comment to the calculateTotal function *
325
+
326
+ <reasoning>
327
+ The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization.
328
+ </reasoning>
329
+ </example>
330
+
331
+ <example>
332
+ User: What time is it in Tokyo right now?
333
+ Assistant: I'll check the current time in Tokyo for you.
334
+
335
+ *Searches for current time in Tokyo*
336
+
337
+ The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
338
+
339
+ <reasoning>
340
+ The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request.
341
+ </reasoning>
342
+ </example>
343
+
344
+ <example>
345
+ User: I need to write a function that checks if a number is prime and then test it out.
346
+ Assistant: I'll help you write a function that checks if a number is prime and then test it out.
347
+ *Writes function that checks if a number is prime*
348
+ *Tests the function*
349
+
350
+ <reasoning>
351
+ Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens.
352
+ </reasoning>
353
+ </example>
354
+
355
+ <example>
356
+ User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
357
+ Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
358
+ *Orders a pizza from Dominos*
359
+ *Orders a burger from McDonald's*
360
+ *Orders a salad from Subway*
361
+
362
+ <reasoning>
363
+ Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls.
364
+ Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
365
+ </reasoning>
366
+ </example>
367
+
368
+
369
+ ## Task States and Management
370
+
371
+ 1. **Task States**: Use these states to track progress:
372
+ - pending: Task not yet started
373
+ - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)
374
+ - completed: Task finished successfully
375
+
376
+ 2. **Task Management**:
377
+ - Update task status in real-time as you work
378
+ - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
379
+ - Complete current tasks before starting new ones
380
+ - Remove tasks that are no longer relevant from the list entirely
381
+ - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
382
+ - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something.
383
+
384
+ 3. **Task Completion Requirements**:
385
+ - ONLY mark a task as completed when you have FULLY accomplished it
386
+ - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
387
+ - When blocked, create a new task describing what needs to be resolved
388
+ - Never mark a task as completed if:
389
+ - There are unresolved issues or errors
390
+ - Work is partial or incomplete
391
+ - You encountered blockers that prevent completion
392
+ - You couldn't find necessary resources or dependencies
393
+ - Quality standards haven't been met
394
+
395
+ 4. **Task Breakdown**:
396
+ - Create specific, actionable items
397
+ - Break complex tasks into smaller, manageable steps
398
+ - Use clear, descriptive task names
399
+
400
+ Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
401
+ Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`,yl=`## \`write_todos\`
402
+
403
+ You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
404
+ Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
405
+ This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
406
+
407
+ It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.
408
+ For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.
409
+ Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.
410
+
411
+ ## Important To-Do List Usage Notes to Remember
412
+ - The \`write_todos\` tool should never be called multiple times in parallel.
413
+ - Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`,ny=Qt(["pending","in_progress","completed"]).describe("Status of the todo"),wl=z({content:ne().describe("Content of the todo item"),status:ny}),ry=z({todos:ze(wl).default([])});function sy(t){const e=zi(({todos:n},r)=>new K({update:{todos:n,messages:[new U({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??ty,schema:z({todos:ze(wl).describe("List of todo items to update")})});return ge({name:"todoListMiddleware",stateSchema:ry,tools:[e],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
414
+
415
+ `:"")+(t?.systemPrompt??yl)})})}const oy="end",iy=z({threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:Qt(["throw","end"]).optional()}),ay=z({threadModelCallCount:V().default(0),runModelCallCount:V().default(0)});var Ri=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:n,runCount:r}){const s=[];typeof t=="number"&&typeof n=="number"&&s.push(`thread level call limit reached with ${n} model calls`),typeof e=="number"&&typeof r=="number"&&s.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${s.length>0?`: ${s.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function vl(t){return ge({name:"ModelCallLimitMiddleware",contextSchema:iy,stateSchema:ay,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??oy,s=n.context.threadLimit??t?.threadLimit,o=n.context.runLimit??t?.runLimit,i=e.threadModelCallCount,a=e.runModelCallCount;if(typeof s=="number"&&s<=i){const c=new Ri({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new N(c.message)]};throw c}if(typeof o=="number"&&o<=a){const c=new Ri({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new N(c.message)]};throw c}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function cy(...t){return ge({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(r){for(let s=0;s<t.length;s++)try{const o=t[s],i=typeof o=="string"?await cn(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}function ly(t,e){const{backoffFactor:n,initialDelayMs:r,maxDelayMs:s,jitter:o}=t;let i;if(n===0?i=r:i=r*n**e,i=Math.min(i,s),o&&i>0){const a=i*.25;i=i+(Math.random()*2-1)*a,i=Math.max(0,i)}return i}const ji=z({maxRetries:V().min(0).default(2),tools:ze(Ne([ce(),ce(),ne()])).optional(),retryOn:Ne([pr().args(gr(Error)).returns(mr()),ze(ce())]).default(()=>()=>!0),onFailure:Ne([xt("raise"),xt("return_message"),pr().args(gr(Error)).returns(ne())]).default("return_message"),backoffFactor:V().min(0).default(2),initialDelayMs:V().min(0).default(1e3),maxDelayMs:V().min(0).default(6e4),jitter:mr().default(!0)});function uy(t={}){const{maxRetries:e,tools:n,retryOn:r,onFailure:s,backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:c}=ji.parse(t),l=[];for(const p of n??[])if(typeof p=="string")l.push(p);else if("name"in p&&typeof p.name=="string")l.push(p.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const u=p=>l.length===0?!0:l.includes(p),h=p=>typeof r=="function"?r(p):r.some(b=>p.constructor===b),d={backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:c},f=(p,b,C)=>{const y=b.constructor.name;return`Tool '${p}' failed after ${C} ${C===1?"attempt":"attempts"} with ${y}`},g=(p,b,C,y)=>{if(s==="raise")throw C;let _;return typeof s=="function"?_=s(C):_=f(p,C,y),new U({content:_,tool_call_id:b,name:p,status:"error"})};return ge({name:"toolRetryMiddleware",contextSchema:ji,wrapToolCall:async(p,b)=>{const C=p.tool.name;if(!u(C))return b(p);const y=p.toolCall.id??"";for(let _=0;_<=e;_++)try{return await b(p)}catch(w){const E=_+1,T=w&&typeof w=="object"&&"message"in w?w:new Error(String(w));if(!h(T))return g(C,y,T,E);if(_<e){const v=ly(d,_);v>0&&await id(v)}else return g(C,y,T,E)}throw new Error("Unexpected: retry loop completed without returning")}})}var hy={};sa(hy,{AIMessage:()=>N,AIMessageChunk:()=>Yt,BaseMessage:()=>yn,BaseMessageChunk:()=>hh,ClearToolUsesEdit:()=>dl,Document:()=>Ve,DynamicStructuredTool:()=>Kn,DynamicTool:()=>eu,FakeToolCallingModel:()=>np,HumanMessage:()=>pe,HumanMessageChunk:()=>uh,InMemoryStore:()=>va,MultipleStructuredOutputsError:()=>Ms,MultipleToolsBoundError:()=>ks,ProviderStrategy:()=>lt,StructuredOutputParsingError:()=>ca,StructuredTool:()=>$r,SystemMessage:()=>be,SystemMessageChunk:()=>lh,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>yl,Tool:()=>Ql,ToolCallLimitExceededError:()=>gl,ToolInvocationError:()=>lo,ToolMessage:()=>U,ToolMessageChunk:()=>ch,ToolStrategy:()=>We,anthropicPromptCachingMiddleware:()=>jg,contextEditingMiddleware:()=>Jg,countTokensApproximately:()=>ho,createAgent:()=>cl,createMiddleware:()=>ge,dynamicSystemPromptMiddleware:()=>Lg,filterMessages:()=>ah,humanInTheLoopMiddleware:()=>Pg,initChatModel:()=>cn,llmToolSelectorMiddleware:()=>Vg,modelCallLimitMiddleware:()=>vl,modelFallbackMiddleware:()=>cy,piiRedactionMiddleware:()=>Kg,providerStrategy:()=>sd,summarizationMiddleware:()=>gg,todoListMiddleware:()=>sy,tool:()=>zi,toolCallLimitMiddleware:()=>ey,toolRetryMiddleware:()=>uy,toolStrategy:()=>rd,trimMessages:()=>Ji});var _l={},Dt,Vr=(Dt=class extends $r{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(e){super(),this._manager=e}async _call(e,n,r){throw new Error("Method not implemented.")}get manager(){return this._manager}},A(Dt,"MCPServerTool"),Dt),dy=we({}),Ut,fy=(Ut=class extends Vr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=dy;constructor(e){super(e)}async _call(){return this.manager.activeServer?`Currently active MCP server: ${this.manager.activeServer}`:"No MCP server is currently active. Use connect_to_mcp_server to connect to a server."}},A(Ut,"AcquireActiveMCPServerTool"),Ut),Vt,py=(Vt=class extends $r{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=we({serverName:Nr().describe("The name for the new MCP server."),serverConfig:Ee().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(e){super(),this.manager=e}async _call({serverName:e,serverConfig:n}){try{this.manager.client.addServer(e,n);let r=`Server '${e}' added to the client.`;m.debug(`Connecting to new server '${e}' and discovering tools.`);const o=(await this.manager.client.createSession(e)).connector,i=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=i,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=i.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
416
+
417
+ ${i.map(c=>c.name).join(`
418
+ `)}`,m.info(r),r}catch(r){return m.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},A(Vt,"AddMCPServerFromConfigTool"),Vt),my=we({serverName:Nr().describe("The name of the MCP server.")}),Bt,gy=(Bt=class extends Vr{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=my;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(m.debug(`Using existing session for server '${e}'`),r||(m.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,!this.manager.serverTools[e]){const i=r.connector,a=await this.manager.adapter.createToolsFromConnectors([i]),c=await this.manager.adapter.createResourcesFromConnectors([i]),l=await this.manager.adapter.createPromptsFromConnectors([i]),u=[...a,...c,...l];this.manager.serverTools[e]=u,this.manager.initializedServers[e]=!0,m.debug(`Loaded ${u.length} items for server '${e}': ${a.length} tools, ${c.length} resources, ${l.length} prompts`)}const o=(this.manager.serverTools[e]||[]).length;return`Connected to MCP server '${e}'. ${o} tools, resources, and prompts are now available.`}catch(r){return m.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},A(Bt,"ConnectMCPServerTool"),Bt),yy=we({}),zt,wy=(zt=class extends Vr{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=yy;constructor(e){super(e)}async _call(){const e=this.manager.client.getServerNames();if(e.length===0)return"No MCP servers are currently defined.";const n=["Available MCP servers:"];for(const r of e){const o=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${o}`);try{const i=this.manager.serverTools?.[r]??[],a=Array.isArray(i)?i.length:0;n.push(`${a} tools available for this server
419
+ `)}catch(i){m.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
420
+ `)}},A(zt,"ListMCPServersTool"),zt),vy=we({}),Ht,_y=(Ht=class extends Vr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=vy;constructor(e){super(e)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const e=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${e}'.`}},A(Ht,"ReleaseMCPServerConnectionTool"),Ht);function Or(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?!1:t.every((n,r)=>Or(n,e[r]));if(typeof t=="object"&&typeof e=="object"){const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>Object.prototype.hasOwnProperty.call(e,s)&&Or(t[s],e[s]))}return!1}A(Or,"isEqual");var Wt,Li=(Wt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,m.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){m.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));m.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&m.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),m.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(m.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),m.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(h){m.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const c=[...o,...i,...a],l=this.serverTools[n];!l||!Or(l,c)?(this.serverTools[n]=c,this.initializedServers[n]=!0,m.debug(`Prefetched ${c.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):m.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){m.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){m.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new py(this),new wy(this),new gy(this),new fy(this),new _y(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return m.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},A(Wt,"ServerManager"),Wt),qt,Qs=(qt=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:n}=await Jt(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await import("./langfuse-74RGPTAH-CzkBGeHI.js");return{langfuseHandler:s,langfuseInitPromise:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Jt(async()=>{const{initializeLangfuse:o}=await import("./langfuse-74RGPTAH-CzkBGeHI.js");return{initializeLangfuse:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),m.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),m.debug("ObservabilityManager: Langfuse handler available"))}catch{m.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(m.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?m.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):m.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(m.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),m.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],m.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();m.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();m.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},A(qt,"ObservabilityManager"),qt),by="/api/v1/chats",Sy="/api/v1/chats/{chat_id}/execute";function bl(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}A(bl,"normalizeRemoteRunOptions");var Kt,Sl=(Kt=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const n=e.apiKey??_l.MCP_USE_API_KEY;if(!n)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=n}pydanticToJsonSchema(e){return qn(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){m.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${by}`;m.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),c=s.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} - ${a}`)}const i=(await s.json()).id;return m.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:c,outputSchema:l}=bl(e,n,r,s,o);c!==void 0&&m.warn("External history is not yet supported for remote execution");try{m.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,h={query:i,max_steps:a??10};l&&(h.output_schema=this.pydanticToJsonSchema(l),m.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${Sy.replace("{chat_id}",u)}`;m.info(`🚀 Executing agent in chat ${u}`);const g=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!g.ok){const b=await g.text(),C=g.status;throw C===401?(m.error(`❌ Authentication failed: ${b}`),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.")):C===403?(m.error(`❌ Access forbidden: ${b}`),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.`)):C===404?(m.error(`❌ Agent not found: ${b}`),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.`)):C===422?(m.error(`❌ Validation error: ${b}`),new Error(`Request validation failed: ${b}. Please check your query parameters and output schema format.`)):C===500?(m.error(`❌ Server error: ${b}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(m.error(`❌ Remote execution failed with status ${C}: ${b}`),new Error(`Remote agent execution failed: ${C} - ${b}`))}const p=await g.json();if(m.info(`🔧 Response: ${JSON.stringify(p)}`),m.info("✅ Remote execution completed successfully"),typeof p=="object"&&p!==null){if(p.status==="error"||p.error!==null){const b=p.error??String(p);throw m.error(`❌ Remote agent execution failed: ${b}`),new Error(`Remote agent execution failed: ${b}`)}if(String(p).includes("failed to initialize"))throw m.error(`❌ Agent initialization failed: ${p}`),new Error(`Agent initialization failed on remote server. This usually indicates:
421
+ • Invalid agent configuration (LLM model, system prompt)
422
+ • Missing or invalid MCP server configurations
423
+ • Network connectivity issues with MCP servers
424
+ • Missing environment variables or credentials
425
+ Raw error: ${p}`)}return l?this.parseStructuredResponse(p,l):typeof p=="object"&&p!==null&&"result"in p?p.result:typeof p=="string"?p:String(p)}catch(u){throw u instanceof Error?u.name==="AbortError"?(m.error(`❌ Remote execution timed out: ${u}`),new Error("Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.")):(m.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${u.message}`)):(m.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${String(u)}`))}}async*stream(e,n,r,s,o){return await this.run(e,n,r,s,o)}async close(){m.info("🔌 Remote agent client closed")}},A(Kt,"RemoteAgent"),Kt),On={openai:{package:"@langchain/openai",className:"ChatOpenAI",envVars:["OPENAI_API_KEY"],defaultModel:"gpt-4o"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic",envVars:["ANTHROPIC_API_KEY"],defaultModel:"claude-3-5-sonnet-20241022"},google:{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI",envVars:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY"],defaultModel:"gemini-pro"},groq:{package:"@langchain/groq",className:"ChatGroq",envVars:["GROQ_API_KEY"],defaultModel:"llama-3.1-70b-versatile"}};function Br(t){const e=t.split("/");if(e.length!==2)throw new Error(`Invalid LLM string format. Expected 'provider/model', got '${t}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);const[n,r]=e;if(!n||!r)throw new Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${t}'`);const s=n.toLowerCase();if(!(s in On)){const o=Object.keys(On).join(", ");throw new Error(`Unsupported LLM provider '${n}'. Supported providers: ${o}`)}return{provider:s,model:r}}A(Br,"parseLLMString");function Cl(t,e){if(e?.apiKey)return e.apiKey;const n=On[t];for(const s of n.envVars){const o=_l[s];if(o)return m.debug(`Using API key from environment variable ${s} for provider ${t}`),o}const r=n.envVars.join(" or ");throw new Error(`API key not found for provider '${t}'. Set ${r} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${t}/model', llmConfig: { apiKey: 'your-key' } })`)}A(Cl,"getAPIKey");async function jo(t,e){m.info(`Creating LLM from string: ${t}`);const{provider:n,model:r}=Br(t),s=On[n],o=Cl(n,e);let i;try{m.debug(`Importing package ${s.package}...`),i=await import(s.package)}catch(l){throw l?.code==="MODULE_NOT_FOUND"||l?.message?.includes("Cannot find module")||l?.message?.includes("Cannot find package")?new Error(`Package '${s.package}' is not installed. Install it with: npm install ${s.package} or yarn add ${s.package}`):new Error(`Failed to import ${s.package}: ${l?.message||l}`)}const a=i[s.className];if(!a)throw new Error(`Could not find ${s.className} in package ${s.package}. This might be a version compatibility issue.`);const c={model:r,apiKey:o,...e};e?.apiKey&&(delete c.apiKey,c.apiKey=o),(n==="anthropic"||n==="google"||n==="openai"||n==="groq")&&(c.model=r);try{const l=new a(c);return m.info(`Successfully created ${n} LLM with model ${r}`),l}catch(l){throw new Error(`Failed to instantiate ${s.className} with model '${r}': ${l?.message||l}`)}}A(jo,"createLLMFromString");function El(t){try{return Br(t),!0}catch{return!1}}A(El,"isValidLLMString");function Tl(){return Object.keys(On)}A(Tl,"getSupportedProviders");function xl(t,e){const n=new Set(e??[]),r=[];for(const s of t){if(n.has(s.name))continue;const o=s.description.replace(/\{/g,"{{").replace(/\}/g,"}}");r.push(`- ${s.name}: ${o}`)}return r}A(xl,"generateToolDescriptions");function kl(t,e,n){const r=e.join(`
426
+ `);let s;return t.includes("{tool_descriptions}")?s=t.replace("{tool_descriptions}",r):(console.warn("`{tool_descriptions}` placeholder not found; appending at end."),s=`${t}
427
+
428
+ Available tools:
429
+ ${r}`),n&&(s+=`
430
+
431
+ ${n}`),s}A(kl,"buildSystemPromptContent");function Ml(t,e,n,r,s,o,i){if(o)return new be({content:o});const a=r?n:e,c=xl(t,s),l=kl(a,c,i);return new be({content:l})}A(Ml,"createSystemMessage");var Cy=`You are a helpful AI assistant.
432
+ You have access to the following tools:
433
+
434
+ {tool_descriptions}
435
+
436
+ Use the following format:
437
+
438
+ Question: the input question you must answer
439
+ Thought: you should always think about what to do
440
+ Action: the action to take, should be one of the available tools
441
+ Action Input: the input to the action
442
+ Observation: the result of the action
443
+ ... (this Thought/Action/Action Input/Observation can repeat N times)
444
+ Thought: I now know the final answer
445
+ Final Answer: the final answer to the original input question`,Ey=`You are a helpful assistant designed to interact with MCP
446
+ (Model Context Protocol) servers. You can manage connections to different servers and use the tools
447
+ provided by the currently active server.
448
+
449
+ Important: The available tools change depending on which server is active.
450
+ If a request requires tools not listed below (e.g., file operations, web browsing,
451
+ image manipulation), you MUST first connect to the appropriate server using
452
+ 'connect_to_mcp_server'.
453
+ Use 'list_mcp_servers' to find the relevant server if you are unsure.
454
+ Only after successfully connecting and seeing the new tools listed in
455
+ the response should you attempt to use those server-specific tools.
456
+ Before attempting a task that requires specific tools, you should
457
+ ensure you are connected to the correct server and aware of its
458
+ available tools. If unsure, use 'list_mcp_servers' to see options
459
+ or 'get_active_mcp_server' to check the current connection.
460
+
461
+ When you connect to a server using 'connect_to_mcp_server',
462
+ you will be informed about the new tools that become available.
463
+ You can then use these server-specific tools in subsequent steps.
464
+
465
+ Here are the tools *currently* available to you (this list includes server management tools and will
466
+ change when you connect to a server):
467
+ {tool_descriptions}
468
+ `;function dr(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}A(dr,"normalizeRunOptions");var Gt,Ty=(Gt=class{static getPackageVersion(){return to()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Sl({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new vt,this.telemetry=Wn.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qs({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],m.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new vt(this.disallowedTools),this.telemetry=Wn.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new vt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Li(this.client,this.adapter)}else this.adapter=e.adapter??new vt(this.disallowedTools);if(this.telemetry=Wn.getInstance(),this.llm){const[r,s]=Fo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Qs({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:A(()=>this.getMetadata(),"metadataProvider"),tagsProvider:A(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:A(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:A(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:A(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(m.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(m.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig&&(m.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`),this.client=new Xh({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")),this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await jo(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=Fo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new Li(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&m.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),m.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),m.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(m.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),m.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),m.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],m.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{m.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),m.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}m.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),m.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),m.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Cy;this.systemMessage=Ml(e,n,Ey,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof be))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);m.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[vl({runLimit:this.maxSteps})],s=cl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return m.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new be(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof be)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),m.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new vt(this.disallowedTools),this._initialized&&m.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},m.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],m.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){m.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(m.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){m.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else m.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){m.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){m.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof pe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof N||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o){const{query:i,maxSteps:a,manageConnector:c,externalHistory:l,outputSchema:u}=dr(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,c,l,u);const h=this.stream(i,a,c,l,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:c,externalHistory:l,outputSchema:u}=dr(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,c,l,u);let h=!1;const d=Date.now();let f=!1,g=null,p=0;try{if(c&&!this._initialized?(await this.initialize(),h=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),h=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const T=this.serverManager.tools,v=new Set(T.map(x=>x.name)),S=new Set(this._tools.map(x=>x.name));(v.size!==S.size||[...v].some(x=>!S.has(x)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...v].join(", ")}`),this._tools=T,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const b=l??this.conversationHistory,C=[];for(const T of b)(this._isHumanMessageLike(T)||this._isAIMessageLike(T)||this._isToolMessageLike(T))&&C.push(T);const y=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");m.info(`💬 Received query: '${y}'`),m.info("🏁 Starting agent execution");const _=3;let w=0;const E=[...C,new pe(i)];for(;w<=_;){const T={messages:E};let v=!1;const S=await this._agentExecutor.stream(T,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const x of S){for(const[M,P]of Object.entries(x))if(m.debug(`📦 Node '${M}' output: ${JSON.stringify(P)}`),P&&typeof P=="object"&&"messages"in P){let I=P.messages;Array.isArray(I)||(I=[I]);for(const j of I)E.includes(j)||E.push(j);for(const j of I){if("tool_calls"in j&&Array.isArray(j.tool_calls)&&j.tool_calls.length>0)for(const ee of j.tool_calls){const re=ee.name||"unknown",Se=ee.args||{};this.toolsUsedNames.push(re),p++;let ke=JSON.stringify(Se);ke.length>100&&(ke=`${ke.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${ke}`),yield{action:{tool:re,toolInput:Se,log:`Calling tool ${re}`},observation:""}}if(this._isToolMessageLike(j)){const ee=j.content;let re=String(ee);if(re.length>100&&(re=`${re.slice(0,97)}...`),re=re.replace(/\n/g," "),m.info(`📄 Tool result: ${re}`),this.useServerManager&&this.serverManager){const Se=this.serverManager.tools,ke=new Set(Se.map(un=>un.name)),Ln=new Set(this._tools.map(un=>un.name));if(ke.size!==Ln.size||[...ke].some(un=>!Ln.has(un))){m.info(`🔄 Tools changed during execution. New tools: ${[...ke].join(", ")}`),this._tools=Se,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),v=!0,w++,m.info(`🔃 Restarting execution with updated tools (restart ${w}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(v)break}if(v)break}if(!v)break;if(w>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const T=E.slice(C.length);for(const v of T)this.addToHistory(v)}if(u&&g)try{m.info("🔧 Attempting structured output...");const T=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"),f=!0,T}catch(T){throw m.error(`❌ Structured output failed: ${T}`),new Error(`Failed to generate structured output: ${T instanceof Error?T.message:String(T)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(b){throw m.error(`❌ Error running query: ${b}`),h&&c&&(m.info("🧹 Cleaning up resources after error"),await this.close()),b}finally{const b=Date.now()-d;let C=0;this.client?C=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(C=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0,_=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:c??!0,externalHistoryUsed:l!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:b,errorType:f?null:"execution_error",conversationHistoryLength:y}),c&&!this.client&&h&&(m.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(m.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}m.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(m.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(m.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)m.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(m.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new vt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Jt(async()=>{const{prettyStreamEvents:c}=await import("./display-A5IEINAP-H3Q2-YX2.js");return{prettyStreamEvents:c}},__vite__mapDeps([10,1,2])),a="";for await(const c of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=dr(e,n,r,s,o);let{query:a}=i;const{maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let g=!1,p=0,b=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{l&&!this._initialized?(await this.initialize(),d=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),d=!0);const y=this._agentExecutor;if(!y)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const _=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);m.info(`💬 Received query for streamEvents: '${_}'`),this.memoryEnabled&&(m.info(`🔄 Adding user message to history: ${_}`),this.addToHistory(new pe({content:a})));const w=u??this.conversationHistory,E=[];for(const S of w)this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S)?E.push(S):m.info(`⚠️ Skipped message of type: ${S.constructor?.name||typeof S}`);const T=[...E,new pe(a)];m.info("callbacks",this.callbacks);const v=y.streamEvents({messages:T},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const S of v)if(p++,!(!S||typeof S!="object")){if(S.event==="on_chat_model_stream"&&S.data?.chunk?.content&&(b+=S.data.chunk.content.length),S.event==="on_chat_model_stream"&&S.data?.chunk){const x=S.data.chunk;if(x.content){C||(C="");const M=this._normalizeOutput(x.content);C+=M,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!C){const x=S.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?C=x[0].text:typeof x=="string"?C=x:x&&typeof x=="object"&&"output"in x&&(C=x.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let S=!1,x=null,M=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(S=!0,x=I,I)).catch(I=>{throw S=!0,M=I,I});let P=0;for(;!S;)await new Promise(I=>setTimeout(I,2e3)),S||(P++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${P*2}s)`,elapsed:P*2}});if(M)throw M;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(x)}`)),m.info("✅ Structured output successful"))}catch(S){m.warn(`⚠️ Structured output failed: ${S}`),yield{event:"on_structured_output_error",data:{error:S instanceof Error?S.message:String(S)}}}}else this.memoryEnabled&&C&&this.addToHistory(new N(C));console.log(`
469
+
470
+ `),m.info(`🎉 StreamEvents complete - ${p} events emitted`),g=!0}catch(y){throw m.error(`❌ Error during streamEvents: ${y}`),d&&l&&(m.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),y}finally{const y=Date.now()-f;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const w=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(E=>E.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(E=>E.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,response:`[STREAMED RESPONSE - ${b} chars]`,executionTimeMs:y,errorType:g?null:"streaming_error",conversationHistoryLength:w}),l&&!this.client&&d&&(m.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){m.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),m.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(m.debug(`🔄 Structured output requested, schema: ${JSON.stringify(qn(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=qn(r),{$schema:a,additionalProperties:c,...l}=i;o=JSON.stringify(l,null,2),m.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),m.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){m.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
471
+ Please format the following information according to the EXACT schema specified below.
472
+ You must use the exact field names and types as shown in the schema.
473
+
474
+ Required schema format:
475
+ ${o}
476
+
477
+ Content to extract from:
478
+ ${u}
479
+
480
+ IMPORTANT:
481
+ - Use ONLY the field names specified in the schema
482
+ - Match the data types exactly (string, number, boolean, array, etc.)
483
+ - Include ALL required fields
484
+ - Return valid JSON that matches the schema structure exactly
485
+ - For missing data: use null for nullable fields, omit optional fields entirely
486
+ - Do NOT use empty strings ("") or zero (0) as placeholders for missing data
487
+ `;f>1&&(g+=`
488
+
489
+ PREVIOUS ATTEMPT FAILED with error: ${d}
490
+ Please fix the issues mentioned above and ensure the output matches the schema exactly.
491
+ `);try{m.info(`🔄 Structured output attempt ${f} - using streaming approach`);const p=u.length>300?`${u.slice(0,300)}...`:u;m.info(`🔄 Content being formatted (${u.length} chars): ${p}`),m.info(`🔄 Full format prompt (${g.length} chars):
492
+ ${g}`);const b=await s.stream(g);let C=null,y=0;for await(const w of b){if(y++,m.debug(`Chunk ${y}: ${JSON.stringify(w,null,2)}`),typeof w=="string")try{C=JSON.parse(w)}catch{m.warn(`🔄 Failed to parse string chunk as JSON: ${w}`)}else if(w&&typeof w=="object")C=w;else try{C=JSON.parse(String(w))}catch{m.warn(`🔄 Failed to parse chunk as JSON: ${w}`)}y%10===0&&m.debug(`🔄 Structured output streaming: ${y} chunks`)}if(m.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(C,null,2)}`),!C)throw new Error("No structured result received from stream");const _=this._validateStructuredResult(C,r);return m.info(`✅ Structured output successful on attempt ${f}`),_}catch(p){if(d=p instanceof Error?p.message:String(p),m.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw m.error(`❌ All ${h} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${h} attempts. Last error: ${d}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(e,n){try{const r=n.parse(e),s=n;if(s._def&&s._def.shape)for(const[o,i]of Object.entries(s._def.shape)){const a=i,c=a.isOptional?.()??a._def?.typeName==="ZodOptional",l=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!c&&!l){const u=r[o];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${o}' is missing or empty`)}}return r}catch(r){throw m.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=qn(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
493
+ ${e}
494
+
495
+ IMPORTANT: Your response must include sufficient information to populate the following structured output:
496
+
497
+ ${a}
498
+
499
+ Make sure you gather ALL the required information during your task execution.
500
+ If any required information is missing, continue working to find it.
501
+ `}catch(r){return m.warn(`Could not extract schema details: ${r}`),e}}},A(Gt,"MCPAgent"),Gt),X={},xy=X.MCP_USE_LANGFUSE?.toLowerCase()==="false",Nn={handler:null,client:null,initPromise:null};async function Al(t,e,n,r){try{const s=await Jt(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){m.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,g,p,b){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=b,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,b,C,y,_){m.debug("Langfuse: Chain start intercepted");const w=this.getCustomTags(),E=this.getMetadata(),T=[...b||[],...w],v={...C||{},...E};return this.verbose&&(m.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(T)}`),m.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(v)}`)),super.handleChainStart(d,f,g,p,T,v,y,_)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const g=this.tagsProvider();g&&g.length>0&&d.push(...g)}return d}getMetadata(){const d={},f=this.getEnvironmentTag();if(f&&(d.env=f),this.agentId&&(d.agent_id=this.agentId),this.metadata&&Object.assign(d,this.metadata),this.metadataProvider){const g=this.metadataProvider();g&&Object.assign(d,g)}return d}getEnvironmentTag(){const d=X.MCP_USE_AGENT_ENV;if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return m.debug("Langfuse: LLM start intercepted"),this.verbose&&m.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return m.debug("Langfuse: Tool start intercepted"),this.verbose&&m.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return m.debug("Langfuse: Retriever start intercepted"),this.verbose&&m.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return m.debug("Langfuse: Agent action intercepted"),this.verbose&&m.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return m.debug("Langfuse: Agent end intercepted"),this.verbose&&m.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};A(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),c=r?r():[],l={publicKey:X.LANGFUSE_PUBLIC_KEY,secretKey:X.LANGFUSE_SECRET_KEY,baseUrl:X.LANGFUSE_HOST||X.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(X.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(X.LANGFUSE_FLUSH_INTERVAL||"10000"),release:X.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(X.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:X.LANGFUSE_ENABLED!=="false",traceName:a.trace_name||X.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:c.length>0?c:void 0,metadata:a||void 0};m.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Nn.handler=new i(l,t,e,n,r),m.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Jt(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Nn.client=new d({publicKey:X.LANGFUSE_PUBLIC_KEY,secretKey:X.LANGFUSE_SECRET_KEY,baseUrl:X.LANGFUSE_HOST||"https://cloud.langfuse.com"}),m.debug("Langfuse client initialized")}}catch(h){m.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){m.debug(`Langfuse initialization error: ${s}`)}}A(Al,"initializeLangfuse");xy?m.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!X.LANGFUSE_PUBLIC_KEY||!X.LANGFUSE_SECRET_KEY?m.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Nn.initPromise=Al();var Uy=A(()=>Nn.handler,"langfuseHandler"),Vy=A(()=>Nn.initPromise,"langfuseInitPromise");const By=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:na,BaseConnector:eo,BrowserOAuthClientProvider:Vl,BrowserTelemetry:_s,HttpConnector:Di,Logger:Bl,MCPAgent:Ty,MCPClient:zl,MCPSession:Fi,ObservabilityManager:Qs,RemoteAgent:Sl,Tel:_s,Telemetry:Wn,VERSION:Hl,createLLMFromString:jo,createReadableStreamFromGenerator:Zi,getPackageVersion:to,getSupportedProviders:Tl,isValidLLMString:El,logger:m,onMcpAuthorization:Wl,parseLLMString:Br,setBrowserTelemetrySource:Do,setTelemetrySource:Do,streamEventsToAISDK:Xi,streamEventsToAISDKWithTools:Qi},Symbol.toStringTag,{value:"Module"}));export{Vy as a,By as b,Al as i,Uy as l};