@mcp-use/inspector 0.14.0-canary.9 → 0.14.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/assets/{browser-CAet5h5U.js → browser-EyInsrZa.js} +48 -48
  2. package/dist/client/assets/client-JeU2zpxn.js +92 -0
  3. package/dist/client/assets/{display-A5IEINAP-CQoSnHLt.js → display-A5IEINAP-Btv2gL3n.js} +2 -2
  4. package/dist/client/assets/{embeddings-DtafgfMS.js → embeddings-Dya_KnH0.js} +1 -1
  5. package/dist/client/assets/{index-Meiz2XrK.js → index--IpKhg5F.js} +1 -1
  6. package/dist/client/assets/{index-BwjhL_Ts.js → index-01y2e9ko.js} +1 -1
  7. package/dist/client/assets/{index-BghX1ooe.js → index-3gQQW6s7.js} +1 -1
  8. package/dist/client/assets/{index-hiNxmj9U.js → index-BZCfajuh.js} +1 -1
  9. package/dist/client/assets/{index-DrmcYZGT.js → index-BiUxRAkS.js} +1 -1
  10. package/dist/client/assets/{index-DXT6rsWo.js → index-CwGEcSpK.js} +1 -1
  11. package/dist/client/assets/{index-c1SU-y-r.js → index-D7646HFQ.js} +1 -1
  12. package/dist/client/assets/index-DoHGzyNN.js +1753 -0
  13. package/dist/client/assets/index-G80eS8Oh.css +1 -0
  14. package/dist/client/assets/{index-B8ArYgSz.js → index-dRu1bjMq.js} +1 -1
  15. package/dist/client/assets/{llms-Bpg_7xxf.js → llms-CQ_t8ic9.js} +1 -1
  16. package/dist/client/index.html +3 -3
  17. package/dist/client/index.js +1096 -0
  18. package/dist/server/server.d.ts +11 -0
  19. package/dist/server/server.d.ts.map +1 -1
  20. package/dist/server/shared-static.d.ts +5 -1
  21. package/dist/server/shared-static.d.ts.map +1 -1
  22. package/dist/server/shared-utils-browser.d.ts +9 -1
  23. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  24. package/dist/server/transport-wrapper.d.ts +1 -1
  25. package/dist/server/transport-wrapper.d.ts.map +1 -1
  26. package/dist/server/utils.d.ts +13 -0
  27. package/dist/server/utils.d.ts.map +1 -1
  28. package/package.json +9 -4
  29. package/dist/client/assets/client-CAJCPqsR.js +0 -92
  30. package/dist/client/assets/index-D_5vBeGJ.css +0 -1
  31. package/dist/client/assets/index-DfGhdcvP.js +0 -1753
