@mcp-use/inspector 0.13.0-canary.14 → 0.13.0-canary.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{browser-DWTlE230.js → browser-BdgwD-Xy.js} +54 -54
- package/dist/client/assets/{display-A5IEINAP-BqXf1TEf.js → display-A5IEINAP-CfCBjcIF.js} +2 -2
- package/dist/client/assets/{embeddings-T7SMbbwA.js → embeddings-Cakl8vQL.js} +1 -1
- package/dist/client/assets/fs-u42MReIY.js +1 -0
- package/dist/client/assets/{index-D48Cm8M4.js → index-B8CYAksP.js} +1 -1
- package/dist/client/assets/{index-Cyq-cOBe.js → index-BpxjKxoG.js} +1 -1
- package/dist/client/assets/{index-DGiu3fcD.js → index-C7PKszie.js} +1 -1
- package/dist/client/assets/{index-CWSqzUc_.js → index-ChSqK61a.js} +1 -1
- package/dist/client/assets/{index-CQAG94lY.js → index-DD1EEYLj.js} +1 -1
- package/dist/client/assets/{index-BFDHTA3s.js → index-DVjxbcyK.js} +1 -1
- package/dist/client/assets/{index-aOfNG-KD.js → index-D_2-yD7c.js} +1 -1
- package/dist/client/assets/{index-CSfP5GPL.js → index-DeEFVSB3.js} +6 -6
- package/dist/client/assets/{index-JBzxP9jc.js → index-od9OW8CP.js} +1 -1
- package/dist/client/assets/{llms-UpKGGvfL.js → llms-DMFlNZDY.js} +1 -1
- package/dist/client/assets/path-BKBHARRM.js +1 -0
- package/dist/client/assets/{winston-DrYP2ZsM.js → winston-H8_kROqE.js} +2 -2
- package/dist/client/index.html +2 -2
- package/package.json +2 -2
- package/dist/client/assets/langfuse-74RGPTAH-N7gq8lpA.js +0 -1
- package/dist/client/assets/path-DpGL3tFL.js +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/
|
|
2
|
-
import{_ as A,c as
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-CfCBjcIF.js","assets/index-DeEFVSB3.js","assets/index-DQ7i0BFM.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as A,g as Ml,c as Al,J as Pl,E as Ol,F as $i,T as Nl,G as m,M as Il,H as $l,I as Ri,a as Jt,K as Rl,L as Io,N as jl,o as we,s as Or,O as Ee,Z as Ur,j as Vr,e as Ll,n as Fl,d as Dl,P as Ul,Q as Vl,S as Bl,p as ji,U as Br,V as $o,k as Hn}from"./index-DeEFVSB3.js";import{W as Jy,X as Yy,Y as Xy,a0 as Zy,a1 as Qy,a2 as ew,a2 as tw}from"./index-DeEFVSB3.js";import{a as zr,r as zl}from"./fs-u42MReIY.js";import{a as Hl}from"./path-MNZaYwxc.js";import{r as Li,a as Fi}from"./path-BKBHARRM.js";import{D as Wn,S as Nr,t as Wl,a as Di,T as ql,b as Kl}from"./index-BpxjKxoG.js";import{h as Nn,s as Gl,k as Jl,I as Yl,C as Xl,g as Ui,d as Zl,l as Ql,m as eu,t as tu,n as nu,o as ru,p as su,q as ou,r as iu,u as au,v as cu,w as lu,x as uu,y as hu,R as du,z as fu,e as pu}from"./index-od9OW8CP.js";import{aT as mu,aU as Xs,aV as gu,aw as Oe,e as dn,aW as yu,aX as _n,a4 as fe,y as xe,aY as Vi,i as wu,aZ as vs,g as J,aj as an,ah as pe,B as N,S as Q,p as vu,C as _u,a_ as bu,aE as Bi,a$ as be,al as bn,b0 as gn,F as zi,z as je,b1 as Zs,u as Ro,D as _s,E as Yt,ap as Xt,b2 as Su,b3 as Cu,b4 as Eu,b5 as Tu,b6 as xu,b7 as ku,b8 as Mu,b9 as Au,ba as Pu,bb as Ou,bc as Nu,bd as Iu,be as $u,bf as Ru,bg as ju,bh as Lu,bi as Fu,L as Du,bj as Uu,bk as Vu,bl as Bu,A as Ve,k as yn,m as De,M as rt,at as Zt,bm as zu,H as Hu,aF as jo,au as Wu,bn as Lo,bo as Fo,af as Qs,ae as Do,ad as bs,ag as qu,V as Ku,a9 as eo,ac as Xe,bp as hr,o as z,bq as ce,br as Gu,bs as Ie,bt as xt,bu as Ju,bv as to,f as U,aa as Yu,r as Xu,T as Zu,bw as dr,bx as He,by as V,bz as Hi,s as ne,ab as Qu,bA as qn,bB as Wi,bC as Qt,bD as Sn,bE as fr,bF as pr,bG as eh,aP as th,aN as nh,aM as rh,bH as sh}from"./index-DD1EEYLj.js";import{E as qi,c as oh,e as ih}from"./embeddings-Cakl8vQL.js";import{L as Ki,o as ah,l as ch}from"./llms-DMFlNZDY.js";import"./index-DRz5BQNA.js";var Hr,Ln,Wr=0,qr=0;function lh(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=Hr),i==null&&(i=Ln)),o==null||i==null){var a=t.random||(t.rng||mu)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Hr&&!t._v6&&(o[0]|=1,Hr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Ln===void 0&&!t._v6&&(Ln=i))}var c=t.msecs!==void 0?t.msecs:Date.now(),l=t.nsecs!==void 0?t.nsecs:qr+1,u=c-Wr+(l-qr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||c>Wr)&&t.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Wr=c,qr=l,Ln=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||Xs(s)}function uh(t){var e=typeof t=="string"?gu(t):t,n=hh(e);return typeof t=="string"?Xs(n):n}function hh(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 Uo(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 Vo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Uo(Object(n),!0).forEach(function(r){dh(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Uo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function dh(t,e,n){return(e=fh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function fh(t){var e=ph(t,"string");return typeof e=="symbol"?e:e+""}function ph(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 mh(t={},e,n=0){var r=lh(Vo(Vo({},t),{},{_v6:!0}),new Uint8Array(16));return r=uh(r),Xs(r)}async function*gh(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(gh,"streamEventsToAISDK");function yh(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(yh,"createReadableStreamFromGenerator");async function*wh(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
3
|
🔧 Using tool: ${e.name}
|
|
4
4
|
`;break;case"on_tool_end":yield`
|
|
5
5
|
✅ Tool completed: ${e.name}
|
|
6
|
-
`;break}}A(
|
|
7
|
-
`);if(e===-1)return null;const n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
8
|
-
`}const
|
|
6
|
+
`;break}}A(wh,"streamEventsToAISDKWithTools");const vh={},_h="browser",bh="v18.0.0",Sh={node:"18.0.0"},Ch=()=>"/",Eh=(t,...e)=>queueMicrotask(()=>t(...e)),Th=!0,mr={env:vh,platform:_h,version:bh,versions:Sh,cwd:Ch,nextTick:Eh,browser:Th};var ot={exports:{}};function Gi(){throw new Error("child_process.spawn is not available in browser environment")}function Ji(){throw new Error("child_process.exec is not available in browser environment")}function Yi(){throw new Error("child_process.execFile is not available in browser environment")}function Xi(){throw new Error("child_process.fork is not available in browser environment")}function Zi(){throw new Error("child_process.execSync is not available in browser environment")}function Qi(){throw new Error("child_process.spawnSync is not available in browser environment")}function ea(){throw new Error("child_process.execFileSync is not available in browser environment")}const xh={spawn:Gi,exec:Ji,execFile:Yi,fork:Xi,execSync:Zi,spawnSync:Qi,execFileSync:ea},kh=Object.freeze(Object.defineProperty({__proto__:null,default:xh,exec:Ji,execFile:Yi,execFileSync:ea,execSync:Zi,fork:Xi,spawn:Gi,spawnSync:Qi},Symbol.toStringTag,{value:"Module"})),Mh=Ml(kh);var Kr,Bo;function Ah(){if(Bo)return Kr;Bo=1;var t={};Kr=s,s.sync=o;var e=Li;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 Kr}var Gr,zo;function Ph(){if(zo)return Gr;zo=1,Gr=e,e.sync=n;var t=Li;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 Gr}var Jr,Ho;function Oh(){if(Ho)return Jr;Ho=1;var t;globalThis.TESTING_WINDOWS?t=Ah():t=Ph(),Jr=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 Jr}var Yr,Wo;function Nh(){if(Wo)return Yr;Wo=1;var t={};const e=t.OSTYPE==="cygwin"||t.OSTYPE==="msys",n=Fi,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 Yr=a,a.sync=c,Yr}var Fn={exports:{}},qo;function Ih(){if(qo)return Fn.exports;qo=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 Fn.exports=e,Fn.exports.default=e,Fn.exports}var Xr,Ko;function $h(){if(Ko)return Xr;Ko=1;var t={};const e=Fi,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 Xr=o,Xr}var Zr,Go;function Rh(){if(Go)return Zr;Go=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 Zr=e,Zr}var Qr,Jo;function jh(){if(Jo)return Qr;Jo=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 Qr={hookChildProcess:e,verifyENOENT:n,verifyENOENTSync:r,notFoundError:t},Qr}var Yo;function Lh(){if(Yo)return ot.exports;Yo=1;const t=Mh,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 ot.exports=r,ot.exports.spawn=r,ot.exports.sync=s,ot.exports._parse=e,ot.exports._enoent=n,ot.exports}var Fh=Lh();const Dh=Al(Fh);class Uh{constructor(){console.warn("PassThrough stream is not available in browser environment")}}class Vh{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),Bh(n)}clear(){this._buffer=void 0}}function Bh(t){return Pl.parse(JSON.parse(t))}function zh(t){return JSON.stringify(t)+`
|
|
8
|
+
`}const Hh=["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Wh(){const t={};for(const e of Hh){const n=mr.env[e];n!==void 0&&(n.startsWith("()")||(t[e]=n))}return t}class qh{constructor(e){this._readBuffer=new Vh,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Uh)}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:{...Wh(),...this._serverParams.env},stdio:["pipe","pipe",(s=this._serverParams.stderr)!==null&&s!==void 0?s:"inherit"],shell:!1,windowsHide:mr.platform==="win32",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=zh(e);this._process.stdin.write(s)?n():this._process.stdin.once("drain",n)})}}var Kh={},Pt,no=(Pt=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(Pt,"BaseCodeExecutor"),Pt),Ot,Xo=(Ot=class extends no{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
9
|
// MCP Bridge Shim
|
|
10
10
|
global.__callMcpTool = async (server, tool, args) => {
|
|
11
11
|
const id = Math.random().toString(36).substring(7);
|
|
@@ -86,7 +86,7 @@ ${this.generateShim(c)}
|
|
|
86
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
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
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(Ot,"E2BCodeExecutor"),Ot),Ze=null,
|
|
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(Ot,"E2BCodeExecutor"),Ot),Ze=null,Ss=!1;function ro(){return["node","vm"].join(":")}A(ro,"getVMModuleName");function Ir(){if(Ss)return Ze!==null;Ss=!0;try{const t=typeof Io<"u"?Io:null;if(t)return Ze=t(ro()),!0}catch{m.debug("node:vm module not available via require")}return!1}A(Ir,"tryLoadVM");async function ta(){if(Ze!==null||!Ss&&Ir())return!0;try{return Ze=await import(ro()),!0}catch{return m.debug("node:vm module not available in this environment (e.g., Deno)"),!1}}A(ta,"tryLoadVMAsync");function Gh(){return Ir(),Ze!==null}A(Gh,"isVMAvailable");var Nt,Zo=(Nt=class extends no{defaultTimeout;memoryLimitMb;constructor(e,n){super(e),this.defaultTimeout=n?.timeoutMs??3e4,this.memoryLimitMb=n?.memoryLimitMb,Ir()}async ensureVMLoaded(){if(Ze!==null)return;if(!await ta())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
90
|
(async () => {
|
|
91
91
|
try {
|
|
92
92
|
${e}
|
|
@@ -94,46 +94,46 @@ ${this.generateShim(c)}
|
|
|
94
94
|
throw e;
|
|
95
95
|
}
|
|
96
96
|
})()
|
|
97
|
-
`;i=await new Ze.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),Ze.createContext(r)}async cleanup(){}},A(Nt,"VMCodeExecutor"),Nt),It,Jh=(It=class extends to{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(It,"CodeModeConnector"),It),$t,Yh=($t=class extends Rl{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,Xh=(Rt=class extends to{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 Yh(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 $l(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=Kl(t,"utf-8");return JSON.parse(e)}A(Ts,"loadConfigFile");function ta(t,e){if("command"in t&&"args"in t)return new Xh({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 nt,Zh=(nt=class extends Il{static getPackageVersion(){return eo()}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 nt(e,n)}static fromConfigFile(e,n){return new nt(Ts(e),n)}saveConfig(e){const n=Gl.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 Jh(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(nt,"MCPClient"),nt),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,Qh=(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 jl();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Ll();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=Fl(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(Dl()):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 Qh.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=
|
|
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),
|
|
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
|
|
102
|
-
- ${n}`).join("")}.`),this.toolName=t,this.errors=e}},
|
|
103
|
-
Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function
|
|
104
|
-
All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof qe||t instanceof lt)return[t];const r=ha(n);if(fe(t))return r?[lt.fromSchema(t)]:[qe.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[lt.fromSchema(t)]:[qe.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function sd(t,e){return ua(t,e)}function od(t){return lt.fromSchema(t)}const id=["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"||id.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 Je(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Lr(t){return typeof t=="function"?t:t.hook}function ad(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 bh({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 cd="__error__",Yn="__scheduled__",ld="__interrupt__",ud="__resume__";var ii="[...]",hd="[Circular]",wr=[],Ct=[];function dd(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function fd(t,e,n,r){typeof r>"u"&&(r=dd()),Ps(t,"",0,[],void 0,0,r);var s;try{Ct.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,pd(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(hd,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 pd(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 md=[];var gd={},fa={};J(fa,{BaseChatMessageHistory:()=>pa,BaseListChatMessageHistory:()=>fo,InMemoryChatMessageHistory:()=>yd});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.")}},yd=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=[]}},wd={},ma={};J(ma,{BaseMemory:()=>vd,getInputValue:()=>_d,getOutputValue:()=>bd,getPromptInputKey:()=>Sd});var vd=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]]},_d=(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},bd=(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 Sd(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(Tu(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:()=>Cd,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})}}},Cd=class extends mo{static load(t,e){throw new Error("Not implemented")}},Sa={};J(Sa,{BaseDocumentLoader:()=>Ca});var Ca=class{},Ea={};J(Ea,{LangSmithLoader:()=>Ed});var Ed=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 xu(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Td,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 Td(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var Be=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)}},kd=class extends Ta{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},ka={};J(ka,{BaseDocumentTransformer:()=>Ta,Document:()=>Be,MappingDocumentTransformer:()=>kd});var go=class extends an{lc_namespace=["langchain_core","example_selectors","base"]},xa=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},xd=class extends xa{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 Md(t){return t._modelType()==="base_llm"}function Ad(t){return t._modelType()==="base_chat_model"}function ai(t){return t.split(/\n| /).length}var Pd=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 Od=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 Be({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:()=>xa,ConditionalPromptSelector:()=>xd,LengthBasedExampleSelector:()=>Pd,SemanticSimilarityExampleSelector:()=>Od,isChatModel:()=>Ad,isLLM:()=>Md});const Os="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Nd=class extends an{lc_namespace=["langchain","recordmanagers"]},Oa=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=eu;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 Be({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 Id(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=[],k=new Set;if(_.forEach((M,P)=>{if(E[P])if(l)k.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-k.size,p+=k.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:()=>Nd,UUIDV5_NAMESPACE:()=>Os,_HashedDocument:()=>Oa,_batch:()=>Na,_deduplicateInOrder:()=>Ia,_getSourceIdAssigner:()=>$a,_isBaseDocumentLoader:()=>Ra,index:()=>Id});var $d={},La={};J(La,{BaseDocumentCompressor:()=>Rd});var Rd=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}},$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 tu(e)}};var jd=Object.prototype.toString,ln=Array.isArray||function(e){return jd.call(e)==="[object Array]"};function yo(t){return typeof t=="function"}function Ld(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 Fd(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Dd=RegExp.prototype.test;function Ud(t,e){return Dd.call(t,e)}var Vd=/\S/;function Bd(t){return!Ud(Vd,t)}var zd={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function Hd(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return zd[n]})}var Wd=/\s*/,qd=/\s+/,li=/\s*=/,Kd=/\s*\}/,Gd=/#|\^|\/|>|\{|&|=|!/;function Jd(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(qd,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),Bd(_)?(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(
|
|
97
|
+
`;i=await new Ze.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),Ze.createContext(r)}async cleanup(){}},A(Nt,"VMCodeExecutor"),Nt),It,Jh=(It=class extends Ri{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(It,"CodeModeConnector"),It),$t,Yh=($t=class extends jl{serverParams;errlog;_transport=null;constructor(e,n=process.stderr){super(),this.serverParams=e,this.errlog=n}async establishConnection(){return this._transport=new qh(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,Xh=(Rt=class extends Ri{command;args;env;errlog;clientInfo;constructor({command:e="npx",args:n=[],env:r,errlog:s=mr.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(mr.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 Yh(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 Rl(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 Cs(t){const e=zl();return JSON.parse(e)}A(Cs,"loadConfigFile");function na(t,e){if("command"in t&&"args"in t)return new Xh({command:t.command,args:t.args,env:t.env,...e});if("url"in t){const n=t.transport||"http";return new $l(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(na,"createConnectorFromConfig");var nt,Zh=(nt=class extends Ol{static getPackageVersion(){return $i()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig="vm";_executorOptions;_samplingCallback;_elicitationCallback;constructor(e,n){e?typeof e=="string"?super(Cs()):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;Nl.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 nt(e,n)}static fromConfigFile(e,n){return new nt(Cs(),n)}saveConfig(e){const n=Hl.dirname(e);zr.existsSync(n)||zr.mkdirSync(n,{recursive:!0}),zr.writeFileSync(e,JSON.stringify(this.config,null,2),"utf-8")}createConnectorFromConfig(e){return na(e,{samplingCallback:this._samplingCallback,elicitationCallback:this._elicitationCallback})}_setupCodeModeConnector(){m.debug("Code mode connector initialized as internal meta server");const e=new Jh(this),n=new Il(e);this.sessions.code_mode=n,this.activeSessions.push("code_mode")}_ensureCodeExecutor(){if(!this._codeExecutor){const e=this._codeExecutorConfig;if(e instanceof no)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 Xo(this,n);else{m.warn("E2B executor requires apiKey. Falling back to VM.");try{this._codeExecutor=new Zo(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 Zo(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 Xo(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(nt,"MCPClient"),nt),jt,Qh=(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,ed=(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:Ur.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Ur.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:Ur.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 Vr(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 Ll();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Fl();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=Or();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 Vr(o)}const n=e.items?this.parseSchema(e.items):Ee(),r=Dl(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(Ul()):n.push(this.parseSchema(r));return n.length>=2?Vr(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 ed.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 Qh{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 Wn({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 Wn({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=Or();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?we(o):we({}).optional()}return new Wn({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),td=Object.defineProperty,sa=(t,e)=>{for(var n in e)td(t,n,{get:e[n],enumerable:!0})},nd={};sa(nd,{ConfigurableModel:()=>Es,MODEL_PROVIDER_CONFIG:()=>$r,_inferModelProvider:()=>aa,getChatModelByClassName:()=>ia,initChatModel:()=>cn});const $r={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($r);async function ia(t){const e=Object.entries($r).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 rd(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=$r[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 Es=class Kn extends Nn{_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 rd(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 Kn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new Kn({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 Kn({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new Oe({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 yu({generator:await r.stream(e,n),config:n});return await s.setup,_n.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 _n.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 Es({defaultConfig:{...a,model:t,modelProvider:s},configPrefix:r}):(t&&(a.model=t),s&&(a.modelProvider=s),new Es({defaultConfig:a,configPrefix:r,configurableFields:i}))}var Ts=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.")}},xs=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}},so=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 oo(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function gr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}let sd=0;var qe=class ks{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-${++sd}`}if(wu(e)){const a=xe(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 ks(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=xe(e),i={type:"function",function:s};return new ks(o,i,n)}parse(e){const r=new Vi(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=xe(e);return new la(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new Vi(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 qe||s instanceof lt))return t;if(t.every(s=>fe(s)))return t.map(s=>qe.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!fe(s)))return t.map(s=>qe.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 qe||t instanceof lt)return[t];const r=ha(n);if(fe(t))return r?[lt.fromSchema(t)]:[qe.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[lt.fromSchema(t)]:[qe.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function od(t,e){return ua(t,e)}function id(t){return lt.fromSchema(t)}const ad=["ChatOpenAI","ChatXAI"],Qo=["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 Qo.some(r=>n.includes(r))}if(gr(t))return ha(t._defaultConfig.model);if(!oo(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||ad.includes(e)&&("model"in t&&Qo.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function io(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 Je(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Rr(t){return typeof t=="function"?t:t.hook}function cd(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 mh({clockseq:t})}function St(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return vs(t,new Uint8Array(n))}const ld="__error__",Gn="__scheduled__",ud="__interrupt__",hd="__resume__";var ei="[...]",dd="[Circular]",yr=[],Ct=[];function fd(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function pd(t,e,n,r){typeof r>"u"&&(r=fd()),Ms(t,"",0,[],void 0,0,r);var s;try{Ct.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,md(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;yr.length!==0;){var o=yr.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function es(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),yr.push([r,n,e,s])):Ct.push([e,n,t]):(r[n]=t,yr.push([r,n,e]))}function Ms(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){es(dd,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){es(ei,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){es(ei,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)Ms(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];Ms(t[l],l,a,r,t,o,i)}}r.pop()}}function md(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 gd=[];var yd={},fa={};J(fa,{BaseChatMessageHistory:()=>pa,BaseListChatMessageHistory:()=>ao,InMemoryChatMessageHistory:()=>wd});var pa=class extends an{async addMessages(t){for(const e of t)await this.addMessage(e)}},ao=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.")}},wd=class extends ao{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=[]}},vd={},ma={};J(ma,{BaseMemory:()=>_d,getInputValue:()=>bd,getOutputValue:()=>Sd,getPromptInputKey:()=>Cd});var _d=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]]},bd=(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},Sd=(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 Cd(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:()=>co});var co=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(vu(e)),s=await(await _u.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:()=>Ed,VectorStore:()=>lo,VectorStoreRetriever:()=>Jn});var Jn=class extends co{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)}},lo=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 Jn({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 Jn({...i,searchKwargs:t.searchKwargs}):new Jn({...i})}}},Ed=class extends lo{static load(t,e){throw new Error("Not implemented")}},Sa={};J(Sa,{BaseDocumentLoader:()=>Ca});var Ca=class{},Ea={};J(Ea,{LangSmithLoader:()=>Td});var Td=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 bu(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??xd,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 xd(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var Be=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)}},kd=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:()=>Be,MappingDocumentTransformer:()=>kd});var uo=class extends an{lc_namespace=["langchain_core","example_selectors","base"]},ka=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Md=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 Ad(t){return t._modelType()==="base_llm"}function Pd(t){return t._modelType()==="base_chat_model"}function ti(t){return t.split(/\n| /).length}var Od=class Ma extends uo{examples=[];examplePrompt;getTextLength=ti;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??ti}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 ts(t){return Object.keys(t).sort().map(e=>t[e])}var Nd=class Aa extends uo{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=ts(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Be({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=ts(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=>ts(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:()=>uo,BasePromptSelector:()=>ka,ConditionalPromptSelector:()=>Md,LengthBasedExampleSelector:()=>Od,SemanticSimilarityExampleSelector:()=>Nd,isChatModel:()=>Pd,isLLM:()=>Ad});const As="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Id=class extends an{lc_namespace=["langchain","recordmanagers"]},Oa=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Gl;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 Be({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 vs(e,As)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return vs(n,As)}};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 $d(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:()=>Id,UUIDV5_NAMESPACE:()=>As,_HashedDocument:()=>Oa,_batch:()=>Na,_deduplicateInOrder:()=>Ia,_getSourceIdAssigner:()=>$a,_isBaseDocumentLoader:()=>Ra,index:()=>$d});var Rd={},La={};J(La,{BaseDocumentCompressor:()=>jd});var jd=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}},In=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"})}},Cn=class extends In{async formatPromptValue(t){const e=await this.format(t);return new Jl(e)}};var Ld=Object.prototype.toString,ln=Array.isArray||function(e){return Ld.call(e)==="[object Array]"};function ho(t){return typeof t=="function"}function Fd(t){return ln(t)?"array":typeof t}function ns(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function ni(t,e){return t!=null&&typeof t=="object"&&e in t}function Dd(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Ud=RegExp.prototype.test;function Vd(t,e){return Ud.call(t,e)}var Bd=/\S/;function zd(t){return!Vd(Bd,t)}var Hd={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function Wd(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Hd[n]})}var qd=/\s*/,Kd=/\s+/,ri=/\s*=/,Gd=/\s*\}/,Jd=/#|\^|\/|>|\{|&|=|!/;function Yd(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(Kd,2)),!ln(S)||S.length!==2)throw new Error("Invalid tags: "+S);h=new RegExp(ns(S[0])+"\\s*"),d=new RegExp("\\s*"+ns(S[1])),f=new RegExp("\\s*"+ns("}"+S[1]))}g(e||ue.tags);for(var p=new $n(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),zd(_)?(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(Jd)||"name",p.scan(qd),C==="="?(y=p.scanUntil(ri),p.scan(ri),p.scanUntil(d)):C==="{"?(y=p.scanUntil(f),p.scan(Gd),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 Zd(Xd(s))}function Xd(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 Zd(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 $n(t){this.string=t,this.tail=t,this.pos=0}$n.prototype.eos=function(){return this.tail===""};$n.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};$n.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=ni(o,i[a])||Dd(o,i[a])),o=o[i[a++]];else o=s.view[e],c=ni(s.view,e);if(c){r=o;break}s=s.parent}n[e]=r}return ho(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=Yd(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(ho(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
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=
|
|
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")
|
|
107
|
+
`)};ie.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=ho(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){En.templateCache=t},get templateCache(){return En.templateCache}},En=new ie;ue.clearCache=function(){return En.clearCache()};ue.parse=function(e,n){return En.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 "'+Fd(e)+'" was given as the first argument for mustache#render(template, view, partials)');return En.render(e,n,r,s)};ue.escape=Wd;ue.Scanner=$n;ue.Context=en;ue.Writer=ie;function Fa(){ue.escape=t=>t}const Tn=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},Da=(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=Da(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},wr=t=>{Fa();const e=ue.parse(t);return Da(e)},Ua=(t,e)=>Tn(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},""),Va=(t,e)=>(Fa(),ue.render(t,e)),vr={"f-string":Ua,mustache:Va},Ba={"f-string":Tn,mustache:wr},ke=(t,e,n)=>{try{return vr[e](t,n)}catch(r){throw Bi(r,"INVALID_PROMPT_INPUT")}},_r=(t,e)=>Ba[e](t),Rn=(t,e,n)=>{if(!(e in vr)){const r=Object.keys(vr);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")ke(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")ke(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;ke(o,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):ke(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Qe=class fn extends Cn{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))),Rn(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return ke(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
|
|
109
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
|
|
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 _r(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})}},Yn=class za extends In{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))),Rn([{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 za(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=ke(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 Yl(n)}},Ps=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=Os(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return Ns(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function Os(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")_r(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?_r(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...Os(s,e));else typeof r=="object"&&r!==null&&n.push(...Os(r,e));return Array.from(new Set(n))}function Ns(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=ke(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(ke(a,n,e)):typeof a=="object"&&i.push(Ns(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=Ns(o,e,n):r[s]=o;return r}var jr=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"})}},Is=class extends jr{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(bn):n=[bn(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
111
|
|
|
112
|
-
`));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},Ha=class extends
|
|
112
|
+
`));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},Ha=class extends jr{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)]}},fo=class extends In{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Xl(e)}},Wa=class extends Ha{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 zi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Qe.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function Qd(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function ef(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 po=class extends jr{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(Qe.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(Qe.fromTemplate(r,e));else if(r!==null)if(Qd(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(Qe.fromTemplate(s,o))}else if(ef(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=wr(s):a=Tn(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
113
|
Got: ${c}
|
|
114
|
-
From: ${s}`);i=[c[0]]}else i=[];s={url:s},o=new
|
|
114
|
+
From: ${s}`);i=[c[0]]}else i=[];s={url:s},o=new Yn({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=wr(s.url):a=Tn(s.url),i=a.flatMap(c=>c.type==="variable"?[c.name]:[])}else i=[];o=new Yn({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 Ps({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof Cn){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 Cn){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 Yn){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 Ps){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)]}},mo=class extends po{static _messageClass(){return pe}static lc_name(){return"HumanMessagePromptTemplate"}},qa=class extends po{static _messageClass(){return N}static lc_name(){return"AIMessagePromptTemplate"}},Ka=class extends po{static _messageClass(){return be}static lc_name(){return"SystemMessagePromptTemplate"}};function tf(t){return typeof t.formatMessages=="function"}function nf(t,e){if(tf(t)||je(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 Is({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new Is({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=bn(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 mo.fromTemplate(r,e);if(n._getType()==="ai")return qa.fromTemplate(r,e);if(n._getType()==="system")return Ka.fromTemplate(r,e);if(zi.isInstance(n))return Wa.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function rf(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var go=class Xn extends fo{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 gn))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 Qe.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 gn)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)&&!(rf(s)&&s.optional))throw Bi(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 Xn(s)}static fromTemplate(e,n){const r=Qe.fromTemplate(e,n),s=new mo({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof Xn?a.promptMessages:[nf(a,n)]),[]),s=e.reduce((i,a)=>a instanceof Xn?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof gn))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})}},sf=class $s extends Cn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
115
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))),
|
|
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))),Rn(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 $s(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 ke(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 Qe.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 $s({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},of=class Ga extends fo{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
117
117
|
|
|
118
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
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 Ga(s)}},of=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 af(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 cf=class Ja 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(af(e)&&ui(e.bound))return super.pipe(new Oe({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 Ja.fromMessages(e,{schema:n,method:r})}},Ya={};J(Ya,{AIMessagePromptTemplate:()=>qa,BaseChatPromptTemplate:()=>wo,BaseMessagePromptTemplate:()=>Fr,BaseMessageStringPromptTemplate:()=>Ha,BasePromptTemplate:()=>$n,BaseStringPromptTemplate:()=>En,ChatMessagePromptTemplate:()=>Wa,ChatPromptTemplate:()=>bo,DEFAULT_FORMATTER_MAPPING:()=>_r,DEFAULT_PARSER_MAPPING:()=>Ba,DictPromptTemplate:()=>Ns,FewShotChatMessagePromptTemplate:()=>sf,FewShotPromptTemplate:()=>rf,HumanMessagePromptTemplate:()=>_o,ImagePromptTemplate:()=>Zn,MessagesPlaceholder:()=>Rs,PipelinePromptTemplate:()=>of,PromptTemplate:()=>Qe,StructuredPrompt:()=>cf,SystemMessagePromptTemplate:()=>Ka,checkValidTemplate:()=>jn,interpolateFString:()=>Ua,interpolateMustache:()=>Va,parseFString:()=>kn,parseMustache:()=>vr,parseTemplate:()=>br,renderTemplate:()=>xe});var lf={},Xa={};J(Xa,{RunCollectorCallbackHandler:()=>uf});var uf=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)}},Za=class extends zi{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)}`)}},Qa=class extends su{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 Za(t)}_diff(t,e){return e?ou(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""}},hf=class extends zi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Qa;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]}},ec={};J(ec,{JsonKeyOutputFunctionsParser:()=>hf,JsonOutputFunctionsParser:()=>Qa,OutputFunctionsParser:()=>Za});const Ye={and:"and",or:"or",not:"not"},R={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var tc=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{},df=class extends Co{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},ff=class extends Co{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},pf=class extends So{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function nc(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Te(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:nc(t)&&Object.keys(t).length===0:!0}function rc(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 sc(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 oc(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function ic(t){return typeof t=="boolean"}function Eo(t){let e;if(oc(t))e=t;else if(rc(t))e=parseInt(t,10);else if(sc(t))e=parseFloat(t);else if(ic(t))e=!!t;else throw new Error("Unsupported value type");return e}var To=class extends tc{},mf=class extends To{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Ye.and,Ye.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 Ye){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")}}},gf=class extends To{allowedOperators=[Ye.and,Ye.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 Ye.and:return(e,n)=>e&&n;case Ye.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")}}},ac={};J(ac,{BaseTranslator:()=>To,BasicTranslator:()=>mf,Comparators:()=>R,Comparison:()=>df,Expression:()=>So,FilterDirective:()=>Co,FunctionalTranslator:()=>gf,Operation:()=>ff,Operators:()=>Ye,StructuredQuery:()=>pf,Visitor:()=>tc,castValue:()=>Eo,isBoolean:()=>ic,isFilterEmpty:()=>Te,isFloat:()=>sc,isInt:()=>rc,isObject:()=>nc,isString:()=>oc});var yf=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(`
|
|
121
|
-
`);return await n?.handleLLMNewToken(r),{generations:[{message:new N(r),text:r}],llmOutput:{}}}},wf=class cc 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:ke(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:ke(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:ke(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:ke(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new cc({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})}}},vf=class lc extends In{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(e){super(e);const{responses:n,sleep:r,emitCustomEvent:s,generationInfo:o}=e;this.responses=n,this.sleep=r,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=o}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,n,r){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{const s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(e){return{message:new N(e),text:e}}async*_streamResponseChunks(e,n,r){const s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});const o=[...s];for(let i=0;i<o.length;i++){const a=o[i],c=i===o.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);yield this._createResponseChunk(a,c?this.generationInfo:void 0),r?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,n){return new Ss({message:new Yt({content:e}),text:e,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}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:ke(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:ke(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:ke(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:ke(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new lc({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return o.tools=n,o.toolStyle=this.toolStyle,o.i=this.i,o.withConfig({tools:s})}withStructuredOutput(e,n){return Xt.from(async r=>{const s=await this.invoke(r);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}},_f=class extends Ji{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})}},bf=class extends Ji{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},Sf=class extends Yi{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}},Cf=class extends Yi{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)}},Ef=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=[]}},Tf=class extends fo{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},kf=class extends ro{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},xf=class extends iu{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Mf=class extends po{lc_namespace=["test","fake"];output=[new Be({pageContent:"foo"}),new Be({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Af=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}}},Pf=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)}},Of=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}};function uc(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))}var Nf=class hc extends mo{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??uc}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 Be({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 Be({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 Be({pageContent:e[i],metadata:a});o.push(c)}return hc.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)}},dc={};J(dc,{FakeChatMessageHistory:()=>Ef,FakeChatModel:()=>yf,FakeEmbeddings:()=>bf,FakeLLM:()=>Sf,FakeListChatMessageHistory:()=>Tf,FakeListChatModel:()=>vf,FakeRetriever:()=>Mf,FakeRunnable:()=>Af,FakeSplitIntoListParser:()=>xf,FakeStreamingChatModel:()=>wf,FakeStreamingLLM:()=>Cf,FakeTool:()=>Pf,FakeTracer:()=>kf,FakeVectorStore:()=>Nf,SingleRunExtractor:()=>Of,SyntheticEmbeddings:()=>_f});var fc={};J(fc,{EventStreamContentType:()=>If,convertEventStreamToIterableReadableDataStream:()=>Rf,getBytes:()=>pc,getLines:()=>mc,getMessages:()=>gc});const If="text/event-stream";async function pc(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(`
|
|
122
|
-
`))}}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 mc(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
|
|
123
|
-
`+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 $f(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 Rf(t,e){const n=new ReadableStream({async start(r){const s=gc(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 pc(t,mc((i,a,c)=>{s(i,a,c),c&&r.close()}))}});return bn.fromReadableStream(n)}function jf(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Lf={};function Ff(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function Df(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 Uf(t,e){return Math.sqrt(Df(t,e))}var yc={};J(yc,{cosineSimilarity:()=>Ls,euclideanDistance:()=>zf,innerProduct:()=>Bf,matrixFunc:()=>Dr,maximalMarginalRelevance:()=>Hf,normalize:()=>Vf});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 Vf(t,e=!1){const n=Wf(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Ls(t,e){return Dr(t,e,uc)}function Bf(t,e){return Dr(t,e,Ff)}function zf(t,e){return Dr(t,e,Uf)}function Hf(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=wc(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 wc(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 Wf(t){return t.reduce((e,n)=>Math.max(e,wc(n).maxValue),0)}var vc={};J(vc,{agents:()=>gd,caches:()=>yu,callbacks__base:()=>Hu,callbacks__manager:()=>zu,callbacks__promises:()=>Bu,chat_history:()=>fa,document_loaders__base:()=>Sa,document_loaders__langsmith:()=>Ea,documents:()=>ka,embeddings:()=>dh,example_selectors:()=>Pa,index:()=>wd,indexing:()=>ja,language_models__base:()=>gu,language_models__chat_models:()=>mu,language_models__llms:()=>ph,language_models__profile:()=>$d,load__serializable:()=>Vu,memory:()=>ma,messages:()=>Uu,messages__tool:()=>Du,output_parsers:()=>pu,output_parsers__openai_functions:()=>ec,output_parsers__openai_tools:()=>fh,outputs:()=>Fu,prompt_values:()=>fu,prompts:()=>Ya,retrievers:()=>_a,retrievers__document_compressors:()=>La,runnables:()=>du,runnables__graph:()=>Lu,singletons:()=>ju,stores:()=>ya,structured_query:()=>ac,tools:()=>Xl,tracers__base:()=>Ru,tracers__console:()=>$u,tracers__log_stream:()=>Iu,tracers__run_collector:()=>Xa,tracers__tracer_langchain:()=>Nu,types__stream:()=>lf,utils__async_caller:()=>Ou,utils__chunk_array:()=>hh,utils__env:()=>Pu,utils__event_source_parse:()=>fc,utils__format:()=>Lf,utils__function_calling:()=>hu,utils__hash:()=>uu,utils__json_patch:()=>lu,utils__json_schema:()=>Au,utils__math:()=>yc,utils__stream:()=>Mu,utils__testing:()=>dc,utils__tiktoken:()=>cu,utils__types:()=>au,vectorstores:()=>ba});function qf(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=Wu(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:vc,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(md.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"&&qu(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(Ku(C,Gu,qf(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 Kf(t,e){const n=JSON.parse(t);return tr.call({...e},n)}function Gf(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(Gf(e))return Kf(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 Jf(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 Yf=class{_dumps(t){return new TextEncoder().encode(fd(t,(n,r)=>Jf(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 _c(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]=_c(t[n]));return e}function bc(){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:_c(t.versions_seen)}}function Sc(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function Xf(...t){return t.reduce((e,n,r)=>r===0?n:Sc(e,n)>=0?e:n)}const Zf={[cd]:-1,[Yn]:-2,[ld]:-3,[ud]:-4};var hn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function Qf(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 ep=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){Qf(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 tp=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var np=class extends ep{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=tp(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]"}}},rp=class{serde=new Yf;constructor(t){this.serde=t||this.serde}},sp=class Cc 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 Cc({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 op{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 ip(){Ve.initializeGlobalInstance(new op)}var gt=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
|
|
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))),Rn(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 ke(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 Ga(s)}},af=class Zn extends In{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=Zn.extractRequiredInputValues(n,s.inputVariables);s instanceof go?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return Zn.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 Zn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function si(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function cf(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 lf=class Ja extends go{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(si(e))return super.pipe(e.withStructuredOutput(this.schema));if(cf(e)&&si(e.bound))return super.pipe(new Oe({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 Ja.fromMessages(e,{schema:n,method:r})}},Ya={};J(Ya,{AIMessagePromptTemplate:()=>qa,BaseChatPromptTemplate:()=>fo,BaseMessagePromptTemplate:()=>jr,BaseMessageStringPromptTemplate:()=>Ha,BasePromptTemplate:()=>In,BaseStringPromptTemplate:()=>Cn,ChatMessagePromptTemplate:()=>Wa,ChatPromptTemplate:()=>go,DEFAULT_FORMATTER_MAPPING:()=>vr,DEFAULT_PARSER_MAPPING:()=>Ba,DictPromptTemplate:()=>Ps,FewShotChatMessagePromptTemplate:()=>of,FewShotPromptTemplate:()=>sf,HumanMessagePromptTemplate:()=>mo,ImagePromptTemplate:()=>Yn,MessagesPlaceholder:()=>Is,PipelinePromptTemplate:()=>af,PromptTemplate:()=>Qe,StructuredPrompt:()=>lf,SystemMessagePromptTemplate:()=>Ka,checkValidTemplate:()=>Rn,interpolateFString:()=>Ua,interpolateMustache:()=>Va,parseFString:()=>Tn,parseMustache:()=>wr,parseTemplate:()=>_r,renderTemplate:()=>ke});var uf={},Xa={};J(Xa,{RunCollectorCallbackHandler:()=>hf});var hf=class extends Zs{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)}},Za=class extends Ui{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)}`)}},Qa=class extends Zl{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 Za(t)}_diff(t,e){return e?Ql(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?Ro(r.arguments):{...r,arguments:Ro(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""}},df=class extends Ui{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Qa;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]}},ec={};J(ec,{JsonKeyOutputFunctionsParser:()=>df,JsonOutputFunctionsParser:()=>Qa,OutputFunctionsParser:()=>Za});const Ye={and:"and",or:"or",not:"not"},R={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var tc=class{},yo=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")}},wo=class extends yo{},ff=class extends wo{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},pf=class extends wo{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},mf=class extends yo{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function nc(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Te(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:nc(t)&&Object.keys(t).length===0:!0}function rc(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 sc(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 oc(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function ic(t){return typeof t=="boolean"}function vo(t){let e;if(oc(t))e=t;else if(rc(t))e=parseInt(t,10);else if(sc(t))e=parseFloat(t);else if(ic(t))e=!!t;else throw new Error("Unsupported value type");return e}var _o=class extends tc{},gf=class extends _o{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Ye.and,Ye.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 Ye){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)]:vo(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")}}},yf=class extends _o{allowedOperators=[Ye.and,Ye.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 Ye.and:return(e,n)=>e&&n;case Ye.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,vo(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")}}},ac={};J(ac,{BaseTranslator:()=>_o,BasicTranslator:()=>gf,Comparators:()=>R,Comparison:()=>ff,Expression:()=>yo,FilterDirective:()=>wo,FunctionalTranslator:()=>yf,Operation:()=>pf,Operators:()=>Ye,StructuredQuery:()=>mf,Visitor:()=>tc,castValue:()=>vo,isBoolean:()=>ic,isFilterEmpty:()=>Te,isFloat:()=>sc,isInt:()=>rc,isObject:()=>nc,isString:()=>oc});var wf=class extends Nn{_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(`
|
|
121
|
+
`);return await n?.handleLLMNewToken(r),{generations:[{message:new N(r),text:r}],llmOutput:{}}}},vf=class cc extends Nn{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:xe(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:xe(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:xe(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:xe(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new cc({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 _s({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 _s({message:new Yt({content:i}),text:i});yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},_f=class lc extends Nn{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(e){super(e);const{responses:n,sleep:r,emitCustomEvent:s,generationInfo:o}=e;this.responses=n,this.sleep=r,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=o}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,n,r){if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);if(this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0}),n?.stop?.length)return{generations:[this._formatGeneration(n.stop[0])]};{const s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(e){return{message:new N(e),text:e}}async*_streamResponseChunks(e,n,r){const s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await r?.handleCustomEvent("some_test_event",{someval:!0});const o=[...s];for(let i=0;i<o.length;i++){const a=o[i],c=i===o.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);yield this._createResponseChunk(a,c?this.generationInfo:void 0),r?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,n){return new _s({message:new Yt({content:e}),text:e,generationInfo:n})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}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:xe(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:xe(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:xe(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:xe(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new lc({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return o.tools=n,o.toolStyle=this.toolStyle,o.i=this.i,o.withConfig({tools:s})}withStructuredOutput(e,n){return Xt.from(async r=>{const s=await this.invoke(r);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}},bf=class extends qi{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})}},Sf=class extends qi{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},Cf=class extends Ki{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}},Ef=class extends Ki{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)}},Tf=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=[]}},xf=class extends ao{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},kf=class extends Zs{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Mf=class extends eu{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Af=class extends co{lc_namespace=["test","fake"];output=[new Be({pageContent:"foo"}),new Be({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Pf=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}}},Of=class extends Nr{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)}},Nf=class extends Zs{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}};function uc(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))}var If=class hc extends lo{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??uc}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 Be({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 Be({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 Be({pageContent:e[i],metadata:a});o.push(c)}return hc.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)}},dc={};J(dc,{FakeChatMessageHistory:()=>Tf,FakeChatModel:()=>wf,FakeEmbeddings:()=>Sf,FakeLLM:()=>Cf,FakeListChatMessageHistory:()=>xf,FakeListChatModel:()=>_f,FakeRetriever:()=>Af,FakeRunnable:()=>Pf,FakeSplitIntoListParser:()=>Mf,FakeStreamingChatModel:()=>vf,FakeStreamingLLM:()=>Ef,FakeTool:()=>Of,FakeTracer:()=>kf,FakeVectorStore:()=>If,SingleRunExtractor:()=>Nf,SyntheticEmbeddings:()=>bf});var fc={};J(fc,{EventStreamContentType:()=>$f,convertEventStreamToIterableReadableDataStream:()=>jf,getBytes:()=>pc,getLines:()=>mc,getMessages:()=>gc});const $f="text/event-stream";async function pc(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(`
|
|
122
|
+
`))}}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 mc(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=Rf(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 gc(t,e,n){let r=rs();const s=new TextDecoder;return function(i,a,c){if(c){Lf(r)||(t?.(r),r=rs());return}if(i.length===0)t?.(r),r=rs();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+`
|
|
123
|
+
`+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 Rf(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function rs(){return{data:"",event:"",id:"",retry:void 0}}function jf(t,e){const n=new ReadableStream({async start(r){const s=gc(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 pc(t,mc((i,a,c)=>{s(i,a,c),c&&r.close()}))}});return _n.fromReadableStream(n)}function Lf(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Ff={};function Df(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function Uf(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 Vf(t,e){return Math.sqrt(Uf(t,e))}var yc={};J(yc,{cosineSimilarity:()=>Rs,euclideanDistance:()=>Hf,innerProduct:()=>zf,matrixFunc:()=>Lr,maximalMarginalRelevance:()=>Wf,normalize:()=>Bf});function Lr(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 Bf(t,e=!1){const n=qf(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Rs(t,e){return Lr(t,e,uc)}function zf(t,e){return Lr(t,e,Df)}function Hf(t,e){return Lr(t,e,Vf)}function Wf(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=Rs(s,e)[0],i=wc(o).maxIndex,a=[e[i]],c=[i];for(;c.length<Math.min(r,e.length);){let l=-1/0,u=-1;const h=Rs(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 wc(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 qf(t){return t.reduce((e,n)=>Math.max(e,wc(n).maxValue),0)}var vc={};J(vc,{agents:()=>yd,caches:()=>hu,callbacks__base:()=>Fu,callbacks__manager:()=>Lu,callbacks__promises:()=>ju,chat_history:()=>fa,document_loaders__base:()=>Sa,document_loaders__langsmith:()=>Ea,documents:()=>xa,embeddings:()=>ih,example_selectors:()=>Pa,index:()=>vd,indexing:()=>ja,language_models__base:()=>uu,language_models__chat_models:()=>lu,language_models__llms:()=>ch,language_models__profile:()=>Rd,load__serializable:()=>Ru,memory:()=>ma,messages:()=>$u,messages__tool:()=>Iu,output_parsers:()=>cu,output_parsers__openai_functions:()=>ec,output_parsers__openai_tools:()=>ah,outputs:()=>Nu,prompt_values:()=>au,prompts:()=>Ya,retrievers:()=>_a,retrievers__document_compressors:()=>La,runnables:()=>iu,runnables__graph:()=>Ou,singletons:()=>Pu,stores:()=>ya,structured_query:()=>ac,tools:()=>Wl,tracers__base:()=>Au,tracers__console:()=>Mu,tracers__log_stream:()=>ku,tracers__run_collector:()=>Xa,tracers__tracer_langchain:()=>xu,types__stream:()=>uf,utils__async_caller:()=>Tu,utils__chunk_array:()=>oh,utils__env:()=>Eu,utils__event_source_parse:()=>fc,utils__format:()=>Ff,utils__function_calling:()=>ou,utils__hash:()=>su,utils__json_patch:()=>ru,utils__json_schema:()=>Cu,utils__math:()=>yc,utils__stream:()=>Su,utils__testing:()=>dc,utils__tiktoken:()=>nu,utils__types:()=>tu,vectorstores:()=>ba});function Kf(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 Qn(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=Du(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:vc,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(gd.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"&&Uu(y)===l);if(typeof b!="function")throw new Error(`Invalid identifer: ${i} -> ${c}`);const C=await Qn.call({...this,path:[...o,"kwargs"]},a.kwargs);if(a.type==="constructor"){const y=new b(Vu(C,Bu,Kf(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)=>Qn.call({...this,path:[...o,`${c}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,c])=>[a,await Qn.call({...this,path:[...o,a]},c)])));return t}async function Gf(t,e){const n=JSON.parse(t);return Qn.call({...e},n)}function Jf(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function js(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>js(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await js(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(Jf(e))return Gf(JSON.stringify(e));return e}}return t}function ss(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function Yf(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?ss(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?ss(RegExp,void 0,[t.source,t.flags]):t instanceof Error?ss(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var Xf=class{_dumps(t){return new TextEncoder().encode(pd(t,(n,r)=>Yf(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return js(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 _c(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]=_c(t[n]));return e}function bc(){return{v:4,id:da(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function br(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:_c(t.versions_seen)}}function Sc(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function Zf(...t){return t.reduce((e,n,r)=>r===0?n:Sc(e,n)>=0?e:n)}const Qf={[ld]:-1,[Gn]:-2,[ud]:-3,[hd]:-4};var hn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function ep(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 tp=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){ep(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 np=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var rp=class extends tp{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=np(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]"}}},sp=class{serde=new Xf;constructor(t){this.serde=t||this.serde}},op=class Cc extends Nn{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 Cc({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 ip{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 ap(){Ve.initializeGlobalInstance(new ip)}var gt=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
|
|
124
124
|
|
|
125
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}},Ec=class extends gt{get is_bubble_up(){return!0}},ap=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"}},xt=class extends Ec{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Tc=class extends xt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},kc=class extends Ec{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function cp(t){return t!==void 0&&t.name===kc.unminifiable_name}function rr(t){return t!==void 0&&t.is_bubble_up===!0}function ut(t){return t!==void 0&&[xt.unminifiable_name,Tc.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"}},lp=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 ko(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=ko(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 ct(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 Mc 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 Mc(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}},xo=class Ac extends yt{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new Ac;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}},up=class Pc extends yt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new Pc;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}},hp=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const Vs=function(t){return t?Bs(t):new xo};Vs.Root=t=>new hp(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 xo}const F="__start__",O="__end__",Le="__input__",dp="__copy__",ae="__error__",is="__pregel_ns_writes",et="__pregel_send",Mo="__pregel_call",dt="__pregel_read",W="__pregel_checkpointer",Ke="__pregel_resuming",vn="__pregel_task_id",Er="__pregel_stream",fp="__pregel_resume_value",sr="__pregel_resume_map",tt="__pregel_scratchpad",or="__pregel_previous",Oc="__pregel_durability",zs="checkpoint_id",Pe="checkpoint_ns",pp="__pregel_node_finished",ye="checkpoint_map",di="__pregel_abort_signals",L="__interrupt__",le="__resume__",Ao="__no_writes__",tn="__return__",as="__previous__",q="langsmith:hidden",mp="langsmith:nostream",fi="__self__",ve="__pregel_tasks",de="__pregel_push",ir="__pregel_pull",_e="00000000-0000-0000-0000-000000000000",gp=[q,Le,L,le,ae,Ao,et,dt,W,Oc,Er,Ke,vn,Mo,fp,tt,or,ye,Pe,zs],G="|",ze=":",pi=Symbol.for("langgraph.command");var yp=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=xn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function me(t){return t instanceof se}function Nc(t){return!t||typeof t!="object"||!(L in t)?!1:Array.isArray(t[L])}var K=class extends yp{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)?xn(t.goto):[xn(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 xn(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]=xn(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]=xn(s,e)}return n}return t}const wp=["tags","metadata","callbacks","configurable"],vp=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],_p=25;function Ic(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:_p,configurable:{}},n=Ve.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(wp.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&&vp.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 bp(){return Ve.getRunnableConfig()}function cs(t){return t.split(G).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(ze)[0]).join(G)}function Sp(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 x=t=>BigInt(t),D=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),$c=x("0x9E3779B1"),Rc=x("0x85EBCA77"),Cp=x("0xC2B2AE3D"),st=x("0x9E3779B185EBCA87"),pt=x("0xC2B2AE3D27D4EB4F"),jc=x("0x165667B19E3779F9"),Po=x("0x85EBCA77C2B2AE63"),Ep=x("0x27D4EB2F165667C5"),Tp=x("0x165667919E3779F9"),kp=x("0x9FB21C651E98DF25"),xp=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)},Ae=xp("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Mt=(x(1)<<x(128))-x(1),$=(x(1)<<x(64))-x(1),Tr=(x(1)<<x(32))-x(1),Fe=64,Lc=Fe/8,Mp=8,Un=4;function nn(t){if(!t)throw new Error("Assert failed")}function Ap(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Pp(t){let e=t;return e=(e&x(65535))<<x(16)|(e&x(4294901760))>>x(16),e=(e&x(16711935))<<x(8)|(e&x(4278255360))>>x(8),e}function Op(t,e){return(t&Tr)*(e&Tr)&$}function Np(t,e){return(t<<e|t>>x(32)-e)&Tr}function Fc(t,e,n){for(let r=0;r<Lc;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Op(o,o>>x(32))}return t}function mi(t,e,n,r){for(let s=0;s<r;s+=1)Fc(t,D(e,s*Fe),D(n,s*8));return t}function Ip(t,e){for(let n=0;n<Lc;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Ws(s,x(47)),s^=r,s*=$c,t[n]=s&$}return t}function Vn(t,e){return Dc(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Mp,!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)),Ne(r&$)}function $p(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Fe)/8),a=Fe*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-Fe));{const l=Math.floor((e.byteLength-1-a*c)/Fe);o=mi(o,D(e,c*a),n,l),o=r(o,D(e,e.byteLength-Fe),D(n,n.byteLength-Fe-7))}return o}function Rp(t,e){let n=new BigUint64Array([Cp,st,pt,jc,Po,Rc,Ep,$c]);nn(t.byteLength>128),n=$p(n,t,e,Fc,Ip),nn(n.length*8===64);{const r=gi(n,D(e,11),x(t.byteLength)*st&$);return gi(n,D(e,e.byteLength-Fe-11),~(x(t.byteLength)*pt)&$)<<x(64)|r}}function Dc(t,e){const n=t*e&Mt;return n&$^n>>x(64)}function yi(t,e,n){return Dc((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>>x(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<<x(64)|o}function Ne(t){let e=t;return e^=e>>x(37),e*=Tp,e&=$,e^=e>>x(32),e}function kr(t){let e=t;return e^=e>>x(33),e*=pt,e&=$,e^=e>>x(29),e*=jc,e&=$,e^=e>>x(32),e}function jp(t,e,n){const r=t.byteLength;nn(r>0&&r<=3);const s=x(t.getUint8(r-1))|x(r<<8)|x(t.getUint8(0)<<16)|x(t.getUint8(r>>1)<<24),o=(x(e.getUint32(0,!0))^x(e.getUint32(4,!0)))+n,i=(s^o)&$,a=(x(e.getUint32(8,!0))^x(e.getUint32(12,!0)))-n,c=(Np(Pp(s),x(13))^a)&$;return(kr(c)&$)<<x(64)|kr(i)}function Ws(t,e){return t^t>>e}function Lp(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=x(s)|x(o)<<x(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&$;let l=(i^a)*(st+(x(r)<<x(2)))&Mt;return l+=(l&$)<<x(65),l&=Mt,l^=l>>x(67),Ws(Ws(l&$,x(35))*kp&$,x(28))|Ne(l>>x(64))<<x(64)}}function Fp(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)*st;const l=(c&$)+(x(r-1)<<x(54));c=c&(Mt^$)|l,a^=o,c+=a+(a&Tr)*(Rc-x(1))<<x(64),c&=Mt,c^=Ap(c>>x(64));let u=(c&$)*pt;return u+=(c>>x(64))*pt<<x(64),u&=Mt,Ne(u&$)|Ne(u>>x(64))<<x(64)}}function Dp(t,e){const n=t.byteLength;return nn(n<=16),n>8?Fp(t,Ae,e):n>=4?Lp(t,Ae,e):n>0?jp(t,Ae,e):kr(e^Ae.getBigUint64(64,!0)^Ae.getBigUint64(72,!0))|kr(e^Ae.getBigUint64(80,!0)^Ae.getBigUint64(88,!0))<<x(64)}function qs(t){return~t+x(1)&$}function Up(t,e,n){let r=x(t.byteLength)*st&$,s=x(t.byteLength-1)/x(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-=x(1)}let o=r+(r>>x(64))&$;o=Ne(o);let i=(r&$)*st+(r>>x(64))*Po+(x(t.byteLength)-n&$)*pt;return i&=$,i=qs(Ne(i)),o|i<<x(64)}function Vp(t,e,n){let r=x(t.byteLength)*st&$;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=Ne(r&$)|Ne(r>>x(64))<<x(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>>x(64))&$;s=Ne(s);let o=(r&$)*st+(r>>x(64))*Po+(x(t.byteLength)-n&$)*pt;return o&=$,o=qs(Ne(o)),s|o<<x(64)}function at(t,e=x(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(Dp(r,e)):s<=128?o(Up(r,Ae,e)):s<=240?o(Vp(r,Ae,e)):o(Rp(r,Ae))}function Uc(t){return/^[0-9a-f]{32}$/.test(t)}function Vc(t){const e=Ve.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[tt];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[et]?.([[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[et]?.([[le,s.resume]]),c}const i=n[Pe]?.split(G),a=i?at(i.join(G)):void 0;throw new xt([{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()});Ve.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=Ic(n),o=De(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await Ve.runWithConfig(o,async()=>this.func(e,o)),Q.isRunnable(r)&&this.recurse?await Ve.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*We(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ge(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 Bp(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(Bp(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?.[et];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 zp=class Bc extends wt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Bc.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 wu;var Mn=class mn extends Oe{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 rt({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new rt({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 Hp(t){return"steps"in t&&Array.isArray(t.steps)}function Oo(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function zc(t){const e=[t];for(const n of e){if(Oo(n))return n;Hp(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*Wp(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(Uc))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*Hc(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*qp(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 Kp(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 it(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 xr(...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 Gp=(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 Jp=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 Yp(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Xp(t,e){const n=new wt({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new rt({name:t,first:n,last:new oe([{channel:tn,value:ft}],[q])})}const Zp=t=>t!==void 0?t+1:1;function Qp(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function em(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=Xf(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=ct(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 tm=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=ko(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=em(t.channel_versions);const c=new Set(n.flatMap(d=>d.triggers).filter(d=>!gp.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)tm.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&&!Qp(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*nm(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 nm(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&&Yp(t[t.length-1])){const f=t[t.length-1],g=Xp(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}${ze}${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(De(o,{metadata:w,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[vn]:C,[et]: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},[tt]:fs({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:o.configurable?.[sr],namespaceHash:at(y)}),[or]:e.channel_values[as],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:at((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}${ze}${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(De(o,{metadata:w,tags:E.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[vn]:y,[et]:S=>ds(k=>v.push(...k),r,S),[dt]:(S,k=!1)=>ur(e,s,{name:p.node,writes:v,triggers:b,path:t},S,k),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[tt]:fs({pendingWrites:n??[],taskId:y,currentTaskInput:p.args,resumeMap:o.configurable?.[sr],namespaceHash:at(_)}),[or]:e.channel_values[as],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:b,retry_policy:E.retryPolicy,cache_key:E.cachePolicy?{key:at((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=rm(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=`${_}${ze}${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(De(o,{metadata:T,tags:g.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[vn]:w,[et]:k=>ds(M=>{S.push(...M)},r,k),[dt]:(k,M=!1)=>ur(e,s,{name:f,writes:S,triggers:[C],path:t},k,M),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[tt]:fs({pendingWrites:n??[],taskId:w,currentTaskInput:y,resumeMap:o.configurable?.[sr],namespaceHash:at(E)}),[or]:e.channel_values[as],checkpoint_id:void 0,checkpoint_ns:E}}),triggers:[C],retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:at((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 rm(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 sm(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Wc(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=sm(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*om(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(q)||(yield{id:n,name:r,result:Wc(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===L).map(i=>i[1])})}function*im(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(zc))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:qc(s,o,u,a),parentConfig:i?c(i):void 0}}function qc(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?Wc(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 am(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 Kc(t,e){const n=e.length;console.log([`${
|
|
128
|
-
`,e.map(r=>`- ${
|
|
129
|
-
`)].join(""))}function
|
|
130
|
-
`,Object.entries(r).map(([s,o])=>`- ${
|
|
131
|
-
`)].join(""))}var
|
|
132
|
-
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:um(s)})}n.close()}})}const Hn=Symbol.for("INPUT_DONE"),ms=Symbol.for("INPUT_RESUMING"),dm=25;function fm(...t){return new Gc({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 pm=class extends rp{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}},mm=class Jc{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?.[Ke]!==void 0&&this.config.configurable?.[Ke],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=Zp,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 pm(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=fm(r,n.configurable[Er]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[tt];n.configurable&&o&&(o.subgraphCounter>0&&(n=Ce(n,{[Pe]:[n.configurable[Pe],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:bc(),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??dm)+1,C={...h.channel_versions},y=e.store?new np(e.store):void 0;return y&&await y.start(),new Jc({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 Zf)&&(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,{[Pe]: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(We(qp(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(pn(We(om([[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 xt;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 Ge(We(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 xt;this.config.configurable?.[Ke]!==void 0&&delete this.config.configurable?.[Ke]}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 Ge(We(im(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 xt;const s=await Ge(We(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(ze)))&&(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(We(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(We(wi([s]),"tasks"))),this.debug&&Kc(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?.[tt];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(Uc)&&(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 Wp(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:Le,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 Ge(We(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 Ge(Hc(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:Le,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Hn}else if(Ke 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,{[Ke]: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,{[Pe]: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=ct(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,{[Pe]: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 gm(t){return je(t?.message)}var ym=class extends Ju{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&&(Yu(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(mp)&&!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&&(gm(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];je(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((je(c)||Vo(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(const l of c)(je(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(je(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)je(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(je(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)je(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const wm=500,vm=2,_m=128e3,bm=3,Sm=[400,401,402,403,404,405,406,407,409],Cm=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&&Sm.includes(+e)||t?.error?.code==="insufficient_quota")};async function Yc(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??wm: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,cp(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=Sp(g);a.command=new K({...a.command,graph:b})}}if(rr(a)||s===void 0||(i+=1,i>=(s.maxAttempts??bm))||!(s.retryOn??Cm)(a))break;o=Math.min(s.maxInterval??_m,o*(s.backoffFactor??vm));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,{[Ke]:!0})}}return{task:t,result:c,error:a,signalAborted:r?.aborted}}const Js=Symbol.for("promiseAdded");function Em(){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 Tm=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}=xr(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=Em(),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=xr(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]=Yc(f,n,{[Mo]:Xc?.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 Xc(t,e,n,r,s,o={}){const i=e.config?.configurable?.[tt];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 Jp({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=Yc(l,o.retry,{[Mo]:Xc.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 $e=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function km({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new $e("Channels not provided");const a=new Set,c=new Set;for(const[l,u]of Object.entries(t)){if(l===L)throw new $e(`"Node name ${L} is reserved"`);if(u.constructor===Mn)u.triggers.forEach(h=>a.add(h));else throw new $e(`Invalid node type ${typeof u}, expected PregelNode`)}for(const l of a)if(!(l in e))throw new $e(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(n)){if(n.every(l=>!a.has(l)))throw new $e(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new $e(`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 $e(`Output channel '${String(l)}' not in channels`);if(o&&o!=="*"){for(const l of o)if(!(l in t))throw new $e(`Node ${String(l)} not in nodes`)}if(i&&i!=="*"){for(const l of i)if(!(l in t))throw new $e(`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 xm=class Zc 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 Zc({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}},Mm=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)}},Am=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)}},Pm=class extends Am{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 xm({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=De(this.config,t);return new this.constructor({...this,config:e})}validate(){km({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=zc(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:Le,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 Ge(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)}${ze}${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:qc(o,e?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:it(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=De(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=De(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?De(this.config,i):i,l=await n.getTuple(c),u=l!==void 0?Sr(l.checkpoint):bc(),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,ct(u,void 0,d),{source:"update",step:d+1,parents:l?.metadata?.parents??{}},{});return it(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}),k=(l.pendingWrites||[]).filter(M=>M[0]===_e).map(M=>M.slice(1));k.length>0&&he(u,C,[{name:Le,writes:k,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,ct(u,C,d),{...g,source:"update",step:d+1,parents:l?.metadata?.parents??{}},lr(h,u.channel_versions));return it(v,l?l.metadata:void 0)}if(b===dp){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=ct(u,void 0,d),k=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,k,!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 Me=j[Se].length,Ln=P[Se]?.[Me]?.id;return j[Se].push({values:re,asNode:Se,taskId:Ln}),j},{});return s(it(k,l.metadata),Object.values(I).flat())}return it(k,l.metadata)}if(b===Le){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const v=await Ge(Hc(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:Le,writes:v,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const S=l?.metadata?.step!=null?l.metadata.step+1:-1,k=await n.put(f,ct(u,C,S),{source:"input",step:S,parents:l?.metadata?.parents??{}},lr(h,u.channel_versions));return await n.putWrites(k,v,St(Le,u.id)),it(k,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:Le,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 k=Object.values(v).filter(M=>M.writes.length>0);k.length>0&&he(u,C,k,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:k}=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])=>Sc(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:k})}else for(const{asNode:v,values:S,taskId:k}of a){if(v==null)throw new B('"asNode" is required when applying multiple updates');_.push({values:S,asNode:v,taskId:k})}const w=[];for(const{asNode:v,values:S,taskId:k}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?rt.from(M,{omitSequenceTags:!0}):M[0],writes:[],triggers:[L],id:k??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:{[et]:S=>v.writes.push(...S),[dt]:(S,k=!1)=>ur(u,C,v,S,k)}}));for(const v of w){const S=v.writes.filter(k=>k[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,ct(u,C,d+1),{source:"update",step:d+1,parents:l?.metadata?.parents??{}},E);for(const v of w){const S=v.writes.filter(k=>k[0]===de);S.length>0&&await n.putWrites(T,S,v.id)}return it(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?.[Oc]??"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:xr(e?.signal,n.signal).signal},s=await super.stream(t,r);return new vi(e?.encoding==="text/event-stream"?hm(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:Gp(this.config?.callbacks,e?.callbacks),signal:xr(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=Ic(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 Gc({modes:new Set(l)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[Pe]??"";h.configurable[Pe]=P.split(G).map(I=>I.split(ze)[0]).join(G)}if(l.includes("messages")){const P=new ym(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=bp()?.configurable?.[Pe]?.split(G).slice(0,-1);_.push([I??[],"custom",P])},h.interrupt??=this.userInterrupt??Vc;const E=await(await Xu(h))?.handleChainStart(this.toJSON(),Kp(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),T=ko(this.channels);let v,S;const M=(async()=>{try{v=await mm.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 Tm({loop:v,nodeFinished:h.configurable?.[pp]});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"?Nc(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&&am(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&Kc(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&cm(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new ap([`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 Qc extends yt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Qc(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}},el=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===Tc.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}},
|
|
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}},tl=class extends Pm{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]=Mm.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 Ge(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 Nm=class nl extends yt{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new nl(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)}},Im=class rl 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 rl(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 $m="lg:";var Rm=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 xo}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(`${$m}${h}`)}return[i,l]});s=Zu(t,Object.fromEntries(o)),Qu(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=oo(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const sn=new Rm;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 Ue="__root__",Ys=Symbol.for("langgraph.state.partial");var jm=class extends Om{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=sn;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),zm(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(Bm(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Vm(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Dm(t)||Ei(t)){const r=Ei(t)?t.spec:t;this._schemaDefinition=r}else if(Um(t)){const r=Lm(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,ze])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]===Ue?Ue:a,l=Object.keys(this.channels),u=l.length===1&&l[0]===Ue?Ue:l,h=this._interrupt,d=new Fm({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 Lm(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Bs(r);return e}var Fm=class extends tl{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([Ue,l]);return c}else if(a!=null)return[[Ue,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]===Ue?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&&Ue in c,u=`branch:to:${t}`;this.channels[u]=e?.defer?new up: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 Im(new Set(t)):new Nm(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=>zp.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=Xe(e,t.update)),n}return e!=null?Xe(e,t):t}isInterrupted(t){return Nc(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return fe(e)&&Xe(e,t),t}};function Dm(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 Um(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Vm(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function Bm(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function zm(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 Hm(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 kc(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:Hm,tags:[q],trace:!1,recurse:!1,name:"<control_branch>"});return new el({path:t})}const sl="__remove_all__";function ol(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===sl&&(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:ol,default:()=>[]})});const Mr={reducer:{fn:ol},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:on(ce(),Mr)});ip();const Xs=Symbol.for("langgraph-zod");Xs in globalThis||(globalThis[Xs]=new WeakSet);function ki(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{ki(eh.prototype),ki(Ul.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 Wm=class extends Vl{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 Wm(sn);function qm(t=!0,e,n=[]){const r={messages:on(ce(),Mr),jumpTo:Ie([kt("model_request"),kt("tools"),kt("end"),th()]).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 xi="prompt",gs=/<name>(.*?)<\/name>/s,ys=/<content>(.*?)<\/content>/s;function Km(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 Gm(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(Oe.isRunnableBinding(t)&&Mi(t.bound)){const r=t.bound.bindTools(e,n);return Oe.isRunnableBinding(r)?new Oe({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Oe({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function il(t){if(typeof t=="function")return;let e=t;if(rt.isRunnableSequence(e)&&(e=e.steps.find(n=>Oe.isRunnableBinding(n))||e),!yr(e)){if(Oe.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 xs}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new xs}}function Zs(t){return!!(N.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Jm(t){let e;if(t==null)e=Xt.from(n=>n.messages).withConfig({runName:xi});else if(typeof t=="string"){const n=new be(t);e=Xt.from(r=>[n,...r.messages??[]]).withConfig({runName:xi})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function Ym(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(rt.isRunnableSequence(t)){const s=t.steps.findIndex(o=>Oe.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),rt.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Xm(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 Zm(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Xm(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?Xe(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 Qm(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=nh(r.stateSchema,a=>a.startsWith("_")),o=await rh(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(`
|
|
126
|
+
`),super(n),this.lc_error_code=e?.lc_error_code}},Ec=class extends gt{get is_bubble_up(){return!0}},cp=class extends gt{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},er=class extends gt{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},kt=class extends Ec{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Tc=class extends kt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},xc=class extends Ec{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function lp(t){return t!==void 0&&t.name===xc.unminifiable_name}function tr(t){return t!==void 0&&t.is_bubble_up===!0}function ut(t){return t!==void 0&&[kt.unminifiable_name,Tc.unminifiable_name].includes(t.name)}var oi=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"}},up=class extends gt{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function kc(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 Ls=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function bo(t){if(t[Ls]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];kc(r)&&(e[n]=r)}return Object.assign(e,{[Ls]:!0}),e}function Sr(t,e){const n=bo(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,{[Ls]:!0}),r}function ct(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 Fs=class Mc 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 Mc(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}},So=class Ac extends yt{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new Ac;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}},hp=class Pc extends yt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new Pc;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}},dp=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const Ds=function(t){return t?Us(t):new So};Ds.Root=t=>new dp(t);function Us(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new Fs(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new Fs(t.value,t.default):new So}const F="__start__",O="__end__",Le="__input__",fp="__copy__",ae="__error__",os="__pregel_ns_writes",et="__pregel_send",Co="__pregel_call",dt="__pregel_read",W="__pregel_checkpointer",Ke="__pregel_resuming",wn="__pregel_task_id",Cr="__pregel_stream",pp="__pregel_resume_value",nr="__pregel_resume_map",tt="__pregel_scratchpad",rr="__pregel_previous",Oc="__pregel_durability",Vs="checkpoint_id",Pe="checkpoint_ns",mp="__pregel_node_finished",ye="checkpoint_map",ii="__pregel_abort_signals",L="__interrupt__",le="__resume__",Eo="__no_writes__",tn="__return__",is="__previous__",q="langsmith:hidden",gp="langsmith:nostream",ai="__self__",ve="__pregel_tasks",de="__pregel_push",sr="__pregel_pull",_e="00000000-0000-0000-0000-000000000000",yp=[q,Le,L,le,ae,Eo,et,dt,W,Oc,Cr,Ke,wn,Co,pp,tt,rr,ye,Pe,Vs],G="|",ze=":",ci=Symbol.for("langgraph.command");var wp=class{[ci];constructor(t){this[ci]=t}};function Bs(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=xn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function me(t){return t instanceof se}function Nc(t){return!t||typeof t!="object"||!(L in t)?!1:Array.isArray(t[L])}var K=class extends wp{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)?xn(t.goto):[xn(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 xn(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]=xn(r,e)});else if(Y(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(Bs(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]=xn(s,e)}return n}return t}const vp=["tags","metadata","callbacks","configurable"],_p=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],bp=25;function Ic(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:bp,configurable:{}},n=Ve.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(vp.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&&_p.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 Sp(){return Ve.getRunnableConfig()}function as(t){return t.split(G).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(ze)[0]).join(G)}function Cp(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),$c=k("0x9E3779B1"),Rc=k("0x85EBCA77"),Ep=k("0xC2B2AE3D"),st=k("0x9E3779B185EBCA87"),pt=k("0xC2B2AE3D27D4EB4F"),jc=k("0x165667B19E3779F9"),To=k("0x85EBCA77C2B2AE63"),Tp=k("0x27D4EB2F165667C5"),xp=k("0x165667919E3779F9"),kp=k("0x9FB21C651E98DF25"),Mp=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)},Ae=Mp("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Mt=(k(1)<<k(128))-k(1),$=(k(1)<<k(64))-k(1),Er=(k(1)<<k(32))-k(1),Fe=64,Lc=Fe/8,Ap=8,Dn=4;function nn(t){if(!t)throw new Error("Assert failed")}function Pp(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Op(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 Np(t,e){return(t&Er)*(e&Er)&$}function Ip(t,e){return(t<<e|t>>k(32)-e)&Er}function Fc(t,e,n){for(let r=0;r<Lc;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Np(o,o>>k(32))}return t}function li(t,e,n,r){for(let s=0;s<r;s+=1)Fc(t,D(e,s*Fe),D(n,s*8));return t}function $p(t,e){for(let n=0;n<Lc;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=zs(s,k(47)),s^=r,s*=$c,t[n]=s&$}return t}function Un(t,e){return Dc(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Ap,!0))}function ui(t,e,n){let r=n;return r+=Un(t.slice(0),D(e,0*Dn)),r+=Un(t.slice(2),D(e,4*Dn)),r+=Un(t.slice(4),D(e,8*Dn)),r+=Un(t.slice(6),D(e,12*Dn)),Ne(r&$)}function Rp(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Fe)/8),a=Fe*i,c=Math.floor((e.byteLength-1)/a);for(let l=0;l<c;l+=1)o=li(o,D(e,l*a),n,i),o=s(o,D(n,n.byteLength-Fe));{const l=Math.floor((e.byteLength-1-a*c)/Fe);o=li(o,D(e,c*a),n,l),o=r(o,D(e,e.byteLength-Fe),D(n,n.byteLength-Fe-7))}return o}function jp(t,e){let n=new BigUint64Array([Ep,st,pt,jc,To,Rc,Tp,$c]);nn(t.byteLength>128),n=Rp(n,t,e,Fc,$p),nn(n.length*8===64);{const r=ui(n,D(e,11),k(t.byteLength)*st&$);return ui(n,D(e,e.byteLength-Fe-11),~(k(t.byteLength)*pt)&$)<<k(64)|r}}function Dc(t,e){const n=t*e&Mt;return n&$^n>>k(64)}function hi(t,e,n){return Dc((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&$,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&$)}function or(t,e,n,r,s){let o=t&$,i=t>>k(64)&$;return o+=hi(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=$,i+=hi(n,D(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=$,i<<k(64)|o}function Ne(t){let e=t;return e^=e>>k(37),e*=xp,e&=$,e^=e>>k(32),e}function Tr(t){let e=t;return e^=e>>k(33),e*=pt,e&=$,e^=e>>k(29),e*=jc,e&=$,e^=e>>k(32),e}function Lp(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=(Ip(Op(s),k(13))^a)&$;return(Tr(c)&$)<<k(64)|Tr(i)}function zs(t,e){return t^t>>e}function Fp(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)*(st+(k(r)<<k(2)))&Mt;return l+=(l&$)<<k(65),l&=Mt,l^=l>>k(67),zs(zs(l&$,k(35))*kp&$,k(28))|Ne(l>>k(64))<<k(64)}}function Dp(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)*st;const l=(c&$)+(k(r-1)<<k(54));c=c&(Mt^$)|l,a^=o,c+=a+(a&Er)*(Rc-k(1))<<k(64),c&=Mt,c^=Pp(c>>k(64));let u=(c&$)*pt;return u+=(c>>k(64))*pt<<k(64),u&=Mt,Ne(u&$)|Ne(u>>k(64))<<k(64)}}function Up(t,e){const n=t.byteLength;return nn(n<=16),n>8?Dp(t,Ae,e):n>=4?Fp(t,Ae,e):n>0?Lp(t,Ae,e):Tr(e^Ae.getBigUint64(64,!0)^Ae.getBigUint64(72,!0))|Tr(e^Ae.getBigUint64(80,!0)^Ae.getBigUint64(88,!0))<<k(64)}function Hs(t){return~t+k(1)&$}function Vp(t,e,n){let r=k(t.byteLength)*st&$,s=k(t.byteLength-1)/k(32);for(;s>=0;){const a=Number(s);r=or(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=Ne(o);let i=(r&$)*st+(r>>k(64))*To+(k(t.byteLength)-n&$)*pt;return i&=$,i=Hs(Ne(i)),o|i<<k(64)}function Bp(t,e,n){let r=k(t.byteLength)*st&$;for(let i=32;i<160;i+=32)r=or(r,D(t,i-32),D(t,i-16),D(e,i-32),n);r=Ne(r&$)|Ne(r>>k(64))<<k(64);for(let i=160;i<=t.byteLength;i+=32)r=or(r,D(t,i-32),D(t,i-16),D(e,3+i-160),n);r=or(r,D(t,t.byteLength-16),D(t,t.byteLength-32),D(e,103),Hs(n));let s=r+(r>>k(64))&$;s=Ne(s);let o=(r&$)*st+(r>>k(64))*To+(k(t.byteLength)-n&$)*pt;return o&=$,o=Hs(Ne(o)),s|o<<k(64)}function at(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(Up(r,e)):s<=128?o(Vp(r,Ae,e)):s<=240?o(Bp(r,Ae,e)):o(jp(r,Ae))}function Uc(t){return/^[0-9a-f]{32}$/.test(t)}function Vc(t){const e=Ve.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 er("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[tt];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[et]?.([[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[et]?.([[le,s.resume]]),c}const i=n[Pe]?.split(G),a=i?at(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=yn(n,{callbacks:r?.getChild()});Ve.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=Ic(n),o=De(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await Ve.runWithConfig(o,async()=>this.func(e,o)),Q.isRunnable(r)&&this.recurse?await Ve.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*We(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ge(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 zp(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const ft={[Symbol.for("LG_PASSTHROUGH")]:!0};function Vn(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const cs=Symbol("IS_WRITER");var oe=class Ws 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=>ls(s)&&Vn(s.value)?{mapper:s.mapper,value:e}:ir(s)&&Vn(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Ws.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(ir(o)){if(o.channel===ve)throw new B("Cannot write to the reserved channel TASKS");if(Vn(o.value))throw new B("PASSTHROUGH value must be replaced")}if(ls(o)&&Vn(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(ls(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(ir(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(zp(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?.[et];s(r)}static isWriter(e){return e instanceof Ws||cs in e&&!!e[cs]}static registerWriter(e){return Object.defineProperty(e,cs,{value:!0})}};function ir(t){return t!==void 0&&typeof t.channel=="string"}function ls(t){return t!==void 0&&!ir(t)&&Q.isRunnable(t.mapper)}var Hp=class Bc extends wt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Bc.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 du;var kn=class mn extends Oe{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 rt({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new rt({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 Wp(t){return"steps"in t&&Array.isArray(t.steps)}function xo(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function zc(t){const e=[t];for(const n of e){if(xo(n))return n;Wp(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*qp(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(Uc))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*Hc(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*us(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*Kp(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 ko(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 ar(t,e){if(Object.keys(t).length>0){const n=ko(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function Gp(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 it(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 xr(...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 Jp=(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 Yp=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 Xp(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Zp(t,e){const n=new wt({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new rt({name:t,first:n,last:new oe([{channel:tn,value:ft}],[q])})}const Qp=t=>t!==void 0?t+1:1;function em(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function tm(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=Zf(e,t[n]));return e}function Bn(t,e,n){const r=ko(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 cr(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=ct(t,a,-1),l=Sr(a,c);he(br(c),l,[n],void 0,void 0),i=mt({...e,...l},r)}else i=mt(e,r);return i}function hs(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 nm=new Set([Eo,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=bo(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=tm(t.channel_versions);const c=new Set(n.flatMap(d=>d.triggers).filter(d=>!yp.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)nm.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&&!em(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*rm(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=qs([de,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const l of rm(t,n,i)){const u=qs([sr,l],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function qs(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&&Xp(t[t.length-1])){const f=t[t.length-1],g=Zp(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}${ze}${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:yn(De(o,{metadata:w,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[wn]:C,[et]:v=>hs(S=>E.push(...S),r,v),[dt]:(v,S=!1)=>cr(e,s,{name:f.name,writes:E,triggers:p,path:_},v,S),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[tt]:ds({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:o.configurable?.[nr],namespaceHash:at(y)}),[rr]:e.channel_values[is],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:at((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[os,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=Bs(g[f])&&!me(g[f])?new se(g[f].node,g[f].args):g[f];if(!Bs(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}${ze}${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:yn(De(o,{metadata:w,tags:E.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[wn]:y,[et]:S=>hs(x=>v.push(...x),r,S),[dt]:(S,x=!1)=>cr(e,s,{name:p.node,writes:v,triggers:b,path:t},S,x),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[tt]:ds({pendingWrites:n??[],taskId:y,currentTaskInput:p.args,resumeMap:o.configurable?.[nr],namespaceHash:at(_)}),[rr]:e.channel_values[is],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:b,retry_policy:E.retryPolicy,cache_key:E.cachePolicy?{key:at((E.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[os,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]===sr){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,sr,f]),e.id);if(n.some(E=>E[0]===_&&E[1]!==ae))return}const p=ko(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=sm(g,s,i);if(y===void 0)return;const _=d===""?f:`${d}${G}${f}`,w=St(JSON.stringify([_,c.toString(),f,sr,[C]]),e.id),E=`${_}${ze}${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:yn(De(o,{metadata:T,tags:g.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[wn]:w,[et]:x=>hs(M=>{S.push(...M)},r,x),[dt]:(x,M=!1)=>cr(e,s,{name:f,writes:S,triggers:[C],path:t},x,M),[W]:l??h[W],[ye]:{...h[ye],[d]:e.id},[tt]:ds({pendingWrites:n??[],taskId:w,currentTaskInput:y,resumeMap:o.configurable?.[nr],namespaceHash:at(E)}),[rr]:e.channel_values[is],checkpoint_id:void 0,checkpoint_ns:E}}),triggers:[C],retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:at((g.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[os,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 sm(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 ds({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 Mn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},An=(t,e)=>`${t.start}${e}${t.end}`;function*di(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 om(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Wc(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=om(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*im(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(q)||(yield{id:n,name:r,result:Wc(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===L).map(i=>i[1])})}function*am(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(zc))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:qc(s,o,u,a),parentConfig:i?c(i):void 0}}function qc(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?Wc(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 cm(t,e,n){console.log([`${An(Mn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
|
|
127
|
+
`,JSON.stringify(mt(e,n),null,2)].join(""))}function Kc(t,e){const n=e.length;console.log([`${An(Mn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
|
|
128
|
+
`,e.map(r=>`- ${An(Mn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
|
|
129
|
+
`)].join(""))}function lm(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${An(Mn.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])=>`- ${An(Mn.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
|
|
131
|
+
`)].join(""))}var fi=class extends _n{_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}},Gc=class extends _n{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 um(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 hm(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function Mo(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function fs(t){return!Mo(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 pi(t){if(Mo(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 mi(t){const e={...t,checkpoint:fs(t.config),parent_checkpoint:fs(t.parentConfig),config:pi(t.config),parent_config:pi(t.parentConfig),tasks:t.tasks.map(n=>{if(Mo(n.state)){const r=fs(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function dm(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
|
|
132
|
+
data: ${um(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:mi(u.payload)})}i==="checkpoints"&&(c=mi(a));const l=o?.length?`${i}|${o.join("|")}`:i;r({event:l,data:c})}}catch(s){r({event:"error",data:hm(s)})}n.close()}})}const zn=Symbol.for("INPUT_DONE"),ps=Symbol.for("INPUT_RESUMING"),fm=25;function pm(...t){return new Gc({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 mm=class extends sp{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}},gm=class Jc{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?.[Ke]!==void 0&&this.config.configurable?.[Ke],s=this.input===null||this.input===void 0,o=Y(this.input)&&this.input.resume!=null,i=this.input===ps,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=Qp,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 mm(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?.[Cr]!==void 0&&(r=pm(r,n.configurable[Cr]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[tt];n.configurable&&o&&(o.subgraphCounter>0&&(n=Ce(n,{[Pe]:[n.configurable[Pe],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:bc(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...l.config,configurable:{checkpoint_ns:"",...n.configurable,...l.config.configurable}};const u=l.parentConfig,h=br(l.checkpoint),d={...l.metadata},f=l.pendingWrites??[],g=Sr(e.channelSpecs,h),p=(d.step??0)+1,b=p+(n.recursionLimit??fm)+1,C={...h.channel_versions},y=e.store?new rp(e.store):void 0;return y&&await y.start(),new Jc({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 Qf)&&(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,{[Pe]:this.config.configurable?.checkpoint_ns??"",[Vs]: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(We(Kp(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(pn(We(im([[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(![zn,ps].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 Ge(We(us(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Bn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new kt;this.config.configurable?.[Ke]!==void 0&&delete this.config.configurable?.[Ke]}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 Ge(We(am(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(Bn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new kt;const s=await Ge(We(di(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(ze)))&&(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(We(us(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&&Bn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=qs([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&&Bn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(pn(We(di([s]),"tasks"))),this.debug&&Kc(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?.[tt];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(Uc)&&(this.config.configurable??={},this.config.configurable[nr]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[c,l,u]of qp(this.input,this.checkpointPendingWrites))a[c]??=[],a[c].push([l,u]);if(Object.keys(a).length===0)throw new oi("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:Le,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 Ge(We(us(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=ps;else if(o)await this._putCheckpoint({source:"input"}),this.input=zn;else{const i=await Ge(Hc(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:Le,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=zn}else if(Ke in(this.config.configurable??{}))this.input=zn;else throw new oi(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Ce(this.config,{[Ke]: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,{[Pe]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=ar(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:br(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=ct(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,{[Pe]:this.config.configurable?.checkpoint_ns??"",[Vs]: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 ym(t){return je(t?.message)}var wm=class extends zu{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&&(Hu(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(gp)&&!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&&(ym(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];je(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((je(c)||jo(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(const l of c)(je(l)||jo(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(je(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)je(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(je(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)je(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const vm=500,_m=2,bm=128e3,Sm=3,Cm=[400,401,402,403,404,405,406,407,409],Em=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&&Cm.includes(+e)||t?.error?.code==="insufficient_quota")};async function Yc(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??vm: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,lp(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=Cp(g);a.command=new K({...a.command,graph:b})}}if(tr(a)||s===void 0||(i+=1,i>=(s.maxAttempts??Sm))||!(s.retryOn??Em)(a))break;o=Math.min(s.maxInterval??bm,o*(s.backoffFactor??_m));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,{[Ke]:!0})}}return{task:t,result:c,error:a,signalAborted:r?.aborted}}const Ks=Symbol.for("promiseAdded");function Tm(){const t={next:()=>{},wait:Promise.resolve(Ks)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Ks)}}return t.wait=new Promise(e),t}var xm=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)||tr(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)||tr(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[ii]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=xr(s,o,t),c={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Ce(this.loop.config,{[ii]:c}),{signals:c,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Tm(),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=xr(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]=Yc(f,n,{[Co]:Xc?.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!==Ks&&(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 tr(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([Eo,null]),this.loop.putWrites(t.id,t.writes)}};async function Xc(t,e,n,r,s,o={}){const i=e.config?.configurable?.[tt];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 Yp({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=Yc(l,o.retry,{[Co]:Xc.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 $e=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function km({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new $e("Channels not provided");const a=new Set,c=new Set;for(const[l,u]of Object.entries(t)){if(l===L)throw new $e(`"Node name ${L} is reserved"`);if(u.constructor===kn)u.triggers.forEach(h=>a.add(h));else throw new $e(`Invalid node type ${typeof u}, expected PregelNode`)}for(const l of a)if(!(l in e))throw new $e(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(n)){if(n.every(l=>!a.has(l)))throw new $e(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new $e(`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 $e(`Output channel '${String(l)}' not in channels`);if(o&&o!=="*"){for(const l of o)if(!(l in t))throw new $e(`Node ${String(l)} not in nodes`)}if(i&&i!=="*"){for(const l of i)if(!(l in t))throw new $e(`Node ${String(l)} not in nodes`)}}function gi(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 Mm=class Zc 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 Zc({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}},Am=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 kn({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)}},Pm=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)}},Om=class extends Pm{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 Mm({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=De(this.config,t);return new this.constructor({...this,config:e})}validate(){km({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=zc(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=Sr(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:Le,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 Ge(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)}${ze}${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,Gn].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:qc(o,e?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:it(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 er("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const a=as(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=De(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 er("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const o=as(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=De(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 er("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=as(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?De(this.config,i):i,l=await n.getTuple(c),u=l!==void 0?br(l.checkpoint):bc(),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,ct(u,void 0,d),{source:"update",step:d+1,parents:l?.metadata?.parents??{}},{});return it(v,l?l.metadata:void 0)}const C=Sr(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:Le,writes:x,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[M,P,I]of l.pendingWrites||[])[ae,L,Gn].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,ct(u,C,d),{...g,source:"update",step:d+1,parents:l?.metadata?.parents??{}},ar(h,u.channel_versions));return it(v,l?l.metadata:void 0)}if(b===fp){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=ct(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 Me=j[Se].length,jn=P[Se]?.[Me]?.id;return j[Se].push({values:re,asNode:Se,taskId:jn}),j},{});return s(it(x,l.metadata),Object.values(I).flat())}return it(x,l.metadata)}if(b===Le){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const v=await Ge(Hc(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:Le,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,ct(u,C,S),{source:"input",step:S,parents:l?.metadata?.parents??{}},ar(h,u.channel_versions));return await n.putWrites(x,v,St(Le,u.id)),it(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:Le,writes:S,triggers:[]}],void 0,this.triggerToNodes);for(const[M,P,I]of l.pendingWrites)[ae,L,Gn].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])=>Sc(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?rt.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,yn({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[et]:S=>v.writes.push(...S),[dt]:(S,x=!1)=>cr(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=ar(h,u.channel_versions),T=await n.put(f,ct(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 it(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:gi(u,this.channels);let h=r;h===void 0?h=this.inputChannels:gi(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?.[wn]!==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?.[Oc]??"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:xr(e?.signal,n.signal).signal},s=await super.stream(t,r);return new fi(e?.encoding==="text/event-stream"?dm(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:Jp(this.config?.callbacks,e?.callbacks),signal:xr(e?.signal,r.signal).signal};return new fi(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=Ic(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 Gc({modes:new Set(l)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[Pe]??"";h.configurable[Pe]=P.split(G).map(I=>I.split(ze)[0]).join(G)}if(l.includes("messages")){const P=new wm(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=Sp()?.configurable?.[Pe]?.split(G).slice(0,-1);_.push([I??[],"custom",P])},h.interrupt??=this.userInterrupt??Vc;const E=await(await Wu(h))?.handleChainStart(this.toJSON(),Gp(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),T=bo(this.channels);let v,S;const M=(async()=>{try{v=await gm.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 xm({loop:v,nodeFinished:h.configurable?.[mp]});e?.subgraphs&&(v.config.configurable={...v.config.configurable,[Cr]: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"?Nc(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&&cm(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&Kc(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&lm(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new cp([`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 Qc extends yt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Qc(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}},el=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===Tc.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}},Nm=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,ze])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:xo(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 el(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 tl({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 up([`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}},tl=class extends Om{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new rn,this.nodes[t]=new kn({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]=Am.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 Lo,r={[F]:n.addNode({schema:Ee()},F)},s={};let o={};e&&(o=Object.fromEntries((await Ge(this.getSubgraphsAsync())).filter(c=>yi(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&&!Fo(_))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 Lo,r={[F]:n.addNode({schema:Ee()},F)},s={};let o={};e&&(o=Object.fromEntries(pn(this.getSubgraphs()).filter(c=>yi(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&&!Fo(_))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 yi(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 Im=class nl extends yt{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new nl(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)}},$m=class rl 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 rl(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 Rm="lg:";var jm=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=Do(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new Fs(o.reducer.fn,o.default):e[r]=new So}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(Do(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=bs(l)??bs(a),h=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`${Rm}${h}`)}return[i,l]});s=qu(t,Object.fromEntries(o)),Ku(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=eo(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const sn=new jm;function on(t,e){if(e.reducer&&!e.default){const n=Qs(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 Ue="__root__",Gs=Symbol.for("langgraph.state.partial");var Lm=class extends Nm{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=sn;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Hm(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??Gs,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=Gs,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(zm(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Bm(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Um(t)||wi(t)){const r=wi(t)?t.spec:t;this._schemaDefinition=r}else if(Vm(t)){const r=Fm(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,ze])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:xo(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]===Ue?Ue:a,l=Object.keys(this.channels),u=l.length===1&&l[0]===Ue?Ue:l,h=this._interrupt,d=new Dm({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,ai,vi(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,ai,vi(),{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 Fm(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Us(r);return e}var Dm=class extends tl{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([Ue,l]);return c}else if(a!=null)return[[Ue,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]===Ue?r:o,trace:!1,recurse:!1})}];if(t===F)this.nodes[t]=new kn({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&&Ue in c,u=`branch:to:${t}`;this.channels[u]=e?.defer?new hp:new rn(!1),this.nodes[t]=new kn({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 $m(new Set(t)):new Im(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=>Hp.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===Gs)return eo(s(r))})();if(Y(t)){const n=t;return t.update&&e!=null&&(n.update=Xe(e,t.update)),n}return e!=null?Xe(e,t):t}isInterrupted(t){return Nc(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return fe(e)&&Xe(e,t),t}};function Um(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||kc(e))}function wi(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function Vm(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Bm(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function zm(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Hm(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 Wm(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 xc(r);me(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function vi(){const t=new wt({func:Wm,tags:[q],trace:!1,recurse:!1,name:"<control_branch>"});return new el({path:t})}const sl="__remove_all__";function ol(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(bn),o=r.map(bn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=hr(),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=hr(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===sl&&(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))}Ds.Root({messages:Ds({reducer:ol,default:()=>[]})});const kr={reducer:{fn:ol},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:on(ce(),kr)});ap();const Js=Symbol.for("langgraph-zod");Js in globalThis||(globalThis[Js]=new WeakSet);function _i(t){const e=globalThis[Js];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return on(n,{jsonSchemaExtra:r})},reducer(r,s){const o=Qs(n);return on(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{_i(Gu.prototype),_i(Vl.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 qm=class extends Bl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Qs(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new qm(sn);function Km(t=!0,e,n=[]){const r={messages:on(ce(),kr),jumpTo:Ie([xt("model_request"),xt("tools"),xt("end"),Ju()]).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=to().optional());const o=z(r);return sn.getChannelsForSchema(o)}z({llmInputMessages:on(ce(),{reducer:{fn:(t,e)=>kr.reducer.fn([],e)},default:()=>[]}),messages:on(ce(),kr)});const bi="prompt",ms=/<name>(.*?)<\/name>/s,gs=/<content>(.*?)<\/content>/s;function Gm(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 Jm(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(ms),o=r.text.match(gs);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(ms),o=r.text.match(gs);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(ms),o=r.match(gs);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 Si(t){return oo(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const ys=(t,e,n={})=>{if(Si(t))return t.bindTools(e,n);if(Oe.isRunnableBinding(t)&&Si(t.bound)){const r=t.bound.bindTools(e,n);return Oe.isRunnableBinding(r)?new Oe({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Oe({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function il(t){if(typeof t=="function")return;let e=t;if(rt.isRunnableSequence(e)&&(e=e.steps.find(n=>Oe.isRunnableBinding(n))||e),!gr(e)){if(Oe.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 Ts}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new Ts}}function Ys(t){return!!(N.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Ym(t){let e;if(t==null)e=Xt.from(n=>n.messages).withConfig({runName:bi});else if(typeof t=="string"){const n=new be(t);e=Xt.from(r=>[n,...r.messages??[]]).withConfig({runName:bi})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function Xm(t,e,n={}){const r=ys(t,e,n);if(r)return r;if(gr(t)){const s=ys(await t._model(),e,n);if(s)return s}if(rt.isRunnableSequence(t)){const s=t.steps.findIndex(o=>Oe.isRunnableBinding(o)||oo(o)||gr(o));if(s>=0){const o=ys(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),rt.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Zm(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 Qm(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Zm(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?Xe(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 eg(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=Yu(r.stateSchema,a=>a.startsWith("_")),o=await Xu(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
137
|
`);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
|
|
138
138
|
${i}
|
|
139
139
|
|
|
@@ -152,9 +152,9 @@ To fix this, either:
|
|
|
152
152
|
agent.invoke({
|
|
153
153
|
messages: [...],
|
|
154
154
|
${o.error.issues[0]?.path.join(".")}: "value"
|
|
155
|
-
})`)}return n}function
|
|
156
|
-
Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var
|
|
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:al(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 sh?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(sg(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(cl(t))o=t;else if(rg(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=>ag(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 ag(t){return t instanceof se}var cg=class{},lg=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=Xe(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 lg,{...s,context:Object.freeze(Object.assign(new cg,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Je(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Je(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Je(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Je(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:eg(this.middleware.stateSchema)}}},ug=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)}},hg=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)}},dg=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)}},fg=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)}},pg=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}},mg=class{#e;#n="v2";#s;#t=new pg;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"&&il(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=qm(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new jm(s,this.options.contextSchema),a=[],c=[],l=[],u=[],h=[];this.#s=new ng({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 ug(v,{getState:()=>this.#t.getState(v.name)}),this.#t.addNode(v,_);const S=`${v.name}.before_agent`;a.push({index:y,name:S,allowed:Je(v.beforeAgent)}),i.addNode(S,_,_.nodeOptions)}if(v.beforeModel){w=new hg(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:Je(v.beforeModel)}),i.addNode(S,w,w.nodeOptions)}if(v.afterModel){E=new dg(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:Je(v.afterModel)}),i.addNode(S,E,E.nodeOptions)}if(v.afterAgent){T=new fg(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:Je(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 ig(n.filter(H),{signal:this.options.signal,wrapToolCall:Zm(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=>Re(M)).filter(M=>M!=="tools"||v),k=Array.from(new Set([T,...S.map(M=>M===O?b:M)]));i.addConditionalEdges(w,this.#l(n.filter(H),T,b),k)}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=>Re(M)).filter(M=>M!=="tools"||v),k=Array.from(new Set([T,...S]));i.addConditionalEdges(w,this.#u(n.filter(H),T),k)}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(k=>Re(k)).filter(k=>k!=="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(k=>Re(k)).filter(k=>k!=="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=>Re(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=>Re(s)));return s=>{if(s.jumpTo){const o=Re(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=Re(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=Re(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 Qm(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 ll(t){return new mg(t)}const hr=`<role>
|
|
155
|
+
})`)}return n}function tg(t){const e={messages:ce(()=>[]),structuredResponse:to().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 Re(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 al(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var Ao=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=De(this.config,e),r=await Ve.runWithConfig(n,async()=>this.func(t,n));return Q.isRunnable(r)&&this.recurse?await Ve.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function ng(t,e){let n,r;if(e==="inline")n=Gm,r=Jm;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return rt.from([Xt.from(s),t,Xt.from(r)])}var rg=class extends Ao{#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 qe).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=>{il(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=al(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?Xe(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?Xe(eo(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 xs(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 xs))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&&Ys(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:bs(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 Xm(t,o,{...r,...e?.modelSettings??{},tool_choice:i});return Ym(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?ng(a,this.#e.includeAgentName):a)}getState(){const t=super.getState(),e=t&&!(t instanceof K)?t:{};return{messages:[],...e}}};const cl=t=>Array.isArray(t)&&t.every(gn.isInstance),sg=t=>typeof t=="object"&&t!=null&&"messages"in t&&cl(t.messages),og=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function ig(t,e){return t instanceof so?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 ag=class extends Ao{tools;trace=!1;signal;handleToolErrors=ig;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:al(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 Zu?new so(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(og(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(cl(t))o=t;else if(sg(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=>cg(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 cg(t){return t instanceof se}var lg=class{},ug=class{},Fr=class extends Ao{#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=Xe(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 ug,{...s,context:Object.freeze(Object.assign(new lg,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Je(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Je(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Je(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Je(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:tg(this.middleware.stateSchema)}}},hg=class extends Fr{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 Rr(this.middleware.beforeAgent)(t,e)}},dg=class extends Fr{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 Rr(this.middleware.beforeModel)(t,e)}},fg=class extends Fr{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 Rr(this.middleware.afterModel)(t,e)}},pg=class extends Fr{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 Rr(this.middleware.afterAgent)(t,e)}},mg=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}},gg=class{#e;#n="v2";#s;#t=new mg;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"&&il(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=Km(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new Lm(s,this.options.contextSchema),a=[],c=[],l=[],u=[],h=[];this.#s=new rg({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 hg(v,{getState:()=>this.#t.getState(v.name)}),this.#t.addNode(v,_);const S=`${v.name}.before_agent`;a.push({index:y,name:S,allowed:Je(v.beforeAgent)}),i.addNode(S,_,_.nodeOptions)}if(v.beforeModel){w=new dg(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:Je(v.beforeModel)}),i.addNode(S,w,w.nodeOptions)}if(v.afterModel){E=new fg(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:Je(v.afterModel)}),i.addNode(S,E,E.nodeOptions)}if(v.afterAgent){T=new pg(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:Je(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 ag(n.filter(H),{signal:this.options.signal,wrapToolCall:Qm(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=>Re(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=>Re(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=>Re(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=>Re(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=>Re(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=>Re(s)));return s=>{if(s.jumpTo){const o=Re(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=Re(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=Re(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 eg(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 ll(t){return new gg(t)}const lr=`<role>
|
|
158
158
|
Context Extraction Assistant
|
|
159
159
|
</role>
|
|
160
160
|
|
|
@@ -180,13 +180,13 @@ Respond ONLY with the extracted context. Do not include any additional informati
|
|
|
180
180
|
<messages>
|
|
181
181
|
Messages to summarize:
|
|
182
182
|
{messages}
|
|
183
|
-
</messages>`,
|
|
183
|
+
</messages>`,Mr=20,yg=4e3,Ci=5,wg=dr().args(He(ce())).returns(Ie([V(),Hi(V())])),Ar=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"}),ul=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"}),Ei=z({model:ce(),trigger:Ie([Ar,He(Ar)]).optional(),keep:ul.optional(),tokenCounter:wg.optional(),summaryPrompt:ne().default(lr),trimTokensToSummarize:V().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:V().optional(),messagesToKeep:V().optional()});function Po(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 fu(n)}catch{}}function vg(t){const{data:e,error:n}=Qu(Ei,t);if(n)throw new Error(`Invalid summarization middleware options: ${ji(n)}`);return ge({name:"SummarizationMiddleware",contextSchema:Ei.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===Mr)&&(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:Mr},l=ul.parse(c);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(x=>Ar.parse(x)):u=[Ar.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&&!Po(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context.summaryPrompt===lr?e.summaryPrompt??lr:s.context.summaryPrompt??e.summaryPrompt??lr,g=s.context.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??yg;_g(r.messages);const p=s.context.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??io,b=await p(r.messages);if(!await Cg(r.messages,b,u,d))return;const{systemPrompt:y,conversationMessages:_}=bg(r.messages),w=await Eg(_,l,p,d);if(w<=0)return;const{messagesToSummarize:E,preservedMessages:T}=Sg(y,_,w),v=await Mg(E,d,f,p,g),S=new pe({content:`Here is a summary of the conversation to date:
|
|
184
184
|
|
|
185
|
-
${v}`,id:
|
|
185
|
+
${v}`,id:hr()});return{messages:[new qn({id:sl}),S,...T]}}})}function _g(t){for(const e of t)e.id||(e.id=hr())}function bg(t){return t.length>0&&be.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Sg(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function Cg(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=Po(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 Eg(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Tg(t,e,n,r);return typeof s=="number"?s:Ti(t,Mr)}return Ti(t,e.messages??Mr)}async function Tg(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const u=Po(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(hl(t,u))return u;return 0}function Ti(t,e){if(t.length<=e)return 0;const n=t.length-e;for(let r=n;r>=0;r--)if(hl(t,r))return r;return 0}function hl(t,e){if(e>=t.length)return!0;if(e<t.length&&N.isInstance(t[e])&&Ys(t[e]))return!1;const n=Math.max(0,e-Ci),r=Math.min(t.length,e+Ci);for(let s=n;s<r;s++){if(!Ys(t[s]))continue;const o=xg(t[s]);if(kg(t,s,e,o))return!1}return!0}function xg(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 kg(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 Mg(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const o=await Ag(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 Ag(t,e,n){if(n===void 0)return t;try{return await Wi(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const Pg=dr().args(ce(),ce(),ce()).returns(Ie([ne(),Hi(ne())])),dl=["approve","edit","reject"],Og=Qt(dl),Ng=z({allowedDecisions:He(Og),description:Ie([ne(),Pg]).optional(),argsSchema:Sn(to()).optional()}),xi=z({interruptOn:Sn(Ie([fr(),Ng])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function Ig(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
186
|
|
|
187
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:
|
|
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
|
|
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:xi,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=Xe(xi,{...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:[...dl]}):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 Vc({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 $g=!0,Rg="5m",jg=3,Lg="warn",Fg=z({enableCaching:fr().optional(),ttl:Qt(["5m","1h"]).optional(),minMessagesToCache:V().optional(),unsupportedModelBehavior:Qt(["ignore","warn","raise"]).optional()});var ki=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function Dg(t){return ge({name:"PromptCachingMiddleware",contextSchema:Fg,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??$g,s=e.runtime.context.ttl??t?.ttl??Rg,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??jg,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??Lg;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 ki(`${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 ki("Last message content is not a string or array")}})}function Ug(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 Vg="Your goal is to select the most relevant tools for answering the user's query.";function Bg(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=Ie(e);return z({tools:He(n).describe("Tools to use. Place the most relevant tools first.")})}const zg=z({model:ne().or(pr(pu)).optional(),systemPrompt:ne().optional(),maxTools:V().optional(),alwaysInclude:He(ne()).optional()});function Hg(t){return ge({name:"LLMToolSelector",contextSchema:zg,async wrapModelCall(e,n){const r=await Wg(e,t,e.runtime);if(!r)return n(e);const s=Bg(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(qg(i,r.availableTools,r.validToolNames,e,t))}})}async function Wg(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??Vg;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 qg(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 Kg=z({rules:Sn(ne(),pr(RegExp).describe("Regular expression pattern to match PII")).optional()});function Gg(){return Math.random().toString(36).substring(2,11)}function ws(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=Gg();return n[c]=a,`[REDACTED_${i}_${c}]`})}return r}async function Jg(t,e){if(pe.isInstance(t)||U.isInstance(t)||be.isInstance(t)){const n=t.content,r=await ws(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 ws(n,e.rules,e.redactionMap),o=await ws(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 vn(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 Mi(t,e){if(pe.isInstance(t)||U.isInstance(t)||be.isInstance(t)){const n=t.content,r=vn(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=vn(n,e),o=vn(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 Yg(t={}){const e={};return ge({name:"PIIRedactionMiddleware",contextSchema:Kg,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=>Jg(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}=Mi(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(vn(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}=Mi(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(vn(JSON.stringify(h),e)):void 0;if(i||u)return{...n,...d?{structuredResponse:d}:{},messages:[new qn({id:s.id}),new qn({id:r.id}),l,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new qn({id:r.id}),o]}}})}const Xg="[cleared]";var fl=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??Xg}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 Zg(t={}){const e=t.edits??[new fl],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"?io: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 Qg(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const ey=["continue","error","end"],pl="continue";function ml(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 gl=Qt(ey).default(pl);var yl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=ml(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:gl});const ty=z({threadToolCallCount:Sn(ne(),V()).default({}),runToolCallCount:Sn(ne(),V()).default({})}),ny="__all__";function ry(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??pl,n=gl.safeParse(e);if(!n.success)throw new Error(ji(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:ty,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??ny,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 yl(w,C,t.threadLimit,t.runLimit,t.toolName)}const y=Qg(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=ml(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 sy=`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
190
|
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
191
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
192
|
|
|
@@ -410,25 +410,25 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
|
|
|
410
410
|
|
|
411
411
|
## Important To-Do List Usage Notes to Remember
|
|
412
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.`,
|
|
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.`,oy=Qt(["pending","in_progress","completed"]).describe("Status of the todo"),vl=z({content:ne().describe("Content of the todo item"),status:oy}),iy=z({todos:He(vl).default([])});function ay(t){const e=Di(({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??sy,schema:z({todos:He(vl).describe("List of todo items to update")})});return ge({name:"todoListMiddleware",stateSchema:iy,tools:[e],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
|
|
414
414
|
|
|
415
|
-
`:"")+(t?.systemPrompt??wl)})})}const
|
|
415
|
+
`:"")+(t?.systemPrompt??wl)})})}const cy="end",ly=z({threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:Qt(["throw","end"]).optional()}),uy=z({threadModelCallCount:V().default(0),runModelCallCount:V().default(0)});var Ai=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 _l(t){return ge({name:"ModelCallLimitMiddleware",contextSchema:ly,stateSchema:uy,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??cy,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 Ai({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 Ai({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 hy(...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 dy(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 Pi=z({maxRetries:V().min(0).default(2),tools:He(Ie([ce(),ce(),ne()])).optional(),retryOn:Ie([dr().args(pr(Error)).returns(fr()),He(ce())]).default(()=>()=>!0),onFailure:Ie([xt("raise"),xt("return_message"),dr().args(pr(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:fr().default(!0)});function fy(t={}){const{maxRetries:e,tools:n,retryOn:r,onFailure:s,backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:c}=Pi.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:Pi,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=dy(d,_);v>0&&await cd(v)}else return g(C,y,T,E)}throw new Error("Unexpected: retry loop completed without returning")}})}var py={};sa(py,{AIMessage:()=>N,AIMessageChunk:()=>Yt,BaseMessage:()=>gn,BaseMessageChunk:()=>sh,ClearToolUsesEdit:()=>fl,Document:()=>Be,DynamicStructuredTool:()=>Wn,DynamicTool:()=>Kl,FakeToolCallingModel:()=>op,HumanMessage:()=>pe,HumanMessageChunk:()=>rh,InMemoryStore:()=>va,MultipleStructuredOutputsError:()=>xs,MultipleToolsBoundError:()=>Ts,ProviderStrategy:()=>lt,StructuredOutputParsingError:()=>ca,StructuredTool:()=>Nr,SystemMessage:()=>be,SystemMessageChunk:()=>nh,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>wl,Tool:()=>ql,ToolCallLimitExceededError:()=>yl,ToolInvocationError:()=>so,ToolMessage:()=>U,ToolMessageChunk:()=>th,ToolStrategy:()=>qe,anthropicPromptCachingMiddleware:()=>Dg,contextEditingMiddleware:()=>Zg,countTokensApproximately:()=>io,createAgent:()=>ll,createMiddleware:()=>ge,dynamicSystemPromptMiddleware:()=>Ug,filterMessages:()=>eh,humanInTheLoopMiddleware:()=>Ig,initChatModel:()=>cn,llmToolSelectorMiddleware:()=>Hg,modelCallLimitMiddleware:()=>_l,modelFallbackMiddleware:()=>hy,piiRedactionMiddleware:()=>Yg,providerStrategy:()=>id,summarizationMiddleware:()=>vg,todoListMiddleware:()=>ay,tool:()=>Di,toolCallLimitMiddleware:()=>ry,toolRetryMiddleware:()=>fy,toolStrategy:()=>od,trimMessages:()=>Wi});var bl={},Dt,Dr=(Dt=class extends Nr{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),my=we({}),Ut,gy=(Ut=class extends Dr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=my;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,yy=(Vt=class extends Nr{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:Or().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
416
|
|
|
417
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),
|
|
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),wy=we({serverName:Or().describe("The name of the MCP server.")}),Bt,vy=(Bt=class extends Dr{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=wy;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),_y=we({}),zt,by=(zt=class extends Dr{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=_y;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
419
|
`)}catch(i){m.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
|
|
420
|
-
`)}},A(zt,"ListMCPServersTool"),zt),by=we({}),Ht,Sy=(Ht=class extends Vr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=by;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 gy(this),new _y(this),new wy(this),new my(this),new Sy(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-N7gq8lpA.js");return{langfuseHandler:s,langfuseInitPromise:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Jt(async()=>{const{initializeLangfuse:o}=await import("./langfuse-74RGPTAH-N7gq8lpA.js");return{initializeLangfuse:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));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),Cy="/api/v1/chats",Ey="/api/v1/chats/{chat_id}/execute";function Sl(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(Sl,"normalizeRemoteRunOptions");var Kt,Cl=(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??bl.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}${Cy}`;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}=Sl(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}${Ey.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:
|
|
420
|
+
`)}},A(zt,"ListMCPServersTool"),zt),Sy=we({}),Ht,Cy=(Ht=class extends Dr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Sy;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 Pr(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)=>Pr(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)&&Pr(t[s],e[s]))}return!1}A(Pr,"isEqual");var Wt,Oi=(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||!Pr(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 yy(this),new by(this),new vy(this),new gy(this),new Cy(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,Ni=(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 Promise.resolve().then(()=>Ii);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Jt(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>Ii);return{initializeLangfuse:o}},void 0);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),Ey="/api/v1/chats",Ty="/api/v1/chats/{chat_id}/execute";function Sl(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(Sl,"normalizeRemoteRunOptions");var Kt,xy=(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??bl.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 Hn(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}${Ey}`;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}=Sl(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}${Ty.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
421
|
• Invalid agent configuration (LLM model, system prompt)
|
|
422
422
|
• Missing or invalid MCP server configurations
|
|
423
423
|
• Network connectivity issues with MCP servers
|
|
424
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),
|
|
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),Pn={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 Oo(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 Pn)){const o=Object.keys(Pn).join(", ");throw new Error(`Unsupported LLM provider '${n}'. Supported providers: ${o}`)}return{provider:s,model:r}}A(Oo,"parseLLMString");function Cl(t,e){if(e?.apiKey)return e.apiKey;const n=Pn[t];for(const s of n.envVars){const o=bl[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 El(t,e){m.info(`Creating LLM from string: ${t}`);const{provider:n,model:r}=Oo(t),s=Pn[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(El,"createLLMFromString");function ky(t){try{return Oo(t),!0}catch{return!1}}A(ky,"isValidLLMString");function My(){return Object.keys(Pn)}A(My,"getSupportedProviders");function Tl(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(Tl,"generateToolDescriptions");function xl(t,e,n){const r=e.join(`
|
|
426
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
427
|
|
|
428
428
|
Available tools:
|
|
429
429
|
${r}`),n&&(s+=`
|
|
430
430
|
|
|
431
|
-
${n}`),s}A(
|
|
431
|
+
${n}`),s}A(xl,"buildSystemPromptContent");function kl(t,e,n,r,s,o,i){if(o)return new be({content:o});const a=r?n:e,c=Tl(t,s),l=xl(a,c,i);return new be({content:l})}A(kl,"createSystemMessage");var Ay=`You are a helpful AI assistant.
|
|
432
432
|
You have access to the following tools:
|
|
433
433
|
|
|
434
434
|
{tool_descriptions}
|
|
@@ -442,7 +442,7 @@ Action Input: the input to the action
|
|
|
442
442
|
Observation: the result of the action
|
|
443
443
|
... (this Thought/Action/Action Input/Observation can repeat N times)
|
|
444
444
|
Thought: I now know the final answer
|
|
445
|
-
Final Answer: the final answer to the original input question`,
|
|
445
|
+
Final Answer: the final answer to the original input question`,Py=`You are a helpful assistant designed to interact with MCP
|
|
446
446
|
(Model Context Protocol) servers. You can manage connections to different servers and use the tools
|
|
447
447
|
provided by the currently active server.
|
|
448
448
|
|
|
@@ -465,9 +465,9 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
465
465
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
466
466
|
change when you connect to a server):
|
|
467
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,xy=(Gt=class{static getPackageVersion(){return eo()}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 Cl({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 Zh({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??Ty;this.systemMessage=Al(e,n,ky,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=[_l({runLimit:this.maxSteps})],s=ll({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(k=>k.name)),S=new Set(this._tools.map(k=>k.name));(v.size!==S.size||[...v].some(k=>!S.has(k)))&&(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 k of S){for(const[M,P]of Object.entries(k))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 Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),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,Me=new Set(Se.map(un=>un.name)),Ln=new Set(this._tools.map(un=>un.name));if(Me.size!==Ln.size||[...Me].some(un=>!Ln.has(un))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].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-BqXf1TEf.js");return{prettyStreamEvents:c}},__vite__mapDeps([11,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 k=S.data.chunk;if(k.content){C||(C="");const M=this._normalizeOutput(k.content);C+=M,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!C){const k=S.data.output;Array.isArray(k)&&k.length>0&&k[0]?.text?C=k[0].text:typeof k=="string"?C=k:k&&typeof k=="object"&&"output"in k&&(C=k.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let S=!1,k=null,M=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(S=!0,k=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;k&&(yield{event:"on_structured_output",data:{output:k}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(k)}`)),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(`
|
|
468
|
+
`;function ur(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(ur,"normalizeRunOptions");var Gt,qy=(Gt=class{static getPackageVersion(){return $i()}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 xy({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=Br.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Ni({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=Br.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 Oi(this.client,this.adapter)}else this.adapter=e.adapter??new vt(this.disallowedTools);if(this.telemetry=Br.getInstance(),this.llm){const[r,s]=$o(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Ni({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 Zh({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")),this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await El(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=$o(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 Oi(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??Ay;this.systemMessage=kl(e,n,Py,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=[_l({runLimit:this.maxSteps})],s=ll({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}=ur(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}=ur(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 Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),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,Me=new Set(Se.map(un=>un.name)),jn=new Set(this._tools.map(un=>un.name));if(Me.size!==jn.size||[...Me].some(un=>!jn.has(un))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].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-CfCBjcIF.js");return{prettyStreamEvents:c}},__vite__mapDeps([0,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=ur(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
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(
|
|
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(Hn(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=Hn(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
471
|
Please format the following information according to the EXACT schema specified below.
|
|
472
472
|
You must use the exact field names and types as shown in the schema.
|
|
473
473
|
|
|
@@ -489,7 +489,7 @@ Here are the tools *currently* available to you (this list includes server manag
|
|
|
489
489
|
PREVIOUS ATTEMPT FAILED with error: ${d}
|
|
490
490
|
Please fix the issues mentioned above and ensure the output matches the schema exactly.
|
|
491
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=
|
|
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=Hn(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
|
|
493
493
|
${e}
|
|
494
494
|
|
|
495
495
|
IMPORTANT: Your response must include sufficient information to populate the following structured output:
|
|
@@ -498,4 +498,4 @@ ${g}`);const b=await s.stream(g);let C=null,y=0;for await(const w of b){if(y++,m
|
|
|
498
498
|
|
|
499
499
|
Make sure you gather ALL the required information during your task execution.
|
|
500
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={},
|
|
501
|
+
`}catch(r){return m.warn(`Could not extract schema details: ${r}`),e}}},A(Gt,"MCPAgent"),Gt),X={},Oy=X.MCP_USE_LANGFUSE?.toLowerCase()==="false",On={handler:null,client:null,initPromise:null};async function No(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)),On.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;On.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(No,"initializeLangfuse");Oy?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"):On.initPromise=No();var Ny=A(()=>On.handler,"langfuseHandler"),Iy=A(()=>On.initPromise,"langfuseInitPromise");const Ii=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:No,langfuseHandler:Ny,langfuseInitPromise:Iy},Symbol.toStringTag,{value:"Module"}));export{Qh as BaseAdapter,Ri as BaseConnector,Jy as BrowserOAuthClientProvider,Nl as BrowserTelemetry,$l as HttpConnector,Yy as Logger,qy as MCPAgent,Xy as MCPClient,Il as MCPSession,Ni as ObservabilityManager,xy as RemoteAgent,Nl as Tel,Br as Telemetry,Zy as VERSION,El as createLLMFromString,yh as createReadableStreamFromGenerator,$i as getPackageVersion,My as getSupportedProviders,ky as isValidLLMString,m as logger,Qy as onMcpAuthorization,Oo as parseLLMString,ew as setBrowserTelemetrySource,tw as setTelemetrySource,gh as streamEventsToAISDK,wh as streamEventsToAISDKWithTools};
|