@mcp-use/inspector 0.14.6 → 0.15.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/client/components/ui/badge.d.ts +4 -2
  2. package/dist/client/components/ui/badge.d.ts.map +1 -1
  3. package/dist/client/components/ui/button.d.ts +5 -2
  4. package/dist/client/components/ui/button.d.ts.map +1 -1
  5. package/dist/client/components/ui/checkbox.d.ts +1 -1
  6. package/dist/client/components/ui/checkbox.d.ts.map +1 -1
  7. package/dist/client/components/ui/command.d.ts +6 -6
  8. package/dist/client/components/ui/dropdown-menu.d.ts +6 -6
  9. package/dist/client/components/ui/dropdown-menu.d.ts.map +1 -1
  10. package/dist/client/components/ui/popover.d.ts +3 -3
  11. package/dist/client/components/ui/popover.d.ts.map +1 -1
  12. package/dist/client/components/ui/shimmer-button.d.ts.map +1 -1
  13. package/dist/client/index.js +8 -11
  14. package/dist/web/assets/{browser-CuuCFEmm.js → browser-BiosB35b.js} +55 -55
  15. package/dist/web/assets/{client-DQIxf_-5.js → client-D1IJiNmS.js} +1 -1
  16. package/dist/web/assets/{display-A5IEINAP-BJTIyc8Q.js → display-A5IEINAP-Do8oS54J.js} +2 -2
  17. package/dist/web/assets/{embeddings-BAQ5E5rq.js → embeddings-C5q2tZ5G.js} +1 -1
  18. package/dist/web/assets/{index-DXSSgw-c.js → index-8zz2f-kP.js} +123 -123
  19. package/dist/web/assets/{index-B3cB9iGY.js → index-BEgiBywX.js} +1 -1
  20. package/dist/web/assets/{index-DcRK73Zl.js → index-BMqss1BC.js} +1 -1
  21. package/dist/web/assets/{index-CjtkuJC9.js → index-BZFKAvKL.js} +1 -1
  22. package/dist/web/assets/{index-DoCBreOO.js → index-Bl_SD_Xk.js} +1 -1
  23. package/dist/web/assets/{index-BH85Uo_1.js → index-CC_s1InY.js} +1 -1
  24. package/dist/web/assets/{index-C-gSpTEe.js → index-D8a3mdcb.js} +1 -1
  25. package/dist/web/assets/{index-CYcqvRTi.js → index-Dp3iVZb1.js} +1 -1
  26. package/dist/web/assets/{index-Dkgjqqsw.js → index-cnkEhkHG.js} +1 -1
  27. package/dist/web/assets/index-dY4py1HD.css +1 -0
  28. package/dist/web/assets/{llms-Bhh0xPrn.js → llms-Dszbti5W.js} +1 -1
  29. package/dist/web/index.html +3 -3
  30. package/package.json +3 -3
  31. package/dist/web/assets/index-DlhqMiEp.css +0 -1
@@ -1,54 +1,54 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-DQIxf_-5.js","assets/index-DXSSgw-c.js","assets/index-DlhqMiEp.css","assets/display-A5IEINAP-BJTIyc8Q.js"])))=>i.map(i=>d[i]);
2
- import{bV as vo,bW as lc,bX as cc,_ as $,bw as ve,bq as y,bB as kr,bY as ke,bZ as Nr,bH as $r,by as uc,bD as hc,bx as dc,b_ as fc,b$ as pc,c0 as mc,p as Ds,bo as gc,c1 as Rr,c2 as bo,a as Ht,bI as Vn}from"./index-DXSSgw-c.js";import{bj as cy,c3 as uy,bp as hy,bs as dy,c4 as fy,c5 as py,br as my,bp as gy,c6 as yy,c7 as wy,c8 as vy,c8 as by}from"./index-DXSSgw-c.js";import{D as Bn,S as Er,t as yc,a as hi,T as wc,b as vc}from"./index-CYcqvRTi.js";import{h as xn,s as di,g as fi,d as bc,k as _c,l as Sc,I as Cc,C as Tc,m as kc,t as Ec,n as xc,o as Mc,p as Ac,q as Pc,r as Ic,u as Oc,v as Nc,w as $c,x as Rc,y as jc,R as Lc,z as _o,e as Dc}from"./index-Dkgjqqsw.js";import{aT as Fc,aU as Fs,aV as Uc,aw as $e,e as sn,aW as Vc,aX as fn,a4 as ge,y as xe,aY as pi,i as mi,B as I,f as j,aZ as as,g as q,aj as en,ah as ee,S as re,p as Bc,C as zc,a_ as Wc,u as So,aE as gi,a$ as te,al as pn,b0 as cn,F as yi,z as De,b1 as Us,D as ls,E as Gt,ap as lr,b2 as Hc,b3 as Gc,b4 as Kc,b5 as Jc,b6 as qc,b7 as Yc,b8 as Xc,b9 as Zc,ba as Qc,bb as eu,bc as tu,bd as nu,be as ru,bf as su,bg as ou,bh as iu,bi as au,bj as lu,bk as cu,L as uu,bl as hu,bm as du,bn as fu,A as ze,k as un,m as Ve,M as st,at as Kt,bo as pu,H as mu,aF as Co,au as gu,bp as To,bq as ko,af as Vs,ae as cs,ad as us,ag as yu,V as wu,a9 as Bs,ac as et,br as cr,o as B,bs as Se,bt as vu,bu as Ae,bv as Re,bw as bu,U as jr,s as Q,bx as zs,aa as _u,r as Su,ax as Cu,T as Tu,by as Mn,bz as wi,bA as Jt,bB as mn,bC as Ge,bD as ft,bE as V,ab as ku,bF as zn,ai as Eu,bG as vi,bH as An,bI as xu,aP as Mu,aN as Au,aM as Pu,bJ as Iu}from"./index-CjtkuJC9.js";import{E as bi,c as Ou,e as Nu}from"./embeddings-BAQ5E5rq.js";import{L as _i,o as $u,l as Ru}from"./llms-Bhh0xPrn.js";const ju=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Lu=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${ju(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${lc(r.values[0])}`:`Invalid option: expected one of ${vo(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",o=e(r.origin);return o?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",o=e(r.origin);return o?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${o.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${vo(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Du(){return{localeError:Lu()}}cc(Du());var Lr,$n,Dr=0,Fr=0;function Fu(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=Lr),i==null&&(i=$n)),o==null||i==null){var a=t.random||(t.rng||Fc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Lr&&!t._v6&&(o[0]|=1,Lr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,$n===void 0&&!t._v6&&($n=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Fr+1,u=l-Dr+(c-Fr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Dr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Dr=l,Fr=c,$n=i,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/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||Fs(s)}function Uu(t){var e=typeof t=="string"?Uc(t):t,n=Vu(e);return typeof t=="string"?Fs(n):n}function Vu(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 Eo(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 xo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Eo(Object(n),!0).forEach(function(r){Bu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Eo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Bu(t,e,n){return(e=zu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function zu(t){var e=Wu(t,"string");return typeof e=="symbol"?e:e+""}function Wu(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 Hu(t={},e,n=0){var r=Fu(xo(xo({},t),{},{_v6:!0}),new Uint8Array(16));return r=Uu(r),Fs(r)}async function*Gu(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)}}$(Gu,"streamEventsToAISDK");function Ku(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}$(Ku,"createReadableStreamFromGenerator");async function*Ju(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`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-D1IJiNmS.js","assets/index-8zz2f-kP.js","assets/index-dY4py1HD.css","assets/display-A5IEINAP-Do8oS54J.js"])))=>i.map(i=>d[i]);
2
+ import{bV as _o,bW as uc,bX as hc,_ as $,bw as be,bq as y,bB as Er,bY as ke,bZ as $r,bH as Rr,by as dc,bD as fc,bx as pc,b_ as mc,b$ as gc,c0 as yc,p as Fs,bo as wc,c1 as jr,c2 as So,a as Kt,bI as Bn}from"./index-8zz2f-kP.js";import{bj as hy,c3 as dy,bp as fy,bs as py,c4 as my,c5 as gy,br as yy,bp as wy,c6 as vy,c7 as by,c8 as _y,c8 as Sy}from"./index-8zz2f-kP.js";import{D as zn,S as xr,t as vc,a as fi,T as bc,b as _c}from"./index-Dp3iVZb1.js";import{h as An,s as pi,g as mi,d as Sc,k as Cc,l as Tc,I as kc,C as Ec,m as xc,t as Mc,n as Ac,o as Pc,p as Ic,q as Oc,r as Nc,u as $c,v as Rc,w as jc,x as Lc,y as Dc,R as Fc,z as Co,e as Uc}from"./index-cnkEhkHG.js";import{aT as Vc,aU as Us,aV as Bc,aw as $e,e as an,aW as zc,aX as mn,a4 as ye,y as xe,aY as gi,i as yi,B as P,f as j,aZ as ls,g as Y,aj as nn,ah as te,S as se,p as Wc,C as Hc,a_ as Gc,u as To,aE as wi,a$ as ne,al as gn,b0 as hn,F as vi,z as De,b1 as Vs,D as cs,E as Jt,ap as cr,b2 as Kc,b3 as Jc,b4 as qc,b5 as Yc,b6 as Xc,b7 as Zc,b8 as Qc,b9 as eu,ba as tu,bb as nu,bc as ru,bd as su,be as ou,bf as iu,bg as au,bh as lu,bi as cu,bj as uu,bk as hu,L as du,bl as fu,bm as pu,bn as mu,A as ze,k as dn,m as Ve,M as ot,at as qt,bo as gu,H as yu,aF as ko,au as wu,bp as Eo,bq as xo,af as Bs,ae as us,ad as hs,ag as vu,V as bu,a9 as zs,ac as tt,br as ur,o as z,bs as Ce,bt as _u,bu as Ae,bv as Re,bw as Su,U as Lr,s as ee,bx as Ws,aa as Cu,r as Tu,ax as ku,T as Eu,by as Pn,bz as bi,bA as Yt,bB as yn,bC as Ge,bD as mt,bE as B,ab as xu,bF as Wn,ai as Mu,bG as _i,bH as In,bI as Au,aP as Pu,aN as Iu,aM as Ou,bJ as Nu}from"./index-BZFKAvKL.js";import{E as Si,c as $u,e as Ru}from"./embeddings-C5q2tZ5G.js";import{L as Ci,o as ju,l as Lu}from"./llms-Dszbti5W.js";const Du=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Fu=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${Du(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${uc(r.values[0])}`:`Invalid option: expected one of ${_o(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",o=e(r.origin);return o?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",o=e(r.origin);return o?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${o.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${_o(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Uu(){return{localeError:Fu()}}hc(Uu());var Dr,Rn,Fr=0,Ur=0;function Vu(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=Dr),i==null&&(i=Rn)),o==null||i==null){var a=t.random||(t.rng||Vc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Dr&&!t._v6&&(o[0]|=1,Dr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Rn===void 0&&!t._v6&&(Rn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ur+1,u=l-Fr+(c-Ur)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Fr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Fr=l,Ur=c,Rn=i,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/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||Us(s)}function Bu(t){var e=typeof t=="string"?Bc(t):t,n=zu(e);return typeof t=="string"?Us(n):n}function zu(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 Mo(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 Ao(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Mo(Object(n),!0).forEach(function(r){Wu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Mo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Wu(t,e,n){return(e=Hu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Hu(t){var e=Gu(t,"string");return typeof e=="symbol"?e:e+""}function Gu(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 Ku(t={},e,n=0){var r=Vu(Ao(Ao({},t),{},{_v6:!0}),new Uint8Array(16));return r=Bu(r),Us(r)}async function*Ju(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)}}$(Ju,"streamEventsToAISDK");function qu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}$(qu,"createReadableStreamFromGenerator");async function*Yu(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}}$(Ju,"streamEventsToAISDKWithTools");var Ot,qu=(Ot=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)&&(y.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 y.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),y.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 y.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)}y.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.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)}y.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.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 y.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 y.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){y.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return y.error(`Error initializing connector: ${n}`),!1}}return!0}},$(Ot,"BaseAdapter"),Ot),Nt,Yu=(Nt=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:Nr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Nr.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:Nr.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 $r(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):ke();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return uc();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=hc();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=kr();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 $r(o)}const n=e.items?this.parseSchema(e.items):ke(),r=dc(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,ve(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 l=this.applyDefaultValues(i,e);this.matchesCondition(l,r)?this.validateConditionalSchema(l,s,a):o&&this.validateConditionalSchema(l,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=ve(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 ke();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(fc()):n.push(this.parseSchema(r));return n.length>=2?$r(n):n.length===1?n[0]:ke()}static parseAllOf(e){if(e.length===0)return ke();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}},$(Nt,"JSONSchemaToZod"),Nt);function Si(t){try{return Yu.convert(t)}catch(e){return y.warn(`Failed to convert JSON schema to Zod: ${e}`),ke()}}$(Si,"schemaToZod");var $t,St=($t=class extends qu{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?Si(e.inputSchema):ve({}).optional();return new Bn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:$(async o=>{y.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 y.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=$(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Bn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:ve({}).optional(),func:$(async()=>{y.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(l=>typeof l=="string"?l:l.text?l.text:l.uri?l.uri:JSON.stringify(l)).join(`
7
- `):"Resource is empty or unavailable"}catch(a){return y.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=ve({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=kr();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?ve(o):ve({}).optional()}return new Bn({name:e.name,description:e.description||"",schema:r,func:$(async o=>{y.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(`
8
- `):"Prompt returned no messages"}catch(i){return y.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},$($t,"LangChainAdapter"),$t),Xu=Object.defineProperty,Ci=(t,e)=>{for(var n in e)Xu(t,n,{get:e[n],enumerable:!0})},Zu={};Ci(Zu,{ConfigurableModel:()=>hs,MODEL_PROVIDER_CONFIG:()=>xr,_inferModelProvider:()=>Ei,getChatModelByClassName:()=>ki,initChatModel:()=>it});const xr={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}},Ti=Object.keys(xr);async function ki(t){const e=Object.entries(xr).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&&typeof s.message=="string"){const i=(s.message.startsWith("Error: ")?s.message.slice(7):s.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${i}. Please install with \`npm install ${i}\` or \`pnpm install ${i}\``)}throw r}}async function Qu(t,e,n={}){const r=e||Ei(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=xr[r];if(!s){const l=Ti.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
9
-
10
- Supported model providers are: ${l}`)}const{modelProvider:o,...i}=n,a=await ki(s.className);return new a({model:t,...i})}function Ei(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 hs=class Wn extends xn{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;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,this._profile=e.profile??void 0}async _getModelInstance(e){const n=JSON.stringify(e??{}),r=this._modelInstanceCache.get(n);if(r)return r;const s={...this._defaultConfig,...this._modelParams(e)};let o=await Qu(s.model,s.modelProvider,s);for(const[i,a]of Object.entries(this._queuedMethodOperations))i in o&&typeof o[i]=="function"&&(o=await o[i](...a));return this._modelInstanceCache.set(n,o),o}async _generate(e,n,r){return(await this._getModelInstance(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new Wn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new Wn({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 Wn({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new $e({config:n,bound:o})}async invoke(e,n){const r=await this._getModelInstance(n),s=sn(n);return r.invoke(e,s)}async stream(e,n){const r=await this._getModelInstance(n),s=new Vc({generator:await r.stream(e,n),config:n});return await s.setup,fn.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._getModelInstance(n),s=sn(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._getModelInstance(n),o=sn(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._getModelInstance(n),a=sn(n),l=i.streamEvents(e,a,r);for await(const c of l)yield c}return fn.fromAsyncGenerator(o())}get profile(){if(this._profile)return this._profile;const e=JSON.stringify({});return this._modelInstanceCache.get(e)?.profile??{}}};async function it(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,profile:o,...i}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[u,...h]=t.split(":"),d=h.length===0?[u]:[u,h.join(":")];Ti.includes(d[0])&&([s,t]=d)}let a=Array.isArray(n)?[...n]:n;!t&&a===void 0&&(a=["model","modelProvider"]),r&&a===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 l={...i};let c;return a===void 0?c=new hs({defaultConfig:{...l,model:t,modelProvider:s},configPrefix:r,profile:o}):(t&&(l.model=t),s&&(l.modelProvider=s),c=new hs({defaultConfig:l,configPrefix:r,configurableFields:a,profile:o})),await c._getModelInstance(),c}var ds=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.")}},fs=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}},xi=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
11
- - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},Ws=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}
12
- Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function Hs(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function ur(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}const Mo=!0;let eh=0;var Je=class ps{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-${++eh}`}if(mi(e)){const a=xe(e),l={type:"function",function:{name:r(a.title),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new ps(a,l,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 ps(o,i,n)}parse(e){const r=new pi(this.schema).validate(e);if(!r.valid)throw new xi(this.name,r.errors.map(s=>s.error));return e}},Xe=class Mi{_schemaType;schema;strict;constructor(e,n){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){const r=e;this.schema=r.schema,this.strict=r.strict??Mo}else this.schema=e,this.strict=n??Mo}static fromSchema(e,n){const r=xe(e);return new Mi(r,n)}parse(e){let n;if(typeof e.content=="string")n=e.content;else if(Array.isArray(e.content)){for(const r of e.content)if(typeof r=="object"&&r!==null&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"){n=r.text;break}}if(!(!n||n===""))try{const r=JSON.parse(n);return new pi(this.schema).validate(r).valid?r:void 0}catch{}}};function Ai(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 Je||s instanceof Xe))return t;if(t.every(s=>ge(s)))return t.map(s=>Je.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!ge(s)))return t.map(s=>Je.fromSchema(s,e));throw new Error(`Invalid response format: list contains mixed types.
13
- All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof Je||t instanceof Xe)return[t];const r=Pi(n);if(ge(t))return r?[Xe.fromSchema(t)]:[Je.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[Xe.fromSchema(t)]:[Je.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function th(t,e){return Ai(t,e)}function nh(t){if(typeof t=="object"&&t!==null&&"schema"in t&&!mi(t)&&!("type"in t)){const{schema:e,strict:n}=t;return Xe.fromSchema(e,n)}return Xe.fromSchema(t)}const rh=["ChatOpenAI","ChatXAI"],Ao=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function Pi(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return Ao.some(r=>n.includes(r))}if(ur(t))return Pi(t._defaultConfig.model);if(!Hs(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||rh.includes(e)&&("model"in t&&Ao.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Gs(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="",I.isInstance(n)&&Array.isArray(n.tool_calls)&&n.tool_calls.length>0&&(r+=JSON.stringify(n.tool_calls)),j.isInstance(n)&&(r+=n.tool_call_id??""),e+=r.length}return Math.ceil(e/4)}function Ze(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Mr(t){return typeof t=="function"?t:t.hook}function Ii(t){return new Promise(e=>setTimeout(e,t))}function Oi(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 Ni=Symbol("AgentMiddleware");function se(t){return{[Ni]:!0,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 $i(t){return Hu({clockseq:t})}function kt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return as(t,new Uint8Array(n))}const sh="__error__",Hn="__scheduled__",oh="__interrupt__",ih="__resume__";var Po="[...]",ah="[Circular]",hr=[],Et=[];function lh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function ch(t,e,n,r){typeof r>"u"&&(r=lh()),ms(t,"",0,[],void 0,0,r);var s;try{Et.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,uh(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;hr.length!==0;){var o=hr.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function Ur(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),hr.push([r,n,e,s])):Et.push([e,n,t]):(r[n]=t,hr.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){Ur(ah,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){Ur(Po,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Ur(Po,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 l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];ms(t[c],c,a,r,t,o,i)}}r.pop()}}function uh(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Et.length>0)for(var r=0;r<Et.length;r++){var s=Et[r];if(s[1]===e&&s[0]===n){n=s[2],Et.splice(r,1);break}}return t.call(this,e,n)}}const hh=[];var dh={},Ri={};q(Ri,{BaseChatMessageHistory:()=>ji,BaseListChatMessageHistory:()=>Ks,InMemoryChatMessageHistory:()=>fh});var ji=class extends en{async addMessages(t){for(const e of t)await this.addMessage(e)}},Ks=class extends en{addUserMessage(t){return this.addMessage(new ee(t))}addAIMessage(t){return this.addMessage(new I(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},fh=class extends Ks{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=[]}},ph={},Li={};q(Li,{BaseMemory:()=>mh,getInputValue:()=>gh,getOutputValue:()=>yh,getPromptInputKey:()=>wh});var mh=class{};const Di=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},gh=(t,e)=>{const n=Di(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},yh=(t,e)=>{const n=Di(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 wh(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 Fi={};q(Fi,{BaseStore:()=>Ui,InMemoryStore:()=>Vi});var Ui=class extends en{},Vi=class extends Ui{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)}},Bi={};q(Bi,{BaseRetriever:()=>Js});var Js=class extends re{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=sn(Bc(e)),s=await(await zc.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}}},zi={};q(zi,{SaveableVectorStore:()=>vh,VectorStore:()=>qs,VectorStoreRetriever:()=>Gn});var Gn=class extends Js{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)}},qs=class extends en{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 Gn({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 Gn({...i,searchKwargs:t.searchKwargs}):new Gn({...i})}}},vh=class extends qs{static load(t,e){throw new Error("Not implemented")}},Wi={};q(Wi,{BaseDocumentLoader:()=>Hi});var Hi=class{},Gi={};q(Gi,{LangSmithLoader:()=>bh});var bh=class extends Hi{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 Wc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??_h,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 _h(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var We=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},Ki=class extends re{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Sh=class extends Ki{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},Ji={};q(Ji,{BaseDocumentTransformer:()=>Ki,Document:()=>We,MappingDocumentTransformer:()=>Sh});var Ys=class extends en{lc_namespace=["langchain_core","example_selectors","base"]},qi=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Ch=class extends qi{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 Th(t){return t._modelType()==="base_llm"}function kh(t){return t._modelType()==="base_chat_model"}function Io(t){return t.split(/\n| /).length}var Eh=class Yi extends Ys{examples=[];examplePrompt;getTextLength=Io;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Io}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 Yi(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Vr(t){return Object.keys(t).sort().map(e=>t[e])}var xh=class Xi extends Ys{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=Vr(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new We({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Vr(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,l)=>({...a,[l]:i[l]}),{})):o}static async fromExamples(e,n,r,s={}){const o=s.inputKeys??null,i=e.map(l=>Vr(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new Xi({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Zi={};q(Zi,{BaseExampleSelector:()=>Ys,BasePromptSelector:()=>qi,ConditionalPromptSelector:()=>Ch,LengthBasedExampleSelector:()=>Eh,SemanticSimilarityExampleSelector:()=>xh,isChatModel:()=>kh,isLLM:()=>Th});const gs="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Mh=class extends en{lc_namespace=["langchain","recordmanagers"]},Qi=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=di;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 We({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 as(e,gs)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return as(n,gs)}};function ea(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 ta(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 na(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 Ah(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:o=100,cleanup:i,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!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=na(a??null),d=await n.getTime();let f=0,p=0,m=0,S=0;const C=ea(o??100,u);for(const E of C){const b=ta(E.map(T=>Qi.fromDocument(T))),w=b.map(T=>h(T));i==="incremental"&&b.forEach((T,M)=>{if(w[M]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const g=await n.exists(b.map(T=>T.uid)),k=[],_=[],v=[],x=new Set;if(b.forEach((T,M)=>{if(g[M])if(c)x.add(T.uid);else{v.push(T.uid);return}k.push(T.uid),_.push(T.toDocument())}),v.length>0&&(await n.update(v,{timeAtLeast:d}),S+=v.length),_.length>0&&(await r.addDocuments(_,{ids:k}),f+=_.length-x.size,m+=x.size),await n.update(b.map(T=>T.uid),{timeAtLeast:d,groupIds:w}),i==="incremental"){w.forEach(M=>{if(!M)throw new Error("Source id cannot be null")});const T=await n.listKeys({before:d,groupIds:w});T.length>0&&(await r.delete({ids:T}),await n.deleteKeys(T),p+=T.length)}}if(i==="full"){let E=await n.listKeys({before:d,limit:l});for(;E.length>0;)await r.delete({ids:E}),await n.deleteKeys(E),p+=E.length,E=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:p,numUpdated:m,numSkipped:S}}var sa={};q(sa,{RecordManager:()=>Mh,UUIDV5_NAMESPACE:()=>gs,_HashedDocument:()=>Qi,_batch:()=>ea,_deduplicateInOrder:()=>ta,_getSourceIdAssigner:()=>na,_isBaseDocumentLoader:()=>ra,index:()=>Ah});var Ph={},oa=class extends fi{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)}`)}},ia=class extends bc{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 oa(t)}_diff(t,e){return e?_c(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?So(r.arguments):{...r,arguments:So(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""}},Ih=class extends fi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new ia;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]}},aa={};q(aa,{JsonKeyOutputFunctionsParser:()=>Ih,JsonOutputFunctionsParser:()=>ia,OutputFunctionsParser:()=>oa});var Pn=class extends re{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"})}},gn=class extends Pn{async formatPromptValue(t){const e=await this.format(t);return new Sc(e)}};var Oh=Object.prototype.toString,tn=Array.isArray||function(e){return Oh.call(e)==="[object Array]"};function Xs(t){return typeof t=="function"}function Nh(t){return tn(t)?"array":typeof t}function Br(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Oo(t,e){return t!=null&&typeof t=="object"&&e in t}function $h(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Rh=RegExp.prototype.test;function jh(t,e){return Rh.call(t,e)}var Lh=/\S/;function Dh(t){return!jh(Lh,t)}var Fh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Uh(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Fh[n]})}var Vh=/\s*/,Bh=/\s+/,No=/\s*=/,zh=/\s*\}/,Wh=/#|\^|\/|>|\{|&|=|!/;function Hh(t,e){if(!t)return[];var n=!1,r=[],s=[],o=[],i=!1,a=!1,l="",c=0;function u(){if(i&&!a)for(;o.length;)delete s[o.pop()];else o=[];i=!1,a=!1}var h,d,f;function p(v){if(typeof v=="string"&&(v=v.split(Bh,2)),!tn(v)||v.length!==2)throw new Error("Invalid tags: "+v);h=new RegExp(Br(v[0])+"\\s*"),d=new RegExp("\\s*"+Br(v[1])),f=new RegExp("\\s*"+Br("}"+v[1]))}p(e||fe.tags);for(var m=new In(t),S,C,E,b,w,g;!m.eos();){if(S=m.pos,E=m.scanUntil(h),E)for(var k=0,_=E.length;k<_;++k)b=E.charAt(k),Dh(b)?(o.push(s.length),l+=b):(a=!0,n=!0,l+=" "),s.push(["text",b,S,S+1]),S+=1,b===`
14
- `&&(u(),l="",c=0,n=!1);if(!m.scan(h))break;if(i=!0,C=m.scan(Wh)||"name",m.scan(Vh),C==="="?(E=m.scanUntil(No),m.scan(No),m.scanUntil(d)):C==="{"?(E=m.scanUntil(f),m.scan(zh),m.scanUntil(d),C="&"):E=m.scanUntil(d),!m.scan(d))throw new Error("Unclosed tag at "+m.pos);if(C==">"?w=[C,E,S,m.pos,l,c,n]:w=[C,E,S,m.pos],c++,s.push(w),C==="#"||C==="^")r.push(w);else if(C==="/"){if(g=r.pop(),!g)throw new Error('Unopened section "'+E+'" at '+S);if(g[1]!==E)throw new Error('Unclosed section "'+g[1]+'" at '+S)}else C==="name"||C==="{"||C==="&"?a=!0:C==="="&&p(E)}if(u(),g=r.pop(),g)throw new Error('Unclosed section "'+g[1]+'" at '+m.pos);return Kh(Gh(s))}function Gh(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 Kh(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 In(t){this.string=t,this.tail=t,this.pos=0}In.prototype.eos=function(){return this.tail===""};In.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};In.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 qt(t,e){this.view=t,this.cache={".":this.view},this.parent=e}qt.prototype.push=function(e){return new qt(e,this)};qt.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,o,i,a,l=!1;s;){if(e.indexOf(".")>0)for(o=s.view,i=e.split("."),a=0;o!=null&&a<i.length;)a===i.length-1&&(l=Oo(o,i[a])||$h(o,i[a])),o=o[i[a++]];else o=s.view[e],l=Oo(s.view,e);if(l){r=o;break}s=s.parent}n[e]=r}return Xs(r)&&(r=r.call(this.view)),r};function ue(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}ue.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ue.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||fe.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=Hh(e,n),o&&r.set(s,i)),i};ue.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof qt?n:new qt(n,void 0);return this.renderTokens(i,a,r,e,s)};ue.prototype.renderTokens=function(e,n,r,s,o){for(var i="",a,l,c,u=0,h=e.length;u<h;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,s,o):l==="^"?c=this.renderInverted(a,n,r,s,o):l===">"?c=this.renderPartial(a,n,r,o):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,o):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(i+=c);return i};ue.prototype.renderSection=function(e,n,r,s,o){var i=this,a="",l=n.lookup(e[1]);function c(d){return i.render(d,n,r,o)}if(l){if(tn(l))for(var u=0,h=l.length;u<h;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,s,o);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,s,o);else if(Xs(l)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,s.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,s,o);return a}};ue.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||tn(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};ue.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
6
+ `;break}}$(Yu,"streamEventsToAISDKWithTools");var $t,Xu=($t=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)&&(y.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 y.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),y.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 y.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)}y.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.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)}y.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){y.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 y.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 y.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){y.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return y.error(`Error initializing connector: ${n}`),!1}}return!0}},$($t,"BaseAdapter"),$t),Rt,Zu=(Rt=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:$r.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:$r.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:$r.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 Rr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):ke();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return dc();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=fc();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=Er();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 Rr(o)}const n=e.items?this.parseSchema(e.items):ke(),r=pc(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,be(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 l=this.applyDefaultValues(i,e);this.matchesCondition(l,r)?this.validateConditionalSchema(l,s,a):o&&this.validateConditionalSchema(l,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=be(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 ke();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(mc()):n.push(this.parseSchema(r));return n.length>=2?Rr(n):n.length===1?n[0]:ke()}static parseAllOf(e){if(e.length===0)return ke();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}},$(Rt,"JSONSchemaToZod"),Rt);function Ti(t){try{return Zu.convert(t)}catch(e){return y.warn(`Failed to convert JSON schema to Zod: ${e}`),ke()}}$(Ti,"schemaToZod");var jt,Tt=(jt=class extends Xu{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?Ti(e.inputSchema):be({}).optional();return new zn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:$(async o=>{y.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 y.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=$(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new zn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:be({}).optional(),func:$(async()=>{y.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(l=>typeof l=="string"?l:l.text?l.text:l.uri?l.uri:JSON.stringify(l)).join(`
7
+ `):"Resource is empty or unavailable"}catch(a){return y.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=be({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=Er();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?be(o):be({}).optional()}return new zn({name:e.name,description:e.description||"",schema:r,func:$(async o=>{y.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(`
8
+ `):"Prompt returned no messages"}catch(i){return y.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},$(jt,"LangChainAdapter"),jt),Qu=Object.defineProperty,ki=(t,e)=>{for(var n in e)Qu(t,n,{get:e[n],enumerable:!0})},eh={};ki(eh,{ConfigurableModel:()=>ds,MODEL_PROVIDER_CONFIG:()=>Mr,_inferModelProvider:()=>Mi,getChatModelByClassName:()=>xi,initChatModel:()=>at});const Mr={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}},Ei=Object.keys(Mr);async function xi(t){const e=Object.entries(Mr).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&&typeof s.message=="string"){const i=(s.message.startsWith("Error: ")?s.message.slice(7):s.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${i}. Please install with \`npm install ${i}\` or \`pnpm install ${i}\``)}throw r}}async function th(t,e,n={}){const r=e||Mi(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=Mr[r];if(!s){const l=Ei.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
9
+
10
+ Supported model providers are: ${l}`)}const{modelProvider:o,...i}=n,a=await xi(s.className);return new a({model:t,...i})}function Mi(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 ds=class Hn extends An{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;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,this._profile=e.profile??void 0}async _getModelInstance(e){const n=JSON.stringify(e??{}),r=this._modelInstanceCache.get(n);if(r)return r;const s={...this._defaultConfig,...this._modelParams(e)};let o=await th(s.model,s.modelProvider,s);for(const[i,a]of Object.entries(this._queuedMethodOperations))i in o&&typeof o[i]=="function"&&(o=await o[i](...a));return this._modelInstanceCache.set(n,o),o}async _generate(e,n,r){return(await this._getModelInstance(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new Hn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new Hn({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 Hn({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new $e({config:n,bound:o})}async invoke(e,n){const r=await this._getModelInstance(n),s=an(n);return r.invoke(e,s)}async stream(e,n){const r=await this._getModelInstance(n),s=new zc({generator:await r.stream(e,n),config:n});return await s.setup,mn.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._getModelInstance(n),s=an(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._getModelInstance(n),o=an(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._getModelInstance(n),a=an(n),l=i.streamEvents(e,a,r);for await(const c of l)yield c}return mn.fromAsyncGenerator(o())}get profile(){if(this._profile)return this._profile;const e=JSON.stringify({});return this._modelInstanceCache.get(e)?.profile??{}}};async function at(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,profile:o,...i}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[u,...h]=t.split(":"),d=h.length===0?[u]:[u,h.join(":")];Ei.includes(d[0])&&([s,t]=d)}let a=Array.isArray(n)?[...n]:n;!t&&a===void 0&&(a=["model","modelProvider"]),r&&a===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 l={...i};let c;return a===void 0?c=new ds({defaultConfig:{...l,model:t,modelProvider:s},configPrefix:r,profile:o}):(t&&(l.model=t),s&&(l.modelProvider=s),c=new ds({defaultConfig:l,configPrefix:r,configurableFields:a,profile:o})),await c._getModelInstance(),c}var fs=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.")}},ps=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}},Ai=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
11
+ - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},Hs=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}
12
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function Gs(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function hr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}const Po=!0;let nh=0;var qe=class ms{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-${++nh}`}if(yi(e)){const a=xe(e),l={type:"function",function:{name:r(a.title),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new ms(a,l,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 ms(o,i,n)}parse(e){const r=new gi(this.schema).validate(e);if(!r.valid)throw new Ai(this.name,r.errors.map(s=>s.error));return e}},Ze=class Pi{_schemaType;schema;strict;constructor(e,n){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){const r=e;this.schema=r.schema,this.strict=r.strict??Po}else this.schema=e,this.strict=n??Po}static fromSchema(e,n){const r=xe(e);return new Pi(r,n)}parse(e){let n;if(typeof e.content=="string")n=e.content;else if(Array.isArray(e.content)){for(const r of e.content)if(typeof r=="object"&&r!==null&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"){n=r.text;break}}if(!(!n||n===""))try{const r=JSON.parse(n);return new gi(this.schema).validate(r).valid?r:void 0}catch{}}};function Ii(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 Ze))return t;if(t.every(s=>ye(s)))return t.map(s=>qe.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!ye(s)))return t.map(s=>qe.fromSchema(s,e));throw new Error(`Invalid response format: list contains mixed types.
13
+ All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof qe||t instanceof Ze)return[t];const r=Oi(n);if(ye(t))return r?[Ze.fromSchema(t)]:[qe.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[Ze.fromSchema(t)]:[qe.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function rh(t,e){return Ii(t,e)}function sh(t){if(typeof t=="object"&&t!==null&&"schema"in t&&!yi(t)&&!("type"in t)){const{schema:e,strict:n}=t;return Ze.fromSchema(e,n)}return Ze.fromSchema(t)}const oh=["ChatOpenAI","ChatXAI"],Io=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function Oi(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return Io.some(r=>n.includes(r))}if(hr(t))return Oi(t._defaultConfig.model);if(!Gs(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||oh.includes(e)&&("model"in t&&Io.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Ks(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="",P.isInstance(n)&&Array.isArray(n.tool_calls)&&n.tool_calls.length>0&&(r+=JSON.stringify(n.tool_calls)),j.isInstance(n)&&(r+=n.tool_call_id??""),e+=r.length}return Math.ceil(e/4)}function Qe(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Ar(t){return typeof t=="function"?t:t.hook}function Ni(t){return new Promise(e=>setTimeout(e,t))}function $i(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 Ri=Symbol("AgentMiddleware");function oe(t){return{[Ri]:!0,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 ji(t){return Ku({clockseq:t})}function xt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return ls(t,new Uint8Array(n))}const ih="__error__",Gn="__scheduled__",ah="__interrupt__",lh="__resume__";var Oo="[...]",ch="[Circular]",dr=[],Mt=[];function uh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function hh(t,e,n,r){typeof r>"u"&&(r=uh()),gs(t,"",0,[],void 0,0,r);var s;try{Mt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,dh(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;dr.length!==0;){var o=dr.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function Vr(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),dr.push([r,n,e,s])):Mt.push([e,n,t]):(r[n]=t,dr.push([r,n,e]))}function gs(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){Vr(ch,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){Vr(Oo,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Vr(Oo,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)gs(t[a],a,a,r,t,o,i);else{var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];gs(t[c],c,a,r,t,o,i)}}r.pop()}}function dh(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Mt.length>0)for(var r=0;r<Mt.length;r++){var s=Mt[r];if(s[1]===e&&s[0]===n){n=s[2],Mt.splice(r,1);break}}return t.call(this,e,n)}}const fh=[];var ph={},Li={};Y(Li,{BaseChatMessageHistory:()=>Di,BaseListChatMessageHistory:()=>Js,InMemoryChatMessageHistory:()=>mh});var Di=class extends nn{async addMessages(t){for(const e of t)await this.addMessage(e)}},Js=class extends nn{addUserMessage(t){return this.addMessage(new te(t))}addAIMessage(t){return this.addMessage(new P(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},mh=class extends Js{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=[]}},gh={},Fi={};Y(Fi,{BaseMemory:()=>yh,getInputValue:()=>wh,getOutputValue:()=>vh,getPromptInputKey:()=>bh});var yh=class{};const Ui=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},wh=(t,e)=>{const n=Ui(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},vh=(t,e)=>{const n=Ui(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 bh(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 Vi={};Y(Vi,{BaseStore:()=>Bi,InMemoryStore:()=>zi});var Bi=class extends nn{},zi=class extends Bi{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)}},Wi={};Y(Wi,{BaseRetriever:()=>qs});var qs=class extends se{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=an(Wc(e)),s=await(await Hc.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}}},Hi={};Y(Hi,{SaveableVectorStore:()=>_h,VectorStore:()=>Ys,VectorStoreRetriever:()=>Kn});var Kn=class extends qs{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)}},Ys=class extends nn{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 Kn({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 Kn({...i,searchKwargs:t.searchKwargs}):new Kn({...i})}}},_h=class extends Ys{static load(t,e){throw new Error("Not implemented")}},Gi={};Y(Gi,{BaseDocumentLoader:()=>Ki});var Ki=class{},Ji={};Y(Ji,{LangSmithLoader:()=>Sh});var Sh=class extends Ki{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 Gc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Ch,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 Ch(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var We=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},qi=class extends se{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Th=class extends qi{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},Yi={};Y(Yi,{BaseDocumentTransformer:()=>qi,Document:()=>We,MappingDocumentTransformer:()=>Th});var Xs=class extends nn{lc_namespace=["langchain_core","example_selectors","base"]},Xi=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},kh=class extends Xi{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 Eh(t){return t._modelType()==="base_llm"}function xh(t){return t._modelType()==="base_chat_model"}function No(t){return t.split(/\n| /).length}var Mh=class Zi extends Xs{examples=[];examplePrompt;getTextLength=No;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??No}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 Zi(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Br(t){return Object.keys(t).sort().map(e=>t[e])}var Ah=class Qi extends Xs{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=Br(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new We({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Br(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,l)=>({...a,[l]:i[l]}),{})):o}static async fromExamples(e,n,r,s={}){const o=s.inputKeys??null,i=e.map(l=>Br(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new Qi({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},ea={};Y(ea,{BaseExampleSelector:()=>Xs,BasePromptSelector:()=>Xi,ConditionalPromptSelector:()=>kh,LengthBasedExampleSelector:()=>Mh,SemanticSimilarityExampleSelector:()=>Ah,isChatModel:()=>xh,isLLM:()=>Eh});const ys="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Ph=class extends nn{lc_namespace=["langchain","recordmanagers"]},ta=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=pi;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 We({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 ls(e,ys)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return ls(n,ys)}};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 ra(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 sa(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 oa=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function Ih(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:o=100,cleanup:i,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!1}=s??{};if(i==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=oa(e)?await e.load():e,h=sa(a??null),d=await n.getTime();let f=0,p=0,m=0,C=0;const T=na(o??100,u);for(const k of T){const v=ra(k.map(b=>ta.fromDocument(b))),w=v.map(b=>h(b));i==="incremental"&&v.forEach((b,x)=>{if(w[x]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const g=await n.exists(v.map(b=>b.uid)),E=[],S=[],_=[],M=new Set;if(v.forEach((b,x)=>{if(g[x])if(c)M.add(b.uid);else{_.push(b.uid);return}E.push(b.uid),S.push(b.toDocument())}),_.length>0&&(await n.update(_,{timeAtLeast:d}),C+=_.length),S.length>0&&(await r.addDocuments(S,{ids:E}),f+=S.length-M.size,m+=M.size),await n.update(v.map(b=>b.uid),{timeAtLeast:d,groupIds:w}),i==="incremental"){w.forEach(x=>{if(!x)throw new Error("Source id cannot be null")});const b=await n.listKeys({before:d,groupIds:w});b.length>0&&(await r.delete({ids:b}),await n.deleteKeys(b),p+=b.length)}}if(i==="full"){let k=await n.listKeys({before:d,limit:l});for(;k.length>0;)await r.delete({ids:k}),await n.deleteKeys(k),p+=k.length,k=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:p,numUpdated:m,numSkipped:C}}var ia={};Y(ia,{RecordManager:()=>Ph,UUIDV5_NAMESPACE:()=>ys,_HashedDocument:()=>ta,_batch:()=>na,_deduplicateInOrder:()=>ra,_getSourceIdAssigner:()=>sa,_isBaseDocumentLoader:()=>oa,index:()=>Ih});var Oh={},aa=class extends mi{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)}`)}},la=class extends Sc{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 aa(t)}_diff(t,e){return e?Cc(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?To(r.arguments):{...r,arguments:To(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""}},Nh=class extends mi{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new la;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]}},ca={};Y(ca,{JsonKeyOutputFunctionsParser:()=>Nh,JsonOutputFunctionsParser:()=>la,OutputFunctionsParser:()=>aa});var On=class extends se{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"})}},wn=class extends On{async formatPromptValue(t){const e=await this.format(t);return new Tc(e)}};var $h=Object.prototype.toString,rn=Array.isArray||function(e){return $h.call(e)==="[object Array]"};function Zs(t){return typeof t=="function"}function Rh(t){return rn(t)?"array":typeof t}function zr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function $o(t,e){return t!=null&&typeof t=="object"&&e in t}function jh(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Lh=RegExp.prototype.test;function Dh(t,e){return Lh.call(t,e)}var Fh=/\S/;function Uh(t){return!Dh(Fh,t)}var Vh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Bh(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Vh[n]})}var zh=/\s*/,Wh=/\s+/,Ro=/\s*=/,Hh=/\s*\}/,Gh=/#|\^|\/|>|\{|&|=|!/;function Kh(t,e){if(!t)return[];var n=!1,r=[],s=[],o=[],i=!1,a=!1,l="",c=0;function u(){if(i&&!a)for(;o.length;)delete s[o.pop()];else o=[];i=!1,a=!1}var h,d,f;function p(_){if(typeof _=="string"&&(_=_.split(Wh,2)),!rn(_)||_.length!==2)throw new Error("Invalid tags: "+_);h=new RegExp(zr(_[0])+"\\s*"),d=new RegExp("\\s*"+zr(_[1])),f=new RegExp("\\s*"+zr("}"+_[1]))}p(e||fe.tags);for(var m=new Nn(t),C,T,k,v,w,g;!m.eos();){if(C=m.pos,k=m.scanUntil(h),k)for(var E=0,S=k.length;E<S;++E)v=k.charAt(E),Uh(v)?(o.push(s.length),l+=v):(a=!0,n=!0,l+=" "),s.push(["text",v,C,C+1]),C+=1,v===`
14
+ `&&(u(),l="",c=0,n=!1);if(!m.scan(h))break;if(i=!0,T=m.scan(Gh)||"name",m.scan(zh),T==="="?(k=m.scanUntil(Ro),m.scan(Ro),m.scanUntil(d)):T==="{"?(k=m.scanUntil(f),m.scan(Hh),m.scanUntil(d),T="&"):k=m.scanUntil(d),!m.scan(d))throw new Error("Unclosed tag at "+m.pos);if(T==">"?w=[T,k,C,m.pos,l,c,n]:w=[T,k,C,m.pos],c++,s.push(w),T==="#"||T==="^")r.push(w);else if(T==="/"){if(g=r.pop(),!g)throw new Error('Unopened section "'+k+'" at '+C);if(g[1]!==k)throw new Error('Unclosed section "'+g[1]+'" at '+C)}else T==="name"||T==="{"||T==="&"?a=!0:T==="="&&p(k)}if(u(),g=r.pop(),g)throw new Error('Unclosed section "'+g[1]+'" at '+m.pos);return qh(Jh(s))}function Jh(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 qh(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 Nn(t){this.string=t,this.tail=t,this.pos=0}Nn.prototype.eos=function(){return this.tail===""};Nn.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};Nn.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 Xt(t,e){this.view=t,this.cache={".":this.view},this.parent=e}Xt.prototype.push=function(e){return new Xt(e,this)};Xt.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var s=this,o,i,a,l=!1;s;){if(e.indexOf(".")>0)for(o=s.view,i=e.split("."),a=0;o!=null&&a<i.length;)a===i.length-1&&(l=$o(o,i[a])||jh(o,i[a])),o=o[i[a++]];else o=s.view[e],l=$o(s.view,e);if(l){r=o;break}s=s.parent}n[e]=r}return Zs(r)&&(r=r.call(this.view)),r};function ue(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}ue.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ue.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||fe.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=Kh(e,n),o&&r.set(s,i)),i};ue.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof Xt?n:new Xt(n,void 0);return this.renderTokens(i,a,r,e,s)};ue.prototype.renderTokens=function(e,n,r,s,o){for(var i="",a,l,c,u=0,h=e.length;u<h;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,s,o):l==="^"?c=this.renderInverted(a,n,r,s,o):l===">"?c=this.renderPartial(a,n,r,o):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,o):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(i+=c);return i};ue.prototype.renderSection=function(e,n,r,s,o){var i=this,a="",l=n.lookup(e[1]);function c(d){return i.render(d,n,r,o)}if(l){if(rn(l))for(var u=0,h=l.length;u<h;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,s,o);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,s,o);else if(Zs(l)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,s.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,s,o);return a}};ue.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||rn(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};ue.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
15
15
  `),i=0;i<o.length;i++)o[i].length&&(i>0||!r)&&(o[i]=s+o[i]);return o.join(`
16
- `)};ue.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=Xs(r)?r(e[1]):r[e[1]];if(i!=null){var a=e[6],l=e[5],c=e[4],u=i;l==0&&c&&(u=this.indentPartial(i,c,a));var h=this.parse(u,o);return this.renderTokens(h,n,r,u,s)}}};ue.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ue.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||fe.escape,o=n.lookup(e[1]);if(o!=null)return typeof o=="number"&&s===fe.escape?String(o):s(o)};ue.prototype.rawValue=function(e){return e[1]};ue.prototype.getConfigTags=function(e){return tn(e)?e:e&&typeof e=="object"?e.tags:void 0};ue.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!tn(e))return e.escape};var fe={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){yn.templateCache=t},get templateCache(){return yn.templateCache}},yn=new ue;fe.clearCache=function(){return yn.clearCache()};fe.parse=function(e,n){return yn.parse(e,n)};fe.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Nh(e)+'" was given as the first argument for mustache#render(template, view, partials)');return yn.render(e,n,r,s)};fe.escape=Uh;fe.Scanner=In;fe.Context=qt;fe.Writer=ue;function la(){fe.escape=t=>t}const wn=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},ca=(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=ca(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},dr=t=>{la();const e=fe.parse(t);return ca(e)},ua=(t,e)=>wn(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},""),ha=(t,e)=>(la(),fe.render(t,e)),fr={"f-string":ua,mustache:ha},da={"f-string":wn,mustache:dr},Me=(t,e,n)=>{try{return fr[e](t,n)}catch(r){throw gi(r,"INVALID_PROMPT_INPUT")}},pr=(t,e)=>da[e](t),On=(t,e,n)=>{if(!(e in fr)){const r=Object.keys(fr);throw new Error(`Invalid template format. Got \`${e}\`;
17
- should be one of ${r}`)}try{const r=Object.fromEntries(n.map(s=>[s,"foo"]));Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Me(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Me(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;Me(o,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Me(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var tt=class on extends gn{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))),On(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return Me(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
16
+ `)};ue.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=Zs(r)?r(e[1]):r[e[1]];if(i!=null){var a=e[6],l=e[5],c=e[4],u=i;l==0&&c&&(u=this.indentPartial(i,c,a));var h=this.parse(u,o);return this.renderTokens(h,n,r,u,s)}}};ue.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ue.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||fe.escape,o=n.lookup(e[1]);if(o!=null)return typeof o=="number"&&s===fe.escape?String(o):s(o)};ue.prototype.rawValue=function(e){return e[1]};ue.prototype.getConfigTags=function(e){return rn(e)?e:e&&typeof e=="object"?e.tags:void 0};ue.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!rn(e))return e.escape};var fe={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){vn.templateCache=t},get templateCache(){return vn.templateCache}},vn=new ue;fe.clearCache=function(){return vn.clearCache()};fe.parse=function(e,n){return vn.parse(e,n)};fe.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Rh(e)+'" was given as the first argument for mustache#render(template, view, partials)');return vn.render(e,n,r,s)};fe.escape=Bh;fe.Scanner=Nn;fe.Context=Xt;fe.Writer=ue;function ua(){fe.escape=t=>t}const bn=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},ha=(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=ha(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},fr=t=>{ua();const e=fe.parse(t);return ha(e)},da=(t,e)=>bn(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},""),fa=(t,e)=>(ua(),fe.render(t,e)),pr={"f-string":da,mustache:fa},pa={"f-string":bn,mustache:fr},Me=(t,e,n)=>{try{return pr[e](t,n)}catch(r){throw wi(r,"INVALID_PROMPT_INPUT")}},mr=(t,e)=>pa[e](t),$n=(t,e,n)=>{if(!(e in pr)){const r=Object.keys(pr);throw new Error(`Invalid template format. Got \`${e}\`;
17
+ should be one of ${r}`)}try{const r=Object.fromEntries(n.map(s=>[s,"foo"]));Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Me(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Me(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;Me(o,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Me(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var nt=class ln extends wn{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))),$n(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return Me(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
18
18
 
19
- `,o=""){const i=[o,...e,n].join(s);return new on({inputVariables:r,template:i})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},o=new Set;return pr(e,r).forEach(i=>{i.type==="variable"&&o.add(i.name)}),new on({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 on(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 on({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},Kn=class fa extends Pn{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))),On([{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 fa(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=Me(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 Cc(n)}},ys=class extends re{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=ws(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return vs(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function ws(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")pr(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?pr(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...ws(s,e));else typeof r=="object"&&r!==null&&n.push(...ws(r,e));return Array.from(new Set(n))}function vs(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=Me(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(Me(a,n,e)):typeof a=="object"&&i.push(vs(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=vs(o,e,n):r[s]=o;return r}var Ar=class extends re{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},bs=class extends Ar{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(pn):n=[pn(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(`
19
+ `,o=""){const i=[o,...e,n].join(s);return new ln({inputVariables:r,template:i})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},o=new Set;return mr(e,r).forEach(i=>{i.type==="variable"&&o.add(i.name)}),new ln({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 ln(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 ln({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},Jn=class ma extends On{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))),$n([{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 ma(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=Me(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 kc(n)}},ws=class extends se{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=vs(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return bs(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function vs(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")mr(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?mr(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...vs(s,e));else typeof r=="object"&&r!==null&&n.push(...vs(r,e));return Array.from(new Set(n))}function bs(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=Me(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(Me(a,n,e)):typeof a=="object"&&i.push(bs(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=bs(o,e,n):r[s]=o;return r}var Pr=class extends se{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},_s=class extends Pr{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(gn):n=[gn(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(`
20
20
 
21
- `));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},pa=class extends Ar{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)]}},Zs=class extends Pn{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Tc(e)}},ma=class extends pa{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 yi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(tt.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function Jh(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function qh(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 Qs=class extends Ar{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(tt.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(tt.fromTemplate(r,e));else if(r!==null)if(Jh(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(tt.fromTemplate(s,o))}else if(qh(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=dr(s):a=wn(s);const l=a.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
21
+ `));throw o.name="InputFormatError",o.lc_error_code=r.lc_error_code,o}return n}},ga=class extends Pr{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)]}},Qs=class extends On{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Ec(e)}},ya=class extends ga{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 vi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(nt.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function Yh(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Xh(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 eo=class extends Pr{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(nt.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(nt.fromTemplate(r,e));else if(r!==null)if(Yh(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(nt.fromTemplate(s,o))}else if(Xh(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=fr(s):a=bn(s);const l=a.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
22
22
  Got: ${l}
23
- From: ${s}`);i=[l[0]]}else i=[];s={url:s},o=new Kn({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=dr(s.url):a=wn(s.url),i=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else i=[];o=new Kn({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 ys({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof gn){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 gn){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 Kn){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 ys){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)]}},eo=class extends Qs{static _messageClass(){return ee}static lc_name(){return"HumanMessagePromptTemplate"}},ga=class extends Qs{static _messageClass(){return I}static lc_name(){return"AIMessagePromptTemplate"}},ya=class extends Qs{static _messageClass(){return te}static lc_name(){return"SystemMessagePromptTemplate"}};function Yh(t){return typeof t.formatMessages=="function"}function Xh(t,e){if(Yh(t)||De(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 bs({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new bs({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=pn(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 eo.fromTemplate(r,e);if(n._getType()==="ai")return ga.fromTemplate(r,e);if(n._getType()==="system")return ya.fromTemplate(r,e);if(yi.isInstance(n))return ma.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function Zh(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var to=class Jn extends Zs{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 cn))for(const l of a.inputVariables)n.add(l);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 tt.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 cn)r.push(await this._parseImagePrompts(s,n));else{let o;this.templateFormat==="mustache"?o={...n}:o=s.inputVariables.reduce((a,l)=>{if(!(l in n)&&!(Zh(s)&&s.optional))throw gi(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return a[l]=n[l],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 Jn(s)}static fromTemplate(e,n){const r=tt.fromTemplate(e,n),s=new eo({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof Jn?a.promptMessages:[Xh(a,n)]),[]),s=e.reduce((i,a)=>a instanceof Jn?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof cn))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})}},Qh=class _s extends gn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
23
+ From: ${s}`);i=[l[0]]}else i=[];s={url:s},o=new Jn({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=fr(s.url):a=bn(s.url),i=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else i=[];o=new Jn({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 ws({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof wn){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 wn){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 Jn){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 ws){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)]}},to=class extends eo{static _messageClass(){return te}static lc_name(){return"HumanMessagePromptTemplate"}},wa=class extends eo{static _messageClass(){return P}static lc_name(){return"AIMessagePromptTemplate"}},va=class extends eo{static _messageClass(){return ne}static lc_name(){return"SystemMessagePromptTemplate"}};function Zh(t){return typeof t.formatMessages=="function"}function Qh(t,e){if(Zh(t)||De(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 _s({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new _s({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=gn(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 to.fromTemplate(r,e);if(n._getType()==="ai")return wa.fromTemplate(r,e);if(n._getType()==="system")return va.fromTemplate(r,e);if(vi.isInstance(n))return ya.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function ed(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var no=class qn extends Qs{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 hn))for(const l of a.inputVariables)n.add(l);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 nt.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 hn)r.push(await this._parseImagePrompts(s,n));else{let o;this.templateFormat==="mustache"?o={...n}:o=s.inputVariables.reduce((a,l)=>{if(!(l in n)&&!(ed(s)&&s.optional))throw wi(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return a[l]=n[l],a},{});const i=await s.formatMessages(o);r=r.concat(i)}return r}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new qn(s)}static fromTemplate(e,n){const r=nt.fromTemplate(e,n),s=new to({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof qn?a.promptMessages:[Qh(a,n)]),[]),s=e.reduce((i,a)=>a instanceof qn?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof hn))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})}},td=class Ss extends wn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
24
24
 
25
- `;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))),On(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 Me(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 tt.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})}},ed=class wa extends Zs{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
25
+ `;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))),$n(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 Ss(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 Me(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 nt.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 Ss({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},nd=class ba extends Qs{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
26
26
 
27
27
  `;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??`
28
28
 
29
- `,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))),On(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 Me(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 wa(s)}},td=class qn extends Pn{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=qn.extractRequiredInputValues(n,s.inputVariables);s instanceof to?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return qn.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 qn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function $o(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function nd(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 rd=class va extends to{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($o(e))return super.pipe(e.withStructuredOutput(this.schema));if(nd(e)&&$o(e.bound))return super.pipe(new $e({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 va.fromMessages(e,{schema:n,method:r})}},ba={};q(ba,{AIMessagePromptTemplate:()=>ga,BaseChatPromptTemplate:()=>Zs,BaseMessagePromptTemplate:()=>Ar,BaseMessageStringPromptTemplate:()=>pa,BasePromptTemplate:()=>Pn,BaseStringPromptTemplate:()=>gn,ChatMessagePromptTemplate:()=>ma,ChatPromptTemplate:()=>to,DEFAULT_FORMATTER_MAPPING:()=>fr,DEFAULT_PARSER_MAPPING:()=>da,DictPromptTemplate:()=>ys,FewShotChatMessagePromptTemplate:()=>ed,FewShotPromptTemplate:()=>Qh,HumanMessagePromptTemplate:()=>eo,ImagePromptTemplate:()=>Kn,MessagesPlaceholder:()=>bs,PipelinePromptTemplate:()=>td,PromptTemplate:()=>tt,StructuredPrompt:()=>rd,SystemMessagePromptTemplate:()=>ya,checkValidTemplate:()=>On,interpolateFString:()=>ua,interpolateMustache:()=>ha,parseFString:()=>wn,parseMustache:()=>dr,parseTemplate:()=>pr,renderTemplate:()=>Me});var _a={};q(_a,{BaseDocumentCompressor:()=>sd});var sd=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const Qe={and:"and",or:"or",not:"not"},L={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var Sa=class{},no=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")}},ro=class extends no{},od=class extends ro{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},id=class extends ro{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},ad=class extends no{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function Ca(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Ee(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:Ca(t)&&Object.keys(t).length===0:!0}function Ta(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 ka(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 Ea(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function xa(t){return typeof t=="boolean"}function so(t){let e;if(Ea(t))e=t;else if(Ta(t))e=parseInt(t,10);else if(ka(t))e=parseFloat(t);else if(xa(t))e=!!t;else throw new Error("Unsupported value type");return e}var oo=class extends Sa{},ld=class extends oo{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Qe.and,Qe.or],this.allowedComparators=t?.allowedComparators??[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte]}formatFunction(t){if(t in L){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 Qe){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)]:so(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Ee(t)&&Ee(e))){if(Ee(t)||n==="replace")return Ee(e)?void 0:e;if(Ee(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")}}},cd=class extends oo{allowedOperators=[Qe.and,Qe.or];allowedComparators=[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case"number":return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case"boolean":return[L.eq,L.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case L.eq:return(e,n)=>e===n;case L.ne:return(e,n)=>e!==n;case L.gt:return(e,n)=>e>n;case L.gte:return(e,n)=>e>=n;case L.lt:return(e,n)=>e<n;case L.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case Qe.and:return(e,n)=>e&&n;case Qe.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=[L.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,so(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(!(Ee(t)&&Ee(e))){if(Ee(t)||n==="replace")return Ee(e)?void 0:e;if(Ee(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")}}},Ma={};q(Ma,{BaseTranslator:()=>oo,BasicTranslator:()=>ld,Comparators:()=>L,Comparison:()=>od,Expression:()=>no,FilterDirective:()=>ro,FunctionalTranslator:()=>cd,Operation:()=>id,Operators:()=>Qe,StructuredQuery:()=>ad,Visitor:()=>Sa,castValue:()=>so,isBoolean:()=>xa,isFilterEmpty:()=>Ee,isFloat:()=>ka,isInt:()=>Ta,isObject:()=>Ca,isString:()=>Ea});var Aa={};q(Aa,{RunCollectorCallbackHandler:()=>ud});var ud=class extends Us{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)}},hd={},Pa={};q(Pa,{context:()=>Ia});function Ia(t,...e){const n=t.raw;let r="";for(let s=0;s<n.length;s++){const o=n[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(r+=o,s<e.length){const i=dd(e[s],r);r+=typeof i=="string"?i:JSON.stringify(i)}}return r=fd(r),r=r.trim(),r=r.replace(/\\n/g,`
30
- `),r}function dd(t,e){if(typeof t!="string"||!t.includes(`
29
+ `,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))),$n(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 Me(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 ba(s)}},rd=class Yn extends On{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=Yn.extractRequiredInputValues(n,s.inputVariables);s instanceof no?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return Yn.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 Yn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function jo(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function sd(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 od=class _a extends no{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(jo(e))return super.pipe(e.withStructuredOutput(this.schema));if(sd(e)&&jo(e.bound))return super.pipe(new $e({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 _a.fromMessages(e,{schema:n,method:r})}},Sa={};Y(Sa,{AIMessagePromptTemplate:()=>wa,BaseChatPromptTemplate:()=>Qs,BaseMessagePromptTemplate:()=>Pr,BaseMessageStringPromptTemplate:()=>ga,BasePromptTemplate:()=>On,BaseStringPromptTemplate:()=>wn,ChatMessagePromptTemplate:()=>ya,ChatPromptTemplate:()=>no,DEFAULT_FORMATTER_MAPPING:()=>pr,DEFAULT_PARSER_MAPPING:()=>pa,DictPromptTemplate:()=>ws,FewShotChatMessagePromptTemplate:()=>nd,FewShotPromptTemplate:()=>td,HumanMessagePromptTemplate:()=>to,ImagePromptTemplate:()=>Jn,MessagesPlaceholder:()=>_s,PipelinePromptTemplate:()=>rd,PromptTemplate:()=>nt,StructuredPrompt:()=>od,SystemMessagePromptTemplate:()=>va,checkValidTemplate:()=>$n,interpolateFString:()=>da,interpolateMustache:()=>fa,parseFString:()=>bn,parseMustache:()=>fr,parseTemplate:()=>mr,renderTemplate:()=>Me});var Ca={};Y(Ca,{BaseDocumentCompressor:()=>id});var id=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const et={and:"and",or:"or",not:"not"},L={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var Ta=class{},ro=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")}},so=class extends ro{},ad=class extends so{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},ld=class extends so{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},cd=class extends ro{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function ka(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Ee(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:ka(t)&&Object.keys(t).length===0:!0}function Ea(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 xa(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 Ma(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function Aa(t){return typeof t=="boolean"}function oo(t){let e;if(Ma(t))e=t;else if(Ea(t))e=parseInt(t,10);else if(xa(t))e=parseFloat(t);else if(Aa(t))e=!!t;else throw new Error("Unsupported value type");return e}var io=class extends Ta{},ud=class extends io{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[et.and,et.or],this.allowedComparators=t?.allowedComparators??[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte]}formatFunction(t){if(t in L){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 et){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)]:oo(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Ee(t)&&Ee(e))){if(Ee(t)||n==="replace")return Ee(e)?void 0:e;if(Ee(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")}}},hd=class extends io{allowedOperators=[et.and,et.or];allowedComparators=[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case"number":return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case"boolean":return[L.eq,L.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case L.eq:return(e,n)=>e===n;case L.ne:return(e,n)=>e!==n;case L.gt:return(e,n)=>e>n;case L.gte:return(e,n)=>e>=n;case L.lt:return(e,n)=>e<n;case L.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case et.and:return(e,n)=>e&&n;case et.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=[L.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,oo(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(!(Ee(t)&&Ee(e))){if(Ee(t)||n==="replace")return Ee(e)?void 0:e;if(Ee(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")}}},Pa={};Y(Pa,{BaseTranslator:()=>io,BasicTranslator:()=>ud,Comparators:()=>L,Comparison:()=>ad,Expression:()=>ro,FilterDirective:()=>so,FunctionalTranslator:()=>hd,Operation:()=>ld,Operators:()=>et,StructuredQuery:()=>cd,Visitor:()=>Ta,castValue:()=>oo,isBoolean:()=>Aa,isFilterEmpty:()=>Ee,isFloat:()=>xa,isInt:()=>Ea,isObject:()=>ka,isString:()=>Ma});var Ia={};Y(Ia,{RunCollectorCallbackHandler:()=>dd});var dd=class extends Vs{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)}},fd={},Oa={};Y(Oa,{context:()=>Na});function Na(t,...e){const n=t.raw;let r="";for(let s=0;s<n.length;s++){const o=n[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(r+=o,s<e.length){const i=pd(e[s],r);r+=typeof i=="string"?i:JSON.stringify(i)}}return r=md(r),r=r.trim(),r=r.replace(/\\n/g,`
30
+ `),r}function pd(t,e){if(typeof t!="string"||!t.includes(`
31
31
  `))return t;const r=e.slice(e.lastIndexOf(`
32
32
  `)+1).match(/^(\s+)/);if(r){const s=r[1];return t.replace(/\n/g,`
33
- ${s}`)}return t}function fd(t){const e=t.split(`
33
+ ${s}`)}return t}function md(t){const e=t.split(`
34
34
  `);let n=null;for(const r of e){const s=r.match(/^(\s+)\S+/);if(s){const o=s[1].length;n===null?n=o:n=Math.min(n,o)}}return n===null?t:e.map(r=>r[0]===" "||r[0]===" "?r.slice(n):r).join(`
35
- `)}var Oa={};q(Oa,{EventStreamContentType:()=>pd,convertEventStreamToIterableReadableDataStream:()=>gd,getBytes:()=>Na,getLines:()=>$a,getMessages:()=>Ra});const pd="text/event-stream";async function Na(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(`
36
- `))}}var xt=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})(xt||{});function $a(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=md(e,i);const l=e.length;let c=0;for(;n<l;){s&&(e[n]===xt.NewLine&&(c=++n),s=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case xt.Colon:r===-1&&(r=n-c);break;case xt.CarriageReturn:s=!0;case xt.NewLine:u=n;break}if(u===-1)break;t(e.subarray(c,u),r),c=n,r=-1}c===l?e=void 0:c!==0&&(e=e.subarray(c),n-=c)}}function Ra(t,e,n){let r=zr();const s=new TextDecoder;return function(i,a,l){if(l){yd(r)||(t?.(r),r=zr());return}if(i.length===0)t?.(r),r=zr();else if(a>0){const c=s.decode(i.subarray(0,a)),u=a+(i[a+1]===xt.Space?2:1),h=s.decode(i.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
37
- `+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 md(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function zr(){return{data:"",event:"",id:"",retry:void 0}}function gd(t,e){const n=new ReadableStream({async start(r){const s=Ra(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 Na(t,$a((i,a,l)=>{s(i,a,l),l&&r.close()}))}});return fn.fromReadableStream(n)}function yd(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var wd={};function ja(t,e){let n=0,r=0,s=0;for(let o=0;o<t.length;o++)n+=t[o]*e[o],r+=t[o]*t[o],s+=e[o]*e[o];return n/(Math.sqrt(r)*Math.sqrt(s))}function vd(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function bd(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 _d(t,e){return Math.sqrt(bd(t,e))}var La={};q(La,{cosineSimilarity:()=>Ss,euclideanDistance:()=>Td,innerProduct:()=>Cd,matrixFunc:()=>Pr,maximalMarginalRelevance:()=>kd,normalize:()=>Sd});function Pr(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 Sd(t,e=!1){const n=Ed(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Ss(t,e){return Pr(t,e,ja)}function Cd(t,e){return Pr(t,e,vd)}function Td(t,e){return Pr(t,e,_d)}function kd(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=Ss(s,e)[0],i=Da(o).maxIndex,a=[e[i]],l=[i];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const h=Ss(e,a);o.forEach((d,f)=>{if(l.includes(f))return;const p=Math.max(...h[f]),m=n*d-(1-n)*p;m>c&&(c=m,u=f)}),a.push(e[u]),l.push(u)}return l}function Da(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 Ed(t){return t.reduce((e,n)=>Math.max(e,Da(n).maxValue),0)}var xd=class extends xn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new I(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(`
38
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new I(r),text:r}],llmOutput:{}}}},Md=class Fa extends xn{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 Fa({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 I({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 ls({message:new Gt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new I(typeof e[0].content=="string"?e[0].content:""),o=typeof s.content=="string"?s.content:"";for(const i of o){await new Promise(l=>setTimeout(l,this.sleep));const a=new ls({message:new Gt({content:i}),text:i});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},Ad=class Ua extends xn{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 I(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],l=i===o.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);const c=this._createResponseChunk(a,l?this.generationInfo:void 0);if(n.signal?.aborted)break;yield c,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 ls({message:new Gt({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 Ua({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 lr.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")})}},Pd=class extends bi{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 l=0;l<e.length;l+=o)i.push(e.slice(l,l+o));return i.map(l=>{let c=0;for(let h=0;h<l.length;h+=1)c+=l===" "?0:l.charCodeAt(h);return c%26/26})}},Id=class extends bi{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},Od=class extends _i{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}},Nd=class extends _i{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)}},$d=class extends ji{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 ee(t))}async addAIMessage(t){this.messages.push(new I(t))}async clear(){this.messages=[]}},Rd=class extends Ks{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},jd=class extends Us{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Ld=class extends kc{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Dd=class extends Js{lc_namespace=["test","fake"];output=[new We({pageContent:"foo"}),new We({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Fd=class extends re{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},Ud=class extends Er{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)}},Vd=class extends Us{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}},Bd=class Va extends qs{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??ja}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=l=>{if(!r)return!0;const c=new We({metadata:l.metadata,pageContent:l.content});return r(c)},o=this.memoryVectors.filter(s);return o.map((l,c)=>({similarity:this.similarity(e,l.embedding),index:c})).sort((l,c)=>l.similarity>c.similarity?-1:0).slice(0,n).map(l=>[new We({metadata:o[l.index].metadata,pageContent:o[l.index].content}),l.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,l=new We({pageContent:e[i],metadata:a});o.push(l)}return Va.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)}},Ba={};q(Ba,{FakeChatMessageHistory:()=>$d,FakeChatModel:()=>xd,FakeEmbeddings:()=>Id,FakeLLM:()=>Od,FakeListChatMessageHistory:()=>Rd,FakeListChatModel:()=>Ad,FakeRetriever:()=>Dd,FakeRunnable:()=>Fd,FakeSplitIntoListParser:()=>Ld,FakeStreamingChatModel:()=>Md,FakeStreamingLLM:()=>Nd,FakeTool:()=>Ud,FakeTracer:()=>jd,FakeVectorStore:()=>Bd,SingleRunExtractor:()=>Vd,SyntheticEmbeddings:()=>Pd});var za={};q(za,{agents:()=>dh,caches:()=>jc,callbacks__base:()=>au,callbacks__manager:()=>iu,callbacks__promises:()=>ou,chat_history:()=>Ri,document_loaders__base:()=>Wi,document_loaders__langsmith:()=>Gi,documents:()=>Ji,embeddings:()=>Nu,example_selectors:()=>Zi,index:()=>ph,indexing:()=>sa,language_models__base:()=>Rc,language_models__chat_models:()=>$c,language_models__llms:()=>Ru,language_models__profile:()=>Ph,load__serializable:()=>su,memory:()=>Li,messages:()=>ru,messages__tool:()=>nu,output_parsers:()=>Nc,output_parsers__openai_functions:()=>aa,output_parsers__openai_tools:()=>$u,outputs:()=>tu,prompt_values:()=>Oc,prompts:()=>ba,retrievers:()=>Bi,retrievers__document_compressors:()=>_a,runnables:()=>Ic,runnables__graph:()=>eu,singletons:()=>Qc,stores:()=>Fi,structured_query:()=>Ma,tools:()=>yc,tracers__base:()=>Zc,tracers__console:()=>Xc,tracers__log_stream:()=>Yc,tracers__run_collector:()=>Aa,tracers__tracer_langchain:()=>qc,types__stream:()=>hd,utils__async_caller:()=>Jc,utils__chunk_array:()=>Ou,utils__context:()=>Pa,utils__env:()=>Kc,utils__event_source_parse:()=>Oa,utils__format:()=>wd,utils__function_calling:()=>Pc,utils__hash:()=>Ac,utils__json_patch:()=>Mc,utils__json_schema:()=>Gc,utils__math:()=>La,utils__stream:()=>Hc,utils__testing:()=>Ba,utils__tiktoken:()=>xc,utils__types:()=>Ec,vectorstores:()=>zi});const zd=50;function Wd(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 Yn(t){const{optionalImportsMap:e,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:o,path:i,depth:a,maxDepth:l}=this,c=i.join(".");if(a>l)throw new Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((d,f)=>Yn.call({...this,path:[...i,`${f}`],depth:a+1},d)));const u=t;if(lu(u))return cu(u);if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="secret"){const d=u,[f]=d.id;if(f in s)return s[f];if(o){const p=uu(f);if(p)return p}throw new Error(`Missing secret "${f}" at ${c}`)}if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="not_implemented"){const f=JSON.stringify(u);throw new Error(`Trying to load an object that doesn't implement serialization: ${c} -> ${f}`)}if("lc"in u&&"type"in u&&"id"in u&&"kwargs"in u&&u.lc===1&&u.type==="constructor"){const d=u,f=JSON.stringify(d),[p,...m]=d.id.slice().reverse(),S=m.reverse(),C={langchain_core:za,langchain:r};let E=null;const b=[S.join("/")];S[0]==="langchain_community"&&b.push(["langchain",...S.slice(1)].join("/"));const w=b.find(v=>v in e);if(hh.concat(n).includes(S.join("/"))||w)if(w!==void 0)E=await e[w];else throw new Error(`Missing key "${S.join("/")}" for ${c} in load(optionalImportsMap={})`);else{let v;if(S[0]==="langchain"||S[0]==="langchain_core")v=C[S[0]],S.shift();else throw new Error(`Invalid namespace: ${c} -> ${f}`);if(S.length===0)throw new Error(`Invalid namespace: ${c} -> ${f}`);let x;do{if(x=S.join("__"),x in v)break;S.pop()}while(S.length>0);x in v&&(E=v[x])}if(typeof E!="object"||E===null)throw new Error(`Invalid namespace: ${c} -> ${f}`);const g=E[p]??Object.values(E).find(v=>typeof v=="function"&&hu(v)===p);if(typeof g!="function")throw new Error(`Invalid identifer: ${c} -> ${f}`);const k=await Yn.call({...this,path:[...i,"kwargs"],depth:a+1},d.kwargs),_=new g(du(k,fu,Wd(g)));return Object.defineProperty(_.constructor,"name",{value:p}),_}const h={};for(const[d,f]of Object.entries(u))h[d]=await Yn.call({...this,path:[...i,d],depth:a+1},f);return h}async function Hd(t,e){const n=JSON.parse(t),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:zd};return Yn.call(r,n)}function Gd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function Cs(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>Cs(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await Cs(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(Gd(e))return Hd(JSON.stringify(e));return e}}return t}function Wr(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function Kd(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Wr(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Wr(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Wr(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var Jd=class{_dumps(t){return new TextEncoder().encode(ch(t,(n,r)=>Kd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return Cs(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 Wa(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]=Wa(t[n]));return e}function Ha(){return{v:4,id:$i(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function mr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:Wa(t.versions_seen)}}function Ga(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function qd(...t){return t.reduce((e,n,r)=>r===0?n:Ga(e,n)>=0?e:n)}const Yd={[sh]:-1,[Hn]:-2,[oh]:-3,[ih]:-4};var rn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function Xd(t){if(t.length===0)throw new rn("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new rn(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new rn(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new rn(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new rn(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var Zd=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){Xd(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 Qd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var ef=class extends Zd{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=Qd(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]"}}},tf=class{serde=new Jd;constructor(t){this.serde=t||this.serde}},nf=class Ka extends xn{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 Ka({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new lr({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).map(h=>typeof h=="string"?h:typeof h=="object"&&"text"in h?h.text:Array.isArray(h)?h.map(d=>typeof d=="string"?d:typeof d=="object"&&"text"in d?d.text:"").join("-"):JSON.stringify(h)).join("-")),(e.length===1||e.length===2&&e.every(ee.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new I({content:o,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:o,message:c}],llmOutput:{}}}};class rf{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 sf(){ze.initializeGlobalInstance(new rf)}var vt=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
35
+ `)}var $a={};Y($a,{EventStreamContentType:()=>gd,convertEventStreamToIterableReadableDataStream:()=>wd,getBytes:()=>Ra,getLines:()=>ja,getMessages:()=>La});const gd="text/event-stream";async function Ra(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(`
36
+ `))}}var At=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})(At||{});function ja(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=yd(e,i);const l=e.length;let c=0;for(;n<l;){s&&(e[n]===At.NewLine&&(c=++n),s=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case At.Colon:r===-1&&(r=n-c);break;case At.CarriageReturn:s=!0;case At.NewLine:u=n;break}if(u===-1)break;t(e.subarray(c,u),r),c=n,r=-1}c===l?e=void 0:c!==0&&(e=e.subarray(c),n-=c)}}function La(t,e,n){let r=Wr();const s=new TextDecoder;return function(i,a,l){if(l){vd(r)||(t?.(r),r=Wr());return}if(i.length===0)t?.(r),r=Wr();else if(a>0){const c=s.decode(i.subarray(0,a)),u=a+(i[a+1]===At.Space?2:1),h=s.decode(i.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
37
+ `+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 yd(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function Wr(){return{data:"",event:"",id:"",retry:void 0}}function wd(t,e){const n=new ReadableStream({async start(r){const s=La(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 Ra(t,ja((i,a,l)=>{s(i,a,l),l&&r.close()}))}});return mn.fromReadableStream(n)}function vd(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var bd={};function Da(t,e){let n=0,r=0,s=0;for(let o=0;o<t.length;o++)n+=t[o]*e[o],r+=t[o]*t[o],s+=e[o]*e[o];return n/(Math.sqrt(r)*Math.sqrt(s))}function _d(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function Sd(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 Cd(t,e){return Math.sqrt(Sd(t,e))}var Fa={};Y(Fa,{cosineSimilarity:()=>Cs,euclideanDistance:()=>Ed,innerProduct:()=>kd,matrixFunc:()=>Ir,maximalMarginalRelevance:()=>xd,normalize:()=>Td});function Ir(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 Td(t,e=!1){const n=Md(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function Cs(t,e){return Ir(t,e,Da)}function kd(t,e){return Ir(t,e,_d)}function Ed(t,e){return Ir(t,e,Cd)}function xd(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=Cs(s,e)[0],i=Ua(o).maxIndex,a=[e[i]],l=[i];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const h=Cs(e,a);o.forEach((d,f)=>{if(l.includes(f))return;const p=Math.max(...h[f]),m=n*d-(1-n)*p;m>c&&(c=m,u=f)}),a.push(e[u]),l.push(u)}return l}function Ua(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 Md(t){return t.reduce((e,n)=>Math.max(e,Ua(n).maxValue),0)}var Ad=class extends An{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new P(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(`
38
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new P(r),text:r}],llmOutput:{}}}},Pd=class Va extends An{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 Va({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 P({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 cs({message:new Jt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new P(typeof e[0].content=="string"?e[0].content:""),o=typeof s.content=="string"?s.content:"";for(const i of o){await new Promise(l=>setTimeout(l,this.sleep));const a=new cs({message:new Jt({content:i}),text:i});if(n.signal?.aborted)break;yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},Id=class Ba extends An{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 P(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],l=i===o.length-1;if(await this._sleepIfRequested(),n?.thrownErrorString)throw new Error(n.thrownErrorString);const c=this._createResponseChunk(a,l?this.generationInfo:void 0);if(n.signal?.aborted)break;yield c,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 cs({message:new Jt({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 Ba({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 cr.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")})}},Od=class extends Si{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 l=0;l<e.length;l+=o)i.push(e.slice(l,l+o));return i.map(l=>{let c=0;for(let h=0;h<l.length;h+=1)c+=l===" "?0:l.charCodeAt(h);return c%26/26})}},Nd=class extends Si{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},$d=class extends Ci{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}},Rd=class extends Ci{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)}},jd=class extends Di{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 te(t))}async addAIMessage(t){this.messages.push(new P(t))}async clear(){this.messages=[]}},Ld=class extends Js{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},Dd=class extends Vs{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Fd=class extends xc{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Ud=class extends qs{lc_namespace=["test","fake"];output=[new We({pageContent:"foo"}),new We({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Vd=class extends se{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},Bd=class extends xr{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)}},zd=class extends Vs{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}},Wd=class za extends Ys{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??Da}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=l=>{if(!r)return!0;const c=new We({metadata:l.metadata,pageContent:l.content});return r(c)},o=this.memoryVectors.filter(s);return o.map((l,c)=>({similarity:this.similarity(e,l.embedding),index:c})).sort((l,c)=>l.similarity>c.similarity?-1:0).slice(0,n).map(l=>[new We({metadata:o[l.index].metadata,pageContent:o[l.index].content}),l.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,l=new We({pageContent:e[i],metadata:a});o.push(l)}return za.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)}},Wa={};Y(Wa,{FakeChatMessageHistory:()=>jd,FakeChatModel:()=>Ad,FakeEmbeddings:()=>Nd,FakeLLM:()=>$d,FakeListChatMessageHistory:()=>Ld,FakeListChatModel:()=>Id,FakeRetriever:()=>Ud,FakeRunnable:()=>Vd,FakeSplitIntoListParser:()=>Fd,FakeStreamingChatModel:()=>Pd,FakeStreamingLLM:()=>Rd,FakeTool:()=>Bd,FakeTracer:()=>Dd,FakeVectorStore:()=>Wd,SingleRunExtractor:()=>zd,SyntheticEmbeddings:()=>Od});var Ha={};Y(Ha,{agents:()=>ph,caches:()=>Dc,callbacks__base:()=>cu,callbacks__manager:()=>lu,callbacks__promises:()=>au,chat_history:()=>Li,document_loaders__base:()=>Gi,document_loaders__langsmith:()=>Ji,documents:()=>Yi,embeddings:()=>Ru,example_selectors:()=>ea,index:()=>gh,indexing:()=>ia,language_models__base:()=>Lc,language_models__chat_models:()=>jc,language_models__llms:()=>Lu,language_models__profile:()=>Oh,load__serializable:()=>iu,memory:()=>Fi,messages:()=>ou,messages__tool:()=>su,output_parsers:()=>Rc,output_parsers__openai_functions:()=>ca,output_parsers__openai_tools:()=>ju,outputs:()=>ru,prompt_values:()=>$c,prompts:()=>Sa,retrievers:()=>Wi,retrievers__document_compressors:()=>Ca,runnables:()=>Nc,runnables__graph:()=>nu,singletons:()=>tu,stores:()=>Vi,structured_query:()=>Pa,tools:()=>vc,tracers__base:()=>eu,tracers__console:()=>Qc,tracers__log_stream:()=>Zc,tracers__run_collector:()=>Ia,tracers__tracer_langchain:()=>Xc,types__stream:()=>fd,utils__async_caller:()=>Yc,utils__chunk_array:()=>$u,utils__context:()=>Oa,utils__env:()=>qc,utils__event_source_parse:()=>$a,utils__format:()=>bd,utils__function_calling:()=>Oc,utils__hash:()=>Ic,utils__json_patch:()=>Pc,utils__json_schema:()=>Jc,utils__math:()=>Fa,utils__stream:()=>Kc,utils__testing:()=>Wa,utils__tiktoken:()=>Ac,utils__types:()=>Mc,vectorstores:()=>Hi});const Hd=50;function Gd(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 Xn(t){const{optionalImportsMap:e,optionalImportEntrypoints:n,importMap:r,secretsMap:s,secretsFromEnv:o,path:i,depth:a,maxDepth:l}=this,c=i.join(".");if(a>l)throw new Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof t!="object"||t==null)return t;if(Array.isArray(t))return Promise.all(t.map((d,f)=>Xn.call({...this,path:[...i,`${f}`],depth:a+1},d)));const u=t;if(uu(u))return hu(u);if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="secret"){const d=u,[f]=d.id;if(f in s)return s[f];if(o){const p=du(f);if(p)return p}throw new Error(`Missing secret "${f}" at ${c}`)}if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="not_implemented"){const f=JSON.stringify(u);throw new Error(`Trying to load an object that doesn't implement serialization: ${c} -> ${f}`)}if("lc"in u&&"type"in u&&"id"in u&&"kwargs"in u&&u.lc===1&&u.type==="constructor"){const d=u,f=JSON.stringify(d),[p,...m]=d.id.slice().reverse(),C=m.reverse(),T={langchain_core:Ha,langchain:r};let k=null;const v=[C.join("/")];C[0]==="langchain_community"&&v.push(["langchain",...C.slice(1)].join("/"));const w=v.find(_=>_ in e);if(fh.concat(n).includes(C.join("/"))||w)if(w!==void 0)k=await e[w];else throw new Error(`Missing key "${C.join("/")}" for ${c} in load(optionalImportsMap={})`);else{let _;if(C[0]==="langchain"||C[0]==="langchain_core")_=T[C[0]],C.shift();else throw new Error(`Invalid namespace: ${c} -> ${f}`);if(C.length===0)throw new Error(`Invalid namespace: ${c} -> ${f}`);let M;do{if(M=C.join("__"),M in _)break;C.pop()}while(C.length>0);M in _&&(k=_[M])}if(typeof k!="object"||k===null)throw new Error(`Invalid namespace: ${c} -> ${f}`);const g=k[p]??Object.values(k).find(_=>typeof _=="function"&&fu(_)===p);if(typeof g!="function")throw new Error(`Invalid identifer: ${c} -> ${f}`);const E=await Xn.call({...this,path:[...i,"kwargs"],depth:a+1},d.kwargs),S=new g(pu(E,mu,Gd(g)));return Object.defineProperty(S.constructor,"name",{value:p}),S}const h={};for(const[d,f]of Object.entries(u))h[d]=await Xn.call({...this,path:[...i,d],depth:a+1},f);return h}async function Kd(t,e){const n=JSON.parse(t),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:Hd};return Xn.call(r,n)}function Jd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function Ts(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>Ts(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await Ts(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(Jd(e))return Kd(JSON.stringify(e));return e}}return t}function Hr(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function qd(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Hr(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Hr(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Hr(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var Yd=class{_dumps(t){return new TextEncoder().encode(hh(t,(n,r)=>qd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return Ts(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 Ga(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]=Ga(t[n]));return e}function Ka(){return{v:4,id:ji(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function gr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:Ga(t.versions_seen)}}function Ja(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function Xd(...t){return t.reduce((e,n,r)=>r===0?n:Ja(e,n)>=0?e:n)}const Zd={[ih]:-1,[Gn]:-2,[ah]:-3,[lh]:-4};var on=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function Qd(t){if(t.length===0)throw new on("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new on(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new on(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new on(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new on(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var ef=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){Qd(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 tf=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var nf=class extends ef{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=tf(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]"}}},rf=class{serde=new Yd;constructor(t){this.serde=t||this.serde}},sf=class qa extends An{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 qa({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new cr({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).map(h=>typeof h=="string"?h:typeof h=="object"&&"text"in h?h.text:Array.isArray(h)?h.map(d=>typeof d=="string"?d:typeof d=="object"&&"text"in d?d.text:"").join("-"):JSON.stringify(h)).join("-")),(e.length===1||e.length===2&&e.every(te.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new P({content:o,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:o,message:c}],llmOutput:{}}}};class of{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 af(){ze.initializeGlobalInstance(new of)}var _t=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
39
39
 
40
40
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${e.lc_error_code}/
41
- `),super(n),this.lc_error_code=e?.lc_error_code}},Ja=class extends vt{get is_bubble_up(){return!0}},of=class extends vt{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Xn=class extends vt{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},At=class extends Ja{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},qa=class extends At{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Ya=class extends Ja{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function af(t){return t!==void 0&&t.name===Ya.unminifiable_name}function Zn(t){return t!==void 0&&t.is_bubble_up===!0}function ht(t){return t!==void 0&&[At.unminifiable_name,qa.unminifiable_name].includes(t.name)}var Ro=class extends vt{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},ne=class extends vt{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},z=class extends vt{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},lf=class extends vt{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function Xa(t){return t!=null&&t.lg_is_channel===!0}var bt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===ne.unminifiable_name)return!1;throw t}}};const Ts=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function io(t){if(t[Ts]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];Xa(r)&&(e[n]=r)}return Object.assign(e,{[Ts]:!0}),e}function gr(t,e){const n=io(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,{[Ts]:!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!==ne.unminifiable_name)throw i}}return{v:4,id:r?.id??$i(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var ks=class Za extends bt{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 Za(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 ne;return this.value}checkpoint(){if(this.value===void 0)throw new ne;return this.value}isAvailable(){return this.value!==void 0}},ao=class Qa extends bt{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new Qa;return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new z("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 ne;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ne;return this.value[0]}isAvailable(){return this.value.length!==0}},cf=class el extends bt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new el;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 ne;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}},uf=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const Es=function(t){return t?xs(t):new ao};Es.Root=t=>new uf(t);function xs(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new ks(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new ks(t.value,t.default):new ao}const F="__start__",O="__end__",Fe="__input__",hf="__copy__",he="__error__",Hr="__pregel_ns_writes",nt="__pregel_send",lo="__pregel_call",pt="__pregel_read",K="__pregel_checkpointer",qe="__pregel_resuming",hn="__pregel_task_id",yr="__pregel_stream",df="__pregel_resume_value",Qn="__pregel_resume_map",rt="__pregel_scratchpad",er="__pregel_previous",tl="__pregel_durability",Ms="checkpoint_id",Ne="checkpoint_ns",ff="__pregel_node_finished",we="checkpoint_map",jo="__pregel_abort_signals",D="__interrupt__",de="__resume__",co="__no_writes__",Yt="__return__",Gr="__previous__",J="langsmith:hidden",pf="langsmith:nostream",Lo="__self__",be="__pregel_tasks",me="__pregel_push",tr="__pregel_pull",_e="00000000-0000-0000-0000-000000000000",mf=[J,Fe,D,de,he,co,nt,pt,K,tl,yr,qe,hn,lo,df,rt,er,we,Ne,Ms],Y="|",He=":",Do=Symbol.for("langgraph.command");var gf=class{[Do];constructor(t){this[Do]=t}};function As(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var le=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=vn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function ye(t){return t instanceof le}function nl(t){return!t||typeof t!="object"||!(D in t)?!1:Array.isArray(t[D])}var G=class extends gf{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)?vn(t.goto):[vn(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:ye(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 Z(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function vn(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]=vn(r,e)});else if(Z(t)&&!(t instanceof G))n=new G(t),e.set(t,n);else if(As(t)&&!(t instanceof le))n=new le(t.node,t.args),e.set(t,n);else if(Z(t)||ye(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]=vn(s,e)}return n}return t}const yf=["tags","metadata","callbacks","configurable"],wf=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],vf=25;function rl(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:vf,configurable:{}},n=ze.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(yf.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&&wf.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 bf(){return ze.getRunnableConfig()}function Kr(t){return t.split(Y).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(He)[0]).join(Y)}function _f(t){const e=t.split(Y);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(Y)}const A=t=>BigInt(t),U=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),sl=A("0x9E3779B1"),ol=A("0x85EBCA77"),Sf=A("0xC2B2AE3D"),ot=A("0x9E3779B185EBCA87"),gt=A("0xC2B2AE3D27D4EB4F"),il=A("0x165667B19E3779F9"),uo=A("0x85EBCA77C2B2AE63"),Cf=A("0x27D4EB2F165667C5"),Tf=A("0x165667919E3779F9"),kf=A("0x9FB21C651E98DF25"),Ef=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 U(r)},Oe=Ef("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Pt=(A(1)<<A(128))-A(1),R=(A(1)<<A(64))-A(1),wr=(A(1)<<A(32))-A(1),Ue=64,al=Ue/8,xf=8,Rn=4;function Xt(t){if(!t)throw new Error("Assert failed")}function Mf(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Af(t){let e=t;return e=(e&A(65535))<<A(16)|(e&A(4294901760))>>A(16),e=(e&A(16711935))<<A(8)|(e&A(4278255360))>>A(8),e}function Pf(t,e){return(t&wr)*(e&wr)&R}function If(t,e){return(t<<e|t>>A(32)-e)&wr}function ll(t,e,n){for(let r=0;r<al;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Pf(o,o>>A(32))}return t}function Fo(t,e,n,r){for(let s=0;s<r;s+=1)ll(t,U(e,s*Ue),U(n,s*8));return t}function Of(t,e){for(let n=0;n<al;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Ps(s,A(47)),s^=r,s*=sl,t[n]=s&R}return t}function jn(t,e){return cl(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(xf,!0))}function Uo(t,e,n){let r=n;return r+=jn(t.slice(0),U(e,0*Rn)),r+=jn(t.slice(2),U(e,4*Rn)),r+=jn(t.slice(4),U(e,8*Rn)),r+=jn(t.slice(6),U(e,12*Rn)),je(r&R)}function Nf(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Ue)/8),a=Ue*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=Fo(o,U(e,c*a),n,i),o=s(o,U(n,n.byteLength-Ue));{const c=Math.floor((e.byteLength-1-a*l)/Ue);o=Fo(o,U(e,l*a),n,c),o=r(o,U(e,e.byteLength-Ue),U(n,n.byteLength-Ue-7))}return o}function $f(t,e){let n=new BigUint64Array([Sf,ot,gt,il,uo,ol,Cf,sl]);Xt(t.byteLength>128),n=Nf(n,t,e,ll,Of),Xt(n.length*8===64);{const r=Uo(n,U(e,11),A(t.byteLength)*ot&R);return Uo(n,U(e,e.byteLength-Ue-11),~(A(t.byteLength)*gt)&R)<<A(64)|r}}function cl(t,e){const n=t*e&Pt;return n&R^n>>A(64)}function Vo(t,e,n){return cl((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&R,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&R)}function nr(t,e,n,r,s){let o=t&R,i=t>>A(64)&R;return o+=Vo(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=R,i+=Vo(n,U(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=R,i<<A(64)|o}function je(t){let e=t;return e^=e>>A(37),e*=Tf,e&=R,e^=e>>A(32),e}function vr(t){let e=t;return e^=e>>A(33),e*=gt,e&=R,e^=e>>A(29),e*=il,e&=R,e^=e>>A(32),e}function Rf(t,e,n){const r=t.byteLength;Xt(r>0&&r<=3);const s=A(t.getUint8(r-1))|A(r<<8)|A(t.getUint8(0)<<16)|A(t.getUint8(r>>1)<<24),o=(A(e.getUint32(0,!0))^A(e.getUint32(4,!0)))+n,i=(s^o)&R,a=(A(e.getUint32(8,!0))^A(e.getUint32(12,!0)))-n,l=(If(Af(s),A(13))^a)&R;return(vr(l)&R)<<A(64)|vr(i)}function Ps(t,e){return t^t>>e}function jf(t,e,n){const r=t.byteLength;Xt(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0),i=A(s)|A(o)<<A(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&R;let c=(i^a)*(ot+(A(r)<<A(2)))&Pt;return c+=(c&R)<<A(65),c&=Pt,c^=c>>A(67),Ps(Ps(c&R,A(35))*kf&R,A(28))|je(c>>A(64))<<A(64)}}function Lf(t,e,n){const r=t.byteLength;Xt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&R,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&R,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*ot;const c=(l&R)+(A(r-1)<<A(54));l=l&(Pt^R)|c,a^=o,l+=a+(a&wr)*(ol-A(1))<<A(64),l&=Pt,l^=Mf(l>>A(64));let u=(l&R)*gt;return u+=(l>>A(64))*gt<<A(64),u&=Pt,je(u&R)|je(u>>A(64))<<A(64)}}function Df(t,e){const n=t.byteLength;return Xt(n<=16),n>8?Lf(t,Oe,e):n>=4?jf(t,Oe,e):n>0?Rf(t,Oe,e):vr(e^Oe.getBigUint64(64,!0)^Oe.getBigUint64(72,!0))|vr(e^Oe.getBigUint64(80,!0)^Oe.getBigUint64(88,!0))<<A(64)}function Is(t){return~t+A(1)&R}function Ff(t,e,n){let r=A(t.byteLength)*ot&R,s=A(t.byteLength-1)/A(32);for(;s>=0;){const a=Number(s);r=nr(r,U(t,16*a),U(t,t.byteLength-16*(a+1)),U(e,32*a),n),s-=A(1)}let o=r+(r>>A(64))&R;o=je(o);let i=(r&R)*ot+(r>>A(64))*uo+(A(t.byteLength)-n&R)*gt;return i&=R,i=Is(je(i)),o|i<<A(64)}function Uf(t,e,n){let r=A(t.byteLength)*ot&R;for(let i=32;i<160;i+=32)r=nr(r,U(t,i-32),U(t,i-16),U(e,i-32),n);r=je(r&R)|je(r>>A(64))<<A(64);for(let i=160;i<=t.byteLength;i+=32)r=nr(r,U(t,i-32),U(t,i-16),U(e,3+i-160),n);r=nr(r,U(t,t.byteLength-16),U(t,t.byteLength-32),U(e,103),Is(n));let s=r+(r>>A(64))&R;s=je(s);let o=(r&R)*ot+(r>>A(64))*uo+(A(t.byteLength)-n&R)*gt;return o&=R,o=Is(je(o)),s|o<<A(64)}function lt(t,e=A(0)){const n=new TextEncoder,r=U(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(Df(r,e)):s<=128?o(Ff(r,Oe,e)):s<=240?o(Uf(r,Oe,e)):o($f(r,Oe))}function ul(t){return/^[0-9a-f]{32}$/.test(t)}function hl(t){const e=ze.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[K])throw new Xn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[rt];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[nt]?.([[de,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 l=s.consumeNullResume();return s.resume.push(l),n[nt]?.([[de,s.resume]]),l}const i=n[Ne]?.split(Y),a=i?lt(i.join(Y)):void 0;throw new At([{id:a,value:t}])}var _t=class extends re{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=un(n,{callbacks:r?.getChild()});ze.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=rl(n),o=Ve(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await ze.runWithConfig(o,async()=>this.func(e,o)),re.isRunnable(r)&&this.recurse?await ze.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*Ke(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Ye(t){const e=[];for await(const n of await t)e.push(n);return e}function an(t){const e=[];for(const n of t)e.push(n);return e}function Ct(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function Vf(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const mt={[Symbol.for("LG_PASSTHROUGH")]:!0};function Ln(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Jr=Symbol("IS_WRITER");var ce=class Os extends _t{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>ye(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=>qr(s)&&Ln(s.value)?{mapper:s.mapper,value:e}:rr(s)&&Ln(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Os.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(rr(o)){if(o.channel===be)throw new z("Cannot write to the reserved channel TASKS");if(Ln(o.value))throw new z("PASSTHROUGH value must be replaced")}if(qr(o)&&Ln(o.value))throw new z("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(ye(o))r.push([be,o]);else if(qr(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(rr(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(Vf(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?.[nt];s(r)}static isWriter(e){return e instanceof Os||Jr in e&&!!e[Jr]}static registerWriter(e){return Object.defineProperty(e,Jr,{value:!0})}};function rr(t){return t!==void 0&&typeof t.channel=="string"}function qr(t){return t!==void 0&&!rr(t)&&re.isRunnable(t.mapper)}var Bf=class dl extends _t{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>dl.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?.[pt];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 Tt=new Lc;var bn=class ln extends $e{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=Tt;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:o,bound:i,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:h,subgraphs:d,ends:f}=e,p=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??Tt,config:{...e.config?e.config:{},tags:p}}),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=l??this.metadata,this.tags=p,this.retryPolicy=c,this.cachePolicy=u,this.subgraphs=d,this.ends=f}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof ce&&e[e.length-2]instanceof ce;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new ce(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===Tt&&e.length===0))return this.bound===Tt&&e.length===1?e[0]:this.bound===Tt?new st({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new st({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 ln({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 ce.isWriter(e)?new ln({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===Tt?new ln({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Kt(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new ln({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 zf(t){return"steps"in t&&Array.isArray(t.steps)}function ho(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function fl(t){const e=[t];for(const n of e){if(ho(n))return n;zf(n)&&e.push(...n.steps)}}function It(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===ne.unminifiable_name){if(r)return s;if(n)return null}throw s}}function yt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=It(t,s,!n)}catch(o){if(o.name===ne.unminifiable_name)continue}return r}else return It(t,e)}function*Wf(t,e){if(t.graph===G.PARENT)throw new z("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(ye(r))yield[_e,be,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(ul))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===de).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,de,s]}else yield[_e,de,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*pl(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*Yr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield yt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield It(n,t))}function*Hf(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(J))&&l[0][0]!==he&&l[0][0]!==D);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===Yt))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===Yt).map(([l,c])=>[a.name,c])):Array.isArray(t)?s=r.flatMap(([a])=>{const{writes:l}=a,c={};for(const[u]of l)t.includes(u)&&(c[u]=(c[u]||0)+1);return Object.values(c).some(u=>u>1)?l.filter(([u])=>t.includes(u)).map(([u,h])=>[a.name,{[u]:h}]):[[a.name,Object.fromEntries(l.filter(([u])=>t.includes(u)))]]}):s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===t).map(([l,c])=>[a.name,c]));const o={};for(const[a,l]of s)a in o||(o[a]=[]),o[a].push(l);const i={};for(const a in o)if(o[a].length===1){const[l]=o[a];i[a]=l}else i[a]=o[a];n&&(i.__metadata__={cached:n}),yield i}function fo(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 sr(t,e){if(Object.keys(t).length>0){const n=fo(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function Gf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Te(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function at(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Te(t,{[we]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function br(...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 Kf=(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 Jf=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 qf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Yf(t,e){const n=new _t({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new st({name:t,first:n,last:new ce([{channel:Yt,value:mt}],[J])})}const Xf=t=>t!==void 0?t+1:1;function Zf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function Qf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=qd(e,t[n]));return e}function Dn(t,e,n){const r=fo(t.channel_versions),s=t.versions_seen[D]??{};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(J):e.includes(a.name));return o&&i}function or(t,e,n,r,s=!1){let o=new Set;if(Array.isArray(r))o=new Set(r.filter(a=>n.writes.some(([l,c])=>l===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))),l=ct(t,a,-1),c=gr(a,l);pe(mr(l),c,[n],void 0,void 0),i=yt({...e,...c},r)}else i=yt(e,r);return i}function Xr(t,e,n){for(const[r,s]of n)if([me,be].includes(r)&&s!=null){if(!ye(s))throw new z(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new z(`Invalid node name "${s.node}" in Send packet`)}t(n)}const ep=new Set([co,me,de,D,Yt,he]);function pe(t,e,n,r,s){n.sort((d,f)=>{const p=d.path?.slice(0,3)||[],m=f.path?.slice(0,3)||[];for(let S=0;S<Math.min(p.length,m.length);S+=1){if(p[S]<m[S])return-1;if(p[S]>m[S])return 1}return p.length-m.length});const o=n.some(d=>d.triggers.length>0),i=io(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=Qf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!mf.includes(d)));let c=!1;for(const d of l)d in i&&i[d].consume()&&r!==void 0&&(t.channel_versions[d]=r(a),c=!0);const u={};for(const d of n)for(const[f,p]of d.writes)ep.has(f)||f in i&&(u[f]??=[],u[f].push(p));a!=null&&r!=null&&(a=c?r(a):a);const h=new Set;for(const[d,f]of Object.entries(u))if(d in i){const p=i[d];let m;try{m=p.update(f)}catch(S){if(S.name===z.unminifiable_name){const C=new z(`Invalid update for channel "${d}" with values ${JSON.stringify(f)}: ${S.message}`);throw C.lc_error_code=S.lc_error_code,C}else throw S}m&&r!==void 0&&(t.channel_versions[d]=r(a),p.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&&!Zf(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*tp(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 Mt(t,e,n,r,s,o,i){const a={},l=r[be];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const h=Ns([me,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const c of tp(t,n,i)){const u=Ns([tr,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function Ns(t,e,n,r,s,o,i,a){const{step:l,checkpointer:c,manager:u}=a,h=o.configurable??{},d=h.checkpoint_ns??"";if(t[0]===me&&qf(t[t.length-1])){const f=t[t.length-1],p=Yf(f.name,f.func),m=[me],S=d===""?f.name:`${d}${Y}${f.name}`,C=kt(JSON.stringify([S,l.toString(),f.name,me,t[1],t[2]]),e.id),E=`${S}${He}${C}`,b=[...t.slice(0,3),!0],w={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:m,langgraph_path:b,langgraph_checkpoint_ns:E};if(i){const g=[];return{name:f.name,input:f.input,proc:p,writes:g,config:un(Ve(o,{metadata:w,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[hn]:C,[nt]:_=>Xr(v=>g.push(...v),r,_),[pt]:(_,v=!1)=>or(e,s,{name:f.name,writes:g,triggers:m,path:b},_,v),[K]:c??h[K],[we]:{...h[we],[d]:e.id},[rt]:Zr({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:o.configurable?.[Qn],namespaceHash:lt(E)}),[er]:e.channel_values[Gr],checkpoint_id:void 0,checkpoint_ns:E}}),triggers:m,retry_policy:f.retry,cache_key:f.cache?{key:lt((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Hr,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:C,path:b,writers:[]}}else return{id:C,name:f.name,interrupts:[],path:b}}else if(t[0]===me){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[be]?.isAvailable())return;const p=s[be].get();if(f<0||f>=p.length)return;const m=As(p[f])&&!ye(p[f])?new le(p[f].node,p[f].args):p[f];if(!As(m)){console.warn(`Ignoring invalid packet ${JSON.stringify(m)} in pending sends.`);return}if(!(m.node in r)){console.warn(`Ignoring unknown node name ${m.node} in pending sends.`);return}const S=[me],C=d===""?m.node:`${d}${Y}${m.node}`,E=kt(JSON.stringify([C,l.toString(),m.node,me,f.toString()]),e.id),b=`${C}${He}${E}`;let w={langgraph_step:l,langgraph_node:m.node,langgraph_triggers:S,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:b};if(i){const g=r[m.node],k=g.getNode();if(k!==void 0){g.metadata!==void 0&&(w={...w,...g.metadata});const _=[];return{name:m.node,input:m.args,proc:k,subgraphs:g.subgraphs,writes:_,config:un(Ve(o,{metadata:w,tags:g.tags,store:a.store??o.store}),{runName:m.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[hn]:E,[nt]:v=>Xr(x=>_.push(...x),r,v),[pt]:(v,x=!1)=>or(e,s,{name:m.node,writes:_,triggers:S,path:t},v,x),[K]:c??h[K],[we]:{...h[we],[d]:e.id},[rt]:Zr({pendingWrites:n??[],taskId:E,currentTaskInput:m.args,resumeMap:o.configurable?.[Qn],namespaceHash:lt(b)}),[er]:e.channel_values[Gr],checkpoint_id:void 0,checkpoint_ns:b}}),triggers:S,retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:lt((g.cachePolicy.keyFunc??JSON.stringify)([m.args])),ns:[Hr,g.name??"__dynamic__",m.node],ttl:g.cachePolicy.ttl}:void 0,id:E,path:t,writers:g.getWriters()}}}else return{id:E,name:m.node,interrupts:[],path:t}}else if(t[0]===tr){const f=t[1].toString(),p=r[f];if(p===void 0)return;if(n?.length){const E=d===""?f:`${d}${Y}${f}`,b=kt(JSON.stringify([E,l.toString(),f,tr,f]),e.id);if(n.some(g=>g[0]===b&&g[1]!==he))return}const m=fo(e.channel_versions);if(m===void 0)return;const S=e.versions_seen[f]??{},C=p.triggers.find(E=>s[E].isAvailable()?(e.channel_versions[E]??m)>(S[E]??m):!1);if(C!==void 0){const E=np(p,s,i);if(E===void 0)return;const b=d===""?f:`${d}${Y}${f}`,w=kt(JSON.stringify([b,l.toString(),f,tr,[C]]),e.id),g=`${b}${He}${w}`;let k={langgraph_step:l,langgraph_node:f,langgraph_triggers:[C],langgraph_path:t,langgraph_checkpoint_ns:g};if(i){const _=p.getNode();if(_!==void 0){p.metadata!==void 0&&(k={...k,...p.metadata});const v=[];return{name:f,input:E,proc:_,subgraphs:p.subgraphs,writes:v,config:un(Ve(o,{metadata:k,tags:p.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[hn]:w,[nt]:x=>Xr(T=>{v.push(...T)},r,x),[pt]:(x,T=!1)=>or(e,s,{name:f,writes:v,triggers:[C],path:t},x,T),[K]:c??h[K],[we]:{...h[we],[d]:e.id},[rt]:Zr({pendingWrites:n??[],taskId:w,currentTaskInput:E,resumeMap:o.configurable?.[Qn],namespaceHash:lt(g)}),[er]:e.channel_values[Gr],checkpoint_id:void 0,checkpoint_ns:g}}),triggers:[C],retry_policy:p.retryPolicy,cache_key:p.cachePolicy?{key:lt((p.cachePolicy.keyFunc??JSON.stringify)([E])),ns:[Hr,p.name??"__dynamic__",f],ttl:p.cachePolicy.ttl}:void 0,id:w,path:t,writers:p.getWriters()}}}else return{id:w,name:f,interrupts:[],path:t}}}}function np(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]=It(e,o,!1)}catch(i){if(i.name===ne.unminifiable_name)return;throw i}else if(o in e)try{r[s]=It(e,o,!1)}catch(i){if(i.name===ne.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=It(e,o,!1),s=!0;break}catch(i){if(i.name===ne.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 Zr({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([l,c])=>l===_e&&c===de)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const l=t.filter(([c,u])=>c===e&&u===de).flatMap(([c,u,h])=>h);if(r!=null&&s in r){const c=r[s];l.push(c)}return l})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,t.splice(t.findIndex(([l,c])=>l===_e&&c===de),1),o}};return a}const _n={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Sn=(t,e)=>`${t.start}${e}${t.end}`;function*Bo(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t){if(s?.tags?.includes(J))continue;const a=i.filter(([l,c])=>l===e&&c===D).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:o,interrupts:a}}}function rp(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function ml(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=rp(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*sp(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(J)||(yield{id:n,name:r,result:ml(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===D).map(i=>i[1])})}function*op(t,e,n,r,s,o,i,a){function l(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 c=t.configurable?.checkpoint_ns,u={};for(const h of s){if(!(h.subgraphs?.length?h.subgraphs:[h.proc]).find(fl))continue;let f=`${h.name}:${h.id}`;c&&(f=`${c}|${f}`),u[h.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:f}}}yield{config:l(t),values:yt(e,n),metadata:r,next:s.map(h=>h.name),tasks:gl(s,o,u,a),parentConfig:i?l(i):void 0}}function gl(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===he)?.[2],i=e.filter(([c,u])=>c===s.id&&u===D).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,h])=>u===s.id&&h===Yt);if(c>=0)return e[c][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?ml(u):void 0}})();if(o)return{id:s.id,name:s.name,path:s.path,error:o,interrupts:i,result:a};const l=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...l!==void 0?{state:l}:{},result:a}})}function ip(t,e,n){console.log([`${Sn(_n.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
42
- `,JSON.stringify(yt(e,n),null,2)].join(""))}function yl(t,e){const n=e.length;console.log([`${Sn(_n.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
43
- `,e.map(r=>`- ${Sn(_n.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
44
- `)].join(""))}function ap(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${Sn(_n.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
45
- `,Object.entries(r).map(([s,o])=>`- ${Sn(_n.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
46
- `)].join(""))}var zo=class extends fn{_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}},wl=class extends fn{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 lp(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 cp(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function po(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Qr(t){return!po(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 Wo(t){if(po(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 Ho(t){const e={...t,checkpoint:Qr(t.config),parent_checkpoint:Qr(t.parentConfig),config:Wo(t.config),parent_config:Wo(t.parentConfig),tasks:t.tasks.map(n=>{if(po(n.state)){const r=Qr(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function up(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
47
- data: ${lp(s.data)}
48
-
49
- `))};try{for await(const s of t){const[o,i,a]=s;let l=a;if(i==="debug"){const u=a;u.type==="checkpoint"&&(l={...u,payload:Ho(u.payload)})}i==="checkpoints"&&(l=Ho(a));const c=o?.length?`${i}|${o.join("|")}`:i;r({event:c,data:l})}}catch(s){r({event:"error",data:cp(s)})}n.close()}})}const Fn=Symbol.for("INPUT_DONE"),es=Symbol.for("INPUT_RESUMING"),hp=25;function dp(...t){return new wl({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 fp=class extends tf{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}},pp=class vl{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 l in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,l)){e=!0;break}const r=this.config.configurable?.[qe]!==void 0&&this.config.configurable?.[qe],s=this.input===null||this.input===void 0,o=Z(this.input)&&this.input.resume!=null,i=this.input===es,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=Xf,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 fp(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?.[yr]!==void 0&&(r=dp(r,n.configurable[yr]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[rt];n.configurable&&o&&(o.subgraphCounter>0&&(n=Te(n,{[Ne]:[n.configurable[Ne],o.subgraphCounter.toString()].join(Y)})),o.subgraphCounter+=1);const i=pt in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Te(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[we]!==void 0&&n.configurable?.[we]?.[n.configurable?.checkpoint_ns]&&(a=Te(n,{checkpoint_id:n.configurable[we][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(Y)??[],c=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:Ha(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,h=mr(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],p=gr(e.channelSpecs,h),m=(d.step??0)+1,S=m+(n.recursionLimit??hp)+1,C={...h.channel_versions},E=e.store?new ef(e.store):void 0;return E&&await E.start(),new vl({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:p,isNested:i,manager:e.manager,skipDoneTasks:s,step:m,stop:S,checkpointPreviousVersions:C,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:E,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 Yd)&&(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=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Ms]: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]===he||n[0][0]===D||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(J))return;if(n.length>0)if(n[0][0]===D){if(s.path?.[0]===me&&s.path?.at(-1)===!0)return;const o=n.filter(i=>i[0]===D).flatMap(i=>i[1]);this._emit([["updates",{[D]:o}],["values",{[D]:o}]])}else n[0][0]!==he&&this._emit(an(Ke(Hf(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(an(Ke(sp([[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 l=s[n(i)];l!=null&&(l.writes.push(...a),e.push({task:l,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(![Fn,es].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new At;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=pe(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await Ye(Ke(Yr(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Dn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new At;this.config.configurable?.[qe]!==void 0&&delete this.config.configurable?.[qe]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=Mt(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 Ye(Ke(op(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===he||i===D||i===de)continue;const l=Object.values(this.tasks).find(c=>c.id===o);l&&l.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(Dn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new At;const s=await Ye(Ke(Bo(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(He)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=yt(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=pe(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(an(Ke(Yr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),ht(e)&&!e.interrupts.length&&this._emit([["updates",{[D]:[]}],["values",{[D]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&Dn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=Ns([me,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&&Dn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(an(Ke(Bo([s]),"tasks"))),this.debug&&yl(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 ht(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[rt];if(r&&r.nullResume!==void 0&&this.putWrites(_e,[[de,r.nullResume]]),Z(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(ul)&&(this.config.configurable??={},this.config.configurable[Qn]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of Wf(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new Ro("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===_e).map(i=>i.slice(1));s.length>0&&pe(this.checkpoint,this.channels,[{name:Fe,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=Z(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 l=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[D]={...this.checkpoint.versions_seen[D],[a]:l}}const i=await Ye(Ke(Yr(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=es;else if(o)await this._putCheckpoint({source:"input"}),this.input=Fn;else{const i=await Ye(pl(e,this.input));if(i.length>0){const a=Mt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=pe(this.checkpoint,this.channels,Object.values(a).concat([{name:Fe,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Fn}else if(qe in(this.config.configurable??{}))this.input=Fn;else throw new Ro(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Te(this.config,{[qe]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=sr(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:mr(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?.[we]??{}}),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=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[Ms]: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===he||r===D||r===de)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 mp(t){return De(t?.message)}var gp=class extends pu{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&&(mu(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(pf)&&!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&&(mp(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Gt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];De(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(J))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const l of Object.values(e))if((De(l)||Co(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(De(c)||Co(c))&&c.id!==void 0&&(this.seen[c.id]=c)}}handleChainEnd(t,e){const n=this.metadatas[e];if(delete this.metadatas[e],n!==void 0){if(De(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)De(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(De(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)De(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const yp=500,wp=2,vp=128e3,bp=3,_p=[400,401,402,403,404,405,406,407,409],Sp=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&&_p.includes(+e)||t?.error?.code==="insufficient_quota")};async function bl(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??yp:0,i=0,a,l,{config:c}=t;for(n&&(c=Te(c,n)),c={...c,signal:r};!r?.aborted;){t.writes.splice(0,t.writes.length),a=void 0;try{l=await t.proc.invoke(t.input,c);break}catch(u){if(a=u,a.pregelTaskId=t.id,af(a)){const p=c?.configurable?.checkpoint_ns,m=a.command;if(m.graph===p){for(const S of t.writers)await S.invoke(m,c);a=void 0;break}else if(m.graph===G.PARENT){const S=_f(p);a.command=new G({...a.command,graph:S})}}if(Zn(a)||s===void 0||(i+=1,i>=(s.maxAttempts??bp))||!(s.retryOn??Sp)(a))break;o=Math.min(s.maxInterval??vp,o*(s.backoffFactor??wp));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(p=>setTimeout(p,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}`),c=Te(c,{[qe]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const $s=Symbol.for("promiseAdded");function Cp(){const t={next:()=>{},wait:Promise.resolve($s)};function e(n){t.next=()=>{t.wait=new Promise(e),n($s)}}return t.wait=new Promise(e),t}var Tp=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,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(p=>p.writes.length===0),{signals:h,disposeCombinedSignal:d}=this._initializeAbortSignals({exceptionSignal:l,stepTimeoutSignal:c,signal:t.signal}),f=this._executeTasksWithRetry(u,{signals:h,retryPolicy:n,maxConcurrency:s});for await(const{task:p,error:m,signalAborted:S}of f)this._commit(p,m),ht(m)||Zn(m)&&!ht(i)?i=m:m&&(o.size===0||!S)&&(a.abort(),o.add(m));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(p=>p.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(ht(i)||Zn(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[jo]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=br(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Te(this.loop.config,{[jo]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Cp(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(d,f,p)=>this.loop.acceptPush(d,f,p)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=br(s?.externalAbortSignal,s?.timeoutAbortSignal),h=u.signal?new Promise((d,f)=>{c=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",c,{once:!0})}):void 0;for(;(l===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&l<t.length;l+=1){const f=t[l];i[f.id]=bl(f,n,{[lo]:_l?.bind(a,this,f)},s?.composedAbortSignal).catch(p=>({task:f,error:p,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(i),...h?[h]:[],o.wait]);d!==$s&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[d.task.id])}}_commit(t,e){if(e!==void 0)if(ht(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[D,s]),r=t.writes.filter(s=>s[0]===de);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Zn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[he,{message:e.message,name:e.name}]]);else this.nodeFinished&&(t.config?.tags==null||!t.config.tags.includes(J))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([co,null]),this.loop.putWrites(t.id,t.writes)}};async function _l(t,e,n,r,s,o={}){const i=e.config?.configurable?.[rt];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new Jf({func:n,name:r,input:s,cache:o.cache,retry:o.retry,callbacks:o.callbacks}),c=await this.scheduleTask(e,a,l);if(!c)return;const u=this.executingTasksMap[c.id];if(u!==void 0)return u;if(c.writes.length>0){const h=c.writes.filter(([f])=>f===Yt),d=c.writes.filter(([f])=>f===he);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(d.length>0){if(d.length===1){const f=d[0][1],p=f instanceof Error?f:new Error(String(f));return Promise.reject(p)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=bl(c,o.retry,{[lo]:_l.bind(this,t,c)});return this.executingTasksMap[c.id]=h,this.barrier.next(),h.then(({result:d,error:f})=>f?Promise.reject(f):d)}}var Le=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function kp({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new Le("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===D)throw new Le(`"Node name ${D} is reserved"`);if(u.constructor===bn)u.triggers.forEach(h=>a.add(h));else throw new Le(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Le(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Le(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Le(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(c=>l.add(c)):l.add(r),s&&!Array.isArray(s)?l.add(s):Array.isArray(s)&&s.forEach(c=>l.add(c));for(const c of l)if(!(c in e))throw new Le(`Output channel '${String(c)}' not in channels`);if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Le(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Le(`Node ${String(c)} not in nodes`)}}function Go(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 Ep=class Sl extends bt{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 Sl({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 ne;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},xp=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 bn({channels:s,triggers:o,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:mt,skipNone:!1});for(const[r,s]of Object.entries(e??{}))re.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:mt,skipNone:!0,mapper:Kt(s)}):n.push({channel:r,value:s,skipNone:!1});return new ce(n)}},Mp=class extends re{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)}},Ap=class extends Mp{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,be in this.channels&&"lc_graph_name"in this.channels[be]&&this.channels[be].lc_graph_name!=="Topic")throw new Error(`Channel '${be}' is reserved and cannot be used in the graph.`);this.channels[be]=new Ep({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=Ve(this.config,t);return new this.constructor({...this,config:e})}validate(){kp({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=fl(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[l,c]of i.getSubgraphs(a,e))yield[`${n}${Y}${l}`,c]}}}}}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=gr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===_e).map(([d,f,p])=>[String(f),p]);h.length>0&&pe(e.checkpoint,s,[{name:Fe,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(Mt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await Ye(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of o){const d=i.find(([p])=>p===h.name);if(!d)continue;let f=`${String(h.name)}${He}${h.id}`;if(a&&(f=`${a}${Y}${f}`),n===void 0){const p={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=p}else{const p={configurable:{[K]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},m=d[1];l[h.id]=await m.getState(p,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,p,m]of e.pendingWrites)[he,D,Hn].includes(p)||f in h&&h[f].writes.push([String(p),m]);const d=o.filter(f=>f.writes.length>0);d.length>0&&pe(e.checkpoint,s,d,void 0,this.triggerToNodes)}let c=e?.metadata;c&&e?.config?.configurable?.thread_id&&(c={...c,thread_id:e.config.configurable.thread_id});const u=o.filter(h=>h.writes.length===0).map(h=>h.name);return{values:yt(s,this.streamChannelsAsIs),next:u,tasks:gl(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:at(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[K]??this.checkpointer;if(!n)throw new Xn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[K]===void 0){const a=Kr(r);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(Ct(t,{[K]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Ve(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?.[K]??this.checkpointer;if(!n)throw new Xn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[K]===void 0){const o=Kr(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(Ct(t,{[K]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=Ve(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?.[K]??this.checkpointer;if(!n)throw new Xn("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?.[K]===void 0){const i=Kr(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(Ct(t,{[K]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?Ve(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?mr(c.checkpoint):Ha(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=Ct(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),p=l.metadata??{};c?.config.configurable&&(f=Ct(l,c.config.configurable),p={...c.metadata,...p});const{values:m,asNode:S}=a[0];if(m==null&&S===void 0){if(a.length>1)throw new z("Cannot create empty checkpoint with multiple updates");const _=await n.put(f,ct(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return at(_,c?c.metadata:void 0)}const C=gr(this.channels,u);if(m===null&&S===O){if(a.length>1)throw new z("Cannot apply multiple updates when clearing state");if(c){const v=Mt(u,c.pendingWrites||[],this.nodes,C,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),x=(c.pendingWrites||[]).filter(T=>T[0]===_e).map(T=>T.slice(1));x.length>0&&pe(u,C,[{name:Fe,writes:x,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[T,M,P]of c.pendingWrites||[])[he,D,Hn].includes(M)||T in v&&v[T].writes.push([M,P]);pe(u,C,Object.values(v),n.getNextVersion.bind(n),this.triggerToNodes)}const _=await n.put(f,ct(u,C,d),{...p,source:"update",step:d+1,parents:c?.metadata?.parents??{}},sr(h,u.channel_versions));return at(_,c?c.metadata:void 0)}if(S===hf){if(a.length>1)throw new z("Cannot copy checkpoint with multiple updates");if(c==null)throw new z("Cannot copy a non-existent checkpoint");const _=T=>!Array.isArray(T)||T.length===0?!1:T.every(M=>Array.isArray(M)&&M.length===2),v=ct(u,void 0,d),x=await n.put(c.parentConfig??Ct(c.config,{checkpoint_id:void 0}),v,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(_(m)){const T=Mt(v,c.pendingWrites,this.nodes,C,x,!1,{step:d+2}),M=Object.values(T).reduce((N,{name:oe,id:ae})=>(N[oe]??=[],N[oe].push({id:ae}),N),{}),P=m.reduce((N,oe)=>{const[ae,Ce]=oe;N[Ce]??=[];const Pe=N[Ce].length,Nn=M[Ce]?.[Pe]?.id;return N[Ce].push({values:ae,asNode:Ce,taskId:Nn}),N},{});return s(at(x,c.metadata),Object.values(P).flat())}return at(x,c.metadata)}if(S===Fe){if(a.length>1)throw new z("Cannot apply multiple updates when updating as input");const _=await Ye(pl(this.inputChannels,m));if(_.length===0)throw new z(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);pe(u,C,[{name:Fe,writes:_,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const v=c?.metadata?.step!=null?c.metadata.step+1:-1,x=await n.put(f,ct(u,C,v),{source:"input",step:v,parents:c?.metadata?.parents??{}},sr(h,u.channel_versions));return await n.putWrites(x,_,kt(Fe,u.id)),at(x,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const _=Mt(u,c.pendingWrites,this.nodes,C,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),v=(c.pendingWrites??[]).filter(T=>T[0]===_e).map(T=>T.slice(1));v.length>0&&pe(c.checkpoint,C,[{name:Fe,writes:v,triggers:[]}],void 0,this.triggerToNodes);for(const[T,M,P]of c.pendingWrites)[he,D,Hn].includes(M)||_[T]===void 0||_[T].writes.push([M,P]);const x=Object.values(_).filter(T=>T.writes.length>0);x.length>0&&pe(u,C,x,void 0,this.triggerToNodes)}const E=Object.values(u.versions_seen).map(_=>Object.values(_)).flat().find(_=>!!_),b=[];if(a.length===1){let{values:_,asNode:v,taskId:x}=a[0];if(v===void 0&&Object.keys(this.nodes).length===1)[v]=Object.keys(this.nodes);else if(v===void 0&&E===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(v=this.inputChannels);else if(v===void 0){const T=Object.entries(u.versions_seen).map(([M,P])=>Object.values(P).map(N=>[N,M])).flat().filter(([M,P])=>P!==D).sort(([M],[P])=>Ga(M,P));T&&(T.length===1?v=T[0][1]:T[T.length-1][0]!==T[T.length-2][0]&&(v=T[T.length-1][1]))}if(v===void 0)throw new z('Ambiguous update, specify "asNode"');b.push({values:_,asNode:v,taskId:x})}else for(const{asNode:_,values:v,taskId:x}of a){if(_==null)throw new z('"asNode" is required when applying multiple updates');b.push({values:v,asNode:_,taskId:x})}const w=[];for(const{asNode:_,values:v,taskId:x}of b){if(this.nodes[_]===void 0)throw new z(`Node "${_.toString()}" does not exist`);const T=this.nodes[_].getWriters();if(!T.length)throw new z(`No writers found for node "${_.toString()}"`);w.push({name:_,input:v,proc:T.length>1?st.from(T,{omitSequenceTags:!0}):T[0],writes:[],triggers:[D],id:x??kt(D,u.id),writers:[]})}for(const _ of w)await _.proc.invoke(_.input,un({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[nt]:v=>_.writes.push(...v),[pt]:(v,x=!1)=>or(u,C,_,v,x)}}));for(const _ of w){const v=_.writes.filter(x=>x[0]!==me);c!==void 0&&v.length>0&&await n.putWrites(f,v,_.id)}pe(u,C,w,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const g=sr(h,u.channel_versions),k=await n.put(f,ct(u,C,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},g);for(const _ of w){const v=_.writes.filter(x=>x[0]===me);v.length>0&&await n.putWrites(k,v,_.id)}return at(k,c?c.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 l=!0;const c=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:Go(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Go(h,this.channels);const d=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let p;n!==void 0?(p=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[hn]!==void 0?p=["values"]:p=this.streamMode,l=!0);let m;if(this.checkpointer===!1)m=void 0;else if(t!==void 0&&t.configurable?.[K]!==void 0)m=t.configurable[K];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");m=this.checkpointer}const S=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 E=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),b=t.durability??E??t?.configurable?.[tl]??"async";return[c,p,h,u,a,d,f,m,S,l,C,b]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:br(e?.signal,n.signal).signal},s=await super.stream(t,r);return new zo(e?.encoding==="text/event-stream"?up(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:Kf(this.config?.callbacks,e?.callbacks),signal:br(e?.signal,r.signal).signal};return new zo(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=rl(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,[l,c,,u,h,d,f,p,m,S,C,E]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const b=new wl({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const M=h.configurable[Ne]??"";h.configurable[Ne]=M.split(Y).map(P=>P.split(He)[0]).join(Y)}if(c.includes("messages")){const M=new gp(N=>b.push(N)),{callbacks:P}=h;if(P===void 0)h.callbacks=[M];else if(Array.isArray(P))h.callbacks=P.concat(M);else{const N=P.copy();N.addHandler(M,!0),h.callbacks=N}}h.writer??=M=>{if(!c.includes("custom"))return;const P=bf()?.configurable?.[Ne]?.split(Y).slice(0,-1);b.push([P??[],"custom",M])},h.interrupt??=this.userInterrupt??hl;const g=await(await gu(h))?.handleChainStart(this.toJSON(),Gf(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),k=io(this.channels);let _,v;const T=(async()=>{try{_=await pp.initialize({input:o,config:h,checkpointer:p,nodes:this.nodes,channelSpecs:k,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:m,cache:C,stream:b,interruptAfter:f,interruptBefore:d,manager:g,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:E});const M=new Tp({loop:_,nodeFinished:h.configurable?.[ff]});e?.subgraphs&&(_.config.configurable={..._.config.configurable,[yr]:_.stream}),await this._runLoop({loop:_,runner:M,debug:l,config:h}),E==="sync"&&await Promise.all(_?.checkpointerPromises??[])}catch(M){v=M}finally{try{_&&(await _.store?.stop(),await _.cache?.stop()),await Promise.all(_?.checkpointerPromises??[])}catch(M){v=v??M}v?b.error(v):b.close()}})();try{for await(const M of b){if(M===void 0)throw new Error("Data structure error.");const[P,N,oe]=M;if(c.includes(N)){if(n==="text/event-stream"){r?yield[P,N,oe]:yield[null,N,oe];continue}r&&!S?yield[P,N,oe]:S?r?yield[P,oe]:yield oe:yield[N,oe]}}}catch(M){throw await g?.handleChainError(v),M}finally{await T}await g?.handleChainEnd(_?.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 l of o)n==="values"?nl(l)?i.push(l[D]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.flat(1);if(a==null)return{[D]:l};if(typeof a=="object")return{...a,[D]:l}}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&&ip(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&yl(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&ap(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new of([`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([])}},Zt=class Cl extends bt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Cl(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 z("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new ne;return this.value[0]}checkpoint(){if(this.value.length===0)throw new ne;return this.value[0]}isAvailable(){return this.value.length!==0}},Tl=class{path;ends;constructor(t){re.isRunnable(t.path)?this.path=t.path:this.path=Kt(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 ce.registerWriter(new _t({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===qa.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
50
- 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=>ye(a)?a:this.ends[a]):o=s,o.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(o.filter(ye).some(a=>a.node===O))throw new z("Cannot send a packet to the END node");return await n(o,e)??t}},Pp=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[Y,He])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=Kt(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:ho(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."),!re.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=Kt(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 Tl(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 kl({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[F]:new Zt,[O]:new Zt},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,l]of Object.entries(i))s.attachBranch(o,a,l);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 lf([`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(`
51
- `),{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}},kl=class extends Ap{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new Zt,this.nodes[t]=new bn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new ce([{channel:t,value:mt}],[J])),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 ce([{channel:O,value:mt}],[J]))}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]=xp.subscribeTo(F,{tags:[J]})),this.nodes[t].pipe(n.run(s=>{const o=s.map(i=>ye(i)?i:{channel:i===O?O:`branch:${t}:${e}:${i}`,value:mt});return new ce(o,[J])}));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 Zt,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new To,r={[F]:n.addNode({schema:ke()},F)},s={};let o={};e&&(o=Object.fromEntries((await Ye(this.getSubgraphsAsync())).filter(l=>Ko(l[1]))));function i(l,c,u,h=!1){if(c===O&&s[O]===void 0&&(s[O]=n.addNode({schema:ke()},O)),r[l]!==void 0){if(s[c]===void 0)throw new Error(`End node ${c} not found!`);return n.addEdge(r[l],s[c],u!==c?u:void 0,h)}}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ie(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,p=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let C=function(b){return b?b.lc_runnable:!1},E=function(b,w){if(b!==void 0&&!ko(b))return b;if(C(w))try{let g=w.getName();return g=g.startsWith("Runnable")?g.slice(8):g,g}catch{return w.getName()}else return w.name??"UnknownSchema"};const[m,S]=n.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:E(S.id,S.data),...S}),s[u]={name:E(m.id,m.data),...m}}else{const m=n.addNode(h,u,d);r[u]=m,s[u]=m}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ie(l),ie(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[ie(h),ie(h)])),[O]:O};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,p]of Object.entries(d))i(ie(l),ie(p),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)i(ie(l),ie(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new To,r={[F]:n.addNode({schema:ke()},F)},s={};let o={};e&&(o=Object.fromEntries(an(this.getSubgraphs()).filter(l=>Ko(l[1]))));function i(l,c,u,h=!1){return c===O&&s[O]===void 0&&(s[O]=n.addNode({schema:ke()},O)),n.addEdge(r[l],s[c],u!==c?u:void 0,h)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ie(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,p=o[l]!==void 0?o[l].getGraph({...t,xray:f}):h.getGraph(t);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let C=function(b){return b?b.lc_runnable:!1},E=function(b,w){if(b!==void 0&&!ko(b))return b;if(C(w))try{let g=w.getName();return g=g.startsWith("Runnable")?g.slice(8):g,g}catch{return w.getName()}else return w.name??"UnknownSchema"};const[m,S]=n.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:E(S.id,S.data),...S}),s[u]={name:E(m.id,m.data),...m}}else{const m=n.addNode(h,u,d);r[u]=m,s[u]=m}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ie(l),ie(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[ie(h),ie(h)])),[O]:O};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,p]of Object.entries(d))i(ie(l),ie(p),f,!0)}}return n}};function Ko(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function ie(t){return t==="subgraph"?`"${t}"`:t}const dt=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Ip=class El extends bt{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new El(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 z(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!dt(this.names,this.seen))throw new ne}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&dt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&dt(this.names,this.seen)}},Op=class xl extends bt{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 xl(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 z(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!dt(this.names,this.seen))throw new ne}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&dt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&dt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&dt(this.names,this.seen)}};const Np="lg:";var $p=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=cs(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new ks(o.reducer.fn,o.default):e[r]=new ao}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(cs(t)).map(([i,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=us(c)??us(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${Np}${h}`)}return[i,c]});s=yu(t,Object.fromEntries(o)),wu(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=Bs(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const Cn=new $p;function _r(t,e){if(e.reducer&&!e.default){const n=Vs(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return Cn.extend(n,()=>e),n}else return Cn.extend(t,()=>e),t}const Be="__root__",Rs=Symbol.for("langgraph.state.partial");var Rp=class extends Pp{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Cn;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Bp(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??Rs,this._outputDefinition=o,this._outputRuntimeDefinition=t.output??t.state}else if(ge(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=Rs,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(Vp(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Up(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Dp(t)||Jo(t)){const r=Jo(t)?t.spec:t;this._schemaDefinition=r}else if(Fp(t)){const r=jp(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)&&!ge(r)}n(e)?(ge(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):ge(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[Y,He])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&&(ge(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;re.isRunnable(s)?a=s:typeof s=="function"?a=new _t({func:s,name:r,trace:!1}):a=Kt(s);let l=o?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:o?.retryPolicy,cachePolicy:l,metadata:o?.metadata,input:i??this._schemaDefinition,subgraphs:ho(a)?[a]:o?.subgraphs,ends:o?.ends,defer:o?.defer};this.nodes[r]=c}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)),l=a.length===1&&a[0]===Be?Be:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===Be?Be:c,h=this._interrupt,d=new Lp({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[F]:new Zt},inputChannels:F,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:h});d.attachNode(F);for(const[f,p]of Object.entries(this.nodes))d.attachNode(f,p);d.attachBranch(F,Lo,qo(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,Lo,qo(),{withReader:!1});for(const[f,p]of this.edges)d.attachEdge(f,p);for(const[f,p]of this.waitingEdges)d.attachEdge(f,p);for(const[f,p]of Object.entries(this.branches))for(const[m,S]of Object.entries(p))d.attachBranch(f,m,S);return d.validate()}};function jp(t){const e={};for(const[n,r]of Object.entries(t))e[n]=xs(r);return e}var Lp=class extends kl{description;_metaRegistry=Cn;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(Z(a))return a.graph===G.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>Z(l))){const l=[];for(const c of a)if(Z(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([Be,c]);return l}else if(a!=null)return[[Be,a]];return null}const s=t;function o(a){if(a){if(Z(a))return a.graph===G.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(Z)){const l=[];for(const c of a)if(Z(c)){if(c.graph===G.PARENT)continue;l.push(...c._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=o(c);u&&l.push(...u??[])}return l}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([l])=>n.includes(l));{const l=Array.isArray(a)?"array":typeof a;throw new z(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:mt,mapper:new _t({func:n.length&&n[0]===Be?r:o,trace:!1,recurse:!1})}];if(t===F)this.nodes[t]=new bn({tags:[J],triggers:[F],channels:[F],writers:[new ce(i,[J])]});else{const a=e?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(h=>[h,h])),c=Object.keys(l).length===1&&Be in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new cf:new Zt(!1),this.nodes[t]=new bn({triggers:[u],channels:c?Object.keys(l):l,writers:[new ce(i,[J])],mapper:c?void 0:h=>Object.fromEntries(Object.entries(h).filter(([d])=>d in l)),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 ce([{channel:`branch:to:${e}`,value:null}],[J]));else if(Array.isArray(t)){const n=`join:${t.join("+")}:${e}`;this.channels[n]=this.builder.nodes[e].defer?new Op(new Set(t)):new Ip(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new ce([{channel:n,value:r}],[J]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(c=>c!==O);if(!a.length)return;const l=a.map(c=>ye(c)?c:{channel:c===O?c:`branch:to:${c}`,value:t});await ce.doWrite({...i,tags:(i.tags??[]).concat([J])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>Bf.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(ge(n))return s(n);if(n===Rs)return Bs(s(r))})();if(Z(t)){const n=t;return t.update&&e!=null&&(n.update=et(e,t.update)),n}return e!=null?et(e,t):t}isInterrupted(t){return nl(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return ge(e)&&et(e,t),t}};function Dp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Xa(e))}function Jo(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function Fp(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Up(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function Vp(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Bp(t){return!(typeof t!="object"||t==null||!("state"in t)||!ge(t.state)||"input"in t&&!ge(t.input)||"output"in t&&!ge(t.output))}function zp(t){if(ye(t))return[t];const e=[];Z(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Z));const n=[];for(const r of e){if(r.graph===G.PARENT)throw new Ya(r);ye(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function qo(){const t=new _t({func:zp,tags:[J],trace:!1,recurse:!1,name:"<control_branch>"});return new Tl({path:t})}const Ml="__remove_all__";function Al(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(pn),o=r.map(pn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=cr(),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=cr(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===Ml&&(i=u)}if(i!=null)return o.slice(i+1);const a=[...s],l=new Map(a.map((u,h)=>[u.id,h])),c=new Set;for(const u of o){const h=l.get(u.id);if(h!==void 0)u.getType()==="remove"?c.add(u.id):(c.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}')`);l.set(u.id,a.length),a.push(u)}}return a.filter(u=>!c.has(u.id))}Es.Root({messages:Es({reducer:Al,default:()=>[]})});const Wp={reducer:{fn:Al},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},Hp=B({messages:_r(Se(),Wp)});sf();const js=Symbol.for("langgraph-zod");js in globalThis||(globalThis[js]=new WeakSet);function Yo(t){const e=globalThis[js];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return _r(n,{jsonSchemaExtra:r})},reducer(r,s){const o=Vs(n);return _r(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Yo(vu.prototype),Yo(pc.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 Gp=class extends mc{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Vs(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new Gp(Cn);function Kp(t=!0,e,n=[]){const r={jumpTo:Ae([Re("model_request"),Re("tools"),Re("end"),bu()]).optional()},s=i=>{const a=jr(i)?cs(i):i.shape;for(const[l,c]of Object.entries(a))l.startsWith("_")||l in r||(r[l]=jr(c)?zs():c)};e&&("shape"in e||jr(e))&&s(e);for(const i of n)i.stateSchema&&s(i.stateSchema);t&&(r.structuredResponse=Q().optional());const o=_r(Se(),{jsonSchemaExtra:{langgraph_type:"messages"}});return{state:Hp.extend(r),input:B({messages:o,...Object.fromEntries(Object.entries(r).filter(([i])=>!["structuredResponse","jumpTo"].includes(i)))}),output:B({messages:o,...Object.fromEntries(Object.entries(r).filter(([i])=>i!=="jumpTo"))})}}const ts=/<name>(.*?)<\/name>/s,ns=/<content>(.*?)<\/content>/s;function Jp(t){if(!I.isInstance(t)||Gt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new I({...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 I({...t.lc_kwargs,content:n,name:void 0})}function qp(t){if(!I.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(ts),o=r.text.match(ns);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(ts),o=r.text.match(ns);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(ts),o=r.match(ns);if(!s||!o)return t;n=s[1],e=o[1]}return new I({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function ut(t){return re.isRunnable(t)}function Xo(t){return Hs(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const rs=(t,e,n={})=>{if(Xo(t))return t.bindTools(e,n);if($e.isRunnableBinding(t)&&Xo(t.bound)){const r=t.bound.bindTools(e,n);return $e.isRunnableBinding(r)?new $e({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new $e({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function Pl(t){if(typeof t=="function")return;let e=t;if(st.isRunnableSequence(e)&&(e=e.steps.find(n=>$e.isRunnableBinding(n))||e),!ur(e)){if($e.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 ds}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new ds}}function Sr(t){return!!(I.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Yp(t){if(t==null)return new te("");if(te.isInstance(t))return t;if(typeof t=="string")return new te({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function Xp(t,e,n={}){const r=rs(t,e,n);if(r)return r;if(ur(t)){const s=rs(await t._getModelInstance(),e,n);if(s)return s}if(st.isRunnableSequence(t)){const s=t.steps.findIndex(o=>$e.isRunnableBinding(o)||Hs(o)||ur(o));if(s>=0){const o=rs(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),st.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Zp(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 Qp(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Zp(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?et(n.stateSchema,{...o.state}):{}}},i);if(!j.isInstance(a)&&!Z(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 em(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=_u(r.stateSchema,a=>a.startsWith("_")),o=await Su(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(`
41
+ `),super(n),this.lc_error_code=e?.lc_error_code}},Ya=class extends _t{get is_bubble_up(){return!0}},lf=class extends _t{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Zn=class extends _t{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},It=class extends Ya{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Xa=class extends It{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Za=class extends Ya{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function cf(t){return t!==void 0&&t.name===Za.unminifiable_name}function Qn(t){return t!==void 0&&t.is_bubble_up===!0}function ft(t){return t!==void 0&&[It.unminifiable_name,Xa.unminifiable_name].includes(t.name)}var Lo=class extends _t{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},re=class extends _t{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},W=class extends _t{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},uf=class extends _t{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function Qa(t){return t!=null&&t.lg_is_channel===!0}var St=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===re.unminifiable_name)return!1;throw t}}};const ks=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function ao(t){if(t[ks]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];Qa(r)&&(e[n]=r)}return Object.assign(e,{[ks]:!0}),e}function yr(t,e){const n=ao(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,{[ks]:!0}),r}function ht(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!==re.unminifiable_name)throw i}}return{v:4,id:r?.id??ji(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var Es=class el extends St{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 el(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 re;return this.value}checkpoint(){if(this.value===void 0)throw new re;return this.value}isAvailable(){return this.value!==void 0}},lo=class tl extends St{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new tl;return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new W("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 re;return this.value[0]}checkpoint(){if(this.value.length===0)throw new re;return this.value[0]}isAvailable(){return this.value.length!==0}},hf=class nl extends St{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new nl;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 re;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}},df=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const xs=function(t){return t?Ms(t):new lo};xs.Root=t=>new df(t);function Ms(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new Es(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new Es(t.value,t.default):new lo}const F="__start__",O="__end__",Fe="__input__",ff="__copy__",he="__error__",Gr="__pregel_ns_writes",rt="__pregel_send",co="__pregel_call",gt="__pregel_read",J="__pregel_checkpointer",Ye="__pregel_resuming",fn="__pregel_task_id",wr="__pregel_stream",pf="__pregel_resume_value",er="__pregel_resume_map",st="__pregel_scratchpad",tr="__pregel_previous",rl="__pregel_durability",As="checkpoint_id",Ne="checkpoint_ns",mf="__pregel_node_finished",ve="checkpoint_map",Do="__pregel_abort_signals",D="__interrupt__",de="__resume__",uo="__no_writes__",Zt="__return__",Kr="__previous__",q="langsmith:hidden",gf="langsmith:nostream",Fo="__self__",_e="__pregel_tasks",ge="__pregel_push",nr="__pregel_pull",Se="00000000-0000-0000-0000-000000000000",yf=[q,Fe,D,de,he,uo,rt,gt,J,rl,wr,Ye,fn,co,pf,st,tr,ve,Ne,As],X="|",He=":",Uo=Symbol.for("langgraph.command");var wf=class{[Uo];constructor(t){this[Uo]=t}};function Ps(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var le=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=_n(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function we(t){return t instanceof le}function sl(t){return!t||typeof t!="object"||!(D in t)?!1:Array.isArray(t[D])}var K=class extends wf{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)?_n(t.goto):[_n(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:we(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 Q(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function _n(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]=_n(r,e)});else if(Q(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(Ps(t)&&!(t instanceof le))n=new le(t.node,t.args),e.set(t,n);else if(Q(t)||we(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]=_n(s,e)}return n}return t}const vf=["tags","metadata","callbacks","configurable"],bf=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],_f=25;function ol(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:_f,configurable:{}},n=ze.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(vf.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&&bf.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 Sf(){return ze.getRunnableConfig()}function Jr(t){return t.split(X).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(He)[0]).join(X)}function Cf(t){const e=t.split(X);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(X)}const A=t=>BigInt(t),U=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),il=A("0x9E3779B1"),al=A("0x85EBCA77"),Tf=A("0xC2B2AE3D"),it=A("0x9E3779B185EBCA87"),wt=A("0xC2B2AE3D27D4EB4F"),ll=A("0x165667B19E3779F9"),ho=A("0x85EBCA77C2B2AE63"),kf=A("0x27D4EB2F165667C5"),Ef=A("0x165667919E3779F9"),xf=A("0x9FB21C651E98DF25"),Mf=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 U(r)},Oe=Mf("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Ot=(A(1)<<A(128))-A(1),R=(A(1)<<A(64))-A(1),vr=(A(1)<<A(32))-A(1),Ue=64,cl=Ue/8,Af=8,jn=4;function Qt(t){if(!t)throw new Error("Assert failed")}function Pf(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function If(t){let e=t;return e=(e&A(65535))<<A(16)|(e&A(4294901760))>>A(16),e=(e&A(16711935))<<A(8)|(e&A(4278255360))>>A(8),e}function Of(t,e){return(t&vr)*(e&vr)&R}function Nf(t,e){return(t<<e|t>>A(32)-e)&vr}function ul(t,e,n){for(let r=0;r<cl;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Of(o,o>>A(32))}return t}function Vo(t,e,n,r){for(let s=0;s<r;s+=1)ul(t,U(e,s*Ue),U(n,s*8));return t}function $f(t,e){for(let n=0;n<cl;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Is(s,A(47)),s^=r,s*=il,t[n]=s&R}return t}function Ln(t,e){return hl(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Af,!0))}function Bo(t,e,n){let r=n;return r+=Ln(t.slice(0),U(e,0*jn)),r+=Ln(t.slice(2),U(e,4*jn)),r+=Ln(t.slice(4),U(e,8*jn)),r+=Ln(t.slice(6),U(e,12*jn)),je(r&R)}function Rf(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-Ue)/8),a=Ue*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=Vo(o,U(e,c*a),n,i),o=s(o,U(n,n.byteLength-Ue));{const c=Math.floor((e.byteLength-1-a*l)/Ue);o=Vo(o,U(e,l*a),n,c),o=r(o,U(e,e.byteLength-Ue),U(n,n.byteLength-Ue-7))}return o}function jf(t,e){let n=new BigUint64Array([Tf,it,wt,ll,ho,al,kf,il]);Qt(t.byteLength>128),n=Rf(n,t,e,ul,$f),Qt(n.length*8===64);{const r=Bo(n,U(e,11),A(t.byteLength)*it&R);return Bo(n,U(e,e.byteLength-Ue-11),~(A(t.byteLength)*wt)&R)<<A(64)|r}}function hl(t,e){const n=t*e&Ot;return n&R^n>>A(64)}function zo(t,e,n){return hl((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&R,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&R)}function rr(t,e,n,r,s){let o=t&R,i=t>>A(64)&R;return o+=zo(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=R,i+=zo(n,U(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=R,i<<A(64)|o}function je(t){let e=t;return e^=e>>A(37),e*=Ef,e&=R,e^=e>>A(32),e}function br(t){let e=t;return e^=e>>A(33),e*=wt,e&=R,e^=e>>A(29),e*=ll,e&=R,e^=e>>A(32),e}function Lf(t,e,n){const r=t.byteLength;Qt(r>0&&r<=3);const s=A(t.getUint8(r-1))|A(r<<8)|A(t.getUint8(0)<<16)|A(t.getUint8(r>>1)<<24),o=(A(e.getUint32(0,!0))^A(e.getUint32(4,!0)))+n,i=(s^o)&R,a=(A(e.getUint32(8,!0))^A(e.getUint32(12,!0)))-n,l=(Nf(If(s),A(13))^a)&R;return(br(l)&R)<<A(64)|br(i)}function Is(t,e){return t^t>>e}function Df(t,e,n){const r=t.byteLength;Qt(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0),i=A(s)|A(o)<<A(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&R;let c=(i^a)*(it+(A(r)<<A(2)))&Ot;return c+=(c&R)<<A(65),c&=Ot,c^=c>>A(67),Is(Is(c&R,A(35))*xf&R,A(28))|je(c>>A(64))<<A(64)}}function Ff(t,e,n){const r=t.byteLength;Qt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&R,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&R,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*it;const c=(l&R)+(A(r-1)<<A(54));l=l&(Ot^R)|c,a^=o,l+=a+(a&vr)*(al-A(1))<<A(64),l&=Ot,l^=Pf(l>>A(64));let u=(l&R)*wt;return u+=(l>>A(64))*wt<<A(64),u&=Ot,je(u&R)|je(u>>A(64))<<A(64)}}function Uf(t,e){const n=t.byteLength;return Qt(n<=16),n>8?Ff(t,Oe,e):n>=4?Df(t,Oe,e):n>0?Lf(t,Oe,e):br(e^Oe.getBigUint64(64,!0)^Oe.getBigUint64(72,!0))|br(e^Oe.getBigUint64(80,!0)^Oe.getBigUint64(88,!0))<<A(64)}function Os(t){return~t+A(1)&R}function Vf(t,e,n){let r=A(t.byteLength)*it&R,s=A(t.byteLength-1)/A(32);for(;s>=0;){const a=Number(s);r=rr(r,U(t,16*a),U(t,t.byteLength-16*(a+1)),U(e,32*a),n),s-=A(1)}let o=r+(r>>A(64))&R;o=je(o);let i=(r&R)*it+(r>>A(64))*ho+(A(t.byteLength)-n&R)*wt;return i&=R,i=Os(je(i)),o|i<<A(64)}function Bf(t,e,n){let r=A(t.byteLength)*it&R;for(let i=32;i<160;i+=32)r=rr(r,U(t,i-32),U(t,i-16),U(e,i-32),n);r=je(r&R)|je(r>>A(64))<<A(64);for(let i=160;i<=t.byteLength;i+=32)r=rr(r,U(t,i-32),U(t,i-16),U(e,3+i-160),n);r=rr(r,U(t,t.byteLength-16),U(t,t.byteLength-32),U(e,103),Os(n));let s=r+(r>>A(64))&R;s=je(s);let o=(r&R)*it+(r>>A(64))*ho+(A(t.byteLength)-n&R)*wt;return o&=R,o=Os(je(o)),s|o<<A(64)}function ut(t,e=A(0)){const n=new TextEncoder,r=U(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(Uf(r,e)):s<=128?o(Vf(r,Oe,e)):s<=240?o(Bf(r,Oe,e)):o(jf(r,Oe))}function dl(t){return/^[0-9a-f]{32}$/.test(t)}function fl(t){const e=ze.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[J])throw new Zn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[st];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[rt]?.([[de,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 l=s.consumeNullResume();return s.resume.push(l),n[rt]?.([[de,s.resume]]),l}const i=n[Ne]?.split(X),a=i?ut(i.join(X)):void 0;throw new It([{id:a,value:t}])}var Ct=class extends se{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=dn(n,{callbacks:r?.getChild()});ze.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=ol(n),o=Ve(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await ze.runWithConfig(o,async()=>this.func(e,o)),se.isRunnable(r)&&this.recurse?await ze.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*Je(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function Xe(t){const e=[];for await(const n of await t)e.push(n);return e}function cn(t){const e=[];for(const n of t)e.push(n);return e}function kt(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function zf(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const yt={[Symbol.for("LG_PASSTHROUGH")]:!0};function Dn(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const qr=Symbol("IS_WRITER");var ce=class Ns extends Ct{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>we(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=>Yr(s)&&Dn(s.value)?{mapper:s.mapper,value:e}:sr(s)&&Dn(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Ns.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(sr(o)){if(o.channel===_e)throw new W("Cannot write to the reserved channel TASKS");if(Dn(o.value))throw new W("PASSTHROUGH value must be replaced")}if(Yr(o)&&Dn(o.value))throw new W("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(we(o))r.push([_e,o]);else if(Yr(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(sr(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(zf(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?.[rt];s(r)}static isWriter(e){return e instanceof Ns||qr in e&&!!e[qr]}static registerWriter(e){return Object.defineProperty(e,qr,{value:!0})}};function sr(t){return t!==void 0&&typeof t.channel=="string"}function Yr(t){return t!==void 0&&!sr(t)&&se.isRunnable(t.mapper)}var Wf=class pl extends Ct{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>pl.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?.[gt];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 Et=new Fc;var Sn=class un extends $e{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=Et;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:o,bound:i,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:h,subgraphs:d,ends:f}=e,p=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??Et,config:{...e.config?e.config:{},tags:p}}),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=l??this.metadata,this.tags=p,this.retryPolicy=c,this.cachePolicy=u,this.subgraphs=d,this.ends=f}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof ce&&e[e.length-2]instanceof ce;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new ce(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===Et&&e.length===0))return this.bound===Et&&e.length===1?e[0]:this.bound===Et?new ot({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new ot({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 un({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 ce.isWriter(e)?new un({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===Et?new un({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:qt(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new un({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 Hf(t){return"steps"in t&&Array.isArray(t.steps)}function fo(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function ml(t){const e=[t];for(const n of e){if(fo(n))return n;Hf(n)&&e.push(...n.steps)}}function Nt(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===re.unminifiable_name){if(r)return s;if(n)return null}throw s}}function vt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Nt(t,s,!n)}catch(o){if(o.name===re.unminifiable_name)continue}return r}else return Nt(t,e)}function*Gf(t,e){if(t.graph===K.PARENT)throw new W("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(we(r))yield[Se,_e,r];else if(typeof r=="string")yield[Se,`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(dl))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===de).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,de,s]}else yield[Se,de,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[Se,n,r];else for(const[n,r]of Object.entries(t.update))yield[Se,n,r]}}function*gl(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*Xr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield vt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Nt(n,t))}function*Kf(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(q))&&l[0][0]!==he&&l[0][0]!==D);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===Zt))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===Zt).map(([l,c])=>[a.name,c])):Array.isArray(t)?s=r.flatMap(([a])=>{const{writes:l}=a,c={};for(const[u]of l)t.includes(u)&&(c[u]=(c[u]||0)+1);return Object.values(c).some(u=>u>1)?l.filter(([u])=>t.includes(u)).map(([u,h])=>[a.name,{[u]:h}]):[[a.name,Object.fromEntries(l.filter(([u])=>t.includes(u)))]]}):s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===t).map(([l,c])=>[a.name,c]));const o={};for(const[a,l]of s)a in o||(o[a]=[]),o[a].push(l);const i={};for(const a in o)if(o[a].length===1){const[l]=o[a];i[a]=l}else i[a]=o[a];n&&(i.__metadata__={cached:n}),yield i}function po(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 or(t,e){if(Object.keys(t).length>0){const n=po(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function Jf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Te(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function ct(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Te(t,{[ve]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function _r(...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 qf=(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 Yf=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 Xf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Zf(t,e){const n=new Ct({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new ot({name:t,first:n,last:new ce([{channel:Zt,value:yt}],[q])})}const Qf=t=>t!==void 0?t+1:1;function ep(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function tp(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=Xd(e,t[n]));return e}function Fn(t,e,n){const r=po(t.channel_versions),s=t.versions_seen[D]??{};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 ir(t,e,n,r,s=!1){let o=new Set;if(Array.isArray(r))o=new Set(r.filter(a=>n.writes.some(([l,c])=>l===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))),l=ht(t,a,-1),c=yr(a,l);me(gr(l),c,[n],void 0,void 0),i=vt({...e,...c},r)}else i=vt(e,r);return i}function Zr(t,e,n){for(const[r,s]of n)if([ge,_e].includes(r)&&s!=null){if(!we(s))throw new W(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new W(`Invalid node name "${s.node}" in Send packet`)}t(n)}const np=new Set([uo,ge,de,D,Zt,he]);function me(t,e,n,r,s){n.sort((d,f)=>{const p=d.path?.slice(0,3)||[],m=f.path?.slice(0,3)||[];for(let C=0;C<Math.min(p.length,m.length);C+=1){if(p[C]<m[C])return-1;if(p[C]>m[C])return 1}return p.length-m.length});const o=n.some(d=>d.triggers.length>0),i=ao(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=tp(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!yf.includes(d)));let c=!1;for(const d of l)d in i&&i[d].consume()&&r!==void 0&&(t.channel_versions[d]=r(a),c=!0);const u={};for(const d of n)for(const[f,p]of d.writes)np.has(f)||f in i&&(u[f]??=[],u[f].push(p));a!=null&&r!=null&&(a=c?r(a):a);const h=new Set;for(const[d,f]of Object.entries(u))if(d in i){const p=i[d];let m;try{m=p.update(f)}catch(C){if(C.name===W.unminifiable_name){const T=new W(`Invalid update for channel "${d}" with values ${JSON.stringify(f)}: ${C.message}`);throw T.lc_error_code=C.lc_error_code,T}else throw C}m&&r!==void 0&&(t.channel_versions[d]=r(a),p.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&&!ep(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*rp(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 Pt(t,e,n,r,s,o,i){const a={},l=r[_e];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const h=$s([ge,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const c of rp(t,n,i)){const u=$s([nr,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function $s(t,e,n,r,s,o,i,a){const{step:l,checkpointer:c,manager:u}=a,h=o.configurable??{},d=h.checkpoint_ns??"";if(t[0]===ge&&Xf(t[t.length-1])){const f=t[t.length-1],p=Zf(f.name,f.func),m=[ge],C=d===""?f.name:`${d}${X}${f.name}`,T=xt(JSON.stringify([C,l.toString(),f.name,ge,t[1],t[2]]),e.id),k=`${C}${He}${T}`,v=[...t.slice(0,3),!0],w={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:m,langgraph_path:v,langgraph_checkpoint_ns:k};if(i){const g=[];return{name:f.name,input:f.input,proc:p,writes:g,config:dn(Ve(o,{metadata:w,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[fn]:T,[rt]:S=>Zr(_=>g.push(..._),r,S),[gt]:(S,_=!1)=>ir(e,s,{name:f.name,writes:g,triggers:m,path:v},S,_),[J]:c??h[J],[ve]:{...h[ve],[d]:e.id},[st]:Qr({pendingWrites:n??[],taskId:T,currentTaskInput:f.input,resumeMap:o.configurable?.[er],namespaceHash:ut(k)}),[tr]:e.channel_values[Kr],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:m,retry_policy:f.retry,cache_key:f.cache?{key:ut((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Gr,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:T,path:v,writers:[]}}else return{id:T,name:f.name,interrupts:[],path:v}}else if(t[0]===ge){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[_e]?.isAvailable())return;const p=s[_e].get();if(f<0||f>=p.length)return;const m=Ps(p[f])&&!we(p[f])?new le(p[f].node,p[f].args):p[f];if(!Ps(m)){console.warn(`Ignoring invalid packet ${JSON.stringify(m)} in pending sends.`);return}if(!(m.node in r)){console.warn(`Ignoring unknown node name ${m.node} in pending sends.`);return}const C=[ge],T=d===""?m.node:`${d}${X}${m.node}`,k=xt(JSON.stringify([T,l.toString(),m.node,ge,f.toString()]),e.id),v=`${T}${He}${k}`;let w={langgraph_step:l,langgraph_node:m.node,langgraph_triggers:C,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:v};if(i){const g=r[m.node],E=g.getNode();if(E!==void 0){g.metadata!==void 0&&(w={...w,...g.metadata});const S=[];return{name:m.node,input:m.args,proc:E,subgraphs:g.subgraphs,writes:S,config:dn(Ve(o,{metadata:w,tags:g.tags,store:a.store??o.store}),{runName:m.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[fn]:k,[rt]:_=>Zr(M=>S.push(...M),r,_),[gt]:(_,M=!1)=>ir(e,s,{name:m.node,writes:S,triggers:C,path:t},_,M),[J]:c??h[J],[ve]:{...h[ve],[d]:e.id},[st]:Qr({pendingWrites:n??[],taskId:k,currentTaskInput:m.args,resumeMap:o.configurable?.[er],namespaceHash:ut(v)}),[tr]:e.channel_values[Kr],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:C,retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:ut((g.cachePolicy.keyFunc??JSON.stringify)([m.args])),ns:[Gr,g.name??"__dynamic__",m.node],ttl:g.cachePolicy.ttl}:void 0,id:k,path:t,writers:g.getWriters()}}}else return{id:k,name:m.node,interrupts:[],path:t}}else if(t[0]===nr){const f=t[1].toString(),p=r[f];if(p===void 0)return;if(n?.length){const k=d===""?f:`${d}${X}${f}`,v=xt(JSON.stringify([k,l.toString(),f,nr,f]),e.id);if(n.some(g=>g[0]===v&&g[1]!==he))return}const m=po(e.channel_versions);if(m===void 0)return;const C=e.versions_seen[f]??{},T=p.triggers.find(k=>s[k].isAvailable()?(e.channel_versions[k]??m)>(C[k]??m):!1);if(T!==void 0){const k=sp(p,s,i);if(k===void 0)return;const v=d===""?f:`${d}${X}${f}`,w=xt(JSON.stringify([v,l.toString(),f,nr,[T]]),e.id),g=`${v}${He}${w}`;let E={langgraph_step:l,langgraph_node:f,langgraph_triggers:[T],langgraph_path:t,langgraph_checkpoint_ns:g};if(i){const S=p.getNode();if(S!==void 0){p.metadata!==void 0&&(E={...E,...p.metadata});const _=[];return{name:f,input:k,proc:S,subgraphs:p.subgraphs,writes:_,config:dn(Ve(o,{metadata:E,tags:p.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[fn]:w,[rt]:M=>Zr(b=>{_.push(...b)},r,M),[gt]:(M,b=!1)=>ir(e,s,{name:f,writes:_,triggers:[T],path:t},M,b),[J]:c??h[J],[ve]:{...h[ve],[d]:e.id},[st]:Qr({pendingWrites:n??[],taskId:w,currentTaskInput:k,resumeMap:o.configurable?.[er],namespaceHash:ut(g)}),[tr]:e.channel_values[Kr],checkpoint_id:void 0,checkpoint_ns:g}}),triggers:[T],retry_policy:p.retryPolicy,cache_key:p.cachePolicy?{key:ut((p.cachePolicy.keyFunc??JSON.stringify)([k])),ns:[Gr,p.name??"__dynamic__",f],ttl:p.cachePolicy.ttl}:void 0,id:w,path:t,writers:p.getWriters()}}}else return{id:w,name:f,interrupts:[],path:t}}}}function sp(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]=Nt(e,o,!1)}catch(i){if(i.name===re.unminifiable_name)return;throw i}else if(o in e)try{r[s]=Nt(e,o,!1)}catch(i){if(i.name===re.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=Nt(e,o,!1),s=!0;break}catch(i){if(i.name===re.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 Qr({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([l,c])=>l===Se&&c===de)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const l=t.filter(([c,u])=>c===e&&u===de).flatMap(([c,u,h])=>h);if(r!=null&&s in r){const c=r[s];l.push(c)}return l})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,t.splice(t.findIndex(([l,c])=>l===Se&&c===de),1),o}};return a}const Cn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},Tn=(t,e)=>`${t.start}${e}${t.end}`;function*Wo(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(([l,c])=>l===e&&c===D).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:o,interrupts:a}}}function op(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function yl(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=op(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*ip(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(q)||(yield{id:n,name:r,result:yl(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===D).map(i=>i[1])})}function*ap(t,e,n,r,s,o,i,a){function l(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 c=t.configurable?.checkpoint_ns,u={};for(const h of s){if(!(h.subgraphs?.length?h.subgraphs:[h.proc]).find(ml))continue;let f=`${h.name}:${h.id}`;c&&(f=`${c}|${f}`),u[h.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:f}}}yield{config:l(t),values:vt(e,n),metadata:r,next:s.map(h=>h.name),tasks:wl(s,o,u,a),parentConfig:i?l(i):void 0}}function wl(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===he)?.[2],i=e.filter(([c,u])=>c===s.id&&u===D).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,h])=>u===s.id&&h===Zt);if(c>=0)return e[c][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?yl(u):void 0}})();if(o)return{id:s.id,name:s.name,path:s.path,error:o,interrupts:i,result:a};const l=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...l!==void 0?{state:l}:{},result:a}})}function lp(t,e,n){console.log([`${Tn(Cn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
42
+ `,JSON.stringify(vt(e,n),null,2)].join(""))}function vl(t,e){const n=e.length;console.log([`${Tn(Cn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
43
+ `,e.map(r=>`- ${Tn(Cn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
44
+ `)].join(""))}function cp(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${Tn(Cn.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
45
+ `,Object.entries(r).map(([s,o])=>`- ${Tn(Cn.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
46
+ `)].join(""))}var Ho=class extends mn{_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}},bl=class extends mn{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 up(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 hp(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 es(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 Go(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 Ko(t){const e={...t,checkpoint:es(t.config),parent_checkpoint:es(t.parentConfig),config:Go(t.config),parent_config:Go(t.parentConfig),tasks:t.tasks.map(n=>{if(mo(n.state)){const r=es(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function dp(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
47
+ data: ${up(s.data)}
48
+
49
+ `))};try{for await(const s of t){const[o,i,a]=s;let l=a;if(i==="debug"){const u=a;u.type==="checkpoint"&&(l={...u,payload:Ko(u.payload)})}i==="checkpoints"&&(l=Ko(a));const c=o?.length?`${i}|${o.join("|")}`:i;r({event:c,data:l})}}catch(s){r({event:"error",data:hp(s)})}n.close()}})}const Un=Symbol.for("INPUT_DONE"),ts=Symbol.for("INPUT_RESUMING"),fp=25;function pp(...t){return new bl({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 mp=class extends rf{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}},gp=class _l{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 l in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,l)){e=!0;break}const r=this.config.configurable?.[Ye]!==void 0&&this.config.configurable?.[Ye],s=this.input===null||this.input===void 0,o=Q(this.input)&&this.input.resume!=null,i=this.input===ts,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=Qf,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 mp(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?.[wr]!==void 0&&(r=pp(r,n.configurable[wr]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[st];n.configurable&&o&&(o.subgraphCounter>0&&(n=Te(n,{[Ne]:[n.configurable[Ne],o.subgraphCounter.toString()].join(X)})),o.subgraphCounter+=1);const i=gt in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Te(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ve]!==void 0&&n.configurable?.[ve]?.[n.configurable?.checkpoint_ns]&&(a=Te(n,{checkpoint_id:n.configurable[ve][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(X)??[],c=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:Ka(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,h=gr(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],p=yr(e.channelSpecs,h),m=(d.step??0)+1,C=m+(n.recursionLimit??fp)+1,T={...h.channel_versions},k=e.store?new nf(e.store):void 0;return k&&await k.start(),new _l({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:p,isNested:i,manager:e.manager,skipDoneTasks:s,step:m,stop:C,checkpointPreviousVersions:T,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:k,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 Zd)&&(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=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[As]: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]===he||n[0][0]===D||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]===D){if(s.path?.[0]===ge&&s.path?.at(-1)===!0)return;const o=n.filter(i=>i[0]===D).flatMap(i=>i[1]);this._emit([["updates",{[D]:o}],["values",{[D]:o}]])}else n[0][0]!==he&&this._emit(cn(Je(Kf(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(cn(Je(ip([[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 l=s[n(i)];l!=null&&(l.writes.push(...a),e.push({task:l,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(![Un,ts].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new It;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=me(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await Xe(Je(Xr(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Fn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new It;this.config.configurable?.[Ye]!==void 0&&delete this.config.configurable?.[Ye]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=Pt(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 Xe(Je(ap(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===he||i===D||i===de)continue;const l=Object.values(this.tasks).find(c=>c.id===o);l&&l.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(Fn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new It;const s=await Xe(Je(Wo(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(He)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=vt(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=me(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(cn(Je(Xr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),ft(e)&&!e.interrupts.length&&this._emit([["updates",{[D]:[]}],["values",{[D]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&Fn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=$s([ge,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&&Fn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(cn(Je(Wo([s]),"tasks"))),this.debug&&vl(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 ft(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[st];if(r&&r.nullResume!==void 0&&this.putWrites(Se,[[de,r.nullResume]]),Q(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(dl)&&(this.config.configurable??={},this.config.configurable[er]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of Gf(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new Lo("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===Se).map(i=>i.slice(1));s.length>0&&me(this.checkpoint,this.channels,[{name:Fe,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=Q(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 l=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[D]={...this.checkpoint.versions_seen[D],[a]:l}}const i=await Xe(Je(Xr(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=ts;else if(o)await this._putCheckpoint({source:"input"}),this.input=Un;else{const i=await Xe(gl(e,this.input));if(i.length>0){const a=Pt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=me(this.checkpoint,this.channels,Object.values(a).concat([{name:Fe,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Un}else if(Ye in(this.config.configurable??{}))this.input=Un;else throw new Lo(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Te(this.config,{[Ye]: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=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=or(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:gr(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?.[ve]??{}}),this.checkpoint=ht(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=Te(this.checkpointConfig,{[Ne]:this.config.configurable?.checkpoint_ns??"",[As]: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===he||r===D||r===de)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 yp(t){return De(t?.message)}var wp=class extends gu{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(gf)&&!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&&(yp(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Jt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];De(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 l of Object.values(e))if((De(l)||ko(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(De(c)||ko(c))&&c.id!==void 0&&(this.seen[c.id]=c)}}handleChainEnd(t,e){const n=this.metadatas[e];if(delete this.metadatas[e],n!==void 0){if(De(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)De(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(De(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)De(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const vp=500,bp=2,_p=128e3,Sp=3,Cp=[400,401,402,403,404,405,406,407,409],Tp=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&&Cp.includes(+e)||t?.error?.code==="insufficient_quota")};async function Sl(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??vp:0,i=0,a,l,{config:c}=t;for(n&&(c=Te(c,n)),c={...c,signal:r};!r?.aborted;){t.writes.splice(0,t.writes.length),a=void 0;try{l=await t.proc.invoke(t.input,c);break}catch(u){if(a=u,a.pregelTaskId=t.id,cf(a)){const p=c?.configurable?.checkpoint_ns,m=a.command;if(m.graph===p){for(const C of t.writers)await C.invoke(m,c);a=void 0;break}else if(m.graph===K.PARENT){const C=Cf(p);a.command=new K({...a.command,graph:C})}}if(Qn(a)||s===void 0||(i+=1,i>=(s.maxAttempts??Sp))||!(s.retryOn??Tp)(a))break;o=Math.min(s.maxInterval??_p,o*(s.backoffFactor??bp));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(p=>setTimeout(p,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}`),c=Te(c,{[Ye]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const Rs=Symbol.for("promiseAdded");function kp(){const t={next:()=>{},wait:Promise.resolve(Rs)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Rs)}}return t.wait=new Promise(e),t}var Ep=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,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(p=>p.writes.length===0),{signals:h,disposeCombinedSignal:d}=this._initializeAbortSignals({exceptionSignal:l,stepTimeoutSignal:c,signal:t.signal}),f=this._executeTasksWithRetry(u,{signals:h,retryPolicy:n,maxConcurrency:s});for await(const{task:p,error:m,signalAborted:C}of f)this._commit(p,m),ft(m)||Qn(m)&&!ft(i)?i=m:m&&(o.size===0||!C)&&(a.abort(),o.add(m));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(p=>p.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(ft(i)||Qn(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[Do]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=_r(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Te(this.loop.config,{[Do]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=kp(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(d,f,p)=>this.loop.acceptPush(d,f,p)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=_r(s?.externalAbortSignal,s?.timeoutAbortSignal),h=u.signal?new Promise((d,f)=>{c=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",c,{once:!0})}):void 0;for(;(l===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&l<t.length;l+=1){const f=t[l];i[f.id]=Sl(f,n,{[co]:Cl?.bind(a,this,f)},s?.composedAbortSignal).catch(p=>({task:f,error:p,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(i),...h?[h]:[],o.wait]);d!==Rs&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[d.task.id])}}_commit(t,e){if(e!==void 0)if(ft(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[D,s]),r=t.writes.filter(s=>s[0]===de);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Qn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[he,{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([uo,null]),this.loop.putWrites(t.id,t.writes)}};async function Cl(t,e,n,r,s,o={}){const i=e.config?.configurable?.[st];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new Yf({func:n,name:r,input:s,cache:o.cache,retry:o.retry,callbacks:o.callbacks}),c=await this.scheduleTask(e,a,l);if(!c)return;const u=this.executingTasksMap[c.id];if(u!==void 0)return u;if(c.writes.length>0){const h=c.writes.filter(([f])=>f===Zt),d=c.writes.filter(([f])=>f===he);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(d.length>0){if(d.length===1){const f=d[0][1],p=f instanceof Error?f:new Error(String(f));return Promise.reject(p)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=Sl(c,o.retry,{[co]:Cl.bind(this,t,c)});return this.executingTasksMap[c.id]=h,this.barrier.next(),h.then(({result:d,error:f})=>f?Promise.reject(f):d)}}var Le=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function xp({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new Le("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===D)throw new Le(`"Node name ${D} is reserved"`);if(u.constructor===Sn)u.triggers.forEach(h=>a.add(h));else throw new Le(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Le(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Le(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Le(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(c=>l.add(c)):l.add(r),s&&!Array.isArray(s)?l.add(s):Array.isArray(s)&&s.forEach(c=>l.add(c));for(const c of l)if(!(c in e))throw new Le(`Output channel '${String(c)}' not in channels`);if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Le(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Le(`Node ${String(c)} not in nodes`)}}function Jo(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 Mp=class Tl extends St{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 Tl({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 re;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Ap=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 Sn({channels:s,triggers:o,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:yt,skipNone:!1});for(const[r,s]of Object.entries(e??{}))se.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:yt,skipNone:!0,mapper:qt(s)}):n.push({channel:r,value:s,skipNone:!1});return new ce(n)}},Pp=class extends se{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)}},Ip=class extends Pp{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,_e in this.channels&&"lc_graph_name"in this.channels[_e]&&this.channels[_e].lc_graph_name!=="Topic")throw new Error(`Channel '${_e}' is reserved and cannot be used in the graph.`);this.channels[_e]=new Mp({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=Ve(this.config,t);return new this.constructor({...this,config:e})}validate(){xp({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=ml(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[l,c]of i.getSubgraphs(a,e))yield[`${n}${X}${l}`,c]}}}}}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=yr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===Se).map(([d,f,p])=>[String(f),p]);h.length>0&&me(e.checkpoint,s,[{name:Fe,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(Pt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await Xe(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of o){const d=i.find(([p])=>p===h.name);if(!d)continue;let f=`${String(h.name)}${He}${h.id}`;if(a&&(f=`${a}${X}${f}`),n===void 0){const p={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=p}else{const p={configurable:{[J]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},m=d[1];l[h.id]=await m.getState(p,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,p,m]of e.pendingWrites)[he,D,Gn].includes(p)||f in h&&h[f].writes.push([String(p),m]);const d=o.filter(f=>f.writes.length>0);d.length>0&&me(e.checkpoint,s,d,void 0,this.triggerToNodes)}let c=e?.metadata;c&&e?.config?.configurable?.thread_id&&(c={...c,thread_id:e.config.configurable.thread_id});const u=o.filter(h=>h.writes.length===0).map(h=>h.name);return{values:vt(s,this.streamChannelsAsIs),next:u,tasks:wl(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:ct(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[J]??this.checkpointer;if(!n)throw new Zn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const a=Jr(r);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(kt(t,{[J]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Ve(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?.[J]??this.checkpointer;if(!n)throw new Zn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[J]===void 0){const o=Jr(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(kt(t,{[J]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=Ve(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?.[J]??this.checkpointer;if(!n)throw new Zn("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?.[J]===void 0){const i=Jr(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(kt(t,{[J]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?Ve(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?gr(c.checkpoint):Ka(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=kt(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),p=l.metadata??{};c?.config.configurable&&(f=kt(l,c.config.configurable),p={...c.metadata,...p});const{values:m,asNode:C}=a[0];if(m==null&&C===void 0){if(a.length>1)throw new W("Cannot create empty checkpoint with multiple updates");const S=await n.put(f,ht(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return ct(S,c?c.metadata:void 0)}const T=yr(this.channels,u);if(m===null&&C===O){if(a.length>1)throw new W("Cannot apply multiple updates when clearing state");if(c){const _=Pt(u,c.pendingWrites||[],this.nodes,T,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),M=(c.pendingWrites||[]).filter(b=>b[0]===Se).map(b=>b.slice(1));M.length>0&&me(u,T,[{name:Fe,writes:M,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[b,x,I]of c.pendingWrites||[])[he,D,Gn].includes(x)||b in _&&_[b].writes.push([x,I]);me(u,T,Object.values(_),n.getNextVersion.bind(n),this.triggerToNodes)}const S=await n.put(f,ht(u,T,d),{...p,source:"update",step:d+1,parents:c?.metadata?.parents??{}},or(h,u.channel_versions));return ct(S,c?c.metadata:void 0)}if(C===ff){if(a.length>1)throw new W("Cannot copy checkpoint with multiple updates");if(c==null)throw new W("Cannot copy a non-existent checkpoint");const S=b=>!Array.isArray(b)||b.length===0?!1:b.every(x=>Array.isArray(x)&&x.length===2),_=ht(u,void 0,d),M=await n.put(c.parentConfig??kt(c.config,{checkpoint_id:void 0}),_,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(S(m)){const b=Pt(_,c.pendingWrites,this.nodes,T,M,!1,{step:d+2}),x=Object.values(b).reduce((N,{name:V,id:ie})=>(N[V]??=[],N[V].push({id:ie}),N),{}),I=m.reduce((N,V)=>{const[ie,Pe]=V;N[Pe]??=[];const pe=N[Pe].length,lt=x[Pe]?.[pe]?.id;return N[Pe].push({values:ie,asNode:Pe,taskId:lt}),N},{});return s(ct(M,c.metadata),Object.values(I).flat())}return ct(M,c.metadata)}if(C===Fe){if(a.length>1)throw new W("Cannot apply multiple updates when updating as input");const S=await Xe(gl(this.inputChannels,m));if(S.length===0)throw new W(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);me(u,T,[{name:Fe,writes:S,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const _=c?.metadata?.step!=null?c.metadata.step+1:-1,M=await n.put(f,ht(u,T,_),{source:"input",step:_,parents:c?.metadata?.parents??{}},or(h,u.channel_versions));return await n.putWrites(M,S,xt(Fe,u.id)),ct(M,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const S=Pt(u,c.pendingWrites,this.nodes,T,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),_=(c.pendingWrites??[]).filter(b=>b[0]===Se).map(b=>b.slice(1));_.length>0&&me(c.checkpoint,T,[{name:Fe,writes:_,triggers:[]}],void 0,this.triggerToNodes);for(const[b,x,I]of c.pendingWrites)[he,D,Gn].includes(x)||S[b]===void 0||S[b].writes.push([x,I]);const M=Object.values(S).filter(b=>b.writes.length>0);M.length>0&&me(u,T,M,void 0,this.triggerToNodes)}const k=Object.values(u.versions_seen).map(S=>Object.values(S)).flat().find(S=>!!S),v=[];if(a.length===1){let{values:S,asNode:_,taskId:M}=a[0];if(_===void 0&&Object.keys(this.nodes).length===1)[_]=Object.keys(this.nodes);else if(_===void 0&&k===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(_=this.inputChannels);else if(_===void 0){const b=Object.entries(u.versions_seen).map(([x,I])=>Object.values(I).map(N=>[N,x])).flat().filter(([x,I])=>I!==D).sort(([x],[I])=>Ja(x,I));b&&(b.length===1?_=b[0][1]:b[b.length-1][0]!==b[b.length-2][0]&&(_=b[b.length-1][1]))}if(_===void 0)throw new W('Ambiguous update, specify "asNode"');v.push({values:S,asNode:_,taskId:M})}else for(const{asNode:S,values:_,taskId:M}of a){if(S==null)throw new W('"asNode" is required when applying multiple updates');v.push({values:_,asNode:S,taskId:M})}const w=[];for(const{asNode:S,values:_,taskId:M}of v){if(this.nodes[S]===void 0)throw new W(`Node "${S.toString()}" does not exist`);const b=this.nodes[S].getWriters();if(!b.length)throw new W(`No writers found for node "${S.toString()}"`);w.push({name:S,input:_,proc:b.length>1?ot.from(b,{omitSequenceTags:!0}):b[0],writes:[],triggers:[D],id:M??xt(D,u.id),writers:[]})}for(const S of w)await S.proc.invoke(S.input,dn({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[rt]:_=>S.writes.push(..._),[gt]:(_,M=!1)=>ir(u,T,S,_,M)}}));for(const S of w){const _=S.writes.filter(M=>M[0]!==ge);c!==void 0&&_.length>0&&await n.putWrites(f,_,S.id)}me(u,T,w,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const g=or(h,u.channel_versions),E=await n.put(f,ht(u,T,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},g);for(const S of w){const _=S.writes.filter(M=>M[0]===ge);_.length>0&&await n.putWrites(E,_,S.id)}return ct(E,c?c.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 l=!0;const c=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:Jo(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Jo(h,this.channels);const d=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let p;n!==void 0?(p=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[fn]!==void 0?p=["values"]:p=this.streamMode,l=!0);let m;if(this.checkpointer===!1)m=void 0;else if(t!==void 0&&t.configurable?.[J]!==void 0)m=t.configurable[J];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");m=this.checkpointer}const C=t.store??this.store,T=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 k=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),v=t.durability??k??t?.configurable?.[rl]??"async";return[c,p,h,u,a,d,f,m,C,l,T,v]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:_r(e?.signal,n.signal).signal},s=await super.stream(t,r);return new Ho(e?.encoding==="text/event-stream"?dp(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:qf(this.config?.callbacks,e?.callbacks),signal:_r(e?.signal,r.signal).signal};return new Ho(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=ol(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,[l,c,,u,h,d,f,p,m,C,T,k]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const v=new bl({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const x=h.configurable[Ne]??"";h.configurable[Ne]=x.split(X).map(I=>I.split(He)[0]).join(X)}if(c.includes("messages")){const x=new wp(N=>v.push(N)),{callbacks:I}=h;if(I===void 0)h.callbacks=[x];else if(Array.isArray(I))h.callbacks=I.concat(x);else{const N=I.copy();N.addHandler(x,!0),h.callbacks=N}}h.writer??=x=>{if(!c.includes("custom"))return;const I=Sf()?.configurable?.[Ne]?.split(X).slice(0,-1);v.push([I??[],"custom",x])},h.interrupt??=this.userInterrupt??fl;const g=await(await wu(h))?.handleChainStart(this.toJSON(),Jf(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),E=ao(this.channels);let S,_;const b=(async()=>{try{S=await gp.initialize({input:o,config:h,checkpointer:p,nodes:this.nodes,channelSpecs:E,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:m,cache:T,stream:v,interruptAfter:f,interruptBefore:d,manager:g,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:k});const x=new Ep({loop:S,nodeFinished:h.configurable?.[mf]});e?.subgraphs&&(S.config.configurable={...S.config.configurable,[wr]:S.stream}),await this._runLoop({loop:S,runner:x,debug:l,config:h}),k==="sync"&&await Promise.all(S?.checkpointerPromises??[])}catch(x){_=x}finally{try{S&&(await S.store?.stop(),await S.cache?.stop()),await Promise.all(S?.checkpointerPromises??[])}catch(x){_=_??x}_?v.error(_):v.close()}})();try{for await(const x of v){if(x===void 0)throw new Error("Data structure error.");const[I,N,V]=x;if(c.includes(N)){if(n==="text/event-stream"){r?yield[I,N,V]:yield[null,N,V];continue}r&&!C?yield[I,N,V]:C?r?yield[I,V]:yield V:yield[N,V]}}}catch(x){throw await g?.handleChainError(_),x}finally{await b}await g?.handleChainEnd(S?.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 l of o)n==="values"?sl(l)?i.push(l[D]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.flat(1);if(a==null)return{[D]:l};if(typeof a=="object")return{...a,[D]:l}}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&&lp(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&vl(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&cp(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new lf([`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([])}},en=class kl extends St{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new kl(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 W("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new re;return this.value[0]}checkpoint(){if(this.value.length===0)throw new re;return this.value[0]}isAvailable(){return this.value.length!==0}},El=class{path;ends;constructor(t){se.isRunnable(t.path)?this.path=t.path:this.path=qt(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 ce.registerWriter(new Ct({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===Xa.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
50
+ 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=>we(a)?a:this.ends[a]):o=s,o.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(o.filter(we).some(a=>a.node===O))throw new W("Cannot send a packet to the END node");return await n(o,e)??t}},Op=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[X,He])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=qt(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:fo(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."),!se.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=qt(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 xl({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[F]:new en,[O]:new en},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,l]of Object.entries(i))s.attachBranch(o,a,l);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 uf([`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(`
51
+ `),{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}},xl=class extends Ip{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new en,this.nodes[t]=new Sn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new ce([{channel:t,value:yt}],[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 ce([{channel:O,value:yt}],[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]=Ap.subscribeTo(F,{tags:[q]})),this.nodes[t].pipe(n.run(s=>{const o=s.map(i=>we(i)?i:{channel:i===O?O:`branch:${t}:${e}:${i}`,value:yt});return new ce(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 en,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new Eo,r={[F]:n.addNode({schema:ke()},F)},s={};let o={};e&&(o=Object.fromEntries((await Xe(this.getSubgraphsAsync())).filter(l=>qo(l[1]))));function i(l,c,u,h=!1){if(c===O&&s[O]===void 0&&(s[O]=n.addNode({schema:ke()},O)),r[l]!==void 0){if(s[c]===void 0)throw new Error(`End node ${c} not found!`);return n.addEdge(r[l],s[c],u!==c?u:void 0,h)}}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ae(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,p=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let T=function(v){return v?v.lc_runnable:!1},k=function(v,w){if(v!==void 0&&!xo(v))return v;if(T(w))try{let g=w.getName();return g=g.startsWith("Runnable")?g.slice(8):g,g}catch{return w.getName()}else return w.name??"UnknownSchema"};const[m,C]=n.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:k(C.id,C.data),...C}),s[u]={name:k(m.id,m.data),...m}}else{const m=n.addNode(h,u,d);r[u]=m,s[u]=m}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ae(l),ae(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[ae(h),ae(h)])),[O]:O};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,p]of Object.entries(d))i(ae(l),ae(p),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)i(ae(l),ae(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new Eo,r={[F]:n.addNode({schema:ke()},F)},s={};let o={};e&&(o=Object.fromEntries(cn(this.getSubgraphs()).filter(l=>qo(l[1]))));function i(l,c,u,h=!1){return c===O&&s[O]===void 0&&(s[O]=n.addNode({schema:ke()},O)),n.addEdge(r[l],s[c],u!==c?u:void 0,h)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=ae(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,p=o[l]!==void 0?o[l].getGraph({...t,xray:f}):h.getGraph(t);if(p.trimFirstNode(),p.trimLastNode(),Object.keys(p.nodes).length>1){let T=function(v){return v?v.lc_runnable:!1},k=function(v,w){if(v!==void 0&&!xo(v))return v;if(T(w))try{let g=w.getName();return g=g.startsWith("Runnable")?g.slice(8):g,g}catch{return w.getName()}else return w.name??"UnknownSchema"};const[m,C]=n.extend(p,u);if(m===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:k(C.id,C.data),...C}),s[u]={name:k(m.id,m.data),...m}}else{const m=n.addNode(h,u,d);r[u]=m,s[u]=m}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(ae(l),ae(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[ae(h),ae(h)])),[O]:O};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,p]of Object.entries(d))i(ae(l),ae(p),f,!0)}}return n}};function qo(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function ae(t){return t==="subgraph"?`"${t}"`:t}const pt=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Np=class Ml extends St{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new Ml(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 W(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!pt(this.names,this.seen))throw new re}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&pt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&pt(this.names,this.seen)}},$p=class Al extends St{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 Al(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 W(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!pt(this.names,this.seen))throw new re}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&pt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&pt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&pt(this.names,this.seen)}};const Rp="lg:";var jp=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=us(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new Es(o.reducer.fn,o.default):e[r]=new lo}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(us(t)).map(([i,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=hs(c)??hs(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${Rp}${h}`)}return[i,c]});s=vu(t,Object.fromEntries(o)),bu(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=zs(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const kn=new jp;function Sr(t,e){if(e.reducer&&!e.default){const n=Bs(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return kn.extend(n,()=>e),n}else return kn.extend(t,()=>e),t}const Be="__root__",js=Symbol.for("langgraph.state.partial");var Lp=class extends Op{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=kn;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Wp(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??js,this._outputDefinition=o,this._outputRuntimeDefinition=t.output??t.state}else if(ye(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=js,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(zp(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Bp(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Up(t)||Yo(t)){const r=Yo(t)?t.spec:t;this._schemaDefinition=r}else if(Vp(t)){const r=Dp(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)&&!ye(r)}n(e)?(ye(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):ye(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[X,He])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&&(ye(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;se.isRunnable(s)?a=s:typeof s=="function"?a=new Ct({func:s,name:r,trace:!1}):a=qt(s);let l=o?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:o?.retryPolicy,cachePolicy:l,metadata:o?.metadata,input:i??this._schemaDefinition,subgraphs:fo(a)?[a]:o?.subgraphs,ends:o?.ends,defer:o?.defer};this.nodes[r]=c}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)),l=a.length===1&&a[0]===Be?Be:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===Be?Be:c,h=this._interrupt,d=new Fp({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[F]:new en},inputChannels:F,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:h});d.attachNode(F);for(const[f,p]of Object.entries(this.nodes))d.attachNode(f,p);d.attachBranch(F,Fo,Xo(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,Fo,Xo(),{withReader:!1});for(const[f,p]of this.edges)d.attachEdge(f,p);for(const[f,p]of this.waitingEdges)d.attachEdge(f,p);for(const[f,p]of Object.entries(this.branches))for(const[m,C]of Object.entries(p))d.attachBranch(f,m,C);return d.validate()}};function Dp(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Ms(r);return e}var Fp=class extends xl{description;_metaRegistry=kn;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(Q(a))return a.graph===K.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>Q(l))){const l=[];for(const c of a)if(Q(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([Be,c]);return l}else if(a!=null)return[[Be,a]];return null}const s=t;function o(a){if(a){if(Q(a))return a.graph===K.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(Q)){const l=[];for(const c of a)if(Q(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=o(c);u&&l.push(...u??[])}return l}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([l])=>n.includes(l));{const l=Array.isArray(a)?"array":typeof a;throw new W(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:yt,mapper:new Ct({func:n.length&&n[0]===Be?r:o,trace:!1,recurse:!1})}];if(t===F)this.nodes[t]=new Sn({tags:[q],triggers:[F],channels:[F],writers:[new ce(i,[q])]});else{const a=e?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(h=>[h,h])),c=Object.keys(l).length===1&&Be in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new hf:new en(!1),this.nodes[t]=new Sn({triggers:[u],channels:c?Object.keys(l):l,writers:[new ce(i,[q])],mapper:c?void 0:h=>Object.fromEntries(Object.entries(h).filter(([d])=>d in l)),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 ce([{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 $p(new Set(t)):new Np(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new ce([{channel:n,value:r}],[q]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(c=>c!==O);if(!a.length)return;const l=a.map(c=>we(c)?c:{channel:c===O?c:`branch:to:${c}`,value:t});await ce.doWrite({...i,tags:(i.tags??[]).concat([q])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>Wf.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(ye(n))return s(n);if(n===js)return zs(s(r))})();if(Q(t)){const n=t;return t.update&&e!=null&&(n.update=tt(e,t.update)),n}return e!=null?tt(e,t):t}isInterrupted(t){return sl(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return ye(e)&&tt(e,t),t}};function Up(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Qa(e))}function Yo(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function Vp(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Bp(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function zp(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Wp(t){return!(typeof t!="object"||t==null||!("state"in t)||!ye(t.state)||"input"in t&&!ye(t.input)||"output"in t&&!ye(t.output))}function Hp(t){if(we(t))return[t];const e=[];Q(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Q));const n=[];for(const r of e){if(r.graph===K.PARENT)throw new Za(r);we(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Xo(){const t=new Ct({func:Hp,tags:[q],trace:!1,recurse:!1,name:"<control_branch>"});return new El({path:t})}const Pl="__remove_all__";function Il(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(gn),o=r.map(gn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=ur(),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=ur(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===Pl&&(i=u)}if(i!=null)return o.slice(i+1);const a=[...s],l=new Map(a.map((u,h)=>[u.id,h])),c=new Set;for(const u of o){const h=l.get(u.id);if(h!==void 0)u.getType()==="remove"?c.add(u.id):(c.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}')`);l.set(u.id,a.length),a.push(u)}}return a.filter(u=>!c.has(u.id))}xs.Root({messages:xs({reducer:Il,default:()=>[]})});const Gp={reducer:{fn:Il},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},Kp=z({messages:Sr(Ce(),Gp)});af();const Ls=Symbol.for("langgraph-zod");Ls in globalThis||(globalThis[Ls]=new WeakSet);function Zo(t){const e=globalThis[Ls];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Sr(n,{jsonSchemaExtra:r})},reducer(r,s){const o=Bs(n);return Sr(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Zo(_u.prototype),Zo(gc.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 Jp=class extends yc{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Bs(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new Jp(kn);function qp(t=!0,e,n=[]){const r={jumpTo:Ae([Re("model_request"),Re("tools"),Re("end"),Su()]).optional()},s=i=>{const a=Lr(i)?us(i):i.shape;for(const[l,c]of Object.entries(a))l.startsWith("_")||l in r||(r[l]=Lr(c)?Ws():c)};e&&("shape"in e||Lr(e))&&s(e);for(const i of n)i.stateSchema&&s(i.stateSchema);t&&(r.structuredResponse=ee().optional());const o=Sr(Ce(),{jsonSchemaExtra:{langgraph_type:"messages"}});return{state:Kp.extend(r),input:z({messages:o,...Object.fromEntries(Object.entries(r).filter(([i])=>!["structuredResponse","jumpTo"].includes(i)))}),output:z({messages:o,...Object.fromEntries(Object.entries(r).filter(([i])=>i!=="jumpTo"))})}}const ns=/<name>(.*?)<\/name>/s,rs=/<content>(.*?)<\/content>/s;function Yp(t){if(!P.isInstance(t)||Jt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new P({...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 P({...t.lc_kwargs,content:n,name:void 0})}function Xp(t){if(!P.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(ns),o=r.text.match(rs);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(ns),o=r.text.match(rs);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(ns),o=r.match(rs);if(!s||!o)return t;n=s[1],e=o[1]}return new P({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function dt(t){return se.isRunnable(t)}function Qo(t){return Gs(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const ss=(t,e,n={})=>{if(Qo(t))return t.bindTools(e,n);if($e.isRunnableBinding(t)&&Qo(t.bound)){const r=t.bound.bindTools(e,n);return $e.isRunnableBinding(r)?new $e({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new $e({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function Ol(t){if(typeof t=="function")return;let e=t;if(ot.isRunnableSequence(e)&&(e=e.steps.find(n=>$e.isRunnableBinding(n))||e),!hr(e)){if($e.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 fs}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new fs}}function Cr(t){return!!(P.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Zp(t){if(t==null)return new ne("");if(ne.isInstance(t))return t;if(typeof t=="string")return new ne({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function Qp(t,e,n={}){const r=ss(t,e,n);if(r)return r;if(hr(t)){const s=ss(await t._getModelInstance(),e,n);if(s)return s}if(ot.isRunnableSequence(t)){const s=t.steps.findIndex(o=>$e.isRunnableBinding(o)||Gs(o)||hr(o));if(s>=0){const o=ss(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),ot.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function em(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 tm(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return em(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?tt(n.stateSchema,{...o.state}):{}}},i);if(!j.isInstance(a)&&!Q(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 nm(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=Cu(r.stateSchema,a=>a.startsWith("_")),o=await Tu(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(`
52
52
  `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
53
53
  ${i}
54
54
 
@@ -67,12 +67,12 @@ To fix this, either:
67
67
  agent.invoke({
68
68
  messages: [...],
69
69
  ${o.error.issues[0]?.path.join(".")}: "value"
70
- })`)}return n}function tm(t){const e={messages:Se(()=>[]),structuredResponse:zs().optional()};if(!t)return B(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 B(r)}function Ie(t){if(t){if(["model_request","tools",O].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return O;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function Il(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var mo=class extends re{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=Ve(this.config,e),r=await ze.runWithConfig(n,async()=>this.func(t,n));return re.isRunnable(r)&&this.recurse?await ze.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function nm(t,e){let n,r;if(e==="inline")n=Jp,r=qp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return st.from([lr.from(s),t,lr.from(r)])}function rm(t){return I.isInstance(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}const H="model_request";var sm=class extends mo{#e;#r;#t;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t,this.#r=t.systemMessage}#n(t){if(!this.#e.responseFormat)return;const e=Ai(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof Xe)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Je).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(t,e){const n=t.messages.at(-1);if(n&&j.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#c(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof G?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#h(t,r)?{messages:[new I({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#l(){if(typeof this.#e.model=="string")return it(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#c(t,e,n={}){const r=await this.#l(),s=e,o=async c=>{Pl(c.model);const u=this.#n(c.model),h=await this.#a(c.model,c,u),d=[...this.#t.text===""?[]:[this.#t],...c.messages],f=Il(this.#e.signal,e.signal),p=await Cu(h.invoke(d,{...e,signal:f}),f);if(u?.type==="native"){const E=u.strategy.parse(p);return E?{structuredResponse:E,messages:[p]}:p}if(!u||!p.tool_calls)return p;const m=p.tool_calls.filter(E=>E.name in u.tools);if(m.length===0)return p;if(m.length>1)return this.#u(p,m,u);const C=u.tools[m[0].name]?.options?.toolMessageContent;return this.#o(p,m[0],u,C??n.lastMessage)},i=this.#e.wrapModelCallHookMiddleware??[];let a=o;for(let c=i.length-1;c>=0;c--){const[u,h]=i[c];if(u.wrapModelCall){const d=a,f=u,p=h;a=async m=>{const S=f.contextSchema?et(f.contextSchema,s?.context||{}):s?.context,C=Object.freeze({context:S,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),E={...m,state:{...u.stateSchema?et(Bs(u.stateSchema),t):{},...p(),messages:t.messages},runtime:C},b=async w=>{const g=w.tools??[],k=g.filter(M=>ut(M)&&!this.#e.toolClasses.some(P=>P.name===M.name));if(k.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${k.map(M=>M.name).join(", ")}. This is not supported.`);const _=g.filter(M=>ut(M)&&this.#e.toolClasses.every(P=>P!==M));if(_.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${_.map(M=>M.name).join(", ")}. This is not supported.`);let v=w;const x=w.systemPrompt!==this.#t.text,T=w.systemMessage!==this.#t;if(x&&T)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");return x&&(this.#t=new te({content:[{type:"text",text:w.systemPrompt}]}),v={...w,systemPrompt:this.#t.text,systemMessage:this.#t}),T&&(this.#t=new te({...w.systemMessage}),v={...w,systemPrompt:this.#t.text,systemMessage:this.#t}),d(v)};if(!f.wrapModelCall)return b(E);try{const w=await f.wrapModelCall(E,b);if(!rm(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}}}}this.#t=this.#r;const l={model:r,systemPrompt:this.#t?.text,systemMessage:this.#t,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(l)}#u(t,e,n){const r=new fs(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#o(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new j({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new I(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(s===!1)throw t;if(s===void 0||typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof fs))return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:H});if(typeof s=="string")return new G({update:{messages:[e,new j({content:s,tool_call_id:o})]},goto:H});if(typeof s=="function"){const i=await s(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new G({update:{messages:[e,new j({content:i,tool_call_id:o})]},goto:H})}return new G({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:H})}#h(t,e){const n=I.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&&Sr(t.messages.at(-1))))}async#a(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c=e?.modelSettings?.strict??n?.strategy?.strict??!0,u={name:n.strategy.schema?.name??"extract",description:us(n.strategy.schema),schema:n.strategy.schema,strict:c};Object.assign(r,{response_format:{type:"json_schema",json_schema:u},output_format:{type:"json_schema",schema:n.strategy.schema},headers:{"anthropic-beta":"structured-outputs-2025-11-13"},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:c})}const a=await Xp(t,o,{...r,...e?.modelSettings??{},tool_choice:i});return this.#e.includeAgentName==="inline"?nm(a,this.#e.includeAgentName):a}getState(){const t=super.getState(),e=t&&!(t instanceof G)?t:{};return{messages:[],...e}}};const W="tools",Ol=t=>Array.isArray(t)&&t.every(cn.isInstance),om=t=>typeof t=="object"&&t!=null&&"messages"in t&&Ol(t.messages),im=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function am(t,e){return t instanceof Ws?new j({content:t.message,tool_call_id:e.id,name:e.name}):new j({content:`${t}
71
- Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var lm=class extends mo{tools;trace=!1;signal;handleToolErrors=am;wrapToolCall;constructor(t,e){const{name:n,tags:r,handleToolErrors:s,signal:o,wrapToolCall:i}=e??{};super({name:n,tags:r,func:(a,l)=>this.run(a,l)}),this.options=e,this.tools=t,this.handleToolErrors=s??this.handleToolErrors,this.signal=o,this.wrapToolCall=i}#e(t,e,n){if(ht(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&&j.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new j({name:e.name,content:`${t}
72
- Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,n){const r=async l=>{const{toolCall:c}=l,u=this.tools.find(h=>h.name===c.name);if(u===void 0)throw new Error(`Tool "${c.name}" not found.`);try{const h=await u.invoke({...c,type:"tool_call"},{...e,config:e,toolCallId:c.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Il(this.signal,e.signal)});return j.isInstance(h)||Z(h)?h:new j({name:u.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:c.id})}catch(h){throw h instanceof Tu?new Ws(h,c):h}},s=e,o={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal},i=this.tools.find(l=>l.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(l){return this.#e(l,t,!0)}try{return await r(a)}catch(l){return this.#e(l,t,!1)}}async run(t,e){let n;if(im(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(Ol(t))o=t;else if(om(t))o=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=o.length-1;l>=0;l-=1){const c=o[l];if(I.isInstance(c)){a=c;break}}if(!I.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!i.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(Z))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)Z(o)?o.graph===G.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>cm(i))?s?s.goto.push(...o.goto):s=new G({graph:G.PARENT,goto:o.goto}):r.push(o):r.push(Array.isArray(t)?[o]:{messages:[o]});return s&&r.push(s),r}};function cm(t){return t instanceof le}var um=class{},hm=class{},Ir=class extends mo{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let n={};if(this.middleware.contextSchema){const l=this.middleware.contextSchema?.shape;if(l){const c={},u=e?.context||{};for(const h of Object.keys(l))h in u&&(c[h]=u[h]);n=et(this.middleware.contextSchema,c)}}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 hm,{...s,context:Object.freeze(Object.assign(new um,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Ze(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Ze(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Ze(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Ze(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const l=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}, ${l}.`)}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:tm(this.middleware.stateSchema)}}},dm=class extends Ir{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 Mr(this.middleware.beforeAgent)(t,e)}},fm=class extends Ir{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 Mr(this.middleware.beforeModel)(t,e)}},pm=class extends Ir{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 Mr(this.middleware.afterModel)(t,e)}},mm=class extends Ir{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 Mr(this.middleware.afterAgent)(t,e)}},gm=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}},ym=class{#e;#r="v2";#t;#n=new gm;constructor(t){if(this.options=t,this.#r=t.version??this.#r,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&Pl(t.model);const e=this.options.middleware?.filter(g=>g.tools).flatMap(g=>g.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(ut).filter(g=>"returnDirect"in g&&g.returnDirect).map(g=>g.name)),{state:s,input:o,output:i}=Kp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),l=new Rp({state:s,input:o,output:i},this.options.contextSchema),c=[],u=[],h=[],d=[],f=[];this.#t=new sm({model:this.options.model,systemMessage:Yp(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:f});const p=new Set,m=this.options.middleware??[];for(let g=0;g<m.length;g++){let k,_,v,x;const T=m[g];if(p.has(T.name))throw new Error(`Middleware ${T.name} is defined multiple times`);if(p.add(T.name),T.beforeAgent){k=new dm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,k);const M=`${T.name}.before_agent`;c.push({index:g,name:M,allowed:Ze(T.beforeAgent)}),l.addNode(M,k,k.nodeOptions)}if(T.beforeModel){_=new fm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,_);const M=`${T.name}.before_model`;u.push({index:g,name:M,allowed:Ze(T.beforeModel)}),l.addNode(M,_,_.nodeOptions)}if(T.afterModel){v=new pm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,v);const M=`${T.name}.after_model`;h.push({index:g,name:M,allowed:Ze(T.afterModel)}),l.addNode(M,v,v.nodeOptions)}if(T.afterAgent){x=new mm(T,{getState:()=>this.#n.getState(T.name)}),this.#n.addNode(T,x);const M=`${T.name}.after_agent`;d.push({index:g,name:M,allowed:Ze(T.afterAgent)}),l.addNode(M,x,x.nodeOptions)}T.wrapModelCall&&f.push([T,()=>this.#n.getState(T.name)])}if(l.addNode(H,this.#t),n.filter(ut).length>0){const g=new lm(n.filter(ut),{signal:this.options.signal,wrapToolCall:Qp(m)});l.addNode(W,g)}let S;c.length>0?S=c[0].name:u.length>0?S=u[0].name:S=H;const C=u.length>0?u[0].name:H,E=d.length>0?d[d.length-1].name:O;l.addEdge(F,S);const b=n.filter(ut);for(let g=0;g<c.length;g++){const k=c[g],_=k.name,x=g===c.length-1?C:c[g+1].name;if(k.allowed&&k.allowed.length>0){const T=b.length>0,M=k.allowed.map(N=>Ie(N)).filter(N=>N!==W||T),P=Array.from(new Set([x,...M.map(N=>N===O?E:N)]));l.addConditionalEdges(_,this.#i(b,x,E),P)}else l.addEdge(_,x)}for(let g=0;g<u.length;g++){const k=u[g],_=k.name,x=g===u.length-1?H:u[g+1].name;if(k.allowed&&k.allowed.length>0){const T=b.length>0,M=k.allowed.map(N=>Ie(N)).filter(N=>N!==W||T),P=Array.from(new Set([x,...M]));l.addConditionalEdges(_,this.#h(b,x),P)}else l.addEdge(_,x)}const w=h.at(-1);if(h.length>0&&w)l.addEdge(H,w.name);else{const k=this.#s(b).map(_=>_===O?E:_);k.length===1?l.addEdge(H,k[0]):l.addConditionalEdges(H,this.#c(E),k)}for(let g=h.length-1;g>0;g--){const k=h[g],_=k.name,v=h[g-1].name;if(k.allowed&&k.allowed.length>0){const x=b.length>0,T=k.allowed.map(P=>Ie(P)).filter(P=>P!==W||x),M=Array.from(new Set([v,...T]));l.addConditionalEdges(_,this.#o(b,k.allowed,v),M)}else l.addEdge(_,v)}if(h.length>0){const g=h[0],k=g.name,_=this.#s(b,!0).filter(T=>T!==W||n.filter(ut).length>0),v=!!(g.allowed&&g.allowed.length>0),x=_.map(T=>T===O?E:T);l.addConditionalEdges(k,this.#u(b,v,E),x)}for(let g=d.length-1;g>0;g--){const k=d[g],_=k.name,v=d[g-1].name;if(k.allowed&&k.allowed.length>0){const x=b.length>0,T=k.allowed.map(P=>Ie(P)).filter(P=>P!==W||x),M=Array.from(new Set([v,...T]));l.addConditionalEdges(_,this.#o(b,k.allowed,v),M)}else l.addEdge(_,v)}if(d.length>0){const g=d[0],k=g.name;if(g.allowed&&g.allowed.length>0){const _=b.length>0,v=g.allowed.map(T=>Ie(T)).filter(T=>T!==W||_),x=Array.from(new Set([O,...v]));l.addConditionalEdges(k,this.#o(b,g.allowed,O),x)}else l.addEdge(k,O)}if(b.length>0){const g=C;r.size>0?l.addConditionalEdges(W,this.#l(r,E),[g,E]):l.addEdge(W,g)}this.#e=l.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#s(t,e=!1){const n=[];return t.length>0&&n.push(W),e&&n.push(H),n.push(O),n}#l(t,e){return n=>{const s=n.messages,o=s[s.length-1];return j.isInstance(o)&&o.name&&t.has(o.name)?this.options.responseFormat?H:e:H}}#c(t=O){return e=>{const s=e.messages.at(-1);if(!I.isInstance(s)||!s.tool_calls||s.tool_calls.length===0||s.tool_calls.every(a=>a.name.startsWith("extract-")))return t;if(this.#r==="v1")return W;const i=s.tool_calls.filter(a=>!a.name.startsWith("extract-"));return i.length===0?t:i.map(a=>new le(W,{...e,lg_tool_call:a}))}}#u(t,e,n){const r=!!this.options.responseFormat;return s=>{const o=s,i=o.messages,a=i.at(-1);if(I.isInstance(a)&&(!a.tool_calls||a.tool_calls.length===0))return n;if(e&&o.jumpTo){const p=Ie(o.jumpTo);return p===O?n:p===W?t.length===0?n:new le(W,{...s,jumpTo:void 0}):new le(H,{...s,jumpTo:void 0})}const l=i.filter(j.isInstance),c=i.filter(I.isInstance).at(-1),u=c?.tool_calls?.filter(p=>!l.some(m=>m.tool_call_id===p.id));if(u&&u.length>0)return u.map(p=>new le(W,{...s,lg_tool_call:p}));const h=c?.tool_calls?.some(p=>p.name.startsWith("extract-"));if(u&&u.length===0&&!h&&r)return H;if(!I.isInstance(a)||!a.tool_calls||a.tool_calls.length===0)return n;const d=a.tool_calls.every(p=>p.name.startsWith("extract-")),f=a.tool_calls.some(p=>!p.name.startsWith("extract-"));return d||!f?n:W}}#o(t,e,n){const r=new Set(e.map(s=>Ie(s)));return s=>{const o=s;if(o.jumpTo){const i=Ie(o.jumpTo);if(i===O&&r.has(O))return O;if(i===W&&r.has(W))return t.length===0?O:new le(W,{...s,jumpTo:void 0});if(i===H&&r.has(H))return new le(H,{...s,jumpTo:void 0})}return n}}#i(t,e,n){return r=>{const s=r;if(!s.jumpTo)return e;const o=Ie(s.jumpTo);return o===O?n:o===W?t.length===0?n:new le(W,{...r,jumpTo:void 0}):new le(H,{...r,jumpTo:void 0})}}#h(t,e){return n=>{const r=n;if(!r.jumpTo)return e;const s=Ie(r.jumpTo);return s===O?O:s===W?t.length===0?O:new le(W,{...n,jumpTo:void 0}):new le(H,{...n,jumpTo:void 0})}}async#a(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof G||!t)return t;const n=await em(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.#a(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#a(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)}get builder(){return this.#e.builder}};function Nl(t){return new ym(t)}const wm=Mn().args(Se(),Se(),Se()).returns(Ae([Q(),wi(Q())])),$l=["approve","edit","reject"],vm=Jt($l),bm=B({allowedDecisions:Ge(vm),description:Ae([Q(),wm]).optional(),argsSchema:mn(zs()).optional()}),Zo=B({interruptOn:mn(Ae([ft(),bm])).optional(),descriptionPrefix:Q().default("Tool execution requires approval")});function _m(t){const e=async(r,s,o,i)=>{const a=r.name,l=r.args,c=s.description;let u;typeof c=="function"?u=await c(r,o,i):c!==void 0?u=c:u=`${t.descriptionPrefix??"Tool execution requires approval"}
70
+ })`)}return n}function rm(t){const e={messages:Ce(()=>[]),structuredResponse:Ws().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 Ie(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 Nl(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var go=class extends se{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=Ve(this.config,e),r=await ze.runWithConfig(n,async()=>this.func(t,n));return se.isRunnable(r)&&this.recurse?await ze.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function sm(t,e){let n,r;if(e==="inline")n=Yp,r=Xp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return ot.from([cr.from(s),t,cr.from(r)])}function om(t){return P.isInstance(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}const G="model_request";var im=class extends go{#e;#r;#t;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t,this.#r=t.systemMessage}#n(t){if(!this.#e.responseFormat)return;const e=Ii(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof Ze)?{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&&j.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#c(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.#h(t,r)?{messages:[new P({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#l(){if(typeof this.#e.model=="string")return at(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#c(t,e,n={}){const r=await this.#l(),s=e,o=async c=>{Ol(c.model);const u=this.#n(c.model),h=await this.#a(c.model,c,u),d=[...this.#t.text===""?[]:[this.#t],...c.messages],f=Nl(this.#e.signal,e.signal),p=await ku(h.invoke(d,{...e,signal:f}),f);if(u?.type==="native"){const k=u.strategy.parse(p);return k?{structuredResponse:k,messages:[p]}:p}if(!u||!p.tool_calls)return p;const m=p.tool_calls.filter(k=>k.name in u.tools);if(m.length===0)return p;if(m.length>1)return this.#u(p,m,u);const T=u.tools[m[0].name]?.options?.toolMessageContent;return this.#o(p,m[0],u,T??n.lastMessage)},i=this.#e.wrapModelCallHookMiddleware??[];let a=o;for(let c=i.length-1;c>=0;c--){const[u,h]=i[c];if(u.wrapModelCall){const d=a,f=u,p=h;a=async m=>{const C=f.contextSchema?tt(f.contextSchema,s?.context||{}):s?.context,T=Object.freeze({context:C,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),k={...m,state:{...u.stateSchema?tt(zs(u.stateSchema),t):{},...p(),messages:t.messages},runtime:T},v=async w=>{const g=w.tools??[],E=g.filter(x=>dt(x)&&!this.#e.toolClasses.some(I=>I.name===x.name));if(E.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${E.map(x=>x.name).join(", ")}. This is not supported.`);const S=g.filter(x=>dt(x)&&this.#e.toolClasses.every(I=>I!==x));if(S.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${S.map(x=>x.name).join(", ")}. This is not supported.`);let _=w;const M=w.systemPrompt!==this.#t.text,b=w.systemMessage!==this.#t;if(M&&b)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");return M&&(this.#t=new ne({content:[{type:"text",text:w.systemPrompt}]}),_={...w,systemPrompt:this.#t.text,systemMessage:this.#t}),b&&(this.#t=new ne({...w.systemMessage}),_={...w,systemPrompt:this.#t.text,systemMessage:this.#t}),d(_)};if(!f.wrapModelCall)return v(k);try{const w=await f.wrapModelCall(k,v);if(!om(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}}}}this.#t=this.#r;const l={model:r,systemPrompt:this.#t?.text,systemMessage:this.#t,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(l)}#u(t,e,n){const r=new ps(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#o(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new j({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new P(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(s===!1)throw t;if(s===void 0||typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof ps))return new K({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:G});if(typeof s=="string")return new K({update:{messages:[e,new j({content:s,tool_call_id:o})]},goto:G});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 j({content:i,tool_call_id:o})]},goto:G})}return new K({update:{messages:[e,new j({content:t.message,tool_call_id:o})]},goto:G})}#h(t,e){const n=P.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&&Cr(t.messages.at(-1))))}async#a(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c=e?.modelSettings?.strict??n?.strategy?.strict??!0,u={name:n.strategy.schema?.name??"extract",description:hs(n.strategy.schema),schema:n.strategy.schema,strict:c};Object.assign(r,{response_format:{type:"json_schema",json_schema:u},output_format:{type:"json_schema",schema:n.strategy.schema},headers:{"anthropic-beta":"structured-outputs-2025-11-13"},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:c})}const a=await Qp(t,o,{...r,...e?.modelSettings??{},tool_choice:i});return this.#e.includeAgentName==="inline"?sm(a,this.#e.includeAgentName):a}getState(){const t=super.getState(),e=t&&!(t instanceof K)?t:{};return{messages:[],...e}}};const H="tools",$l=t=>Array.isArray(t)&&t.every(hn.isInstance),am=t=>typeof t=="object"&&t!=null&&"messages"in t&&$l(t.messages),lm=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function cm(t,e){return t instanceof Hs?new j({content:t.message,tool_call_id:e.id,name:e.name}):new j({content:`${t}
71
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var um=class extends go{tools;trace=!1;signal;handleToolErrors=cm;wrapToolCall;constructor(t,e){const{name:n,tags:r,handleToolErrors:s,signal:o,wrapToolCall:i}=e??{};super({name:n,tags:r,func:(a,l)=>this.run(a,l)}),this.options=e,this.tools=t,this.handleToolErrors=s??this.handleToolErrors,this.signal=o,this.wrapToolCall=i}#e(t,e,n){if(ft(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&&j.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new j({name:e.name,content:`${t}
72
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,n){const r=async l=>{const{toolCall:c}=l,u=this.tools.find(h=>h.name===c.name);if(u===void 0)throw new Error(`Tool "${c.name}" not found.`);try{const h=await u.invoke({...c,type:"tool_call"},{...e,config:e,toolCallId:c.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Nl(this.signal,e.signal)});return j.isInstance(h)||Q(h)?h:new j({name:u.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:c.id})}catch(h){throw h instanceof Eu?new Hs(h,c):h}},s=e,o={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal},i=this.tools.find(l=>l.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(l){return this.#e(l,t,!0)}try{return await r(a)}catch(l){return this.#e(l,t,!1)}}async run(t,e){let n;if(lm(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if($l(t))o=t;else if(am(t))o=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=o.length-1;l>=0;l-=1){const c=o[l];if(P.isInstance(c)){a=c;break}}if(!P.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!i.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(Q))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)Q(o)?o.graph===K.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>hm(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 hm(t){return t instanceof le}var dm=class{},fm=class{},Or=class extends go{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let n={};if(this.middleware.contextSchema){const l=this.middleware.contextSchema?.shape;if(l){const c={},u=e?.context||{};for(const h of Object.keys(l))h in u&&(c[h]=u[h]);n=tt(this.middleware.contextSchema,c)}}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 fm,{...s,context:Object.freeze(Object.assign(new dm,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Qe(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Qe(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Qe(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Qe(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const l=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}, ${l}.`)}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:rm(this.middleware.stateSchema)}}},pm=class extends Or{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 Ar(this.middleware.beforeAgent)(t,e)}},mm=class extends Or{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 Ar(this.middleware.beforeModel)(t,e)}},gm=class extends Or{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 Ar(this.middleware.afterModel)(t,e)}},ym=class extends Or{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 Ar(this.middleware.afterAgent)(t,e)}},wm=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}},vm=class{#e;#r="v2";#t;#n=new wm;constructor(t){if(this.options=t,this.#r=t.version??this.#r,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&Ol(t.model);const e=this.options.middleware?.filter(g=>g.tools).flatMap(g=>g.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(dt).filter(g=>"returnDirect"in g&&g.returnDirect).map(g=>g.name)),{state:s,input:o,output:i}=qp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),l=new Lp({state:s,input:o,output:i},this.options.contextSchema),c=[],u=[],h=[],d=[],f=[];this.#t=new im({model:this.options.model,systemMessage:Zp(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:f});const p=new Set,m=this.options.middleware??[];for(let g=0;g<m.length;g++){let E,S,_,M;const b=m[g];if(p.has(b.name))throw new Error(`Middleware ${b.name} is defined multiple times`);if(p.add(b.name),b.beforeAgent){E=new pm(b,{getState:()=>this.#n.getState(b.name)}),this.#n.addNode(b,E);const x=`${b.name}.before_agent`;c.push({index:g,name:x,allowed:Qe(b.beforeAgent)}),l.addNode(x,E,E.nodeOptions)}if(b.beforeModel){S=new mm(b,{getState:()=>this.#n.getState(b.name)}),this.#n.addNode(b,S);const x=`${b.name}.before_model`;u.push({index:g,name:x,allowed:Qe(b.beforeModel)}),l.addNode(x,S,S.nodeOptions)}if(b.afterModel){_=new gm(b,{getState:()=>this.#n.getState(b.name)}),this.#n.addNode(b,_);const x=`${b.name}.after_model`;h.push({index:g,name:x,allowed:Qe(b.afterModel)}),l.addNode(x,_,_.nodeOptions)}if(b.afterAgent){M=new ym(b,{getState:()=>this.#n.getState(b.name)}),this.#n.addNode(b,M);const x=`${b.name}.after_agent`;d.push({index:g,name:x,allowed:Qe(b.afterAgent)}),l.addNode(x,M,M.nodeOptions)}b.wrapModelCall&&f.push([b,()=>this.#n.getState(b.name)])}if(l.addNode(G,this.#t),n.filter(dt).length>0){const g=new um(n.filter(dt),{signal:this.options.signal,wrapToolCall:tm(m)});l.addNode(H,g)}let C;c.length>0?C=c[0].name:u.length>0?C=u[0].name:C=G;const T=u.length>0?u[0].name:G,k=d.length>0?d[d.length-1].name:O;l.addEdge(F,C);const v=n.filter(dt);for(let g=0;g<c.length;g++){const E=c[g],S=E.name,M=g===c.length-1?T:c[g+1].name;if(E.allowed&&E.allowed.length>0){const b=v.length>0,x=E.allowed.map(N=>Ie(N)).filter(N=>N!==H||b),I=Array.from(new Set([M,...x.map(N=>N===O?k:N)]));l.addConditionalEdges(S,this.#i(v,M,k),I)}else l.addEdge(S,M)}for(let g=0;g<u.length;g++){const E=u[g],S=E.name,M=g===u.length-1?G:u[g+1].name;if(E.allowed&&E.allowed.length>0){const b=v.length>0,x=E.allowed.map(N=>Ie(N)).filter(N=>N!==H||b),I=Array.from(new Set([M,...x]));l.addConditionalEdges(S,this.#h(v,M),I)}else l.addEdge(S,M)}const w=h.at(-1);if(h.length>0&&w)l.addEdge(G,w.name);else{const E=this.#s(v).map(S=>S===O?k:S);E.length===1?l.addEdge(G,E[0]):l.addConditionalEdges(G,this.#c(k),E)}for(let g=h.length-1;g>0;g--){const E=h[g],S=E.name,_=h[g-1].name;if(E.allowed&&E.allowed.length>0){const M=v.length>0,b=E.allowed.map(I=>Ie(I)).filter(I=>I!==H||M),x=Array.from(new Set([_,...b]));l.addConditionalEdges(S,this.#o(v,E.allowed,_),x)}else l.addEdge(S,_)}if(h.length>0){const g=h[0],E=g.name,S=this.#s(v,!0).filter(b=>b!==H||n.filter(dt).length>0),_=!!(g.allowed&&g.allowed.length>0),M=S.map(b=>b===O?k:b);l.addConditionalEdges(E,this.#u(v,_,k),M)}for(let g=d.length-1;g>0;g--){const E=d[g],S=E.name,_=d[g-1].name;if(E.allowed&&E.allowed.length>0){const M=v.length>0,b=E.allowed.map(I=>Ie(I)).filter(I=>I!==H||M),x=Array.from(new Set([_,...b]));l.addConditionalEdges(S,this.#o(v,E.allowed,_),x)}else l.addEdge(S,_)}if(d.length>0){const g=d[0],E=g.name;if(g.allowed&&g.allowed.length>0){const S=v.length>0,_=g.allowed.map(b=>Ie(b)).filter(b=>b!==H||S),M=Array.from(new Set([O,..._]));l.addConditionalEdges(E,this.#o(v,g.allowed,O),M)}else l.addEdge(E,O)}if(v.length>0){const g=T;r.size>0?l.addConditionalEdges(H,this.#l(r,k),[g,k]):l.addEdge(H,g)}this.#e=l.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#s(t,e=!1){const n=[];return t.length>0&&n.push(H),e&&n.push(G),n.push(O),n}#l(t,e){return n=>{const s=n.messages,o=s[s.length-1];return j.isInstance(o)&&o.name&&t.has(o.name)?this.options.responseFormat?G:e:G}}#c(t=O){return e=>{const s=e.messages.at(-1);if(!P.isInstance(s)||!s.tool_calls||s.tool_calls.length===0||s.tool_calls.every(a=>a.name.startsWith("extract-")))return t;if(this.#r==="v1")return H;const i=s.tool_calls.filter(a=>!a.name.startsWith("extract-"));return i.length===0?t:i.map(a=>new le(H,{...e,lg_tool_call:a}))}}#u(t,e,n){const r=!!this.options.responseFormat;return s=>{const o=s,i=o.messages,a=i.at(-1);if(P.isInstance(a)&&(!a.tool_calls||a.tool_calls.length===0))return n;if(e&&o.jumpTo){const p=Ie(o.jumpTo);return p===O?n:p===H?t.length===0?n:new le(H,{...s,jumpTo:void 0}):new le(G,{...s,jumpTo:void 0})}const l=i.filter(j.isInstance),c=i.filter(P.isInstance).at(-1),u=c?.tool_calls?.filter(p=>!l.some(m=>m.tool_call_id===p.id));if(u&&u.length>0)return u.map(p=>new le(H,{...s,lg_tool_call:p}));const h=c?.tool_calls?.some(p=>p.name.startsWith("extract-"));if(u&&u.length===0&&!h&&r)return G;if(!P.isInstance(a)||!a.tool_calls||a.tool_calls.length===0)return n;const d=a.tool_calls.every(p=>p.name.startsWith("extract-")),f=a.tool_calls.some(p=>!p.name.startsWith("extract-"));return d||!f?n:H}}#o(t,e,n){const r=new Set(e.map(s=>Ie(s)));return s=>{const o=s;if(o.jumpTo){const i=Ie(o.jumpTo);if(i===O&&r.has(O))return O;if(i===H&&r.has(H))return t.length===0?O:new le(H,{...s,jumpTo:void 0});if(i===G&&r.has(G))return new le(G,{...s,jumpTo:void 0})}return n}}#i(t,e,n){return r=>{const s=r;if(!s.jumpTo)return e;const o=Ie(s.jumpTo);return o===O?n:o===H?t.length===0?n:new le(H,{...r,jumpTo:void 0}):new le(G,{...r,jumpTo:void 0})}}#h(t,e){return n=>{const r=n;if(!r.jumpTo)return e;const s=Ie(r.jumpTo);return s===O?O:s===H?t.length===0?O:new le(H,{...n,jumpTo:void 0}):new le(G,{...n,jumpTo:void 0})}}async#a(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof K||!t)return t;const n=await nm(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.#a(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#a(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)}get builder(){return this.#e.builder}};function Rl(t){return new vm(t)}const bm=Pn().args(Ce(),Ce(),Ce()).returns(Ae([ee(),bi(ee())])),jl=["approve","edit","reject"],_m=Yt(jl),Sm=z({allowedDecisions:Ge(_m),description:Ae([ee(),bm]).optional(),argsSchema:yn(Ws()).optional()}),ei=z({interruptOn:yn(Ae([mt(),Sm])).optional(),descriptionPrefix:ee().default("Tool execution requires approval")});function Cm(t){const e=async(r,s,o,i)=>{const a=r.name,l=r.args,c=s.description;let u;typeof c=="function"?u=await c(r,o,i):c!==void 0?u=c:u=`${t.descriptionPrefix??"Tool execution requires approval"}
73
73
 
74
74
  Tool: ${a}
75
- Args: ${JSON.stringify(l,null,2)}`;const h={name:a,args:l,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 l=r.editedAction;if(!l||typeof l.name!="string")throw new Error(`Invalid edited action for tool "${s.name}": name must be a string`);if(!l.args||typeof l.args!="object")throw new Error(`Invalid edited action for tool "${s.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:l.name,args:l.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 l=r.message??`User rejected the tool call for \`${s.name}\` with id ${s.id}`,c=new j({content:l,name:s.name,tool_call_id:s.id,status:"error"});return{revisedToolCall:s,toolMessage:c}}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 se({name:"HumanInTheLoopMiddleware",contextSchema:Zo,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=et(Zo,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(w=>I.isInstance(w));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const l={};for(const[w,g]of Object.entries(o.interruptOn))typeof g=="boolean"?g===!0&&(l[w]={allowedDecisions:[...$l]}):g.allowedDecisions&&(l[w]=g);const c=[],u=[];for(const w of a.tool_calls)w.name in l?c.push(w):u.push(w);if(!c.length)return;const h=[],d=[];for(const w of c){const g=l[w.name],{actionRequest:k,reviewConfig:_}=await e(w,g,r,s);h.push(k),d.push(_)}const m=(await hl({actionRequests:h,reviewConfigs:d})).decisions;if(!m||!Array.isArray(m))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(m.length!==c.length)throw new Error(`Number of human decisions (${m.length}) does not match number of hanging tool calls (${c.length}).`);const S=[...u],C=[],E=m.some(w=>w.type==="reject");for(let w=0;w<m.length;w++){const g=m[w],k=c[w],_=l[k.name],{revisedToolCall:v,toolMessage:x}=n(g,k,_);v&&(!E||g.type==="reject")&&S.push(v),x&&C.push(x)}I.isInstance(a)&&(a.tool_calls=S);const b=E?"model":void 0;return{messages:[a,...C],jumpTo:b}}}})}const ir=`<role>
75
+ Args: ${JSON.stringify(l,null,2)}`;const h={name:a,args:l,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 l=r.editedAction;if(!l||typeof l.name!="string")throw new Error(`Invalid edited action for tool "${s.name}": name must be a string`);if(!l.args||typeof l.args!="object")throw new Error(`Invalid edited action for tool "${s.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:l.name,args:l.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 l=r.message??`User rejected the tool call for \`${s.name}\` with id ${s.id}`,c=new j({content:l,name:s.name,tool_call_id:s.id,status:"error"});return{revisedToolCall:s,toolMessage:c}}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 oe({name:"HumanInTheLoopMiddleware",contextSchema:ei,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=tt(ei,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(w=>P.isInstance(w));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const l={};for(const[w,g]of Object.entries(o.interruptOn))typeof g=="boolean"?g===!0&&(l[w]={allowedDecisions:[...jl]}):g.allowedDecisions&&(l[w]=g);const c=[],u=[];for(const w of a.tool_calls)w.name in l?c.push(w):u.push(w);if(!c.length)return;const h=[],d=[];for(const w of c){const g=l[w.name],{actionRequest:E,reviewConfig:S}=await e(w,g,r,s);h.push(E),d.push(S)}const m=(await fl({actionRequests:h,reviewConfigs:d})).decisions;if(!m||!Array.isArray(m))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(m.length!==c.length)throw new Error(`Number of human decisions (${m.length}) does not match number of hanging tool calls (${c.length}).`);const C=[...u],T=[],k=m.some(w=>w.type==="reject");for(let w=0;w<m.length;w++){const g=m[w],E=c[w],S=l[E.name],{revisedToolCall:_,toolMessage:M}=n(g,E,S);_&&(!k||g.type==="reject")&&C.push(_),M&&T.push(M)}P.isInstance(a)&&(a.tool_calls=C);const v=k?"model":void 0;return{messages:[a,...T],jumpTo:v}}}})}const ar=`<role>
76
76
  Context Extraction Assistant
77
77
  </role>
78
78
 
@@ -98,10 +98,10 @@ Respond ONLY with the extracted context. Do not include any additional informati
98
98
  <messages>
99
99
  Messages to summarize:
100
100
  {messages}
101
- </messages>`,Sm="Here is a summary of the conversation to date:",Cr=20,Cm=4e3,Qo=5,Tm=Mn().args(Ge(Se())).returns(Ae([V(),wi(V())])),Qt=B({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"}),go=B({fraction:V().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().min(0,"Tokens must be greater than or equal to 0").optional(),messages:V().int("Messages must be an integer").min(0,"Messages must be non-negative").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=B({model:Se(),trigger:Ae([Qt,Ge(Qt)]).optional(),keep:go.optional(),tokenCounter:Tm.optional(),summaryPrompt:Q().default(ir),trimTokensToSummarize:V().optional(),summaryPrefix:Q().optional(),maxTokensBeforeSummary:V().optional(),messagesToKeep:V().optional()});function Tn(t){if("profile"in t&&typeof t.profile=="object"&&t.profile&&"maxInputTokens"in t.profile&&(typeof t.profile.maxInputTokens=="number"||t.profile.maxInputTokens==null))return t.profile.maxInputTokens??void 0;if("model"in t&&typeof t.model=="string")return _o(t.model);if("modelName"in t&&typeof t.modelName=="string")return _o(t.modelName)}function km(t){const{data:e,error:n}=ku(ei,t);if(n)throw new Error(`Invalid summarization middleware options: ${Ds(n)}`);return se({name:"SummarizationMiddleware",contextSchema:ei.extend({model:Se().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===Cr)&&(i={messages:e.messagesToKeep}));const a=s.context?.trigger!==void 0?s.context.trigger:o,l=s.context?.keep!==void 0?s.context.keep:i??{messages:Cr},c=go.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(T=>Qt.parse(T)):u=[Qt.parse(a)];const h=u.some(T=>"fraction"in T)||"fraction"in c,d=typeof e.model=="string"?await it(e.model):e.model;if(h&&!Tn(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context?.summaryPrompt===ir?e.summaryPrompt??ir:s.context?.summaryPrompt??e.summaryPrompt??ir,p=s.context.summaryPrefix??e.summaryPrefix??Sm,m=s.context?.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??Cm;Em(r.messages);const S=s.context?.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Gs,C=await S(r.messages);if(!await Am(r.messages,C,u,d))return;const{systemPrompt:b,conversationMessages:w}=xm(r.messages),g=await Pm(w,c,S,d);if(g<=0)return;const{messagesToSummarize:k,preservedMessages:_}=Mm(b,w,g),v=await Nm(k,d,f,S,m),x=new ee({content:`${p}
101
+ </messages>`,Tm="Here is a summary of the conversation to date:",Tr=20,km=4e3,ti=5,Em=Pn().args(Ge(Ce())).returns(Ae([B(),bi(B())])),tn=z({fraction:B().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:B().positive("Tokens must be greater than 0").optional(),messages:B().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"}),yo=z({fraction:B().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:B().min(0,"Tokens must be greater than or equal to 0").optional(),messages:B().int("Messages must be an integer").min(0,"Messages must be non-negative").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"}),ni=z({model:Ce(),trigger:Ae([tn,Ge(tn)]).optional(),keep:yo.optional(),tokenCounter:Em.optional(),summaryPrompt:ee().default(ar),trimTokensToSummarize:B().optional(),summaryPrefix:ee().optional(),maxTokensBeforeSummary:B().optional(),messagesToKeep:B().optional()});function En(t){if("profile"in t&&typeof t.profile=="object"&&t.profile&&"maxInputTokens"in t.profile&&(typeof t.profile.maxInputTokens=="number"||t.profile.maxInputTokens==null))return t.profile.maxInputTokens??void 0;if("model"in t&&typeof t.model=="string")return Co(t.model);if("modelName"in t&&typeof t.modelName=="string")return Co(t.modelName)}function xm(t){const{data:e,error:n}=xu(ni,t);if(n)throw new Error(`Invalid summarization middleware options: ${Fs(n)}`);return oe({name:"SummarizationMiddleware",contextSchema:ni.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===Tr)&&(i={messages:e.messagesToKeep}));const a=s.context?.trigger!==void 0?s.context.trigger:o,l=s.context?.keep!==void 0?s.context.keep:i??{messages:Tr},c=yo.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(b=>tn.parse(b)):u=[tn.parse(a)];const h=u.some(b=>"fraction"in b)||"fraction"in c,d=typeof e.model=="string"?await at(e.model):e.model;if(h&&!En(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context?.summaryPrompt===ar?e.summaryPrompt??ar:s.context?.summaryPrompt??e.summaryPrompt??ar,p=s.context.summaryPrefix??e.summaryPrefix??Tm,m=s.context?.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??km;Mm(r.messages);const C=s.context?.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Ks,T=await C(r.messages);if(!await Im(r.messages,T,u,d))return;const{systemPrompt:v,conversationMessages:w}=Am(r.messages),g=await Om(w,c,C,d);if(g<=0)return;const{messagesToSummarize:E,preservedMessages:S}=Pm(v,w,g),_=await Rm(E,d,f,C,m),M=new te({content:`${p}
102
102
 
103
- ${v}`,id:cr()});return{messages:[new zn({id:Ml}),x,..._]}}})}function Em(t){for(const e of t)e.id||(e.id=cr())}function xm(t){return t.length>0&&te.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Mm(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function Am(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=Tn(r);if(typeof a=="number"){const l=Math.floor(a*s.fraction);e<l&&(o=!1)}else o=!1}if(i&&o)return!0}return!1}async function Pm(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Im(t,e,n,r);return typeof s=="number"?s:ti(t,Cr)}return ti(t,e.messages??Cr)}async function Im(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const h=Tn(r);if(typeof h!="number")return;s=Math.floor(h*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,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let h=0;h<c&&!(i>=a);h++){const d=Math.floor((i+a)/2);await n(t.slice(d))<=s?(l=d,a=d):i=d+1}if(l===t.length&&(l=i),l>=t.length){if(t.length===1)return 0;l=t.length-1}const u=Ll(t,l);if(u<=l)return u;for(let h=l;h>=0;h--)if(Rl(t,h))return h;return 0}function ti(t,e){if(t.length<=e)return 0;const n=t.length-e,r=Ll(t,n);if(r<=n)return r;for(let s=n;s>=0;s--)if(Rl(t,s))return s;return 0}function Rl(t,e){if(e>=t.length)return!0;if(e<t.length&&I.isInstance(t[e])&&Sr(t[e]))return!1;const n=Math.max(0,e-Qo),r=Math.min(t.length,e+Qo);for(let s=n;s<r;s++){if(!Sr(t[s]))continue;const o=jl(t[s]);if(Om(t,s,e,o))return!1}return!0}function jl(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 Ll(t,e){if(e>=t.length||!j.isInstance(t[e]))return e;const n=new Set;let r=e;for(;r<t.length&&j.isInstance(t[r]);){const s=t[r];s.tool_call_id&&n.add(s.tool_call_id),r++}for(let s=e-1;s>=0;s--){const o=t[s];if(I.isInstance(o)&&Sr(o)){const i=jl(o);for(const a of n)if(i.has(a))return s}}return r}function Om(t,e,n,r){for(let s=e+1;s<t.length;s++){const o=t[s];if(j.isInstance(o)&&r.has(o.tool_call_id)){const i=e<n,a=s<n;if(i!==a)return!0}}return!1}async function Nm(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const o=await $m(t,r,s);if(!o.length)return"Previous conversation was too long to summarize.";const i=Eu(o);try{const a=n.replace("{messages}",i),c=(await e.invoke(a,{callbacks:[]})).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(h=>typeof h=="string"?h:typeof h=="object"&&h!==null&&"text"in h?h.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(a){return`Error generating summary: ${a}`}}async function $m(t,e,n){if(n===void 0)return t;try{return await vi(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}function Rm(t){return se({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const r=await t(e.state,e.runtime);if(!(typeof r=="string"||te.isInstance(r)))throw new Error("dynamicSystemPromptMiddleware function must return a string or SystemMessage");return n({...e,systemMessage:e.systemMessage.concat(r)})}})}const jm="Your goal is to select the most relevant tools for answering the user's query.";function Lm(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>Re(r.name)),n=Ae(e);return B({tools:Ge(n).describe("Tools to use. Place the most relevant tools first.")})}const Dm=B({model:Q().or(An(Dc)).optional(),systemPrompt:Q().optional(),maxTools:V().optional(),alwaysInclude:Ge(Q()).optional()});function Fm(t){return se({name:"LLMToolSelector",contextSchema:Dm,async wrapModelCall(e,n){const r=await Um(e,t,e.runtime);if(!r)return n(e);const s=Lm(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(Vm(i,r.availableTools,r.validToolNames,e,t))}})}async function Um(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??jm;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(m=>m.name)),p=o.filter(m=>!f.has(m));if(p.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${p.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!o.includes(f.name));if(l.length===0)return;let c=i;s!==void 0&&(c+=`
104
- 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)ee.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await it(r):r:t.model,d=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:h,validToolNames:d}}function Vm(t,e,n,r,s){const o=s.maxTools,i=s.alwaysInclude??[],a=[],l=[];for(const d of t.tools){if(!n.includes(d)){l.push(d);continue}!a.includes(d)&&(o===void 0||a.length<o)&&a.push(d)}if(l.length>0)throw new Error(`Model selected invalid tools: ${l.join(", ")}`);const c=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));c.push(...u);const h=(r.tools??[]).filter(d=>!(typeof d=="object"&&"name"in d&&"description"in d&&typeof d.name=="string"));return{...r,tools:[...c,...h]}}var Dl=class extends Error{constructor(t,e){super(`PII detected: ${t} found ${e.length} occurrence(s)`),this.piiType=t,this.matches=e,this.name="PIIDetectionError"}};const Bm=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,zm=/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,Wm=/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,Hm=/\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g,Gm=/(?:https?:\/\/|www\.)[^\s<>"{}|\\^`[\]]+/gi;function Km(t){const e=t.replace(/\D/g,"");let n=0,r=!1;for(let s=e.length-1;s>=0;s--){let o=parseInt(e[s],10);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function wt(t){return{text:t[0],start:t.index??0,end:(t.index??0)+t[0].length}}function Fl(t){const e=[],n=new RegExp(Bm);let r;for(;(r=n.exec(t))!==null;)e.push(wt(r));return e}function Ul(t){const e=[],n=new RegExp(zm);let r;for(;(r=n.exec(t))!==null;){const s=r[0].replace(/\D/g,"");s.length>=13&&s.length<=19&&Km(s)&&e.push(wt(r))}return e}function Vl(t){const e=[],n=new RegExp(Wm);let r;for(;(r=n.exec(t))!==null;){const o=r[0].split(".");o.length===4&&o.every(i=>{const a=parseInt(i,10);return a>=0&&a<=255})&&e.push(wt(r))}return e}function Bl(t){const e=[],n=new RegExp(Hm);let r;for(;(r=n.exec(t))!==null;)e.push(wt(r));return e}function zl(t){const e=[],n=new RegExp(Gm);let r;for(;(r=n.exec(t))!==null;)e.push(wt(r));return e}const ss={email:Fl,credit_card:Ul,ip:Vl,mac_address:Bl,url:zl};function Wl(t){let e;if(t.detector)if(typeof t.detector=="string"){const n=new RegExp(t.detector,"g");e=r=>{const s=[];let o;const i=new RegExp(n);for(;(o=i.exec(r))!==null;)s.push(wt(o));return s}}else t.detector instanceof RegExp?e=n=>{if(!(t.detector instanceof RegExp))throw new Error("Detector is required");const r=[];let s;for(;(s=t.detector.exec(n))!==null;)r.push(wt(s));return r}:e=t.detector;else{const n=t.piiType;if(!ss[n])throw new Error(`Unknown PII type: ${t.piiType}. Must be one of: ${Object.keys(ss).join(", ")}, or provide a custom detector.`);e=ss[n]}return{piiType:t.piiType,strategy:t.strategy,detector:e}}function Jm(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=`[REDACTED_${n.toUpperCase()}]`;r=r.slice(0,o.start)+i+r.slice(o.end)}return r}function qm(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=o.text;let a;if(n==="credit_card")a=`****-****-****-${i.replace(/\D/g,"").slice(-4)}`;else if(n==="email"){const[l,c]=i.split("@");l&&c?a=`${l[0]}***@${c}`:a="***"}else{const l=Math.min(4,i.length);a=`${"*".repeat(Math.max(0,i.length-l))}${i.slice(-l)}`}r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function Ym(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=di(o.text).slice(0,8),a=`<${n}_hash:${i}>`;r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function Hl(t,e,n,r){if(e.length===0)return t;switch(n){case"block":throw new Dl(r,e);case"redact":return Jm(t,e,r);case"mask":return qm(t,e,r);case"hash":return Ym(t,e,r);default:throw new Error(`Unknown strategy: ${n}`)}}const Xm=B({applyToInput:ft().optional(),applyToOutput:ft().optional(),applyToToolResults:ft().optional()});function os(t,e){const n=e.detector(t);return n.length===0?{content:t,matches:[]}:{content:Hl(t,n,e.strategy,e.piiType),matches:n}}function Zm(t,e={}){const{strategy:n="redact",detector:r}=e,s=Wl({piiType:t,strategy:n,detector:r}),o=`PIIMiddleware[${s.piiType}]`;return se({name:o,contextSchema:Xm,beforeModel:async(i,a)=>{const l=a.context.applyToInput??e.applyToInput??!0,c=a.context.applyToToolResults??e.applyToToolResults??!1;if(!l&&!c)return;const u=i.messages;if(!u||u.length===0)return;const h=[...u];let d=!1;if(l){let f=null;for(let p=u.length-1;p>=0;p--)if(ee.isInstance(u[p])){f=p;break}if(f!==null){const p=u[f];if(p&&p.content){const m=String(p.content),{content:S,matches:C}=os(m,s);C.length>0&&(h[f]=new ee({content:S,id:p.id,name:p.name}),d=!0)}}}if(c){let f=null;for(let p=u.length-1;p>=0;p--)if(I.isInstance(u[p])){f=p;break}if(f!==null)for(let p=f+1;p<u.length;p++){const m=u[p];if(j.isInstance(m)){if(!m.content)continue;const S=String(m.content),{content:C,matches:E}=os(S,s);E.length>0&&(h[p]=new j({content:C,id:m.id,name:m.name,tool_call_id:m.tool_call_id}),d=!0)}}}if(d)return{messages:h}},afterModel:async(i,a)=>{if(!(a.context.applyToOutput??e.applyToOutput??!1))return;const c=i.messages;if(!c||c.length===0)return;let u=null,h=null;for(let C=c.length-1;C>=0;C--)if(I.isInstance(c[C])){h=c[C],u=C;break}if(u===null||!h||!h.content)return;const d=String(h.content),{content:f,matches:p}=os(d,s);if(p.length===0)return;const m=new I({content:f,id:h.id,name:h.name,tool_calls:h.tool_calls}),S=[...c];return S[u]=m,{messages:S}}})}const Qm=B({rules:mn(Q(),An(RegExp).describe("Regular expression pattern to match PII")).optional()});function eg(){return Math.random().toString(36).substring(2,11)}function is(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 l=eg();return n[l]=a,`[REDACTED_${i}_${l}]`})}return r}async function tg(t,e){if(ee.isInstance(t)||j.isInstance(t)||te.isInstance(t)){const n=t.content,r=await is(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(I.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await is(n,e.rules,e.redactionMap),o=await is(r,e.rules,e.redactionMap);return s!==n||o!==r?new I({...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 dn(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 ni(t,e){if(ee.isInstance(t)||j.isInstance(t)||te.isInstance(t)){const n=t.content,r=dn(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(I.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=dn(n,e),o=dn(r,e);return s!==n||o!==r?{message:new I({...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 ng(t={}){const e={};return console.warn("DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information."),se({name:"PIIRedactionMiddleware",contextSchema:Qm,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=>tg(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(!I.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=ni(r,e);if(!i)return;let a;if(I.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(dn(r.content,e))}catch{}if(I.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=ni(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(dn(JSON.stringify(h),e)):void 0;if(i||u)return{...n,...d?{structuredResponse:d}:{},messages:[new zn({id:s.id}),new zn({id:r.id}),c,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new zn({id:r.id}),o]}}})}const rg="[cleared]",sg=1e5,Un=3;var Gl=class{#e;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(t={}){let e=t.trigger;t.triggerTokens!==void 0&&(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),e===void 0&&(e={tokens:t.triggerTokens}));let n=t.keep;if(t.keepMessages!==void 0&&(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),n===void 0&&(n={messages:t.keepMessages})),e===void 0&&(e={tokens:sg}),n===void 0&&(n={messages:Un}),Array.isArray(e))this.#e=e.map(s=>Qt.parse(s)),this.trigger=this.#e;else{const s=Qt.parse(e);this.#e=[s],this.trigger=s}const r=go.parse(n);this.keep=r,t.clearAtLeast!==void 0&&console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."),this.clearAtLeast=t.clearAtLeast??0,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??rg}async apply(t){const{messages:e,model:n,countTokens:r}=t,s=await r(e),o=[];for(let d=0;d<e.length;d++){const f=e[d];if(j.isInstance(f)){const p=this.#n(e.slice(0,d),f.tool_call_id);p&&p.tool_calls?.find(S=>S.id===f.tool_call_id)||o.push(d)}}for(let d=o.length-1;d>=0;d--)e.splice(o[d],1);let i=s;if(o.length>0&&(i=await r(e)),!this.#r(e,i,n))return;const a=[];for(let d=0;d<e.length;d++){const f=e[d];j.isInstance(f)&&a.push({idx:d,msg:f})}if(a.length===0)return;const l=await this.#t(a,r,n),c=l>=a.length?[]:l>0?a.slice(0,-l):a;let u=0;const h=[...c];for(const{idx:d,msg:f}of h){if(f.response_metadata?.context_editing?.cleared)continue;const m=this.#n(e.slice(0,d),f.tool_call_id);if(!m)continue;const S=m.tool_calls?.find(b=>b.id===f.tool_call_id);if(!S)continue;const C=f.name||S.name;if(this.excludeTools.has(C))continue;if(e[d]=new j({tool_call_id:f.tool_call_id,content:this.placeholder,name:f.name,artifact:void 0,response_metadata:{...f.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const b=e.indexOf(m);b>=0&&(e[b]=this.#s(m,f.tool_call_id))}const E=await r(e);u=Math.max(0,i-E)}if(this.clearAtLeast>0&&u<this.clearAtLeast){const d=l>0&&l<a.length?a.slice(-l):[];for(let f=d.length-1;f>=0&&!(u>=this.clearAtLeast);f--){const{idx:p,msg:m}=d[f];if(m.response_metadata?.context_editing?.cleared)continue;const C=this.#n(e.slice(0,p),m.tool_call_id);if(!C)continue;const E=C.tool_calls?.find(g=>g.id===m.tool_call_id);if(!E)continue;const b=m.name||E.name;if(this.excludeTools.has(b))continue;if(e[p]=new j({tool_call_id:m.tool_call_id,content:this.placeholder,name:m.name,artifact:void 0,response_metadata:{...m.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const g=e.indexOf(C);g>=0&&(e[g]=this.#s(C,m.tool_call_id))}const w=await r(e);u=Math.max(0,i-w)}}}#r(t,e,n){for(const r of this.#e){let s=!0,o=!1;if(r.messages!==void 0&&(o=!0,t.length<r.messages&&(s=!1)),r.tokens!==void 0&&(o=!0,e<r.tokens&&(s=!1)),r.fraction!==void 0){if(o=!0,!n)continue;const i=Tn(n);if(typeof i=="number"){const a=Math.floor(i*r.fraction);if(a<=0)continue;e<a&&(s=!1)}else continue}if(o&&s)return!0}return!1}async#t(t,e,n){if("messages"in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if("tokens"in this.keep&&this.keep.tokens!==void 0){const r=this.keep.tokens;let s=0,o=0;for(let i=t.length-1;i>=0;i--){const a=t[i],l=await e([a.msg]);if(s+l<=r)s+=l,o++;else break}return o}if("fraction"in this.keep&&this.keep.fraction!==void 0){if(!n)return Un;const r=Tn(n);if(typeof r=="number"){const s=Math.floor(r*this.keep.fraction);if(s<=0)return Un;let o=0,i=0;for(let a=t.length-1;a>=0;a--){const l=t[a],c=await e([l.msg]);if(o+c<=s)o+=c,i++;else break}return i}}return Un}#n(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(I.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#s(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 I({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function og(t={}){const e=t.edits??[new Gl],n=t.tokenCountMethod??"approx";return se({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new te(r.systemPrompt)]:[],i=n==="approx"?Gs:async a=>{const l=[...o,...a];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(l).then(({totalCount:c})=>c);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};for(const a of e)await a.apply({messages:r.messages,model:r.model,countTokens:i});return s(r)}})}function ig(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const ag=["continue","error","end"],Kl="continue";function Jl(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 ql=Jt(ag).default(Kl);var Yl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=Jl(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}};B({toolName:Q().optional(),threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:ql});const lg=B({threadToolCallCount:mn(Q(),V()).default({}),runToolCallCount:mn(Q(),V()).default({})}),cg="__all__";function ug(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??Kl,n=ql.safeParse(e);if(!n.success)throw new Error(Ds(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 se({name:r,stateSchema:lg,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(I.isInstance);if(!o||!o.tool_calls)return;const i=(w,g)=>t.threadLimit!==void 0&&w+1>t.threadLimit||t.runLimit!==void 0&&g+1>t.runLimit,a=w=>t.toolName===void 0||w.name===t.toolName,l=(w,g,k)=>{const _=[],v=[];let x=g,T=k;for(const M of w)a(M)&&(i(x,T)?v.push(M):(_.push(M),x+=1,T+=1));return{allowed:_,blocked:v,finalThreadCount:x,finalRunCount:T+v.length}},c=t.toolName??cg,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:p,blocked:m,finalThreadCount:S,finalRunCount:C}=l(o.tool_calls,d,f);if(u[c]=S,h[c]=C,m.length===0)return p.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const w=S+m.length;throw new Yl(w,C,t.threadLimit,t.runLimit,t.toolName)}const E=ig(t.toolName),b=m.map(w=>new j({content:E,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(_=>_.name!==t.toolName):new Set(o.tool_calls.map(v=>v.name).filter(Boolean)).size>1&&(w=p.length>0?p:o.tool_calls),w.length>0){const _=Array.from(new Set(w.map(v=>v.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${_}. Use 'continue' or 'error' behavior instead.`)}const g=S+m.length,k=Jl(g,C,t.threadLimit,t.runLimit,t.toolName);return b.push(new I(k)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:b}}return{threadToolCallCount:u,runToolCallCount:h,messages:b}}},afterAgent:()=>({runToolCallCount:{}})})}const hg=`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.
103
+ ${_}`,id:ur()});return{messages:[new Wn({id:Pl}),M,...S]}}})}function Mm(t){for(const e of t)e.id||(e.id=ur())}function Am(t){return t.length>0&&ne.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Pm(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function Im(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=En(r);if(typeof a=="number"){const l=Math.floor(a*s.fraction);e<l&&(o=!1)}else o=!1}if(i&&o)return!0}return!1}async function Om(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Nm(t,e,n,r);return typeof s=="number"?s:ri(t,Tr)}return ri(t,e.messages??Tr)}async function Nm(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const h=En(r);if(typeof h!="number")return;s=Math.floor(h*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,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let h=0;h<c&&!(i>=a);h++){const d=Math.floor((i+a)/2);await n(t.slice(d))<=s?(l=d,a=d):i=d+1}if(l===t.length&&(l=i),l>=t.length){if(t.length===1)return 0;l=t.length-1}const u=Fl(t,l);if(u<=l)return u;for(let h=l;h>=0;h--)if(Ll(t,h))return h;return 0}function ri(t,e){if(t.length<=e)return 0;const n=t.length-e,r=Fl(t,n);if(r<=n)return r;for(let s=n;s>=0;s--)if(Ll(t,s))return s;return 0}function Ll(t,e){if(e>=t.length)return!0;if(e<t.length&&P.isInstance(t[e])&&Cr(t[e]))return!1;const n=Math.max(0,e-ti),r=Math.min(t.length,e+ti);for(let s=n;s<r;s++){if(!Cr(t[s]))continue;const o=Dl(t[s]);if($m(t,s,e,o))return!1}return!0}function Dl(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 Fl(t,e){if(e>=t.length||!j.isInstance(t[e]))return e;const n=new Set;let r=e;for(;r<t.length&&j.isInstance(t[r]);){const s=t[r];s.tool_call_id&&n.add(s.tool_call_id),r++}for(let s=e-1;s>=0;s--){const o=t[s];if(P.isInstance(o)&&Cr(o)){const i=Dl(o);for(const a of n)if(i.has(a))return s}}return r}function $m(t,e,n,r){for(let s=e+1;s<t.length;s++){const o=t[s];if(j.isInstance(o)&&r.has(o.tool_call_id)){const i=e<n,a=s<n;if(i!==a)return!0}}return!1}async function Rm(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const o=await jm(t,r,s);if(!o.length)return"Previous conversation was too long to summarize.";const i=Mu(o);try{const a=n.replace("{messages}",i),c=(await e.invoke(a,{callbacks:[]})).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(h=>typeof h=="string"?h:typeof h=="object"&&h!==null&&"text"in h?h.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(a){return`Error generating summary: ${a}`}}async function jm(t,e,n){if(n===void 0)return t;try{return await _i(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}function Lm(t){return oe({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const r=await t(e.state,e.runtime);if(!(typeof r=="string"||ne.isInstance(r)))throw new Error("dynamicSystemPromptMiddleware function must return a string or SystemMessage");return n({...e,systemMessage:e.systemMessage.concat(r)})}})}const Dm="Your goal is to select the most relevant tools for answering the user's query.";function Fm(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>Re(r.name)),n=Ae(e);return z({tools:Ge(n).describe("Tools to use. Place the most relevant tools first.")})}const Um=z({model:ee().or(In(Uc)).optional(),systemPrompt:ee().optional(),maxTools:B().optional(),alwaysInclude:Ge(ee()).optional()});function Vm(t){return oe({name:"LLMToolSelector",contextSchema:Um,async wrapModelCall(e,n){const r=await Bm(e,t,e.runtime);if(!r)return n(e);const s=Fm(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(zm(i,r.availableTools,r.validToolNames,e,t))}})}async function Bm(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??Dm;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(m=>m.name)),p=o.filter(m=>!f.has(m));if(p.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${p.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!o.includes(f.name));if(l.length===0)return;let c=i;s!==void 0&&(c+=`
104
+ 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)te.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await at(r):r:t.model,d=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:h,validToolNames:d}}function zm(t,e,n,r,s){const o=s.maxTools,i=s.alwaysInclude??[],a=[],l=[];for(const d of t.tools){if(!n.includes(d)){l.push(d);continue}!a.includes(d)&&(o===void 0||a.length<o)&&a.push(d)}if(l.length>0)throw new Error(`Model selected invalid tools: ${l.join(", ")}`);const c=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));c.push(...u);const h=(r.tools??[]).filter(d=>!(typeof d=="object"&&"name"in d&&"description"in d&&typeof d.name=="string"));return{...r,tools:[...c,...h]}}var Ul=class extends Error{constructor(t,e){super(`PII detected: ${t} found ${e.length} occurrence(s)`),this.piiType=t,this.matches=e,this.name="PIIDetectionError"}};const Wm=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,Hm=/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,Gm=/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,Km=/\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g,Jm=/(?:https?:\/\/|www\.)[^\s<>"{}|\\^`[\]]+/gi;function qm(t){const e=t.replace(/\D/g,"");let n=0,r=!1;for(let s=e.length-1;s>=0;s--){let o=parseInt(e[s],10);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function bt(t){return{text:t[0],start:t.index??0,end:(t.index??0)+t[0].length}}function Vl(t){const e=[],n=new RegExp(Wm);let r;for(;(r=n.exec(t))!==null;)e.push(bt(r));return e}function Bl(t){const e=[],n=new RegExp(Hm);let r;for(;(r=n.exec(t))!==null;){const s=r[0].replace(/\D/g,"");s.length>=13&&s.length<=19&&qm(s)&&e.push(bt(r))}return e}function zl(t){const e=[],n=new RegExp(Gm);let r;for(;(r=n.exec(t))!==null;){const o=r[0].split(".");o.length===4&&o.every(i=>{const a=parseInt(i,10);return a>=0&&a<=255})&&e.push(bt(r))}return e}function Wl(t){const e=[],n=new RegExp(Km);let r;for(;(r=n.exec(t))!==null;)e.push(bt(r));return e}function Hl(t){const e=[],n=new RegExp(Jm);let r;for(;(r=n.exec(t))!==null;)e.push(bt(r));return e}const os={email:Vl,credit_card:Bl,ip:zl,mac_address:Wl,url:Hl};function Gl(t){let e;if(t.detector)if(typeof t.detector=="string"){const n=new RegExp(t.detector,"g");e=r=>{const s=[];let o;const i=new RegExp(n);for(;(o=i.exec(r))!==null;)s.push(bt(o));return s}}else t.detector instanceof RegExp?e=n=>{if(!(t.detector instanceof RegExp))throw new Error("Detector is required");const r=[];let s;for(;(s=t.detector.exec(n))!==null;)r.push(bt(s));return r}:e=t.detector;else{const n=t.piiType;if(!os[n])throw new Error(`Unknown PII type: ${t.piiType}. Must be one of: ${Object.keys(os).join(", ")}, or provide a custom detector.`);e=os[n]}return{piiType:t.piiType,strategy:t.strategy,detector:e}}function Ym(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=`[REDACTED_${n.toUpperCase()}]`;r=r.slice(0,o.start)+i+r.slice(o.end)}return r}function Xm(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=o.text;let a;if(n==="credit_card")a=`****-****-****-${i.replace(/\D/g,"").slice(-4)}`;else if(n==="email"){const[l,c]=i.split("@");l&&c?a=`${l[0]}***@${c}`:a="***"}else{const l=Math.min(4,i.length);a=`${"*".repeat(Math.max(0,i.length-l))}${i.slice(-l)}`}r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function Zm(t,e,n){let r=t;for(let s=e.length-1;s>=0;s--){const o=e[s],i=pi(o.text).slice(0,8),a=`<${n}_hash:${i}>`;r=r.slice(0,o.start)+a+r.slice(o.end)}return r}function Kl(t,e,n,r){if(e.length===0)return t;switch(n){case"block":throw new Ul(r,e);case"redact":return Ym(t,e,r);case"mask":return Xm(t,e,r);case"hash":return Zm(t,e,r);default:throw new Error(`Unknown strategy: ${n}`)}}const Qm=z({applyToInput:mt().optional(),applyToOutput:mt().optional(),applyToToolResults:mt().optional()});function is(t,e){const n=e.detector(t);return n.length===0?{content:t,matches:[]}:{content:Kl(t,n,e.strategy,e.piiType),matches:n}}function eg(t,e={}){const{strategy:n="redact",detector:r}=e,s=Gl({piiType:t,strategy:n,detector:r}),o=`PIIMiddleware[${s.piiType}]`;return oe({name:o,contextSchema:Qm,beforeModel:async(i,a)=>{const l=a.context.applyToInput??e.applyToInput??!0,c=a.context.applyToToolResults??e.applyToToolResults??!1;if(!l&&!c)return;const u=i.messages;if(!u||u.length===0)return;const h=[...u];let d=!1;if(l){let f=null;for(let p=u.length-1;p>=0;p--)if(te.isInstance(u[p])){f=p;break}if(f!==null){const p=u[f];if(p&&p.content){const m=String(p.content),{content:C,matches:T}=is(m,s);T.length>0&&(h[f]=new te({content:C,id:p.id,name:p.name}),d=!0)}}}if(c){let f=null;for(let p=u.length-1;p>=0;p--)if(P.isInstance(u[p])){f=p;break}if(f!==null)for(let p=f+1;p<u.length;p++){const m=u[p];if(j.isInstance(m)){if(!m.content)continue;const C=String(m.content),{content:T,matches:k}=is(C,s);k.length>0&&(h[p]=new j({content:T,id:m.id,name:m.name,tool_call_id:m.tool_call_id}),d=!0)}}}if(d)return{messages:h}},afterModel:async(i,a)=>{if(!(a.context.applyToOutput??e.applyToOutput??!1))return;const c=i.messages;if(!c||c.length===0)return;let u=null,h=null;for(let T=c.length-1;T>=0;T--)if(P.isInstance(c[T])){h=c[T],u=T;break}if(u===null||!h||!h.content)return;const d=String(h.content),{content:f,matches:p}=is(d,s);if(p.length===0)return;const m=new P({content:f,id:h.id,name:h.name,tool_calls:h.tool_calls}),C=[...c];return C[u]=m,{messages:C}}})}const tg=z({rules:yn(ee(),In(RegExp).describe("Regular expression pattern to match PII")).optional()});function ng(){return Math.random().toString(36).substring(2,11)}function as(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 l=ng();return n[l]=a,`[REDACTED_${i}_${l}]`})}return r}async function rg(t,e){if(te.isInstance(t)||j.isInstance(t)||ne.isInstance(t)){const n=t.content,r=await as(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(P.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await as(n,e.rules,e.redactionMap),o=await as(r,e.rules,e.redactionMap);return s!==n||o!==r?new P({...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 pn(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 si(t,e){if(te.isInstance(t)||j.isInstance(t)||ne.isInstance(t)){const n=t.content,r=pn(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(P.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=pn(n,e),o=pn(r,e);return s!==n||o!==r?{message:new P({...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 sg(t={}){const e={};return console.warn("DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information."),oe({name:"PIIRedactionMiddleware",contextSchema:tg,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=>rg(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(!P.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=si(r,e);if(!i)return;let a;if(P.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(pn(r.content,e))}catch{}if(P.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=si(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(pn(JSON.stringify(h),e)):void 0;if(i||u)return{...n,...d?{structuredResponse:d}:{},messages:[new Wn({id:s.id}),new Wn({id:r.id}),c,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new Wn({id:r.id}),o]}}})}const og="[cleared]",ig=1e5,Vn=3;var Jl=class{#e;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(t={}){let e=t.trigger;t.triggerTokens!==void 0&&(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),e===void 0&&(e={tokens:t.triggerTokens}));let n=t.keep;if(t.keepMessages!==void 0&&(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),n===void 0&&(n={messages:t.keepMessages})),e===void 0&&(e={tokens:ig}),n===void 0&&(n={messages:Vn}),Array.isArray(e))this.#e=e.map(s=>tn.parse(s)),this.trigger=this.#e;else{const s=tn.parse(e);this.#e=[s],this.trigger=s}const r=yo.parse(n);this.keep=r,t.clearAtLeast!==void 0&&console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."),this.clearAtLeast=t.clearAtLeast??0,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??og}async apply(t){const{messages:e,model:n,countTokens:r}=t,s=await r(e),o=[];for(let d=0;d<e.length;d++){const f=e[d];if(j.isInstance(f)){const p=this.#n(e.slice(0,d),f.tool_call_id);p&&p.tool_calls?.find(C=>C.id===f.tool_call_id)||o.push(d)}}for(let d=o.length-1;d>=0;d--)e.splice(o[d],1);let i=s;if(o.length>0&&(i=await r(e)),!this.#r(e,i,n))return;const a=[];for(let d=0;d<e.length;d++){const f=e[d];j.isInstance(f)&&a.push({idx:d,msg:f})}if(a.length===0)return;const l=await this.#t(a,r,n),c=l>=a.length?[]:l>0?a.slice(0,-l):a;let u=0;const h=[...c];for(const{idx:d,msg:f}of h){if(f.response_metadata?.context_editing?.cleared)continue;const m=this.#n(e.slice(0,d),f.tool_call_id);if(!m)continue;const C=m.tool_calls?.find(v=>v.id===f.tool_call_id);if(!C)continue;const T=f.name||C.name;if(this.excludeTools.has(T))continue;if(e[d]=new j({tool_call_id:f.tool_call_id,content:this.placeholder,name:f.name,artifact:void 0,response_metadata:{...f.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const v=e.indexOf(m);v>=0&&(e[v]=this.#s(m,f.tool_call_id))}const k=await r(e);u=Math.max(0,i-k)}if(this.clearAtLeast>0&&u<this.clearAtLeast){const d=l>0&&l<a.length?a.slice(-l):[];for(let f=d.length-1;f>=0&&!(u>=this.clearAtLeast);f--){const{idx:p,msg:m}=d[f];if(m.response_metadata?.context_editing?.cleared)continue;const T=this.#n(e.slice(0,p),m.tool_call_id);if(!T)continue;const k=T.tool_calls?.find(g=>g.id===m.tool_call_id);if(!k)continue;const v=m.name||k.name;if(this.excludeTools.has(v))continue;if(e[p]=new j({tool_call_id:m.tool_call_id,content:this.placeholder,name:m.name,artifact:void 0,response_metadata:{...m.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const g=e.indexOf(T);g>=0&&(e[g]=this.#s(T,m.tool_call_id))}const w=await r(e);u=Math.max(0,i-w)}}}#r(t,e,n){for(const r of this.#e){let s=!0,o=!1;if(r.messages!==void 0&&(o=!0,t.length<r.messages&&(s=!1)),r.tokens!==void 0&&(o=!0,e<r.tokens&&(s=!1)),r.fraction!==void 0){if(o=!0,!n)continue;const i=En(n);if(typeof i=="number"){const a=Math.floor(i*r.fraction);if(a<=0)continue;e<a&&(s=!1)}else continue}if(o&&s)return!0}return!1}async#t(t,e,n){if("messages"in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if("tokens"in this.keep&&this.keep.tokens!==void 0){const r=this.keep.tokens;let s=0,o=0;for(let i=t.length-1;i>=0;i--){const a=t[i],l=await e([a.msg]);if(s+l<=r)s+=l,o++;else break}return o}if("fraction"in this.keep&&this.keep.fraction!==void 0){if(!n)return Vn;const r=En(n);if(typeof r=="number"){const s=Math.floor(r*this.keep.fraction);if(s<=0)return Vn;let o=0,i=0;for(let a=t.length-1;a>=0;a--){const l=t[a],c=await e([l.msg]);if(o+c<=s)o+=c,i++;else break}return i}}return Vn}#n(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(P.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#s(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 P({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function ag(t={}){const e=t.edits??[new Jl],n=t.tokenCountMethod??"approx";return oe({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new ne(r.systemPrompt)]:[],i=n==="approx"?Ks:async a=>{const l=[...o,...a];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(l).then(({totalCount:c})=>c);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};for(const a of e)await a.apply({messages:r.messages,model:r.model,countTokens:i});return s(r)}})}function lg(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const cg=["continue","error","end"],ql="continue";function Yl(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 Xl=Yt(cg).default(ql);var Zl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=Yl(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:ee().optional(),threadLimit:B().optional(),runLimit:B().optional(),exitBehavior:Xl});const ug=z({threadToolCallCount:yn(ee(),B()).default({}),runToolCallCount:yn(ee(),B()).default({})}),hg="__all__";function dg(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??ql,n=Xl.safeParse(e);if(!n.success)throw new Error(Fs(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 oe({name:r,stateSchema:ug,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(P.isInstance);if(!o||!o.tool_calls)return;const i=(w,g)=>t.threadLimit!==void 0&&w+1>t.threadLimit||t.runLimit!==void 0&&g+1>t.runLimit,a=w=>t.toolName===void 0||w.name===t.toolName,l=(w,g,E)=>{const S=[],_=[];let M=g,b=E;for(const x of w)a(x)&&(i(M,b)?_.push(x):(S.push(x),M+=1,b+=1));return{allowed:S,blocked:_,finalThreadCount:M,finalRunCount:b+_.length}},c=t.toolName??hg,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:p,blocked:m,finalThreadCount:C,finalRunCount:T}=l(o.tool_calls,d,f);if(u[c]=C,h[c]=T,m.length===0)return p.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const w=C+m.length;throw new Zl(w,T,t.threadLimit,t.runLimit,t.toolName)}const k=lg(t.toolName),v=m.map(w=>new j({content:k,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(S=>S.name!==t.toolName):new Set(o.tool_calls.map(_=>_.name).filter(Boolean)).size>1&&(w=p.length>0?p:o.tool_calls),w.length>0){const S=Array.from(new Set(w.map(_=>_.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${S}. Use 'continue' or 'error' behavior instead.`)}const g=C+m.length,E=Yl(g,T,t.threadLimit,t.runLimit,t.toolName);return v.push(new P(E)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:v}}return{threadToolCallCount:u,runToolCallCount:h,messages:v}}},afterAgent:()=>({runToolCallCount:{}})})}const fg=`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.
105
105
  It also helps the user understand the progress of the task and overall progress of their requests.
106
106
  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.
107
107
 
@@ -313,7 +313,7 @@ Using the todo list here is overkill and wastes time and tokens. These three too
313
313
  - Use clear, descriptive task names
314
314
 
315
315
  Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
316
- Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`,Xl=`## \`write_todos\`
316
+ Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`,Ql=`## \`write_todos\`
317
317
 
318
318
  You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
319
319
  Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
@@ -325,32 +325,32 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
325
325
 
326
326
  ## Important To-Do List Usage Notes to Remember
327
327
  - The \`write_todos\` tool should never be called multiple times in parallel.
328
- - 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.`,dg=Jt(["pending","in_progress","completed"]).describe("Status of the todo"),Zl=B({content:Q().describe("Content of the todo item"),status:dg}),fg=B({todos:Ge(Zl).default([])});function pg(t){const e=hi(({todos:n},r)=>new G({update:{todos:n,messages:[new j({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??hg,schema:B({todos:Ge(Zl).describe("List of todo items to update")})});return se({name:"todoListMiddleware",stateSchema:fg,tools:[e],wrapModelCall:(n,r)=>r({...n,systemMessage:n.systemMessage.concat(`
328
+ - 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.`,pg=Yt(["pending","in_progress","completed"]).describe("Status of the todo"),ec=z({content:ee().describe("Content of the todo item"),status:pg}),mg=z({todos:Ge(ec).default([])});function gg(t){const e=fi(({todos:n},r)=>new K({update:{todos:n,messages:[new j({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??fg,schema:z({todos:Ge(ec).describe("List of todo items to update")})});return oe({name:"todoListMiddleware",stateSchema:mg,tools:[e],wrapModelCall:(n,r)=>r({...n,systemMessage:n.systemMessage.concat(`
329
329
 
330
- ${t?.systemPrompt??Xl}`)}),afterModel:n=>{const r=n.messages;if(!r||r.length===0)return;const s=[...r].reverse().find(i=>I.isInstance(i));if(!s||!s.tool_calls||s.tool_calls.length===0)return;const o=s.tool_calls.filter(i=>i.name===e.name);if(o.length>1)return{messages:o.map(a=>new j({content:"Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",tool_call_id:a.id,status:"error"}))}}})}const mg="end",gg=B({threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:Jt(["error","end"]).optional()}),yg=B({threadModelCallCount:V().default(0),runModelCallCount:V().default(0)});var ri=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:n,runCount:r}){const s=[];typeof t=="number"&&typeof n=="number"&&s.push(`thread level call limit reached with ${n} model calls`),typeof e=="number"&&typeof r=="number"&&s.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${s.length>0?`: ${s.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function Ql(t){return se({name:"ModelCallLimitMiddleware",contextSchema:gg,stateSchema:yg,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{let r=n.context.exitBehavior??t?.exitBehavior??mg;r==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),r="error");const 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 l=new ri({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new I(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new ri({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new I(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function wg(...t){return se({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 it(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}const ec=B({maxRetries:V().min(0).default(2),retryOn:Ae([Mn().args(An(Error)).returns(ft()),Ge(Se())]).default(()=>()=>!0),backoffFactor:V().min(0).default(2),initialDelayMs:V().min(0).default(1e3),maxDelayMs:V().min(0).default(6e4),jitter:ft().default(!0)});var tc=class extends Error{cause;constructor(t){const e=Ds(t).slice(2);super(e),this.name="InvalidRetryConfigError",this.cause=t}};const si=B({onFailure:Ae([Re("error"),Re("continue"),Mn().args(An(Error)).returns(Q())]).default("continue")}).merge(ec);function vg(t={}){const{success:e,error:n,data:r}=si.safeParse(t);if(!e)throw new tc(n);const{maxRetries:s,retryOn:o,onFailure:i,backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u}=r,h=m=>typeof o=="function"?o(m):o.some(S=>m.constructor===S),d={backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u},f=(m,S)=>{const C=m.constructor.name;return`Model call failed after ${S} ${S===1?"attempt":"attempts"} with ${C}: ${m.message}`},p=(m,S)=>{if(i==="error")throw m;let C;return typeof i=="function"?C=i(m):C=f(m,S),new I({content:C})};return se({name:"modelRetryMiddleware",contextSchema:si,wrapModelCall:async(m,S)=>{for(let C=0;C<=s;C++)try{return await S(m)}catch(E){const b=C+1,w=E&&typeof E=="object"&&"message"in E?E:new Error(String(E));if(!h(w))return p(w,b);if(C<s){const g=Oi(d,C);g>0&&await Ii(g)}else return p(w,b)}throw new Error("Unexpected: retry loop completed without returning")}})}const oi=B({tools:Ge(Ae([Se(),Se(),Q()])).optional(),onFailure:Ae([Re("error"),Re("continue"),Re("raise"),Re("return_message"),Mn().args(An(Error)).returns(Q())]).default("continue")}).merge(ec);function bg(t={}){const{success:e,error:n,data:r}=oi.safeParse(t);if(!e)throw new tc(n);const{maxRetries:s,tools:o,retryOn:i,onFailure:a,backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:h}=r;let d=a;a==="raise"?(console.warn("⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead."),d="error"):a==="return_message"&&(console.warn("⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead."),d="continue");const f=[];for(const b of o??[])if(typeof b=="string")f.push(b);else if("name"in b&&typeof b.name=="string")f.push(b.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const p=b=>f.length===0?!0:f.includes(b),m=b=>typeof i=="function"?i(b):i.some(w=>b instanceof w),S={backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:h},C=(b,w,g)=>{const k=w.constructor.name;return`Tool '${b}' failed after ${g} ${g===1?"attempt":"attempts"} with ${k}`},E=(b,w,g,k)=>{if(d==="error")throw g;let _;return typeof d=="function"?_=d(g):_=C(b,g,k),new j({content:_,tool_call_id:w,name:b,status:"error"})};return se({name:"toolRetryMiddleware",contextSchema:oi,wrapToolCall:async(b,w)=>{const g=b.tool?.name??b.toolCall.name;if(!p(g))return w(b);const k=b.toolCall.id??"";for(let _=0;_<=s;_++)try{return await w(b)}catch(v){const x=_+1,T=v&&typeof v=="object"&&"message"in v?v:new Error(String(v));if(!m(T))return E(g,k,T,x);if(_<s){const M=Oi(S,_);M>0&&await Ii(M)}else return E(g,k,T,x)}throw new Error("Unexpected: retry loop completed without returning")}})}function _g(t={}){let e;const{tools:n,model:r}=t,s=!n||n.length===0,o=new Set;if(!s&&n)for(const l of n)if(typeof l=="string")o.add(l);else{const c=typeof l.name=="string"?l.name:String(l.name);o.add(c)}let i;const a=async()=>typeof r=="object"?r:typeof r=="string"?(i=i??await it(r,{temperature:1}).catch(l=>(console.error("Error initializing emulator model, using agent model:",l),e)),i):e;return se({name:"ToolEmulatorMiddleware",wrapModelCall:async(l,c)=>(e=l.model,c(l)),wrapToolCall:async(l,c)=>{const u=l.toolCall.name;if(!(s||o.has(u)))return c(l);const d=l.toolCall.args,f=l.tool.description||"No description available",p=typeof d=="string"?d:JSON.stringify(d),m=`You are emulating a tool call for testing purposes.
330
+ ${t?.systemPrompt??Ql}`)}),afterModel:n=>{const r=n.messages;if(!r||r.length===0)return;const s=[...r].reverse().find(i=>P.isInstance(i));if(!s||!s.tool_calls||s.tool_calls.length===0)return;const o=s.tool_calls.filter(i=>i.name===e.name);if(o.length>1)return{messages:o.map(a=>new j({content:"Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",tool_call_id:a.id,status:"error"}))}}})}const yg="end",wg=z({threadLimit:B().optional(),runLimit:B().optional(),exitBehavior:Yt(["error","end"]).optional()}),vg=z({threadModelCallCount:B().default(0),runModelCallCount:B().default(0)});var oi=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 tc(t){return oe({name:"ModelCallLimitMiddleware",contextSchema:wg,stateSchema:vg,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{let r=n.context.exitBehavior??t?.exitBehavior??yg;r==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),r="error");const 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 l=new oi({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new P(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new oi({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new P(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function bg(...t){return oe({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 at(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}const nc=z({maxRetries:B().min(0).default(2),retryOn:Ae([Pn().args(In(Error)).returns(mt()),Ge(Ce())]).default(()=>()=>!0),backoffFactor:B().min(0).default(2),initialDelayMs:B().min(0).default(1e3),maxDelayMs:B().min(0).default(6e4),jitter:mt().default(!0)});var rc=class extends Error{cause;constructor(t){const e=Fs(t).slice(2);super(e),this.name="InvalidRetryConfigError",this.cause=t}};const ii=z({onFailure:Ae([Re("error"),Re("continue"),Pn().args(In(Error)).returns(ee())]).default("continue")}).merge(nc);function _g(t={}){const{success:e,error:n,data:r}=ii.safeParse(t);if(!e)throw new rc(n);const{maxRetries:s,retryOn:o,onFailure:i,backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u}=r,h=m=>typeof o=="function"?o(m):o.some(C=>m.constructor===C),d={backoffFactor:a,initialDelayMs:l,maxDelayMs:c,jitter:u},f=(m,C)=>{const T=m.constructor.name;return`Model call failed after ${C} ${C===1?"attempt":"attempts"} with ${T}: ${m.message}`},p=(m,C)=>{if(i==="error")throw m;let T;return typeof i=="function"?T=i(m):T=f(m,C),new P({content:T})};return oe({name:"modelRetryMiddleware",contextSchema:ii,wrapModelCall:async(m,C)=>{for(let T=0;T<=s;T++)try{return await C(m)}catch(k){const v=T+1,w=k&&typeof k=="object"&&"message"in k?k:new Error(String(k));if(!h(w))return p(w,v);if(T<s){const g=$i(d,T);g>0&&await Ni(g)}else return p(w,v)}throw new Error("Unexpected: retry loop completed without returning")}})}const ai=z({tools:Ge(Ae([Ce(),Ce(),ee()])).optional(),onFailure:Ae([Re("error"),Re("continue"),Re("raise"),Re("return_message"),Pn().args(In(Error)).returns(ee())]).default("continue")}).merge(nc);function Sg(t={}){const{success:e,error:n,data:r}=ai.safeParse(t);if(!e)throw new rc(n);const{maxRetries:s,tools:o,retryOn:i,onFailure:a,backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:h}=r;let d=a;a==="raise"?(console.warn("⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead."),d="error"):a==="return_message"&&(console.warn("⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead."),d="continue");const f=[];for(const v of o??[])if(typeof v=="string")f.push(v);else if("name"in v&&typeof v.name=="string")f.push(v.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const p=v=>f.length===0?!0:f.includes(v),m=v=>typeof i=="function"?i(v):i.some(w=>v instanceof w),C={backoffFactor:l,initialDelayMs:c,maxDelayMs:u,jitter:h},T=(v,w,g)=>{const E=w.constructor.name;return`Tool '${v}' failed after ${g} ${g===1?"attempt":"attempts"} with ${E}`},k=(v,w,g,E)=>{if(d==="error")throw g;let S;return typeof d=="function"?S=d(g):S=T(v,g,E),new j({content:S,tool_call_id:w,name:v,status:"error"})};return oe({name:"toolRetryMiddleware",contextSchema:ai,wrapToolCall:async(v,w)=>{const g=v.tool?.name??v.toolCall.name;if(!p(g))return w(v);const E=v.toolCall.id??"";for(let S=0;S<=s;S++)try{return await w(v)}catch(_){const M=S+1,b=_&&typeof _=="object"&&"message"in _?_:new Error(String(_));if(!m(b))return k(g,E,b,M);if(S<s){const x=$i(C,S);x>0&&await Ni(x)}else return k(g,E,b,M)}throw new Error("Unexpected: retry loop completed without returning")}})}function Cg(t={}){let e;const{tools:n,model:r}=t,s=!n||n.length===0,o=new Set;if(!s&&n)for(const l of n)if(typeof l=="string")o.add(l);else{const c=typeof l.name=="string"?l.name:String(l.name);o.add(c)}let i;const a=async()=>typeof r=="object"?r:typeof r=="string"?(i=i??await at(r,{temperature:1}).catch(l=>(console.error("Error initializing emulator model, using agent model:",l),e)),i):e;return oe({name:"ToolEmulatorMiddleware",wrapModelCall:async(l,c)=>(e=l.model,c(l)),wrapToolCall:async(l,c)=>{const u=l.toolCall.name;if(!(s||o.has(u)))return c(l);const d=l.toolCall.args,f=l.tool.description||"No description available",p=typeof d=="string"?d:JSON.stringify(d),m=`You are emulating a tool call for testing purposes.
331
331
 
332
332
  Tool: ${u}
333
333
  Description: ${f}
334
334
  Arguments: ${p}
335
335
 
336
336
  Generate a realistic response that this tool would return given these arguments.
337
- Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`,C=await(await a()).invoke([new ee(m)]),E=typeof C.content=="string"?C.content:JSON.stringify(C.content);return new j({content:E,tool_call_id:l.toolCall.id??"",name:u})}})}function Sg(t){return!t||typeof t!="object"||t===null||!("client"in t)||!("_getClientOptions"in t)||typeof t._getClientOptions!="function"?!1:(t._getClientOptions(),typeof t.client=="object"&&t.client!==null&&"moderations"in t.client&&typeof t.client.moderations=="object"&&t.client.moderations!==null&&"create"in t.client.moderations&&typeof t.client.moderations.create=="function")}const Cg="I'm sorry, but I can't comply with that request. It was flagged for {categories}.";var Tg=class extends Error{content;stage;result;originalMessage;constructor({content:t,stage:e,result:n,message:r}){super(r),this.name="OpenAIModerationError",this.content=t,this.stage=e,this.result=n,this.originalMessage=r}};function kg(t){const{model:e,moderationModel:n="omni-moderation-latest",checkInput:r=!0,checkOutput:s=!0,checkToolResults:o=!1,exitBehavior:i="end",violationMessage:a}=t;let l;const c=async()=>{if(l)return l;const b=typeof e=="string"?await it(e):e;if(!b.getName().includes("ChatOpenAI"))throw new Error(`Model must be an OpenAI model to use moderation middleware. Got: ${b.getName()}`);if(!Sg(b))throw new Error("Model must support moderation to use moderation middleware.");return l=b,l},u=b=>b.content==null?null:b.text||null,h=(b,w)=>{for(let g=b.length-1;g>=0;g--)if(w.isInstance(b[g]))return g;return null},d=(b,w)=>{const g=[],k=w.categories;for(const[T,M]of Object.entries(k))M&&g.push(T.replace(/_/g," "));const _=g.length>0?g.join(", "):"OpenAI's safety policies",v=a||Cg,x=JSON.stringify(w.category_scores,null,2);try{return v.replace("{categories}",_).replace("{category_scores}",x).replace("{original_content}",b)}catch{return v}};function f(b,w){const g=l?._getClientOptions?.(),k=w?.model??"omni-moderation-latest",_={input:b,model:k};return l.client.moderations.create(_,g)}const p=(b,w,g,k,_)=>{const v=d(k,_);if(i==="error")throw new Tg({content:k,stage:g,result:_,message:v});if(i==="end")return{jumpTo:"end",messages:[new I({content:v})]};if(w==null)return;const x=[...b],T=x[w],M=Object.getPrototypeOf(T).constructor;return x[w]=new M({...T,content:v}),{messages:x}},m=async b=>{const w=h(b,ee);if(w==null)return null;const g=b[w],k=u(g);if(!k)return null;await c();const v=(await f(k,{model:n})).results.find(x=>x.flagged);return v?p(b,w,"input",k,v):null},S=async b=>{const w=h(b,I);if(w==null)return null;const g=[...b];let k=!1;for(let _=w+1;_<g.length;_++){const v=g[_];if(!j.isInstance(v))continue;const x=u(v);if(!x)continue;await c();const M=(await f(x,{model:n})).results.find(N=>N.flagged);if(!M)continue;const P=p(g,_,"tool",x,M);if(P){if("jumpTo"in P)return P;"messages"in P&&(g.splice(0,g.length,...P.messages),k=!0)}}return k?{messages:g}:null},C=async b=>{const w=h(b,I);if(w==null)return null;const g=b[w],k=u(g);if(!k)return null;await c();const v=(await f(k,{model:n})).results.find(x=>x.flagged);return v?p(b,w,"output",k,v):null},E=async b=>{const w=[...b];let g=!1;if(o){const k=await S(w);if(k){if("jumpTo"in k)return k;"messages"in k&&(w.splice(0,w.length,...k.messages),g=!0)}}if(r){const k=await m(w);if(k){if("jumpTo"in k)return k;"messages"in k&&(w.splice(0,w.length,...k.messages),g=!0)}}return g?{messages:w}:null};return se({name:"OpenAIModerationMiddleware",beforeModel:{hook:async b=>{if(!r&&!o)return;const w=b.messages||[];if(w.length!==0)return await E(w)??void 0},canJumpTo:["end"]},afterModel:{hook:async b=>{if(!s)return;const w=b.messages||[];if(w.length!==0)return await C(w)??void 0},canJumpTo:["end"]}})}const Eg=!0,xg="5m",Mg=3,Ag="warn",Pg=B({enableCaching:ft().optional(),ttl:Jt(["5m","1h"]).optional(),minMessagesToCache:V().optional(),unsupportedModelBehavior:Jt(["ignore","warn","raise"]).optional()});var ii=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function Ig(t){return se({name:"PromptCachingMiddleware",contextSchema:Pg,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??Eg,s=e.runtime.context.ttl??t?.ttl??xg,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??Mg,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??Ag;if(!r||!e.model)return n(e);if(!(e.model.getName()==="ChatAnthropic"||e.model.getName()==="ConfigurableModel"&&e.model._defaultConfig?.modelProvider==="anthropic")){const h=e.model.getName(),f=`Unsupported model '${e.model.getName()==="ConfigurableModel"?`${h} (${e.model._defaultConfig?.modelProvider})`:h}'. Prompt caching requires an Anthropic model`;if(i==="raise")throw new ii(`${f} (e.g., 'anthropic:claude-4-0-sonnet').`);return i==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${h}. Consider switching to an Anthropic model for caching benefits.`),n(e)}if(e.state.messages.length+(e.systemPrompt?1:0)<o)return n(e);const c=e.messages.at(-1);if(!c)return n(e);const u=Object.getPrototypeOf(c).constructor;if(Array.isArray(c.content)){const h=new u({...c,content:[...c.content.slice(0,-1),{...c.content.at(-1),cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}else if(typeof c.content=="string"){const h=new u({...c,content:[{type:"text",text:c.content,cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}throw new ii("Last message content is not a string or array")}})}var Og={};Ci(Og,{AIMessage:()=>I,AIMessageChunk:()=>Gt,BaseMessage:()=>cn,BaseMessageChunk:()=>Iu,ClearToolUsesEdit:()=>Gl,Document:()=>We,DynamicStructuredTool:()=>Bn,DynamicTool:()=>vc,FakeToolCallingModel:()=>nf,HumanMessage:()=>ee,HumanMessageChunk:()=>Pu,InMemoryStore:()=>Vi,MIDDLEWARE_BRAND:()=>Ni,MultipleStructuredOutputsError:()=>fs,MultipleToolsBoundError:()=>ds,PIIDetectionError:()=>Dl,ProviderStrategy:()=>Xe,StructuredOutputParsingError:()=>xi,StructuredTool:()=>Er,SystemMessage:()=>te,SystemMessageChunk:()=>Au,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>Xl,Tool:()=>wc,ToolCallLimitExceededError:()=>Yl,ToolInvocationError:()=>Ws,ToolMessage:()=>j,ToolMessageChunk:()=>Mu,ToolStrategy:()=>Je,anthropicPromptCachingMiddleware:()=>Ig,applyStrategy:()=>Hl,context:()=>Ia,contextEditingMiddleware:()=>og,countTokensApproximately:()=>Gs,createAgent:()=>Nl,createMiddleware:()=>se,detectCreditCard:()=>Ul,detectEmail:()=>Fl,detectIP:()=>Vl,detectMacAddress:()=>Bl,detectUrl:()=>zl,dynamicSystemPromptMiddleware:()=>Rm,filterMessages:()=>xu,humanInTheLoopMiddleware:()=>_m,initChatModel:()=>it,llmToolSelectorMiddleware:()=>Fm,modelCallLimitMiddleware:()=>Ql,modelFallbackMiddleware:()=>wg,modelRetryMiddleware:()=>vg,openAIModerationMiddleware:()=>kg,piiMiddleware:()=>Zm,piiRedactionMiddleware:()=>ng,providerStrategy:()=>nh,resolveRedactionRule:()=>Wl,summarizationMiddleware:()=>km,todoListMiddleware:()=>pg,tool:()=>hi,toolCallLimitMiddleware:()=>ug,toolEmulatorMiddleware:()=>_g,toolRetryMiddleware:()=>bg,toolStrategy:()=>th,trimMessages:()=>vi});var Ls={},Rt,Or=(Rt=class extends Er{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}},$(Rt,"MCPServerTool"),Rt),Ng=ve({}),jt,$g=(jt=class extends Or{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Ng;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."}},$(jt,"AcquireActiveMCPServerTool"),jt),Lt,Rg=(Lt=class extends Er{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=ve({serverName:kr().describe("The name for the new MCP server."),serverConfig:ke().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.`;y.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+=`
337
+ Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`,T=await(await a()).invoke([new te(m)]),k=typeof T.content=="string"?T.content:JSON.stringify(T.content);return new j({content:k,tool_call_id:l.toolCall.id??"",name:u})}})}function Tg(t){return!t||typeof t!="object"||t===null||!("client"in t)||!("_getClientOptions"in t)||typeof t._getClientOptions!="function"?!1:(t._getClientOptions(),typeof t.client=="object"&&t.client!==null&&"moderations"in t.client&&typeof t.client.moderations=="object"&&t.client.moderations!==null&&"create"in t.client.moderations&&typeof t.client.moderations.create=="function")}const kg="I'm sorry, but I can't comply with that request. It was flagged for {categories}.";var Eg=class extends Error{content;stage;result;originalMessage;constructor({content:t,stage:e,result:n,message:r}){super(r),this.name="OpenAIModerationError",this.content=t,this.stage=e,this.result=n,this.originalMessage=r}};function xg(t){const{model:e,moderationModel:n="omni-moderation-latest",checkInput:r=!0,checkOutput:s=!0,checkToolResults:o=!1,exitBehavior:i="end",violationMessage:a}=t;let l;const c=async()=>{if(l)return l;const v=typeof e=="string"?await at(e):e;if(!v.getName().includes("ChatOpenAI"))throw new Error(`Model must be an OpenAI model to use moderation middleware. Got: ${v.getName()}`);if(!Tg(v))throw new Error("Model must support moderation to use moderation middleware.");return l=v,l},u=v=>v.content==null?null:v.text||null,h=(v,w)=>{for(let g=v.length-1;g>=0;g--)if(w.isInstance(v[g]))return g;return null},d=(v,w)=>{const g=[],E=w.categories;for(const[b,x]of Object.entries(E))x&&g.push(b.replace(/_/g," "));const S=g.length>0?g.join(", "):"OpenAI's safety policies",_=a||kg,M=JSON.stringify(w.category_scores,null,2);try{return _.replace("{categories}",S).replace("{category_scores}",M).replace("{original_content}",v)}catch{return _}};function f(v,w){const g=l?._getClientOptions?.(),E=w?.model??"omni-moderation-latest",S={input:v,model:E};return l.client.moderations.create(S,g)}const p=(v,w,g,E,S)=>{const _=d(E,S);if(i==="error")throw new Eg({content:E,stage:g,result:S,message:_});if(i==="end")return{jumpTo:"end",messages:[new P({content:_})]};if(w==null)return;const M=[...v],b=M[w],x=Object.getPrototypeOf(b).constructor;return M[w]=new x({...b,content:_}),{messages:M}},m=async v=>{const w=h(v,te);if(w==null)return null;const g=v[w],E=u(g);if(!E)return null;await c();const _=(await f(E,{model:n})).results.find(M=>M.flagged);return _?p(v,w,"input",E,_):null},C=async v=>{const w=h(v,P);if(w==null)return null;const g=[...v];let E=!1;for(let S=w+1;S<g.length;S++){const _=g[S];if(!j.isInstance(_))continue;const M=u(_);if(!M)continue;await c();const x=(await f(M,{model:n})).results.find(N=>N.flagged);if(!x)continue;const I=p(g,S,"tool",M,x);if(I){if("jumpTo"in I)return I;"messages"in I&&(g.splice(0,g.length,...I.messages),E=!0)}}return E?{messages:g}:null},T=async v=>{const w=h(v,P);if(w==null)return null;const g=v[w],E=u(g);if(!E)return null;await c();const _=(await f(E,{model:n})).results.find(M=>M.flagged);return _?p(v,w,"output",E,_):null},k=async v=>{const w=[...v];let g=!1;if(o){const E=await C(w);if(E){if("jumpTo"in E)return E;"messages"in E&&(w.splice(0,w.length,...E.messages),g=!0)}}if(r){const E=await m(w);if(E){if("jumpTo"in E)return E;"messages"in E&&(w.splice(0,w.length,...E.messages),g=!0)}}return g?{messages:w}:null};return oe({name:"OpenAIModerationMiddleware",beforeModel:{hook:async v=>{if(!r&&!o)return;const w=v.messages||[];if(w.length!==0)return await k(w)??void 0},canJumpTo:["end"]},afterModel:{hook:async v=>{if(!s)return;const w=v.messages||[];if(w.length!==0)return await T(w)??void 0},canJumpTo:["end"]}})}const Mg=!0,Ag="5m",Pg=3,Ig="warn",Og=z({enableCaching:mt().optional(),ttl:Yt(["5m","1h"]).optional(),minMessagesToCache:B().optional(),unsupportedModelBehavior:Yt(["ignore","warn","raise"]).optional()});var li=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function Ng(t){return oe({name:"PromptCachingMiddleware",contextSchema:Og,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??Mg,s=e.runtime.context.ttl??t?.ttl??Ag,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??Pg,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??Ig;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 li(`${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 c=e.messages.at(-1);if(!c)return n(e);const u=Object.getPrototypeOf(c).constructor;if(Array.isArray(c.content)){const h=new u({...c,content:[...c.content.slice(0,-1),{...c.content.at(-1),cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}else if(typeof c.content=="string"){const h=new u({...c,content:[{type:"text",text:c.content,cache_control:{type:"ephemeral",ttl:s}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}throw new li("Last message content is not a string or array")}})}var $g={};ki($g,{AIMessage:()=>P,AIMessageChunk:()=>Jt,BaseMessage:()=>hn,BaseMessageChunk:()=>Nu,ClearToolUsesEdit:()=>Jl,Document:()=>We,DynamicStructuredTool:()=>zn,DynamicTool:()=>_c,FakeToolCallingModel:()=>sf,HumanMessage:()=>te,HumanMessageChunk:()=>Ou,InMemoryStore:()=>zi,MIDDLEWARE_BRAND:()=>Ri,MultipleStructuredOutputsError:()=>ps,MultipleToolsBoundError:()=>fs,PIIDetectionError:()=>Ul,ProviderStrategy:()=>Ze,StructuredOutputParsingError:()=>Ai,StructuredTool:()=>xr,SystemMessage:()=>ne,SystemMessageChunk:()=>Iu,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>Ql,Tool:()=>bc,ToolCallLimitExceededError:()=>Zl,ToolInvocationError:()=>Hs,ToolMessage:()=>j,ToolMessageChunk:()=>Pu,ToolStrategy:()=>qe,anthropicPromptCachingMiddleware:()=>Ng,applyStrategy:()=>Kl,context:()=>Na,contextEditingMiddleware:()=>ag,countTokensApproximately:()=>Ks,createAgent:()=>Rl,createMiddleware:()=>oe,detectCreditCard:()=>Bl,detectEmail:()=>Vl,detectIP:()=>zl,detectMacAddress:()=>Wl,detectUrl:()=>Hl,dynamicSystemPromptMiddleware:()=>Lm,filterMessages:()=>Au,humanInTheLoopMiddleware:()=>Cm,initChatModel:()=>at,llmToolSelectorMiddleware:()=>Vm,modelCallLimitMiddleware:()=>tc,modelFallbackMiddleware:()=>bg,modelRetryMiddleware:()=>_g,openAIModerationMiddleware:()=>xg,piiMiddleware:()=>eg,piiRedactionMiddleware:()=>sg,providerStrategy:()=>sh,resolveRedactionRule:()=>Gl,summarizationMiddleware:()=>xm,todoListMiddleware:()=>gg,tool:()=>fi,toolCallLimitMiddleware:()=>dg,toolEmulatorMiddleware:()=>Cg,toolRetryMiddleware:()=>Sg,toolStrategy:()=>rh,trimMessages:()=>_i});var Ds={},Lt,Nr=(Lt=class extends xr{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}},$(Lt,"MCPServerTool"),Lt),Rg=be({}),Dt,jg=(Dt=class extends Nr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Rg;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."}},$(Dt,"AcquireActiveMCPServerTool"),Dt),Ft,Lg=(Ft=class extends xr{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=be({serverName:Er().describe("The name for the new MCP server."),serverConfig:ke().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.`;y.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+=`
338
338
 
339
339
  ${i.map(l=>l.name).join(`
340
- `)}`,y.info(r),r}catch(r){return y.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},$(Lt,"AddMCPServerFromConfigTool"),Lt),jg=ve({serverName:kr().describe("The name of the MCP server.")}),Dt,Lg=(Dt=class extends Or{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=jg;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(y.debug(`Using existing session for server '${e}'`),r||(y.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]),l=await this.manager.adapter.createResourcesFromConnectors([i]),c=await this.manager.adapter.createPromptsFromConnectors([i]),u=[...a,...l,...c];this.manager.serverTools[e]=u,this.manager.initializedServers[e]=!0,y.debug(`Loaded ${u.length} items for server '${e}': ${a.length} tools, ${l.length} resources, ${c.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 y.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},$(Dt,"ConnectMCPServerTool"),Dt),Dg=ve({}),Ft,Fg=(Ft=class extends Or{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=Dg;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
340
+ `)}`,y.info(r),r}catch(r){return y.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},$(Ft,"AddMCPServerFromConfigTool"),Ft),Dg=be({serverName:Er().describe("The name of the MCP server.")}),Ut,Fg=(Ut=class extends Nr{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=Dg;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(y.debug(`Using existing session for server '${e}'`),r||(y.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]),l=await this.manager.adapter.createResourcesFromConnectors([i]),c=await this.manager.adapter.createPromptsFromConnectors([i]),u=[...a,...l,...c];this.manager.serverTools[e]=u,this.manager.initializedServers[e]=!0,y.debug(`Loaded ${u.length} items for server '${e}': ${a.length} tools, ${l.length} resources, ${c.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 y.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},$(Ut,"ConnectMCPServerTool"),Ut),Ug=be({}),Vt,Vg=(Vt=class extends Nr{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=Ug;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
341
341
  `)}catch(i){y.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
342
- `)}},$(Ft,"ListMCPServersTool"),Ft),Ug=ve({}),Ut,Vg=(Ut=class extends Or{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Ug;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}'.`}},$(Ut,"ReleaseMCPServerConnectionTool"),Ut);function Tr(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)=>Tr(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)&&Tr(t[s],e[s]))}return!1}$(Tr,"isEqual");var Vt,ai=(Vt=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,y.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){y.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?"✅":"❌"}));y.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&y.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),y.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(y.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),y.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){y.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!Tr(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,y.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):y.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){y.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){y.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Rg(this),new Fg(this),new Lg(this),new $g(this),new Vg(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return y.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},$(Vt,"ServerManager"),Vt),Bt,li=(Bt=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 Ht(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>ui);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Ht(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>ui);return{initializeLangfuse:o}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),y.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"),y.debug("ObservabilityManager: Langfuse handler available"))}catch{y.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(y.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?y.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):y.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(y.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),y.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],y.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();y.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();y.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},$(Bt,"ObservabilityManager"),Bt),Bg="/api/v1/chats",zg="/api/v1/chats/{chat_id}/execute";function nc(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}}$(nc,"normalizeRemoteRunOptions");var zt,Wg=(zt=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??(typeof process<"u"&&Ls?.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 Vn(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){y.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}${Bg}`;y.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(),l=s.status;throw l===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: ${l} - ${a}`)}const i=(await s.json()).id;return y.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:l,outputSchema:c}=nc(e,n,r,s,o);l!==void 0&&y.warn("External history is not yet supported for remote execution");try{y.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};c&&(h.output_schema=this.pydanticToJsonSchema(c),y.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${zg.replace("{chat_id}",u)}`;y.info(`🚀 Executing agent in chat ${u}`);const p=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!p.ok){const S=await p.text(),C=p.status;throw C===401?(y.error(`❌ Authentication failed: ${S}`),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?(y.error(`❌ Access forbidden: ${S}`),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?(y.error(`❌ Agent not found: ${S}`),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?(y.error(`❌ Validation error: ${S}`),new Error(`Request validation failed: ${S}. Please check your query parameters and output schema format.`)):C===500?(y.error(`❌ Server error: ${S}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(y.error(`❌ Remote execution failed with status ${C}: ${S}`),new Error(`Remote agent execution failed: ${C} - ${S}`))}const m=await p.json();if(y.info(`🔧 Response: ${JSON.stringify(m)}`),y.info("✅ Remote execution completed successfully"),typeof m=="object"&&m!==null){if(m.status==="error"||m.error!==null){const S=m.error??String(m);throw y.error(`❌ Remote agent execution failed: ${S}`),new Error(`Remote agent execution failed: ${S}`)}if(String(m).includes("failed to initialize"))throw y.error(`❌ Agent initialization failed: ${m}`),new Error(`Agent initialization failed on remote server. This usually indicates:
342
+ `)}},$(Vt,"ListMCPServersTool"),Vt),Bg=be({}),Bt,zg=(Bt=class extends Nr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Bg;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}'.`}},$(Bt,"ReleaseMCPServerConnectionTool"),Bt);function kr(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)=>kr(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)&&kr(t[s],e[s]))}return!1}$(kr,"isEqual");var zt,ci=(zt=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,y.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){y.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?"✅":"❌"}));y.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&y.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),y.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(y.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),y.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){y.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!kr(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,y.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):y.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){y.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){y.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Lg(this),new Vg(this),new Fg(this),new jg(this),new zg(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return y.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},$(zt,"ServerManager"),zt),Wt,ui=(Wt=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 Kt(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>di);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Kt(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>di);return{initializeLangfuse:o}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),y.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"),y.debug("ObservabilityManager: Langfuse handler available"))}catch{y.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(y.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?y.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):y.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(y.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),y.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],y.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();y.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();y.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},$(Wt,"ObservabilityManager"),Wt),Wg="/api/v1/chats",Hg="/api/v1/chats/{chat_id}/execute";function sc(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}}$(sc,"normalizeRemoteRunOptions");var Ht,Gg=(Ht=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??(typeof process<"u"&&Ds?.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 Bn(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){y.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}${Wg}`;y.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(),l=s.status;throw l===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: ${l} - ${a}`)}const i=(await s.json()).id;return y.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:l,outputSchema:c}=sc(e,n,r,s,o);l!==void 0&&y.warn("External history is not yet supported for remote execution");try{y.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};c&&(h.output_schema=this.pydanticToJsonSchema(c),y.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${Hg.replace("{chat_id}",u)}`;y.info(`🚀 Executing agent in chat ${u}`);const p=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!p.ok){const C=await p.text(),T=p.status;throw T===401?(y.error(`❌ Authentication failed: ${C}`),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.")):T===403?(y.error(`❌ Access forbidden: ${C}`),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.`)):T===404?(y.error(`❌ Agent not found: ${C}`),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.`)):T===422?(y.error(`❌ Validation error: ${C}`),new Error(`Request validation failed: ${C}. Please check your query parameters and output schema format.`)):T===500?(y.error(`❌ Server error: ${C}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(y.error(`❌ Remote execution failed with status ${T}: ${C}`),new Error(`Remote agent execution failed: ${T} - ${C}`))}const m=await p.json();if(y.info(`🔧 Response: ${JSON.stringify(m)}`),y.info("✅ Remote execution completed successfully"),typeof m=="object"&&m!==null){if(m.status==="error"||m.error!==null){const C=m.error??String(m);throw y.error(`❌ Remote agent execution failed: ${C}`),new Error(`Remote agent execution failed: ${C}`)}if(String(m).includes("failed to initialize"))throw y.error(`❌ Agent initialization failed: ${m}`),new Error(`Agent initialization failed on remote server. This usually indicates:
343
343
  • Invalid agent configuration (LLM model, system prompt)
344
344
  • Missing or invalid MCP server configurations
345
345
  • Network connectivity issues with MCP servers
346
346
  • Missing environment variables or credentials
347
- Raw error: ${m}`)}return c?this.parseStructuredResponse(m,c):typeof m=="object"&&m!==null&&"result"in m?m.result:typeof m=="string"?m:String(m)}catch(u){throw u instanceof Error?u.name==="AbortError"?(y.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.")):(y.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${u.message}`)):(y.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(){y.info("🔌 Remote agent client closed")}},$(zt,"RemoteAgent"),zt),kn={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 yo(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 kn)){const o=Object.keys(kn).join(", ");throw new Error(`Unsupported LLM provider '${n}'. Supported providers: ${o}`)}return{provider:s,model:r}}$(yo,"parseLLMString");function rc(t,e){if(e?.apiKey)return e.apiKey;const n=kn[t];if(typeof process<"u"&&Ls)for(const s of n.envVars){const o=Ls[s];if(o)return y.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' } })`)}$(rc,"getAPIKey");async function sc(t,e){y.info(`Creating LLM from string: ${t}`);const{provider:n,model:r}=yo(t),s=kn[n],o=rc(n,e);let i;try{y.debug(`Importing package ${s.package}...`),i=await import(s.package)}catch(c){throw c?.code==="MODULE_NOT_FOUND"||c?.message?.includes("Cannot find module")||c?.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}: ${c?.message||c}`)}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 l={model:r,apiKey:o,...e};e?.apiKey&&(delete l.apiKey,l.apiKey=o),(n==="anthropic"||n==="google"||n==="openai"||n==="groq")&&(l.model=r);try{const c=new a(l);return y.info(`Successfully created ${n} LLM with model ${r}`),c}catch(c){throw new Error(`Failed to instantiate ${s.className} with model '${r}': ${c?.message||c}`)}}$(sc,"createLLMFromString");function Hg(t){try{return yo(t),!0}catch{return!1}}$(Hg,"isValidLLMString");function Gg(){return Object.keys(kn)}$(Gg,"getSupportedProviders");function oc(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}$(oc,"generateToolDescriptions");function ic(t,e,n){const r=e.join(`
347
+ Raw error: ${m}`)}return c?this.parseStructuredResponse(m,c):typeof m=="object"&&m!==null&&"result"in m?m.result:typeof m=="string"?m:String(m)}catch(u){throw u instanceof Error?u.name==="AbortError"?(y.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.")):(y.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${u.message}`)):(y.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(){y.info("🔌 Remote agent client closed")}},$(Ht,"RemoteAgent"),Ht),xn={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 wo(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 xn)){const o=Object.keys(xn).join(", ");throw new Error(`Unsupported LLM provider '${n}'. Supported providers: ${o}`)}return{provider:s,model:r}}$(wo,"parseLLMString");function oc(t,e){if(e?.apiKey)return e.apiKey;const n=xn[t];if(typeof process<"u"&&Ds)for(const s of n.envVars){const o=Ds[s];if(o)return y.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' } })`)}$(oc,"getAPIKey");async function ic(t,e){y.info(`Creating LLM from string: ${t}`);const{provider:n,model:r}=wo(t),s=xn[n],o=oc(n,e);let i;try{y.debug(`Importing package ${s.package}...`),i=await import(s.package)}catch(c){throw c?.code==="MODULE_NOT_FOUND"||c?.message?.includes("Cannot find module")||c?.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}: ${c?.message||c}`)}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 l={model:r,apiKey:o,...e};e?.apiKey&&(delete l.apiKey,l.apiKey=o),(n==="anthropic"||n==="google"||n==="openai"||n==="groq")&&(l.model=r);try{const c=new a(l);return y.info(`Successfully created ${n} LLM with model ${r}`),c}catch(c){throw new Error(`Failed to instantiate ${s.className} with model '${r}': ${c?.message||c}`)}}$(ic,"createLLMFromString");function Kg(t){try{return wo(t),!0}catch{return!1}}$(Kg,"isValidLLMString");function Jg(){return Object.keys(xn)}$(Jg,"getSupportedProviders");function ac(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}$(ac,"generateToolDescriptions");function lc(t,e,n){const r=e.join(`
348
348
  `);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}
349
349
 
350
350
  Available tools:
351
351
  ${r}`),n&&(s+=`
352
352
 
353
- ${n}`),s}$(ic,"buildSystemPromptContent");function ac(t,e,n,r,s,o,i){if(o)return new te({content:o});const a=r?n:e,l=oc(t,s),c=ic(a,l,i);return new te({content:c})}$(ac,"createSystemMessage");var Kg=`You are a helpful AI assistant.
353
+ ${n}`),s}$(lc,"buildSystemPromptContent");function cc(t,e,n,r,s,o,i){if(o)return new ne({content:o});const a=r?n:e,l=ac(t,s),c=lc(a,l,i);return new ne({content:c})}$(cc,"createSystemMessage");var qg=`You are a helpful AI assistant.
354
354
  You have access to the following tools:
355
355
 
356
356
  {tool_descriptions}
@@ -364,7 +364,7 @@ Action Input: the input to the action
364
364
  Observation: the result of the action
365
365
  ... (this Thought/Action/Action Input/Observation can repeat N times)
366
366
  Thought: I now know the final answer
367
- Final Answer: the final answer to the original input question`,Jg=`You are a helpful assistant designed to interact with MCP
367
+ Final Answer: the final answer to the original input question`,Yg=`You are a helpful assistant designed to interact with MCP
368
368
  (Model Context Protocol) servers. You can manage connections to different servers and use the tools
369
369
  provided by the currently active server.
370
370
 
@@ -387,9 +387,9 @@ You can then use these server-specific tools in subsequent steps.
387
387
  Here are the tools *currently* available to you (this list includes server management tools and will
388
388
  change when you connect to a server):
389
389
  {tool_descriptions}
390
- `;function ar(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}}$(ar,"normalizeRunOptions");var Wt,iy=(Wt=class{static getPackageVersion(){return gc()}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 Wg({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 St,this.telemetry=Rr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new li({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=[],y.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 St(this.disallowedTools),this.telemetry=Rr.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 St(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new ai(this.client,this.adapter)}else this.adapter=e.adapter??new St(this.disallowedTools);if(this.telemetry=Rr.getInstance(),this.llm){const[r,s]=bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new li({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:$(()=>this.getMetadata(),"metadataProvider"),tagsProvider:$(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:$(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:$(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:$(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ht(async()=>{const{MCPClient:s}=await import("./client-DQIxf_-5.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await sc(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=bo(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 ai(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.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),y.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(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.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]),y.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],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.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),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.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),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Kg;this.systemMessage=ac(e,n,Jg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof te))])}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);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Ql({runLimit:this.maxSteps})],s=Nl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.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 te(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof te)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new St(this.disallowedTools),this._initialized&&y.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},y.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])],y.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){y.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?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.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){y.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){y.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 I)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 ee)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 j)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 I||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:l,externalHistory:c,outputSchema:u}=ar(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,l,c,u);const h=this.stream(i,a,l,c,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=ar(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,l,c,u);let h=!1;const d=Date.now();let f=!1,p=null,m=0;try{if(l&&!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 k=this.serverManager.tools,_=new Set(k.map(x=>x.name)),v=new Set(this._tools.map(x=>x.name));(_.size!==v.size||[..._].some(x=>!v.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[..._].join(", ")}`),this._tools=k,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const k of S)(this._isHumanMessageLike(k)||this._isAIMessageLike(k)||this._isToolMessageLike(k))&&C.push(k);const E=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");y.info(`💬 Received query: '${E}'`),y.info("🏁 Starting agent execution");const b=3;let w=0;const g=[...C,new ee(i)];for(;w<=b;){const k={messages:g};let _=!1;const v=await this._agentExecutor.stream(k,{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 v){for(const[T,M]of Object.entries(x))if(y.debug(`📦 Node '${T}' output: ${JSON.stringify(M)}`),M&&typeof M=="object"&&"messages"in M){let P=M.messages;Array.isArray(P)||(P=[P]);for(const N of P)g.includes(N)||g.push(N);for(const N of P){if("tool_calls"in N&&Array.isArray(N.tool_calls)&&N.tool_calls.length>0)for(const oe of N.tool_calls){const ae=oe.name||"unknown",Ce=oe.args||{};this.toolsUsedNames.push(ae),m++;let Pe=JSON.stringify(Ce);Pe.length>100&&(Pe=`${Pe.slice(0,97)}...`),y.info(`🔧 Tool call: ${ae} with input: ${Pe}`),yield{action:{tool:ae,toolInput:Ce,log:`Calling tool ${ae}`},observation:""}}if(this._isToolMessageLike(N)){const oe=N.content;let ae=String(oe);if(ae.length>100&&(ae=`${ae.slice(0,97)}...`),ae=ae.replace(/\n/g," "),y.info(`📄 Tool result: ${ae}`),this.useServerManager&&this.serverManager){const Ce=this.serverManager.tools,Pe=new Set(Ce.map(nn=>nn.name)),Nn=new Set(this._tools.map(nn=>nn.name));if(Pe.size!==Nn.size||[...Pe].some(nn=>!Nn.has(nn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Pe].join(", ")}`),this._tools=Ce,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),_=!0,w++,y.info(`🔃 Restarting execution with updated tools (restart ${w}/${b})`);break}}}this._isAIMessageLike(N)&&!this._messageHasToolCalls(N)&&(p=this._normalizeOutput(this._getMessageContent(N)),y.info("✅ Agent finished with output"))}if(_)break}if(_)break}if(!_)break;if(w>b){y.warn(`⚠️ Max restarts (${b}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const k=g.slice(C.length);for(const _ of k)this.addToHistory(_)}if(u&&p)try{y.info("🔧 Attempting structured output...");const k=await this._attemptStructuredOutput(p,this.llm,u);return this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(k)}`)),y.info("✅ Structured output successful"),f=!0,k}catch(k){throw y.error(`❌ Structured output failed: ${k}`),new Error(`Failed to generate structured output: ${k instanceof Error?k.message:String(k)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,p||"No output generated"}catch(S){throw y.error(`❌ Error running query: ${S}`),h&&l&&(y.info("🧹 Cleaning up resources after error"),await this.close()),S}finally{const S=Date.now()-d;let C=0;this.client?C=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(C=this.connectors.length);const E=this.memoryEnabled?this.conversationHistory.length:0,b=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:b.length,toolsAvailableNames:b.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:m,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:p||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:E}),l&&!this.client&&h&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new St)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ht(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-BJTIyc8Q.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=ar(e,n,r,s,o);let{query:a}=i;const{maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let p=!1,m=0,S=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{c&&!this._initialized?(await this.initialize(),d=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),d=!0);const E=this._agentExecutor;if(!E)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const b=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);y.info(`💬 Received query for streamEvents: '${b}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${b}`),this.addToHistory(new ee({content:a})));const w=u??this.conversationHistory,g=[];for(const v of w)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?g.push(v):y.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const k=[...g,new ee(a)];y.info("callbacks",this.callbacks);const _=E.streamEvents({messages:k},{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 v of _)if(m++,!(!v||typeof v!="object")){if(v.event==="on_chat_model_stream"&&v.data?.chunk?.content&&(S+=v.data.chunk.content.length),v.event==="on_chat_model_stream"&&v.data?.chunk){const x=v.data.chunk;if(x.content){C||(C="");const T=this._normalizeOutput(x.content);C+=T,y.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const x=v.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){y.info("🔧 Attempting structured output conversion...");try{let v=!1,x=null,T=null;this._attemptStructuredOutput(C,this.llm,h).then(P=>(v=!0,x=P,P)).catch(P=>{throw v=!0,T=P,P});let M=0;for(;!v;)await new Promise(P=>setTimeout(P,2e3)),v||(M++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${M*2}s)`,elapsed:M*2}});if(T)throw T;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new I(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(v){y.warn(`⚠️ Structured output failed: ${v}`),yield{event:"on_structured_output_error",data:{error:v instanceof Error?v.message:String(v)}}}}else this.memoryEnabled&&C&&this.addToHistory(new I(C));console.log(`
390
+ `;function lr(t,e,n,r,s,o){if(typeof t=="object"&&t!==null){const i=t;return{query:i.prompt,maxSteps:i.maxSteps,manageConnector:i.manageConnector,externalHistory:i.externalHistory,outputSchema:i.schema,signal:i.signal}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s,signal:o}}$(lr,"normalizeRunOptions");var Gt,ly=(Gt=class{static getPackageVersion(){return wc()}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 Gg({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 Tt,this.telemetry=jr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new ui({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=[],y.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 Tt(this.disallowedTools),this.telemetry=jr.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 Tt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new ci(this.client,this.adapter)}else this.adapter=e.adapter??new Tt(this.disallowedTools);if(this.telemetry=jr.getInstance(),this.llm){const[r,s]=So(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new ui({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:$(()=>this.getMetadata(),"metadataProvider"),tagsProvider:$(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:$(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:$(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:$(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Kt(async()=>{const{MCPClient:s}=await import("./client-D1IJiNmS.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await ic(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=So(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 ci(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.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),y.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(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.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]),y.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],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.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),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.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),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??qg;this.systemMessage=cc(e,n,Yg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof ne))])}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);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[tc({runLimit:this.maxSteps})],s=Rl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.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 ne(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof ne)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new Tt(this.disallowedTools),this._initialized&&y.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},y.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])],y.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){y.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?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.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){y.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){y.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 P)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 te)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 j)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 P||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,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h,signal:d}=lr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(a,l,c,u,h);const f=this.stream(a,l,c,u,h,d);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h,signal:d}=lr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(a,l,c,u,h);let f=!1;const p=Date.now();let m=!1,C=null,T=0;try{if(c&&!this._initialized?(await this.initialize(),f=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),f=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const _=this.serverManager.tools,M=new Set(_.map(x=>x.name)),b=new Set(this._tools.map(x=>x.name));(M.size!==b.size||[...M].some(x=>!b.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...M].join(", ")}`),this._tools=_,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const k=u??this.conversationHistory,v=[];for(const _ of k)(this._isHumanMessageLike(_)||this._isAIMessageLike(_)||this._isToolMessageLike(_))&&v.push(_);const w=a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:a.replace(/\n/g," ");y.info(`💬 Received query: '${w}'`),y.info("🏁 Starting agent execution");const g=3;let E=0;const S=[...v,new te(a)];for(;E<=g;){const _={messages:S};let M=!1;const b=await this._agentExecutor.stream(_,{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},...d&&{signal:d}});for await(const x of b){if(d?.aborted)break;for(const[I,N]of Object.entries(x))if(y.debug(`📦 Node '${I}' output: ${JSON.stringify(N)}`),N&&typeof N=="object"&&"messages"in N){let V=N.messages;Array.isArray(V)||(V=[V]);for(const ie of V)S.includes(ie)||S.push(ie);for(const ie of V){if("tool_calls"in ie&&Array.isArray(ie.tool_calls)&&ie.tool_calls.length>0)for(const Pe of ie.tool_calls){const pe=Pe.name||"unknown",lt=Pe.args||{};this.toolsUsedNames.push(pe),T++;let Ke=JSON.stringify(lt);Ke.length>100&&(Ke=`${Ke.slice(0,97)}...`),y.info(`🔧 Tool call: ${pe} with input: ${Ke}`),yield{action:{tool:pe,toolInput:lt,log:`Calling tool ${pe}`},observation:""}}if(this._isToolMessageLike(ie)){const Pe=ie.content;let pe=String(Pe);if(pe.length>100&&(pe=`${pe.slice(0,97)}...`),pe=pe.replace(/\n/g," "),y.info(`📄 Tool result: ${pe}`),this.useServerManager&&this.serverManager){const lt=this.serverManager.tools,Ke=new Set(lt.map(sn=>sn.name)),bo=new Set(this._tools.map(sn=>sn.name));if(Ke.size!==bo.size||[...Ke].some(sn=>!bo.has(sn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Ke].join(", ")}`),this._tools=lt,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),M=!0,E++,y.info(`🔃 Restarting execution with updated tools (restart ${E}/${g})`);break}}}this._isAIMessageLike(ie)&&!this._messageHasToolCalls(ie)&&(C=this._normalizeOutput(this._getMessageContent(ie)),y.info("✅ Agent finished with output"))}if(M)break}if(M)break}if(!M)break;if(E>g){y.warn(`⚠️ Max restarts (${g}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const _=S.slice(v.length);for(const M of _)this.addToHistory(M)}if(h&&C)try{y.info("🔧 Attempting structured output...");const _=await this._attemptStructuredOutput(C,this.llm,h);return this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(_)}`)),y.info("✅ Structured output successful"),m=!0,_}catch(_){throw y.error(`❌ Structured output failed: ${_}`),new Error(`Failed to generate structured output: ${_ instanceof Error?_.message:String(_)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-p)/1e3).toFixed(2)} seconds`),m=!0,C||"No output generated"}catch(k){throw y.error(`❌ Error running query: ${k}`),f&&c&&(y.info("🧹 Cleaning up resources after error"),await this.close()),k}finally{const k=Date.now()-p;let v=0;this.client?v=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(v=this.connectors.length);const w=this.memoryEnabled?this.conversationHistory.length:0,g=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:a,success:m,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:v,serverIdentifiers:this.connectors.map(E=>E.publicIdentifier),totalToolsAvailable:g.length,toolsAvailableNames:g.map(E=>E.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,stepsTaken:T,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:C||"",executionTimeMs:k,errorType:m?null:"execution_error",conversationHistoryLength:w}),c&&!this.client&&f&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new Tt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Kt(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-Do8oS54J.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o,i){const a=lr(e,n,r,s,o,i);let{query:l}=a;const{maxSteps:c,manageConnector:u,externalHistory:h,outputSchema:d,signal:f}=a;let p=!1;const m=Date.now();let C=!1,T=0,k=0,v="";d&&(l=this._enhanceQueryWithSchema(l,d));try{u&&!this._initialized?(await this.initialize(),p=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),p=!0);const w=this._agentExecutor;if(!w)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const g=typeof l=="string"&&l.length>50?`${l.slice(0,50).replace(/\n/g," ")}...`:typeof l=="string"?l.replace(/\n/g," "):String(l);y.info(`💬 Received query for streamEvents: '${g}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${g}`),this.addToHistory(new te({content:l})));const E=h??this.conversationHistory,S=[];for(const b of E)this._isHumanMessageLike(b)||this._isAIMessageLike(b)||this._isToolMessageLike(b)?S.push(b):y.info(`⚠️ Skipped message of type: ${b.constructor?.name||typeof b}`);const _=[...S,new te(l)];y.info("callbacks",this.callbacks);const M=w.streamEvents({messages:_},{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},...f&&{signal:f}});for await(const b of M){if(f?.aborted)break;if(T++,!(!b||typeof b!="object")){if(b.event==="on_chat_model_stream"&&b.data?.chunk?.content&&(k+=b.data.chunk.content.length),b.event==="on_chat_model_stream"&&b.data?.chunk){const x=b.data.chunk;if(x.content){v||(v="");const I=this._normalizeOutput(x.content);v+=I,y.debug(`📝 Accumulated response length: ${v.length}`)}}if(yield b,b.event==="on_chain_end"&&b.data?.output&&!v){const x=b.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?v=x[0].text:typeof x=="string"?v=x:x&&typeof x=="object"&&"output"in x&&(v=x.output)}}}if(d&&v){y.info("🔧 Attempting structured output conversion...");try{let b=!1,x=null,I=null;this._attemptStructuredOutput(v,this.llm,d).then(V=>(b=!0,x=V,V)).catch(V=>{throw b=!0,I=V,V});let N=0;for(;!b;)await new Promise(V=>setTimeout(V,2e3)),b||(N++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${N*2}s)`,elapsed:N*2}});if(I)throw I;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(b){y.warn(`⚠️ Structured output failed: ${b}`),yield{event:"on_structured_output_error",data:{error:b instanceof Error?b.message:String(b)}}}}else this.memoryEnabled&&v&&this.addToHistory(new P(v));console.log(`
391
391
 
392
- `),y.info(`🎉 StreamEvents complete - ${m} events emitted`),p=!0}catch(E){throw y.error(`❌ Error during streamEvents: ${E}`),d&&c&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),E}finally{const E=Date.now()-f;let b=0;this.client?b=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(b=this.connectors.length);const w=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:p,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:b,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(g=>g.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,response:`[STREAMED RESPONSE - ${S} chars]`,executionTimeMs:E,errorType:p?null:"streaming_error",conversationHistoryLength:w}),c&&!this.client&&d&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Vn(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=Vn(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){y.info(`🔄 Structured output attempt ${f}/${h}`);let p=`
392
+ `),y.info(`🎉 StreamEvents complete - ${T} events emitted`),C=!0}catch(w){throw y.error(`❌ Error during streamEvents: ${w}`),p&&u&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),w}finally{const w=Date.now()-m;let g=0;this.client?g=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(g=this.connectors.length);const E=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:l,success:C,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:g,serverIdentifiers:this.connectors.map(S=>S.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(S=>S.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:u??!0,externalHistoryUsed:h!==void 0,response:`[STREAMED RESPONSE - ${k} chars]`,executionTimeMs:w,errorType:C?null:"streaming_error",conversationHistoryLength:E}),u&&!this.client&&p&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Bn(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=Bn(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){y.info(`🔄 Structured output attempt ${f}/${h}`);let p=`
393
393
  Please format the following information according to the EXACT schema specified below.
394
394
  You must use the exact field names and types as shown in the schema.
395
395
 
@@ -411,7 +411,7 @@ Here are the tools *currently* available to you (this list includes server manag
411
411
  PREVIOUS ATTEMPT FAILED with error: ${d}
412
412
  Please fix the issues mentioned above and ensure the output matches the schema exactly.
413
413
  `);try{y.info(`🔄 Structured output attempt ${f} - using streaming approach`);const m=u.length>300?`${u.slice(0,300)}...`:u;y.info(`🔄 Content being formatted (${u.length} chars): ${m}`),y.info(`🔄 Full format prompt (${p.length} chars):
414
- ${p}`);const S=await s.stream(p);let C=null,E=0;for await(const w of S){if(E++,y.debug(`Chunk ${E}: ${JSON.stringify(w,null,2)}`),typeof w=="string")try{C=JSON.parse(w)}catch{y.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{y.warn(`🔄 Failed to parse chunk as JSON: ${w}`)}E%10===0&&y.debug(`🔄 Structured output streaming: ${E} chunks`)}if(y.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(C,null,2)}`),!C)throw new Error("No structured result received from stream");const b=this._validateStructuredResult(C,r);return y.info(`✅ Structured output successful on attempt ${f}`),b}catch(m){if(d=m instanceof Error?m.message:String(m),y.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw y.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,l=a.isOptional?.()??a._def?.typeName==="ZodOptional",c=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!l&&!c){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 y.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=Vn(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
414
+ ${p}`);const C=await s.stream(p);let T=null,k=0;for await(const w of C){if(k++,y.debug(`Chunk ${k}: ${JSON.stringify(w,null,2)}`),typeof w=="string")try{T=JSON.parse(w)}catch{y.warn(`🔄 Failed to parse string chunk as JSON: ${w}`)}else if(w&&typeof w=="object")T=w;else try{T=JSON.parse(String(w))}catch{y.warn(`🔄 Failed to parse chunk as JSON: ${w}`)}k%10===0&&y.debug(`🔄 Structured output streaming: ${k} chunks`)}if(y.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(T,null,2)}`),!T)throw new Error("No structured result received from stream");const v=this._validateStructuredResult(T,r);return y.info(`✅ Structured output successful on attempt ${f}`),v}catch(m){if(d=m instanceof Error?m.message:String(m),y.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw y.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,l=a.isOptional?.()??a._def?.typeName==="ZodOptional",c=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!l&&!c){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 y.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=Bn(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
415
415
  ${e}
416
416
 
417
417
  IMPORTANT: Your response must include sufficient information to populate the following structured output:
@@ -420,4 +420,4 @@ ${p}`);const S=await s.stream(p);let C=null,E=0;for await(const w of S){if(E++,y
420
420
 
421
421
  Make sure you gather ALL the required information during your task execution.
422
422
  If any required information is missing, continue working to find it.
423
- `}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},$(Wt,"MCPAgent"),Wt),ci={};function X(t){if(typeof process<"u"&&ci)return ci[t]}$(X,"getEnvVar");var qg=X("MCP_USE_LANGFUSE")?.toLowerCase()==="false",En={handler:null,client:null,initPromise:null};async function wo(t,e,n,r){try{const s=await Ht(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.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,p,m,S){super(d),this.agentId=f,this.metadata=p,this.metadataProvider=m,this.tagsProvider=S,this.verbose=d?.verbose??!1}async handleChainStart(d,f,p,m,S,C,E,b){y.debug("Langfuse: Chain start intercepted");const w=this.getCustomTags(),g=this.getMetadata(),k=[...S||[],...w],_={...C||{},...g};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(k)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(_)}`)),super.handleChainStart(d,f,p,m,k,_,E,b)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const p=this.tagsProvider();p&&p.length>0&&d.push(...p)}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 p=this.metadataProvider();p&&Object.assign(d,p)}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 y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};$(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),l=r?r():[],c={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:l.length>0?l:void 0,metadata:a||void 0};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),En.handler=new i(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Ht(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;En.client=new d({publicKey:X("LANGFUSE_PUBLIC_KEY"),secretKey:X("LANGFUSE_SECRET_KEY"),baseUrl:X("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(h){y.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}$(wo,"initializeLangfuse");qg?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!X("LANGFUSE_PUBLIC_KEY")||!X("LANGFUSE_SECRET_KEY")?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):En.initPromise=wo();var Yg=$(()=>En.handler,"langfuseHandler"),Xg=$(()=>En.initPromise,"langfuseInitPromise");const ui=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:wo,langfuseHandler:Yg,langfuseInitPromise:Xg},Symbol.toStringTag,{value:"Module"}));export{qu as BaseAdapter,cy as BaseConnector,uy as BrowserOAuthClientProvider,hy as BrowserTelemetry,dy as HttpConnector,fy as Logger,iy as MCPAgent,py as MCPClient,my as MCPSession,li as ObservabilityManager,Wg as RemoteAgent,gy as Tel,Rr as Telemetry,yy as VERSION,sc as createLLMFromString,Ku as createReadableStreamFromGenerator,gc as getPackageVersion,Gg as getSupportedProviders,Hg as isValidLLMString,y as logger,wy as onMcpAuthorization,yo as parseLLMString,vy as setBrowserTelemetrySource,by as setTelemetrySource,Gu as streamEventsToAISDK,Ju as streamEventsToAISDKWithTools};
423
+ `}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},$(Gt,"MCPAgent"),Gt),hi={};function Z(t){if(typeof process<"u"&&hi)return hi[t]}$(Z,"getEnvVar");var Xg=Z("MCP_USE_LANGFUSE")?.toLowerCase()==="false",Mn={handler:null,client:null,initPromise:null};async function vo(t,e,n,r){try{const s=await Kt(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.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,p,m,C){super(d),this.agentId=f,this.metadata=p,this.metadataProvider=m,this.tagsProvider=C,this.verbose=d?.verbose??!1}async handleChainStart(d,f,p,m,C,T,k,v){y.debug("Langfuse: Chain start intercepted");const w=this.getCustomTags(),g=this.getMetadata(),E=[...C||[],...w],S={...T||{},...g};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(E)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(S)}`)),super.handleChainStart(d,f,p,m,E,S,k,v)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const p=this.tagsProvider();p&&p.length>0&&d.push(...p)}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 p=this.metadataProvider();p&&Object.assign(d,p)}return d}getEnvironmentTag(){const d=Z("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 y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};$(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Z("LANGFUSE_PUBLIC_KEY"),secretKey:Z("LANGFUSE_SECRET_KEY"),baseUrl:Z("LANGFUSE_HOST")||Z("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(Z("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(Z("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:Z("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(Z("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:Z("LANGFUSE_ENABLED")!=="false",traceName:a.trace_name||Z("LANGFUSE_TRACE_NAME")||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),Mn.handler=new i(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Kt(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Mn.client=new d({publicKey:Z("LANGFUSE_PUBLIC_KEY"),secretKey:Z("LANGFUSE_SECRET_KEY"),baseUrl:Z("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(h){y.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}$(vo,"initializeLangfuse");Xg?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Z("LANGFUSE_PUBLIC_KEY")||!Z("LANGFUSE_SECRET_KEY")?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Mn.initPromise=vo();var Zg=$(()=>Mn.handler,"langfuseHandler"),Qg=$(()=>Mn.initPromise,"langfuseInitPromise");const di=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:vo,langfuseHandler:Zg,langfuseInitPromise:Qg},Symbol.toStringTag,{value:"Module"}));export{Xu as BaseAdapter,hy as BaseConnector,dy as BrowserOAuthClientProvider,fy as BrowserTelemetry,py as HttpConnector,my as Logger,ly as MCPAgent,gy as MCPClient,yy as MCPSession,ui as ObservabilityManager,Gg as RemoteAgent,wy as Tel,jr as Telemetry,vy as VERSION,ic as createLLMFromString,qu as createReadableStreamFromGenerator,wc as getPackageVersion,Jg as getSupportedProviders,Kg as isValidLLMString,y as logger,by as onMcpAuthorization,wo as parseLLMString,_y as setBrowserTelemetrySource,Sy as setTelemetrySource,Ju as streamEventsToAISDK,Yu as streamEventsToAISDKWithTools};