@@ -1,48 +1,48 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-CAJCPqsR.js","assets/index-DfGhdcvP.js","assets/index-D_5vBeGJ.css","assets/display-A5IEINAP-CQoSnHLt.js"])))=>i.map(i=>d[i]);
2
- import{_ as N,o as we,l as m,s as vr,O as ke,Z as Mr,w as Ar,j as $l,n as Rl,i as jl,P as Ll,Q as Dl,S as Fl,p as ei,e as Ul,U as Pr,V as co,a as Ut,x as $n}from"./index-DfGhdcvP.js";import{B as ag,W as lg,T as cg,H as ug,X as hg,Y as dg,M as fg,T as pg,a0 as mg,a1 as gg,a2 as yg,a2 as wg}from"./index-DfGhdcvP.js";import{D as Rn,S as _r,t as Vl,a as ti,T as Bl,b as zl}from"./index-DXT6rsWo.js";import{h as Cn,s as Hl,k as Wl,I as Gl,C as Kl,g as ni,d as ql,l as Jl,m as Yl,t as Xl,n as Zl,o as Ql,p as ec,q as tc,r as nc,u as rc,v as sc,w as oc,x as ic,y as ac,R as lc,z as cc,e as uc}from"./index-BwjhL_Ts.js";import{aT as hc,aU as Ps,aV as dc,aw as Oe,e as nn,aW as fc,aX as hn,a4 as fe,y as Ee,aY as ri,i as pc,aZ as Qr,g as J,aj as Xt,ah as pe,B as O,S as Q,p as mc,C as gc,a_ as yc,aE as si,a$ as _e,al as dn,b0 as an,F as oi,z as je,b1 as Os,u as uo,D as es,E as Vt,ap as Bt,b2 as wc,b3 as bc,b4 as vc,b5 as _c,b6 as Sc,b7 as Cc,b8 as kc,b9 as Tc,ba as Ec,bb as xc,bc as Mc,bd as Ac,be as Pc,bf as Oc,bg as Nc,bh as Ic,bi as $c,L as Rc,bj as jc,bk as Lc,bl as Dc,A as Ve,k as ln,m as Fe,M as tt,at as zt,bm as Fc,H as Uc,aF as ho,au as Vc,bn as fo,bo as po,af as Ns,ae as mo,ad as ts,ag as Bc,V as zc,a9 as Is,ac as Xe,bp as tr,o as z,bq as le,br as Hc,bs as Ie,bt as Ct,bu as Wc,bv as $s,f as U,aa as Gc,r as Kc,T as qc,bw as nr,bx as He,by as V,bz as ii,s as ne,ab as Jc,bA as jn,bB as ai,bC as Ht,bD as fn,bE as rr,bF as sr,bG as Yc,aP as Xc,aN as Zc,aM as Qc,bH as eu}from"./index-DrmcYZGT.js";import{E as li,c as tu,e as nu}from"./embeddings-DtafgfMS.js";import{L as ci,o as ru,l as su}from"./llms-Bpg_7xxf.js";var Or,Mn,Nr=0,Ir=0;function ou(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=Or),i==null&&(i=Mn)),o==null||i==null){var a=t.random||(t.rng||hc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Or&&!t._v6&&(o[0]|=1,Or=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Mn===void 0&&!t._v6&&(Mn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ir+1,u=l-Nr+(c-Ir)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Nr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Nr=l,Ir=c,Mn=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||Ps(s)}function iu(t){var e=typeof t=="string"?dc(t):t,n=au(e);return typeof t=="string"?Ps(n):n}function au(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 go(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 yo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?go(Object(n),!0).forEach(function(r){lu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):go(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function lu(t,e,n){return(e=cu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function cu(t){var e=uu(t,"string");return typeof e=="symbol"?e:e+""}function uu(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=ou(yo(yo({},t),{},{_v6:!0}),new Uint8Array(16));return r=iu(r),Ps(r)}async function*du(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)}}N(du,"streamEventsToAISDK");function fu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}N(fu,"createReadableStreamFromGenerator");async function*pu(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-JeU2zpxn.js","assets/index-DoHGzyNN.js","assets/index-G80eS8Oh.css","assets/display-A5IEINAP-Btv2gL3n.js"])))=>i.map(i=>d[i]);
2
+ import{O as co,P as Rl,Q as jl,_ as N,o as we,l as m,s as br,S as ke,Z as Mr,w as Ar,j as Ll,n as Dl,i as Fl,U as Ul,V as Vl,W as Bl,p as ti,e as zl,X as Pr,Y as uo,a as Ut,x as $n}from"./index-DoHGzyNN.js";import{B as fg,a0 as pg,T as mg,H as gg,a1 as yg,a2 as wg,M as vg,T as bg,a3 as _g,a4 as Sg,a5 as Cg,a5 as kg}from"./index-DoHGzyNN.js";import{D as Rn,S as _r,t as Wl,a as ni,T as Hl,b as Gl}from"./index-CwGEcSpK.js";import{h as Cn,s as Kl,k as ql,I as Jl,C as Yl,g as ri,d as Xl,l as Zl,m as Ql,t as ec,n as tc,o as nc,p as rc,q as sc,r as oc,u as ic,v as ac,w as lc,x as cc,y as uc,R as hc,z as dc,e as fc}from"./index-01y2e9ko.js";import{aT as pc,aU as Ps,aV as mc,aw as Oe,e as nn,aW as gc,aX as hn,a4 as fe,y as Ee,aY as si,i as yc,aZ as Qr,g as J,aj as Xt,ah as pe,B as O,S as Q,p as wc,C as vc,a_ as bc,aE as oi,a$ as _e,al as dn,b0 as an,F as ii,z as je,b1 as Os,u as ho,D as es,E as Vt,ap as Bt,b2 as _c,b3 as Sc,b4 as Cc,b5 as kc,b6 as Tc,b7 as Ec,b8 as xc,b9 as Mc,ba as Ac,bb as Pc,bc as Oc,bd as Nc,be as Ic,bf as $c,bg as Rc,bh as jc,bi as Lc,L as Dc,bj as Fc,bk as Uc,bl as Vc,A as Ve,k as ln,m as Fe,M as tt,at as zt,bm as Bc,H as zc,aF as fo,au as Wc,bn as po,bo as mo,af as Ns,ae as go,ad as ts,ag as Hc,V as Gc,a9 as Is,ac as Xe,bp as tr,o as z,bq as le,br as Kc,bs as Ie,bt as Ct,bu as qc,bv as $s,f as U,aa as Jc,r as Yc,T as Xc,bw as nr,bx as We,by as V,bz as ai,s as ne,ab as Zc,bA as jn,bB as li,bC as Wt,bD as fn,bE as rr,bF as sr,bG as Qc,aP as eu,aN as tu,aM as nu,bH as ru}from"./index-BiUxRAkS.js";import{E as ci,c as su,e as ou}from"./embeddings-Dya_KnH0.js";import{L as ui,o as iu,l as au}from"./llms-CQ_t8ic9.js";const lu=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},cu=()=>{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 ${lu(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Rl(r.values[0])}`:`Invalid option: expected one of ${co(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":""}: ${co(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:cu()}}jl(uu());var Or,Mn,Nr=0,Ir=0;function hu(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=Or),i==null&&(i=Mn)),o==null||i==null){var a=t.random||(t.rng||pc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Or&&!t._v6&&(o[0]|=1,Or=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Mn===void 0&&!t._v6&&(Mn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ir+1,u=l-Nr+(c-Ir)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Nr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Nr=l,Ir=c,Mn=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||Ps(s)}function du(t){var e=typeof t=="string"?mc(t):t,n=fu(e);return typeof t=="string"?Ps(n):n}function fu(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 yo(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 wo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?yo(Object(n),!0).forEach(function(r){pu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):yo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function pu(t,e,n){return(e=mu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mu(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 yu(t={},e,n=0){var r=hu(wo(wo({},t),{},{_v6:!0}),new Uint8Array(16));return r=du(r),Ps(r)}async function*wu(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)}}N(wu,"streamEventsToAISDK");function vu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}N(vu,"createReadableStreamFromGenerator");async function*bu(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}}N(pu,"streamEventsToAISDKWithTools");var xt,mu=(xt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(m.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return m.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),m.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return m.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return m.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return m.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){m.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return m.error(`Error initializing connector: ${n}`),!1}}return!0}},N(xt,"BaseAdapter"),xt),Mt,gu=(Mt=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:Mr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Mr.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:Mr.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 Ar(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 $l();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Rl();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=vr();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 Ar(o)}const n=e.items?this.parseSchema(e.items):ke(),r=jl(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,we(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const 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=we(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return ke();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Ll()):n.push(this.parseSchema(r));return n.length>=2?Ar(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}},N(Mt,"JSONSchemaToZod"),Mt);function ui(t){try{return gu.convert(t)}catch(e){return m.warn(`Failed to convert JSON schema to Zod: ${e}`),ke()}}N(ui,"schemaToZod");var At,gt=(At=class extends mu{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?ui(e.inputSchema):we({}).optional();return new Rn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:N(async o=>{m.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return m.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=N(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Rn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:we({}).optional(),func:N(async()=>{m.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 m.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=we({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=vr();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?we(o):we({}).optional()}return new Rn({name:e.name,description:e.description||"",schema:r,func:N(async o=>{m.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
8
- `):"Prompt returned no messages"}catch(i){return m.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},N(At,"LangChainAdapter"),At),yu=Object.defineProperty,hi=(t,e)=>{for(var n in e)yu(t,n,{get:e[n],enumerable:!0})},wu={};hi(wu,{ConfigurableModel:()=>ns,MODEL_PROVIDER_CONFIG:()=>Sr,_inferModelProvider:()=>pi,getChatModelByClassName:()=>fi,initChatModel:()=>Zt});const Sr={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}},di=Object.keys(Sr);async function fi(t){const e=Object.entries(Sr).find(([,r])=>r.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s){const o=s.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${o}. Please install with \`npm install ${o}\` or \`pnpm install ${o}\``)}throw r}}async function bu(t,e,n={}){const r=e||pi(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=Sr[r];if(!s){const l=di.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
6
+ `;break}}N(bu,"streamEventsToAISDKWithTools");var xt,_u=(xt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(m.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return m.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),m.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return m.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return m.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return m.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){m.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return m.error(`Error initializing connector: ${n}`),!1}}return!0}},N(xt,"BaseAdapter"),xt),Mt,Su=(Mt=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:Mr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Mr.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:Mr.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 Ar(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 Ll();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Dl();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=br();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 Ar(o)}const n=e.items?this.parseSchema(e.items):ke(),r=Fl(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,we(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const 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=we(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return ke();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Ul()):n.push(this.parseSchema(r));return n.length>=2?Ar(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}},N(Mt,"JSONSchemaToZod"),Mt);function hi(t){try{return Su.convert(t)}catch(e){return m.warn(`Failed to convert JSON schema to Zod: ${e}`),ke()}}N(hi,"schemaToZod");var At,gt=(At=class extends _u{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?hi(e.inputSchema):we({}).optional();return new Rn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:N(async o=>{m.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return m.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=N(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Rn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:we({}).optional(),func:N(async()=>{m.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 m.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=we({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=br();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?we(o):we({}).optional()}return new Rn({name:e.name,description:e.description||"",schema:r,func:N(async o=>{m.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
8
+ `):"Prompt returned no messages"}catch(i){return m.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},N(At,"LangChainAdapter"),At),Cu=Object.defineProperty,di=(t,e)=>{for(var n in e)Cu(t,n,{get:e[n],enumerable:!0})},ku={};di(ku,{ConfigurableModel:()=>ns,MODEL_PROVIDER_CONFIG:()=>Sr,_inferModelProvider:()=>mi,getChatModelByClassName:()=>pi,initChatModel:()=>Zt});const Sr={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}},fi=Object.keys(Sr);async function pi(t){const e=Object.entries(Sr).find(([,r])=>r.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s){const o=s.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${o}. Please install with \`npm install ${o}\` or \`pnpm install ${o}\``)}throw r}}async function Tu(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=Sr[r];if(!s){const l=fi.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
9
9
 
10
- Supported model providers are: ${l}`)}const{modelProvider:o,...i}=n,a=await fi(s.className);return new a({model:t,...i})}function pi(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 ns=class Ln extends Cn{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations}async _model(e){const n={...this._defaultConfig,...this._modelParams(e)};let r=await bu(n.model,n.modelProvider,n);const s=Object.entries(this._queuedMethodOperations);if(s.length>0)for(const[o,i]of s)o in r&&typeof r[o]=="function"&&(r=await r[o](...i));return r}async _generate(e,n,r){return(await this._model(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new Ln({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new Ln({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 Ln({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new Oe({config:n,bound:o})}async invoke(e,n){const r=await this._model(n),s=nn(n);return r.invoke(e,s)}async stream(e,n){const r=await this._model(n),s=new fc({generator:await r.stream(e,n),config:n});return await s.setup,hn.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._model(n),s=nn(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._model(n),o=nn(n);yield*s.streamLog(e,o,{...r,_schemaFormat:"original",includeNames:r?.includeNames,includeTypes:r?.includeTypes,includeTags:r?.includeTags,excludeNames:r?.excludeNames,excludeTypes:r?.excludeTypes,excludeTags:r?.excludeTags})}streamEvents(e,n,r){const s=this;async function*o(){const i=await s._model(n),a=nn(n),l=i.streamEvents(e,a,r);for await(const c of l)yield c}return hn.fromAsyncGenerator(o())}};async function Zt(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,...o}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[l,...c]=t.split(":"),u=c.length===0?[l]:[l,c.join(":")];di.includes(u[0])&&([s,t]=u)}let i=Array.isArray(n)?[...n]:n;!t&&i===void 0&&(i=["model","modelProvider"]),r&&i===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);const a={...o};return i===void 0?new ns({defaultConfig:{...a,model:t,modelProvider:s},configPrefix:r}):(t&&(a.model=t),s&&(a.modelProvider=s),new ns({defaultConfig:a,configPrefix:r,configurableFields:i}))}var rs=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.")}},ss=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}},mi=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
10
+ Supported model providers are: ${l}`)}const{modelProvider:o,...i}=n,a=await pi(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 ns=class Ln extends Cn{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations}async _model(e){const n={...this._defaultConfig,...this._modelParams(e)};let r=await Tu(n.model,n.modelProvider,n);const s=Object.entries(this._queuedMethodOperations);if(s.length>0)for(const[o,i]of s)o in r&&typeof r[o]=="function"&&(r=await r[o](...i));return r}async _generate(e,n,r){return(await this._model(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new Ln({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new Ln({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 Ln({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new Oe({config:n,bound:o})}async invoke(e,n){const r=await this._model(n),s=nn(n);return r.invoke(e,s)}async stream(e,n){const r=await this._model(n),s=new gc({generator:await r.stream(e,n),config:n});return await s.setup,hn.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._model(n),s=nn(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._model(n),o=nn(n);yield*s.streamLog(e,o,{...r,_schemaFormat:"original",includeNames:r?.includeNames,includeTypes:r?.includeTypes,includeTags:r?.includeTags,excludeNames:r?.excludeNames,excludeTypes:r?.excludeTypes,excludeTags:r?.excludeTags})}streamEvents(e,n,r){const s=this;async function*o(){const i=await s._model(n),a=nn(n),l=i.streamEvents(e,a,r);for await(const c of l)yield c}return hn.fromAsyncGenerator(o())}};async function Zt(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,...o}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[l,...c]=t.split(":"),u=c.length===0?[l]:[l,c.join(":")];fi.includes(u[0])&&([s,t]=u)}let i=Array.isArray(n)?[...n]:n;!t&&i===void 0&&(i=["model","modelProvider"]),r&&i===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);const a={...o};return i===void 0?new ns({defaultConfig:{...a,model:t,modelProvider:s},configPrefix:r}):(t&&(a.model=t),s&&(a.modelProvider=s),new ns({defaultConfig:a,configPrefix:r,configurableFields:i}))}var rs=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.")}},ss=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}},gi=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
11
11
  - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},Rs=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 js(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function or(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}let vu=0;var Ge=class os{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-${++vu}`}if(pc(e)){const a=Ee(e),l={type:"function",function:{name:r(),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new os(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=Ee(e),i={type:"function",function:s};return new os(o,i,n)}parse(e){const r=new ri(this.schema).validate(e);if(!r.valid)throw new mi(this.name,r.errors.map(s=>s.error));return e}},it=class gi{_schemaType;constructor(e){this.schema=e}static fromSchema(e){const n=Ee(e);return new gi(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new ri(this.schema).validate(n).valid?n:void 0}catch{}}};function yi(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 Ge||s instanceof it))return t;if(t.every(s=>fe(s)))return t.map(s=>Ge.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!fe(s)))return t.map(s=>Ge.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 Ge||t instanceof it)return[t];const r=wi(n);if(fe(t))return r?[it.fromSchema(t)]:[Ge.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[it.fromSchema(t)]:[Ge.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function _u(t,e){return yi(t,e)}function Su(t){return it.fromSchema(t)}const Cu=["ChatOpenAI","ChatXAI"],wo=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function wi(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return wo.some(r=>n.includes(r))}if(or(t))return wi(t._defaultConfig.model);if(!js(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||Cu.includes(e)&&("model"in t&&wo.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Ls(t){let e=0;for(const n of t){let r;typeof n.content=="string"?r=n.content:Array.isArray(n.content)?r=n.content.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join(""):r="",e+=r.length}return Math.ceil(e/4)}function Je(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Cr(t){return typeof t=="function"?t:t.hook}function ku(t){return new Promise(e=>setTimeout(e,t))}function ge(t){return{name:t.name,stateSchema:t.stateSchema,contextSchema:t.contextSchema,wrapToolCall:t.wrapToolCall,wrapModelCall:t.wrapModelCall,beforeAgent:t.beforeAgent,beforeModel:t.beforeModel,afterModel:t.afterModel,afterAgent:t.afterAgent,tools:t.tools??[]}}function bi(t){return hu({clockseq:t})}function bt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Qr(t,new Uint8Array(n))}const Tu="__error__",Dn="__scheduled__",Eu="__interrupt__",xu="__resume__";var bo="[...]",Mu="[Circular]",ir=[],vt=[];function Au(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Pu(t,e,n,r){typeof r>"u"&&(r=Au()),is(t,"",0,[],void 0,0,r);var s;try{vt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,Ou(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;ir.length!==0;){var o=ir.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function $r(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),ir.push([r,n,e,s])):vt.push([e,n,t]):(r[n]=t,ir.push([r,n,e]))}function is(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){$r(Mu,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){$r(bo,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){$r(bo,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)is(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];is(t[c],c,a,r,t,o,i)}}r.pop()}}function Ou(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(vt.length>0)for(var r=0;r<vt.length;r++){var s=vt[r];if(s[1]===e&&s[0]===n){n=s[2],vt.splice(r,1);break}}return t.call(this,e,n)}}const Nu=[];var Iu={},vi={};J(vi,{BaseChatMessageHistory:()=>_i,BaseListChatMessageHistory:()=>Ds,InMemoryChatMessageHistory:()=>$u});var _i=class extends Xt{async addMessages(t){for(const e of t)await this.addMessage(e)}},Ds=class extends Xt{addUserMessage(t){return this.addMessage(new pe(t))}addAIMessage(t){return this.addMessage(new O(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},$u=class extends Ds{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=[]}},Ru={},Si={};J(Si,{BaseMemory:()=>ju,getInputValue:()=>Lu,getOutputValue:()=>Du,getPromptInputKey:()=>Fu});var ju=class{};const Ci=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Lu=(t,e)=>{const n=Ci(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},Du=(t,e)=>{const n=Ci(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 Fu(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 ki={};J(ki,{BaseStore:()=>Ti,InMemoryStore:()=>Ei});var Ti=class extends Xt{},Ei=class extends Ti{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)}},xi={};J(xi,{BaseRetriever:()=>Fs});var Fs=class extends Q{callbacks;tags;metadata;verbose;constructor(t){super(t),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){const n=nn(mc(e)),s=await(await gc.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}}},Mi={};J(Mi,{SaveableVectorStore:()=>Uu,VectorStore:()=>Us,VectorStoreRetriever:()=>Fn});var Fn=class extends Fs{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)}},Us=class extends Xt{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 Fn({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 Fn({...i,searchKwargs:t.searchKwargs}):new Fn({...i})}}},Uu=class extends Us{static load(t,e){throw new Error("Not implemented")}},Ai={};J(Ai,{BaseDocumentLoader:()=>Pi});var Pi=class{},Oi={};J(Oi,{LangSmithLoader:()=>Vu});var Vu=class extends Pi{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 yc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Bu,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 Bu(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var Be=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},Ni=class extends Q{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},zu=class extends Ni{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},Ii={};J(Ii,{BaseDocumentTransformer:()=>Ni,Document:()=>Be,MappingDocumentTransformer:()=>zu});var Vs=class extends Xt{lc_namespace=["langchain_core","example_selectors","base"]},$i=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Hu=class extends $i{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 Wu(t){return t._modelType()==="base_llm"}function Gu(t){return t._modelType()==="base_chat_model"}function vo(t){return t.split(/\n| /).length}var Ku=class Ri extends Vs{examples=[];examplePrompt;getTextLength=vo;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??vo}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 Ri(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Rr(t){return Object.keys(t).sort().map(e=>t[e])}var qu=class ji extends Vs{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=Rr(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Be({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Rr(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=>Rr(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new ji({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Li={};J(Li,{BaseExampleSelector:()=>Vs,BasePromptSelector:()=>$i,ConditionalPromptSelector:()=>Hu,LengthBasedExampleSelector:()=>Ku,SemanticSimilarityExampleSelector:()=>qu,isChatModel:()=>Gu,isLLM:()=>Wu});const as="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Ju=class extends Xt{lc_namespace=["langchain","recordmanagers"]},Di=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Hl;constructor(t){this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new Be({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){const e=this.keyEncoder(t);return Qr(e,as)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return Qr(n,as)}};function Fi(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 Ui(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 Vi(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 Bi=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function Yu(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=Bi(e)?await e.load():e,h=Vi(a??null),d=await n.getTime();let f=0,g=0,p=0,S=0;const C=Fi(o??100,u);for(const y of C){const _=Ui(y.map(x=>Di.fromDocument(x))),v=_.map(x=>h(x));i==="incremental"&&_.forEach((x,A)=>{if(v[A]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const k=await n.exists(_.map(x=>x.uid)),M=[],w=[],b=[],T=new Set;if(_.forEach((x,A)=>{if(k[A])if(c)T.add(x.uid);else{b.push(x.uid);return}M.push(x.uid),w.push(x.toDocument())}),b.length>0&&(await n.update(b,{timeAtLeast:d}),S+=b.length),w.length>0&&(await r.addDocuments(w,{ids:M}),f+=w.length-T.size,p+=T.size),await n.update(_.map(x=>x.uid),{timeAtLeast:d,groupIds:v}),i==="incremental"){v.forEach(A=>{if(!A)throw new Error("Source id cannot be null")});const x=await n.listKeys({before:d,groupIds:v});x.length>0&&(await r.delete({ids:x}),await n.deleteKeys(x),g+=x.length)}}if(i==="full"){let y=await n.listKeys({before:d,limit:l});for(;y.length>0;)await r.delete({ids:y}),await n.deleteKeys(y),g+=y.length,y=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:g,numUpdated:p,numSkipped:S}}var zi={};J(zi,{RecordManager:()=>Ju,UUIDV5_NAMESPACE:()=>as,_HashedDocument:()=>Di,_batch:()=>Fi,_deduplicateInOrder:()=>Ui,_getSourceIdAssigner:()=>Vi,_isBaseDocumentLoader:()=>Bi,index:()=>Yu});var Xu={},Hi={};J(Hi,{BaseDocumentCompressor:()=>Zu});var Zu=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}},kn=class extends Q{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(t){super(t);const{inputVariables:e}=t;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){const e=this.partialVariables??{},n={};for(const[s,o]of Object.entries(e))typeof o=="string"?n[s]=o:n[s]=await o();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},pn=class extends kn{async formatPromptValue(t){const e=await this.format(t);return new Wl(e)}};var Qu=Object.prototype.toString,Qt=Array.isArray||function(e){return Qu.call(e)==="[object Array]"};function Bs(t){return typeof t=="function"}function eh(t){return Qt(t)?"array":typeof t}function jr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _o(t,e){return t!=null&&typeof t=="object"&&e in t}function th(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var nh=RegExp.prototype.test;function rh(t,e){return nh.call(t,e)}var sh=/\S/;function oh(t){return!rh(sh,t)}var ih={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function ah(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return ih[n]})}var lh=/\s*/,ch=/\s+/,So=/\s*=/,uh=/\s*\}/,hh=/#|\^|\/|>|\{|&|=|!/;function dh(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 g(b){if(typeof b=="string"&&(b=b.split(ch,2)),!Qt(b)||b.length!==2)throw new Error("Invalid tags: "+b);h=new RegExp(jr(b[0])+"\\s*"),d=new RegExp("\\s*"+jr(b[1])),f=new RegExp("\\s*"+jr("}"+b[1]))}g(e||ue.tags);for(var p=new Tn(t),S,C,y,_,v,k;!p.eos();){if(S=p.pos,y=p.scanUntil(h),y)for(var M=0,w=y.length;M<w;++M)_=y.charAt(M),oh(_)?(o.push(s.length),l+=_):(a=!0,n=!0,l+=" "),s.push(["text",_,S,S+1]),S+=1,_===`
14
- `&&(u(),l="",c=0,n=!1);if(!p.scan(h))break;if(i=!0,C=p.scan(hh)||"name",p.scan(lh),C==="="?(y=p.scanUntil(So),p.scan(So),p.scanUntil(d)):C==="{"?(y=p.scanUntil(f),p.scan(uh),p.scanUntil(d),C="&"):y=p.scanUntil(d),!p.scan(d))throw new Error("Unclosed tag at "+p.pos);if(C==">"?v=[C,y,S,p.pos,l,c,n]:v=[C,y,S,p.pos],c++,s.push(v),C==="#"||C==="^")r.push(v);else if(C==="/"){if(k=r.pop(),!k)throw new Error('Unopened section "'+y+'" at '+S);if(k[1]!==y)throw new Error('Unclosed section "'+k[1]+'" at '+S)}else C==="name"||C==="{"||C==="&"?a=!0:C==="="&&g(y)}if(u(),k=r.pop(),k)throw new Error('Unclosed section "'+k[1]+'" at '+p.pos);return ph(fh(s))}function fh(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 ph(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 Tn(t){this.string=t,this.tail=t,this.pos=0}Tn.prototype.eos=function(){return this.tail===""};Tn.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};Tn.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 Wt(t,e){this.view=t,this.cache={".":this.view},this.parent=e}Wt.prototype.push=function(e){return new Wt(e,this)};Wt.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])||th(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 Bs(r)&&(r=r.call(this.view)),r};function ie(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}ie.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ie.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||ue.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=dh(e,n),o&&r.set(s,i)),i};ie.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof Wt?n:new Wt(n,void 0);return this.renderTokens(i,a,r,e,s)};ie.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};ie.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(Qt(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(Bs(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}};ie.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||Qt(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};ie.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
12
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function js(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function or(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}let Eu=0;var Ge=class os{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-${++Eu}`}if(yc(e)){const a=Ee(e),l={type:"function",function:{name:r(),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new os(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=Ee(e),i={type:"function",function:s};return new os(o,i,n)}parse(e){const r=new si(this.schema).validate(e);if(!r.valid)throw new gi(this.name,r.errors.map(s=>s.error));return e}},it=class yi{_schemaType;constructor(e){this.schema=e}static fromSchema(e){const n=Ee(e);return new yi(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new si(this.schema).validate(n).valid?n:void 0}catch{}}};function wi(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 Ge||s instanceof it))return t;if(t.every(s=>fe(s)))return t.map(s=>Ge.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!fe(s)))return t.map(s=>Ge.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 Ge||t instanceof it)return[t];const r=vi(n);if(fe(t))return r?[it.fromSchema(t)]:[Ge.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[it.fromSchema(t)]:[Ge.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function xu(t,e){return wi(t,e)}function Mu(t){return it.fromSchema(t)}const Au=["ChatOpenAI","ChatXAI"],vo=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function vi(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return vo.some(r=>n.includes(r))}if(or(t))return vi(t._defaultConfig.model);if(!js(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||Au.includes(e)&&("model"in t&&vo.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Ls(t){let e=0;for(const n of t){let r;typeof n.content=="string"?r=n.content:Array.isArray(n.content)?r=n.content.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join(""):r="",e+=r.length}return Math.ceil(e/4)}function Je(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Cr(t){return typeof t=="function"?t:t.hook}function Pu(t){return new Promise(e=>setTimeout(e,t))}function ge(t){return{name:t.name,stateSchema:t.stateSchema,contextSchema:t.contextSchema,wrapToolCall:t.wrapToolCall,wrapModelCall:t.wrapModelCall,beforeAgent:t.beforeAgent,beforeModel:t.beforeModel,afterModel:t.afterModel,afterAgent:t.afterAgent,tools:t.tools??[]}}function bi(t){return yu({clockseq:t})}function vt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Qr(t,new Uint8Array(n))}const Ou="__error__",Dn="__scheduled__",Nu="__interrupt__",Iu="__resume__";var bo="[...]",$u="[Circular]",ir=[],bt=[];function Ru(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function ju(t,e,n,r){typeof r>"u"&&(r=Ru()),is(t,"",0,[],void 0,0,r);var s;try{bt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,Lu(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;ir.length!==0;){var o=ir.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function $r(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),ir.push([r,n,e,s])):bt.push([e,n,t]):(r[n]=t,ir.push([r,n,e]))}function is(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){$r($u,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){$r(bo,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){$r(bo,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)is(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];is(t[c],c,a,r,t,o,i)}}r.pop()}}function Lu(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(bt.length>0)for(var r=0;r<bt.length;r++){var s=bt[r];if(s[1]===e&&s[0]===n){n=s[2],bt.splice(r,1);break}}return t.call(this,e,n)}}const Du=[];var Fu={},_i={};J(_i,{BaseChatMessageHistory:()=>Si,BaseListChatMessageHistory:()=>Ds,InMemoryChatMessageHistory:()=>Uu});var Si=class extends Xt{async addMessages(t){for(const e of t)await this.addMessage(e)}},Ds=class extends Xt{addUserMessage(t){return this.addMessage(new pe(t))}addAIMessage(t){return this.addMessage(new O(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Uu=class extends Ds{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=[]}},Vu={},Ci={};J(Ci,{BaseMemory:()=>Bu,getInputValue:()=>zu,getOutputValue:()=>Wu,getPromptInputKey:()=>Hu});var Bu=class{};const ki=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},zu=(t,e)=>{const n=ki(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},Wu=(t,e)=>{const n=ki(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 Hu(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 Ti={};J(Ti,{BaseStore:()=>Ei,InMemoryStore:()=>xi});var Ei=class extends Xt{},xi=class extends Ei{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)}},Mi={};J(Mi,{BaseRetriever:()=>Fs});var Fs=class extends Q{callbacks;tags;metadata;verbose;constructor(t){super(t),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,e){throw new Error("Not implemented!")}async invoke(t,e){const n=nn(wc(e)),s=await(await vc.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}}},Ai={};J(Ai,{SaveableVectorStore:()=>Gu,VectorStore:()=>Us,VectorStoreRetriever:()=>Fn});var Fn=class extends Fs{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)}},Us=class extends Xt{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 Fn({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 Fn({...i,searchKwargs:t.searchKwargs}):new Fn({...i})}}},Gu=class extends Us{static load(t,e){throw new Error("Not implemented")}},Pi={};J(Pi,{BaseDocumentLoader:()=>Oi});var Oi=class{},Ni={};J(Ni,{LangSmithLoader:()=>Ku});var Ku=class extends Oi{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 bc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??qu,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 qu(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var Be=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},Ii=class extends Q{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Ju=class extends Ii{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},$i={};J($i,{BaseDocumentTransformer:()=>Ii,Document:()=>Be,MappingDocumentTransformer:()=>Ju});var Vs=class extends Xt{lc_namespace=["langchain_core","example_selectors","base"]},Ri=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Yu=class extends Ri{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 Xu(t){return t._modelType()==="base_llm"}function Zu(t){return t._modelType()==="base_chat_model"}function _o(t){return t.split(/\n| /).length}var Qu=class ji extends Vs{examples=[];examplePrompt;getTextLength=_o;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??_o}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 ji(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Rr(t){return Object.keys(t).sort().map(e=>t[e])}var eh=class Li extends Vs{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=Rr(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Be({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Rr(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=>Rr(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new Li({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Di={};J(Di,{BaseExampleSelector:()=>Vs,BasePromptSelector:()=>Ri,ConditionalPromptSelector:()=>Yu,LengthBasedExampleSelector:()=>Qu,SemanticSimilarityExampleSelector:()=>eh,isChatModel:()=>Zu,isLLM:()=>Xu});const as="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var th=class extends Xt{lc_namespace=["langchain","recordmanagers"]},Fi=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Kl;constructor(t){this.uid=t.uid,this.pageContent=t.pageContent,this.metadata=t.metadata}makeDefaultKeyEncoder(t){this.keyEncoder=t}calculateHashes(){const t=["hash_","content_hash","metadata_hash"];for(const n of t)if(n in this.metadata)throw new Error(`Metadata cannot contain key ${n} as it is reserved for internal use. Restricted keys: [${t.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const n=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=n}catch(n){throw new Error(`Failed to hash metadata: ${n}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new Be({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(t,e){const n=new this({pageContent:t.pageContent,metadata:t.metadata,uid:e||t.uid});return n.calculateHashes(),n}_hashStringToUUID(t){const e=this.keyEncoder(t);return Qr(e,as)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return Qr(n,as)}};function Ui(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 Vi(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 Bi(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 zi=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function nh(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=zi(e)?await e.load():e,h=Bi(a??null),d=await n.getTime();let f=0,g=0,p=0,S=0;const C=Ui(o??100,u);for(const y of C){const _=Vi(y.map(x=>Fi.fromDocument(x))),b=_.map(x=>h(x));i==="incremental"&&_.forEach((x,A)=>{if(b[A]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const k=await n.exists(_.map(x=>x.uid)),M=[],w=[],v=[],T=new Set;if(_.forEach((x,A)=>{if(k[A])if(c)T.add(x.uid);else{v.push(x.uid);return}M.push(x.uid),w.push(x.toDocument())}),v.length>0&&(await n.update(v,{timeAtLeast:d}),S+=v.length),w.length>0&&(await r.addDocuments(w,{ids:M}),f+=w.length-T.size,p+=T.size),await n.update(_.map(x=>x.uid),{timeAtLeast:d,groupIds:b}),i==="incremental"){b.forEach(A=>{if(!A)throw new Error("Source id cannot be null")});const x=await n.listKeys({before:d,groupIds:b});x.length>0&&(await r.delete({ids:x}),await n.deleteKeys(x),g+=x.length)}}if(i==="full"){let y=await n.listKeys({before:d,limit:l});for(;y.length>0;)await r.delete({ids:y}),await n.deleteKeys(y),g+=y.length,y=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:g,numUpdated:p,numSkipped:S}}var Wi={};J(Wi,{RecordManager:()=>th,UUIDV5_NAMESPACE:()=>as,_HashedDocument:()=>Fi,_batch:()=>Ui,_deduplicateInOrder:()=>Vi,_getSourceIdAssigner:()=>Bi,_isBaseDocumentLoader:()=>zi,index:()=>nh});var rh={},Hi={};J(Hi,{BaseDocumentCompressor:()=>sh});var sh=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}},kn=class extends Q{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(t){super(t);const{inputVariables:e}=t;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){const e=this.partialVariables??{},n={};for(const[s,o]of Object.entries(e))typeof o=="string"?n[s]=o:n[s]=await o();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},pn=class extends kn{async formatPromptValue(t){const e=await this.format(t);return new ql(e)}};var oh=Object.prototype.toString,Qt=Array.isArray||function(e){return oh.call(e)==="[object Array]"};function Bs(t){return typeof t=="function"}function ih(t){return Qt(t)?"array":typeof t}function jr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function So(t,e){return t!=null&&typeof t=="object"&&e in t}function ah(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var lh=RegExp.prototype.test;function ch(t,e){return lh.call(t,e)}var uh=/\S/;function hh(t){return!ch(uh,t)}var dh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function fh(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return dh[n]})}var ph=/\s*/,mh=/\s+/,Co=/\s*=/,gh=/\s*\}/,yh=/#|\^|\/|>|\{|&|=|!/;function wh(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 g(v){if(typeof v=="string"&&(v=v.split(mh,2)),!Qt(v)||v.length!==2)throw new Error("Invalid tags: "+v);h=new RegExp(jr(v[0])+"\\s*"),d=new RegExp("\\s*"+jr(v[1])),f=new RegExp("\\s*"+jr("}"+v[1]))}g(e||ue.tags);for(var p=new Tn(t),S,C,y,_,b,k;!p.eos();){if(S=p.pos,y=p.scanUntil(h),y)for(var M=0,w=y.length;M<w;++M)_=y.charAt(M),hh(_)?(o.push(s.length),l+=_):(a=!0,n=!0,l+=" "),s.push(["text",_,S,S+1]),S+=1,_===`
14
+ `&&(u(),l="",c=0,n=!1);if(!p.scan(h))break;if(i=!0,C=p.scan(yh)||"name",p.scan(ph),C==="="?(y=p.scanUntil(Co),p.scan(Co),p.scanUntil(d)):C==="{"?(y=p.scanUntil(f),p.scan(gh),p.scanUntil(d),C="&"):y=p.scanUntil(d),!p.scan(d))throw new Error("Unclosed tag at "+p.pos);if(C==">"?b=[C,y,S,p.pos,l,c,n]:b=[C,y,S,p.pos],c++,s.push(b),C==="#"||C==="^")r.push(b);else if(C==="/"){if(k=r.pop(),!k)throw new Error('Unopened section "'+y+'" at '+S);if(k[1]!==y)throw new Error('Unclosed section "'+k[1]+'" at '+S)}else C==="name"||C==="{"||C==="&"?a=!0:C==="="&&g(y)}if(u(),k=r.pop(),k)throw new Error('Unclosed section "'+k[1]+'" at '+p.pos);return bh(vh(s))}function vh(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 bh(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 Tn(t){this.string=t,this.tail=t,this.pos=0}Tn.prototype.eos=function(){return this.tail===""};Tn.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};Tn.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 Ht(t,e){this.view=t,this.cache={".":this.view},this.parent=e}Ht.prototype.push=function(e){return new Ht(e,this)};Ht.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=So(o,i[a])||ah(o,i[a])),o=o[i[a++]];else o=s.view[e],l=So(s.view,e);if(l){r=o;break}s=s.parent}n[e]=r}return Bs(r)&&(r=r.call(this.view)),r};function ie(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}ie.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ie.prototype.parse=function(e,n){var r=this.templateCache,s=e+":"+(n||ue.tags).join(":"),o=typeof r<"u",i=o?r.get(s):void 0;return i==null&&(i=wh(e,n),o&&r.set(s,i)),i};ie.prototype.render=function(e,n,r,s){var o=this.getConfigTags(s),i=this.parse(e,o),a=n instanceof Ht?n:new Ht(n,void 0);return this.renderTokens(i,a,r,e,s)};ie.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};ie.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(Qt(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(Bs(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}};ie.prototype.renderInverted=function(e,n,r,s,o){var i=n.lookup(e[1]);if(!i||Qt(i)&&i.length===0)return this.renderTokens(e[4],n,r,s,o)};ie.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),o=e.split(`
15
15
  `),i=0;i<o.length;i++)o[i].length&&(i>0||!r)&&(o[i]=s+o[i]);return o.join(`
16
- `)};ie.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=Bs(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)}}};ie.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ie.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||ue.escape,o=n.lookup(e[1]);if(o!=null)return typeof o=="number"&&s===ue.escape?String(o):s(o)};ie.prototype.rawValue=function(e){return e[1]};ie.prototype.getConfigTags=function(e){return Qt(e)?e:e&&typeof e=="object"?e.tags:void 0};ie.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!Qt(e))return e.escape};var ue={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){mn.templateCache=t},get templateCache(){return mn.templateCache}},mn=new ie;ue.clearCache=function(){return mn.clearCache()};ue.parse=function(e,n){return mn.parse(e,n)};ue.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+eh(e)+'" was given as the first argument for mustache#render(template, view, partials)');return mn.render(e,n,r,s)};ue.escape=ah;ue.Scanner=Tn;ue.Context=Wt;ue.Writer=ie;function Wi(){ue.escape=t=>t}const gn=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},Gi=(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=Gi(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},ar=t=>{Wi();const e=ue.parse(t);return Gi(e)},Ki=(t,e)=>gn(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},""),qi=(t,e)=>(Wi(),ue.render(t,e)),lr={"f-string":Ki,mustache:qi},Ji={"f-string":gn,mustache:ar},xe=(t,e,n)=>{try{return lr[e](t,n)}catch(r){throw si(r,"INVALID_PROMPT_INPUT")}},cr=(t,e)=>Ji[e](t),En=(t,e,n)=>{if(!(e in lr)){const r=Object.keys(lr);throw new Error(`Invalid template format. Got \`${e}\`;
16
+ `)};ie.prototype.renderPartial=function(e,n,r,s){if(r){var o=this.getConfigTags(s),i=Bs(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)}}};ie.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ie.prototype.escapedValue=function(e,n,r){var s=this.getConfigEscape(r)||ue.escape,o=n.lookup(e[1]);if(o!=null)return typeof o=="number"&&s===ue.escape?String(o):s(o)};ie.prototype.rawValue=function(e){return e[1]};ie.prototype.getConfigTags=function(e){return Qt(e)?e:e&&typeof e=="object"?e.tags:void 0};ie.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!Qt(e))return e.escape};var ue={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){mn.templateCache=t},get templateCache(){return mn.templateCache}},mn=new ie;ue.clearCache=function(){return mn.clearCache()};ue.parse=function(e,n){return mn.parse(e,n)};ue.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+ih(e)+'" was given as the first argument for mustache#render(template, view, partials)');return mn.render(e,n,r,s)};ue.escape=fh;ue.Scanner=Tn;ue.Context=Ht;ue.Writer=ie;function Gi(){ue.escape=t=>t}const gn=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},Ki=(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=Ki(r[4],s);n.push(...o)}}else n.push({type:"literal",text:r[1]});return n},ar=t=>{Gi();const e=ue.parse(t);return Ki(e)},qi=(t,e)=>gn(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},""),Ji=(t,e)=>(Gi(),ue.render(t,e)),lr={"f-string":qi,mustache:Ji},Yi={"f-string":gn,mustache:ar},xe=(t,e,n)=>{try{return lr[e](t,n)}catch(r){throw oi(r,"INVALID_PROMPT_INPUT")}},cr=(t,e)=>Yi[e](t),En=(t,e,n)=>{if(!(e in lr)){const r=Object.keys(lr);throw new Error(`Invalid template format. Got \`${e}\`;
17
17
  should be one of ${r}`)}try{const r=n.reduce((s,o)=>(s[o]="foo",s),{});Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")xe(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")xe(s.image_url,e,r);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){const o=s.image_url.url;xe(o,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):xe(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Ze=class rn extends pn{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))),En(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return xe(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
18
18
 
19
- `,o=""){const i=[o,...e,n].join(s);return new rn({inputVariables:r,template:i})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},o=new Set;return cr(e,r).forEach(i=>{i.type==="variable"&&o.add(i.name)}),new rn({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 rn(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 rn({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},Un=class Yi extends kn{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))),En([{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 Yi(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=xe(a,this.templateFormat,e):n[i]=a;const r=e.url||n.url,s=e.detail||n.detail;if(!r)throw new Error("Must provide either an image URL.");if(typeof r!="string")throw new Error("url must be a string.");const o={url:r};return s&&(o.detail=s),o}async formatPromptValue(e){const n=await this.format(e);return new Gl(n)}},ls=class extends Q{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(t){const e=t.templateFormat??"f-string",n=cs(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return us(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function cs(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")cr(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?cr(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...cs(s,e));else typeof r=="object"&&r!==null&&n.push(...cs(r,e));return Array.from(new Set(n))}function us(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=xe(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(xe(a,n,e)):typeof a=="object"&&i.push(us(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=us(o,e,n):r[s]=o;return r}var kr=class extends Q{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},hs=class extends kr{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(dn):n=[dn(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 rn({inputVariables:r,template:i})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},o=new Set;return cr(e,r).forEach(i=>{i.type==="variable"&&o.add(i.name)}),new rn({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 rn(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 rn({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},Un=class Xi extends kn{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))),En([{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 Xi(s)}async format(e){const n={};for(const[i,a]of Object.entries(this.template))typeof a=="string"?n[i]=xe(a,this.templateFormat,e):n[i]=a;const r=e.url||n.url,s=e.detail||n.detail;if(!r)throw new Error("Must provide either an image URL.");if(typeof r!="string")throw new Error("url must be a string.");const o={url:r};return s&&(o.detail=s),o}async formatPromptValue(e){const n=await this.format(e);return new Jl(n)}},ls=class extends Q{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(t){const e=t.templateFormat??"f-string",n=cs(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return us(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function cs(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")cr(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?cr(s,e).forEach(o=>{o.type==="variable"&&n.push(o.name)}):typeof s=="object"&&n.push(...cs(s,e));else typeof r=="object"&&r!==null&&n.push(...cs(r,e));return Array.from(new Set(n))}function us(t,e,n){const r={};for(const[s,o]of Object.entries(t))if(typeof o=="string")r[s]=xe(o,n,e);else if(Array.isArray(o)){const i=[];for(const a of o)typeof a=="string"?i.push(xe(a,n,e)):typeof a=="object"&&i.push(us(a,e,n));r[s]=i}else typeof o=="object"&&o!==null?r[s]=us(o,e,n):r[s]=o;return r}var kr=class extends Q{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},hs=class extends kr{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(dn):n=[dn(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}},Xi=class extends kr{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 kn{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Kl(e)}},Zi=class extends Xi{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 oi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Ze.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function mh(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function gh(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 Hs=class extends kr{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(t,e){if("prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(r=>{"inputVariables"in r&&(n=n.concat(r.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=e??this.additionalOptions}createMessage(t){const e=this.constructor;if(e._messageClass()){const n=e._messageClass();return new n({content:t})}else if(e.chatMessageClass){const n=e.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(t,e){if(typeof t=="string")return new this(Ze.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(Ze.fromTemplate(r,e));else if(r!==null)if(mh(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(Ze.fromTemplate(s,o))}else if(gh(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=ar(s):a=gn(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}},Zi=class extends kr{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 kn{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Yl(e)}},Qi=class extends Zi{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 ii(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Ze.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function _h(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Sh(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 Ws=class extends kr{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(t,e){if("prompt"in t||(t={prompt:t}),super(t),this.prompt=t.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(r=>{"inputVariables"in r&&(n=n.concat(r.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=e??this.additionalOptions}createMessage(t){const e=this.constructor;if(e._messageClass()){const n=e._messageClass();return new n({content:t})}else if(e.chatMessageClass){const n=e.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(t,e){if(typeof t=="string")return new this(Ze.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(Ze.fromTemplate(r,e));else if(r!==null)if(_h(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const o={...e,additionalContentFields:r};n.push(Ze.fromTemplate(s,o))}else if(Sh(r)){let s=r.image_url??"",o,i=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=ar(s):a=gn(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 Un({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=ar(s.url):a=gn(s.url),i=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else i=[];o=new Un({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 ls({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof pn){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 pn){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 Un){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 ls){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)]}},Ws=class extends Hs{static _messageClass(){return pe}static lc_name(){return"HumanMessagePromptTemplate"}},Qi=class extends Hs{static _messageClass(){return O}static lc_name(){return"AIMessagePromptTemplate"}},ea=class extends Hs{static _messageClass(){return _e}static lc_name(){return"SystemMessagePromptTemplate"}};function yh(t){return typeof t.formatMessages=="function"}function wh(t,e){if(yh(t)||je(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if(e?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){const o=s.slice(2,-2);return new hs({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new hs({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=dn(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 Ws.fromTemplate(r,e);if(n._getType()==="ai")return Qi.fromTemplate(r,e);if(n._getType()==="system")return ea.fromTemplate(r,e);if(oi.isInstance(n))return Zi.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function bh(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var Gs=class Vn 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 an))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 Ze.fromTemplate(o,{templateFormat:this.templateFormat}).format(n);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=a:s.image_url=a,s}));return e.content=r,e}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=[];for(const s of this.promptMessages)if(s instanceof an)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)&&!(bh(s)&&s.optional))throw si(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 Vn(s)}static fromTemplate(e,n){const r=Ze.fromTemplate(e,n),s=new Ws({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof Vn?a.promptMessages:[wh(a,n)]),[]),s=e.reduce((i,a)=>a instanceof Vn?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof an))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})}},vh=class ds extends pn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
23
+ From: ${s}`);i=[l[0]]}else i=[];s={url:s},o=new Un({template:s,inputVariables:i,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=ar(s.url):a=gn(s.url),i=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else i=[];o=new Un({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 ls({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof pn){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 pn){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 Un){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 ls){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)]}},Hs=class extends Ws{static _messageClass(){return pe}static lc_name(){return"HumanMessagePromptTemplate"}},ea=class extends Ws{static _messageClass(){return O}static lc_name(){return"AIMessagePromptTemplate"}},ta=class extends Ws{static _messageClass(){return _e}static lc_name(){return"SystemMessagePromptTemplate"}};function Ch(t){return typeof t.formatMessages=="function"}function kh(t,e){if(Ch(t)||je(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const s=t[1];if(e?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}"){const o=s.slice(2,-2);return new hs({variableName:o,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const o=s.slice(1,-1);return new hs({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=dn(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 Hs.fromTemplate(r,e);if(n._getType()==="ai")return ea.fromTemplate(r,e);if(n._getType()==="system")return ta.fromTemplate(r,e);if(ii.isInstance(n))return Qi.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function Th(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var Gs=class Vn 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 an))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 Ze.fromTemplate(o,{templateFormat:this.templateFormat}).format(n);return typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url?s.image_url.url=a:s.image_url=a,s}));return e.content=r,e}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=[];for(const s of this.promptMessages)if(s instanceof an)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)&&!(Th(s)&&s.optional))throw oi(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 Vn(s)}static fromTemplate(e,n){const r=Ze.fromTemplate(e,n),s=new Hs({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((i,a)=>i.concat(a instanceof Vn?a.promptMessages:[kh(a,n)]),[]),s=e.reduce((i,a)=>a instanceof Vn?Object.assign(i,a.partialVariables):i,Object.create(null)),o=new Set;for(const i of r)if(!(i instanceof an))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})}},Eh=class ds extends pn{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))),En(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 ds(s)}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),s=await Promise.all(r.map(i=>this.examplePrompt.format(i))),o=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return xe(o,this.templateFormat,n)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:n}=e;if(!n)throw new Error("Missing example prompt");const r=await Ze.deserialize(n);let s;if(Array.isArray(e.examples))s=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new ds({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},_h=class ta 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))),En(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 ds(s)}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),s=await Promise.all(r.map(i=>this.examplePrompt.format(i))),o=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return xe(o,this.templateFormat,n)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:n}=e;if(!n)throw new Error("Missing example prompt");const r=await Ze.deserialize(n);let s;if(Array.isArray(e.examples))s=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new ds({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},xh=class na extends zs{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))),En(this.prefix+this.suffix,this.templateFormat,n)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=await this.getExamples(n);r=r.map(o=>{const i={};return this.examplePrompt.inputVariables.forEach(a=>{i[a]=o[a]}),i});const s=[];for(const o of r){const i=await this.examplePrompt.formatMessages(o);s.push(...i)}return s}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),o=(await Promise.all(r.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return xe(i,this.templateFormat,n)}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new ta(s)}},Sh=class Bn extends kn{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=Bn.extractRequiredInputValues(n,s.inputVariables);s instanceof Gs?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return Bn.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 Bn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function Co(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function Ch(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 kh=class na extends Gs{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(Co(e))return super.pipe(e.withStructuredOutput(this.schema));if(Ch(e)&&Co(e.bound))return super.pipe(new Oe({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,n,r){return na.fromMessages(e,{schema:n,method:r})}},ra={};J(ra,{AIMessagePromptTemplate:()=>Qi,BaseChatPromptTemplate:()=>zs,BaseMessagePromptTemplate:()=>kr,BaseMessageStringPromptTemplate:()=>Xi,BasePromptTemplate:()=>kn,BaseStringPromptTemplate:()=>pn,ChatMessagePromptTemplate:()=>Zi,ChatPromptTemplate:()=>Gs,DEFAULT_FORMATTER_MAPPING:()=>lr,DEFAULT_PARSER_MAPPING:()=>Ji,DictPromptTemplate:()=>ls,FewShotChatMessagePromptTemplate:()=>_h,FewShotPromptTemplate:()=>vh,HumanMessagePromptTemplate:()=>Ws,ImagePromptTemplate:()=>Un,MessagesPlaceholder:()=>hs,PipelinePromptTemplate:()=>Sh,PromptTemplate:()=>Ze,StructuredPrompt:()=>kh,SystemMessagePromptTemplate:()=>ea,checkValidTemplate:()=>En,interpolateFString:()=>Ki,interpolateMustache:()=>qi,parseFString:()=>gn,parseMustache:()=>ar,parseTemplate:()=>cr,renderTemplate:()=>xe});var Th={},sa={};J(sa,{RunCollectorCallbackHandler:()=>Eh});var Eh=class extends Os{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)}},oa=class extends ni{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 ql{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?Jl(t??{},e):void 0}async parsePartialResult(t){const e=t[0];if(!e.message)return;const{message:n}=e,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?uo(r.arguments):{...r,arguments:uo(r.arguments)}}async parseResult(t){const e=await this.outputParser.parseResult(t);if(!e)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(t)}`);return this.parse(e)}async parse(t){const e=JSON.parse(t);return this.argsOnly||(e.arguments=JSON.parse(e.arguments)),e}getFormatInstructions(){return""}},xh=class extends ni{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={};J(aa,{JsonKeyOutputFunctionsParser:()=>xh,JsonOutputFunctionsParser:()=>ia,OutputFunctionsParser:()=>oa});const Ye={and:"and",or:"or",not:"not"},R={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var la=class{},Ks=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")}},qs=class extends Ks{},Mh=class extends qs{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},Ah=class extends qs{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},Ph=class extends Ks{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function ca(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Te(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:ca(t)&&Object.keys(t).length===0:!0}function ua(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 ha(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 da(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function fa(t){return typeof t=="boolean"}function Js(t){let e;if(da(t))e=t;else if(ua(t))e=parseInt(t,10);else if(ha(t))e=parseFloat(t);else if(fa(t))e=!!t;else throw new Error("Unsupported value type");return e}var Ys=class extends la{},Oh=class extends Ys{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Ye.and,Ye.or],this.allowedComparators=t?.allowedComparators??[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte]}formatFunction(t){if(t in R){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(t)===-1)throw new Error(`Comparator ${t} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(t in Ye){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(t)===-1)throw new Error(`Operator ${t} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${t}`}visitOperation(t){const e=t.args?.map(n=>n.accept(this));return{[this.formatFunction(t.operator)]:e}}visitComparison(t){return{[t.attribute]:{[this.formatFunction(t.comparator)]:Js(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Te(t)&&Te(e))){if(Te(t)||n==="replace")return Te(e)?void 0:e;if(Te(e))return r?t:n==="and"?void 0:t;if(n==="and")return{$and:[t,e]};if(n==="or")return{$or:[t,e]};throw new Error("Unknown merge type")}}},Nh=class extends Ys{allowedOperators=[Ye.and,Ye.or];allowedComparators=[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"number":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"boolean":return[R.eq,R.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case R.eq:return(e,n)=>e===n;case R.ne:return(e,n)=>e!==n;case R.gt:return(e,n)=>e>n;case R.gte:return(e,n)=>e>=n;case R.lt:return(e,n)=>e<n;case R.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case Ye.and:return(e,n)=>e&&n;case Ye.or:return(e,n)=>e||n;default:throw new Error("Unknown operator")}}visitOperation(t){const{operator:e,args:n}=t;if(this.allowedOperators.includes(e)){const r=this.getOperatorFunction(e);return s=>n?n.reduce((o,i)=>{const a=i.accept(this);if(typeof a=="function")return r(o,a(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(t){const{comparator:e,attribute:n,value:r}=t,s=[R.ne];if(this.allowedComparators.includes(e)){if(!this.getAllowedComparatorsForType(typeof r).includes(e))throw new Error(`'${e}' comparator not allowed to be used with ${typeof r}`);const o=this.getComparatorFunction(e);return i=>{const a=i.metadata[n];return a===void 0?!!s.includes(e):o(a,Js(r))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(t){if(!t.filter)return{};const e=t.filter?.accept(this);if(typeof e!="function")throw new Error("Structured query filter is not a function");return{filter:e}}mergeFilters(t,e,n="and"){if(!(Te(t)&&Te(e))){if(Te(t)||n==="replace")return Te(e)?void 0:e;if(Te(e))return n==="and"?void 0:t;if(n==="and")return r=>t(r)&&e(r);if(n==="or")return r=>t(r)||e(r);throw new Error("Unknown merge type")}}},pa={};J(pa,{BaseTranslator:()=>Ys,BasicTranslator:()=>Oh,Comparators:()=>R,Comparison:()=>Mh,Expression:()=>Ks,FilterDirective:()=>qs,FunctionalTranslator:()=>Nh,Operation:()=>Ah,Operators:()=>Ye,StructuredQuery:()=>Ph,Visitor:()=>la,castValue:()=>Js,isBoolean:()=>fa,isFilterEmpty:()=>Te,isFloat:()=>ha,isInt:()=>ua,isObject:()=>ca,isString:()=>da});var Ih=class extends Cn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new O(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(`
30
- `);return await n?.handleLLMNewToken(r),{generations:[{message:new O(r),text:r}],llmOutput:{}}}},$h=class ma extends Cn{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:Ee(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Ee(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Ee(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Ee(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new ma({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 O({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 es({message:new Vt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new O(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 es({message:new Vt({content:i}),text:i});yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},Rh=class ga extends Cn{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 O(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);yield this._createResponseChunk(a,l?this.generationInfo:void 0),r?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,n){return new es({message:new Vt({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:Ee(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Ee(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Ee(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Ee(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new ga({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 Bt.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")})}},jh=class extends li{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})}},Lh=class extends li{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},Dh=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}},Fh=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)}},Uh=class extends _i{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async addUserMessage(t){this.messages.push(new pe(t))}async addAIMessage(t){this.messages.push(new O(t))}async clear(){this.messages=[]}},Vh=class extends Ds{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},Bh=class extends Os{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},zh=class extends Yl{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Hh=class extends Fs{lc_namespace=["test","fake"];output=[new Be({pageContent:"foo"}),new Be({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Wh=class extends Q{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},Gh=class extends _r{name;description;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.schema=t.schema}async _call(t,e){return JSON.stringify(t)}},Kh=class extends Os{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(t=>{this.runPromiseResolver=t})}async persistRun(t){this.runPromiseResolver(t)}async extract(){return this.runPromise}};function ya(t,e){let n=0,r=0,s=0;for(let o=0;o<t.length;o++)n+=t[o]*e[o],r+=t[o]*t[o],s+=e[o]*e[o];return n/(Math.sqrt(r)*Math.sqrt(s))}var qh=class wa extends Us{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??ya}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 Be({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 Be({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 Be({pageContent:e[i],metadata:a});o.push(l)}return wa.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={};J(ba,{FakeChatMessageHistory:()=>Uh,FakeChatModel:()=>Ih,FakeEmbeddings:()=>Lh,FakeLLM:()=>Dh,FakeListChatMessageHistory:()=>Vh,FakeListChatModel:()=>Rh,FakeRetriever:()=>Hh,FakeRunnable:()=>Wh,FakeSplitIntoListParser:()=>zh,FakeStreamingChatModel:()=>$h,FakeStreamingLLM:()=>Fh,FakeTool:()=>Gh,FakeTracer:()=>Bh,FakeVectorStore:()=>qh,SingleRunExtractor:()=>Kh,SyntheticEmbeddings:()=>jh});var va={};J(va,{EventStreamContentType:()=>Jh,convertEventStreamToIterableReadableDataStream:()=>Xh,getBytes:()=>_a,getLines:()=>Sa,getMessages:()=>Ca});const Jh="text/event-stream";async function _a(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(`
31
- `))}}var _t=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})(_t||{});function Sa(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=Yh(e,i);const l=e.length;let c=0;for(;n<l;){s&&(e[n]===_t.NewLine&&(c=++n),s=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case _t.Colon:r===-1&&(r=n-c);break;case _t.CarriageReturn:s=!0;case _t.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 Ca(t,e,n){let r=Lr();const s=new TextDecoder;return function(i,a,l){if(l){Zh(r)||(t?.(r),r=Lr());return}if(i.length===0)t?.(r),r=Lr();else if(a>0){const c=s.decode(i.subarray(0,a)),u=a+(i[a+1]===_t.Space?2:1),h=s.decode(i.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
32
- `+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 Yh(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function Lr(){return{data:"",event:"",id:"",retry:void 0}}function Xh(t,e){const n=new ReadableStream({async start(r){const s=Ca(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 _a(t,Sa((i,a,l)=>{s(i,a,l),l&&r.close()}))}});return hn.fromReadableStream(n)}function Zh(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Qh={};function ed(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function td(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 nd(t,e){return Math.sqrt(td(t,e))}var ka={};J(ka,{cosineSimilarity:()=>fs,euclideanDistance:()=>od,innerProduct:()=>sd,matrixFunc:()=>Tr,maximalMarginalRelevance:()=>id,normalize:()=>rd});function Tr(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 rd(t,e=!1){const n=ad(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function fs(t,e){return Tr(t,e,ya)}function sd(t,e){return Tr(t,e,ed)}function od(t,e){return Tr(t,e,nd)}function id(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=fs(s,e)[0],i=Ta(o).maxIndex,a=[e[i]],l=[i];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const h=fs(e,a);o.forEach((d,f)=>{if(l.includes(f))return;const g=Math.max(...h[f]),p=n*d-(1-n)*g;p>c&&(c=p,u=f)}),a.push(e[u]),l.push(u)}return l}function Ta(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 ad(t){return t.reduce((e,n)=>Math.max(e,Ta(n).maxValue),0)}var Ea={};J(Ea,{agents:()=>Iu,caches:()=>ac,callbacks__base:()=>$c,callbacks__manager:()=>Ic,callbacks__promises:()=>Nc,chat_history:()=>vi,document_loaders__base:()=>Ai,document_loaders__langsmith:()=>Oi,documents:()=>Ii,embeddings:()=>nu,example_selectors:()=>Li,index:()=>Ru,indexing:()=>zi,language_models__base:()=>ic,language_models__chat_models:()=>oc,language_models__llms:()=>su,language_models__profile:()=>Xu,load__serializable:()=>Oc,memory:()=>Si,messages:()=>Pc,messages__tool:()=>Ac,output_parsers:()=>sc,output_parsers__openai_functions:()=>aa,output_parsers__openai_tools:()=>ru,outputs:()=>Mc,prompt_values:()=>rc,prompts:()=>ra,retrievers:()=>xi,retrievers__document_compressors:()=>Hi,runnables:()=>nc,runnables__graph:()=>xc,singletons:()=>Ec,stores:()=>ki,structured_query:()=>pa,tools:()=>Vl,tracers__base:()=>Tc,tracers__console:()=>kc,tracers__log_stream:()=>Cc,tracers__run_collector:()=>sa,tracers__tracer_langchain:()=>Sc,types__stream:()=>Th,utils__async_caller:()=>_c,utils__chunk_array:()=>tu,utils__env:()=>vc,utils__event_source_parse:()=>va,utils__format:()=>Qh,utils__function_calling:()=>tc,utils__hash:()=>ec,utils__json_patch:()=>Ql,utils__json_schema:()=>bc,utils__math:()=>ka,utils__stream:()=>wc,utils__testing:()=>ba,utils__tiktoken:()=>Zl,utils__types:()=>Xl,vectorstores:()=>Mi});function ld(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 zn(t){const{optionalImportsMap:e={},optionalImportEntrypoints:n=[],importMap:r={},secretsMap:s={},path:o=["$"]}=this,i=o.join(".");if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="secret"){const a=t,[l]=a.id;if(l in s)return s[l];{const c=Rc(l);if(c)return c;throw new Error(`Missing key "${l}" for ${i} in load(secretsMap={})`)}}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="not_implemented"){const l=JSON.stringify(t);throw new Error(`Trying to load an object that doesn't implement serialization: ${i} -> ${l}`)}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&"kwargs"in t&&t.lc===1){const a=t,l=JSON.stringify(a),[c,...u]=a.id.slice().reverse(),h=u.reverse(),d={langchain_core:Ea,langchain:r};let f=null;const g=[h.join("/")];h[0]==="langchain_community"&&g.push(["langchain",...h.slice(1)].join("/"));const p=g.find(y=>y in e);if(Nu.concat(n).includes(h.join("/"))||p)if(p!==void 0)f=await e[p];else throw new Error(`Missing key "${h.join("/")}" for ${i} in load(optionalImportsMap={})`);else{let y;if(h[0]==="langchain"||h[0]==="langchain_core")y=d[h[0]],h.shift();else throw new Error(`Invalid namespace: ${i} -> ${l}`);if(h.length===0)throw new Error(`Invalid namespace: ${i} -> ${l}`);let _;do{if(_=h.join("__"),_ in y)break;h.pop()}while(h.length>0);_ in y&&(f=y[_])}if(typeof f!="object"||f===null)throw new Error(`Invalid namespace: ${i} -> ${l}`);const S=f[c]??Object.values(f).find(y=>typeof y=="function"&&jc(y)===c);if(typeof S!="function")throw new Error(`Invalid identifer: ${i} -> ${l}`);const C=await zn.call({...this,path:[...o,"kwargs"]},a.kwargs);if(a.type==="constructor"){const y=new S(Lc(C,Dc,ld(S)));return Object.defineProperty(y.constructor,"name",{value:c}),y}else throw new Error(`Invalid type: ${i} -> ${l}`)}else if(typeof t=="object"&&t!==null)return Array.isArray(t)?Promise.all(t.map((a,l)=>zn.call({...this,path:[...o,`${l}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,l])=>[a,await zn.call({...this,path:[...o,a]},l)])));return t}async function cd(t,e){const n=JSON.parse(t);return zn.call({...e},n)}function ud(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function ps(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>ps(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await ps(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(ud(e))return cd(JSON.stringify(e));return e}}return t}function Dr(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function hd(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Dr(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Dr(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Dr(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var dd=class{_dumps(t){return new TextEncoder().encode(Pu(t,(n,r)=>hd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return ps(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 xa(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]=xa(t[n]));return e}function Ma(){return{v:4,id:bi(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function ur(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:xa(t.versions_seen)}}function Aa(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function fd(...t){return t.reduce((e,n,r)=>r===0?n:Aa(e,n)>=0?e:n)}const pd={[Tu]:-1,[Dn]:-2,[Eu]:-3,[xu]:-4};var tn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function md(t){if(t.length===0)throw new tn("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new tn(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new tn(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new tn(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new tn(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var gd=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){md(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 yd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var wd=class extends gd{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=yd(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]"}}},bd=class{serde=new dd;constructor(t){this.serde=t||this.serde}},vd=class Pa extends Cn{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 Pa({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new Bt({func:async()=>this.structuredResponse})}async _generate(e,n,r){let o=e[e.length-1].content;e.length>1&&(o=e.map(h=>h.content).filter(Boolean).join("-")),(e.length===1||e.length===2&&e.every(pe.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new O({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 _d{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 Sd(){Ve.initializeGlobalInstance(new _d)}var ft=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
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))),En(this.prefix+this.suffix,this.templateFormat,n)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=await this.getExamples(n);r=r.map(o=>{const i={};return this.examplePrompt.inputVariables.forEach(a=>{i[a]=o[a]}),i});const s=[];for(const o of r){const i=await this.examplePrompt.formatMessages(o);s.push(...i)}return s}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),o=(await Promise.all(r.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return xe(i,this.templateFormat,n)}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new na(s)}},Mh=class Bn extends kn{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=Bn.extractRequiredInputValues(n,s.inputVariables);s instanceof Gs?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return Bn.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 Bn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function ko(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function Ah(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 Ph=class ra extends Gs{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(ko(e))return super.pipe(e.withStructuredOutput(this.schema));if(Ah(e)&&ko(e.bound))return super.pipe(new Oe({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,n,r){return ra.fromMessages(e,{schema:n,method:r})}},sa={};J(sa,{AIMessagePromptTemplate:()=>ea,BaseChatPromptTemplate:()=>zs,BaseMessagePromptTemplate:()=>kr,BaseMessageStringPromptTemplate:()=>Zi,BasePromptTemplate:()=>kn,BaseStringPromptTemplate:()=>pn,ChatMessagePromptTemplate:()=>Qi,ChatPromptTemplate:()=>Gs,DEFAULT_FORMATTER_MAPPING:()=>lr,DEFAULT_PARSER_MAPPING:()=>Yi,DictPromptTemplate:()=>ls,FewShotChatMessagePromptTemplate:()=>xh,FewShotPromptTemplate:()=>Eh,HumanMessagePromptTemplate:()=>Hs,ImagePromptTemplate:()=>Un,MessagesPlaceholder:()=>hs,PipelinePromptTemplate:()=>Mh,PromptTemplate:()=>Ze,StructuredPrompt:()=>Ph,SystemMessagePromptTemplate:()=>ta,checkValidTemplate:()=>En,interpolateFString:()=>qi,interpolateMustache:()=>Ji,parseFString:()=>gn,parseMustache:()=>ar,parseTemplate:()=>cr,renderTemplate:()=>xe});var Oh={},oa={};J(oa,{RunCollectorCallbackHandler:()=>Nh});var Nh=class extends Os{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)}},ia=class extends ri{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)}`)}},aa=class extends Xl{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 ia(t)}_diff(t,e){return e?Zl(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?ho(r.arguments):{...r,arguments:ho(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 ri{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new aa;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]}},la={};J(la,{JsonKeyOutputFunctionsParser:()=>Ih,JsonOutputFunctionsParser:()=>aa,OutputFunctionsParser:()=>ia});const Ye={and:"and",or:"or",not:"not"},R={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var ca=class{},Ks=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")}},qs=class extends Ks{},$h=class extends qs{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},Rh=class extends qs{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},jh=class extends Ks{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function ua(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Te(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:ua(t)&&Object.keys(t).length===0:!0}function ha(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 da(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 fa(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function pa(t){return typeof t=="boolean"}function Js(t){let e;if(fa(t))e=t;else if(ha(t))e=parseInt(t,10);else if(da(t))e=parseFloat(t);else if(pa(t))e=!!t;else throw new Error("Unsupported value type");return e}var Ys=class extends ca{},Lh=class extends Ys{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Ye.and,Ye.or],this.allowedComparators=t?.allowedComparators??[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte]}formatFunction(t){if(t in R){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(t)===-1)throw new Error(`Comparator ${t} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(t in Ye){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(t)===-1)throw new Error(`Operator ${t} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${t}`}visitOperation(t){const e=t.args?.map(n=>n.accept(this));return{[this.formatFunction(t.operator)]:e}}visitComparison(t){return{[t.attribute]:{[this.formatFunction(t.comparator)]:Js(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Te(t)&&Te(e))){if(Te(t)||n==="replace")return Te(e)?void 0:e;if(Te(e))return r?t:n==="and"?void 0:t;if(n==="and")return{$and:[t,e]};if(n==="or")return{$or:[t,e]};throw new Error("Unknown merge type")}}},Dh=class extends Ys{allowedOperators=[Ye.and,Ye.or];allowedComparators=[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"number":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"boolean":return[R.eq,R.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case R.eq:return(e,n)=>e===n;case R.ne:return(e,n)=>e!==n;case R.gt:return(e,n)=>e>n;case R.gte:return(e,n)=>e>=n;case R.lt:return(e,n)=>e<n;case R.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case Ye.and:return(e,n)=>e&&n;case Ye.or:return(e,n)=>e||n;default:throw new Error("Unknown operator")}}visitOperation(t){const{operator:e,args:n}=t;if(this.allowedOperators.includes(e)){const r=this.getOperatorFunction(e);return s=>n?n.reduce((o,i)=>{const a=i.accept(this);if(typeof a=="function")return r(o,a(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(t){const{comparator:e,attribute:n,value:r}=t,s=[R.ne];if(this.allowedComparators.includes(e)){if(!this.getAllowedComparatorsForType(typeof r).includes(e))throw new Error(`'${e}' comparator not allowed to be used with ${typeof r}`);const o=this.getComparatorFunction(e);return i=>{const a=i.metadata[n];return a===void 0?!!s.includes(e):o(a,Js(r))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(t){if(!t.filter)return{};const e=t.filter?.accept(this);if(typeof e!="function")throw new Error("Structured query filter is not a function");return{filter:e}}mergeFilters(t,e,n="and"){if(!(Te(t)&&Te(e))){if(Te(t)||n==="replace")return Te(e)?void 0:e;if(Te(e))return n==="and"?void 0:t;if(n==="and")return r=>t(r)&&e(r);if(n==="or")return r=>t(r)||e(r);throw new Error("Unknown merge type")}}},ma={};J(ma,{BaseTranslator:()=>Ys,BasicTranslator:()=>Lh,Comparators:()=>R,Comparison:()=>$h,Expression:()=>Ks,FilterDirective:()=>qs,FunctionalTranslator:()=>Dh,Operation:()=>Rh,Operators:()=>Ye,StructuredQuery:()=>jh,Visitor:()=>ca,castValue:()=>Js,isBoolean:()=>pa,isFilterEmpty:()=>Te,isFloat:()=>da,isInt:()=>ha,isObject:()=>ua,isString:()=>fa});var Fh=class extends Cn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new O(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(`
30
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new O(r),text:r}],llmOutput:{}}}},Uh=class ga extends Cn{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:Ee(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Ee(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Ee(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Ee(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new ga({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 O({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 es({message:new Vt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new O(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 es({message:new Vt({content:i}),text:i});yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},Vh=class ya extends Cn{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 O(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);yield this._createResponseChunk(a,l?this.generationInfo:void 0),r?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,n){return new es({message:new Vt({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:Ee(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:Ee(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:Ee(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:Ee(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new ya({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 Bt.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")})}},Bh=class extends ci{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})}},zh=class extends ci{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},Wh=class extends ui{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}},Hh=class extends ui{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)}},Gh=class extends Si{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async addUserMessage(t){this.messages.push(new pe(t))}async addAIMessage(t){this.messages.push(new O(t))}async clear(){this.messages=[]}},Kh=class extends Ds{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},qh=class extends Os{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Jh=class extends Ql{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},Yh=class extends Fs{lc_namespace=["test","fake"];output=[new Be({pageContent:"foo"}),new Be({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Xh=class extends Q{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},Zh=class extends _r{name;description;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.schema=t.schema}async _call(t,e){return JSON.stringify(t)}},Qh=class extends Os{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(t=>{this.runPromiseResolver=t})}async persistRun(t){this.runPromiseResolver(t)}async extract(){return this.runPromise}};function wa(t,e){let n=0,r=0,s=0;for(let o=0;o<t.length;o++)n+=t[o]*e[o],r+=t[o]*t[o],s+=e[o]*e[o];return n/(Math.sqrt(r)*Math.sqrt(s))}var ed=class va extends Us{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??wa}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 Be({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 Be({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 Be({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={};J(ba,{FakeChatMessageHistory:()=>Gh,FakeChatModel:()=>Fh,FakeEmbeddings:()=>zh,FakeLLM:()=>Wh,FakeListChatMessageHistory:()=>Kh,FakeListChatModel:()=>Vh,FakeRetriever:()=>Yh,FakeRunnable:()=>Xh,FakeSplitIntoListParser:()=>Jh,FakeStreamingChatModel:()=>Uh,FakeStreamingLLM:()=>Hh,FakeTool:()=>Zh,FakeTracer:()=>qh,FakeVectorStore:()=>ed,SingleRunExtractor:()=>Qh,SyntheticEmbeddings:()=>Bh});var _a={};J(_a,{EventStreamContentType:()=>td,convertEventStreamToIterableReadableDataStream:()=>rd,getBytes:()=>Sa,getLines:()=>Ca,getMessages:()=>ka});const td="text/event-stream";async function Sa(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(`
31
+ `))}}var _t=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})(_t||{});function Ca(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=nd(e,i);const l=e.length;let c=0;for(;n<l;){s&&(e[n]===_t.NewLine&&(c=++n),s=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case _t.Colon:r===-1&&(r=n-c);break;case _t.CarriageReturn:s=!0;case _t.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 ka(t,e,n){let r=Lr();const s=new TextDecoder;return function(i,a,l){if(l){sd(r)||(t?.(r),r=Lr());return}if(i.length===0)t?.(r),r=Lr();else if(a>0){const c=s.decode(i.subarray(0,a)),u=a+(i[a+1]===_t.Space?2:1),h=s.decode(i.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
32
+ `+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 nd(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function Lr(){return{data:"",event:"",id:"",retry:void 0}}function rd(t,e){const n=new ReadableStream({async start(r){const s=ka(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 Sa(t,Ca((i,a,l)=>{s(i,a,l),l&&r.close()}))}});return hn.fromReadableStream(n)}function sd(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var od={};function id(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function ad(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 ld(t,e){return Math.sqrt(ad(t,e))}var Ta={};J(Ta,{cosineSimilarity:()=>fs,euclideanDistance:()=>hd,innerProduct:()=>ud,matrixFunc:()=>Tr,maximalMarginalRelevance:()=>dd,normalize:()=>cd});function Tr(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 cd(t,e=!1){const n=fd(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function fs(t,e){return Tr(t,e,wa)}function ud(t,e){return Tr(t,e,id)}function hd(t,e){return Tr(t,e,ld)}function dd(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],o=fs(s,e)[0],i=Ea(o).maxIndex,a=[e[i]],l=[i];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const h=fs(e,a);o.forEach((d,f)=>{if(l.includes(f))return;const g=Math.max(...h[f]),p=n*d-(1-n)*g;p>c&&(c=p,u=f)}),a.push(e[u]),l.push(u)}return l}function Ea(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 fd(t){return t.reduce((e,n)=>Math.max(e,Ea(n).maxValue),0)}var xa={};J(xa,{agents:()=>Fu,caches:()=>uc,callbacks__base:()=>Lc,callbacks__manager:()=>jc,callbacks__promises:()=>Rc,chat_history:()=>_i,document_loaders__base:()=>Pi,document_loaders__langsmith:()=>Ni,documents:()=>$i,embeddings:()=>ou,example_selectors:()=>Di,index:()=>Vu,indexing:()=>Wi,language_models__base:()=>cc,language_models__chat_models:()=>lc,language_models__llms:()=>au,language_models__profile:()=>rh,load__serializable:()=>$c,memory:()=>Ci,messages:()=>Ic,messages__tool:()=>Nc,output_parsers:()=>ac,output_parsers__openai_functions:()=>la,output_parsers__openai_tools:()=>iu,outputs:()=>Oc,prompt_values:()=>ic,prompts:()=>sa,retrievers:()=>Mi,retrievers__document_compressors:()=>Hi,runnables:()=>oc,runnables__graph:()=>Pc,singletons:()=>Ac,stores:()=>Ti,structured_query:()=>ma,tools:()=>Wl,tracers__base:()=>Mc,tracers__console:()=>xc,tracers__log_stream:()=>Ec,tracers__run_collector:()=>oa,tracers__tracer_langchain:()=>Tc,types__stream:()=>Oh,utils__async_caller:()=>kc,utils__chunk_array:()=>su,utils__env:()=>Cc,utils__event_source_parse:()=>_a,utils__format:()=>od,utils__function_calling:()=>sc,utils__hash:()=>rc,utils__json_patch:()=>nc,utils__json_schema:()=>Sc,utils__math:()=>Ta,utils__stream:()=>_c,utils__testing:()=>ba,utils__tiktoken:()=>tc,utils__types:()=>ec,vectorstores:()=>Ai});function pd(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 zn(t){const{optionalImportsMap:e={},optionalImportEntrypoints:n=[],importMap:r={},secretsMap:s={},path:o=["$"]}=this,i=o.join(".");if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="secret"){const a=t,[l]=a.id;if(l in s)return s[l];{const c=Dc(l);if(c)return c;throw new Error(`Missing key "${l}" for ${i} in load(secretsMap={})`)}}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="not_implemented"){const l=JSON.stringify(t);throw new Error(`Trying to load an object that doesn't implement serialization: ${i} -> ${l}`)}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&"kwargs"in t&&t.lc===1){const a=t,l=JSON.stringify(a),[c,...u]=a.id.slice().reverse(),h=u.reverse(),d={langchain_core:xa,langchain:r};let f=null;const g=[h.join("/")];h[0]==="langchain_community"&&g.push(["langchain",...h.slice(1)].join("/"));const p=g.find(y=>y in e);if(Du.concat(n).includes(h.join("/"))||p)if(p!==void 0)f=await e[p];else throw new Error(`Missing key "${h.join("/")}" for ${i} in load(optionalImportsMap={})`);else{let y;if(h[0]==="langchain"||h[0]==="langchain_core")y=d[h[0]],h.shift();else throw new Error(`Invalid namespace: ${i} -> ${l}`);if(h.length===0)throw new Error(`Invalid namespace: ${i} -> ${l}`);let _;do{if(_=h.join("__"),_ in y)break;h.pop()}while(h.length>0);_ in y&&(f=y[_])}if(typeof f!="object"||f===null)throw new Error(`Invalid namespace: ${i} -> ${l}`);const S=f[c]??Object.values(f).find(y=>typeof y=="function"&&Fc(y)===c);if(typeof S!="function")throw new Error(`Invalid identifer: ${i} -> ${l}`);const C=await zn.call({...this,path:[...o,"kwargs"]},a.kwargs);if(a.type==="constructor"){const y=new S(Uc(C,Vc,pd(S)));return Object.defineProperty(y.constructor,"name",{value:c}),y}else throw new Error(`Invalid type: ${i} -> ${l}`)}else if(typeof t=="object"&&t!==null)return Array.isArray(t)?Promise.all(t.map((a,l)=>zn.call({...this,path:[...o,`${l}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,l])=>[a,await zn.call({...this,path:[...o,a]},l)])));return t}async function md(t,e){const n=JSON.parse(t);return zn.call({...e},n)}function gd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function ps(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>ps(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await ps(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 md(JSON.stringify(e));return e}}return t}function Dr(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function yd(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Dr(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Dr(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Dr(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var wd=class{_dumps(t){return new TextEncoder().encode(ju(t,(n,r)=>yd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return ps(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 Ma(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]=Ma(t[n]));return e}function Aa(){return{v:4,id:bi(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function ur(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:Ma(t.versions_seen)}}function Pa(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function vd(...t){return t.reduce((e,n,r)=>r===0?n:Pa(e,n)>=0?e:n)}const bd={[Ou]:-1,[Dn]:-2,[Nu]:-3,[Iu]:-4};var tn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function _d(t){if(t.length===0)throw new tn("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new tn(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new tn(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new tn(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new tn(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var Sd=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){_d(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 Cd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var kd=class extends Sd{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=Cd(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]"}}},Td=class{serde=new wd;constructor(t){this.serde=t||this.serde}},Ed=class Oa extends Cn{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 Oa({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new Bt({func:async()=>this.structuredResponse})}async _generate(e,n,r){let o=e[e.length-1].content;e.length>1&&(o=e.map(h=>h.content).filter(Boolean).join("-")),(e.length===1||e.length===2&&e.every(pe.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new O({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 xd{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 Md(){Ve.initializeGlobalInstance(new xd)}var ft=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
33
33
 
34
34
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${e.lc_error_code}/
35
- `),super(n),this.lc_error_code=e?.lc_error_code}},Oa=class extends ft{get is_bubble_up(){return!0}},Cd=class extends ft{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Hn=class extends ft{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},kt=class extends Oa{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Na=class extends kt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Ia=class extends Oa{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function kd(t){return t!==void 0&&t.name===Ia.unminifiable_name}function Wn(t){return t!==void 0&&t.is_bubble_up===!0}function at(t){return t!==void 0&&[kt.unminifiable_name,Na.unminifiable_name].includes(t.name)}var ko=class extends ft{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Z=class extends ft{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ft{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Td=class extends ft{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function $a(t){return t!=null&&t.lg_is_channel===!0}var pt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===Z.unminifiable_name)return!1;throw t}}};const ms=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function Xs(t){if(t[ms]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];$a(r)&&(e[n]=r)}return Object.assign(e,{[ms]:!0}),e}function hr(t,e){const n=Xs(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,{[ms]:!0}),r}function ot(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{s[o]=e[o].checkpoint()}catch(i){if(i.name!==Z.unminifiable_name)throw i}}return{v:4,id:r?.id??bi(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var gs=class Ra extends pt{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 Ra(this.operator,this.initialValueFactory);return typeof e<"u"&&(n.value=e),n}update(e){let n=e;if(!n.length)return!1;this.value===void 0&&([this.value]=n,n=n.slice(1));for(const r of n)this.value!==void 0&&(this.value=this.operator(this.value,r));return!0}get(){if(this.value===void 0)throw new Z;return this.value}checkpoint(){if(this.value===void 0)throw new Z;return this.value}isAvailable(){return this.value!==void 0}},Zs=class ja extends pt{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new ja;return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new B("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Z;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Z;return this.value[0]}isAvailable(){return this.value.length!==0}},Ed=class La extends pt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new La;if(typeof e<"u"){const[r,s]=e;n.value=[r],n.finished=s}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Z;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},xd=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const ys=function(t){return t?ws(t):new Zs};ys.Root=t=>new xd(t);function ws(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new gs(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new gs(t.value,t.default):new Zs}const D="__start__",P="__end__",Le="__input__",Md="__copy__",ae="__error__",Fr="__pregel_ns_writes",Qe="__pregel_send",Qs="__pregel_call",ct="__pregel_read",W="__pregel_checkpointer",Ke="__pregel_resuming",cn="__pregel_task_id",dr="__pregel_stream",Ad="__pregel_resume_value",Gn="__pregel_resume_map",et="__pregel_scratchpad",Kn="__pregel_previous",Da="__pregel_durability",bs="checkpoint_id",Pe="checkpoint_ns",Pd="__pregel_node_finished",ye="checkpoint_map",To="__pregel_abort_signals",L="__interrupt__",ce="__resume__",eo="__no_writes__",Gt="__return__",Ur="__previous__",G="langsmith:hidden",Od="langsmith:nostream",Eo="__self__",be="__pregel_tasks",de="__pregel_push",qn="__pregel_pull",ve="00000000-0000-0000-0000-000000000000",Nd=[G,Le,L,ce,ae,eo,Qe,ct,W,Da,dr,Ke,cn,Qs,Ad,et,Kn,ye,Pe,bs],q="|",ze=":",xo=Symbol.for("langgraph.command");var Id=class{[xo];constructor(t){this[xo]=t}};function vs(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var se=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=yn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function me(t){return t instanceof se}function Fa(t){return!t||typeof t!="object"||!(L in t)?!1:Array.isArray(t[L])}var K=class extends Id{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)?yn(t.goto):[yn(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:me(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function X(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function yn(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]=yn(r,e)});else if(X(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(vs(t)&&!(t instanceof se))n=new se(t.node,t.args),e.set(t,n);else if(X(t)||me(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=yn(s,e)}return n}return t}const $d=["tags","metadata","callbacks","configurable"],Rd=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],jd=25;function Ua(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:jd,configurable:{}},n=Ve.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if($d.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&&Rd.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 Ld(){return Ve.getRunnableConfig()}function Vr(t){return t.split(q).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(ze)[0]).join(q)}function Dd(t){const e=t.split(q);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(q)}const E=t=>BigInt(t),F=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Va=E("0x9E3779B1"),Ba=E("0x85EBCA77"),Fd=E("0xC2B2AE3D"),nt=E("0x9E3779B185EBCA87"),ht=E("0xC2B2AE3D27D4EB4F"),za=E("0x165667B19E3779F9"),to=E("0x85EBCA77C2B2AE63"),Ud=E("0x27D4EB2F165667C5"),Vd=E("0x165667919E3779F9"),Bd=E("0x9FB21C651E98DF25"),zd=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 F(r)},Ae=zd("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Tt=(E(1)<<E(128))-E(1),$=(E(1)<<E(64))-E(1),fr=(E(1)<<E(32))-E(1),De=64,Ha=De/8,Hd=8,An=4;function Kt(t){if(!t)throw new Error("Assert failed")}function Wd(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Gd(t){let e=t;return e=(e&E(65535))<<E(16)|(e&E(4294901760))>>E(16),e=(e&E(16711935))<<E(8)|(e&E(4278255360))>>E(8),e}function Kd(t,e){return(t&fr)*(e&fr)&$}function qd(t,e){return(t<<e|t>>E(32)-e)&fr}function Wa(t,e,n){for(let r=0;r<Ha;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Kd(o,o>>E(32))}return t}function Mo(t,e,n,r){for(let s=0;s<r;s+=1)Wa(t,F(e,s*De),F(n,s*8));return t}function Jd(t,e){for(let n=0;n<Ha;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=_s(s,E(47)),s^=r,s*=Va,t[n]=s&$}return t}function Pn(t,e){return Ga(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Hd,!0))}function Ao(t,e,n){let r=n;return r+=Pn(t.slice(0),F(e,0*An)),r+=Pn(t.slice(2),F(e,4*An)),r+=Pn(t.slice(4),F(e,8*An)),r+=Pn(t.slice(6),F(e,12*An)),Ne(r&$)}function Yd(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-De)/8),a=De*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=Mo(o,F(e,c*a),n,i),o=s(o,F(n,n.byteLength-De));{const c=Math.floor((e.byteLength-1-a*l)/De);o=Mo(o,F(e,l*a),n,c),o=r(o,F(e,e.byteLength-De),F(n,n.byteLength-De-7))}return o}function Xd(t,e){let n=new BigUint64Array([Fd,nt,ht,za,to,Ba,Ud,Va]);Kt(t.byteLength>128),n=Yd(n,t,e,Wa,Jd),Kt(n.length*8===64);{const r=Ao(n,F(e,11),E(t.byteLength)*nt&$);return Ao(n,F(e,e.byteLength-De-11),~(E(t.byteLength)*ht)&$)<<E(64)|r}}function Ga(t,e){const n=t*e&Tt;return n&$^n>>E(64)}function Po(t,e,n){return Ga((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&$,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&$)}function Jn(t,e,n,r,s){let o=t&$,i=t>>E(64)&$;return o+=Po(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=$,i+=Po(n,F(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=$,i<<E(64)|o}function Ne(t){let e=t;return e^=e>>E(37),e*=Vd,e&=$,e^=e>>E(32),e}function pr(t){let e=t;return e^=e>>E(33),e*=ht,e&=$,e^=e>>E(29),e*=za,e&=$,e^=e>>E(32),e}function Zd(t,e,n){const r=t.byteLength;Kt(r>0&&r<=3);const s=E(t.getUint8(r-1))|E(r<<8)|E(t.getUint8(0)<<16)|E(t.getUint8(r>>1)<<24),o=(E(e.getUint32(0,!0))^E(e.getUint32(4,!0)))+n,i=(s^o)&$,a=(E(e.getUint32(8,!0))^E(e.getUint32(12,!0)))-n,l=(qd(Gd(s),E(13))^a)&$;return(pr(l)&$)<<E(64)|pr(i)}function _s(t,e){return t^t>>e}function Qd(t,e,n){const r=t.byteLength;Kt(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0),i=E(s)|E(o)<<E(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&$;let c=(i^a)*(nt+(E(r)<<E(2)))&Tt;return c+=(c&$)<<E(65),c&=Tt,c^=c>>E(67),_s(_s(c&$,E(35))*Bd&$,E(28))|Ne(c>>E(64))<<E(64)}}function ef(t,e,n){const r=t.byteLength;Kt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&$,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&$,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*nt;const c=(l&$)+(E(r-1)<<E(54));l=l&(Tt^$)|c,a^=o,l+=a+(a&fr)*(Ba-E(1))<<E(64),l&=Tt,l^=Wd(l>>E(64));let u=(l&$)*ht;return u+=(l>>E(64))*ht<<E(64),u&=Tt,Ne(u&$)|Ne(u>>E(64))<<E(64)}}function tf(t,e){const n=t.byteLength;return Kt(n<=16),n>8?ef(t,Ae,e):n>=4?Qd(t,Ae,e):n>0?Zd(t,Ae,e):pr(e^Ae.getBigUint64(64,!0)^Ae.getBigUint64(72,!0))|pr(e^Ae.getBigUint64(80,!0)^Ae.getBigUint64(88,!0))<<E(64)}function Ss(t){return~t+E(1)&$}function nf(t,e,n){let r=E(t.byteLength)*nt&$,s=E(t.byteLength-1)/E(32);for(;s>=0;){const a=Number(s);r=Jn(r,F(t,16*a),F(t,t.byteLength-16*(a+1)),F(e,32*a),n),s-=E(1)}let o=r+(r>>E(64))&$;o=Ne(o);let i=(r&$)*nt+(r>>E(64))*to+(E(t.byteLength)-n&$)*ht;return i&=$,i=Ss(Ne(i)),o|i<<E(64)}function rf(t,e,n){let r=E(t.byteLength)*nt&$;for(let i=32;i<160;i+=32)r=Jn(r,F(t,i-32),F(t,i-16),F(e,i-32),n);r=Ne(r&$)|Ne(r>>E(64))<<E(64);for(let i=160;i<=t.byteLength;i+=32)r=Jn(r,F(t,i-32),F(t,i-16),F(e,3+i-160),n);r=Jn(r,F(t,t.byteLength-16),F(t,t.byteLength-32),F(e,103),Ss(n));let s=r+(r>>E(64))&$;s=Ne(s);let o=(r&$)*nt+(r>>E(64))*to+(E(t.byteLength)-n&$)*ht;return o&=$,o=Ss(Ne(o)),s|o<<E(64)}function st(t,e=E(0)){const n=new TextEncoder,r=F(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(tf(r,e)):s<=128?o(nf(r,Ae,e)):s<=240?o(rf(r,Ae,e)):o(Xd(r,Ae))}function Ka(t){return/^[0-9a-f]{32}$/.test(t)}function qa(t){const e=Ve.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n[W])throw new Hn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[et];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[Qe]?.([[ce,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[Qe]?.([[ce,s.resume]]),l}const i=n[Pe]?.split(q),a=i?st(i.join(q)):void 0;throw new kt([{id:a,value:t}])}var mt=class extends Q{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,o)=>{const i=ln(n,{callbacks:r?.getChild()});Ve.runWithConfig(i,async()=>{try{const a=await this.func(e,i);s(a)}catch(a){o(a)}})})}async invoke(e,n){let r;const s=Ua(n),o=Fe(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await Ve.runWithConfig(o,async()=>this.func(e,o)),Q.isRunnable(r)&&this.recurse?await Ve.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*We(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function qe(t){const e=[];for await(const n of await t)e.push(n);return e}function sn(t){const e=[];for(const n of t)e.push(n);return e}function yt(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function sf(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const ut={[Symbol.for("LG_PASSTHROUGH")]:!0};function On(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Br=Symbol("IS_WRITER");var oe=class Cs extends mt{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>me(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:e,name:r,tags:n,func:async(s,o)=>this._write(s,o??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>zr(s)&&On(s.value)?{mapper:s.mapper,value:e}:Yn(s)&&On(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Cs.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(Yn(o)){if(o.channel===be)throw new B("Cannot write to the reserved channel TASKS");if(On(o.value))throw new B("PASSTHROUGH value must be replaced")}if(zr(o)&&On(o.value))throw new B("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(me(o))r.push([be,o]);else if(zr(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(Yn(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(sf(i)||o.skipNone&&i===void 0)continue;r.push([o.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);const s=e.configurable?.[Qe];s(r)}static isWriter(e){return e instanceof Cs||Br in e&&!!e[Br]}static registerWriter(e){return Object.defineProperty(e,Br,{value:!0})}};function Yn(t){return t!==void 0&&typeof t.channel=="string"}function zr(t){return t!==void 0&&!Yn(t)&&Q.isRunnable(t.mapper)}var of=class Ja extends mt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Ja.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?.[ct];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 wt=new lc;var wn=class on extends Oe{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=wt;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,g=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??wt,config:{...e.config?e.config:{},tags:g}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=o??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=g,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 oe&&e[e.length-2]instanceof oe;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new oe(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===wt&&e.length===0))return this.bound===wt&&e.length===1?e[0]:this.bound===wt?new tt({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new tt({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 on({channels:{...this.channels,...Object.fromEntries(e.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(e){return oe.isWriter(e)?new on({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===wt?new on({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:zt(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new on({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 af(t){return"steps"in t&&Array.isArray(t.steps)}function no(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Ya(t){const e=[t];for(const n of e){if(no(n))return n;af(n)&&e.push(...n.steps)}}function Et(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===Z.unminifiable_name){if(r)return s;if(n)return null}throw s}}function dt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Et(t,s,!n)}catch(o){if(o.name===Z.unminifiable_name)continue}return r}else return Et(t,e)}function*lf(t,e){if(t.graph===K.PARENT)throw new B("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(me(r))yield[ve,be,r];else if(typeof r=="string")yield[ve,`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(Ka))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===ce).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,ce,s]}else yield[ve,ce,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[ve,n,r];else for(const[n,r]of Object.entries(t.update))yield[ve,n,r]}}function*Xa(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*Hr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield dt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Et(n,t))}function*cf(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(G))&&l[0][0]!==ae&&l[0][0]!==L);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===Gt))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===Gt).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 ro(t){const e=typeof t[D];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 Xn(t,e){if(Object.keys(t).length>0){const n=ro(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function uf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Ce(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function rt(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Ce(t,{[ye]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function mr(...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 hf=(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 df=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 ff(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function pf(t,e){const n=new mt({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new tt({name:t,first:n,last:new oe([{channel:Gt,value:ut}],[G])})}const mf=t=>t!==void 0?t+1:1;function gf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function yf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=fd(e,t[n]));return e}function Nn(t,e,n){const r=ro(t.channel_versions),s=t.versions_seen[L]??{};let o=!1;if((t.channel_versions[D]??r)>(s[D]??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(G):e.includes(a.name));return o&&i}function Zn(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=ot(t,a,-1),c=hr(a,l);he(ur(l),c,[n],void 0,void 0),i=dt({...e,...c},r)}else i=dt(e,r);return i}function Wr(t,e,n){for(const[r,s]of n)if([de,be].includes(r)&&s!=null){if(!me(s))throw new B(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new B(`Invalid node name "${s.node}" in Send packet`)}t(n)}const wf=new Set([eo,de,ce,L,Gt,ae]);function he(t,e,n,r,s){n.sort((d,f)=>{const g=d.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let S=0;S<Math.min(g.length,p.length);S+=1){if(g[S]<p[S])return-1;if(g[S]>p[S])return 1}return g.length-p.length});const o=n.some(d=>d.triggers.length>0),i=Xs(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=yf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!Nd.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,g]of d.writes)wf.has(f)||f in i&&(u[f]??=[],u[f].push(g));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 g=i[d];let p;try{p=g.update(f)}catch(S){if(S.name===B.unminifiable_name){const C=new B(`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}p&&r!==void 0&&(t.channel_versions[d]=r(a),g.isAvailable()&&h.add(d))}if(o)for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.isAvailable()&&!h.has(d)&&f.update([])&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}if(o&&!gf(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*bf(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 St(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=ks([de,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const c of bf(t,n,i)){const u=ks([qn,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function ks(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]===de&&ff(t[t.length-1])){const f=t[t.length-1],g=pf(f.name,f.func),p=[de],S=d===""?f.name:`${d}${q}${f.name}`,C=bt(JSON.stringify([S,l.toString(),f.name,de,t[1],t[2]]),e.id),y=`${S}${ze}${C}`,_=[...t.slice(0,3),!0],v={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:_,langgraph_checkpoint_ns:y};if(i){const k=[];return{name:f.name,input:f.input,proc:g,writes:k,config:ln(Fe(o,{metadata:v,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:C,[Qe]:w=>Wr(b=>k.push(...b),r,w),[ct]:(w,b=!1)=>Zn(e,s,{name:f.name,writes:k,triggers:p,path:_},w,b),[W]:c??h[W],[ye]:{...h[ye],[d]:e.id},[et]:Gr({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:o.configurable?.[Gn],namespaceHash:st(y)}),[Kn]:e.channel_values[Ur],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:st((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Fr,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:C,path:_,writers:[]}}else return{id:C,name:f.name,interrupts:[],path:_}}else if(t[0]===de){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[be]?.isAvailable())return;const g=s[be].get();if(f<0||f>=g.length)return;const p=vs(g[f])&&!me(g[f])?new se(g[f].node,g[f].args):g[f];if(!vs(p)){console.warn(`Ignoring invalid packet ${JSON.stringify(p)} in pending sends.`);return}if(!(p.node in r)){console.warn(`Ignoring unknown node name ${p.node} in pending sends.`);return}const S=[de],C=d===""?p.node:`${d}${q}${p.node}`,y=bt(JSON.stringify([C,l.toString(),p.node,de,f.toString()]),e.id),_=`${C}${ze}${y}`;let v={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:S,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:_};if(i){const k=r[p.node],M=k.getNode();if(M!==void 0){k.metadata!==void 0&&(v={...v,...k.metadata});const w=[];return{name:p.node,input:p.args,proc:M,subgraphs:k.subgraphs,writes:w,config:ln(Fe(o,{metadata:v,tags:k.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:y,[Qe]:b=>Wr(T=>w.push(...T),r,b),[ct]:(b,T=!1)=>Zn(e,s,{name:p.node,writes:w,triggers:S,path:t},b,T),[W]:c??h[W],[ye]:{...h[ye],[d]:e.id},[et]:Gr({pendingWrites:n??[],taskId:y,currentTaskInput:p.args,resumeMap:o.configurable?.[Gn],namespaceHash:st(_)}),[Kn]:e.channel_values[Ur],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:S,retry_policy:k.retryPolicy,cache_key:k.cachePolicy?{key:st((k.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[Fr,k.name??"__dynamic__",p.node],ttl:k.cachePolicy.ttl}:void 0,id:y,path:t,writers:k.getWriters()}}}else return{id:y,name:p.node,interrupts:[],path:t}}else if(t[0]===qn){const f=t[1].toString(),g=r[f];if(g===void 0)return;if(n?.length){const y=d===""?f:`${d}${q}${f}`,_=bt(JSON.stringify([y,l.toString(),f,qn,f]),e.id);if(n.some(k=>k[0]===_&&k[1]!==ae))return}const p=ro(e.channel_versions);if(p===void 0)return;const S=e.versions_seen[f]??{},C=g.triggers.find(y=>s[y].isAvailable()?(e.channel_versions[y]??p)>(S[y]??p):!1);if(C!==void 0){const y=vf(g,s,i);if(y===void 0)return;const _=d===""?f:`${d}${q}${f}`,v=bt(JSON.stringify([_,l.toString(),f,qn,[C]]),e.id),k=`${_}${ze}${v}`;let M={langgraph_step:l,langgraph_node:f,langgraph_triggers:[C],langgraph_path:t,langgraph_checkpoint_ns:k};if(i){const w=g.getNode();if(w!==void 0){g.metadata!==void 0&&(M={...M,...g.metadata});const b=[];return{name:f,input:y,proc:w,subgraphs:g.subgraphs,writes:b,config:ln(Fe(o,{metadata:M,tags:g.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:v,[Qe]:T=>Wr(x=>{b.push(...x)},r,T),[ct]:(T,x=!1)=>Zn(e,s,{name:f,writes:b,triggers:[C],path:t},T,x),[W]:c??h[W],[ye]:{...h[ye],[d]:e.id},[et]:Gr({pendingWrites:n??[],taskId:v,currentTaskInput:y,resumeMap:o.configurable?.[Gn],namespaceHash:st(k)}),[Kn]:e.channel_values[Ur],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:[C],retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:st((g.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[Fr,g.name??"__dynamic__",f],ttl:g.cachePolicy.ttl}:void 0,id:v,path:t,writers:g.getWriters()}}}else return{id:v,name:f,interrupts:[],path:t}}}}function vf(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]=Et(e,o,!1)}catch(i){if(i.name===Z.unminifiable_name)return;throw i}else if(o in e)try{r[s]=Et(e,o,!1)}catch(i){if(i.name===Z.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=Et(e,o,!1),s=!0;break}catch(i){if(i.name===Z.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function Gr({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([l,c])=>l===ve&&c===ce)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const l=t.filter(([c,u])=>c===e&&u===ce).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===ve&&c===ce),1),o}};return a}const bn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},vn=(t,e)=>`${t.start}${e}${t.end}`;function*Oo(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t){if(s?.tags?.includes(G))continue;const a=i.filter(([l,c])=>l===e&&c===L).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:o,interrupts:a}}}function _f(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Za(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=_f(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*Sf(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(G)||(yield{id:n,name:r,result:Za(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===L).map(i=>i[1])})}function*Cf(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(Ya))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:dt(e,n),metadata:r,next:s.map(h=>h.name),tasks:Qa(s,o,u,a),parentConfig:i?l(i):void 0}}function Qa(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===ae)?.[2],i=e.filter(([c,u])=>c===s.id&&u===L).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,h])=>u===s.id&&h===Gt);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?Za(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 kf(t,e,n){console.log([`${vn(bn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
36
- `,JSON.stringify(dt(e,n),null,2)].join(""))}function el(t,e){const n=e.length;console.log([`${vn(bn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
37
- `,e.map(r=>`- ${vn(bn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
38
- `)].join(""))}function Tf(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${vn(bn.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
39
- `,Object.entries(r).map(([s,o])=>`- ${vn(bn.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
40
- `)].join(""))}var No=class extends hn{_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}},tl=class extends hn{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 Ef(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 xf(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function so(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Kr(t){return!so(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 Io(t){if(so(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 $o(t){const e={...t,checkpoint:Kr(t.config),parent_checkpoint:Kr(t.parentConfig),config:Io(t.config),parent_config:Io(t.parentConfig),tasks:t.tasks.map(n=>{if(so(n.state)){const r=Kr(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function Mf(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
41
- data: ${Ef(s.data)}
42
-
43
- `))};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:$o(u.payload)})}i==="checkpoints"&&(l=$o(a));const c=o?.length?`${i}|${o.join("|")}`:i;r({event:c,data:l})}}catch(s){r({event:"error",data:xf(s)})}n.close()}})}const In=Symbol.for("INPUT_DONE"),qr=Symbol.for("INPUT_RESUMING"),Af=25;function Pf(...t){return new tl({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 Of=class extends bd{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}},Nf=class nl{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(D 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?.[Ke]!==void 0&&this.config.configurable?.[Ke],s=this.input===null||this.input===void 0,o=X(this.input)&&this.input.resume!=null,i=this.input===qr,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=mf,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 Of(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?.[dr]!==void 0&&(r=Pf(r,n.configurable[dr]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[et];n.configurable&&o&&(o.subgraphCounter>0&&(n=Ce(n,{[Pe]:[n.configurable[Pe],o.subgraphCounter.toString()].join(q)})),o.subgraphCounter+=1);const i=ct in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Ce(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ye]!==void 0&&n.configurable?.[ye]?.[n.configurable?.checkpoint_ns]&&(a=Ce(n,{checkpoint_id:n.configurable[ye][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(q)??[],c=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:Ma(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,h=ur(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],g=hr(e.channelSpecs,h),p=(d.step??0)+1,S=p+(n.recursionLimit??Af)+1,C={...h.channel_versions},y=e.store?new wd(e.store):void 0;return y&&await y.start(),new nl({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:g,isNested:i,manager:e.manager,skipDoneTasks:s,step:p,stop:S,checkpointPreviousVersions:C,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:y,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(e,n){let r=n;if(r.length===0)return;r.every(([i])=>i in pd)&&(r=Array.from(new Map(r.map(i=>[i[0],i])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(i=>i[0]!==e);for(const[i,a]of r)this.checkpointPendingWrites.push([e,i,a]);const s=Ce(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??"",[bs]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(s,r,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||n[0][0]===ae||n[0][0]===L||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,n,r=!1){const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(G))return;if(n.length>0)if(n[0][0]===L){if(s.path?.[0]===de&&s.path?.at(-1)===!0)return;const o=n.filter(i=>i[0]===L).flatMap(i=>i[1]);this._emit([["updates",{[L]:o}],["values",{[L]:o}]])}else n[0][0]!==ae&&this._emit(sn(We(cf(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(sn(We(Sf([[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(![In,qr].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new kt;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await qe(We(Hr(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Nn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new kt;this.config.configurable?.[Ke]!==void 0&&delete this.config.configurable?.[Ke]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=St(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 qe(We(Cf(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[o,i,a]of this.checkpointPendingWrites){if(i===ae||i===L||i===ce)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(Nn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new kt;const s=await qe(We(Oo(Object.values(this.tasks)),"tasks"));return this._emit(s),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(ze)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=dt(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(sn(We(Hr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),at(e)&&!e.interrupts.length&&this._emit([["updates",{[L]:[]}],["values",{[L]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&Nn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=ks([de,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&Nn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(sn(We(Oo([s]),"tasks"))),this.debug&&el(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 at(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[et];if(r&&r.nullResume!==void 0&&this.putWrites(ve,[[ce,r.nullResume]]),X(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Ka)&&(this.config.configurable??={},this.config.configurable[Gn]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of lf(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new ko("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===ve).map(i=>i.slice(1));s.length>0&&he(this.checkpoint,this.channels,[{name:Le,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=X(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[L]={...this.checkpoint.versions_seen[L],[a]:l}}const i=await qe(We(Hr(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=qr;else if(o)await this._putCheckpoint({source:"input"}),this.input=In;else{const i=await qe(Xa(e,this.input));if(i.length>0){const a=St(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=he(this.checkpoint,this.channels,Object.values(a).concat([{name:Le,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=In}else if(Ke in(this.config.configurable??{}))this.input=In;else throw new ko(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Ce(this.config,{[Ke]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Ce(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=Xn(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ur(o),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.[ye]??{}}),this.checkpoint=ot(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=Ce(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??"",[bs]:this.checkpoint.id}),n={};for(const[r,s,o]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,o]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,s,r))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r===ae||r===L||r===ce)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 If(t){return je(t?.message)}var $f=class extends Fc{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&&(Uc(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(Od)&&!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&&(If(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Vt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];je(n?.message)&&this._emit(this.metadatas[e],n?.message,e,!0),delete this.emittedChatModelRunIds[e]}delete this.metadatas[e],delete this.stableMessageIdMap[e]}}handleLLMError(t,e){delete this.metadatas[e]}handleChainStart(t,e,n,r,s,o,i,a){if(o!==void 0&&a===o.langgraph_node&&(s===void 0||!s.includes(G))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const l of Object.values(e))if((je(l)||ho(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(je(c)||ho(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(je(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)je(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(je(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)je(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const Rf=500,jf=2,Lf=128e3,Df=3,Ff=[400,401,402,403,404,405,406,407,409],Uf=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&&Ff.includes(+e)||t?.error?.code==="insufficient_quota")};async function rl(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??Rf:0,i=0,a,l,{config:c}=t;for(n&&(c=Ce(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,kd(a)){const g=c?.configurable?.checkpoint_ns,p=a.command;if(p.graph===g){for(const S of t.writers)await S.invoke(p,c);a=void 0;break}else if(p.graph===K.PARENT){const S=Dd(g);a.command=new K({...a.command,graph:S})}}if(Wn(a)||s===void 0||(i+=1,i>=(s.maxAttempts??Df))||!(s.retryOn??Uf)(a))break;o=Math.min(s.maxInterval??Lf,o*(s.backoffFactor??jf));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(g=>setTimeout(g,d));const f=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${o.toFixed(2)}ms (attempt ${i}) after ${f}: ${a}`),c=Ce(c,{[Ke]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const Ts=Symbol.for("promiseAdded");function Vf(){const t={next:()=>{},wait:Promise.resolve(Ts)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Ts)}}return t.wait=new Promise(e),t}var Bf=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(g=>g.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:g,error:p,signalAborted:S}of f)this._commit(g,p),at(p)||Wn(p)&&!at(i)?i=p:p&&(o.size===0||!S)&&(a.abort(),o.add(p));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(g=>g.writes).flat()),o.size===1)throw Array.from(o)[0];if(o.size>1)throw new AggregateError(Array.from(o),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(at(i)||Wn(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[To]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=mr(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Ce(this.loop.config,{[To]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Vf(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(d,f,g)=>this.loop.acceptPush(d,f,g)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=mr(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]=rl(f,n,{[Qs]:sl?.bind(a,this,f)},s?.composedAbortSignal).catch(g=>({task:f,error:g,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(i),...h?[h]:[],o.wait]);d!==Ts&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[d.task.id])}}_commit(t,e){if(e!==void 0)if(at(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[L,s]),r=t.writes.filter(s=>s[0]===ce);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Wn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[ae,{message:e.message,name:e.name}]]);else this.nodeFinished&&(t.config?.tags==null||!t.config.tags.includes(G))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([eo,null]),this.loop.putWrites(t.id,t.writes)}};async function sl(t,e,n,r,s,o={}){const i=e.config?.configurable?.[et];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new df({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===Gt),d=c.writes.filter(([f])=>f===ae);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(d.length>0){if(d.length===1){const f=d[0][1],g=f instanceof Error?f:new Error(String(f));return Promise.reject(g)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=rl(c,o.retry,{[Qs]:sl.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 $e=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function zf({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new $e("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===L)throw new $e(`"Node name ${L} is reserved"`);if(u.constructor===wn)u.triggers.forEach(h=>a.add(h));else throw new $e(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new $e(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new $e(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new $e(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(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 $e(`Output channel '${String(c)}' not in channels`);if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new $e(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new $e(`Node ${String(c)} not in nodes`)}}function Ro(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 Hf=class ol extends pt{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 ol({unique:this.unique,accumulate:this.accumulate});return typeof e<"u"&&(n.seen=new Set(e[0]),n.values=e[1]),n}update(e){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=e.flat();if(r.length>0)if(this.unique)for(const s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new Z;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Wf=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 wn({channels:s,triggers:o,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:ut,skipNone:!1});for(const[r,s]of Object.entries(e??{}))Q.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:ut,skipNone:!0,mapper:zt(s)}):n.push({channel:r,value:s,skipNone:!1});return new oe(n)}},Gf=class extends Q{lc_namespace=["langgraph","pregel"];invoke(t,e){throw new Error("Not implemented")}withConfig(t){return super.withConfig(t)}stream(t,e){return super.stream(t,e)}},Kf=class extends Gf{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 Hf({accumulate:!1}),this.autoValidate=t.autoValidate??this.autoValidate,this.streamMode=e??this.streamMode,this.inputChannels=t.inputChannels,this.outputChannels=t.outputChannels,this.streamChannels=t.streamChannels??this.streamChannels,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.stepTimeout=t.stepTimeout??this.stepTimeout,this.debug=t.debug??this.debug,this.checkpointer=t.checkpointer,this.retryPolicy=t.retryPolicy,this.config=t.config,this.store=t.store,this.cache=t.cache,this.name=t.name,this.triggerToNodes=t.triggerToNodes??this.triggerToNodes,this.userInterrupt=t.userInterrupt,this.autoValidate&&this.validate()}withConfig(t){const e=Fe(this.config,t);return new this.constructor({...this,config:e})}validate(){zf({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=Ya(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}${q}${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=hr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===ve).map(([d,f,g])=>[String(f),g]);h.length>0&&he(e.checkpoint,s,[{name:Le,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(St(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await qe(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of o){const d=i.find(([g])=>g===h.name);if(!d)continue;let f=`${String(h.name)}${ze}${h.id}`;if(a&&(f=`${a}${q}${f}`),n===void 0){const g={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=g}else{const g={configurable:{[W]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=d[1];l[h.id]=await p.getState(g,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,g,p]of e.pendingWrites)[ae,L,Dn].includes(g)||f in h&&h[f].writes.push([String(g),p]);const d=o.filter(f=>f.writes.length>0);d.length>0&&he(e.checkpoint,s,d,void 0,this.triggerToNodes)}let 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:dt(s,this.streamChannelsAsIs),next:u,tasks:Qa(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:rt(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[W]??this.checkpointer;if(!n)throw new Hn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const a=Vr(r);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(yt(t,{[W]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Fe(this.config,t),o=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:o,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[W]??this.checkpointer;if(!n)throw new Hn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const o=Vr(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(yt(t,{[W]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=Fe(this.config,t,{configurable:{checkpoint_ns:r}});for await(const o of n.list(s,e))yield this._prepareStateSnapshot({config:o.config,saved:o})}async bulkUpdateState(t,e){const n=t.configurable?.[W]??this.checkpointer;if(!n)throw new Hn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(e.length===0)throw new Error("No supersteps provided");if(e.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[W]===void 0){const i=Vr(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(yt(t,{[W]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?Fe(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?ur(c.checkpoint):Ma(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=yt(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),g=l.metadata??{};c?.config.configurable&&(f=yt(l,c.config.configurable),g={...c.metadata,...g});const{values:p,asNode:S}=a[0];if(p==null&&S===void 0){if(a.length>1)throw new B("Cannot create empty checkpoint with multiple updates");const w=await n.put(f,ot(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return rt(w,c?c.metadata:void 0)}const C=hr(this.channels,u);if(p===null&&S===P){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const b=St(u,c.pendingWrites||[],this.nodes,C,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),T=(c.pendingWrites||[]).filter(x=>x[0]===ve).map(x=>x.slice(1));T.length>0&&he(u,C,[{name:Le,writes:T,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[x,A,I]of c.pendingWrites||[])[ae,L,Dn].includes(A)||x in b&&b[x].writes.push([A,I]);he(u,C,Object.values(b),n.getNextVersion.bind(n),this.triggerToNodes)}const w=await n.put(f,ot(u,C,d),{...g,source:"update",step:d+1,parents:c?.metadata?.parents??{}},Xn(h,u.channel_versions));return rt(w,c?c.metadata:void 0)}if(S===Md){if(a.length>1)throw new B("Cannot copy checkpoint with multiple updates");if(c==null)throw new B("Cannot copy a non-existent checkpoint");const w=x=>!Array.isArray(x)||x.length===0?!1:x.every(A=>Array.isArray(A)&&A.length===2),b=ot(u,void 0,d),T=await n.put(c.parentConfig??yt(c.config,{checkpoint_id:void 0}),b,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(w(p)){const x=St(b,c.pendingWrites,this.nodes,C,T,!1,{step:d+2}),A=Object.values(x).reduce((j,{name:ee,id:re})=>(j[ee]??=[],j[ee].push({id:re}),j),{}),I=p.reduce((j,ee)=>{const[re,Se]=ee;j[Se]??=[];const Me=j[Se].length,xn=A[Se]?.[Me]?.id;return j[Se].push({values:re,asNode:Se,taskId:xn}),j},{});return s(rt(T,c.metadata),Object.values(I).flat())}return rt(T,c.metadata)}if(S===Le){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const w=await qe(Xa(this.inputChannels,p));if(w.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);he(u,C,[{name:Le,writes:w,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const b=c?.metadata?.step!=null?c.metadata.step+1:-1,T=await n.put(f,ot(u,C,b),{source:"input",step:b,parents:c?.metadata?.parents??{}},Xn(h,u.channel_versions));return await n.putWrites(T,w,bt(Le,u.id)),rt(T,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const w=St(u,c.pendingWrites,this.nodes,C,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),b=(c.pendingWrites??[]).filter(x=>x[0]===ve).map(x=>x.slice(1));b.length>0&&he(c.checkpoint,C,[{name:Le,writes:b,triggers:[]}],void 0,this.triggerToNodes);for(const[x,A,I]of c.pendingWrites)[ae,L,Dn].includes(A)||w[x]===void 0||w[x].writes.push([A,I]);const T=Object.values(w).filter(x=>x.writes.length>0);T.length>0&&he(u,C,T,void 0,this.triggerToNodes)}const y=Object.values(u.versions_seen).map(w=>Object.values(w)).flat().find(w=>!!w),_=[];if(a.length===1){let{values:w,asNode:b,taskId:T}=a[0];if(b===void 0&&Object.keys(this.nodes).length===1)[b]=Object.keys(this.nodes);else if(b===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(b=this.inputChannels);else if(b===void 0){const x=Object.entries(u.versions_seen).map(([A,I])=>Object.values(I).map(j=>[j,A])).flat().filter(([A,I])=>I!==L).sort(([A],[I])=>Aa(A,I));x&&(x.length===1?b=x[0][1]:x[x.length-1][0]!==x[x.length-2][0]&&(b=x[x.length-1][1]))}if(b===void 0)throw new B('Ambiguous update, specify "asNode"');_.push({values:w,asNode:b,taskId:T})}else for(const{asNode:w,values:b,taskId:T}of a){if(w==null)throw new B('"asNode" is required when applying multiple updates');_.push({values:b,asNode:w,taskId:T})}const v=[];for(const{asNode:w,values:b,taskId:T}of _){if(this.nodes[w]===void 0)throw new B(`Node "${w.toString()}" does not exist`);const x=this.nodes[w].getWriters();if(!x.length)throw new B(`No writers found for node "${w.toString()}"`);v.push({name:w,input:b,proc:x.length>1?tt.from(x,{omitSequenceTags:!0}):x[0],writes:[],triggers:[L],id:T??bt(L,u.id),writers:[]})}for(const w of v)await w.proc.invoke(w.input,ln({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[Qe]:b=>w.writes.push(...b),[ct]:(b,T=!1)=>Zn(u,C,w,b,T)}}));for(const w of v){const b=w.writes.filter(T=>T[0]!==de);c!==void 0&&b.length>0&&await n.putWrites(f,b,w.id)}he(u,C,v,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const k=Xn(h,u.channel_versions),M=await n.put(f,ot(u,C,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},k);for(const w of v){const b=w.writes.filter(T=>T[0]===de);b.length>0&&await n.putWrites(M,b,w.id)}return rt(M,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:Ro(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Ro(h,this.channels);const d=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let g;n!==void 0?(g=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[cn]!==void 0?g=["values"]:g=this.streamMode,l=!0);let p;if(this.checkpointer===!1)p=void 0;else if(t!==void 0&&t.configurable?.[W]!==void 0)p=t.configurable[W];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");p=this.checkpointer}const 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 y=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),_=t.durability??y??t?.configurable?.[Da]??"async";return[c,g,h,u,a,d,f,p,S,l,C,_]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:mr(e?.signal,n.signal).signal},s=await super.stream(t,r);return new No(e?.encoding==="text/event-stream"?Mf(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:hf(this.config?.callbacks,e?.callbacks),signal:mr(e?.signal,r.signal).signal};return new No(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=Ua(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,g,p,S,C,y]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const _=new tl({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const A=h.configurable[Pe]??"";h.configurable[Pe]=A.split(q).map(I=>I.split(ze)[0]).join(q)}if(c.includes("messages")){const A=new $f(j=>_.push(j)),{callbacks:I}=h;if(I===void 0)h.callbacks=[A];else if(Array.isArray(I))h.callbacks=I.concat(A);else{const j=I.copy();j.addHandler(A,!0),h.callbacks=j}}h.writer??=A=>{if(!c.includes("custom"))return;const I=Ld()?.configurable?.[Pe]?.split(q).slice(0,-1);_.push([I??[],"custom",A])},h.interrupt??=this.userInterrupt??qa;const k=await(await Vc(h))?.handleChainStart(this.toJSON(),uf(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),M=Xs(this.channels);let w,b;const x=(async()=>{try{w=await Nf.initialize({input:o,config:h,checkpointer:g,nodes:this.nodes,channelSpecs:M,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:C,stream:_,interruptAfter:f,interruptBefore:d,manager:k,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});const A=new Bf({loop:w,nodeFinished:h.configurable?.[Pd]});e?.subgraphs&&(w.config.configurable={...w.config.configurable,[dr]:w.stream}),await this._runLoop({loop:w,runner:A,debug:l,config:h}),y==="sync"&&await Promise.all(w?.checkpointerPromises??[])}catch(A){b=A}finally{try{w&&(await w.store?.stop(),await w.cache?.stop()),await Promise.all(w?.checkpointerPromises??[])}catch(A){b=b??A}b?_.error(b):_.close()}})();try{for await(const A of _){if(A===void 0)throw new Error("Data structure error.");const[I,j,ee]=A;if(c.includes(j)){if(n==="text/event-stream"){r?yield[I,j,ee]:yield[null,j,ee];continue}r&&!S?yield[I,j,ee]:S?r?yield[I,ee]:yield ee:yield[j,ee]}}}catch(A){throw await k?.handleChainError(b),A}finally{await x}await k?.handleChainEnd(w?.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"?Fa(l)?i.push(l[L]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.flat(1);if(a==null)return{[L]:l};if(typeof a=="object")return{...a,[L]: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&&kf(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&el(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&Tf(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new Cd([`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([])}},qt=class il extends pt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new il(this.guard);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0){const n=this.value.length>0;return this.value=[],n}if(e.length!==1&&this.guard)throw new B("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Z;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Z;return this.value[0]}isAvailable(){return this.value.length!==0}},al=class{path;ends;constructor(t){Q.isRunnable(t.path)?this.path=t.path:this.path=zt(t.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return oe.registerWriter(new mt({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===Na.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
44
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let o;if(this.ends?o=s.map(a=>me(a)?a:this.ends[a]):o=s,o.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(o.filter(me).some(a=>a.node===P))throw new B("Cannot send a packet to the END node");return await n(o,e)??t}},qf=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[q,ze])if(r.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===P)throw new Error(`Node \`${r}\` is reserved.`);const i=zt(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:no(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===P)throw new Error("END cannot be a start node");if(e===D)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){const r=typeof t=="object"?t:{source:t,path:e,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!Q.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=zt(r.path).withConfig({runName:`Branch<${r.source}${o!==""?`,${o}`:""}>`.slice(0,63)})}const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${t}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new al(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(D,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,P)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new ll({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[D]:new qt,[P]:new qt},inputChannels:D,outputChannels:P,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!==D&&!(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(P);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 Td([`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(`
45
- `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==P&&!(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}},ll=class extends Kf{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new qt,this.nodes[t]=new wn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new oe([{channel:t,value:ut}],[G])),this.streamChannels.push(t)}attachEdge(t,e){if(e===P){if(t===D)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new oe([{channel:P,value:ut}],[G]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===D&&!this.nodes[D]&&(this.nodes[D]=Wf.subscribeTo(D,{tags:[G]})),this.nodes[t].pipe(n.run(s=>{const o=s.map(i=>me(i)?i:{channel:i===P?P:`branch:${t}:${e}:${i}`,value:ut});return new oe(o,[G])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==P){const o=`branch:${t}:${e}:${s}`;this.channels[o]=new qt,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new fo,r={[D]:n.addNode({schema:ke()},D)},s={};let o={};e&&(o=Object.fromEntries((await qe(this.getSubgraphsAsync())).filter(l=>jo(l[1]))));function i(l,c,u,h=!1){if(c===P&&s[P]===void 0&&(s[P]=n.addNode({schema:ke()},P)),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=te(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,g=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let C=function(_){return _?_.lc_runnable:!1},y=function(_,v){if(_!==void 0&&!po(_))return _;if(C(v))try{let k=v.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return v.getName()}else return v.name??"UnknownSchema"};const[p,S]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:y(S.id,S.data),...S}),s[u]={name:y(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);r[u]=p,s[u]=p}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(te(l),te(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=>[te(h),te(h)])),[P]:P};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))i(te(l),te(g),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)i(te(l),te(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new fo,r={[D]:n.addNode({schema:ke()},D)},s={};let o={};e&&(o=Object.fromEntries(sn(this.getSubgraphs()).filter(l=>jo(l[1]))));function i(l,c,u,h=!1){return c===P&&s[P]===void 0&&(s[P]=n.addNode({schema:ke()},P)),n.addEdge(r[l],s[c],u!==c?u:void 0,h)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=te(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,g=o[l]!==void 0?o[l].getGraph({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let C=function(_){return _?_.lc_runnable:!1},y=function(_,v){if(_!==void 0&&!po(_))return _;if(C(v))try{let k=v.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return v.getName()}else return v.name??"UnknownSchema"};const[p,S]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:y(S.id,S.data),...S}),s[u]={name:y(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);r[u]=p,s[u]=p}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(te(l),te(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=>[te(h),te(h)])),[P]:P};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))i(te(l),te(g),f,!0)}}return n}};function jo(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function te(t){return t==="subgraph"?`"${t}"`:t}const lt=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Jf=class cl extends pt{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new cl(this.names);return typeof e<"u"&&(n.seen=new Set(e)),n}update(e){let n=!1;for(const r of e)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!lt(this.names,this.seen))throw new Z}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&lt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&lt(this.names,this.seen)}},Yf=class ul extends pt{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 ul(this.names);if(typeof e<"u"){const[r,s]=e;n.seen=new Set(r),n.finished=s}return n}update(e){let n=!1;for(const r of e)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!lt(this.names,this.seen))throw new Z}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&lt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&lt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&lt(this.names,this.seen)}};const Xf="lg:";var Zf=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=mo(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new gs(o.reducer.fn,o.default):e[r]=new Zs}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(mo(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=ts(c)??ts(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${Xf}${h}`)}return[i,c]});s=Bc(t,Object.fromEntries(o)),zc(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=Is(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const Jt=new Zf;function Yt(t,e){if(e.reducer&&!e.default){const n=Ns(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return Jt.extend(n,()=>e),n}else return Jt.extend(t,()=>e),t}const Ue="__root__",Es=Symbol.for("langgraph.state.partial");var Qf=class extends qf{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Jt;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),ip(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??Es,this._outputDefinition=o,this._outputRuntimeDefinition=t.output??t.state}else if(fe(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=Es,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(op(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(sp(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(np(t)||Lo(t)){const r=Lo(t)?t.spec:t;this._schemaDefinition=r}else if(rp(t)){const r=ep(t.channels);this._schemaDefinition=r}else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.");this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition);function n(r){return typeof r=="object"&&r!=null&&!("spec"in r)&&!fe(r)}n(e)?(fe(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):fe(e)&&(this._configRuntimeSchema=e)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([t,e])=>t.map(n=>[n,e]))])}_addSchema(t){if(!this._schemaDefinitions.has(t)){this._schemaDefinitions.set(t,t);for(const[e,n]of Object.entries(t)){let r;if(typeof n=="function"?r=n():r=n,this.channels[e]!==void 0){if(this.channels[e]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=r}}}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([r,s])=>[r,s]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[q,ze])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===P||r===D)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;o?.input!==void 0&&(fe(o.input)?i=this._metaRegistry.getChannelsForSchema(o.input):o.input.spec!==void 0&&(i=o.input.spec)),i!==void 0&&this._addSchema(i);let a;Q.isRunnable(s)?a=s:typeof s=="function"?a=new mt({func:s,name:r,trace:!1}):a=zt(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:no(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===P)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===P)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]===Ue?Ue:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===Ue?Ue:c,h=this._interrupt,d=new tp({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[D]:new qt},inputChannels:D,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:h});d.attachNode(D);for(const[f,g]of Object.entries(this.nodes))d.attachNode(f,g);d.attachBranch(D,Eo,Do(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,Eo,Do(),{withReader:!1});for(const[f,g]of this.edges)d.attachEdge(f,g);for(const[f,g]of this.waitingEdges)d.attachEdge(f,g);for(const[f,g]of Object.entries(this.branches))for(const[p,S]of Object.entries(g))d.attachBranch(f,p,S);return d.validate()}};function ep(t){const e={};for(const[n,r]of Object.entries(t))e[n]=ws(r);return e}var tp=class extends ll{description;_metaRegistry=Jt;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===D?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function r(a){if(X(a))return a.graph===K.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>X(l))){const l=[];for(const c of a)if(X(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([Ue,c]);return l}else if(a!=null)return[[Ue,a]];return null}const s=t;function o(a){if(a){if(X(a))return a.graph===K.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(X)){const l=[];for(const c of a)if(X(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 B(`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:ut,mapper:new mt({func:n.length&&n[0]===Ue?r:o,trace:!1,recurse:!1})}];if(t===D)this.nodes[t]=new wn({tags:[G],triggers:[D],channels:[D],writers:[new oe(i,[G])]});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&&Ue in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new Ed:new qt(!1),this.nodes[t]=new wn({triggers:[u],channels:c?Object.keys(l):l,writers:[new oe(i,[G])],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!==P){if(typeof t=="string")this.nodes[t].writers.push(new oe([{channel:`branch:to:${e}`,value:null}],[G]));else if(Array.isArray(t)){const n=`join:${t.join("+")}:${e}`;this.channels[n]=this.builder.nodes[e].defer?new Yf(new Set(t)):new Jf(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new oe([{channel:n,value:r}],[G]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(c=>c!==P);if(!a.length)return;const l=a.map(c=>me(c)?c:{channel:c===P?c:`branch:to:${c}`,value:t});await oe.doWrite({...i,tags:(i.tags??[]).concat([G])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>of.doRead(o,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=o=>{if(o!=null)return this._metaRegistry.getExtendedChannelSchemas(o,{withReducerSchema:!0})};if(fe(n))return s(n);if(n===Es)return Is(s(r))})();if(X(t)){const n=t;return t.update&&e!=null&&(n.update=Xe(e,t.update)),n}return e!=null?Xe(e,t):t}isInterrupted(t){return Fa(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return fe(e)&&Xe(e,t),t}};function np(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||$a(e))}function Lo(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function rp(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function sp(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function op(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function ip(t){return!(typeof t!="object"||t==null||!("state"in t)||!fe(t.state)||"input"in t&&!fe(t.input)||"output"in t&&!fe(t.output))}function ap(t){if(me(t))return[t];const e=[];X(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(X));const n=[];for(const r of e){if(r.graph===K.PARENT)throw new Ia(r);me(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Do(){const t=new mt({func:ap,tags:[G],trace:!1,recurse:!1,name:"<control_branch>"});return new al({path:t})}const hl="__remove_all__";function dl(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(dn),o=r.map(dn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=tr(),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=tr(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===hl&&(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))}ys.Root({messages:ys({reducer:dl,default:()=>[]})});const gr={reducer:{fn:dl},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:Yt(le(),gr)});Sd();const xs=Symbol.for("langgraph-zod");xs in globalThis||(globalThis[xs]=new WeakSet);function Fo(t){const e=globalThis[xs];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Yt(n,{jsonSchemaExtra:r})},reducer(r,s){const o=Ns(n);return Yt(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Fo(Hc.prototype),Fo(Dl.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var lp=class extends Fl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Ns(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new lp(Jt);function cp(t=!0,e,n=[]){const r={messages:Yt(le(),gr),jumpTo:Ie([Ct("model_request"),Ct("tools"),Ct("end"),Wc()]).optional()},s=a=>{const{shape:l}=a;for(const[c,u]of Object.entries(l))c.startsWith("_")||c in r||(r[c]=u)};e&&"shape"in e&&s(e);for(const a of n)a.stateSchema&&s(a.stateSchema);t&&(r.structuredResponse=$s().optional());const o=z(r);return Jt.getChannelsForSchema(o)}z({llmInputMessages:Yt(le(),{reducer:{fn:(t,e)=>gr.reducer.fn([],e)},default:()=>[]}),messages:Yt(le(),gr)});const Uo="prompt",Jr=/<name>(.*?)<\/name>/s,Yr=/<content>(.*?)<\/content>/s;function up(t){if(!O.isInstance(t)||Vt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new O({...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 O({...t.lc_kwargs,content:n,name:void 0})}function hp(t){if(!O.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(Jr),o=r.text.match(Yr);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(Jr),o=r.text.match(Yr);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(Jr),o=r.match(Yr);if(!s||!o)return t;n=s[1],e=o[1]}return new O({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function H(t){return Q.isRunnable(t)}function Vo(t){return js(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const Xr=(t,e,n={})=>{if(Vo(t))return t.bindTools(e,n);if(Oe.isRunnableBinding(t)&&Vo(t.bound)){const r=t.bound.bindTools(e,n);return Oe.isRunnableBinding(r)?new Oe({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Oe({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function fl(t){if(typeof t=="function")return;let e=t;if(tt.isRunnableSequence(e)&&(e=e.steps.find(n=>Oe.isRunnableBinding(n))||e),!or(e)){if(Oe.isRunnableBinding(e)){const n=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,r=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(n||r)throw new rs}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new rs}}function Ms(t){return!!(O.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function dp(t){let e;if(t==null)e=Bt.from(n=>n.messages).withConfig({runName:Uo});else if(typeof t=="string"){const n=new _e(t);e=Bt.from(r=>[n,...r.messages??[]]).withConfig({runName:Uo})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function fp(t,e,n={}){const r=Xr(t,e,n);if(r)return r;if(or(t)){const s=Xr(await t._model(),e,n);if(s)return s}if(tt.isRunnableSequence(t)){const s=t.steps.findIndex(o=>Oe.isRunnableBinding(o)||js(o)||or(o));if(s>=0){const o=Xr(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),tt.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function pp(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 mp(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return pp(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?Xe(n.stateSchema,{...o.state}):{}}},i);if(!U.isInstance(a)&&!X(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 gp(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=Gc(r.stateSchema,a=>a.startsWith("_")),o=await Kc(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(`
35
+ `),super(n),this.lc_error_code=e?.lc_error_code}},Na=class extends ft{get is_bubble_up(){return!0}},Ad=class extends ft{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Wn=class extends ft{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},kt=class extends Na{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},Ia=class extends kt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},$a=class extends Na{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function Pd(t){return t!==void 0&&t.name===$a.unminifiable_name}function Hn(t){return t!==void 0&&t.is_bubble_up===!0}function at(t){return t!==void 0&&[kt.unminifiable_name,Ia.unminifiable_name].includes(t.name)}var To=class extends ft{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Z=class extends ft{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ft{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Od=class extends ft{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function Ra(t){return t!=null&&t.lg_is_channel===!0}var pt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===Z.unminifiable_name)return!1;throw t}}};const ms=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function Xs(t){if(t[ms]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];Ra(r)&&(e[n]=r)}return Object.assign(e,{[ms]:!0}),e}function hr(t,e){const n=Xs(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,{[ms]:!0}),r}function ot(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{s[o]=e[o].checkpoint()}catch(i){if(i.name!==Z.unminifiable_name)throw i}}return{v:4,id:r?.id??bi(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var gs=class ja extends pt{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 ja(this.operator,this.initialValueFactory);return typeof e<"u"&&(n.value=e),n}update(e){let n=e;if(!n.length)return!1;this.value===void 0&&([this.value]=n,n=n.slice(1));for(const r of n)this.value!==void 0&&(this.value=this.operator(this.value,r));return!0}get(){if(this.value===void 0)throw new Z;return this.value}checkpoint(){if(this.value===void 0)throw new Z;return this.value}isAvailable(){return this.value!==void 0}},Zs=class La extends pt{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new La;return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new B("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Z;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Z;return this.value[0]}isAvailable(){return this.value.length!==0}},Nd=class Da extends pt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new Da;if(typeof e<"u"){const[r,s]=e;n.value=[r],n.finished=s}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Z;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},Id=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const ys=function(t){return t?ws(t):new Zs};ys.Root=t=>new Id(t);function ws(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new gs(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new gs(t.value,t.default):new Zs}const D="__start__",P="__end__",Le="__input__",$d="__copy__",ae="__error__",Fr="__pregel_ns_writes",Qe="__pregel_send",Qs="__pregel_call",ct="__pregel_read",H="__pregel_checkpointer",Ke="__pregel_resuming",cn="__pregel_task_id",dr="__pregel_stream",Rd="__pregel_resume_value",Gn="__pregel_resume_map",et="__pregel_scratchpad",Kn="__pregel_previous",Fa="__pregel_durability",vs="checkpoint_id",Pe="checkpoint_ns",jd="__pregel_node_finished",ye="checkpoint_map",Eo="__pregel_abort_signals",L="__interrupt__",ce="__resume__",eo="__no_writes__",Gt="__return__",Ur="__previous__",G="langsmith:hidden",Ld="langsmith:nostream",xo="__self__",ve="__pregel_tasks",de="__pregel_push",qn="__pregel_pull",be="00000000-0000-0000-0000-000000000000",Dd=[G,Le,L,ce,ae,eo,Qe,ct,H,Fa,dr,Ke,cn,Qs,Rd,et,Kn,ye,Pe,vs],q="|",ze=":",Mo=Symbol.for("langgraph.command");var Fd=class{[Mo];constructor(t){this[Mo]=t}};function bs(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var se=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=yn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function me(t){return t instanceof se}function Ua(t){return!t||typeof t!="object"||!(L in t)?!1:Array.isArray(t[L])}var K=class extends Fd{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)?yn(t.goto):[yn(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:me(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function X(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function yn(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]=yn(r,e)});else if(X(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(bs(t)&&!(t instanceof se))n=new se(t.node,t.args),e.set(t,n);else if(X(t)||me(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=yn(s,e)}return n}return t}const Ud=["tags","metadata","callbacks","configurable"],Vd=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Bd=25;function Va(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Bd,configurable:{}},n=Ve.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(Ud.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&&Vd.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 zd(){return Ve.getRunnableConfig()}function Vr(t){return t.split(q).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(ze)[0]).join(q)}function Wd(t){const e=t.split(q);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(q)}const E=t=>BigInt(t),F=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Ba=E("0x9E3779B1"),za=E("0x85EBCA77"),Hd=E("0xC2B2AE3D"),nt=E("0x9E3779B185EBCA87"),ht=E("0xC2B2AE3D27D4EB4F"),Wa=E("0x165667B19E3779F9"),to=E("0x85EBCA77C2B2AE63"),Gd=E("0x27D4EB2F165667C5"),Kd=E("0x165667919E3779F9"),qd=E("0x9FB21C651E98DF25"),Jd=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 F(r)},Ae=Jd("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Tt=(E(1)<<E(128))-E(1),$=(E(1)<<E(64))-E(1),fr=(E(1)<<E(32))-E(1),De=64,Ha=De/8,Yd=8,An=4;function Kt(t){if(!t)throw new Error("Assert failed")}function Xd(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Zd(t){let e=t;return e=(e&E(65535))<<E(16)|(e&E(4294901760))>>E(16),e=(e&E(16711935))<<E(8)|(e&E(4278255360))>>E(8),e}function Qd(t,e){return(t&fr)*(e&fr)&$}function ef(t,e){return(t<<e|t>>E(32)-e)&fr}function Ga(t,e,n){for(let r=0;r<Ha;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Qd(o,o>>E(32))}return t}function Ao(t,e,n,r){for(let s=0;s<r;s+=1)Ga(t,F(e,s*De),F(n,s*8));return t}function tf(t,e){for(let n=0;n<Ha;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=_s(s,E(47)),s^=r,s*=Ba,t[n]=s&$}return t}function Pn(t,e){return Ka(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Yd,!0))}function Po(t,e,n){let r=n;return r+=Pn(t.slice(0),F(e,0*An)),r+=Pn(t.slice(2),F(e,4*An)),r+=Pn(t.slice(4),F(e,8*An)),r+=Pn(t.slice(6),F(e,12*An)),Ne(r&$)}function nf(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-De)/8),a=De*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=Ao(o,F(e,c*a),n,i),o=s(o,F(n,n.byteLength-De));{const c=Math.floor((e.byteLength-1-a*l)/De);o=Ao(o,F(e,l*a),n,c),o=r(o,F(e,e.byteLength-De),F(n,n.byteLength-De-7))}return o}function rf(t,e){let n=new BigUint64Array([Hd,nt,ht,Wa,to,za,Gd,Ba]);Kt(t.byteLength>128),n=nf(n,t,e,Ga,tf),Kt(n.length*8===64);{const r=Po(n,F(e,11),E(t.byteLength)*nt&$);return Po(n,F(e,e.byteLength-De-11),~(E(t.byteLength)*ht)&$)<<E(64)|r}}function Ka(t,e){const n=t*e&Tt;return n&$^n>>E(64)}function Oo(t,e,n){return Ka((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&$,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&$)}function Jn(t,e,n,r,s){let o=t&$,i=t>>E(64)&$;return o+=Oo(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=$,i+=Oo(n,F(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=$,i<<E(64)|o}function Ne(t){let e=t;return e^=e>>E(37),e*=Kd,e&=$,e^=e>>E(32),e}function pr(t){let e=t;return e^=e>>E(33),e*=ht,e&=$,e^=e>>E(29),e*=Wa,e&=$,e^=e>>E(32),e}function sf(t,e,n){const r=t.byteLength;Kt(r>0&&r<=3);const s=E(t.getUint8(r-1))|E(r<<8)|E(t.getUint8(0)<<16)|E(t.getUint8(r>>1)<<24),o=(E(e.getUint32(0,!0))^E(e.getUint32(4,!0)))+n,i=(s^o)&$,a=(E(e.getUint32(8,!0))^E(e.getUint32(12,!0)))-n,l=(ef(Zd(s),E(13))^a)&$;return(pr(l)&$)<<E(64)|pr(i)}function _s(t,e){return t^t>>e}function of(t,e,n){const r=t.byteLength;Kt(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0),i=E(s)|E(o)<<E(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&$;let c=(i^a)*(nt+(E(r)<<E(2)))&Tt;return c+=(c&$)<<E(65),c&=Tt,c^=c>>E(67),_s(_s(c&$,E(35))*qd&$,E(28))|Ne(c>>E(64))<<E(64)}}function af(t,e,n){const r=t.byteLength;Kt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&$,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&$,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*nt;const c=(l&$)+(E(r-1)<<E(54));l=l&(Tt^$)|c,a^=o,l+=a+(a&fr)*(za-E(1))<<E(64),l&=Tt,l^=Xd(l>>E(64));let u=(l&$)*ht;return u+=(l>>E(64))*ht<<E(64),u&=Tt,Ne(u&$)|Ne(u>>E(64))<<E(64)}}function lf(t,e){const n=t.byteLength;return Kt(n<=16),n>8?af(t,Ae,e):n>=4?of(t,Ae,e):n>0?sf(t,Ae,e):pr(e^Ae.getBigUint64(64,!0)^Ae.getBigUint64(72,!0))|pr(e^Ae.getBigUint64(80,!0)^Ae.getBigUint64(88,!0))<<E(64)}function Ss(t){return~t+E(1)&$}function cf(t,e,n){let r=E(t.byteLength)*nt&$,s=E(t.byteLength-1)/E(32);for(;s>=0;){const a=Number(s);r=Jn(r,F(t,16*a),F(t,t.byteLength-16*(a+1)),F(e,32*a),n),s-=E(1)}let o=r+(r>>E(64))&$;o=Ne(o);let i=(r&$)*nt+(r>>E(64))*to+(E(t.byteLength)-n&$)*ht;return i&=$,i=Ss(Ne(i)),o|i<<E(64)}function uf(t,e,n){let r=E(t.byteLength)*nt&$;for(let i=32;i<160;i+=32)r=Jn(r,F(t,i-32),F(t,i-16),F(e,i-32),n);r=Ne(r&$)|Ne(r>>E(64))<<E(64);for(let i=160;i<=t.byteLength;i+=32)r=Jn(r,F(t,i-32),F(t,i-16),F(e,3+i-160),n);r=Jn(r,F(t,t.byteLength-16),F(t,t.byteLength-32),F(e,103),Ss(n));let s=r+(r>>E(64))&$;s=Ne(s);let o=(r&$)*nt+(r>>E(64))*to+(E(t.byteLength)-n&$)*ht;return o&=$,o=Ss(Ne(o)),s|o<<E(64)}function st(t,e=E(0)){const n=new TextEncoder,r=F(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(lf(r,e)):s<=128?o(cf(r,Ae,e)):s<=240?o(uf(r,Ae,e)):o(rf(r,Ae))}function qa(t){return/^[0-9a-f]{32}$/.test(t)}function Ja(t){const e=Ve.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const n=e.configurable;if(!n)throw new Error("No configurable found in config");if(!n[H])throw new Wn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[et];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[Qe]?.([[ce,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[Qe]?.([[ce,s.resume]]),l}const i=n[Pe]?.split(q),a=i?st(i.join(q)):void 0;throw new kt([{id:a,value:t}])}var mt=class extends Q{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,n,r){return new Promise((s,o)=>{const i=ln(n,{callbacks:r?.getChild()});Ve.runWithConfig(i,async()=>{try{const a=await this.func(e,i);s(a)}catch(a){o(a)}})})}async invoke(e,n){let r;const s=Va(n),o=Fe(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await Ve.runWithConfig(o,async()=>this.func(e,o)),Q.isRunnable(r)&&this.recurse?await Ve.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*He(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function qe(t){const e=[];for await(const n of await t)e.push(n);return e}function sn(t){const e=[];for(const n of t)e.push(n);return e}function yt(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function hf(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const ut={[Symbol.for("LG_PASSTHROUGH")]:!0};function On(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Br=Symbol("IS_WRITER");var oe=class Cs extends mt{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>me(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:e,name:r,tags:n,func:async(s,o)=>this._write(s,o??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>zr(s)&&On(s.value)?{mapper:s.mapper,value:e}:Yn(s)&&On(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Cs.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(Yn(o)){if(o.channel===ve)throw new B("Cannot write to the reserved channel TASKS");if(On(o.value))throw new B("PASSTHROUGH value must be replaced")}if(zr(o)&&On(o.value))throw new B("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(me(o))r.push([ve,o]);else if(zr(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(Yn(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(hf(i)||o.skipNone&&i===void 0)continue;r.push([o.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);const s=e.configurable?.[Qe];s(r)}static isWriter(e){return e instanceof Cs||Br in e&&!!e[Br]}static registerWriter(e){return Object.defineProperty(e,Br,{value:!0})}};function Yn(t){return t!==void 0&&typeof t.channel=="string"}function zr(t){return t!==void 0&&!Yn(t)&&Q.isRunnable(t.mapper)}var df=class Ya extends mt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Ya.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?.[ct];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 wt=new hc;var wn=class on extends Oe{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=wt;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,g=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??wt,config:{...e.config?e.config:{},tags:g}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=o??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=g,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 oe&&e[e.length-2]instanceof oe;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new oe(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===wt&&e.length===0))return this.bound===wt&&e.length===1?e[0]:this.bound===wt?new tt({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new tt({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 on({channels:{...this.channels,...Object.fromEntries(e.map(n=>[n,n]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(e){return oe.isWriter(e)?new on({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===wt?new on({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:zt(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new on({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 ff(t){return"steps"in t&&Array.isArray(t.steps)}function no(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Xa(t){const e=[t];for(const n of e){if(no(n))return n;ff(n)&&e.push(...n.steps)}}function Et(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===Z.unminifiable_name){if(r)return s;if(n)return null}throw s}}function dt(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Et(t,s,!n)}catch(o){if(o.name===Z.unminifiable_name)continue}return r}else return Et(t,e)}function*pf(t,e){if(t.graph===K.PARENT)throw new B("There is no parent graph.");if(t.goto){let n;Array.isArray(t.goto)?n=t.goto:n=[t.goto];for(const r of n)if(me(r))yield[be,ve,r];else if(typeof r=="string")yield[be,`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(qa))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===ce).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,ce,s]}else yield[be,ce,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[be,n,r];else for(const[n,r]of Object.entries(t.update))yield[be,n,r]}}function*Za(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*Wr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield dt(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Et(n,t))}function*mf(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(G))&&l[0][0]!==ae&&l[0][0]!==L);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===Gt))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===Gt).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 ro(t){const e=typeof t[D];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 Xn(t,e){if(Object.keys(t).length>0){const n=ro(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 Ce(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function rt(t,e){const n=e?.parents??{};return Object.keys(n).length>0?Ce(t,{[ye]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function mr(...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 yf=(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 wf=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 vf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function bf(t,e){const n=new mt({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new tt({name:t,first:n,last:new oe([{channel:Gt,value:ut}],[G])})}const _f=t=>t!==void 0?t+1:1;function Sf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function Cf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=vd(e,t[n]));return e}function Nn(t,e,n){const r=ro(t.channel_versions),s=t.versions_seen[L]??{};let o=!1;if((t.channel_versions[D]??r)>(s[D]??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(G):e.includes(a.name));return o&&i}function Zn(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=ot(t,a,-1),c=hr(a,l);he(ur(l),c,[n],void 0,void 0),i=dt({...e,...c},r)}else i=dt(e,r);return i}function Hr(t,e,n){for(const[r,s]of n)if([de,ve].includes(r)&&s!=null){if(!me(s))throw new B(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new B(`Invalid node name "${s.node}" in Send packet`)}t(n)}const kf=new Set([eo,de,ce,L,Gt,ae]);function he(t,e,n,r,s){n.sort((d,f)=>{const g=d.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let S=0;S<Math.min(g.length,p.length);S+=1){if(g[S]<p[S])return-1;if(g[S]>p[S])return 1}return g.length-p.length});const o=n.some(d=>d.triggers.length>0),i=Xs(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=Cf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!Dd.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,g]of d.writes)kf.has(f)||f in i&&(u[f]??=[],u[f].push(g));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 g=i[d];let p;try{p=g.update(f)}catch(S){if(S.name===B.unminifiable_name){const C=new B(`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}p&&r!==void 0&&(t.channel_versions[d]=r(a),g.isAvailable()&&h.add(d))}if(o)for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.isAvailable()&&!h.has(d)&&f.update([])&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}if(o&&!Sf(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*Tf(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 St(t,e,n,r,s,o,i){const a={},l=r[ve];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const h=ks([de,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const c of Tf(t,n,i)){const u=ks([qn,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function ks(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]===de&&vf(t[t.length-1])){const f=t[t.length-1],g=bf(f.name,f.func),p=[de],S=d===""?f.name:`${d}${q}${f.name}`,C=vt(JSON.stringify([S,l.toString(),f.name,de,t[1],t[2]]),e.id),y=`${S}${ze}${C}`,_=[...t.slice(0,3),!0],b={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:_,langgraph_checkpoint_ns:y};if(i){const k=[];return{name:f.name,input:f.input,proc:g,writes:k,config:ln(Fe(o,{metadata:b,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:C,[Qe]:w=>Hr(v=>k.push(...v),r,w),[ct]:(w,v=!1)=>Zn(e,s,{name:f.name,writes:k,triggers:p,path:_},w,v),[H]:c??h[H],[ye]:{...h[ye],[d]:e.id},[et]:Gr({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:o.configurable?.[Gn],namespaceHash:st(y)}),[Kn]:e.channel_values[Ur],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:st((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Fr,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:C,path:_,writers:[]}}else return{id:C,name:f.name,interrupts:[],path:_}}else if(t[0]===de){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[ve]?.isAvailable())return;const g=s[ve].get();if(f<0||f>=g.length)return;const p=bs(g[f])&&!me(g[f])?new se(g[f].node,g[f].args):g[f];if(!bs(p)){console.warn(`Ignoring invalid packet ${JSON.stringify(p)} in pending sends.`);return}if(!(p.node in r)){console.warn(`Ignoring unknown node name ${p.node} in pending sends.`);return}const S=[de],C=d===""?p.node:`${d}${q}${p.node}`,y=vt(JSON.stringify([C,l.toString(),p.node,de,f.toString()]),e.id),_=`${C}${ze}${y}`;let b={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:S,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:_};if(i){const k=r[p.node],M=k.getNode();if(M!==void 0){k.metadata!==void 0&&(b={...b,...k.metadata});const w=[];return{name:p.node,input:p.args,proc:M,subgraphs:k.subgraphs,writes:w,config:ln(Fe(o,{metadata:b,tags:k.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:y,[Qe]:v=>Hr(T=>w.push(...T),r,v),[ct]:(v,T=!1)=>Zn(e,s,{name:p.node,writes:w,triggers:S,path:t},v,T),[H]:c??h[H],[ye]:{...h[ye],[d]:e.id},[et]:Gr({pendingWrites:n??[],taskId:y,currentTaskInput:p.args,resumeMap:o.configurable?.[Gn],namespaceHash:st(_)}),[Kn]:e.channel_values[Ur],checkpoint_id:void 0,checkpoint_ns:_}}),triggers:S,retry_policy:k.retryPolicy,cache_key:k.cachePolicy?{key:st((k.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[Fr,k.name??"__dynamic__",p.node],ttl:k.cachePolicy.ttl}:void 0,id:y,path:t,writers:k.getWriters()}}}else return{id:y,name:p.node,interrupts:[],path:t}}else if(t[0]===qn){const f=t[1].toString(),g=r[f];if(g===void 0)return;if(n?.length){const y=d===""?f:`${d}${q}${f}`,_=vt(JSON.stringify([y,l.toString(),f,qn,f]),e.id);if(n.some(k=>k[0]===_&&k[1]!==ae))return}const p=ro(e.channel_versions);if(p===void 0)return;const S=e.versions_seen[f]??{},C=g.triggers.find(y=>s[y].isAvailable()?(e.channel_versions[y]??p)>(S[y]??p):!1);if(C!==void 0){const y=Ef(g,s,i);if(y===void 0)return;const _=d===""?f:`${d}${q}${f}`,b=vt(JSON.stringify([_,l.toString(),f,qn,[C]]),e.id),k=`${_}${ze}${b}`;let M={langgraph_step:l,langgraph_node:f,langgraph_triggers:[C],langgraph_path:t,langgraph_checkpoint_ns:k};if(i){const w=g.getNode();if(w!==void 0){g.metadata!==void 0&&(M={...M,...g.metadata});const v=[];return{name:f,input:y,proc:w,subgraphs:g.subgraphs,writes:v,config:ln(Fe(o,{metadata:M,tags:g.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:b,[Qe]:T=>Hr(x=>{v.push(...x)},r,T),[ct]:(T,x=!1)=>Zn(e,s,{name:f,writes:v,triggers:[C],path:t},T,x),[H]:c??h[H],[ye]:{...h[ye],[d]:e.id},[et]:Gr({pendingWrites:n??[],taskId:b,currentTaskInput:y,resumeMap:o.configurable?.[Gn],namespaceHash:st(k)}),[Kn]:e.channel_values[Ur],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:[C],retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:st((g.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[Fr,g.name??"__dynamic__",f],ttl:g.cachePolicy.ttl}:void 0,id:b,path:t,writers:g.getWriters()}}}else return{id:b,name:f,interrupts:[],path:t}}}}function Ef(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]=Et(e,o,!1)}catch(i){if(i.name===Z.unminifiable_name)return;throw i}else if(o in e)try{r[s]=Et(e,o,!1)}catch(i){if(i.name===Z.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=Et(e,o,!1),s=!0;break}catch(i){if(i.name===Z.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function Gr({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([l,c])=>l===be&&c===ce)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const l=t.filter(([c,u])=>c===e&&u===ce).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===be&&c===ce),1),o}};return a}const vn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},bn=(t,e)=>`${t.start}${e}${t.end}`;function*No(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t){if(s?.tags?.includes(G))continue;const a=i.filter(([l,c])=>l===e&&c===L).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:o,interrupts:a}}}function xf(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Qa(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=xf(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*Mf(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(G)||(yield{id:n,name:r,result:Qa(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===L).map(i=>i[1])})}function*Af(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(Xa))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:dt(e,n),metadata:r,next:s.map(h=>h.name),tasks:el(s,o,u,a),parentConfig:i?l(i):void 0}}function el(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===ae)?.[2],i=e.filter(([c,u])=>c===s.id&&u===L).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,h])=>u===s.id&&h===Gt);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?Qa(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 Pf(t,e,n){console.log([`${bn(vn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
36
+ `,JSON.stringify(dt(e,n),null,2)].join(""))}function tl(t,e){const n=e.length;console.log([`${bn(vn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
37
+ `,e.map(r=>`- ${bn(vn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
38
+ `)].join(""))}function Of(t,e,n){const r={};for(const[s,o]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(o));console.log([`${bn(vn.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
39
+ `,Object.entries(r).map(([s,o])=>`- ${bn(vn.yellow,s)} -> ${o.map(i=>JSON.stringify(i)).join(", ")}`).join(`
40
+ `)].join(""))}var Io=class extends hn{_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}},nl=class extends hn{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 Nf(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 If(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function so(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Kr(t){return!so(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 $o(t){if(so(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 Ro(t){const e={...t,checkpoint:Kr(t.config),parent_checkpoint:Kr(t.parentConfig),config:$o(t.config),parent_config:$o(t.parentConfig),tasks:t.tasks.map(n=>{if(so(n.state)){const r=Kr(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function $f(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
41
+ data: ${Nf(s.data)}
42
+
43
+ `))};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:Ro(u.payload)})}i==="checkpoints"&&(l=Ro(a));const c=o?.length?`${i}|${o.join("|")}`:i;r({event:c,data:l})}}catch(s){r({event:"error",data:If(s)})}n.close()}})}const In=Symbol.for("INPUT_DONE"),qr=Symbol.for("INPUT_RESUMING"),Rf=25;function jf(...t){return new nl({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 Lf=class extends Td{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}},Df=class rl{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(D 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?.[Ke]!==void 0&&this.config.configurable?.[Ke],s=this.input===null||this.input===void 0,o=X(this.input)&&this.input.resume!=null,i=this.input===qr,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=_f,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 Lf(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?.[dr]!==void 0&&(r=jf(r,n.configurable[dr]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[et];n.configurable&&o&&(o.subgraphCounter>0&&(n=Ce(n,{[Pe]:[n.configurable[Pe],o.subgraphCounter.toString()].join(q)})),o.subgraphCounter+=1);const i=ct in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=Ce(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ye]!==void 0&&n.configurable?.[ye]?.[n.configurable?.checkpoint_ns]&&(a=Ce(n,{checkpoint_id:n.configurable[ye][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(q)??[],c=await e.checkpointer?.getTuple(a)??{config:n,checkpoint:Aa(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,h=ur(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],g=hr(e.channelSpecs,h),p=(d.step??0)+1,S=p+(n.recursionLimit??Rf)+1,C={...h.channel_versions},y=e.store?new kd(e.store):void 0;return y&&await y.start(),new rl({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:g,isNested:i,manager:e.manager,skipDoneTasks:s,step:p,stop:S,checkpointPreviousVersions:C,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:y,cache:e.cache,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,durability:e.durability,debug:e.debug,triggerToNodes:e.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(e,n){let r=n;if(r.length===0)return;r.every(([i])=>i in bd)&&(r=Array.from(new Map(r.map(i=>[i[0],i])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(i=>i[0]!==e);for(const[i,a]of r)this.checkpointPendingWrites.push([e,i,a]);const s=Ce(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??"",[vs]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(s,r,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||n[0][0]===ae||n[0][0]===L||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,n,r=!1){const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(G))return;if(n.length>0)if(n[0][0]===L){if(s.path?.[0]===de&&s.path?.at(-1)===!0)return;const o=n.filter(i=>i[0]===L).flatMap(i=>i[1]);this._emit([["updates",{[L]:o}],["values",{[L]:o}]])}else n[0][0]!==ae&&this._emit(sn(He(mf(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(sn(He(Mf([[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(![In,qr].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new kt;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await qe(He(Wr(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),Nn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new kt;this.config.configurable?.[Ke]!==void 0&&delete this.config.configurable?.[Ke]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=St(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 qe(He(Af(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[o,i,a]of this.checkpointPendingWrites){if(i===ae||i===L||i===ce)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(Nn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new kt;const s=await qe(He(No(Object.values(this.tasks)),"tasks"));return this._emit(s),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(r=>!r.includes(ze)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=dt(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(sn(He(Wr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),at(e)&&!e.interrupts.length&&this._emit([["updates",{[L]:[]}],["values",{[L]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&Nn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=ks([de,e.path??[],n,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!s)return;if(this.interruptBefore?.length>0&&Nn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(sn(He(No([s]),"tasks"))),this.debug&&tl(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 at(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[et];if(r&&r.nullResume!==void 0&&this.putWrites(be,[[ce,r.nullResume]]),X(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(qa)&&(this.config.configurable??={},this.config.configurable[Gn]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of pf(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new To("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===be).map(i=>i.slice(1));s.length>0&&he(this.checkpoint,this.channels,[{name:Le,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=X(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[L]={...this.checkpoint.versions_seen[L],[a]:l}}const i=await qe(He(Wr(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=qr;else if(o)await this._putCheckpoint({source:"input"}),this.input=In;else{const i=await qe(Za(e,this.input));if(i.length>0){const a=St(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=he(this.checkpoint,this.channels,Object.values(a).concat([{name:Le,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=In}else if(Ke in(this.config.configurable??{}))this.input=In;else throw new To(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Ce(this.config,{[Ke]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Ce(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=Xn(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ur(o),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.[ye]??{}}),this.checkpoint=ot(this.checkpoint,r?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),r&&s(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=Ce(this.checkpointConfig,{[Pe]:this.config.configurable?.checkpoint_ns??"",[vs]:this.checkpoint.id}),n={};for(const[r,s,o]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,o]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,s,r))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r===ae||r===L||r===ce)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 Ff(t){return je(t?.message)}var Uf=class extends Bc{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&&(zc(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(Ld)&&!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&&(Ff(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new Vt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];je(n?.message)&&this._emit(this.metadatas[e],n?.message,e,!0),delete this.emittedChatModelRunIds[e]}delete this.metadatas[e],delete this.stableMessageIdMap[e]}}handleLLMError(t,e){delete this.metadatas[e]}handleChainStart(t,e,n,r,s,o,i,a){if(o!==void 0&&a===o.langgraph_node&&(s===void 0||!s.includes(G))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const l of Object.values(e))if((je(l)||fo(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(je(c)||fo(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(je(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)je(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(je(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)je(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const Vf=500,Bf=2,zf=128e3,Wf=3,Hf=[400,401,402,403,404,405,406,407,409],Gf=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&&Hf.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??Vf:0,i=0,a,l,{config:c}=t;for(n&&(c=Ce(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,Pd(a)){const g=c?.configurable?.checkpoint_ns,p=a.command;if(p.graph===g){for(const S of t.writers)await S.invoke(p,c);a=void 0;break}else if(p.graph===K.PARENT){const S=Wd(g);a.command=new K({...a.command,graph:S})}}if(Hn(a)||s===void 0||(i+=1,i>=(s.maxAttempts??Wf))||!(s.retryOn??Gf)(a))break;o=Math.min(s.maxInterval??zf,o*(s.backoffFactor??Bf));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;await new Promise(g=>setTimeout(g,d));const f=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${o.toFixed(2)}ms (attempt ${i}) after ${f}: ${a}`),c=Ce(c,{[Ke]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const Ts=Symbol.for("promiseAdded");function Kf(){const t={next:()=>{},wait:Promise.resolve(Ts)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Ts)}}return t.wait=new Promise(e),t}var qf=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(g=>g.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:g,error:p,signalAborted:S}of f)this._commit(g,p),at(p)||Hn(p)&&!at(i)?i=p:p&&(o.size===0||!S)&&(a.abort(),o.add(p));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(g=>g.writes).flat()),o.size===1)throw Array.from(o)[0];if(o.size>1)throw new AggregateError(Array.from(o),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(at(i)||Hn(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[Eo]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=mr(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=Ce(this.loop.config,{[Eo]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=Kf(),i={},a={executingTasksMap:i,barrier:o,retryPolicy:n,scheduleTask:async(d,f,g)=>this.loop.acceptPush(d,f,g)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=mr(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,{[Qs]:ol?.bind(a,this,f)},s?.composedAbortSignal).catch(g=>({task:f,error:g,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(i),...h?[h]:[],o.wait]);d!==Ts&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[d.task.id])}}_commit(t,e){if(e!==void 0)if(at(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[L,s]),r=t.writes.filter(s=>s[0]===ce);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Hn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[ae,{message:e.message,name:e.name}]]);else this.nodeFinished&&(t.config?.tags==null||!t.config.tags.includes(G))&&this.nodeFinished(String(t.name)),t.writes.length===0&&t.writes.push([eo,null]),this.loop.putWrites(t.id,t.writes)}};async function ol(t,e,n,r,s,o={}){const i=e.config?.configurable?.[et];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new wf({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===Gt),d=c.writes.filter(([f])=>f===ae);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(d.length>0){if(d.length===1){const f=d[0][1],g=f instanceof Error?f:new Error(String(f));return Promise.reject(g)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=sl(c,o.retry,{[Qs]:ol.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 $e=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function Jf({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){if(!e)throw new $e("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===L)throw new $e(`"Node name ${L} is reserved"`);if(u.constructor===wn)u.triggers.forEach(h=>a.add(h));else throw new $e(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new $e(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new $e(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new $e(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(r)?r.forEach(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 $e(`Output channel '${String(c)}' not in channels`);if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new $e(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new $e(`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 Yf=class il extends pt{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 il({unique:this.unique,accumulate:this.accumulate});return typeof e<"u"&&(n.seen=new Set(e[0]),n.values=e[1]),n}update(e){let n=!1;this.accumulate||(n=this.values.length>0,this.values=[]);const r=e.flat();if(r.length>0)if(this.unique)for(const s of r)this.seen.has(s)||(n=!0,this.seen.add(s),this.values.push(s));else n=!0,this.values.push(...r);return n}get(){if(this.values.length===0)throw new Z;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Xf=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 wn({channels:s,triggers:o,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:ut,skipNone:!1});for(const[r,s]of Object.entries(e??{}))Q.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:ut,skipNone:!0,mapper:zt(s)}):n.push({channel:r,value:s,skipNone:!1});return new oe(n)}},Zf=class extends Q{lc_namespace=["langgraph","pregel"];invoke(t,e){throw new Error("Not implemented")}withConfig(t){return super.withConfig(t)}stream(t,e){return super.stream(t,e)}},Qf=class extends Zf{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(t){super(t);let{streamMode:e}=t;if(e!=null&&!Array.isArray(e)&&(e=[e]),this.nodes=t.nodes,this.channels=t.channels,ve in this.channels&&"lc_graph_name"in this.channels[ve]&&this.channels[ve].lc_graph_name!=="Topic")throw new Error(`Channel '${ve}' is reserved and cannot be used in the graph.`);this.channels[ve]=new Yf({accumulate:!1}),this.autoValidate=t.autoValidate??this.autoValidate,this.streamMode=e??this.streamMode,this.inputChannels=t.inputChannels,this.outputChannels=t.outputChannels,this.streamChannels=t.streamChannels??this.streamChannels,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.stepTimeout=t.stepTimeout??this.stepTimeout,this.debug=t.debug??this.debug,this.checkpointer=t.checkpointer,this.retryPolicy=t.retryPolicy,this.config=t.config,this.store=t.store,this.cache=t.cache,this.name=t.name,this.triggerToNodes=t.triggerToNodes??this.triggerToNodes,this.userInterrupt=t.userInterrupt,this.autoValidate&&this.validate()}withConfig(t){const e=Fe(this.config,t);return new this.constructor({...this,config:e})}validate(){Jf({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=Xa(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}${q}${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=hr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===be).map(([d,f,g])=>[String(f),g]);h.length>0&&he(e.checkpoint,s,[{name:Le,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(St(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await qe(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of o){const d=i.find(([g])=>g===h.name);if(!d)continue;let f=`${String(h.name)}${ze}${h.id}`;if(a&&(f=`${a}${q}${f}`),n===void 0){const g={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=g}else{const g={configurable:{[H]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=d[1];l[h.id]=await p.getState(g,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(o.map(f=>[f.id,f]));for(const[f,g,p]of e.pendingWrites)[ae,L,Dn].includes(g)||f in h&&h[f].writes.push([String(g),p]);const d=o.filter(f=>f.writes.length>0);d.length>0&&he(e.checkpoint,s,d,void 0,this.triggerToNodes)}let 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:dt(s,this.streamChannelsAsIs),next:u,tasks:el(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:rt(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[H]??this.checkpointer;if(!n)throw new Wn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const a=Vr(r);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(yt(t,{[H]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Fe(this.config,t),o=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:o,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[H]??this.checkpointer;if(!n)throw new Wn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const o=Vr(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(yt(t,{[H]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=Fe(this.config,t,{configurable:{checkpoint_ns:r}});for await(const o of n.list(s,e))yield this._prepareStateSnapshot({config:o.config,saved:o})}async bulkUpdateState(t,e){const n=t.configurable?.[H]??this.checkpointer;if(!n)throw new Wn("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?.[H]===void 0){const i=Vr(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(yt(t,{[H]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?Fe(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?ur(c.checkpoint):Aa(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=yt(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),g=l.metadata??{};c?.config.configurable&&(f=yt(l,c.config.configurable),g={...c.metadata,...g});const{values:p,asNode:S}=a[0];if(p==null&&S===void 0){if(a.length>1)throw new B("Cannot create empty checkpoint with multiple updates");const w=await n.put(f,ot(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return rt(w,c?c.metadata:void 0)}const C=hr(this.channels,u);if(p===null&&S===P){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const v=St(u,c.pendingWrites||[],this.nodes,C,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),T=(c.pendingWrites||[]).filter(x=>x[0]===be).map(x=>x.slice(1));T.length>0&&he(u,C,[{name:Le,writes:T,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[x,A,I]of c.pendingWrites||[])[ae,L,Dn].includes(A)||x in v&&v[x].writes.push([A,I]);he(u,C,Object.values(v),n.getNextVersion.bind(n),this.triggerToNodes)}const w=await n.put(f,ot(u,C,d),{...g,source:"update",step:d+1,parents:c?.metadata?.parents??{}},Xn(h,u.channel_versions));return rt(w,c?c.metadata:void 0)}if(S===$d){if(a.length>1)throw new B("Cannot copy checkpoint with multiple updates");if(c==null)throw new B("Cannot copy a non-existent checkpoint");const w=x=>!Array.isArray(x)||x.length===0?!1:x.every(A=>Array.isArray(A)&&A.length===2),v=ot(u,void 0,d),T=await n.put(c.parentConfig??yt(c.config,{checkpoint_id:void 0}),v,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(w(p)){const x=St(v,c.pendingWrites,this.nodes,C,T,!1,{step:d+2}),A=Object.values(x).reduce((j,{name:ee,id:re})=>(j[ee]??=[],j[ee].push({id:re}),j),{}),I=p.reduce((j,ee)=>{const[re,Se]=ee;j[Se]??=[];const Me=j[Se].length,xn=A[Se]?.[Me]?.id;return j[Se].push({values:re,asNode:Se,taskId:xn}),j},{});return s(rt(T,c.metadata),Object.values(I).flat())}return rt(T,c.metadata)}if(S===Le){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const w=await qe(Za(this.inputChannels,p));if(w.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);he(u,C,[{name:Le,writes:w,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const v=c?.metadata?.step!=null?c.metadata.step+1:-1,T=await n.put(f,ot(u,C,v),{source:"input",step:v,parents:c?.metadata?.parents??{}},Xn(h,u.channel_versions));return await n.putWrites(T,w,vt(Le,u.id)),rt(T,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const w=St(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(x=>x[0]===be).map(x=>x.slice(1));v.length>0&&he(c.checkpoint,C,[{name:Le,writes:v,triggers:[]}],void 0,this.triggerToNodes);for(const[x,A,I]of c.pendingWrites)[ae,L,Dn].includes(A)||w[x]===void 0||w[x].writes.push([A,I]);const T=Object.values(w).filter(x=>x.writes.length>0);T.length>0&&he(u,C,T,void 0,this.triggerToNodes)}const y=Object.values(u.versions_seen).map(w=>Object.values(w)).flat().find(w=>!!w),_=[];if(a.length===1){let{values:w,asNode:v,taskId:T}=a[0];if(v===void 0&&Object.keys(this.nodes).length===1)[v]=Object.keys(this.nodes);else if(v===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(v=this.inputChannels);else if(v===void 0){const x=Object.entries(u.versions_seen).map(([A,I])=>Object.values(I).map(j=>[j,A])).flat().filter(([A,I])=>I!==L).sort(([A],[I])=>Pa(A,I));x&&(x.length===1?v=x[0][1]:x[x.length-1][0]!==x[x.length-2][0]&&(v=x[x.length-1][1]))}if(v===void 0)throw new B('Ambiguous update, specify "asNode"');_.push({values:w,asNode:v,taskId:T})}else for(const{asNode:w,values:v,taskId:T}of a){if(w==null)throw new B('"asNode" is required when applying multiple updates');_.push({values:v,asNode:w,taskId:T})}const b=[];for(const{asNode:w,values:v,taskId:T}of _){if(this.nodes[w]===void 0)throw new B(`Node "${w.toString()}" does not exist`);const x=this.nodes[w].getWriters();if(!x.length)throw new B(`No writers found for node "${w.toString()}"`);b.push({name:w,input:v,proc:x.length>1?tt.from(x,{omitSequenceTags:!0}):x[0],writes:[],triggers:[L],id:T??vt(L,u.id),writers:[]})}for(const w of b)await w.proc.invoke(w.input,ln({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[Qe]:v=>w.writes.push(...v),[ct]:(v,T=!1)=>Zn(u,C,w,v,T)}}));for(const w of b){const v=w.writes.filter(T=>T[0]!==de);c!==void 0&&v.length>0&&await n.putWrites(f,v,w.id)}he(u,C,b,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const k=Xn(h,u.channel_versions),M=await n.put(f,ot(u,C,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},k);for(const w of b){const v=w.writes.filter(T=>T[0]===de);v.length>0&&await n.putWrites(M,v,w.id)}return rt(M,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 g;n!==void 0?(g=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[cn]!==void 0?g=["values"]:g=this.streamMode,l=!0);let p;if(this.checkpointer===!1)p=void 0;else if(t!==void 0&&t.configurable?.[H]!==void 0)p=t.configurable[H];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");p=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 y=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),_=t.durability??y??t?.configurable?.[Fa]??"async";return[c,g,h,u,a,d,f,p,S,l,C,_]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:mr(e?.signal,n.signal).signal},s=await super.stream(t,r);return new Io(e?.encoding==="text/event-stream"?$f(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:yf(this.config?.callbacks,e?.callbacks),signal:mr(e?.signal,r.signal).signal};return new Io(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=Va(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,g,p,S,C,y]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const _=new nl({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const A=h.configurable[Pe]??"";h.configurable[Pe]=A.split(q).map(I=>I.split(ze)[0]).join(q)}if(c.includes("messages")){const A=new Uf(j=>_.push(j)),{callbacks:I}=h;if(I===void 0)h.callbacks=[A];else if(Array.isArray(I))h.callbacks=I.concat(A);else{const j=I.copy();j.addHandler(A,!0),h.callbacks=j}}h.writer??=A=>{if(!c.includes("custom"))return;const I=zd()?.configurable?.[Pe]?.split(q).slice(0,-1);_.push([I??[],"custom",A])},h.interrupt??=this.userInterrupt??Ja;const k=await(await Wc(h))?.handleChainStart(this.toJSON(),gf(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),M=Xs(this.channels);let w,v;const x=(async()=>{try{w=await Df.initialize({input:o,config:h,checkpointer:g,nodes:this.nodes,channelSpecs:M,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:C,stream:_,interruptAfter:f,interruptBefore:d,manager:k,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});const A=new qf({loop:w,nodeFinished:h.configurable?.[jd]});e?.subgraphs&&(w.config.configurable={...w.config.configurable,[dr]:w.stream}),await this._runLoop({loop:w,runner:A,debug:l,config:h}),y==="sync"&&await Promise.all(w?.checkpointerPromises??[])}catch(A){v=A}finally{try{w&&(await w.store?.stop(),await w.cache?.stop()),await Promise.all(w?.checkpointerPromises??[])}catch(A){v=v??A}v?_.error(v):_.close()}})();try{for await(const A of _){if(A===void 0)throw new Error("Data structure error.");const[I,j,ee]=A;if(c.includes(j)){if(n==="text/event-stream"){r?yield[I,j,ee]:yield[null,j,ee];continue}r&&!S?yield[I,j,ee]:S?r?yield[I,ee]:yield ee:yield[j,ee]}}}catch(A){throw await k?.handleChainError(v),A}finally{await x}await k?.handleChainEnd(w?.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"?Ua(l)?i.push(l[L]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.flat(1);if(a==null)return{[L]:l};if(typeof a=="object")return{...a,[L]: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&&Pf(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&tl(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&Of(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new Ad([`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([])}},qt=class al extends pt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new al(this.guard);return typeof e<"u"&&(n.value=[e]),n}update(e){if(e.length===0){const n=this.value.length>0;return this.value=[],n}if(e.length!==1&&this.guard)throw new B("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new Z;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Z;return this.value[0]}isAvailable(){return this.value.length!==0}},ll=class{path;ends;constructor(t){Q.isRunnable(t.path)?this.path=t.path:this.path=zt(t.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(t.pathMap)?t.pathMap.reduce((e,n)=>(e[n]=n,e),{}):t.pathMap}run(t,e){return oe.registerWriter(new mt({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===Ia.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
44
+ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(t,e,n,r){let s=await this.path.invoke(r?r(e):t,e);Array.isArray(s)||(s=[s]);let o;if(this.ends?o=s.map(a=>me(a)?a:this.ends[a]):o=s,o.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(o.filter(me).some(a=>a.node===P))throw new B("Cannot send a packet to the END node");return await n(o,e)??t}},ep=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[q,ze])if(r.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===P)throw new Error(`Node \`${r}\` is reserved.`);const i=zt(s);this.nodes[r]={runnable:i,metadata:o?.metadata,subgraphs:no(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===P)throw new Error("END cannot be a start node");if(e===D)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([n])=>n===t)&&!("channels"in this))throw new Error(`Already found path for ${t}. For multiple edges, use StateGraph.`);return this.edges.add([t,e]),this}addConditionalEdges(t,e,n){const r=typeof t=="object"?t:{source:t,path:e,pathMap:n};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!Q.isRunnable(r.path)){const o=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=zt(r.path).withConfig({runName:`Branch<${r.source}${o!==""?`,${o}`:""}>`.slice(0,63)})}const s=r.path.getName()==="RunnableLambda"?"condition":r.path.getName();if(this.branches[r.source]&&this.branches[r.source][s])throw new Error(`Condition \`${s}\` already present for node \`${t}\``);return this.branches[r.source]??={},this.branches[r.source][s]=new ll(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(D,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,P)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new cl({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[D]:new qt,[P]:new qt},inputChannels:D,outputChannels:P,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!==D&&!(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(P);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 Od([`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(`
45
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==P&&!(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}},cl=class extends Qf{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new qt,this.nodes[t]=new wn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new oe([{channel:t,value:ut}],[G])),this.streamChannels.push(t)}attachEdge(t,e){if(e===P){if(t===D)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new oe([{channel:P,value:ut}],[G]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===D&&!this.nodes[D]&&(this.nodes[D]=Xf.subscribeTo(D,{tags:[G]})),this.nodes[t].pipe(n.run(s=>{const o=s.map(i=>me(i)?i:{channel:i===P?P:`branch:${t}:${e}:${i}`,value:ut});return new oe(o,[G])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==P){const o=`branch:${t}:${e}:${s}`;this.channels[o]=new qt,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new po,r={[D]:n.addNode({schema:ke()},D)},s={};let o={};e&&(o=Object.fromEntries((await qe(this.getSubgraphsAsync())).filter(l=>Lo(l[1]))));function i(l,c,u,h=!1){if(c===P&&s[P]===void 0&&(s[P]=n.addNode({schema:ke()},P)),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=te(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,g=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let C=function(_){return _?_.lc_runnable:!1},y=function(_,b){if(_!==void 0&&!mo(_))return _;if(C(b))try{let k=b.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return b.getName()}else return b.name??"UnknownSchema"};const[p,S]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:y(S.id,S.data),...S}),s[u]={name:y(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);r[u]=p,s[u]=p}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(te(l),te(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=>[te(h),te(h)])),[P]:P};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))i(te(l),te(g),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)i(te(l),te(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new po,r={[D]:n.addNode({schema:ke()},D)},s={};let o={};e&&(o=Object.fromEntries(sn(this.getSubgraphs()).filter(l=>Lo(l[1]))));function i(l,c,u,h=!1){return c===P&&s[P]===void 0&&(s[P]=n.addNode({schema:ke()},P)),n.addEdge(r[l],s[c],u!==c?u:void 0,h)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=te(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,g=o[l]!==void 0?o[l].getGraph({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let C=function(_){return _?_.lc_runnable:!1},y=function(_,b){if(_!==void 0&&!mo(_))return _;if(C(b))try{let k=b.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return b.getName()}else return b.name??"UnknownSchema"};const[p,S]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:y(S.id,S.data),...S}),s[u]={name:y(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);r[u]=p,s[u]=p}}else{const f=n.addNode(h,u,d);r[u]=f,s[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)i(te(l),te(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=>[te(h),te(h)])),[P]:P};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))i(te(l),te(g),f,!0)}}return n}};function Lo(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function te(t){return t==="subgraph"?`"${t}"`:t}const lt=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var tp=class ul extends pt{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new ul(this.names);return typeof e<"u"&&(n.seen=new Set(e)),n}update(e){let n=!1;for(const r of e)if(this.names.has(r))this.seen.has(r)||(this.seen.add(r),n=!0);else throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!lt(this.names,this.seen))throw new Z}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&lt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&lt(this.names,this.seen)}},np=class hl extends pt{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 hl(this.names);if(typeof e<"u"){const[r,s]=e;n.seen=new Set(r),n.finished=s}return n}update(e){let n=!1;for(const r of e)if(this.names.has(r)&&!this.seen.has(r))this.seen.add(r),n=!0;else if(!this.names.has(r))throw new B(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!lt(this.names,this.seen))throw new Z}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&lt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&lt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&lt(this.names,this.seen)}};const rp="lg:";var sp=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=go(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new gs(o.reducer.fn,o.default):e[r]=new Zs}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(go(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=ts(c)??ts(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${rp}${h}`)}return[i,c]});s=Hc(t,Object.fromEntries(o)),Gc(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=Is(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const Jt=new sp;function Yt(t,e){if(e.reducer&&!e.default){const n=Ns(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return Jt.extend(n,()=>e),n}else return Jt.extend(t,()=>e),t}const Ue="__root__",Es=Symbol.for("langgraph.state.partial");var op=class extends ep{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Jt;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),dp(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??Es,this._outputDefinition=o,this._outputRuntimeDefinition=t.output??t.state}else if(fe(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=Es,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(hp(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(lp(t)||Do(t)){const r=Do(t)?t.spec:t;this._schemaDefinition=r}else if(cp(t)){const r=ip(t.channels);this._schemaDefinition=r}else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema.");this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition);function n(r){return typeof r=="object"&&r!=null&&!("spec"in r)&&!fe(r)}n(e)?(fe(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):fe(e)&&(this._configRuntimeSchema=e)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([t,e])=>t.map(n=>[n,e]))])}_addSchema(t){if(!this._schemaDefinitions.has(t)){this._schemaDefinitions.set(t,t);for(const[e,n]of Object.entries(t)){let r;if(typeof n=="function"?r=n():r=n,this.channels[e]!==void 0){if(this.channels[e]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=r}}}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([r,s])=>[r,s]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[q,ze])if(r.includes(u))throw new Error(`"${u}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),r in this.nodes)throw new Error(`Node \`${r}\` already present.`);if(r===P||r===D)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;o?.input!==void 0&&(fe(o.input)?i=this._metaRegistry.getChannelsForSchema(o.input):o.input.spec!==void 0&&(i=o.input.spec)),i!==void 0&&this._addSchema(i);let a;Q.isRunnable(s)?a=s:typeof s=="function"?a=new mt({func:s,name:r,trace:!1}):a=zt(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:no(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===P)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===P)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]===Ue?Ue:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===Ue?Ue:c,h=this._interrupt,d=new ap({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[D]:new qt},inputChannels:D,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:h});d.attachNode(D);for(const[f,g]of Object.entries(this.nodes))d.attachNode(f,g);d.attachBranch(D,xo,Fo(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,xo,Fo(),{withReader:!1});for(const[f,g]of this.edges)d.attachEdge(f,g);for(const[f,g]of this.waitingEdges)d.attachEdge(f,g);for(const[f,g]of Object.entries(this.branches))for(const[p,S]of Object.entries(g))d.attachBranch(f,p,S);return d.validate()}};function ip(t){const e={};for(const[n,r]of Object.entries(t))e[n]=ws(r);return e}var ap=class extends cl{description;_metaRegistry=Jt;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===D?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function r(a){if(X(a))return a.graph===K.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>X(l))){const l=[];for(const c of a)if(X(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([Ue,c]);return l}else if(a!=null)return[[Ue,a]];return null}const s=t;function o(a){if(a){if(X(a))return a.graph===K.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(X)){const l=[];for(const c of a)if(X(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 B(`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:ut,mapper:new mt({func:n.length&&n[0]===Ue?r:o,trace:!1,recurse:!1})}];if(t===D)this.nodes[t]=new wn({tags:[G],triggers:[D],channels:[D],writers:[new oe(i,[G])]});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&&Ue in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new Nd:new qt(!1),this.nodes[t]=new wn({triggers:[u],channels:c?Object.keys(l):l,writers:[new oe(i,[G])],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!==P){if(typeof t=="string")this.nodes[t].writers.push(new oe([{channel:`branch:to:${e}`,value:null}],[G]));else if(Array.isArray(t)){const n=`join:${t.join("+")}:${e}`;this.channels[n]=this.builder.nodes[e].defer?new np(new Set(t)):new tp(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new oe([{channel:n,value:r}],[G]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(o,i)=>{const a=o.filter(c=>c!==P);if(!a.length)return;const l=a.map(c=>me(c)?c:{channel:c===P?c:`branch:to:${c}`,value:t});await oe.doWrite({...i,tags:(i.tags??[]).concat([G])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>df.doRead(o,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=o=>{if(o!=null)return this._metaRegistry.getExtendedChannelSchemas(o,{withReducerSchema:!0})};if(fe(n))return s(n);if(n===Es)return Is(s(r))})();if(X(t)){const n=t;return t.update&&e!=null&&(n.update=Xe(e,t.update)),n}return e!=null?Xe(e,t):t}isInterrupted(t){return Ua(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return fe(e)&&Xe(e,t),t}};function lp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Ra(e))}function Do(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function cp(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 hp(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function dp(t){return!(typeof t!="object"||t==null||!("state"in t)||!fe(t.state)||"input"in t&&!fe(t.input)||"output"in t&&!fe(t.output))}function fp(t){if(me(t))return[t];const e=[];X(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(X));const n=[];for(const r of e){if(r.graph===K.PARENT)throw new $a(r);me(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Fo(){const t=new mt({func:fp,tags:[G],trace:!1,recurse:!1,name:"<control_branch>"});return new ll({path:t})}const dl="__remove_all__";function fl(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(dn),o=r.map(dn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=tr(),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=tr(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===dl&&(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))}ys.Root({messages:ys({reducer:fl,default:()=>[]})});const gr={reducer:{fn:fl},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:Yt(le(),gr)});Md();const xs=Symbol.for("langgraph-zod");xs in globalThis||(globalThis[xs]=new WeakSet);function Uo(t){const e=globalThis[xs];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Yt(n,{jsonSchemaExtra:r})},reducer(r,s){const o=Ns(n);return Yt(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Uo(Kc.prototype),Uo(Vl.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var pp=class extends Bl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Ns(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new pp(Jt);function mp(t=!0,e,n=[]){const r={messages:Yt(le(),gr),jumpTo:Ie([Ct("model_request"),Ct("tools"),Ct("end"),qc()]).optional()},s=a=>{const{shape:l}=a;for(const[c,u]of Object.entries(l))c.startsWith("_")||c in r||(r[c]=u)};e&&"shape"in e&&s(e);for(const a of n)a.stateSchema&&s(a.stateSchema);t&&(r.structuredResponse=$s().optional());const o=z(r);return Jt.getChannelsForSchema(o)}z({llmInputMessages:Yt(le(),{reducer:{fn:(t,e)=>gr.reducer.fn([],e)},default:()=>[]}),messages:Yt(le(),gr)});const Vo="prompt",Jr=/<name>(.*?)<\/name>/s,Yr=/<content>(.*?)<\/content>/s;function gp(t){if(!O.isInstance(t)||Vt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new O({...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 O({...t.lc_kwargs,content:n,name:void 0})}function yp(t){if(!O.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(Jr),o=r.text.match(Yr);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(Jr),o=r.text.match(Yr);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(Jr),o=r.match(Yr);if(!s||!o)return t;n=s[1],e=o[1]}return new O({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function W(t){return Q.isRunnable(t)}function Bo(t){return js(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const Xr=(t,e,n={})=>{if(Bo(t))return t.bindTools(e,n);if(Oe.isRunnableBinding(t)&&Bo(t.bound)){const r=t.bound.bindTools(e,n);return Oe.isRunnableBinding(r)?new Oe({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Oe({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function pl(t){if(typeof t=="function")return;let e=t;if(tt.isRunnableSequence(e)&&(e=e.steps.find(n=>Oe.isRunnableBinding(n))||e),!or(e)){if(Oe.isRunnableBinding(e)){const n=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,r=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(n||r)throw new rs}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new rs}}function Ms(t){return!!(O.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function wp(t){let e;if(t==null)e=Bt.from(n=>n.messages).withConfig({runName:Vo});else if(typeof t=="string"){const n=new _e(t);e=Bt.from(r=>[n,...r.messages??[]]).withConfig({runName:Vo})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function vp(t,e,n={}){const r=Xr(t,e,n);if(r)return r;if(or(t)){const s=Xr(await t._model(),e,n);if(s)return s}if(tt.isRunnableSequence(t)){const s=t.steps.findIndex(o=>Oe.isRunnableBinding(o)||js(o)||or(o));if(s>=0){const o=Xr(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),tt.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function bp(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 _p(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return bp(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?Xe(n.stateSchema,{...o.state}):{}}},i);if(!U.isInstance(a)&&!X(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 Sp(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=Jc(r.stateSchema,a=>a.startsWith("_")),o=await Yc(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(`
46
46
  `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
47
47
  ${i}
48
48
 
@@ -61,9 +61,9 @@ To fix this, either:
61
61
  agent.invoke({
62
62
  messages: [...],
63
63
  ${o.error.issues[0]?.path.join(".")}: "value"
64
- })`)}return n}function yp(t){const e={messages:le(()=>[]),structuredResponse:$s().optional()};if(!t)return z(e);const{shape:n}=t,r={...e};for(const[s,o]of Object.entries(n))s.startsWith("_")?r[s]=o.optional():r[s]=o;return z(r)}function Re(t){if(t){if(["model_request","tools",P].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return P;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function pl(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var oo=class extends Q{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){const n=Fe(this.config,e),r=await Ve.runWithConfig(n,async()=>this.func(t,n));return Q.isRunnable(r)&&this.recurse?await Ve.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function wp(t,e){let n,r;if(e==="inline")n=up,r=hp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return tt.from([Bt.from(s),t,Bt.from(r)])}var bp=class extends oo{#e;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t}#n(t){if(!this.#e.responseFormat)return;const e=yi(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof it)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Ge).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(t,e){const n=t.messages.at(-1);if(n&&U.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#o(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof K?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#r(t,r)?{messages:[new O({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#t(){if(typeof this.#e.model=="string")return Zt(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#o(t,e,n={}){const r=await this.#t(),s=e,o=async c=>{fl(c.model);const u=this.#n(c.model),h=await this.#u(c.model,c,u);let d=this.#c(t);d={...d,messages:c.messages};const f=pl(this.#e.signal,e.signal),g={...e,signal:f},p=await h.invoke(d,g);if(u?.type==="native"){const _=u.strategy.parse(p);return _?{structuredResponse:_,messages:[p]}:p}if(!u||!p.tool_calls)return p;const S=p.tool_calls.filter(_=>_.name in u.tools);if(S.length===0)return p;if(S.length>1)return this.#a(p,S,u);const y=u.tools[S[0].name]?.options?.toolMessageContent;return this.#l(p,S[0],u,y??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,g=h;a=async p=>{const S=f.contextSchema?Xe(f.contextSchema,s?.context||{}):s?.context,C=Object.freeze({context:S,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),y={...p,state:{...u.stateSchema?Xe(Is(u.stateSchema),t):{},...g(),messages:t.messages},runtime:C},_=async v=>{const k=v.tools??[],M=k.filter(b=>H(b)&&!this.#e.toolClasses.some(T=>T.name===b.name));if(M.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${M.map(b=>b.name).join(", ")}. This is not supported.`);const w=k.filter(b=>H(b)&&this.#e.toolClasses.every(T=>T!==b));if(w.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${w.map(b=>b.name).join(", ")}. This is not supported.`);return d(v)};if(!f.wrapModelCall)return _(y);try{const v=await f.wrapModelCall(y,_);if(!O.isInstance(v))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof v}`);return v}catch(v){throw v instanceof Error&&!v.message.includes(`middleware "${f.name}"`)&&(v.message=`Error in middleware "${f.name}": ${v.message}`),v}}}}const l={model:r,systemPrompt:this.#e.systemPrompt,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return a(l)}#a(t,e,n){const r=new ss(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#l(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new U({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new O(r??`Returning structured response: ${JSON.stringify(o)}`)]}}catch(o){return this.#i(o,t,e,n)}}async#i(t,e,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,o=n.id;if(!o)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof ss))return new K({update:{messages:[e,new U({content:t.message,tool_call_id:o})]},goto:"model"});if(typeof s=="string")return new K({update:{messages:[e,new U({content:s,tool_call_id:o})]},goto:"model"});if(typeof s=="function"){const i=await s(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new K({update:{messages:[e,new U({content:i,tool_call_id:o})]},goto:"model"})}throw t}#r(t,e){const n=O.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&&Ms(t.messages.at(-1))))}#c(t){const{messages:e,llmInputMessages:n,...r}=t;return n&&n.length>0?{messages:n,...r}:{messages:e,...r}}async#u(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c={name:n.strategy.schema?.name??"extract",description:ts(n.strategy.schema),schema:n.strategy.schema,strict:!0};Object.assign(r,{response_format:{type:"json_schema",json_schema:c},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:!0})}const a=await fp(t,o,{...r,...e?.modelSettings??{},tool_choice:i});return dp(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?wp(a,this.#e.includeAgentName):a)}getState(){const t=super.getState(),e=t&&!(t instanceof K)?t:{};return{messages:[],...e}}};const ml=t=>Array.isArray(t)&&t.every(an.isInstance),vp=t=>typeof t=="object"&&t!=null&&"messages"in t&&ml(t.messages),_p=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Sp(t,e){return t instanceof Rs?new U({content:t.message,tool_call_id:e.id,name:e.name}):new U({content:`${t}
65
- Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var Cp=class extends oo{tools;trace=!1;signal;handleToolErrors=Sp;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(at(t)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){const r=this.handleToolErrors(t,e);if(r&&U.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new U({name:e.name,content:`${t}
66
- 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:pl(this.signal,e.signal)});return U.isInstance(h)||X(h)?h:new U({name:u.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:c.id})}catch(h){throw h instanceof qc?new Rs(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(_p(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(ml(t))o=t;else if(vp(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(O.isInstance(c)){a=c;break}}if(!O.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(X))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)X(o)?o.graph===K.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>kp(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 kp(t){return t instanceof se}var Tp=class{},Ep=class{},Er=class extends oo{#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=Xe(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 Ep,{...s,context:Object.freeze(Object.assign(new Tp,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Je(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Je(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Je(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Je(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const 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:yp(this.middleware.stateSchema)}}},xp=class extends Er{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 Cr(this.middleware.beforeAgent)(t,e)}},Mp=class extends Er{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 Cr(this.middleware.beforeModel)(t,e)}},Ap=class extends Er{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 Cr(this.middleware.afterModel)(t,e)}},Pp=class extends Er{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 Cr(this.middleware.afterAgent)(t,e)}},Op=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}},Np=class{#e;#n="v2";#s;#t=new Op;constructor(t){if(this.options=t,this.#n=t.version??this.#n,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&fl(t.model);const e=this.options.middleware?.filter(y=>y.tools).flatMap(y=>y.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(H).filter(y=>"returnDirect"in y&&y.returnDirect).map(y=>y.name)),s=cp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new Qf(s,this.options.contextSchema),a=[],l=[],c=[],u=[],h=[];this.#s=new bp({model:this.options.model,systemPrompt:this.options.systemPrompt,includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:h});const d=new Set,f=this.options.middleware??[];for(let y=0;y<f.length;y++){let _,v,k,M;const w=f[y];if(d.has(w.name))throw new Error(`Middleware ${w.name} is defined multiple times`);if(d.add(w.name),w.beforeAgent){_=new xp(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,_);const b=`${w.name}.before_agent`;a.push({index:y,name:b,allowed:Je(w.beforeAgent)}),i.addNode(b,_,_.nodeOptions)}if(w.beforeModel){v=new Mp(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,v);const b=`${w.name}.before_model`;l.push({index:y,name:b,allowed:Je(w.beforeModel)}),i.addNode(b,v,v.nodeOptions)}if(w.afterModel){k=new Ap(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,k);const b=`${w.name}.after_model`;c.push({index:y,name:b,allowed:Je(w.afterModel)}),i.addNode(b,k,k.nodeOptions)}if(w.afterAgent){M=new Pp(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,M);const b=`${w.name}.after_agent`;u.push({index:y,name:b,allowed:Je(w.afterAgent)}),i.addNode(b,M,M.nodeOptions)}w.wrapModelCall&&h.push([w,()=>this.#t.getState(w.name)])}if(i.addNode("model_request",this.#s),n.filter(H).length>0){const y=new Cp(n.filter(H),{signal:this.options.signal,wrapToolCall:mp(f)});i.addNode("tools",y)}let g;a.length>0?g=a[0].name:l.length>0?g=l[0].name:g="model_request";const p=l.length>0?l[0].name:"model_request",S=u.length>0?u[u.length-1].name:P;i.addEdge(D,g);for(let y=0;y<a.length;y++){const _=a[y],v=_.name,M=y===a.length-1?p:a[y+1].name;if(_.allowed&&_.allowed.length>0){const w=n.filter(H).length>0,b=_.allowed.map(x=>Re(x)).filter(x=>x!=="tools"||w),T=Array.from(new Set([M,...b.map(x=>x===P?S:x)]));i.addConditionalEdges(v,this.#c(n.filter(H),M,S),T)}else i.addEdge(v,M)}for(let y=0;y<l.length;y++){const _=l[y],v=_.name,M=y===l.length-1?"model_request":l[y+1].name;if(_.allowed&&_.allowed.length>0){const w=n.filter(H).length>0,b=_.allowed.map(x=>Re(x)).filter(x=>x!=="tools"||w),T=Array.from(new Set([M,...b]));i.addConditionalEdges(v,this.#u(n.filter(H),M),T)}else i.addEdge(v,M)}const C=c.at(-1);if(c.length>0&&C)i.addEdge("model_request",C.name);else{const _=this.#o(n.filter(H)).map(v=>v===P?S:v);_.length===1?i.addEdge("model_request",_[0]):i.addConditionalEdges("model_request",this.#l(S),_)}for(let y=c.length-1;y>0;y--){const _=c[y],v=_.name,k=c[y-1].name;if(_.allowed&&_.allowed.length>0){const M=n.filter(H).length>0,w=_.allowed.map(T=>Re(T)).filter(T=>T!=="tools"||M),b=Array.from(new Set([k,...w]));i.addConditionalEdges(v,this.#r(n.filter(H),_.allowed,k),b)}else i.addEdge(v,k)}if(c.length>0){const y=c[0],_=y.name,v=this.#o(n.filter(H),!0).filter(w=>w!=="tools"||n.filter(H).length>0),k=!!(y.allowed&&y.allowed.length>0),M=v.map(w=>w===P?S:w);i.addConditionalEdges(_,this.#i(n.filter(H),k,S),M)}for(let y=u.length-1;y>0;y--){const _=u[y],v=_.name,k=u[y-1].name;if(_.allowed&&_.allowed.length>0){const M=n.filter(H).length>0,w=_.allowed.map(T=>Re(T)).filter(T=>T!=="tools"||M),b=Array.from(new Set([k,...w]));i.addConditionalEdges(v,this.#r(n.filter(H),_.allowed,k),b)}else i.addEdge(v,k)}if(u.length>0){const y=u[0],_=y.name;if(y.allowed&&y.allowed.length>0){const v=n.filter(H).length>0,k=y.allowed.map(w=>Re(w)).filter(w=>w!=="tools"||v),M=Array.from(new Set([P,...k]));i.addConditionalEdges(_,this.#r(n.filter(H),y.allowed,P),M)}else i.addEdge(_,P)}if(n.filter(H).length>0){const y=p;r.size>0?i.addConditionalEdges("tools",this.#a(r,S),[y,S]):i.addEdge("tools",y)}this.#e=i.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#o(t,e=!1){const n=[];return t.length>0&&n.push("tools"),e&&n.push("model_request"),n.push(P),n}#a(t,e){return n=>{const r=n.messages,s=r[r.length-1];return U.isInstance(s)&&s.name&&t.has(s.name)?this.options.responseFormat?"model_request":e:"model_request"}}#l(t=P){return e=>{const r=e.messages.at(-1);if(!O.isInstance(r)||!r.tool_calls||r.tool_calls.length===0||r.tool_calls.every(i=>i.name.startsWith("extract-")))return t;if(this.#n==="v1")return"tools";const o=r.tool_calls.filter(i=>!i.name.startsWith("extract-"));return o.length===0?t:o.map(i=>new se("tools",{...e,lg_tool_call:i}))}}#i(t,e,n){const r=!!this.options.responseFormat;return s=>{const o=s.messages,i=o.at(-1);if(O.isInstance(i)&&(!i.tool_calls||i.tool_calls.length===0))return n;if(e&&s.jumpTo)return s.jumpTo===P?n:s.jumpTo==="tools"?t.length===0?n:new se("tools",{...s,jumpTo:void 0}):new se("model_request",{...s,jumpTo:void 0});const a=o.filter(U.isInstance),l=o.filter(O.isInstance).at(-1),c=l?.tool_calls?.filter(f=>!a.some(g=>g.tool_call_id===f.id));if(c&&c.length>0)return c.map(f=>new se("tools",{...s,lg_tool_call:f}));const u=l?.tool_calls?.some(f=>f.name.startsWith("extract-"));if(c&&c.length===0&&!u&&r)return"model_request";if(!O.isInstance(i)||!i.tool_calls||i.tool_calls.length===0)return n;const h=i.tool_calls.every(f=>f.name.startsWith("extract-")),d=i.tool_calls.some(f=>!f.name.startsWith("extract-"));return h||!d?n:"tools"}}#r(t,e,n){const r=new Set(e.map(s=>Re(s)));return s=>{if(s.jumpTo){const o=Re(s.jumpTo);if(o===P&&r.has(P))return P;if(o==="tools"&&r.has("tools"))return t.length===0?P:new se("tools",{...s,jumpTo:void 0});if(o==="model_request"&&r.has("model_request"))return new se("model_request",{...s,jumpTo:void 0})}return n}}#c(t,e,n){return r=>{if(!r.jumpTo)return e;const s=Re(r.jumpTo);return s===P?n:s==="tools"?t.length===0?n:new se("tools",{...r,jumpTo:void 0}):new se("model_request",{...r,jumpTo:void 0})}}#u(t,e){return n=>{if(!n.jumpTo)return e;const r=Re(n.jumpTo);return r===P?P:r==="tools"?t.length===0?P:new se("tools",{...n,jumpTo:void 0}):new se("model_request",{...n,jumpTo:void 0})}}async#h(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof K||!t)return t;const n=await gp(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[o,i]of Object.entries(n))o in s||(s[o]=i);return s}async invoke(t,e){const n=await this.#h(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#h(t,e);return this.#e.stream(n,e)}async drawMermaidPng(t){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,e,n){return this.#e.streamEvents(t,{...e,version:e?.version??"v2"},n)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,e){return this.#e.getState(t,e)}getStateHistory(t,e){return this.#e.getStateHistory(t,e)}getSubgraphs(t,e){return this.#e.getSubgraphs(t,e)}getSubgraphAsync(t,e){return this.#e.getSubgraphsAsync(t,e)}updateState(t,e,n){return this.#e.updateState(t,e,n)}};function gl(t){return new Np(t)}const Qn=`<role>
64
+ })`)}return n}function Cp(t){const e={messages:le(()=>[]),structuredResponse:$s().optional()};if(!t)return z(e);const{shape:n}=t,r={...e};for(const[s,o]of Object.entries(n))s.startsWith("_")?r[s]=o.optional():r[s]=o;return z(r)}function Re(t){if(t){if(["model_request","tools",P].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return P;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function ml(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var oo=class extends Q{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){const n=Fe(this.config,e),r=await Ve.runWithConfig(n,async()=>this.func(t,n));return Q.isRunnable(r)&&this.recurse?await Ve.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function kp(t,e){let n,r;if(e==="inline")n=gp,r=yp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(o){return o.map(n)}return tt.from([Bt.from(s),t,Bt.from(r)])}var Tp=class extends oo{#e;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#s(e,n)}),this.#e=t}#n(t){if(!this.#e.responseFormat)return;const e=wi(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof it)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Ge).reduce((r,s)=>(r[s.name]=s,r),{})}}async#s(t,e){const n=t.messages.at(-1);if(n&&U.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const r=await this.#o(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof K?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#r(t,r)?{messages:[new O({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#t(){if(typeof this.#e.model=="string")return Zt(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#o(t,e,n={}){const r=await this.#t(),s=e,o=async c=>{pl(c.model);const u=this.#n(c.model),h=await this.#u(c.model,c,u);let d=this.#c(t);d={...d,messages:c.messages};const f=ml(this.#e.signal,e.signal),g={...e,signal:f},p=await h.invoke(d,g);if(u?.type==="native"){const _=u.strategy.parse(p);return _?{structuredResponse:_,messages:[p]}:p}if(!u||!p.tool_calls)return p;const S=p.tool_calls.filter(_=>_.name in u.tools);if(S.length===0)return p;if(S.length>1)return this.#a(p,S,u);const y=u.tools[S[0].name]?.options?.toolMessageContent;return this.#l(p,S[0],u,y??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,g=h;a=async p=>{const S=f.contextSchema?Xe(f.contextSchema,s?.context||{}):s?.context,C=Object.freeze({context:S,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),y={...p,state:{...u.stateSchema?Xe(Is(u.stateSchema),t):{},...g(),messages:t.messages},runtime:C},_=async b=>{const k=b.tools??[],M=k.filter(v=>W(v)&&!this.#e.toolClasses.some(T=>T.name===v.name));if(M.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${M.map(v=>v.name).join(", ")}. This is not supported.`);const w=k.filter(v=>W(v)&&this.#e.toolClasses.every(T=>T!==v));if(w.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${w.map(v=>v.name).join(", ")}. This is not supported.`);return d(b)};if(!f.wrapModelCall)return _(y);try{const b=await f.wrapModelCall(y,_);if(!O.isInstance(b))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof b}`);return b}catch(b){throw b instanceof Error&&!b.message.includes(`middleware "${f.name}"`)&&(b.message=`Error in middleware "${f.name}": ${b.message}`),b}}}}const l={model:r,systemPrompt:this.#e.systemPrompt,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return a(l)}#a(t,e,n){const r=new ss(e.map(s=>s.name));return this.#i(r,t,e[0],n)}#l(t,e,n,r){const s=n.tools[e.name];try{const o=s.parse(e.args);return{structuredResponse:o,messages:[t,new U({tool_call_id:e.id??"",content:JSON.stringify(o),name:e.name}),new O(r??`Returning structured response: ${JSON.stringify(o)}`)]}}catch(o){return this.#i(o,t,e,n)}}async#i(t,e,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,o=n.id;if(!o)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(typeof s=="boolean"&&s||Array.isArray(s)&&s.some(i=>i instanceof ss))return new K({update:{messages:[e,new U({content:t.message,tool_call_id:o})]},goto:"model"});if(typeof s=="string")return new K({update:{messages:[e,new U({content:s,tool_call_id:o})]},goto:"model"});if(typeof s=="function"){const i=await s(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new K({update:{messages:[e,new U({content:i,tool_call_id:o})]},goto:"model"})}throw t}#r(t,e){const n=O.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&&Ms(t.messages.at(-1))))}#c(t){const{messages:e,llmInputMessages:n,...r}=t;return n&&n.length>0?{messages:n,...r}:{messages:e,...r}}async#u(t,e,n){const r={},s=Object.values(n&&"tools"in n?n.tools:{}),o=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],i=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c={name:n.strategy.schema?.name??"extract",description:ts(n.strategy.schema),schema:n.strategy.schema,strict:!0};Object.assign(r,{response_format:{type:"json_schema",json_schema:c},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:!0})}const a=await vp(t,o,{...r,...e?.modelSettings??{},tool_choice:i});return wp(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?kp(a,this.#e.includeAgentName):a)}getState(){const t=super.getState(),e=t&&!(t instanceof K)?t:{};return{messages:[],...e}}};const gl=t=>Array.isArray(t)&&t.every(an.isInstance),Ep=t=>typeof t=="object"&&t!=null&&"messages"in t&&gl(t.messages),xp=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Mp(t,e){return t instanceof Rs?new U({content:t.message,tool_call_id:e.id,name:e.name}):new U({content:`${t}
65
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var Ap=class extends oo{tools;trace=!1;signal;handleToolErrors=Mp;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(at(t)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){const r=this.handleToolErrors(t,e);if(r&&U.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new U({name:e.name,content:`${t}
66
+ 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:ml(this.signal,e.signal)});return U.isInstance(h)||X(h)?h:new U({name:u.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:c.id})}catch(h){throw h instanceof Xc?new Rs(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(xp(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(gl(t))o=t;else if(Ep(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(O.isInstance(c)){a=c;break}}if(!O.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(X))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)X(o)?o.graph===K.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>Pp(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 Pp(t){return t instanceof se}var Op=class{},Np=class{},Er=class extends oo{#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=Xe(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 Np,{...s,context:Object.freeze(Object.assign(new Op,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=Je(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Je(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Je(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Je(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const 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:Cp(this.middleware.stateSchema)}}},Ip=class extends Er{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 Cr(this.middleware.beforeAgent)(t,e)}},$p=class extends Er{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 Cr(this.middleware.beforeModel)(t,e)}},Rp=class extends Er{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 Cr(this.middleware.afterModel)(t,e)}},jp=class extends Er{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 Cr(this.middleware.afterAgent)(t,e)}},Lp=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}},Dp=class{#e;#n="v2";#s;#t=new Lp;constructor(t){if(this.options=t,this.#n=t.version??this.#n,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&pl(t.model);const e=this.options.middleware?.filter(y=>y.tools).flatMap(y=>y.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(W).filter(y=>"returnDirect"in y&&y.returnDirect).map(y=>y.name)),s=mp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new op(s,this.options.contextSchema),a=[],l=[],c=[],u=[],h=[];this.#s=new Tp({model:this.options.model,systemPrompt:this.options.systemPrompt,includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:h});const d=new Set,f=this.options.middleware??[];for(let y=0;y<f.length;y++){let _,b,k,M;const w=f[y];if(d.has(w.name))throw new Error(`Middleware ${w.name} is defined multiple times`);if(d.add(w.name),w.beforeAgent){_=new Ip(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,_);const v=`${w.name}.before_agent`;a.push({index:y,name:v,allowed:Je(w.beforeAgent)}),i.addNode(v,_,_.nodeOptions)}if(w.beforeModel){b=new $p(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,b);const v=`${w.name}.before_model`;l.push({index:y,name:v,allowed:Je(w.beforeModel)}),i.addNode(v,b,b.nodeOptions)}if(w.afterModel){k=new Rp(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,k);const v=`${w.name}.after_model`;c.push({index:y,name:v,allowed:Je(w.afterModel)}),i.addNode(v,k,k.nodeOptions)}if(w.afterAgent){M=new jp(w,{getState:()=>this.#t.getState(w.name)}),this.#t.addNode(w,M);const v=`${w.name}.after_agent`;u.push({index:y,name:v,allowed:Je(w.afterAgent)}),i.addNode(v,M,M.nodeOptions)}w.wrapModelCall&&h.push([w,()=>this.#t.getState(w.name)])}if(i.addNode("model_request",this.#s),n.filter(W).length>0){const y=new Ap(n.filter(W),{signal:this.options.signal,wrapToolCall:_p(f)});i.addNode("tools",y)}let g;a.length>0?g=a[0].name:l.length>0?g=l[0].name:g="model_request";const p=l.length>0?l[0].name:"model_request",S=u.length>0?u[u.length-1].name:P;i.addEdge(D,g);for(let y=0;y<a.length;y++){const _=a[y],b=_.name,M=y===a.length-1?p:a[y+1].name;if(_.allowed&&_.allowed.length>0){const w=n.filter(W).length>0,v=_.allowed.map(x=>Re(x)).filter(x=>x!=="tools"||w),T=Array.from(new Set([M,...v.map(x=>x===P?S:x)]));i.addConditionalEdges(b,this.#c(n.filter(W),M,S),T)}else i.addEdge(b,M)}for(let y=0;y<l.length;y++){const _=l[y],b=_.name,M=y===l.length-1?"model_request":l[y+1].name;if(_.allowed&&_.allowed.length>0){const w=n.filter(W).length>0,v=_.allowed.map(x=>Re(x)).filter(x=>x!=="tools"||w),T=Array.from(new Set([M,...v]));i.addConditionalEdges(b,this.#u(n.filter(W),M),T)}else i.addEdge(b,M)}const C=c.at(-1);if(c.length>0&&C)i.addEdge("model_request",C.name);else{const _=this.#o(n.filter(W)).map(b=>b===P?S:b);_.length===1?i.addEdge("model_request",_[0]):i.addConditionalEdges("model_request",this.#l(S),_)}for(let y=c.length-1;y>0;y--){const _=c[y],b=_.name,k=c[y-1].name;if(_.allowed&&_.allowed.length>0){const M=n.filter(W).length>0,w=_.allowed.map(T=>Re(T)).filter(T=>T!=="tools"||M),v=Array.from(new Set([k,...w]));i.addConditionalEdges(b,this.#r(n.filter(W),_.allowed,k),v)}else i.addEdge(b,k)}if(c.length>0){const y=c[0],_=y.name,b=this.#o(n.filter(W),!0).filter(w=>w!=="tools"||n.filter(W).length>0),k=!!(y.allowed&&y.allowed.length>0),M=b.map(w=>w===P?S:w);i.addConditionalEdges(_,this.#i(n.filter(W),k,S),M)}for(let y=u.length-1;y>0;y--){const _=u[y],b=_.name,k=u[y-1].name;if(_.allowed&&_.allowed.length>0){const M=n.filter(W).length>0,w=_.allowed.map(T=>Re(T)).filter(T=>T!=="tools"||M),v=Array.from(new Set([k,...w]));i.addConditionalEdges(b,this.#r(n.filter(W),_.allowed,k),v)}else i.addEdge(b,k)}if(u.length>0){const y=u[0],_=y.name;if(y.allowed&&y.allowed.length>0){const b=n.filter(W).length>0,k=y.allowed.map(w=>Re(w)).filter(w=>w!=="tools"||b),M=Array.from(new Set([P,...k]));i.addConditionalEdges(_,this.#r(n.filter(W),y.allowed,P),M)}else i.addEdge(_,P)}if(n.filter(W).length>0){const y=p;r.size>0?i.addConditionalEdges("tools",this.#a(r,S),[y,S]):i.addEdge("tools",y)}this.#e=i.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#o(t,e=!1){const n=[];return t.length>0&&n.push("tools"),e&&n.push("model_request"),n.push(P),n}#a(t,e){return n=>{const r=n.messages,s=r[r.length-1];return U.isInstance(s)&&s.name&&t.has(s.name)?this.options.responseFormat?"model_request":e:"model_request"}}#l(t=P){return e=>{const r=e.messages.at(-1);if(!O.isInstance(r)||!r.tool_calls||r.tool_calls.length===0||r.tool_calls.every(i=>i.name.startsWith("extract-")))return t;if(this.#n==="v1")return"tools";const o=r.tool_calls.filter(i=>!i.name.startsWith("extract-"));return o.length===0?t:o.map(i=>new se("tools",{...e,lg_tool_call:i}))}}#i(t,e,n){const r=!!this.options.responseFormat;return s=>{const o=s.messages,i=o.at(-1);if(O.isInstance(i)&&(!i.tool_calls||i.tool_calls.length===0))return n;if(e&&s.jumpTo)return s.jumpTo===P?n:s.jumpTo==="tools"?t.length===0?n:new se("tools",{...s,jumpTo:void 0}):new se("model_request",{...s,jumpTo:void 0});const a=o.filter(U.isInstance),l=o.filter(O.isInstance).at(-1),c=l?.tool_calls?.filter(f=>!a.some(g=>g.tool_call_id===f.id));if(c&&c.length>0)return c.map(f=>new se("tools",{...s,lg_tool_call:f}));const u=l?.tool_calls?.some(f=>f.name.startsWith("extract-"));if(c&&c.length===0&&!u&&r)return"model_request";if(!O.isInstance(i)||!i.tool_calls||i.tool_calls.length===0)return n;const h=i.tool_calls.every(f=>f.name.startsWith("extract-")),d=i.tool_calls.some(f=>!f.name.startsWith("extract-"));return h||!d?n:"tools"}}#r(t,e,n){const r=new Set(e.map(s=>Re(s)));return s=>{if(s.jumpTo){const o=Re(s.jumpTo);if(o===P&&r.has(P))return P;if(o==="tools"&&r.has("tools"))return t.length===0?P:new se("tools",{...s,jumpTo:void 0});if(o==="model_request"&&r.has("model_request"))return new se("model_request",{...s,jumpTo:void 0})}return n}}#c(t,e,n){return r=>{if(!r.jumpTo)return e;const s=Re(r.jumpTo);return s===P?n:s==="tools"?t.length===0?n:new se("tools",{...r,jumpTo:void 0}):new se("model_request",{...r,jumpTo:void 0})}}#u(t,e){return n=>{if(!n.jumpTo)return e;const r=Re(n.jumpTo);return r===P?P:r==="tools"?t.length===0?P:new se("tools",{...n,jumpTo:void 0}):new se("model_request",{...n,jumpTo:void 0})}}async#h(t,e){if(!this.options.middleware||this.options.middleware.length===0||t instanceof K||!t)return t;const n=await Sp(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[o,i]of Object.entries(n))o in s||(s[o]=i);return s}async invoke(t,e){const n=await this.#h(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#h(t,e);return this.#e.stream(n,e)}async drawMermaidPng(t){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,e,n){return this.#e.streamEvents(t,{...e,version:e?.version??"v2"},n)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,e){return this.#e.getState(t,e)}getStateHistory(t,e){return this.#e.getStateHistory(t,e)}getSubgraphs(t,e){return this.#e.getSubgraphs(t,e)}getSubgraphAsync(t,e){return this.#e.getSubgraphsAsync(t,e)}updateState(t,e,n){return this.#e.updateState(t,e,n)}};function yl(t){return new Dp(t)}const Qn=`<role>
67
67
  Context Extraction Assistant
68
68
  </role>
69
69
 
@@ -89,13 +89,13 @@ Respond ONLY with the extracted context. Do not include any additional informati
89
89
  <messages>
90
90
  Messages to summarize:
91
91
  {messages}
92
- </messages>`,yr=20,Ip=4e3,Bo=5,$p=nr().args(He(le())).returns(Ie([V(),ii(V())])),wr=z({fraction:V().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().positive("Tokens must be greater than 0").optional(),messages:V().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),yl=z({fraction:V().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().positive("Tokens must be greater than 0").optional(),messages:V().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),zo=z({model:le(),trigger:Ie([wr,He(wr)]).optional(),keep:yl.optional(),tokenCounter:$p.optional(),summaryPrompt:ne().default(Qn),trimTokensToSummarize:V().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:V().optional(),messagesToKeep:V().optional()});function io(t){try{const e=t;if(e.profile&&typeof e.profile.max_input_tokens=="number")return e.profile.max_input_tokens}catch{}try{const e=t,n=e.model||e.modelName;if(typeof n=="string")return cc(n)}catch{}}function Rp(t){const{data:e,error:n}=Jc(zo,t);if(n)throw new Error(`Invalid summarization middleware options: ${ei(n)}`);return ge({name:"SummarizationMiddleware",contextSchema:zo.extend({model:le().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===yr)&&(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:yr},c=yl.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(T=>wr.parse(T)):u=[wr.parse(a)];const h=u.some(T=>"fraction"in T)||"fraction"in c,d=typeof e.model=="string"?await Zt(e.model):e.model;if(h&&!io(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context.summaryPrompt===Qn?e.summaryPrompt??Qn:s.context.summaryPrompt??e.summaryPrompt??Qn,g=s.context.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??Ip;jp(r.messages);const p=s.context.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Ls,S=await p(r.messages);if(!await Fp(r.messages,S,u,d))return;const{systemPrompt:y,conversationMessages:_}=Lp(r.messages),v=await Up(_,c,p,d);if(v<=0)return;const{messagesToSummarize:k,preservedMessages:M}=Dp(y,_,v),w=await Hp(k,d,f,p,g),b=new pe({content:`Here is a summary of the conversation to date:
92
+ </messages>`,yr=20,Fp=4e3,zo=5,Up=nr().args(We(le())).returns(Ie([V(),ai(V())])),wr=z({fraction:V().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().positive("Tokens must be greater than 0").optional(),messages:V().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),wl=z({fraction:V().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:V().positive("Tokens must be greater than 0").optional(),messages:V().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(n=>n!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),Wo=z({model:le(),trigger:Ie([wr,We(wr)]).optional(),keep:wl.optional(),tokenCounter:Up.optional(),summaryPrompt:ne().default(Qn),trimTokensToSummarize:V().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:V().optional(),messagesToKeep:V().optional()});function io(t){try{const e=t;if(e.profile&&typeof e.profile.max_input_tokens=="number")return e.profile.max_input_tokens}catch{}try{const e=t,n=e.model||e.modelName;if(typeof n=="string")return dc(n)}catch{}}function Vp(t){const{data:e,error:n}=Zc(Wo,t);if(n)throw new Error(`Invalid summarization middleware options: ${ti(n)}`);return ge({name:"SummarizationMiddleware",contextSchema:Wo.extend({model:le().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===yr)&&(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:yr},c=wl.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(T=>wr.parse(T)):u=[wr.parse(a)];const h=u.some(T=>"fraction"in T)||"fraction"in c,d=typeof e.model=="string"?await Zt(e.model):e.model;if(h&&!io(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context.summaryPrompt===Qn?e.summaryPrompt??Qn:s.context.summaryPrompt??e.summaryPrompt??Qn,g=s.context.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??Fp;Bp(r.messages);const p=s.context.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Ls,S=await p(r.messages);if(!await Hp(r.messages,S,u,d))return;const{systemPrompt:y,conversationMessages:_}=zp(r.messages),b=await Gp(_,c,p,d);if(b<=0)return;const{messagesToSummarize:k,preservedMessages:M}=Wp(y,_,b),w=await Yp(k,d,f,p,g),v=new pe({content:`Here is a summary of the conversation to date:
93
93
 
94
- ${w}`,id:tr()});return{messages:[new jn({id:hl}),b,...M]}}})}function jp(t){for(const e of t)e.id||(e.id=tr())}function Lp(t){return t.length>0&&_e.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Dp(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function Fp(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=io(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 Up(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Vp(t,e,n,r);return typeof s=="number"?s:Ho(t,yr)}return Ho(t,e.messages??yr)}async function Vp(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const u=io(r);if(typeof u!="number")return;s=Math.floor(u*e.fraction)}else if("tokens"in e&&e.tokens!==void 0)s=Math.floor(e.tokens);else return;if(s<=0&&(s=1),await n(t)<=s)return 0;let i=0,a=t.length,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let u=0;u<c&&!(i>=a);u++){const h=Math.floor((i+a)/2);await n(t.slice(h))<=s?(l=h,a=h):i=h+1}if(l===t.length&&(l=i),l>=t.length){if(t.length===1)return 0;l=t.length-1}for(let u=l;u>=0;u--)if(wl(t,u))return u;return 0}function Ho(t,e){if(t.length<=e)return 0;const n=t.length-e;for(let r=n;r>=0;r--)if(wl(t,r))return r;return 0}function wl(t,e){if(e>=t.length)return!0;if(e<t.length&&O.isInstance(t[e])&&Ms(t[e]))return!1;const n=Math.max(0,e-Bo),r=Math.min(t.length,e+Bo);for(let s=n;s<r;s++){if(!Ms(t[s]))continue;const o=Bp(t[s]);if(zp(t,s,e,o))return!1}return!0}function Bp(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 zp(t,e,n,r){for(let s=e+1;s<t.length;s++){const o=t[s];if(U.isInstance(o)&&r.has(o.tool_call_id)){const i=e<n,a=s<n;if(i!==a)return!0}}return!1}async function Hp(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const o=await Wp(t,r,s);if(!o.length)return"Previous conversation was too long to summarize.";try{const i=n.replace("{messages}",JSON.stringify(o,null,2)),l=(await e.invoke(i)).content;return typeof l=="string"?l.trim():Array.isArray(l)?l.map(u=>typeof u=="string"?u:typeof u=="object"&&u!==null&&"text"in u?u.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(i){return`Error generating summary: ${i}`}}async function Wp(t,e,n){if(n===void 0)return t;try{return await ai(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const Gp=nr().args(le(),le(),le()).returns(Ie([ne(),ii(ne())])),bl=["approve","edit","reject"],Kp=Ht(bl),qp=z({allowedDecisions:He(Kp),description:Ie([ne(),Gp]).optional(),argsSchema:fn($s()).optional()}),Wo=z({interruptOn:fn(Ie([rr(),qp])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function Jp(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"}
94
+ ${w}`,id:tr()});return{messages:[new jn({id:dl}),v,...M]}}})}function Bp(t){for(const e of t)e.id||(e.id=tr())}function zp(t){return t.length>0&&_e.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Wp(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function Hp(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=io(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 Gp(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Kp(t,e,n,r);return typeof s=="number"?s:Ho(t,yr)}return Ho(t,e.messages??yr)}async function Kp(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const u=io(r);if(typeof u!="number")return;s=Math.floor(u*e.fraction)}else if("tokens"in e&&e.tokens!==void 0)s=Math.floor(e.tokens);else return;if(s<=0&&(s=1),await n(t)<=s)return 0;let i=0,a=t.length,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let u=0;u<c&&!(i>=a);u++){const h=Math.floor((i+a)/2);await n(t.slice(h))<=s?(l=h,a=h):i=h+1}if(l===t.length&&(l=i),l>=t.length){if(t.length===1)return 0;l=t.length-1}for(let u=l;u>=0;u--)if(vl(t,u))return u;return 0}function Ho(t,e){if(t.length<=e)return 0;const n=t.length-e;for(let r=n;r>=0;r--)if(vl(t,r))return r;return 0}function vl(t,e){if(e>=t.length)return!0;if(e<t.length&&O.isInstance(t[e])&&Ms(t[e]))return!1;const n=Math.max(0,e-zo),r=Math.min(t.length,e+zo);for(let s=n;s<r;s++){if(!Ms(t[s]))continue;const o=qp(t[s]);if(Jp(t,s,e,o))return!1}return!0}function qp(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 Jp(t,e,n,r){for(let s=e+1;s<t.length;s++){const o=t[s];if(U.isInstance(o)&&r.has(o.tool_call_id)){const i=e<n,a=s<n;if(i!==a)return!0}}return!1}async function Yp(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const o=await Xp(t,r,s);if(!o.length)return"Previous conversation was too long to summarize.";try{const i=n.replace("{messages}",JSON.stringify(o,null,2)),l=(await e.invoke(i)).content;return typeof l=="string"?l.trim():Array.isArray(l)?l.map(u=>typeof u=="string"?u:typeof u=="object"&&u!==null&&"text"in u?u.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(i){return`Error generating summary: ${i}`}}async function Xp(t,e,n){if(n===void 0)return t;try{return await li(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const Zp=nr().args(le(),le(),le()).returns(Ie([ne(),ai(ne())])),bl=["approve","edit","reject"],Qp=Wt(bl),em=z({allowedDecisions:We(Qp),description:Ie([ne(),Zp]).optional(),argsSchema:fn($s()).optional()}),Go=z({interruptOn:fn(Ie([rr(),em])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function tm(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"}
95
95
 
96
96
  Tool: ${a}
97
- 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 U({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 ge({name:"HumanInTheLoopMiddleware",contextSchema:Wo,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=Xe(Wo,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(v=>O.isInstance(v));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const l={};for(const[v,k]of Object.entries(o.interruptOn))typeof k=="boolean"?k===!0&&(l[v]={allowedDecisions:[...bl]}):k.allowedDecisions&&(l[v]=k);const c=[],u=[];for(const v of a.tool_calls)v.name in l?c.push(v):u.push(v);if(!c.length)return;const h=[],d=[];for(const v of c){const k=l[v.name],{actionRequest:M,reviewConfig:w}=await e(v,k,r,s);h.push(M),d.push(w)}const p=(await qa({actionRequests:h,reviewConfigs:d})).decisions;if(!p||!Array.isArray(p))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(p.length!==c.length)throw new Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${c.length}).`);const S=[...u],C=[],y=p.some(v=>v.type==="reject");for(let v=0;v<p.length;v++){const k=p[v],M=c[v],w=l[M.name],{revisedToolCall:b,toolMessage:T}=n(k,M,w);b&&(!y||k.type==="reject")&&S.push(b),T&&C.push(T)}O.isInstance(a)&&(a.tool_calls=S);const _=y?"model":void 0;return{messages:[a,...C],jumpTo:_}}}})}const Yp=!0,Xp="5m",Zp=3,Qp="warn",em=z({enableCaching:rr().optional(),ttl:Ht(["5m","1h"]).optional(),minMessagesToCache:V().optional(),unsupportedModelBehavior:Ht(["ignore","warn","raise"]).optional()});var Go=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function tm(t){return ge({name:"PromptCachingMiddleware",contextSchema:em,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??Yp,s=e.runtime.context.ttl??t?.ttl??Xp,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??Zp,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??Qp;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 Go(`${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 Go("Last message content is not a string or array")}})}function nm(t){return ge({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const r=await t(e.state,e.runtime);if(typeof r!="string")throw new Error("dynamicSystemPromptMiddleware function must return a string");return n({...e,systemPrompt:r})}})}const rm="Your goal is to select the most relevant tools for answering the user's query.";function sm(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>Ct(r.name)),n=Ie(e);return z({tools:He(n).describe("Tools to use. Place the most relevant tools first.")})}const om=z({model:ne().or(sr(uc)).optional(),systemPrompt:ne().optional(),maxTools:V().optional(),alwaysInclude:He(ne()).optional()});function im(t){return ge({name:"LLMToolSelector",contextSchema:om,async wrapModelCall(e,n){const r=await am(e,t,e.runtime);if(!r)return n(e);const s=sm(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(lm(i,r.availableTools,r.validToolNames,e,t))}})}async function am(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??rm;if(!t.tools||t.tools.length===0)return;const a=t.tools.filter(f=>typeof f=="object"&&"name"in f&&"description"in f&&typeof f.name=="string");if(o.length>0){const f=new Set(a.map(p=>p.name)),g=o.filter(p=>!f.has(p));if(g.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${g.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!o.includes(f.name));if(l.length===0)return;let c=i;s!==void 0&&(c+=`
98
- IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${s} will be used.`);let u;for(const f of t.messages)pe.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await Zt(r):r:t.model,d=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:h,validToolNames:d}}function lm(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]}}const cm=z({rules:fn(ne(),sr(RegExp).describe("Regular expression pattern to match PII")).optional()});function um(){return Math.random().toString(36).substring(2,11)}function Zr(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=um();return n[l]=a,`[REDACTED_${i}_${l}]`})}return r}async function hm(t,e){if(pe.isInstance(t)||U.isInstance(t)||_e.isInstance(t)){const n=t.content,r=await Zr(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(O.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await Zr(n,e.rules,e.redactionMap),o=await Zr(r,e.rules,e.redactionMap);return s!==n||o!==r?new O({...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 un(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 Ko(t,e){if(pe.isInstance(t)||U.isInstance(t)||_e.isInstance(t)){const n=t.content,r=un(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(O.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=un(n,e),o=un(r,e);return s!==n||o!==r?{message:new O({...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 dm(t={}){const e={};return ge({name:"PIIRedactionMiddleware",contextSchema:cm,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=>hm(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(!O.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=Ko(r,e);if(!i)return;let a;if(O.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(un(r.content,e))}catch{}if(O.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=Ko(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(un(JSON.stringify(h),e)):void 0;if(i||u)return{...n,...d?{structuredResponse:d}:{},messages:[new jn({id:s.id}),new jn({id:r.id}),c,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new jn({id:r.id}),o]}}})}const fm="[cleared]";var vl=class{triggerTokens;clearAtLeast;keep;clearToolInputs;excludeTools;placeholder;constructor(t={}){this.triggerTokens=t.triggerTokens??1e5,this.clearAtLeast=t.clearAtLeast??0,this.keep=t.keep??3,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??fm}async apply(t){const{tokens:e,messages:n,countTokens:r}=t;if(e<=this.triggerTokens)return e;const s=[];for(let a=0;a<n.length;a++){const l=n[a];U.isInstance(l)&&s.push({idx:a,msg:l})}const o=this.keep>=s.length?[]:this.keep>0?s.slice(0,-this.keep):s;let i=0;for(const{idx:a,msg:l}of o){if(this.clearAtLeast>0&&i>=this.clearAtLeast)break;if(l.response_metadata?.context_editing?.cleared)continue;const u=this.#e(n.slice(0,a),l.tool_call_id);if(!u)continue;const h=u.tool_calls?.find(g=>g.id===l.tool_call_id);if(!h)continue;const d=l.name||h.name;if(this.excludeTools.has(d))continue;if(n[a]=new U({tool_call_id:l.tool_call_id,content:this.placeholder,name:l.name,artifact:void 0,response_metadata:{...l.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const g=n.indexOf(u);g>=0&&(n[g]=this.#n(u,l.tool_call_id))}const f=await r(n);i=Math.max(0,e-f)}return e-i}#e(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(O.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#n(t,e){const n=t.tool_calls?.map(i=>i.id===e?{...i,args:{}}:i),r={...t.response_metadata},s={...r.context_editing},o=new Set(s.cleared_tool_inputs);return o.add(e),s.cleared_tool_inputs=Array.from(o).sort(),r.context_editing=s,new O({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function pm(t={}){const e=t.edits??[new vl],n=t.tokenCountMethod??"approx";return ge({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new _e(r.systemPrompt)]:[],i=n==="approx"?Ls:async l=>{const c=[...o,...l];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(c).then(({totalCount:u})=>u);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};let a=await i(r.messages);for(const l of e)a=await l.apply({tokens:a,messages:r.messages,countTokens:i});return s(r)}})}function mm(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const gm=["continue","error","end"],_l="continue";function Sl(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 Cl=Ht(gm).default(_l);var kl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=Sl(t,e,n,r,s);super(o),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=r,this.toolName=s}};z({toolName:ne().optional(),threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:Cl});const ym=z({threadToolCallCount:fn(ne(),V()).default({}),runToolCallCount:fn(ne(),V()).default({})}),wm="__all__";function bm(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??_l,n=Cl.safeParse(e);if(!n.success)throw new Error(ei(n.error).slice(2));if(t.threadLimit!==void 0&&t.runLimit!==void 0&&t.runLimit>t.threadLimit)throw new Error(`runLimit (${t.runLimit}) cannot exceed threadLimit (${t.threadLimit}). The run limit should be less than or equal to the thread limit.`);const r=t.toolName?`ToolCallLimitMiddleware[${t.toolName}]`:"ToolCallLimitMiddleware";return ge({name:r,stateSchema:ym,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(O.isInstance);if(!o||!o.tool_calls)return;const i=(v,k)=>t.threadLimit!==void 0&&v+1>t.threadLimit||t.runLimit!==void 0&&k+1>t.runLimit,a=v=>t.toolName===void 0||v.name===t.toolName,l=(v,k,M)=>{const w=[],b=[];let T=k,x=M;for(const A of v)a(A)&&(i(T,x)?b.push(A):(w.push(A),T+=1,x+=1));return{allowed:w,blocked:b,finalThreadCount:T,finalRunCount:x+b.length}},c=t.toolName??wm,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:g,blocked:p,finalThreadCount:S,finalRunCount:C}=l(o.tool_calls,d,f);if(u[c]=S,h[c]=C,p.length===0)return g.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const v=S+p.length;throw new kl(v,C,t.threadLimit,t.runLimit,t.toolName)}const y=mm(t.toolName),_=p.map(v=>new U({content:y,tool_call_id:v.id,name:v.name,status:"error"}));if(e==="end"){let v=[];if(t.toolName!==void 0?v=o.tool_calls.filter(w=>w.name!==t.toolName):new Set(o.tool_calls.map(b=>b.name).filter(Boolean)).size>1&&(v=g.length>0?g:o.tool_calls),v.length>0){const w=Array.from(new Set(v.map(b=>b.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${w}. Use 'continue' or 'error' behavior instead.`)}const k=S+p.length,M=Sl(k,C,t.threadLimit,t.runLimit,t.toolName);return _.push(new O(M)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:_}}return{threadToolCallCount:u,runToolCallCount:h,messages:_}}},afterAgent:()=>({runToolCallCount:{}})})}const vm=`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.
97
+ 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 U({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 ge({name:"HumanInTheLoopMiddleware",contextSchema:Go,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const o=Xe(Go,{...t,...s.context||{}});if(!o)return;const{messages:i}=r;if(!i.length)return;const a=[...i].reverse().find(b=>O.isInstance(b));if(!a||!a.tool_calls?.length||!o.interruptOn)return;const l={};for(const[b,k]of Object.entries(o.interruptOn))typeof k=="boolean"?k===!0&&(l[b]={allowedDecisions:[...bl]}):k.allowedDecisions&&(l[b]=k);const c=[],u=[];for(const b of a.tool_calls)b.name in l?c.push(b):u.push(b);if(!c.length)return;const h=[],d=[];for(const b of c){const k=l[b.name],{actionRequest:M,reviewConfig:w}=await e(b,k,r,s);h.push(M),d.push(w)}const p=(await Ja({actionRequests:h,reviewConfigs:d})).decisions;if(!p||!Array.isArray(p))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(p.length!==c.length)throw new Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${c.length}).`);const S=[...u],C=[],y=p.some(b=>b.type==="reject");for(let b=0;b<p.length;b++){const k=p[b],M=c[b],w=l[M.name],{revisedToolCall:v,toolMessage:T}=n(k,M,w);v&&(!y||k.type==="reject")&&S.push(v),T&&C.push(T)}O.isInstance(a)&&(a.tool_calls=S);const _=y?"model":void 0;return{messages:[a,...C],jumpTo:_}}}})}const nm=!0,rm="5m",sm=3,om="warn",im=z({enableCaching:rr().optional(),ttl:Wt(["5m","1h"]).optional(),minMessagesToCache:V().optional(),unsupportedModelBehavior:Wt(["ignore","warn","raise"]).optional()});var Ko=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function am(t){return ge({name:"PromptCachingMiddleware",contextSchema:im,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??nm,s=e.runtime.context.ttl??t?.ttl??rm,o=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??sm,i=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??om;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 Ko(`${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 Ko("Last message content is not a string or array")}})}function lm(t){return ge({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const r=await t(e.state,e.runtime);if(typeof r!="string")throw new Error("dynamicSystemPromptMiddleware function must return a string");return n({...e,systemPrompt:r})}})}const cm="Your goal is to select the most relevant tools for answering the user's query.";function um(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>Ct(r.name)),n=Ie(e);return z({tools:We(n).describe("Tools to use. Place the most relevant tools first.")})}const hm=z({model:ne().or(sr(fc)).optional(),systemPrompt:ne().optional(),maxTools:V().optional(),alwaysInclude:We(ne()).optional()});function dm(t){return ge({name:"LLMToolSelector",contextSchema:hm,async wrapModelCall(e,n){const r=await fm(e,t,e.runtime);if(!r)return n(e);const s=um(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(pm(i,r.availableTools,r.validToolNames,e,t))}})}async function fm(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??cm;if(!t.tools||t.tools.length===0)return;const a=t.tools.filter(f=>typeof f=="object"&&"name"in f&&"description"in f&&typeof f.name=="string");if(o.length>0){const f=new Set(a.map(p=>p.name)),g=o.filter(p=>!f.has(p));if(g.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${g.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!o.includes(f.name));if(l.length===0)return;let c=i;s!==void 0&&(c+=`
98
+ IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${s} will be used.`);let u;for(const f of t.messages)pe.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await Zt(r):r:t.model,d=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:h,validToolNames:d}}function pm(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]}}const mm=z({rules:fn(ne(),sr(RegExp).describe("Regular expression pattern to match PII")).optional()});function gm(){return Math.random().toString(36).substring(2,11)}function Zr(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=gm();return n[l]=a,`[REDACTED_${i}_${l}]`})}return r}async function ym(t,e){if(pe.isInstance(t)||U.isInstance(t)||_e.isInstance(t)){const n=t.content,r=await Zr(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(O.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await Zr(n,e.rules,e.redactionMap),o=await Zr(r,e.rules,e.redactionMap);return s!==n||o!==r?new O({...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 un(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 qo(t,e){if(pe.isInstance(t)||U.isInstance(t)||_e.isInstance(t)){const n=t.content,r=un(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(O.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=un(n,e),o=un(r,e);return s!==n||o!==r?{message:new O({...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 wm(t={}){const e={};return ge({name:"PIIRedactionMiddleware",contextSchema:mm,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=>ym(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(!O.isInstance(r))return;const s=n.messages.at(-2),{message:o,changed:i}=qo(r,e);if(!i)return;let a;if(O.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(un(r.content,e))}catch{}if(O.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=qo(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(un(JSON.stringify(h),e)):void 0;if(i||u)return{...n,...d?{structuredResponse:d}:{},messages:[new jn({id:s.id}),new jn({id:r.id}),c,o]}}return{...n,...a?{structuredResponse:a}:{},messages:[new jn({id:r.id}),o]}}})}const vm="[cleared]";var _l=class{triggerTokens;clearAtLeast;keep;clearToolInputs;excludeTools;placeholder;constructor(t={}){this.triggerTokens=t.triggerTokens??1e5,this.clearAtLeast=t.clearAtLeast??0,this.keep=t.keep??3,this.clearToolInputs=t.clearToolInputs??!1,this.excludeTools=new Set(t.excludeTools??[]),this.placeholder=t.placeholder??vm}async apply(t){const{tokens:e,messages:n,countTokens:r}=t;if(e<=this.triggerTokens)return e;const s=[];for(let a=0;a<n.length;a++){const l=n[a];U.isInstance(l)&&s.push({idx:a,msg:l})}const o=this.keep>=s.length?[]:this.keep>0?s.slice(0,-this.keep):s;let i=0;for(const{idx:a,msg:l}of o){if(this.clearAtLeast>0&&i>=this.clearAtLeast)break;if(l.response_metadata?.context_editing?.cleared)continue;const u=this.#e(n.slice(0,a),l.tool_call_id);if(!u)continue;const h=u.tool_calls?.find(g=>g.id===l.tool_call_id);if(!h)continue;const d=l.name||h.name;if(this.excludeTools.has(d))continue;if(n[a]=new U({tool_call_id:l.tool_call_id,content:this.placeholder,name:l.name,artifact:void 0,response_metadata:{...l.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const g=n.indexOf(u);g>=0&&(n[g]=this.#n(u,l.tool_call_id))}const f=await r(n);i=Math.max(0,e-f)}return e-i}#e(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(O.isInstance(r)&&r.tool_calls?.some(o=>o.id===e))return r}return null}#n(t,e){const n=t.tool_calls?.map(i=>i.id===e?{...i,args:{}}:i),r={...t.response_metadata},s={...r.context_editing},o=new Set(s.cleared_tool_inputs);return o.add(e),s.cleared_tool_inputs=Array.from(o).sort(),r.context_editing=s,new O({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function bm(t={}){const e=t.edits??[new _l],n=t.tokenCountMethod??"approx";return ge({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const o=r.systemPrompt?[new _e(r.systemPrompt)]:[],i=n==="approx"?Ls:async l=>{const c=[...o,...l];if("getNumTokensFromMessages"in r.model)return r.model.getNumTokensFromMessages(c).then(({totalCount:u})=>u);throw new Error(`Model "${r.model.getName()}" does not support token counting`)};let a=await i(r.messages);for(const l of e)a=await l.apply({tokens:a,messages:r.messages,countTokens:i});return s(r)}})}function _m(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const Sm=["continue","error","end"],Sl="continue";function Cl(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 kl=Wt(Sm).default(Sl);var Tl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const o=Cl(t,e,n,r,s);super(o),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=r,this.toolName=s}};z({toolName:ne().optional(),threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:kl});const Cm=z({threadToolCallCount:fn(ne(),V()).default({}),runToolCallCount:fn(ne(),V()).default({})}),km="__all__";function Tm(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??Sl,n=kl.safeParse(e);if(!n.success)throw new Error(ti(n.error).slice(2));if(t.threadLimit!==void 0&&t.runLimit!==void 0&&t.runLimit>t.threadLimit)throw new Error(`runLimit (${t.runLimit}) cannot exceed threadLimit (${t.threadLimit}). The run limit should be less than or equal to the thread limit.`);const r=t.toolName?`ToolCallLimitMiddleware[${t.toolName}]`:"ToolCallLimitMiddleware";return ge({name:r,stateSchema:Cm,afterModel:{canJumpTo:["end"],hook:s=>{const o=[...s.messages].reverse().find(O.isInstance);if(!o||!o.tool_calls)return;const i=(b,k)=>t.threadLimit!==void 0&&b+1>t.threadLimit||t.runLimit!==void 0&&k+1>t.runLimit,a=b=>t.toolName===void 0||b.name===t.toolName,l=(b,k,M)=>{const w=[],v=[];let T=k,x=M;for(const A of b)a(A)&&(i(T,x)?v.push(A):(w.push(A),T+=1,x+=1));return{allowed:w,blocked:v,finalThreadCount:T,finalRunCount:x+v.length}},c=t.toolName??km,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:g,blocked:p,finalThreadCount:S,finalRunCount:C}=l(o.tool_calls,d,f);if(u[c]=S,h[c]=C,p.length===0)return g.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const b=S+p.length;throw new Tl(b,C,t.threadLimit,t.runLimit,t.toolName)}const y=_m(t.toolName),_=p.map(b=>new U({content:y,tool_call_id:b.id,name:b.name,status:"error"}));if(e==="end"){let b=[];if(t.toolName!==void 0?b=o.tool_calls.filter(w=>w.name!==t.toolName):new Set(o.tool_calls.map(v=>v.name).filter(Boolean)).size>1&&(b=g.length>0?g:o.tool_calls),b.length>0){const w=Array.from(new Set(b.map(v=>v.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${w}. Use 'continue' or 'error' behavior instead.`)}const k=S+p.length,M=Cl(k,C,t.threadLimit,t.runLimit,t.toolName);return _.push(new O(M)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:_}}return{threadToolCallCount:u,runToolCallCount:h,messages:_}}},afterAgent:()=>({runToolCallCount:{}})})}const Em=`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.
99
99
  It also helps the user understand the progress of the task and overall progress of their requests.
100
100
  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.
101
101
 
@@ -307,7 +307,7 @@ Using the todo list here is overkill and wastes time and tokens. These three too
307
307
  - Use clear, descriptive task names
308
308
 
309
309
  Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
310
- 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.`,Tl=`## \`write_todos\`
310
+ 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.`,El=`## \`write_todos\`
311
311
 
312
312
  You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
313
313
  Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
@@ -319,25 +319,25 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
319
319
 
320
320
  ## Important To-Do List Usage Notes to Remember
321
321
  - The \`write_todos\` tool should never be called multiple times in parallel.
322
- - 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.`,_m=Ht(["pending","in_progress","completed"]).describe("Status of the todo"),El=z({content:ne().describe("Content of the todo item"),status:_m}),Sm=z({todos:He(El).default([])});function Cm(t){const e=ti(({todos:n},r)=>new K({update:{todos:n,messages:[new U({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??vm,schema:z({todos:He(El).describe("List of todo items to update")})});return ge({name:"todoListMiddleware",stateSchema:Sm,tools:[e],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
322
+ - 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.`,xm=Wt(["pending","in_progress","completed"]).describe("Status of the todo"),xl=z({content:ne().describe("Content of the todo item"),status:xm}),Mm=z({todos:We(xl).default([])});function Am(t){const e=ni(({todos:n},r)=>new K({update:{todos:n,messages:[new U({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??Em,schema:z({todos:We(xl).describe("List of todo items to update")})});return ge({name:"todoListMiddleware",stateSchema:Mm,tools:[e],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
323
323
 
324
- `:"")+(t?.systemPrompt??Tl)})})}const km="end",Tm=z({threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:Ht(["throw","end"]).optional()}),Em=z({threadModelCallCount:V().default(0),runModelCallCount:V().default(0)});var qo=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 xl(t){return ge({name:"ModelCallLimitMiddleware",contextSchema:Tm,stateSchema:Em,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??km,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 qo({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new qo({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function xm(...t){return ge({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(r){for(let s=0;s<t.length;s++)try{const o=t[s],i=typeof o=="string"?await Zt(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}function Mm(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 Jo=z({maxRetries:V().min(0).default(2),tools:He(Ie([le(),le(),ne()])).optional(),retryOn:Ie([nr().args(sr(Error)).returns(rr()),He(le())]).default(()=>()=>!0),onFailure:Ie([Ct("raise"),Ct("return_message"),nr().args(sr(Error)).returns(ne())]).default("return_message"),backoffFactor:V().min(0).default(2),initialDelayMs:V().min(0).default(1e3),maxDelayMs:V().min(0).default(6e4),jitter:rr().default(!0)});function Am(t={}){const{maxRetries:e,tools:n,retryOn:r,onFailure:s,backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:l}=Jo.parse(t),c=[];for(const p of n??[])if(typeof p=="string")c.push(p);else if("name"in p&&typeof p.name=="string")c.push(p.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const u=p=>c.length===0?!0:c.includes(p),h=p=>typeof r=="function"?r(p):r.some(S=>p.constructor===S),d={backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:l},f=(p,S,C)=>{const y=S.constructor.name;return`Tool '${p}' failed after ${C} ${C===1?"attempt":"attempts"} with ${y}`},g=(p,S,C,y)=>{if(s==="raise")throw C;let _;return typeof s=="function"?_=s(C):_=f(p,C,y),new U({content:_,tool_call_id:S,name:p,status:"error"})};return ge({name:"toolRetryMiddleware",contextSchema:Jo,wrapToolCall:async(p,S)=>{const C=p.tool.name;if(!u(C))return S(p);const y=p.toolCall.id??"";for(let _=0;_<=e;_++)try{return await S(p)}catch(v){const k=_+1,M=v&&typeof v=="object"&&"message"in v?v:new Error(String(v));if(!h(M))return g(C,y,M,k);if(_<e){const w=Mm(d,_);w>0&&await ku(w)}else return g(C,y,M,k)}throw new Error("Unexpected: retry loop completed without returning")}})}var Pm={};hi(Pm,{AIMessage:()=>O,AIMessageChunk:()=>Vt,BaseMessage:()=>an,BaseMessageChunk:()=>eu,ClearToolUsesEdit:()=>vl,Document:()=>Be,DynamicStructuredTool:()=>Rn,DynamicTool:()=>zl,FakeToolCallingModel:()=>vd,HumanMessage:()=>pe,HumanMessageChunk:()=>Qc,InMemoryStore:()=>Ei,MultipleStructuredOutputsError:()=>ss,MultipleToolsBoundError:()=>rs,ProviderStrategy:()=>it,StructuredOutputParsingError:()=>mi,StructuredTool:()=>_r,SystemMessage:()=>_e,SystemMessageChunk:()=>Zc,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>Tl,Tool:()=>Bl,ToolCallLimitExceededError:()=>kl,ToolInvocationError:()=>Rs,ToolMessage:()=>U,ToolMessageChunk:()=>Xc,ToolStrategy:()=>Ge,anthropicPromptCachingMiddleware:()=>tm,contextEditingMiddleware:()=>pm,countTokensApproximately:()=>Ls,createAgent:()=>gl,createMiddleware:()=>ge,dynamicSystemPromptMiddleware:()=>nm,filterMessages:()=>Yc,humanInTheLoopMiddleware:()=>Jp,initChatModel:()=>Zt,llmToolSelectorMiddleware:()=>im,modelCallLimitMiddleware:()=>xl,modelFallbackMiddleware:()=>xm,piiRedactionMiddleware:()=>dm,providerStrategy:()=>Su,summarizationMiddleware:()=>Rp,todoListMiddleware:()=>Cm,tool:()=>ti,toolCallLimitMiddleware:()=>bm,toolRetryMiddleware:()=>Am,toolStrategy:()=>_u,trimMessages:()=>ai});var As={},Pt,xr=(Pt=class extends _r{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(e){super(),this._manager=e}async _call(e,n,r){throw new Error("Method not implemented.")}get manager(){return this._manager}},N(Pt,"MCPServerTool"),Pt),Om=we({}),Ot,Nm=(Ot=class extends xr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Om;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."}},N(Ot,"AcquireActiveMCPServerTool"),Ot),Nt,Im=(Nt=class extends _r{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=we({serverName:vr().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.`;m.debug(`Connecting to new server '${e}' and discovering tools.`);const o=(await this.manager.client.createSession(e)).connector,i=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=i,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=i.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
324
+ `:"")+(t?.systemPrompt??El)})})}const Pm="end",Om=z({threadLimit:V().optional(),runLimit:V().optional(),exitBehavior:Wt(["throw","end"]).optional()}),Nm=z({threadModelCallCount:V().default(0),runModelCallCount:V().default(0)});var Jo=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 Ml(t){return ge({name:"ModelCallLimitMiddleware",contextSchema:Om,stateSchema:Nm,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??Pm,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 Jo({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new Jo({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function Im(...t){return ge({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(r){for(let s=0;s<t.length;s++)try{const o=t[s],i=typeof o=="string"?await Zt(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}function $m(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 Yo=z({maxRetries:V().min(0).default(2),tools:We(Ie([le(),le(),ne()])).optional(),retryOn:Ie([nr().args(sr(Error)).returns(rr()),We(le())]).default(()=>()=>!0),onFailure:Ie([Ct("raise"),Ct("return_message"),nr().args(sr(Error)).returns(ne())]).default("return_message"),backoffFactor:V().min(0).default(2),initialDelayMs:V().min(0).default(1e3),maxDelayMs:V().min(0).default(6e4),jitter:rr().default(!0)});function Rm(t={}){const{maxRetries:e,tools:n,retryOn:r,onFailure:s,backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:l}=Yo.parse(t),c=[];for(const p of n??[])if(typeof p=="string")c.push(p);else if("name"in p&&typeof p.name=="string")c.push(p.name);else throw new TypeError("Expected a tool name string or tool instance to be passed to toolRetryMiddleware");const u=p=>c.length===0?!0:c.includes(p),h=p=>typeof r=="function"?r(p):r.some(S=>p.constructor===S),d={backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:l},f=(p,S,C)=>{const y=S.constructor.name;return`Tool '${p}' failed after ${C} ${C===1?"attempt":"attempts"} with ${y}`},g=(p,S,C,y)=>{if(s==="raise")throw C;let _;return typeof s=="function"?_=s(C):_=f(p,C,y),new U({content:_,tool_call_id:S,name:p,status:"error"})};return ge({name:"toolRetryMiddleware",contextSchema:Yo,wrapToolCall:async(p,S)=>{const C=p.tool.name;if(!u(C))return S(p);const y=p.toolCall.id??"";for(let _=0;_<=e;_++)try{return await S(p)}catch(b){const k=_+1,M=b&&typeof b=="object"&&"message"in b?b:new Error(String(b));if(!h(M))return g(C,y,M,k);if(_<e){const w=$m(d,_);w>0&&await Pu(w)}else return g(C,y,M,k)}throw new Error("Unexpected: retry loop completed without returning")}})}var jm={};di(jm,{AIMessage:()=>O,AIMessageChunk:()=>Vt,BaseMessage:()=>an,BaseMessageChunk:()=>ru,ClearToolUsesEdit:()=>_l,Document:()=>Be,DynamicStructuredTool:()=>Rn,DynamicTool:()=>Gl,FakeToolCallingModel:()=>Ed,HumanMessage:()=>pe,HumanMessageChunk:()=>nu,InMemoryStore:()=>xi,MultipleStructuredOutputsError:()=>ss,MultipleToolsBoundError:()=>rs,ProviderStrategy:()=>it,StructuredOutputParsingError:()=>gi,StructuredTool:()=>_r,SystemMessage:()=>_e,SystemMessageChunk:()=>tu,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>El,Tool:()=>Hl,ToolCallLimitExceededError:()=>Tl,ToolInvocationError:()=>Rs,ToolMessage:()=>U,ToolMessageChunk:()=>eu,ToolStrategy:()=>Ge,anthropicPromptCachingMiddleware:()=>am,contextEditingMiddleware:()=>bm,countTokensApproximately:()=>Ls,createAgent:()=>yl,createMiddleware:()=>ge,dynamicSystemPromptMiddleware:()=>lm,filterMessages:()=>Qc,humanInTheLoopMiddleware:()=>tm,initChatModel:()=>Zt,llmToolSelectorMiddleware:()=>dm,modelCallLimitMiddleware:()=>Ml,modelFallbackMiddleware:()=>Im,piiRedactionMiddleware:()=>wm,providerStrategy:()=>Mu,summarizationMiddleware:()=>Vp,todoListMiddleware:()=>Am,tool:()=>ni,toolCallLimitMiddleware:()=>Tm,toolRetryMiddleware:()=>Rm,toolStrategy:()=>xu,trimMessages:()=>li});var As={},Pt,xr=(Pt=class extends _r{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(e){super(),this._manager=e}async _call(e,n,r){throw new Error("Method not implemented.")}get manager(){return this._manager}},N(Pt,"MCPServerTool"),Pt),Lm=we({}),Ot,Dm=(Ot=class extends xr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Lm;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."}},N(Ot,"AcquireActiveMCPServerTool"),Ot),Nt,Fm=(Nt=class extends _r{name="add_mcp_server_from_config";description="Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";schema=we({serverName:br().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.`;m.debug(`Connecting to new server '${e}' and discovering tools.`);const o=(await this.manager.client.createSession(e)).connector,i=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=i,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=i.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
325
325
 
326
326
  ${i.map(l=>l.name).join(`
327
- `)}`,m.info(r),r}catch(r){return m.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},N(Nt,"AddMCPServerFromConfigTool"),Nt),$m=we({serverName:vr().describe("The name of the MCP server.")}),It,Rm=(It=class extends xr{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=$m;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(m.debug(`Using existing session for server '${e}'`),r||(m.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,!this.manager.serverTools[e]){const i=r.connector,a=await this.manager.adapter.createToolsFromConnectors([i]),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,m.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 m.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},N(It,"ConnectMCPServerTool"),It),jm=we({}),$t,Lm=($t=class extends xr{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=jm;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
327
+ `)}`,m.info(r),r}catch(r){return m.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},N(Nt,"AddMCPServerFromConfigTool"),Nt),Um=we({serverName:br().describe("The name of the MCP server.")}),It,Vm=(It=class extends xr{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=Um;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(m.debug(`Using existing session for server '${e}'`),r||(m.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,!this.manager.serverTools[e]){const i=r.connector,a=await this.manager.adapter.createToolsFromConnectors([i]),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,m.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 m.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},N(It,"ConnectMCPServerTool"),It),Bm=we({}),$t,zm=($t=class extends xr{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=Bm;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
328
328
  `)}catch(i){m.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
329
- `)}},N($t,"ListMCPServersTool"),$t),Dm=we({}),Rt,Fm=(Rt=class extends xr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Dm;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}'.`}},N(Rt,"ReleaseMCPServerConnectionTool"),Rt);function br(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)=>br(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)&&br(t[s],e[s]))}return!1}N(br,"isEqual");var jt,Yo=(jt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,m.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){m.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));m.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&m.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),m.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(m.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),m.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(h){m.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!br(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,m.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):m.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){m.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){m.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Im(this),new Lm(this),new Rm(this),new Nm(this),new Fm(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return m.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},N(jt,"ServerManager"),jt),Lt,Xo=(Lt=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 Ut(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>Qo);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Ut(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>Qo);return{initializeLangfuse:o}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),m.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),m.debug("ObservabilityManager: Langfuse handler available"))}catch{m.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(m.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?m.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):m.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(m.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),m.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],m.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();m.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();m.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},N(Lt,"ObservabilityManager"),Lt),Um="/api/v1/chats",Vm="/api/v1/chats/{chat_id}/execute";function Ml(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}}N(Ml,"normalizeRemoteRunOptions");var Dt,Bm=(Dt=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"&&As?.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 $n(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){m.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${Um}`;m.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),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 m.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:l,outputSchema:c}=Ml(e,n,r,s,o);l!==void 0&&m.warn("External history is not yet supported for remote execution");try{m.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,h={query:i,max_steps:a??10};c&&(h.output_schema=this.pydanticToJsonSchema(c),m.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${Vm.replace("{chat_id}",u)}`;m.info(`🚀 Executing agent in chat ${u}`);const g=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!g.ok){const S=await g.text(),C=g.status;throw C===401?(m.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?(m.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?(m.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?(m.error(`❌ Validation error: ${S}`),new Error(`Request validation failed: ${S}. Please check your query parameters and output schema format.`)):C===500?(m.error(`❌ Server error: ${S}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(m.error(`❌ Remote execution failed with status ${C}: ${S}`),new Error(`Remote agent execution failed: ${C} - ${S}`))}const p=await g.json();if(m.info(`🔧 Response: ${JSON.stringify(p)}`),m.info("✅ Remote execution completed successfully"),typeof p=="object"&&p!==null){if(p.status==="error"||p.error!==null){const S=p.error??String(p);throw m.error(`❌ Remote agent execution failed: ${S}`),new Error(`Remote agent execution failed: ${S}`)}if(String(p).includes("failed to initialize"))throw m.error(`❌ Agent initialization failed: ${p}`),new Error(`Agent initialization failed on remote server. This usually indicates:
329
+ `)}},N($t,"ListMCPServersTool"),$t),Wm=we({}),Rt,Hm=(Rt=class extends xr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Wm;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}'.`}},N(Rt,"ReleaseMCPServerConnectionTool"),Rt);function vr(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)=>vr(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)&&vr(t[s],e[s]))}return!1}N(vr,"isEqual");var jt,Xo=(jt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,m.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){m.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));m.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&m.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),m.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(m.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),m.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(h){m.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!vr(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,m.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):m.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){m.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){m.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Fm(this),new zm(this),new Vm(this),new Dm(this),new Hm(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return m.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},N(jt,"ServerManager"),jt),Lt,Zo=(Lt=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 Ut(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>ei);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Ut(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>ei);return{initializeLangfuse:o}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),m.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),m.debug("ObservabilityManager: Langfuse handler available"))}catch{m.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(m.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?m.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):m.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(m.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),m.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],m.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();m.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();m.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},N(Lt,"ObservabilityManager"),Lt),Gm="/api/v1/chats",Km="/api/v1/chats/{chat_id}/execute";function Al(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}}N(Al,"normalizeRemoteRunOptions");var Dt,qm=(Dt=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"&&As?.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 $n(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){m.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${Gm}`;m.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),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 m.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:l,outputSchema:c}=Al(e,n,r,s,o);l!==void 0&&m.warn("External history is not yet supported for remote execution");try{m.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,h={query:i,max_steps:a??10};c&&(h.output_schema=this.pydanticToJsonSchema(c),m.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${Km.replace("{chat_id}",u)}`;m.info(`🚀 Executing agent in chat ${u}`);const g=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!g.ok){const S=await g.text(),C=g.status;throw C===401?(m.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?(m.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?(m.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?(m.error(`❌ Validation error: ${S}`),new Error(`Request validation failed: ${S}. Please check your query parameters and output schema format.`)):C===500?(m.error(`❌ Server error: ${S}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(m.error(`❌ Remote execution failed with status ${C}: ${S}`),new Error(`Remote agent execution failed: ${C} - ${S}`))}const p=await g.json();if(m.info(`🔧 Response: ${JSON.stringify(p)}`),m.info("✅ Remote execution completed successfully"),typeof p=="object"&&p!==null){if(p.status==="error"||p.error!==null){const S=p.error??String(p);throw m.error(`❌ Remote agent execution failed: ${S}`),new Error(`Remote agent execution failed: ${S}`)}if(String(p).includes("failed to initialize"))throw m.error(`❌ Agent initialization failed: ${p}`),new Error(`Agent initialization failed on remote server. This usually indicates:
330
330
  • Invalid agent configuration (LLM model, system prompt)
331
331
  • Missing or invalid MCP server configurations
332
332
  • Network connectivity issues with MCP servers
333
333
  • Missing environment variables or credentials
334
- Raw error: ${p}`)}return c?this.parseStructuredResponse(p,c):typeof p=="object"&&p!==null&&"result"in p?p.result:typeof p=="string"?p:String(p)}catch(u){throw u instanceof Error?u.name==="AbortError"?(m.error(`❌ Remote execution timed out: ${u}`),new Error("Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.")):(m.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${u.message}`)):(m.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${String(u)}`))}}async*stream(e,n,r,s,o){return await this.run(e,n,r,s,o)}async close(){m.info("🔌 Remote agent client closed")}},N(Dt,"RemoteAgent"),Dt),_n={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 ao(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 _n)){const o=Object.keys(_n).join(", ");throw new Error(`Unsupported LLM provider '${n}'. Supported providers: ${o}`)}return{provider:s,model:r}}N(ao,"parseLLMString");function Al(t,e){if(e?.apiKey)return e.apiKey;const n=_n[t];if(typeof process<"u"&&As)for(const s of n.envVars){const o=As[s];if(o)return m.debug(`Using API key from environment variable ${s} for provider ${t}`),o}const r=n.envVars.join(" or ");throw new Error(`API key not found for provider '${t}'. Set ${r} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${t}/model', llmConfig: { apiKey: 'your-key' } })`)}N(Al,"getAPIKey");async function Pl(t,e){m.info(`Creating LLM from string: ${t}`);const{provider:n,model:r}=ao(t),s=_n[n],o=Al(n,e);let i;try{m.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 m.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}`)}}N(Pl,"createLLMFromString");function zm(t){try{return ao(t),!0}catch{return!1}}N(zm,"isValidLLMString");function Hm(){return Object.keys(_n)}N(Hm,"getSupportedProviders");function Ol(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}N(Ol,"generateToolDescriptions");function Nl(t,e,n){const r=e.join(`
334
+ Raw error: ${p}`)}return c?this.parseStructuredResponse(p,c):typeof p=="object"&&p!==null&&"result"in p?p.result:typeof p=="string"?p:String(p)}catch(u){throw u instanceof Error?u.name==="AbortError"?(m.error(`❌ Remote execution timed out: ${u}`),new Error("Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.")):(m.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${u.message}`)):(m.error(`❌ Remote execution error: ${u}`),new Error(`Remote agent execution failed: ${String(u)}`))}}async*stream(e,n,r,s,o){return await this.run(e,n,r,s,o)}async close(){m.info("🔌 Remote agent client closed")}},N(Dt,"RemoteAgent"),Dt),_n={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 ao(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 _n)){const o=Object.keys(_n).join(", ");throw new Error(`Unsupported LLM provider '${n}'. Supported providers: ${o}`)}return{provider:s,model:r}}N(ao,"parseLLMString");function Pl(t,e){if(e?.apiKey)return e.apiKey;const n=_n[t];if(typeof process<"u"&&As)for(const s of n.envVars){const o=As[s];if(o)return m.debug(`Using API key from environment variable ${s} for provider ${t}`),o}const r=n.envVars.join(" or ");throw new Error(`API key not found for provider '${t}'. Set ${r} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${t}/model', llmConfig: { apiKey: 'your-key' } })`)}N(Pl,"getAPIKey");async function Ol(t,e){m.info(`Creating LLM from string: ${t}`);const{provider:n,model:r}=ao(t),s=_n[n],o=Pl(n,e);let i;try{m.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 m.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}`)}}N(Ol,"createLLMFromString");function Jm(t){try{return ao(t),!0}catch{return!1}}N(Jm,"isValidLLMString");function Ym(){return Object.keys(_n)}N(Ym,"getSupportedProviders");function Nl(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}N(Nl,"generateToolDescriptions");function Il(t,e,n){const r=e.join(`
335
335
  `);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}
336
336
 
337
337
  Available tools:
338
338
  ${r}`),n&&(s+=`
339
339
 
340
- ${n}`),s}N(Nl,"buildSystemPromptContent");function Il(t,e,n,r,s,o,i){if(o)return new _e({content:o});const a=r?n:e,l=Ol(t,s),c=Nl(a,l,i);return new _e({content:c})}N(Il,"createSystemMessage");var Wm=`You are a helpful AI assistant.
340
+ ${n}`),s}N(Il,"buildSystemPromptContent");function $l(t,e,n,r,s,o,i){if(o)return new _e({content:o});const a=r?n:e,l=Nl(t,s),c=Il(a,l,i);return new _e({content:c})}N($l,"createSystemMessage");var Xm=`You are a helpful AI assistant.
341
341
  You have access to the following tools:
342
342
 
343
343
  {tool_descriptions}
@@ -351,7 +351,7 @@ Action Input: the input to the action
351
351
  Observation: the result of the action
352
352
  ... (this Thought/Action/Action Input/Observation can repeat N times)
353
353
  Thought: I now know the final answer
354
- Final Answer: the final answer to the original input question`,Gm=`You are a helpful assistant designed to interact with MCP
354
+ Final Answer: the final answer to the original input question`,Zm=`You are a helpful assistant designed to interact with MCP
355
355
  (Model Context Protocol) servers. You can manage connections to different servers and use the tools
356
356
  provided by the currently active server.
357
357
 
@@ -374,9 +374,9 @@ You can then use these server-specific tools in subsequent steps.
374
374
  Here are the tools *currently* available to you (this list includes server management tools and will
375
375
  change when you connect to a server):
376
376
  {tool_descriptions}
377
- `;function er(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}}N(er,"normalizeRunOptions");var Ft,sg=(Ft=class{static getPackageVersion(){return Ul()}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 Bm({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 gt,this.telemetry=Pr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Xo({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],m.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new gt(this.disallowedTools),this.telemetry=Pr.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 gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Yo(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Pr.getInstance(),this.llm){const[r,s]=co(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Xo({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:N(()=>this.getMetadata(),"metadataProvider"),tagsProvider:N(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:N(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:N(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:N(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(m.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(m.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){m.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ut(async()=>{const{MCPClient:s}=await import("./client-CAJCPqsR.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")}if(this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await Pl(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=co(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 Yo(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&m.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),m.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),m.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(m.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),m.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),m.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],m.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{m.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),m.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}m.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),m.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),m.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Wm;this.systemMessage=Il(e,n,Gm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);m.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[xl({runLimit:this.maxSteps})],s=gl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return m.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),m.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&m.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},m.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],m.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){m.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(m.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){m.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else m.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){m.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){m.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof pe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||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}=er(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}=er(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,g=null,p=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 M=this.serverManager.tools,w=new Set(M.map(T=>T.name)),b=new Set(this._tools.map(T=>T.name));(w.size!==b.size||[...w].some(T=>!b.has(T)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=M,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const M of S)(this._isHumanMessageLike(M)||this._isAIMessageLike(M)||this._isToolMessageLike(M))&&C.push(M);const y=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");m.info(`💬 Received query: '${y}'`),m.info("🏁 Starting agent execution");const _=3;let v=0;const k=[...C,new pe(i)];for(;v<=_;){const M={messages:k};let w=!1;const b=await this._agentExecutor.stream(M,{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 T of b){for(const[x,A]of Object.entries(T))if(m.debug(`📦 Node '${x}' output: ${JSON.stringify(A)}`),A&&typeof A=="object"&&"messages"in A){let I=A.messages;Array.isArray(I)||(I=[I]);for(const j of I)k.includes(j)||k.push(j);for(const j of I){if("tool_calls"in j&&Array.isArray(j.tool_calls)&&j.tool_calls.length>0)for(const ee of j.tool_calls){const re=ee.name||"unknown",Se=ee.args||{};this.toolsUsedNames.push(re),p++;let Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),yield{action:{tool:re,toolInput:Se,log:`Calling tool ${re}`},observation:""}}if(this._isToolMessageLike(j)){const ee=j.content;let re=String(ee);if(re.length>100&&(re=`${re.slice(0,97)}...`),re=re.replace(/\n/g," "),m.info(`📄 Tool result: ${re}`),this.useServerManager&&this.serverManager){const Se=this.serverManager.tools,Me=new Set(Se.map(en=>en.name)),xn=new Set(this._tools.map(en=>en.name));if(Me.size!==xn.size||[...Me].some(en=>!xn.has(en))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].join(", ")}`),this._tools=Se,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),w=!0,v++,m.info(`🔃 Restarting execution with updated tools (restart ${v}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(v>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const M=k.slice(C.length);for(const w of M)this.addToHistory(w)}if(u&&g)try{m.info("🔧 Attempting structured output...");const M=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(M)}`)),m.info("✅ Structured output successful"),f=!0,M}catch(M){throw m.error(`❌ Structured output failed: ${M}`),new Error(`Failed to generate structured output: ${M instanceof Error?M.message:String(M)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(S){throw m.error(`❌ Error running query: ${S}`),h&&l&&(m.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 y=this.memoryEnabled?this.conversationHistory.length:0,_=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(v=>v.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(v=>v.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:y}),l&&!this.client&&h&&(m.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(m.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}m.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(m.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(m.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)m.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(m.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ut(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-CQoSnHLt.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=er(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 g=!1,p=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 y=this._agentExecutor;if(!y)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const _=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);m.info(`💬 Received query for streamEvents: '${_}'`),this.memoryEnabled&&(m.info(`🔄 Adding user message to history: ${_}`),this.addToHistory(new pe({content:a})));const v=u??this.conversationHistory,k=[];for(const b of v)this._isHumanMessageLike(b)||this._isAIMessageLike(b)||this._isToolMessageLike(b)?k.push(b):m.info(`⚠️ Skipped message of type: ${b.constructor?.name||typeof b}`);const M=[...k,new pe(a)];m.info("callbacks",this.callbacks);const w=y.streamEvents({messages:M},{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 b of w)if(p++,!(!b||typeof b!="object")){if(b.event==="on_chat_model_stream"&&b.data?.chunk?.content&&(S+=b.data.chunk.content.length),b.event==="on_chat_model_stream"&&b.data?.chunk){const T=b.data.chunk;if(T.content){C||(C="");const x=this._normalizeOutput(T.content);C+=x,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield b,b.event==="on_chain_end"&&b.data?.output&&!C){const T=b.data.output;Array.isArray(T)&&T.length>0&&T[0]?.text?C=T[0].text:typeof T=="string"?C=T:T&&typeof T=="object"&&"output"in T&&(C=T.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let b=!1,T=null,x=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(b=!0,T=I,I)).catch(I=>{throw b=!0,x=I,I});let A=0;for(;!b;)await new Promise(I=>setTimeout(I,2e3)),b||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(x)throw x;T&&(yield{event:"on_structured_output",data:{output:T}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"))}catch(b){m.warn(`⚠️ Structured output failed: ${b}`),yield{event:"on_structured_output_error",data:{error:b instanceof Error?b.message:String(b)}}}}else this.memoryEnabled&&C&&this.addToHistory(new O(C));console.log(`
377
+ `;function er(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}}N(er,"normalizeRunOptions");var Ft,ug=(Ft=class{static getPackageVersion(){return zl()}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 qm({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 gt,this.telemetry=Pr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zo({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],m.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new gt(this.disallowedTools),this.telemetry=Pr.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 gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Xo(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Pr.getInstance(),this.llm){const[r,s]=uo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Zo({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:N(()=>this.getMetadata(),"metadataProvider"),tagsProvider:N(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:N(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:N(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:N(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(m.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(m.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){m.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await Ut(async()=>{const{MCPClient:s}=await import("./client-JeU2zpxn.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")}if(this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await Ol(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=uo(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 Xo(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&m.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),m.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),m.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(m.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),m.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),m.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],m.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{m.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),m.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}m.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),m.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),m.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Xm;this.systemMessage=$l(e,n,Zm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);m.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Ml({runLimit:this.maxSteps})],s=yl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return m.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),m.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&m.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},m.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],m.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){m.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(m.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){m.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else m.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){m.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){m.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof pe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||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}=er(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}=er(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,g=null,p=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 M=this.serverManager.tools,w=new Set(M.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=M,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const M of S)(this._isHumanMessageLike(M)||this._isAIMessageLike(M)||this._isToolMessageLike(M))&&C.push(M);const y=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");m.info(`💬 Received query: '${y}'`),m.info("🏁 Starting agent execution");const _=3;let b=0;const k=[...C,new pe(i)];for(;b<=_;){const M={messages:k};let w=!1;const v=await this._agentExecutor.stream(M,{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 T of v){for(const[x,A]of Object.entries(T))if(m.debug(`📦 Node '${x}' output: ${JSON.stringify(A)}`),A&&typeof A=="object"&&"messages"in A){let I=A.messages;Array.isArray(I)||(I=[I]);for(const j of I)k.includes(j)||k.push(j);for(const j of I){if("tool_calls"in j&&Array.isArray(j.tool_calls)&&j.tool_calls.length>0)for(const ee of j.tool_calls){const re=ee.name||"unknown",Se=ee.args||{};this.toolsUsedNames.push(re),p++;let Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),yield{action:{tool:re,toolInput:Se,log:`Calling tool ${re}`},observation:""}}if(this._isToolMessageLike(j)){const ee=j.content;let re=String(ee);if(re.length>100&&(re=`${re.slice(0,97)}...`),re=re.replace(/\n/g," "),m.info(`📄 Tool result: ${re}`),this.useServerManager&&this.serverManager){const Se=this.serverManager.tools,Me=new Set(Se.map(en=>en.name)),xn=new Set(this._tools.map(en=>en.name));if(Me.size!==xn.size||[...Me].some(en=>!xn.has(en))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].join(", ")}`),this._tools=Se,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),w=!0,b++,m.info(`🔃 Restarting execution with updated tools (restart ${b}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(b>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const M=k.slice(C.length);for(const w of M)this.addToHistory(w)}if(u&&g)try{m.info("🔧 Attempting structured output...");const M=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(M)}`)),m.info("✅ Structured output successful"),f=!0,M}catch(M){throw m.error(`❌ Structured output failed: ${M}`),new Error(`Failed to generate structured output: ${M instanceof Error?M.message:String(M)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(S){throw m.error(`❌ Error running query: ${S}`),h&&l&&(m.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 y=this.memoryEnabled?this.conversationHistory.length:0,_=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(b=>b.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(b=>b.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:y}),l&&!this.client&&h&&(m.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(m.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}m.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(m.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(m.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)m.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(m.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ut(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-Btv2gL3n.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=er(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 g=!1,p=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 y=this._agentExecutor;if(!y)throw new Error("MCP agent failed to initialize");this.maxSteps=l??this.maxSteps;const _=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);m.info(`💬 Received query for streamEvents: '${_}'`),this.memoryEnabled&&(m.info(`🔄 Adding user message to history: ${_}`),this.addToHistory(new pe({content:a})));const b=u??this.conversationHistory,k=[];for(const v of b)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?k.push(v):m.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const M=[...k,new pe(a)];m.info("callbacks",this.callbacks);const w=y.streamEvents({messages:M},{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 w)if(p++,!(!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 T=v.data.chunk;if(T.content){C||(C="");const x=this._normalizeOutput(T.content);C+=x,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const T=v.data.output;Array.isArray(T)&&T.length>0&&T[0]?.text?C=T[0].text:typeof T=="string"?C=T:T&&typeof T=="object"&&"output"in T&&(C=T.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let v=!1,T=null,x=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(v=!0,T=I,I)).catch(I=>{throw v=!0,x=I,I});let A=0;for(;!v;)await new Promise(I=>setTimeout(I,2e3)),v||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(x)throw x;T&&(yield{event:"on_structured_output",data:{output:T}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"))}catch(v){m.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 O(C));console.log(`
378
378
 
379
- `),m.info(`🎉 StreamEvents complete - ${p} events emitted`),g=!0}catch(y){throw m.error(`❌ Error during streamEvents: ${y}`),d&&c&&(m.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),y}finally{const y=Date.now()-f;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const v=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(k=>k.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(k=>k.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:y,errorType:g?null:"streaming_error",conversationHistoryLength:v}),c&&!this.client&&d&&(m.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){m.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),m.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(m.debug(`🔄 Structured output requested, schema: ${JSON.stringify($n(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=$n(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),m.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),m.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){m.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
379
+ `),m.info(`🎉 StreamEvents complete - ${p} events emitted`),g=!0}catch(y){throw m.error(`❌ Error during streamEvents: ${y}`),d&&c&&(m.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),y}finally{const y=Date.now()-f;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const b=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(k=>k.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(k=>k.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:y,errorType:g?null:"streaming_error",conversationHistoryLength:b}),c&&!this.client&&d&&(m.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){m.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),m.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(m.debug(`🔄 Structured output requested, schema: ${JSON.stringify($n(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=$n(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),m.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),m.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){m.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
380
380
  Please format the following information according to the EXACT schema specified below.
381
381
  You must use the exact field names and types as shown in the schema.
382
382
 
@@ -398,7 +398,7 @@ Here are the tools *currently* available to you (this list includes server manag
398
398
  PREVIOUS ATTEMPT FAILED with error: ${d}
399
399
  Please fix the issues mentioned above and ensure the output matches the schema exactly.
400
400
  `);try{m.info(`🔄 Structured output attempt ${f} - using streaming approach`);const p=u.length>300?`${u.slice(0,300)}...`:u;m.info(`🔄 Content being formatted (${u.length} chars): ${p}`),m.info(`🔄 Full format prompt (${g.length} chars):
401
- ${g}`);const S=await s.stream(g);let C=null,y=0;for await(const v of S){if(y++,m.debug(`Chunk ${y}: ${JSON.stringify(v,null,2)}`),typeof v=="string")try{C=JSON.parse(v)}catch{m.warn(`🔄 Failed to parse string chunk as JSON: ${v}`)}else if(v&&typeof v=="object")C=v;else try{C=JSON.parse(String(v))}catch{m.warn(`🔄 Failed to parse chunk as JSON: ${v}`)}y%10===0&&m.debug(`🔄 Structured output streaming: ${y} chunks`)}if(m.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(C,null,2)}`),!C)throw new Error("No structured result received from stream");const _=this._validateStructuredResult(C,r);return m.info(`✅ Structured output successful on attempt ${f}`),_}catch(p){if(d=p instanceof Error?p.message:String(p),m.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw m.error(`❌ All ${h} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${h} attempts. Last error: ${d}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(e,n){try{const r=n.parse(e),s=n;if(s._def&&s._def.shape)for(const[o,i]of Object.entries(s._def.shape)){const a=i,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 m.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=$n(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
401
+ ${g}`);const S=await s.stream(g);let C=null,y=0;for await(const b of S){if(y++,m.debug(`Chunk ${y}: ${JSON.stringify(b,null,2)}`),typeof b=="string")try{C=JSON.parse(b)}catch{m.warn(`🔄 Failed to parse string chunk as JSON: ${b}`)}else if(b&&typeof b=="object")C=b;else try{C=JSON.parse(String(b))}catch{m.warn(`🔄 Failed to parse chunk as JSON: ${b}`)}y%10===0&&m.debug(`🔄 Structured output streaming: ${y} chunks`)}if(m.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(C,null,2)}`),!C)throw new Error("No structured result received from stream");const _=this._validateStructuredResult(C,r);return m.info(`✅ Structured output successful on attempt ${f}`),_}catch(p){if(d=p instanceof Error?p.message:String(p),m.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw m.error(`❌ All ${h} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${h} attempts. Last error: ${d}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(e,n){try{const r=n.parse(e),s=n;if(s._def&&s._def.shape)for(const[o,i]of Object.entries(s._def.shape)){const a=i,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 m.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=$n(n),{$schema:s,additionalProperties:o,...i}=r,a=JSON.stringify(i,null,2);return`
402
402
  ${e}
403
403
 
404
404
  IMPORTANT: Your response must include sufficient information to populate the following structured output:
@@ -407,4 +407,4 @@ ${g}`);const S=await s.stream(g);let C=null,y=0;for await(const v of S){if(y++,m
407
407
 
408
408
  Make sure you gather ALL the required information during your task execution.
409
409
  If any required information is missing, continue working to find it.
410
- `}catch(r){return m.warn(`Could not extract schema details: ${r}`),e}}},N(Ft,"MCPAgent"),Ft),Zo={};function Y(t){if(typeof process<"u"&&Zo)return Zo[t]}N(Y,"getEnvVar");var Km=Y("MCP_USE_LANGFUSE")?.toLowerCase()==="false",Sn={handler:null,client:null,initPromise:null};async function lo(t,e,n,r){try{const s=await Ut(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){m.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,g,p,S){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=S,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,S,C,y,_){m.debug("Langfuse: Chain start intercepted");const v=this.getCustomTags(),k=this.getMetadata(),M=[...S||[],...v],w={...C||{},...k};return this.verbose&&(m.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(M)}`),m.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(w)}`)),super.handleChainStart(d,f,g,p,M,w,y,_)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const g=this.tagsProvider();g&&g.length>0&&d.push(...g)}return d}getMetadata(){const d={},f=this.getEnvironmentTag();if(f&&(d.env=f),this.agentId&&(d.agent_id=this.agentId),this.metadata&&Object.assign(d,this.metadata),this.metadataProvider){const g=this.metadataProvider();g&&Object.assign(d,g)}return d}getEnvironmentTag(){const d=Y("MCP_USE_AGENT_ENV");if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return m.debug("Langfuse: LLM start intercepted"),this.verbose&&m.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return m.debug("Langfuse: Tool start intercepted"),this.verbose&&m.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return m.debug("Langfuse: Retriever start intercepted"),this.verbose&&m.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return m.debug("Langfuse: Agent action intercepted"),this.verbose&&m.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return m.debug("Langfuse: Agent end intercepted"),this.verbose&&m.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};N(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Y("LANGFUSE_PUBLIC_KEY"),secretKey:Y("LANGFUSE_SECRET_KEY"),baseUrl:Y("LANGFUSE_HOST")||Y("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(Y("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(Y("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:Y("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(Y("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:Y("LANGFUSE_ENABLED")!=="false",traceName:a.trace_name||Y("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};m.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),Sn.handler=new i(c,t,e,n,r),m.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Ut(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Sn.client=new d({publicKey:Y("LANGFUSE_PUBLIC_KEY"),secretKey:Y("LANGFUSE_SECRET_KEY"),baseUrl:Y("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),m.debug("Langfuse client initialized")}}catch(h){m.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){m.debug(`Langfuse initialization error: ${s}`)}}N(lo,"initializeLangfuse");Km?m.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Y("LANGFUSE_PUBLIC_KEY")||!Y("LANGFUSE_SECRET_KEY")?m.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Sn.initPromise=lo();var qm=N(()=>Sn.handler,"langfuseHandler"),Jm=N(()=>Sn.initPromise,"langfuseInitPromise");const Qo=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:lo,langfuseHandler:qm,langfuseInitPromise:Jm},Symbol.toStringTag,{value:"Module"}));export{mu as BaseAdapter,ag as BaseConnector,lg as BrowserOAuthClientProvider,cg as BrowserTelemetry,ug as HttpConnector,hg as Logger,sg as MCPAgent,dg as MCPClient,fg as MCPSession,Xo as ObservabilityManager,Bm as RemoteAgent,pg as Tel,Pr as Telemetry,mg as VERSION,Pl as createLLMFromString,fu as createReadableStreamFromGenerator,Ul as getPackageVersion,Hm as getSupportedProviders,zm as isValidLLMString,m as logger,gg as onMcpAuthorization,ao as parseLLMString,yg as setBrowserTelemetrySource,wg as setTelemetrySource,du as streamEventsToAISDK,pu as streamEventsToAISDKWithTools};
410
+ `}catch(r){return m.warn(`Could not extract schema details: ${r}`),e}}},N(Ft,"MCPAgent"),Ft),Qo={};function Y(t){if(typeof process<"u"&&Qo)return Qo[t]}N(Y,"getEnvVar");var Qm=Y("MCP_USE_LANGFUSE")?.toLowerCase()==="false",Sn={handler:null,client:null,initPromise:null};async function lo(t,e,n,r){try{const s=await Ut(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){m.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,g,p,S){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=S,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,S,C,y,_){m.debug("Langfuse: Chain start intercepted");const b=this.getCustomTags(),k=this.getMetadata(),M=[...S||[],...b],w={...C||{},...k};return this.verbose&&(m.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(M)}`),m.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(w)}`)),super.handleChainStart(d,f,g,p,M,w,y,_)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const g=this.tagsProvider();g&&g.length>0&&d.push(...g)}return d}getMetadata(){const d={},f=this.getEnvironmentTag();if(f&&(d.env=f),this.agentId&&(d.agent_id=this.agentId),this.metadata&&Object.assign(d,this.metadata),this.metadataProvider){const g=this.metadataProvider();g&&Object.assign(d,g)}return d}getEnvironmentTag(){const d=Y("MCP_USE_AGENT_ENV");if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return m.debug("Langfuse: LLM start intercepted"),this.verbose&&m.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return m.debug("Langfuse: Tool start intercepted"),this.verbose&&m.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return m.debug("Langfuse: Retriever start intercepted"),this.verbose&&m.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return m.debug("Langfuse: Agent action intercepted"),this.verbose&&m.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return m.debug("Langfuse: Agent end intercepted"),this.verbose&&m.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};N(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Y("LANGFUSE_PUBLIC_KEY"),secretKey:Y("LANGFUSE_SECRET_KEY"),baseUrl:Y("LANGFUSE_HOST")||Y("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(Y("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(Y("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:Y("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(Y("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:Y("LANGFUSE_ENABLED")!=="false",traceName:a.trace_name||Y("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};m.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),Sn.handler=new i(c,t,e,n,r),m.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Ut(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Sn.client=new d({publicKey:Y("LANGFUSE_PUBLIC_KEY"),secretKey:Y("LANGFUSE_SECRET_KEY"),baseUrl:Y("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),m.debug("Langfuse client initialized")}}catch(h){m.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){m.debug(`Langfuse initialization error: ${s}`)}}N(lo,"initializeLangfuse");Qm?m.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Y("LANGFUSE_PUBLIC_KEY")||!Y("LANGFUSE_SECRET_KEY")?m.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Sn.initPromise=lo();var eg=N(()=>Sn.handler,"langfuseHandler"),tg=N(()=>Sn.initPromise,"langfuseInitPromise");const ei=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:lo,langfuseHandler:eg,langfuseInitPromise:tg},Symbol.toStringTag,{value:"Module"}));export{_u as BaseAdapter,fg as BaseConnector,pg as BrowserOAuthClientProvider,mg as BrowserTelemetry,gg as HttpConnector,yg as Logger,ug as MCPAgent,wg as MCPClient,vg as MCPSession,Zo as ObservabilityManager,qm as RemoteAgent,bg as Tel,Pr as Telemetry,_g as VERSION,Ol as createLLMFromString,vu as createReadableStreamFromGenerator,zl as getPackageVersion,Ym as getSupportedProviders,Jm as isValidLLMString,m as logger,Sg as onMcpAuthorization,ao as parseLLMString,Cg as setBrowserTelemetrySource,kg as setTelemetrySource,wu as streamEventsToAISDK,bu as streamEventsToAISDKWithTools};