@mcp-use/inspector 0.11.0 → 0.11.1-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,47 +1,47 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-QhPf51tE.js","assets/index-wW9KsYW0.js","assets/index-DdUJwc4e.css"])))=>i.map(i=>d[i]);
2
- var Ll=Object.defineProperty;var Dl=(t,e,n)=>e in t?Ll(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var hi=(t,e,n)=>Dl(t,typeof e!="symbol"?e+"":e,n);import{_ as O,q as ve,Z as Ul,s as Fl,p as eo,u as g,a as dn,t as Rn,v as Xe,w as Vl,x as Or,y as Ms,z as Ps,A as Bl,B as Wl,C as Hl,D as zl}from"./index-wW9KsYW0.js";import{E as _g,F as bg,H as vg,L as Sg,G as Cg,M as Tg,W as kg,I as Eg}from"./index-wW9KsYW0.js";import{L as to,S as vs,t as Gl,o as Kl,l as Jl,a as no,T as ql,D as Yl,b as so}from"./index-Dy6z3o7k.js";import{o as Qs}from"./__vite-browser-external-DFygW7-s.js";import{j as es,d as di,i as Xl}from"./path-C9FudP8b.js";import{h as Tn,s as Zl,g as ro,B as Ql,k as ec,l as tc,I as nc,C as sc,m as rc,t as ic,n as oc,o as ac,p as lc,q as cc,r as uc,u as hc,v as dc,w as fc,x as pc,y as mc,R as gc,z as yc,a as wc}from"./index-C4rXRq-z.js";import{aO as _c,aP as Ir,aQ as bc,at as xe,e as nn,aR as vc,aS as fn,a0 as fe,x as st,aT as io,g as Sc,aU as er,_ as q,ag as Xt,ae as oe,z as N,ad as ee,d as Cc,C as Tc,aV as kc,p as fi,aA as oo,aW as _e,ai as pn,aX as an,E as ao,y as Oe,aY as Rr,B as tr,D as Vt,am as Bt,aZ as Ec,a_ as xc,a$ as Ac,b0 as Mc,b1 as Pc,b2 as Nc,b3 as Oc,b4 as Ic,b5 as Rc,b6 as $c,b7 as jc,b8 as Lc,b9 as Dc,ba as Uc,bb as Fc,bc as Vc,bd as Bc,K as Wc,be as Hc,bf as zc,bg as Gc,t as Le,r as ln,m as $e,L as Ze,aq as Wt,bh as Kc,F as Jc,aB as pi,ar as qc,bi as mi,bj as gi,ab as $r,aa as yi,a9 as nr,ac as Yc,S as Xc,a5 as jr,a8 as Ke,bk as ts,o as W,bl as le,bm as Zc,bn as Me,bo as vt,bp as Qc,bq as Lr,l as U,a6 as eu,i as tu,T as nu,br as ns,bs as Fe,bt as F,bu as lo,s as ne,a7 as su,bv as $n,bw as co,bx as Ht,by as mn,bz as ss,bA as rs,bB as ru,aK as iu,aI as ou,aH as au,bC as lu}from"./index-B17id_Fn.js";import{E as uo,c as cu,e as uu}from"./embeddings-6IYwOFQO.js";import"./index-DRz5BQNA.js";var Ns,An,Os=0,Is=0;function hu(t,e,n){var s=0,r=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Ns),o==null&&(o=An)),i==null||o==null){var a=t.random||(t.rng||_c)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Ns&&!t._v6&&(i[0]|=1,Ns=i)),o==null&&(o=(a[6]<<8|a[7])&16383,An===void 0&&!t._v6&&(An=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Is+1,u=l-Os+(c-Is)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Os)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Os=l,Is=c,An=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;r[s++]=h>>>24&255,r[s++]=h>>>16&255,r[s++]=h>>>8&255,r[s++]=h&255;var d=l/4294967296*1e4&268435455;r[s++]=d>>>8&255,r[s++]=d&255,r[s++]=d>>>24&15|16,r[s++]=d>>>16&255,r[s++]=o>>>8|128,r[s++]=o&255;for(var f=0;f<6;++f)r[s+f]=i[f];return e||Ir(r)}function du(t){var e=typeof t=="string"?bc(t):t,n=fu(e);return typeof t=="string"?Ir(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 wi(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),n.push.apply(n,s)}return n}function _i(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?wi(Object(n),!0).forEach(function(s){pu(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):wi(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}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 s=n.call(t,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yu(t={},e,n=0){var s=hu(_i(_i({},t),{},{_v6:!0}),new Uint8Array(16));return s=du(s),Ir(s)}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)}}O(wu,"streamEventsToAISDK");function _u(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}O(_u,"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`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-CHcXydt4.js","assets/index-B41aXntr.js","assets/index-DdUJwc4e.css"])))=>i.map(i=>d[i]);
2
+ var Dl=Object.defineProperty;var Ul=(t,e,n)=>e in t?Dl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var hi=(t,e,n)=>Ul(t,typeof e!="symbol"?e+"":e,n);import{t as di,u as Fl,v as Vl,_ as O,w as ve,Z as Bl,$ as Wl,p as to,x as g,a as dn,y as Xe,z as zl,A as Os,B as Mr,C as Pr,D as Hl,E as Gl,F as Kl,G as Jl}from"./index-B41aXntr.js";import{H as kg,I as Eg,J as xg,L as Ag,K as Mg,M as Pg,W as Ng,N as Og}from"./index-B41aXntr.js";import{L as no,S as vr,t as ql,o as Yl,l as Xl,a as ro,T as Zl,D as Ql,b as so}from"./index-CuMbaXfK.js";import{o as Qr}from"./__vite-browser-external-DFygW7-s.js";import{j as er,d as fi,i as ec}from"./path-C9FudP8b.js";import{h as Tn,s as tc,g as io,B as nc,k as rc,l as sc,I as ic,C as oc,m as ac,t as lc,n as cc,o as uc,p as hc,q as dc,r as fc,u as pc,v as mc,w as gc,x as yc,y as wc,R as _c,z as bc,a as vc}from"./index-OG6u-A5H.js";import{aP as Sc,aQ as Is,aR as Cc,at as xe,e as nn,aS as Tc,aT as fn,a0 as fe,x as rt,aU as oo,g as kc,aV as es,_ as q,ag as Xt,ae as oe,z as N,ad as ee,d as Ec,C as xc,aW as Ac,p as pi,aA as ao,aX as _e,ai as pn,aY as an,E as lo,y as Oe,aZ as $s,B as ts,D as Vt,am as Bt,a_ as Mc,a$ as Pc,b0 as Nc,b1 as Oc,b2 as Ic,b3 as $c,b4 as Rc,b5 as jc,b6 as Lc,b7 as Dc,b8 as Uc,b9 as Fc,ba as Vc,bb as Bc,bc as Wc,bd as zc,be as Hc,K as Gc,bf as Kc,bg as Jc,bh as qc,t as Le,r as ln,m as Re,L as Ze,aq as Wt,bi as Yc,F as Xc,aB as mi,ar as Zc,bj as gi,bk as yi,ab as Rs,aa as wi,a9 as ns,ac as Qc,S as eu,a5 as js,a8 as Ke,bl as tr,o as W,bm as le,bn as tu,bo as Me,bp as vt,bq as nu,br as Ls,l as U,a6 as ru,i as su,T as iu,bs as nr,bt as Fe,bu as F,bv as co,s as ne,a7 as ou,bw as $n,bx as uo,by as zt,bz as mn,bA as rr,bB as sr,bC as au,aL as lu,aJ as cu,aI as uu,bD as hu,aH as Rn}from"./index-CmbQnJ_z.js";import{E as ho,c as du,e as fu}from"./embeddings-BGVbBzK6.js";import"./index-DRz5BQNA.js";const pu=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},mu=()=>{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 ${pu(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Fl(r.values[0])}`:`Invalid option: expected one of ${di(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",i=e(r.origin);return i?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",i=e(r.origin);return i?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${i.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":""}: ${di(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 gu(){return{localeError:mu()}}Vl(gu());var Nr,An,Or=0,Ir=0;function yu(t,e,n){var r=0,s=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Nr),o==null&&(o=An)),i==null||o==null){var a=t.random||(t.rng||Sc)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Nr&&!t._v6&&(i[0]|=1,Nr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,An===void 0&&!t._v6&&(An=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ir+1,u=l-Or+(c-Ir)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Or)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Or=l,Ir=c,An=o,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++]=o>>>8|128,s[r++]=o&255;for(var f=0;f<6;++f)s[r+f]=i[f];return e||Is(s)}function wu(t){var e=typeof t=="string"?Cc(t):t,n=_u(e);return typeof t=="string"?Is(n):n}function _u(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 _i(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 bi(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?_i(Object(n),!0).forEach(function(r){bu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_i(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function bu(t,e,n){return(e=vu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vu(t){var e=Su(t,"string");return typeof e=="symbol"?e:e+""}function Su(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 Cu(t={},e,n=0){var r=yu(bi(bi({},t),{},{_v6:!0}),new Uint8Array(16));return r=wu(r),Is(r)}async function*Tu(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)}}O(Tu,"streamEventsToAISDK");function ku(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}O(ku,"createReadableStreamFromGenerator");async function*Eu(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}}O(bu,"streamEventsToAISDKWithTools");class vu{capture(){}shutdown(){return Promise.resolve()}}var Su=Object.defineProperty,ho=(t,e)=>{for(var n in e)Su(t,n,{get:e[n],enumerable:!0})},Cu={};ho(Cu,{ConfigurableModel:()=>sr,MODEL_PROVIDER_CONFIG:()=>Ss,_inferModelProvider:()=>mo,getChatModelByClassName:()=>po,initChatModel:()=>Zt});const Ss={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}},fo=Object.keys(Ss);async function po(t){const e=Object.entries(Ss).find(([,s])=>s.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(s){const r=s;if("code"in r&&r.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in r){const i=r.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${i}. Please install with \`npm install ${i}\` or \`pnpm install ${i}\``)}throw s}}async function Tu(t,e,n={}){const s=e||mo(t);if(!s)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const r=Ss[s];if(!r){const l=fo.join(", ");throw new Error(`Unsupported { modelProvider: ${s} }.
6
+ `;break}}O(Eu,"streamEventsToAISDKWithTools");class xu{capture(){}shutdown(){return Promise.resolve()}}var Au=Object.defineProperty,fo=(t,e)=>{for(var n in e)Au(t,n,{get:e[n],enumerable:!0})},Mu={};fo(Mu,{ConfigurableModel:()=>rs,MODEL_PROVIDER_CONFIG:()=>Sr,_inferModelProvider:()=>go,getChatModelByClassName:()=>mo,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}},po=Object.keys(Sr);async function mo(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 i=s.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${i}. Please install with \`npm install ${i}\` or \`pnpm install ${i}\``)}throw r}}async function Pu(t,e,n={}){const r=e||go(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=po.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
7
7
 
8
- Supported model providers are: ${l}`)}const{modelProvider:i,...o}=n,a=await po(r.className);return new a({model:t,...o})}function mo(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 sr=class jn extends Tn{_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 s=await Tu(n.model,n.modelProvider,n);const r=Object.entries(this._queuedMethodOperations);if(r.length>0)for(const[i,o]of r)i in s&&typeof s[i]=="function"&&(s=await s[i](...o));return s}async _generate(e,n,s){return(await this._model(n))._generate(e,n??{},s)}bindTools(e,n){const s={...this._queuedMethodOperations};return s.bindTools=[e,n],new jn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:s})}withStructuredOutput=(e,...n)=>{const s={...this._queuedMethodOperations};return s.withStructuredOutput=[e,...n],new jn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:s})};_modelParams(e){const n=e?.configurable??{};let s={};for(const[r,i]of Object.entries(n))if(r.startsWith(this._configPrefix)){const o=this._removePrefix(r,this._configPrefix);s[o]=i}return this._configurableFields!=="any"&&(s=Object.fromEntries(Object.entries(s).filter(([r])=>this._configurableFields.includes(r)))),s}_removePrefix(e,n){return e.startsWith(n)?e.slice(n.length):e}withConfig(e){const n={...e||{}},s=this._modelParams(n),r=Object.fromEntries(Object.entries(n).filter(([o])=>o!=="configurable"));r.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([o])=>this._configPrefix&&!Object.keys(s).includes(this._removePrefix(o,this._configPrefix))));const i=new jn({defaultConfig:{...this._defaultConfig,...s},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new xe({config:n,bound:i})}async invoke(e,n){const s=await this._model(n),r=nn(n);return s.invoke(e,r)}async stream(e,n){const s=await this._model(n),r=new vc({generator:await s.stream(e,n),config:n});return await r.setup,fn.fromAsyncGenerator(r)}async batch(e,n,s){return super.batch(e,n,s)}async*transform(e,n){const s=await this._model(n),r=nn(n);yield*s.transform(e,r)}async*streamLog(e,n,s){const r=await this._model(n),i=nn(n);yield*r.streamLog(e,i,{...s,_schemaFormat:"original",includeNames:s?.includeNames,includeTypes:s?.includeTypes,includeTags:s?.includeTags,excludeNames:s?.excludeNames,excludeTypes:s?.excludeTypes,excludeTags:s?.excludeTags})}streamEvents(e,n,s){const r=this;async function*i(){const o=await r._model(n),a=nn(n),l=o.streamEvents(e,a,s);for await(const c of l)yield c}return fn.fromAsyncGenerator(i())}};async function Zt(t,e){let{configurableFields:n,configPrefix:s,modelProvider:r,...i}={configPrefix:"",...e??{}};if(r===void 0&&t?.includes(":")){const[l,...c]=t.split(":"),u=c.length===0?[l]:[l,c.join(":")];fo.includes(u[0])&&([r,t]=u)}let o=Array.isArray(n)?[...n]:n;!t&&o===void 0&&(o=["model","modelProvider"]),s&&o===void 0&&console.warn(`{ configPrefix: ${s} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);const a={...i};return o===void 0?new sr({defaultConfig:{...a,model:t,modelProvider:r},configPrefix:s}):(t&&(a.model=t),r&&(a.modelProvider=r),new sr({defaultConfig:a,configPrefix:s,configurableFields:o}))}var rr=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.")}},ir=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}},go=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
9
- - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},Dr=class extends Error{toolCall;toolError;constructor(t,e){const n=t instanceof Error?t:new Error(String(t)),s=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${s} with error: ${n.stack}
10
- Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function Ur(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function is(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}let ku=0;var Be=class or{constructor(e,n,s){this.schema=e,this.tool=n,this.options=s}get name(){return this.tool.function.name}static fromSchema(e,n){function s(a){return a??`extract-${++ku}`}if(Sc(e)){const a=st(e),l={type:"function",function:{name:s(),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new or(a,l,n)}let r;typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?r=e:r={name:s(e.title),description:e.description??"",parameters:e.schema||e};const i=st(e),o={type:"function",function:r};return new or(i,o,n)}parse(e){const s=new io(this.schema).validate(e);if(!s.valid)throw new go(this.name,s.errors.map(r=>r.error));return e}},rt=class yo{_schemaType;constructor(e){this.schema=e}static fromSchema(e){const n=st(e);return new yo(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new io(this.schema).validate(n).valid?n:void 0}catch{}}};function wo(t,e,n){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(r=>r instanceof Be||r instanceof rt))return t;if(t.every(r=>fe(r)))return t.map(r=>Be.fromSchema(r,e));if(t.every(r=>typeof r=="object"&&r!==null&&!fe(r)))return t.map(r=>Be.fromSchema(r,e));throw new Error(`Invalid response format: list contains mixed types.
11
- All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof Be||t instanceof rt)return[t];const s=_o(n);if(fe(t))return s?[rt.fromSchema(t)]:[Be.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return s?[rt.fromSchema(t)]:[Be.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function Eu(t,e){return wo(t,e)}function xu(t){return rt.fromSchema(t)}const Au=["ChatOpenAI","ChatXAI"],bi=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function _o(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return bi.some(s=>n.includes(s))}if(is(t))return _o(t._defaultConfig.model);if(!Ur(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||Au.includes(e)&&("model"in t&&bi.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Fr(t){let e=0;for(const n of t){let s;typeof n.content=="string"?s=n.content:Array.isArray(n.content)?s=n.content.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join(""):s="",e+=s.length}return Math.ceil(e/4)}function ze(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Cs(t){return typeof t=="function"?t:t.hook}function Mu(t){return new Promise(e=>setTimeout(e,t))}function me(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 bo(t){return yu({clockseq:t})}function yt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(s=>parseInt(s,16));return er(t,new Uint8Array(n))}const Pu="__error__",Ln="__scheduled__",Nu="__interrupt__",Ou="__resume__";var vi="[...]",Iu="[Circular]",os=[],wt=[];function Ru(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function $u(t,e,n,s){typeof s>"u"&&(s=Ru()),ar(t,"",0,[],void 0,0,s);var r;try{wt.length===0?r=JSON.stringify(t,e,n):r=JSON.stringify(t,ju(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;os.length!==0;){var i=os.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return r}function Rs(t,e,n,s){var r=Object.getOwnPropertyDescriptor(s,n);r.get!==void 0?r.configurable?(Object.defineProperty(s,n,{value:t}),os.push([s,n,e,r])):wt.push([e,n,t]):(s[n]=t,os.push([s,n,e]))}function ar(t,e,n,s,r,i,o){i+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<s.length;a++)if(s[a]===t){Rs(Iu,t,e,r);return}if(typeof o.depthLimit<"u"&&i>o.depthLimit){Rs(vi,t,e,r);return}if(typeof o.edgesLimit<"u"&&n+1>o.edgesLimit){Rs(vi,t,e,r);return}if(s.push(t),Array.isArray(t))for(a=0;a<t.length;a++)ar(t[a],a,a,s,t,i,o);else{var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];ar(t[c],c,a,s,t,i,o)}}s.pop()}}function ju(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(wt.length>0)for(var s=0;s<wt.length;s++){var r=wt[s];if(r[1]===e&&r[0]===n){n=r[2],wt.splice(s,1);break}}return t.call(this,e,n)}}const Lu=[];var Du={},vo={};q(vo,{BaseChatMessageHistory:()=>So,BaseListChatMessageHistory:()=>Vr,InMemoryChatMessageHistory:()=>Uu});var So=class extends Xt{async addMessages(t){for(const e of t)await this.addMessage(e)}},Vr=class extends Xt{addUserMessage(t){return this.addMessage(new oe(t))}addAIMessage(t){return this.addMessage(new N(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Uu=class extends Vr{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=[]}},Fu={},Co={};q(Co,{BaseMemory:()=>Vu,getInputValue:()=>Bu,getOutputValue:()=>Wu,getPromptInputKey:()=>Hu});var Vu=class{};const To=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Bu=(t,e)=>{const n=To(t,e);if(!n){const s=Object.keys(t);throw new Error(`input values have ${s.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Wu=(t,e)=>{const n=To(t,e);if(!n&&n!==""){const s=Object.keys(t);throw new Error(`output values have ${s.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(s=>!e.includes(s)&&s!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var ko={};q(ko,{BaseStore:()=>Eo,InMemoryStore:()=>xo});var Eo=class extends Xt{},xo=class extends Eo{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)}},Ao={};q(Ao,{BaseRetriever:()=>Br});var Br=class extends ee{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(Cc(e)),r=await(await Tc.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 i=await this._getRelevantDocuments(t,r);return await r?.handleRetrieverEnd(i),i}catch(i){throw await r?.handleRetrieverError(i),i}}},Mo={};q(Mo,{SaveableVectorStore:()=>zu,VectorStore:()=>Wr,VectorStoreRetriever:()=>Dn});var Dn=class extends Br{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)}},Wr=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,s=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)).map(i=>i[0])}async similaritySearchWithScore(t,e=4,n=void 0,s=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)}static fromTexts(t,e,n,s){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,s,r,i){if(typeof t=="number")return new Dn({vectorStore:this,k:t,filter:e,tags:[...s??[],this._vectorstoreType()],metadata:r,verbose:i,callbacks:n});{const o={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 Dn({...o,searchKwargs:t.searchKwargs}):new Dn({...o})}}},zu=class extends Wr{static load(t,e){throw new Error("Not implemented")}},Po={};q(Po,{BaseDocumentLoader:()=>No});var No=class{},Oo={};q(Oo,{LangSmithLoader:()=>Gu});var Gu=class extends No{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 kc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Ku,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 i of this.contentKey)n=n[i];const s=this.formatContent(n),r=e;["created_at","modified_at"].forEach(i=>{i in r&&typeof r[i]=="object"&&(r[i]=r[i].toString())}),t.push({pageContent:s,metadata:r})}return t}};function Ku(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var De=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},Io=class extends ee{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Ju=class extends Io{async transformDocuments(t){const e=[];for(const n of t){const s=await this._transformDocument(n);e.push(s)}return e}},Ro={};q(Ro,{BaseDocumentTransformer:()=>Io,Document:()=>De,MappingDocumentTransformer:()=>Ju});var Hr=class extends Xt{lc_namespace=["langchain_core","example_selectors","base"]},$o=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},qu=class extends $o{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 Yu(t){return t._modelType()==="base_llm"}function Xu(t){return t._modelType()==="base_chat_model"}function Si(t){return t.split(/\n| /).length}var Zu=class jo extends Hr{examples=[];examplePrompt;getTextLength=Si;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Si}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:s,examplePrompt:r}=n;return(await Promise.all(s.map(o=>r.format(o)))).map(o=>this.getTextLength(o))}async selectExamples(e){const n=Object.values(e).join(" ");let s=this.maxLength-this.getTextLength(n),r=0;const i=[];for(;s>0&&r<this.examples.length;){const o=s-this.exampleTextLengths[r];if(o<0)break;i.push(this.examples[r]),s=o,r+=1}return i}static async fromExamples(e,n){const s=new jo(n);return await Promise.all(e.map(r=>s.addExample(r))),s}};function $s(t){return Object.keys(t).sort().map(e=>t[e])}var Qu=class Lo extends Hr{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),s=$s(n.reduce((r,i)=>({...r,[i]:e[i]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new De({pageContent:s,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),s=$s(n.reduce((o,a)=>({...o,[a]:e[a]}),{})).join(" "),i=(await this.vectorStoreRetriever.invoke(s)).map(o=>o.metadata);return this.exampleKeys?i.map(o=>this.exampleKeys.reduce((a,l)=>({...a,[l]:o[l]}),{})):i}static async fromExamples(e,n,s,r={}){const i=r.inputKeys??null,o=e.map(l=>$s(i?i.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await s.fromTexts(o,e,n,r);return new Lo({vectorStore:a,k:r.k??4,exampleKeys:r.exampleKeys,inputKeys:r.inputKeys})}},Do={};q(Do,{BaseExampleSelector:()=>Hr,BasePromptSelector:()=>$o,ConditionalPromptSelector:()=>qu,LengthBasedExampleSelector:()=>Zu,SemanticSimilarityExampleSelector:()=>Qu,isChatModel:()=>Xu,isLLM:()=>Yu});const lr="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var eh=class extends Xt{lc_namespace=["langchain","recordmanagers"]},Uo=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Zl;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 De({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 er(e,lr)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return er(n,lr)}};function Fo(t,e){const n=[];let s=[];return e.forEach(r=>{s.push(r),s.length>=t&&(n.push(s),s=[])}),s.length>0&&n.push(s),n}function Vo(t){const e=new Set,n=[];for(const s of t){if(!s.hash_)throw new Error("Hashed document does not have a hash");e.has(s.hash_)||(e.add(s.hash_),n.push(s))}return n}function Bo(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 Wo=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function th(t){const{docsSource:e,recordManager:n,vectorStore:s,options:r}=t,{batchSize:i=100,cleanup:o,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!1}=r??{};if(o==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=Wo(e)?await e.load():e,h=Bo(a??null),d=await n.getTime();let f=0,y=0,p=0,S=0;const C=Fo(i??100,u);for(const m of C){const w=Vo(m.map(E=>Uo.fromDocument(E))),b=w.map(E=>h(E));o==="incremental"&&w.forEach((E,P)=>{if(b[P]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const T=await n.exists(w.map(E=>E.uid)),x=[],_=[],v=[],A=new Set;if(w.forEach((E,P)=>{if(T[P])if(c)A.add(E.uid);else{v.push(E.uid);return}x.push(E.uid),_.push(E.toDocument())}),v.length>0&&(await n.update(v,{timeAtLeast:d}),S+=v.length),_.length>0&&(await s.addDocuments(_,{ids:x}),f+=_.length-A.size,p+=A.size),await n.update(w.map(E=>E.uid),{timeAtLeast:d,groupIds:b}),o==="incremental"){b.forEach(P=>{if(!P)throw new Error("Source id cannot be null")});const E=await n.listKeys({before:d,groupIds:b});E.length>0&&(await s.delete({ids:E}),await n.deleteKeys(E),y+=E.length)}}if(o==="full"){let m=await n.listKeys({before:d,limit:l});for(;m.length>0;)await s.delete({ids:m}),await n.deleteKeys(m),y+=m.length,m=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:y,numUpdated:p,numSkipped:S}}var Ho={};q(Ho,{RecordManager:()=>eh,UUIDV5_NAMESPACE:()=>lr,_HashedDocument:()=>Uo,_batch:()=>Fo,_deduplicateInOrder:()=>Vo,_getSourceIdAssigner:()=>Bo,_isBaseDocumentLoader:()=>Wo,index:()=>th});var zo=class extends ro{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)}`)}},Go=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 zo(t)}_diff(t,e){return e?ec(t??{},e):void 0}async parsePartialResult(t){const e=t[0];if(!e.message)return;const{message:n}=e,s=n.additional_kwargs.function_call;if(s)return this.argsOnly?fi(s.arguments):{...s,arguments:fi(s.arguments)}}async parseResult(t){const e=await this.outputParser.parseResult(t);if(!e)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(t)}`);return this.parse(e)}async parse(t){const e=JSON.parse(t);return this.argsOnly||(e.arguments=JSON.parse(e.arguments)),e}getFormatInstructions(){return""}},nh=class extends ro{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Go;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]}},Ko={};q(Ko,{JsonKeyOutputFunctionsParser:()=>nh,JsonOutputFunctionsParser:()=>Go,OutputFunctionsParser:()=>zo});var kn=class extends ee{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[r,i]of Object.entries(e))typeof i=="string"?n[r]=i:n[r]=await i();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},s=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(r=>this.formatPromptValue(r),t,{...e,tags:s,metadata:n,runType:"prompt"})}},gn=class extends kn{async formatPromptValue(t){const e=await this.format(t);return new tc(e)}};var sh=Object.prototype.toString,Qt=Array.isArray||function(e){return sh.call(e)==="[object Array]"};function zr(t){return typeof t=="function"}function rh(t){return Qt(t)?"array":typeof t}function js(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Ci(t,e){return t!=null&&typeof t=="object"&&e in t}function ih(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var oh=RegExp.prototype.test;function ah(t,e){return oh.call(t,e)}var lh=/\S/;function ch(t){return!ah(lh,t)}var uh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function hh(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return uh[n]})}var dh=/\s*/,fh=/\s+/,Ti=/\s*=/,ph=/\s*\}/,mh=/#|\^|\/|>|\{|&|=|!/;function gh(t,e){if(!t)return[];var n=!1,s=[],r=[],i=[],o=!1,a=!1,l="",c=0;function u(){if(o&&!a)for(;i.length;)delete r[i.pop()];else i=[];o=!1,a=!1}var h,d,f;function y(v){if(typeof v=="string"&&(v=v.split(fh,2)),!Qt(v)||v.length!==2)throw new Error("Invalid tags: "+v);h=new RegExp(js(v[0])+"\\s*"),d=new RegExp("\\s*"+js(v[1])),f=new RegExp("\\s*"+js("}"+v[1]))}y(e||ue.tags);for(var p=new En(t),S,C,m,w,b,T;!p.eos();){if(S=p.pos,m=p.scanUntil(h),m)for(var x=0,_=m.length;x<_;++x)w=m.charAt(x),ch(w)?(i.push(r.length),l+=w):(a=!0,n=!0,l+=" "),r.push(["text",w,S,S+1]),S+=1,w===`
12
- `&&(u(),l="",c=0,n=!1);if(!p.scan(h))break;if(o=!0,C=p.scan(mh)||"name",p.scan(dh),C==="="?(m=p.scanUntil(Ti),p.scan(Ti),p.scanUntil(d)):C==="{"?(m=p.scanUntil(f),p.scan(ph),p.scanUntil(d),C="&"):m=p.scanUntil(d),!p.scan(d))throw new Error("Unclosed tag at "+p.pos);if(C==">"?b=[C,m,S,p.pos,l,c,n]:b=[C,m,S,p.pos],c++,r.push(b),C==="#"||C==="^")s.push(b);else if(C==="/"){if(T=s.pop(),!T)throw new Error('Unopened section "'+m+'" at '+S);if(T[1]!==m)throw new Error('Unclosed section "'+T[1]+'" at '+S)}else C==="name"||C==="{"||C==="&"?a=!0:C==="="&&y(m)}if(u(),T=s.pop(),T)throw new Error('Unclosed section "'+T[1]+'" at '+p.pos);return wh(yh(r))}function yh(t){for(var e=[],n,s,r=0,i=t.length;r<i;++r)n=t[r],n&&(n[0]==="text"&&s&&s[0]==="text"?(s[1]+=n[1],s[3]=n[3]):(e.push(n),s=n));return e}function wh(t){for(var e=[],n=e,s=[],r,i,o=0,a=t.length;o<a;++o)switch(r=t[o],r[0]){case"#":case"^":n.push(r),s.push(r),n=r[4]=[];break;case"/":i=s.pop(),i[5]=r[2],n=s.length>0?s[s.length-1][4]:e;break;default:n.push(r)}return e}function En(t){this.string=t,this.tail=t,this.pos=0}En.prototype.eos=function(){return this.tail===""};En.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var s=n[0];return this.tail=this.tail.substring(s.length),this.pos+=s.length,s};En.prototype.scanUntil=function(e){var n=this.tail.search(e),s;switch(n){case-1:s=this.tail,this.tail="";break;case 0:s="";break;default:s=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=s.length,s};function zt(t,e){this.view=t,this.cache={".":this.view},this.parent=e}zt.prototype.push=function(e){return new zt(e,this)};zt.prototype.lookup=function(e){var n=this.cache,s;if(n.hasOwnProperty(e))s=n[e];else{for(var r=this,i,o,a,l=!1;r;){if(e.indexOf(".")>0)for(i=r.view,o=e.split("."),a=0;i!=null&&a<o.length;)a===o.length-1&&(l=Ci(i,o[a])||ih(i,o[a])),i=i[o[a++]];else i=r.view[e],l=Ci(r.view,e);if(l){s=i;break}r=r.parent}n[e]=s}return zr(s)&&(s=s.call(this.view)),s};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 s=this.templateCache,r=e+":"+(n||ue.tags).join(":"),i=typeof s<"u",o=i?s.get(r):void 0;return o==null&&(o=gh(e,n),i&&s.set(r,o)),o};ie.prototype.render=function(e,n,s,r){var i=this.getConfigTags(r),o=this.parse(e,i),a=n instanceof zt?n:new zt(n,void 0);return this.renderTokens(o,a,s,e,r)};ie.prototype.renderTokens=function(e,n,s,r,i){for(var o="",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,s,r,i):l==="^"?c=this.renderInverted(a,n,s,r,i):l===">"?c=this.renderPartial(a,n,s,i):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(o+=c);return o};ie.prototype.renderSection=function(e,n,s,r,i){var o=this,a="",l=n.lookup(e[1]);function c(d){return o.render(d,n,s,i)}if(l){if(Qt(l))for(var u=0,h=l.length;u<h;++u)a+=this.renderTokens(e[4],n.push(l[u]),s,r,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),s,r,i);else if(zr(l)){if(typeof r!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,r.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,s,r,i);return a}};ie.prototype.renderInverted=function(e,n,s,r,i){var o=n.lookup(e[1]);if(!o||Qt(o)&&o.length===0)return this.renderTokens(e[4],n,s,r,i)};ie.prototype.indentPartial=function(e,n,s){for(var r=n.replace(/[^ \t]/g,""),i=e.split(`
13
- `),o=0;o<i.length;o++)i[o].length&&(o>0||!s)&&(i[o]=r+i[o]);return i.join(`
14
- `)};ie.prototype.renderPartial=function(e,n,s,r){if(s){var i=this.getConfigTags(r),o=zr(s)?s(e[1]):s[e[1]];if(o!=null){var a=e[6],l=e[5],c=e[4],u=o;l==0&&c&&(u=this.indentPartial(o,c,a));var h=this.parse(u,i);return this.renderTokens(h,n,s,u,r)}}};ie.prototype.unescapedValue=function(e,n){var s=n.lookup(e[1]);if(s!=null)return s};ie.prototype.escapedValue=function(e,n,s){var r=this.getConfigEscape(s)||ue.escape,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&r===ue.escape?String(i):r(i)};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){yn.templateCache=t},get templateCache(){return yn.templateCache}},yn=new ie;ue.clearCache=function(){return yn.clearCache()};ue.parse=function(e,n){return yn.parse(e,n)};ue.render=function(e,n,s,r){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+rh(e)+'" was given as the first argument for mustache#render(template, view, partials)');return yn.render(e,n,s,r)};ue.escape=hh;ue.Scanner=En;ue.Context=zt;ue.Writer=ie;function Jo(){ue.escape=t=>t}const wn=t=>{const e=t.split(""),n=[],s=(i,o)=>{for(let a=o;a<e.length;a+=1)if(i.includes(e[a]))return a;return-1};let r=0;for(;r<e.length;)if(e[r]==="{"&&r+1<e.length&&e[r+1]==="{")n.push({type:"literal",text:"{"}),r+=2;else if(e[r]==="}"&&r+1<e.length&&e[r+1]==="}")n.push({type:"literal",text:"}"}),r+=2;else if(e[r]==="{"){const i=s("}",r);if(i<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(r+1,i).join("")}),r=i+1}else{if(e[r]==="}")throw new Error("Single '}' in template.");{const i=s("{}",r),o=(i<0?e.slice(r):e.slice(r,i)).join("");n.push({type:"literal",text:o}),r=i<0?e.length:i}}return n},qo=(t,e=[])=>{const n=[];for(const s of t)if(s[0]==="name"){const r=s[1].includes(".")?s[1].split(".")[0]:s[1];n.push({type:"variable",name:r})}else if(["#","&","^",">"].includes(s[0])){if(n.push({type:"variable",name:s[1]}),s[0]==="#"&&s.length>4&&Array.isArray(s[4])){const r=[...e,s[1]],i=qo(s[4],r);n.push(...i)}}else n.push({type:"literal",text:s[1]});return n},as=t=>{Jo();const e=ue.parse(t);return qo(e)},Yo=(t,e)=>wn(t).reduce((n,s)=>{if(s.type==="variable"){if(s.name in e){const r=typeof e[s.name]=="string"?e[s.name]:JSON.stringify(e[s.name]);return n+r}throw new Error(`(f-string) Missing value for input ${s.name}`)}return n+s.text},""),Xo=(t,e)=>(Jo(),ue.render(t,e)),ls={"f-string":Yo,mustache:Xo},Zo={"f-string":wn,mustache:as},Te=(t,e,n)=>{try{return ls[e](t,n)}catch(s){throw oo(s,"INVALID_PROMPT_INPUT")}},cs=(t,e)=>Zo[e](t),xn=(t,e,n)=>{if(!(e in ls)){const s=Object.keys(ls);throw new Error(`Invalid template format. Got \`${e}\`;
15
- should be one of ${s}`)}try{const s=n.reduce((r,i)=>(r[i]="foo",r),{});Array.isArray(t)?t.forEach(r=>{if(r.type==="text"&&"text"in r&&typeof r.text=="string")Te(r.text,e,s);else if(r.type==="image_url"){if(typeof r.image_url=="string")Te(r.image_url,e,s);else if(typeof r.image_url=="object"&&r.image_url!==null&&"url"in r.image_url&&typeof r.image_url.url=="string"){const i=r.image_url.url;Te(i,e,s)}}else throw new Error(`Invalid message template received. ${JSON.stringify(r,null,2)}`)}):Te(t,e,s)}catch(s){throw new Error(`Invalid prompt schema: ${s.message}`)}};var Je=class sn extends gn{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),xn(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return Te(this.template,this.templateFormat,n)}static fromExamples(e,n,s,r=`
8
+ Supported model providers are: ${l}`)}const{modelProvider:i,...o}=n,a=await mo(s.className);return new a({model:t,...o})}function go(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 rs=class jn extends Tn{_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 Pu(n.model,n.modelProvider,n);const s=Object.entries(this._queuedMethodOperations);if(s.length>0)for(const[i,o]of s)i in r&&typeof r[i]=="function"&&(r=await r[i](...o));return r}async _generate(e,n,r){return(await this._model(n))._generate(e,n??{},r)}bindTools(e,n){const r={...this._queuedMethodOperations};return r.bindTools=[e,n],new jn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new jn({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){const n=e?.configurable??{};let r={};for(const[s,i]of Object.entries(n))if(s.startsWith(this._configPrefix)){const o=this._removePrefix(s,this._configPrefix);r[o]=i}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(([o])=>o!=="configurable"));s.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([o])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(o,this._configPrefix))));const i=new jn({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new xe({config:n,bound:i})}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 Tc({generator:await r.stream(e,n),config:n});return await s.setup,fn.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._model(n),s=nn(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._model(n),i=nn(n);yield*s.streamLog(e,i,{...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*i(){const o=await s._model(n),a=nn(n),l=o.streamEvents(e,a,r);for await(const c of l)yield c}return fn.fromAsyncGenerator(i())}};async function Zt(t,e){let{configurableFields:n,configPrefix:r,modelProvider:s,...i}={configPrefix:"",...e??{}};if(s===void 0&&t?.includes(":")){const[l,...c]=t.split(":"),u=c.length===0?[l]:[l,c.join(":")];po.includes(u[0])&&([s,t]=u)}let o=Array.isArray(n)?[...n]:n;!t&&o===void 0&&(o=["model","modelProvider"]),r&&o===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={...i};return o===void 0?new rs({defaultConfig:{...a,model:t,modelProvider:s},configPrefix:r}):(t&&(a.model=t),s&&(a.modelProvider=s),new rs({defaultConfig:a,configPrefix:r,configurableFields:o}))}var ss=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.")}},is=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}},yo=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(n=>`
9
+ - ${n}`).join("")}.`),this.toolName=t,this.errors=e}},Ds=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}
10
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function Us(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function ir(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}let Nu=0;var Be=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-${++Nu}`}if(kc(e)){const a=rt(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 i=rt(e),o={type:"function",function:s};return new os(i,o,n)}parse(e){const r=new oo(this.schema).validate(e);if(!r.valid)throw new yo(this.name,r.errors.map(s=>s.error));return e}},st=class wo{_schemaType;constructor(e){this.schema=e}static fromSchema(e){const n=rt(e);return new wo(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new oo(this.schema).validate(n).valid?n:void 0}catch{}}};function _o(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 Be||s instanceof st))return t;if(t.every(s=>fe(s)))return t.map(s=>Be.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!fe(s)))return t.map(s=>Be.fromSchema(s,e));throw new Error(`Invalid response format: list contains mixed types.
11
+ All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof Be||t instanceof st)return[t];const r=bo(n);if(fe(t))return r?[st.fromSchema(t)]:[Be.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[st.fromSchema(t)]:[Be.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function Ou(t,e){return _o(t,e)}function Iu(t){return st.fromSchema(t)}const $u=["ChatOpenAI","ChatXAI"],vi=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function bo(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return vi.some(r=>n.includes(r))}if(ir(t))return bo(t._defaultConfig.model);if(!Us(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||$u.includes(e)&&("model"in t&&vi.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Fs(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 He(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Cr(t){return typeof t=="function"?t:t.hook}function Ru(t){return new Promise(e=>setTimeout(e,t))}function me(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 vo(t){return Cu({clockseq:t})}function yt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return es(t,new Uint8Array(n))}const ju="__error__",Ln="__scheduled__",Lu="__interrupt__",Du="__resume__";var Si="[...]",Uu="[Circular]",or=[],wt=[];function Fu(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Vu(t,e,n,r){typeof r>"u"&&(r=Fu()),as(t,"",0,[],void 0,0,r);var s;try{wt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,Bu(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;or.length!==0;){var i=or.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[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}),or.push([r,n,e,s])):wt.push([e,n,t]):(r[n]=t,or.push([r,n,e]))}function as(t,e,n,r,s,i,o){i+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){$r(Uu,t,e,s);return}if(typeof o.depthLimit<"u"&&i>o.depthLimit){$r(Si,t,e,s);return}if(typeof o.edgesLimit<"u"&&n+1>o.edgesLimit){$r(Si,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)as(t[a],a,a,r,t,i,o);else{var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];as(t[c],c,a,r,t,i,o)}}r.pop()}}function Bu(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(wt.length>0)for(var r=0;r<wt.length;r++){var s=wt[r];if(s[1]===e&&s[0]===n){n=s[2],wt.splice(r,1);break}}return t.call(this,e,n)}}const Wu=[];var zu={},So={};q(So,{BaseChatMessageHistory:()=>Co,BaseListChatMessageHistory:()=>Vs,InMemoryChatMessageHistory:()=>Hu});var Co=class extends Xt{async addMessages(t){for(const e of t)await this.addMessage(e)}},Vs=class extends Xt{addUserMessage(t){return this.addMessage(new oe(t))}addAIMessage(t){return this.addMessage(new N(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Hu=class extends Vs{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=[]}},Gu={},To={};q(To,{BaseMemory:()=>Ku,getInputValue:()=>Ju,getOutputValue:()=>qu,getPromptInputKey:()=>Yu});var Ku=class{};const ko=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Ju=(t,e)=>{const n=ko(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},qu=(t,e)=>{const n=ko(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 Yu(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 Eo={};q(Eo,{BaseStore:()=>xo,InMemoryStore:()=>Ao});var xo=class extends Xt{},Ao=class extends xo{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)}},Mo={};q(Mo,{BaseRetriever:()=>Bs});var Bs=class extends ee{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(Ec(e)),s=await(await xc.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 i=await this._getRelevantDocuments(t,s);return await s?.handleRetrieverEnd(i),i}catch(i){throw await s?.handleRetrieverError(i),i}}},Po={};q(Po,{SaveableVectorStore:()=>Xu,VectorStore:()=>Ws,VectorStoreRetriever:()=>Dn});var Dn=class extends Bs{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)}},Ws=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(i=>i[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,i){if(typeof t=="number")return new Dn({vectorStore:this,k:t,filter:e,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:i,callbacks:n});{const o={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 Dn({...o,searchKwargs:t.searchKwargs}):new Dn({...o})}}},Xu=class extends Ws{static load(t,e){throw new Error("Not implemented")}},No={};q(No,{BaseDocumentLoader:()=>Oo});var Oo=class{},Io={};q(Io,{LangSmithLoader:()=>Zu});var Zu=class extends Oo{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 Ac(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 i of this.contentKey)n=n[i];const r=this.formatContent(n),s=e;["created_at","modified_at"].forEach(i=>{i in s&&typeof s[i]=="object"&&(s[i]=s[i].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 De=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},$o=class extends ee{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},eh=class extends $o{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},Ro={};q(Ro,{BaseDocumentTransformer:()=>$o,Document:()=>De,MappingDocumentTransformer:()=>eh});var zs=class extends Xt{lc_namespace=["langchain_core","example_selectors","base"]},jo=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},th=class extends jo{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 nh(t){return t._modelType()==="base_llm"}function rh(t){return t._modelType()==="base_chat_model"}function Ci(t){return t.split(/\n| /).length}var sh=class Lo extends zs{examples=[];examplePrompt;getTextLength=Ci;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Ci}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(o=>s.format(o)))).map(o=>this.getTextLength(o))}async selectExamples(e){const n=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(n),s=0;const i=[];for(;r>0&&s<this.examples.length;){const o=r-this.exampleTextLengths[s];if(o<0)break;i.push(this.examples[s]),r=o,s+=1}return i}static async fromExamples(e,n){const r=new Lo(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 ih=class Do extends zs{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,i)=>({...s,[i]:e[i]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new De({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Rr(n.reduce((o,a)=>({...o,[a]:e[a]}),{})).join(" "),i=(await this.vectorStoreRetriever.invoke(r)).map(o=>o.metadata);return this.exampleKeys?i.map(o=>this.exampleKeys.reduce((a,l)=>({...a,[l]:o[l]}),{})):i}static async fromExamples(e,n,r,s={}){const i=s.inputKeys??null,o=e.map(l=>Rr(i?i.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(o,e,n,s);return new Do({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Uo={};q(Uo,{BaseExampleSelector:()=>zs,BasePromptSelector:()=>jo,ConditionalPromptSelector:()=>th,LengthBasedExampleSelector:()=>sh,SemanticSimilarityExampleSelector:()=>ih,isChatModel:()=>rh,isLLM:()=>nh});const ls="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var oh=class extends Xt{lc_namespace=["langchain","recordmanagers"]},Fo=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=tc;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 De({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 es(e,ls)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return es(n,ls)}};function Vo(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 Bo(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 Wo(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 zo=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function ah(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:i=100,cleanup:o,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!1}=s??{};if(o==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=zo(e)?await e.load():e,h=Wo(a??null),d=await n.getTime();let f=0,y=0,p=0,S=0;const C=Vo(i??100,u);for(const m of C){const w=Bo(m.map(E=>Fo.fromDocument(E))),b=w.map(E=>h(E));o==="incremental"&&w.forEach((E,P)=>{if(b[P]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const T=await n.exists(w.map(E=>E.uid)),x=[],_=[],v=[],A=new Set;if(w.forEach((E,P)=>{if(T[P])if(c)A.add(E.uid);else{v.push(E.uid);return}x.push(E.uid),_.push(E.toDocument())}),v.length>0&&(await n.update(v,{timeAtLeast:d}),S+=v.length),_.length>0&&(await r.addDocuments(_,{ids:x}),f+=_.length-A.size,p+=A.size),await n.update(w.map(E=>E.uid),{timeAtLeast:d,groupIds:b}),o==="incremental"){b.forEach(P=>{if(!P)throw new Error("Source id cannot be null")});const E=await n.listKeys({before:d,groupIds:b});E.length>0&&(await r.delete({ids:E}),await n.deleteKeys(E),y+=E.length)}}if(o==="full"){let m=await n.listKeys({before:d,limit:l});for(;m.length>0;)await r.delete({ids:m}),await n.deleteKeys(m),y+=m.length,m=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:y,numUpdated:p,numSkipped:S}}var Ho={};q(Ho,{RecordManager:()=>oh,UUIDV5_NAMESPACE:()=>ls,_HashedDocument:()=>Fo,_batch:()=>Vo,_deduplicateInOrder:()=>Bo,_getSourceIdAssigner:()=>Wo,_isBaseDocumentLoader:()=>zo,index:()=>ah});var Go=class extends io{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)}`)}},Ko=class extends nc{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 Go(t)}_diff(t,e){return e?rc(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?pi(r.arguments):{...r,arguments:pi(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""}},lh=class extends io{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Ko;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]}},Jo={};q(Jo,{JsonKeyOutputFunctionsParser:()=>lh,JsonOutputFunctionsParser:()=>Ko,OutputFunctionsParser:()=>Go});var kn=class extends ee{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,i]of Object.entries(e))typeof i=="string"?n[s]=i:n[s]=await i();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},gn=class extends kn{async formatPromptValue(t){const e=await this.format(t);return new sc(e)}};var ch=Object.prototype.toString,Qt=Array.isArray||function(e){return ch.call(e)==="[object Array]"};function Hs(t){return typeof t=="function"}function uh(t){return Qt(t)?"array":typeof t}function jr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Ti(t,e){return t!=null&&typeof t=="object"&&e in t}function hh(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var dh=RegExp.prototype.test;function fh(t,e){return dh.call(t,e)}var ph=/\S/;function mh(t){return!fh(ph,t)}var gh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function yh(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return gh[n]})}var wh=/\s*/,_h=/\s+/,ki=/\s*=/,bh=/\s*\}/,vh=/#|\^|\/|>|\{|&|=|!/;function Sh(t,e){if(!t)return[];var n=!1,r=[],s=[],i=[],o=!1,a=!1,l="",c=0;function u(){if(o&&!a)for(;i.length;)delete s[i.pop()];else i=[];o=!1,a=!1}var h,d,f;function y(v){if(typeof v=="string"&&(v=v.split(_h,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]))}y(e||ue.tags);for(var p=new En(t),S,C,m,w,b,T;!p.eos();){if(S=p.pos,m=p.scanUntil(h),m)for(var x=0,_=m.length;x<_;++x)w=m.charAt(x),mh(w)?(i.push(s.length),l+=w):(a=!0,n=!0,l+=" "),s.push(["text",w,S,S+1]),S+=1,w===`
12
+ `&&(u(),l="",c=0,n=!1);if(!p.scan(h))break;if(o=!0,C=p.scan(vh)||"name",p.scan(wh),C==="="?(m=p.scanUntil(ki),p.scan(ki),p.scanUntil(d)):C==="{"?(m=p.scanUntil(f),p.scan(bh),p.scanUntil(d),C="&"):m=p.scanUntil(d),!p.scan(d))throw new Error("Unclosed tag at "+p.pos);if(C==">"?b=[C,m,S,p.pos,l,c,n]:b=[C,m,S,p.pos],c++,s.push(b),C==="#"||C==="^")r.push(b);else if(C==="/"){if(T=r.pop(),!T)throw new Error('Unopened section "'+m+'" at '+S);if(T[1]!==m)throw new Error('Unclosed section "'+T[1]+'" at '+S)}else C==="name"||C==="{"||C==="&"?a=!0:C==="="&&y(m)}if(u(),T=r.pop(),T)throw new Error('Unclosed section "'+T[1]+'" at '+p.pos);return Th(Ch(s))}function Ch(t){for(var e=[],n,r,s=0,i=t.length;s<i;++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 Th(t){for(var e=[],n=e,r=[],s,i,o=0,a=t.length;o<a;++o)switch(s=t[o],s[0]){case"#":case"^":n.push(s),r.push(s),n=s[4]=[];break;case"/":i=r.pop(),i[5]=s[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(s)}return e}function En(t){this.string=t,this.tail=t,this.pos=0}En.prototype.eos=function(){return this.tail===""};En.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};En.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,i,o,a,l=!1;s;){if(e.indexOf(".")>0)for(i=s.view,o=e.split("."),a=0;i!=null&&a<o.length;)a===o.length-1&&(l=Ti(i,o[a])||hh(i,o[a])),i=i[o[a++]];else i=s.view[e],l=Ti(s.view,e);if(l){r=i;break}s=s.parent}n[e]=r}return Hs(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(":"),i=typeof r<"u",o=i?r.get(s):void 0;return o==null&&(o=Sh(e,n),i&&r.set(s,o)),o};ie.prototype.render=function(e,n,r,s){var i=this.getConfigTags(s),o=this.parse(e,i),a=n instanceof Ht?n:new Ht(n,void 0);return this.renderTokens(o,a,r,e,s)};ie.prototype.renderTokens=function(e,n,r,s,i){for(var o="",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,i):l==="^"?c=this.renderInverted(a,n,r,s,i):l===">"?c=this.renderPartial(a,n,r,i):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(o+=c);return o};ie.prototype.renderSection=function(e,n,r,s,i){var o=this,a="",l=n.lookup(e[1]);function c(d){return o.render(d,n,r,i)}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,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,s,i);else if(Hs(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,i);return a}};ie.prototype.renderInverted=function(e,n,r,s,i){var o=n.lookup(e[1]);if(!o||Qt(o)&&o.length===0)return this.renderTokens(e[4],n,r,s,i)};ie.prototype.indentPartial=function(e,n,r){for(var s=n.replace(/[^ \t]/g,""),i=e.split(`
13
+ `),o=0;o<i.length;o++)i[o].length&&(o>0||!r)&&(i[o]=s+i[o]);return i.join(`
14
+ `)};ie.prototype.renderPartial=function(e,n,r,s){if(r){var i=this.getConfigTags(s),o=Hs(r)?r(e[1]):r[e[1]];if(o!=null){var a=e[6],l=e[5],c=e[4],u=o;l==0&&c&&(u=this.indentPartial(o,c,a));var h=this.parse(u,i);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,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&s===ue.escape?String(i):s(i)};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){yn.templateCache=t},get templateCache(){return yn.templateCache}},yn=new ie;ue.clearCache=function(){return yn.clearCache()};ue.parse=function(e,n){return yn.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 "'+uh(e)+'" was given as the first argument for mustache#render(template, view, partials)');return yn.render(e,n,r,s)};ue.escape=yh;ue.Scanner=En;ue.Context=Ht;ue.Writer=ie;function qo(){ue.escape=t=>t}const wn=t=>{const e=t.split(""),n=[],r=(i,o)=>{for(let a=o;a<e.length;a+=1)if(i.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 i=r("}",s);if(i<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,i).join("")}),s=i+1}else{if(e[s]==="}")throw new Error("Single '}' in template.");{const i=r("{}",s),o=(i<0?e.slice(s):e.slice(s,i)).join("");n.push({type:"literal",text:o}),s=i<0?e.length:i}}return n},Yo=(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]],i=Yo(r[4],s);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},ar=t=>{qo();const e=ue.parse(t);return Yo(e)},Xo=(t,e)=>wn(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e){const s=typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]);return n+s}throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),Zo=(t,e)=>(qo(),ue.render(t,e)),lr={"f-string":Xo,mustache:Zo},Qo={"f-string":wn,mustache:ar},Te=(t,e,n)=>{try{return lr[e](t,n)}catch(r){throw ao(r,"INVALID_PROMPT_INPUT")}},cr=(t,e)=>Qo[e](t),xn=(t,e,n)=>{if(!(e in lr)){const r=Object.keys(lr);throw new Error(`Invalid template format. Got \`${e}\`;
15
+ should be one of ${r}`)}try{const r=n.reduce((s,i)=>(s[i]="foo",s),{});Array.isArray(t)?t.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Te(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Te(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 i=s.image_url.url;Te(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Te(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Je=class rn extends gn{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),xn(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return Te(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
16
16
 
17
- `,i=""){const o=[i,...e,n].join(r);return new sn({inputVariables:s,template:o})}static fromTemplate(e,n){const{templateFormat:s="f-string",...r}=n??{},i=new Set;return cs(e,s).forEach(o=>{o.type==="variable"&&i.add(o.name)}),new sn({inputVariables:[...i],templateFormat:s,template:e,...r})}async partial(e){const n=this.inputVariables.filter(i=>!(i in e)),s={...this.partialVariables??{},...e},r={...this,inputVariables:n,partialVariables:s};return new sn(r)}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 sn({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},Un=class Qo 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))),xn([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}_getPromptType(){return"prompt"}async partial(e){const n=this.inputVariables.filter(i=>!(i in e)),s={...this.partialVariables??{},...e},r={...this,inputVariables:n,partialVariables:s};return new Qo(r)}async format(e){const n={};for(const[o,a]of Object.entries(this.template))typeof a=="string"?n[o]=Te(a,this.templateFormat,e):n[o]=a;const s=e.url||n.url,r=e.detail||n.detail;if(!s)throw new Error("Must provide either an image URL.");if(typeof s!="string")throw new Error("url must be a string.");const i={url:s};return r&&(i.detail=r),i}async formatPromptValue(e){const n=await this.format(e);return new nc(n)}},cr=class extends ee{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=ur(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return hr(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function ur(t,e){const n=[];for(const s of Object.values(t))if(typeof s=="string")cs(s,e).forEach(r=>{r.type==="variable"&&n.push(r.name)});else if(Array.isArray(s))for(const r of s)typeof r=="string"?cs(r,e).forEach(i=>{i.type==="variable"&&n.push(i.name)}):typeof r=="object"&&n.push(...ur(r,e));else typeof s=="object"&&s!==null&&n.push(...ur(s,e));return Array.from(new Set(n))}function hr(t,e,n){const s={};for(const[r,i]of Object.entries(t))if(typeof i=="string")s[r]=Te(i,n,e);else if(Array.isArray(i)){const o=[];for(const a of i)typeof a=="string"?o.push(Te(a,n,e)):typeof a=="object"&&o.push(hr(a,e,n));s[r]=o}else typeof i=="object"&&i!==null?s[r]=hr(i,e,n):s[r]=i;return s}var Ts=class extends ee{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},dr=class extends Ts{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 s=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw s.name="InputFormatError",s}let n;try{Array.isArray(e)?n=e.map(pn):n=[pn(e)]}catch(s){const r=typeof e=="string"?e:JSON.stringify(e,null,2),i=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${r}`,`Additional message: ${s.message}`].join(`
17
+ `,i=""){const o=[i,...e,n].join(s);return new rn({inputVariables:r,template:o})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},i=new Set;return cr(e,r).forEach(o=>{o.type==="variable"&&i.add(o.name)}),new rn({inputVariables:[...i],templateFormat:r,template:e,...s})}async partial(e){const n=this.inputVariables.filter(i=>!(i 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 ea 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))),xn([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}_getPromptType(){return"prompt"}async partial(e){const n=this.inputVariables.filter(i=>!(i in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new ea(s)}async format(e){const n={};for(const[o,a]of Object.entries(this.template))typeof a=="string"?n[o]=Te(a,this.templateFormat,e):n[o]=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 i={url:r};return s&&(i.detail=s),i}async formatPromptValue(e){const n=await this.format(e);return new ic(n)}},cs=class extends ee{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=us(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return hs(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function us(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(i=>{i.type==="variable"&&n.push(i.name)}):typeof s=="object"&&n.push(...us(s,e));else typeof r=="object"&&r!==null&&n.push(...us(r,e));return Array.from(new Set(n))}function hs(t,e,n){const r={};for(const[s,i]of Object.entries(t))if(typeof i=="string")r[s]=Te(i,n,e);else if(Array.isArray(i)){const o=[];for(const a of i)typeof a=="string"?o.push(Te(a,n,e)):typeof a=="object"&&o.push(hs(a,e,n));r[s]=o}else typeof i=="object"&&i!==null?r[s]=hs(i,e,n):r[s]=i;return r}var Tr=class extends ee{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(t,e){return this._callWithConfig(n=>this.formatMessages(n),t,{...e,runType:"prompt"})}},ds=class extends Tr{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(t){typeof t=="string"&&(t={variableName:t}),super(t),this.variableName=t.variableName,this.optional=t.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(t){const e=t[this.variableName];if(this.optional&&!e)return[];if(!e){const r=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw r.name="InputFormatError",r}let n;try{Array.isArray(e)?n=e.map(pn):n=[pn(e)]}catch(r){const s=typeof e=="string"?e:JSON.stringify(e,null,2),i=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(`
18
18
 
19
- `));throw i.name="InputFormatError",i.lc_error_code=s.lc_error_code,i}return n}},ea=class extends Ts{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)]}},Gr=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 sc(e)}},ta=class extends ea{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 ao(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Je.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 bh(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 Kr=class extends Ts{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(s=>{"inputVariables"in s&&(n=n.concat(s.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(Je.fromTemplate(t,e));const n=[];for(const s of t)if(typeof s=="string")n.push(Je.fromTemplate(s,e));else if(s!==null)if(_h(s)){let r="";typeof s.text=="string"&&(r=s.text??"");const i={...e,additionalContentFields:s};n.push(Je.fromTemplate(r,i))}else if(bh(s)){let r=s.image_url??"",i,o=[];if(typeof r=="string"){let a;e?.templateFormat==="mustache"?a=as(r):a=wn(r);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.
19
+ `));throw i.name="InputFormatError",i.lc_error_code=r.lc_error_code,i}return n}},ta=class extends Tr{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)]}},Gs=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 oc(e)}},na=class extends ta{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 lo(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Je.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function kh(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Eh(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 Ks=class extends Tr{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(Je.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(Je.fromTemplate(r,e));else if(r!==null)if(kh(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const i={...e,additionalContentFields:r};n.push(Je.fromTemplate(s,i))}else if(Eh(r)){let s=r.image_url??"",i,o=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=ar(s):a=wn(s);const l=a.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
20
20
  Got: ${l}
21
- From: ${r}`);o=[l[0]]}else o=[];r={url:r},i=new Un({template:r,inputVariables:o,templateFormat:e?.templateFormat,additionalContentFields:s})}else if(typeof r=="object"){if("url"in r){let a;e?.templateFormat==="mustache"?a=as(r.url):a=wn(r.url),o=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else o=[];i=new Un({template:r,inputVariables:o,templateFormat:e?.templateFormat,additionalContentFields:s})}else throw new Error("Invalid image template");n.push(i)}else typeof s=="object"&&n.push(new cr({template:s,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof gn){const e=await this.prompt.format(t);return this.createMessage(e)}else{const e=[];for(const n of this.prompt){let s={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(const r of n.inputVariables)s||(s={[r]:t[r]}),s={...s,[r]:t[r]};if(n instanceof gn){const r=await n.format(s);let i;"additionalContentFields"in n&&(i=n.additionalContentFields),r!==""&&e.push({...i,type:"text",text:r})}else if(n instanceof Un){const r=await n.format(s);let i;"additionalContentFields"in n&&(i=n.additionalContentFields),e.push({...i,type:"image_url",image_url:r})}else if(n instanceof cr){const r=await n.format(s);let i;"additionalContentFields"in n&&(i=n.additionalContentFields),e.push({...i,...r})}}return this.createMessage(e)}}async formatMessages(t){return[await this.format(t)]}},Jr=class extends Kr{static _messageClass(){return oe}static lc_name(){return"HumanMessagePromptTemplate"}},na=class extends Kr{static _messageClass(){return N}static lc_name(){return"AIMessagePromptTemplate"}},sa=class extends Kr{static _messageClass(){return _e}static lc_name(){return"SystemMessagePromptTemplate"}};function vh(t){return typeof t.formatMessages=="function"}function Sh(t,e){if(vh(t)||Oe(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){const r=t[1];if(e?.templateFormat==="mustache"&&typeof r=="string"&&r.slice(0,2)==="{{"&&r.slice(-2)==="}}"){const i=r.slice(2,-2);return new dr({variableName:i,optional:!0})}else if(typeof r=="string"&&r[0]==="{"&&r[r.length-1]==="}"){const i=r.slice(1,-1);return new dr({variableName:i,optional:!0})}throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const n=pn(t);let s;if(typeof n.content=="string"?s=n.content:s=n.content.map(r=>"text"in r?{...r,text:r.text}:"image_url"in r?{...r,image_url:r.image_url}:r),n._getType()==="human")return Jr.fromTemplate(s,e);if(n._getType()==="ai")return na.fromTemplate(s,e);if(n._getType()==="system")return sa.fromTemplate(s,e);if(ao.isInstance(n))return ta.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function Ch(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var qr=class Fn extends Gr{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 s=this.inputVariables,r=new Set(this.partialVariables?s.concat(Object.keys(this.partialVariables)):s),i=new Set([...r].filter(a=>!n.has(a)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);const o=new Set([...n].filter(a=>!r.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` 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 s=await Promise.all(e.content.map(async r=>{if(r.type!=="image_url")return r;let i="";typeof r.image_url=="string"?i=r.image_url:typeof r.image_url=="object"&&r.image_url!==null&&"url"in r.image_url&&typeof r.image_url.url=="string"&&(i=r.image_url.url);const a=await Je.fromTemplate(i,{templateFormat:this.templateFormat}).format(n);return typeof r.image_url=="object"&&r.image_url!==null&&"url"in r.image_url?r.image_url.url=a:r.image_url=a,r}));return e.content=s,e}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let s=[];for(const r of this.promptMessages)if(r instanceof an)s.push(await this._parseImagePrompts(r,n));else{let i;this.templateFormat==="mustache"?i={...n}:i=r.inputVariables.reduce((a,l)=>{if(!(l in n)&&!(Ch(r)&&r.optional))throw oo(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return a[l]=n[l],a},{});const o=await r.formatMessages(i);s=s.concat(o)}return s}async partial(e){const n=this.inputVariables.filter(i=>!(i in e)),s={...this.partialVariables??{},...e},r={...this,inputVariables:n,partialVariables:s};return new Fn(r)}static fromTemplate(e,n){const s=Je.fromTemplate(e,n),r=new Jr({prompt:s});return this.fromMessages([r])}static fromMessages(e,n){const s=e.reduce((o,a)=>o.concat(a instanceof Fn?a.promptMessages:[Sh(a,n)]),[]),r=e.reduce((o,a)=>a instanceof Fn?Object.assign(o,a.partialVariables):o,Object.create(null)),i=new Set;for(const o of s)if(!(o instanceof an))for(const a of o.inputVariables)a in r||i.add(a);return new this({...n,inputVariables:[...i],promptMessages:s,partialVariables:r,templateFormat:n?.templateFormat})}},Th=class fr extends gn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
21
+ From: ${s}`);o=[l[0]]}else o=[];s={url:s},i=new Un({template:s,inputVariables:o,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=ar(s.url):a=wn(s.url),o=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else o=[];i=new Un({template:s,inputVariables:o,templateFormat:e?.templateFormat,additionalContentFields:r})}else throw new Error("Invalid image template");n.push(i)}else typeof r=="object"&&n.push(new cs({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof gn){const e=await this.prompt.format(t);return this.createMessage(e)}else{const e=[];for(const n of this.prompt){let r={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(const s of n.inputVariables)r||(r={[s]:t[s]}),r={...r,[s]:t[s]};if(n instanceof gn){const s=await n.format(r);let i;"additionalContentFields"in n&&(i=n.additionalContentFields),s!==""&&e.push({...i,type:"text",text:s})}else if(n instanceof Un){const s=await n.format(r);let i;"additionalContentFields"in n&&(i=n.additionalContentFields),e.push({...i,type:"image_url",image_url:s})}else if(n instanceof cs){const s=await n.format(r);let i;"additionalContentFields"in n&&(i=n.additionalContentFields),e.push({...i,...s})}}return this.createMessage(e)}}async formatMessages(t){return[await this.format(t)]}},Js=class extends Ks{static _messageClass(){return oe}static lc_name(){return"HumanMessagePromptTemplate"}},ra=class extends Ks{static _messageClass(){return N}static lc_name(){return"AIMessagePromptTemplate"}},sa=class extends Ks{static _messageClass(){return _e}static lc_name(){return"SystemMessagePromptTemplate"}};function xh(t){return typeof t.formatMessages=="function"}function Ah(t,e){if(xh(t)||Oe(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 i=s.slice(2,-2);return new ds({variableName:i,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const i=s.slice(1,-1);return new ds({variableName:i,optional:!0})}throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}const n=pn(t);let r;if(typeof n.content=="string"?r=n.content:r=n.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),n._getType()==="human")return Js.fromTemplate(r,e);if(n._getType()==="ai")return ra.fromTemplate(r,e);if(n._getType()==="system")return sa.fromTemplate(r,e);if(lo.isInstance(n))return na.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function Mh(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var qs=class Fn extends Gs{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),i=new Set([...s].filter(a=>!n.has(a)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);const o=new Set([...n].filter(a=>!s.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` 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 i="";typeof s.image_url=="string"?i=s.image_url:typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(i=s.image_url.url);const a=await Je.fromTemplate(i,{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 i;this.templateFormat==="mustache"?i={...n}:i=s.inputVariables.reduce((a,l)=>{if(!(l in n)&&!(Mh(s)&&s.optional))throw ao(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return a[l]=n[l],a},{});const o=await s.formatMessages(i);r=r.concat(o)}return r}async partial(e){const n=this.inputVariables.filter(i=>!(i in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Fn(s)}static fromTemplate(e,n){const r=Je.fromTemplate(e,n),s=new Js({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((o,a)=>o.concat(a instanceof Fn?a.promptMessages:[Ah(a,n)]),[]),s=e.reduce((o,a)=>a instanceof Fn?Object.assign(o,a.partialVariables):o,Object.create(null)),i=new Set;for(const o of r)if(!(o instanceof an))for(const a of o.inputVariables)a in s||i.add(a);return new this({...n,inputVariables:[...i],promptMessages:r,partialVariables:s,templateFormat:n?.templateFormat})}},Ph=class fs extends gn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
22
22
 
23
- `;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))),xn(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(i=>!(i in e)),s={...this.partialVariables??{},...e},r={...this,inputVariables:n,partialVariables:s};return new fr(r)}async format(e){const n=await this.mergePartialAndUserVariables(e),s=await this.getExamples(n),r=await Promise.all(s.map(o=>this.examplePrompt.format(o))),i=[this.prefix,...r,this.suffix].join(this.exampleSeparator);return Te(i,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 s=await Je.deserialize(n);let r;if(Array.isArray(e.examples))r=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new fr({inputVariables:e.input_variables,examplePrompt:s,examples:r,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},kh=class ra extends Gr{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
23
+ `;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))),xn(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(i=>!(i in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new fs(s)}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),s=await Promise.all(r.map(o=>this.examplePrompt.format(o))),i=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return Te(i,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 Je.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 fs({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},Nh=class ia extends Gs{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
24
24
 
25
25
  `;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??`
26
26
 
27
- `,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))),xn(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 s=await this.getExamples(n);s=s.map(i=>{const o={};return this.examplePrompt.inputVariables.forEach(a=>{o[a]=i[a]}),o});const r=[];for(const i of s){const o=await this.examplePrompt.formatMessages(i);r.push(...o)}return r}async format(e){const n=await this.mergePartialAndUserVariables(e),s=await this.getExamples(n),i=(await Promise.all(s.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),o=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Te(o,this.templateFormat,n)}async partial(e){const n=this.inputVariables.filter(i=>!(i in e)),s={...this.partialVariables??{},...e},r={...this,inputVariables:n,partialVariables:s};return new ra(r)}},Eh=class Vn 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(s=>s.name),n=this.pipelinePrompts.map(s=>s.prompt.inputVariables.filter(r=>!e.includes(r))).flat();return[...new Set(n)]}static extractRequiredInputValues(e,n){return n.reduce((s,r)=>(s[r]=e[r],s),{})}async formatPipelinePrompts(e){const n=await this.mergePartialAndUserVariables(e);for(const{name:s,prompt:r}of this.pipelinePrompts){const i=Vn.extractRequiredInputValues(n,r.inputVariables);r instanceof qr?n[s]=await r.formatMessages(i):n[s]=await r.format(i)}return Vn.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(s=>!(s in e)),n.partialVariables={...this.partialVariables??{},...e},new Vn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function ki(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function xh(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 Ah=class ia extends qr{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(ki(e))return super.pipe(e.withStructuredOutput(this.schema));if(xh(e)&&ki(e.bound))return super.pipe(new xe({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,s){return ia.fromMessages(e,{schema:n,method:s})}},oa={};q(oa,{AIMessagePromptTemplate:()=>na,BaseChatPromptTemplate:()=>Gr,BaseMessagePromptTemplate:()=>Ts,BaseMessageStringPromptTemplate:()=>ea,BasePromptTemplate:()=>kn,BaseStringPromptTemplate:()=>gn,ChatMessagePromptTemplate:()=>ta,ChatPromptTemplate:()=>qr,DEFAULT_FORMATTER_MAPPING:()=>ls,DEFAULT_PARSER_MAPPING:()=>Zo,DictPromptTemplate:()=>cr,FewShotChatMessagePromptTemplate:()=>kh,FewShotPromptTemplate:()=>Th,HumanMessagePromptTemplate:()=>Jr,ImagePromptTemplate:()=>Un,MessagesPlaceholder:()=>dr,PipelinePromptTemplate:()=>Eh,PromptTemplate:()=>Je,StructuredPrompt:()=>Ah,SystemMessagePromptTemplate:()=>sa,checkValidTemplate:()=>xn,interpolateFString:()=>Yo,interpolateMustache:()=>Xo,parseFString:()=>wn,parseMustache:()=>as,parseTemplate:()=>cs,renderTemplate:()=>Te});var aa={};q(aa,{BaseDocumentCompressor:()=>Mh});var Mh=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const Ge={and:"and",or:"or",not:"not"},$={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var la=class{},Yr=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")}},Xr=class extends Yr{},Ph=class extends Xr{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},Nh=class extends Xr{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},Oh=class extends Yr{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function ca(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Se(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 Zr(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 Qr=class extends la{},Ih=class extends Qr{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Ge.and,Ge.or],this.allowedComparators=t?.allowedComparators??[$.eq,$.ne,$.gt,$.gte,$.lt,$.lte]}formatFunction(t){if(t in $){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 Ge){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)]:Zr(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",s=!1){if(!(Se(t)&&Se(e))){if(Se(t)||n==="replace")return Se(e)?void 0:e;if(Se(e))return s?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")}}},Rh=class extends Qr{allowedOperators=[Ge.and,Ge.or];allowedComparators=[$.eq,$.ne,$.gt,$.gte,$.lt,$.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[$.eq,$.ne,$.gt,$.gte,$.lt,$.lte];case"number":return[$.eq,$.ne,$.gt,$.gte,$.lt,$.lte];case"boolean":return[$.eq,$.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case $.eq:return(e,n)=>e===n;case $.ne:return(e,n)=>e!==n;case $.gt:return(e,n)=>e>n;case $.gte:return(e,n)=>e>=n;case $.lt:return(e,n)=>e<n;case $.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case Ge.and:return(e,n)=>e&&n;case Ge.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 s=this.getOperatorFunction(e);return r=>n?n.reduce((i,o)=>{const a=o.accept(this);if(typeof a=="function")return s(i,a(r));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:s}=t,r=[$.ne];if(this.allowedComparators.includes(e)){if(!this.getAllowedComparatorsForType(typeof s).includes(e))throw new Error(`'${e}' comparator not allowed to be used with ${typeof s}`);const i=this.getComparatorFunction(e);return o=>{const a=o.metadata[n];return a===void 0?!!r.includes(e):i(a,Zr(s))}}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(!(Se(t)&&Se(e))){if(Se(t)||n==="replace")return Se(e)?void 0:e;if(Se(e))return n==="and"?void 0:t;if(n==="and")return s=>t(s)&&e(s);if(n==="or")return s=>t(s)||e(s);throw new Error("Unknown merge type")}}},pa={};q(pa,{BaseTranslator:()=>Qr,BasicTranslator:()=>Ih,Comparators:()=>$,Comparison:()=>Ph,Expression:()=>Yr,FilterDirective:()=>Xr,FunctionalTranslator:()=>Rh,Operation:()=>Nh,Operators:()=>Ge,StructuredQuery:()=>Oh,Visitor:()=>la,castValue:()=>Zr,isBoolean:()=>fa,isFilterEmpty:()=>Se,isFloat:()=>ha,isInt:()=>ua,isObject:()=>ca,isString:()=>da});var ma={};q(ma,{RunCollectorCallbackHandler:()=>$h});var $h=class extends Rr{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)}},jh={},ga={};q(ga,{EventStreamContentType:()=>Lh,convertEventStreamToIterableReadableDataStream:()=>Uh,getBytes:()=>ya,getLines:()=>wa,getMessages:()=>_a});const Lh="text/event-stream";async function ya(t,e){if(t instanceof ReadableStream){const n=t.getReader();for(;;){const s=await n.read();if(s.done){e(new Uint8Array,!0);break}e(s.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(`
28
- `))}}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 wa(t){let e,n,s,r=!1;return function(o,a){if(a){t(o,0,!0);return}e===void 0?(e=o,n=0,s=-1):e=Dh(e,o);const l=e.length;let c=0;for(;n<l;){r&&(e[n]===_t.NewLine&&(c=++n),r=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case _t.Colon:s===-1&&(s=n-c);break;case _t.CarriageReturn:r=!0;case _t.NewLine:u=n;break}if(u===-1)break;t(e.subarray(c,u),s),c=n,s=-1}c===l?e=void 0:c!==0&&(e=e.subarray(c),n-=c)}}function _a(t,e,n){let s=Ls();const r=new TextDecoder;return function(o,a,l){if(l){Fh(s)||(t?.(s),s=Ls());return}if(o.length===0)t?.(s),s=Ls();else if(a>0){const c=r.decode(o.subarray(0,a)),u=a+(o[a+1]===_t.Space?2:1),h=r.decode(o.subarray(u));switch(c){case"data":s.data=s.data?s.data+`
29
- `+h:h;break;case"event":s.event=h;break;case"id":e?.(s.id=h);break;case"retry":{const d=parseInt(h,10);Number.isNaN(d)||n?.(s.retry=d);break}}}}}function Dh(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function Ls(){return{data:"",event:"",id:"",retry:void 0}}function Uh(t,e){const n=new ReadableStream({async start(s){const r=_a(o=>{if(o.event==="error")throw new Error(o.data??"Unspecified event streaming error.");o.event==="metadata"?e?.(o):o.data&&s.enqueue(o.data)});await ya(t,wa((o,a,l)=>{r(o,a,l),l&&s.close()}))}});return fn.fromReadableStream(n)}function Fh(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Vh={};function ba(t,e){let n=0,s=0,r=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],s+=t[i]*t[i],r+=e[i]*e[i];return n/(Math.sqrt(s)*Math.sqrt(r))}function Bh(t,e){let n=0;for(let s=0;s<t.length;s++)n+=t[s]*e[s];return n}function Wh(t,e){let n=0;for(let s=0;s<t.length;s++)n+=(t[s]-e[s])*(t[s]-e[s]);return n}function Hh(t,e){return Math.sqrt(Wh(t,e))}var va={};q(va,{cosineSimilarity:()=>pr,euclideanDistance:()=>Kh,innerProduct:()=>Gh,matrixFunc:()=>ks,maximalMarginalRelevance:()=>Jh,normalize:()=>zh});function ks(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(s=>e.map(r=>n(s,r)).map(r=>Number.isNaN(r)?0:r))}function zh(t,e=!1){const n=qh(t);return t.map(s=>s.map(r=>e?1-r/n:r/n))}function pr(t,e){return ks(t,e,ba)}function Gh(t,e){return ks(t,e,Bh)}function Kh(t,e){return ks(t,e,Hh)}function Jh(t,e,n=.5,s=4){if(Math.min(s,e.length)<=0)return[];const r=Array.isArray(t[0])?t:[t],i=pr(r,e)[0],o=Sa(i).maxIndex,a=[e[o]],l=[o];for(;l.length<Math.min(s,e.length);){let c=-1/0,u=-1;const h=pr(e,a);i.forEach((d,f)=>{if(l.includes(f))return;const y=Math.max(...h[f]),p=n*d-(1-n)*y;p>c&&(c=p,u=f)}),a.push(e[u]),l.push(u)}return l}function Sa(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let s=1;s<t.length;s+=1)t[s]>e&&(n=s,e=t[s]);return{maxIndex:n,maxValue:e}}function qh(t){return t.reduce((e,n)=>Math.max(e,Sa(n).maxValue),0)}var Yh=class extends Tn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new N(e.stop[0]),text:e.stop[0]}]};const s=t.map(r=>typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2)).join(`
30
- `);return await n?.handleLLMNewToken(s),{generations:[{message:new N(s),text:s}],llmOutput:{}}}},Xh=class Ca extends Tn{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:e=50,responses:n=[],chunks:s=[],toolStyle:r="openai",thrownErrorString:i,...o}){super(o),this.sleep=e,this.responses=n,this.chunks=s,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return"fake"}bindTools(e){const n=[...this.tools,...e],s=n.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:st(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:st(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:st(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:st(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),r=this.toolStyle==="google"?[{functionDeclarations:s}]:s,i=new Ca({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return i.tools=n,i.withConfig({tools:r})}async _generate(e,n,s){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new N({content:r,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,s){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const o of this.chunks){const a=new tr({message:new Vt({content:o.content,tool_calls:o.tool_calls,additional_kwargs:o.additional_kwargs??{}}),text:o.content?.toString()??""});yield a,await s?.handleLLMNewToken(o.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const r=this.responses?.[0]??new N(typeof e[0].content=="string"?e[0].content:""),i=typeof r.content=="string"?r.content:"";for(const o of i){await new Promise(l=>setTimeout(l,this.sleep));const a=new tr({message:new Vt({content:o}),text:o});yield a,await s?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:a})}}},Zh=class extends Tn{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;constructor(t){super(t);const{responses:e,sleep:n,emitCustomEvent:s}=t;this.responses=e,this.sleep=n,this.emitCustomEvent=s??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,e,n){if(await this._sleepIfRequested(),e?.thrownErrorString)throw new Error(e.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),e?.stop?.length)return{generations:[this._formatGeneration(e.stop[0])]};{const s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(t){return{message:new N(t),text:t}}async*_streamResponseChunks(t,e,n){const s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});for await(const r of s){if(await this._sleepIfRequested(),e?.thrownErrorString)throw new Error(e.thrownErrorString);yield this._createResponseChunk(r),n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t){return new tr({message:new Vt({content:t}),text:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}withStructuredOutput(t,e){return Bt.from(async n=>{const s=await this.invoke(n);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")})}},Qh=class extends uo{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,s=n===0?0:this.vectorSize-n,r=e.length+s;e=e.padEnd(r," ");const i=e.length/this.vectorSize,o=[];for(let l=0;l<e.length;l+=i)o.push(e.slice(l,l+i));return o.map(l=>{let c=0;for(let h=0;h<l.length;h+=1)c+=l===" "?0:l.charCodeAt(h);return c%26/26})}},ed=class extends uo{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},td=class extends to{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 s=this.response??t;return await n?.handleLLMNewToken(s),s}},nd=class extends to{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 s=this.responses?.[0];this.responses=this.responses?.slice(1);for(const r of s??t)await new Promise(i=>setTimeout(i,this.sleep)),yield{text:r,generationInfo:{}},await n?.handleLLMNewToken(r)}},sd=class extends So{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 oe(t))}async addAIMessage(t){this.messages.push(new N(t))}async clear(){this.messages=[]}},rd=class extends Vr{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},id=class extends Rr{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},od=class extends rc{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},ad=class extends Br{lc_namespace=["test","fake"];output=[new De({pageContent:"foo"}),new De({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},ld=class extends ee{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},cd=class extends vs{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)}},ud=class extends Rr{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}},hd=class Ta extends Wr{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...s}={}){super(e,s),this.similarity=n??ba}async addDocuments(e){const n=e.map(({pageContent:s})=>s);return this.addVectors(await this.embeddings.embedDocuments(n),e)}async addVectors(e,n){const s=e.map((r,i)=>({content:n[i].pageContent,embedding:r,metadata:n[i].metadata}));this.memoryVectors=this.memoryVectors.concat(s)}async similaritySearchVectorWithScore(e,n,s){const r=l=>{if(!s)return!0;const c=new De({metadata:l.metadata,pageContent:l.content});return s(c)},i=this.memoryVectors.filter(r);return i.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 De({metadata:i[l.index].metadata,pageContent:i[l.index].content}),l.similarity])}static async fromTexts(e,n,s,r){const i=[];for(let o=0;o<e.length;o+=1){const a=Array.isArray(n)?n[o]:n,l=new De({pageContent:e[o],metadata:a});i.push(l)}return Ta.fromDocuments(i,s,r)}static async fromDocuments(e,n,s){const r=new this(n,s);return await r.addDocuments(e),r}static async fromExistingIndex(e,n){return new this(e,n)}},ka={};q(ka,{FakeChatMessageHistory:()=>sd,FakeChatModel:()=>Yh,FakeEmbeddings:()=>ed,FakeLLM:()=>td,FakeListChatMessageHistory:()=>rd,FakeListChatModel:()=>Zh,FakeRetriever:()=>ad,FakeRunnable:()=>ld,FakeSplitIntoListParser:()=>od,FakeStreamingChatModel:()=>Xh,FakeStreamingLLM:()=>nd,FakeTool:()=>cd,FakeTracer:()=>id,FakeVectorStore:()=>hd,SingleRunExtractor:()=>ud,SyntheticEmbeddings:()=>Qh});var Ea={};q(Ea,{agents:()=>Du,caches:()=>mc,callbacks__base:()=>Bc,callbacks__manager:()=>Vc,callbacks__promises:()=>Fc,chat_history:()=>vo,document_loaders__base:()=>Po,document_loaders__langsmith:()=>Oo,documents:()=>Ro,embeddings:()=>uu,example_selectors:()=>Do,index:()=>Fu,indexing:()=>Ho,language_models__base:()=>pc,language_models__chat_models:()=>fc,language_models__llms:()=>Jl,load__serializable:()=>Uc,memory:()=>Co,messages:()=>Dc,messages__tool:()=>Lc,output_parsers:()=>dc,output_parsers__openai_functions:()=>Ko,output_parsers__openai_tools:()=>Kl,outputs:()=>jc,prompt_values:()=>hc,prompts:()=>oa,retrievers:()=>Ao,retrievers__document_compressors:()=>aa,runnables:()=>uc,runnables__graph:()=>$c,singletons:()=>Rc,stores:()=>ko,structured_query:()=>pa,tools:()=>Gl,tracers__base:()=>Ic,tracers__console:()=>Oc,tracers__log_stream:()=>Nc,tracers__run_collector:()=>ma,tracers__tracer_langchain:()=>Pc,types__stream:()=>jh,utils__async_caller:()=>Mc,utils__chunk_array:()=>cu,utils__env:()=>Ac,utils__event_source_parse:()=>ga,utils__format:()=>Vh,utils__function_calling:()=>cc,utils__hash:()=>lc,utils__json_patch:()=>ac,utils__json_schema:()=>xc,utils__math:()=>va,utils__stream:()=>Ec,utils__testing:()=>ka,utils__tiktoken:()=>oc,utils__types:()=>ic,vectorstores:()=>Mo});function dd(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,[s,r])=>(n[r]=s,n),{})}async function Bn(t){const{optionalImportsMap:e={},optionalImportEntrypoints:n=[],importMap:s={},secretsMap:r={},path:i=["$"]}=this,o=i.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 r)return r[l];{const c=Wc(l);if(c)return c;throw new Error(`Missing key "${l}" for ${o} 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: ${o} -> ${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:s};let f=null;const y=[h.join("/")];h[0]==="langchain_community"&&y.push(["langchain",...h.slice(1)].join("/"));const p=y.find(m=>m in e);if(Lu.concat(n).includes(h.join("/"))||p)if(p!==void 0)f=await e[p];else throw new Error(`Missing key "${h.join("/")}" for ${o} in load(optionalImportsMap={})`);else{let m;if(h[0]==="langchain"||h[0]==="langchain_core")m=d[h[0]],h.shift();else throw new Error(`Invalid namespace: ${o} -> ${l}`);if(h.length===0)throw new Error(`Invalid namespace: ${o} -> ${l}`);let w;do{if(w=h.join("__"),w in m)break;h.pop()}while(h.length>0);w in m&&(f=m[w])}if(typeof f!="object"||f===null)throw new Error(`Invalid namespace: ${o} -> ${l}`);const S=f[c]??Object.values(f).find(m=>typeof m=="function"&&Hc(m)===c);if(typeof S!="function")throw new Error(`Invalid identifer: ${o} -> ${l}`);const C=await Bn.call({...this,path:[...i,"kwargs"]},a.kwargs);if(a.type==="constructor"){const m=new S(zc(C,Gc,dd(S)));return Object.defineProperty(m.constructor,"name",{value:c}),m}else throw new Error(`Invalid type: ${o} -> ${l}`)}else if(typeof t=="object"&&t!==null)return Array.isArray(t)?Promise.all(t.map((a,l)=>Bn.call({...this,path:[...i,`${l}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,l])=>[a,await Bn.call({...this,path:[...i,a]},l)])));return t}async function fd(t,e){const n=JSON.parse(t);return Bn.call({...e},n)}function pd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function mr(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>mr(n)));{const e={};for(const[n,s]of Object.entries(t))e[n]=await mr(s);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 s;switch(n){case"Set":s=Set;break;case"Map":s=Map;break;case"RegExp":s=RegExp;break;case"Error":s=Error;break;default:return e}return e.method?s[e.method](...e.args||[]):new s(...e.args||[])}catch{return e}else if(pd(e))return fd(JSON.stringify(e));return e}}return t}function Ds(t,e,n,s){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:s??{}}}function md(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Ds(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Ds(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Ds(t.constructor,void 0,[t.message]):t?.lg_name==="Send"?{node:t.node,args:t.args}:t}var gd=class{_dumps(t){return new TextEncoder().encode($u(t,(n,s)=>md(s)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return mr(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 Aa(){return{v:4,id:bo(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function us(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 Ma(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function yd(...t){return t.reduce((e,n,s)=>s===0?n:Ma(e,n)>=0?e:n)}const wd={[Pu]:-1,[Ln]:-2,[Nu]:-3,[Ou]:-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 bd=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:s=10,offset:r=0,query:i}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:s,offset:r,query:i}]))[0]}async put(t,e,n,s){_d(t),await this.batch([{namespace:t,key:e,value:n,index:s}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:s,limit:r=100,offset:i=0}=t,o=[];return e&&o.push({matchType:"prefix",path:e}),n&&o.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:s,limit:r,offset:i}]))[0]}start(){}stop(){}};const vd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var Sd=class extends bd{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=vd(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:s=10,offset:r=0,query:i}=e||{};return this.enqueueOperation({namespacePrefix:t,filter:n,limit:s,offset:r,query:i})}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 s=this.nextKey;this.nextKey+=1,this.queue.set(s,{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:s})=>s),n=await this.store.batch(e);t.forEach(({resolve:s},r)=>{const i=Array.from(t.keys()).indexOf(r);s(n[i])})}catch(e){t.forEach(({reject:n})=>{n(e)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},Cd=class{serde=new gd;constructor(t){this.serde=t||this.serde}},Td=class Pa extends Tn{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:n="openai",index:s=0,structuredResponse:r,indexRef:i,...o}={}){super(o),this.toolCalls=e,this.toolStyle=n,this.indexRef=i??{current:s},this.structuredResponse=r}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,s){let i=e[e.length-1].content;e.length>1&&(i=e.map(h=>h.content).filter(Boolean).join("-")),(e.length===1||e.length===2&&e.every(oe.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 N({content:i,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:i,message:c}],llmOutput:{}}}};class kd{constructor(){this.store=void 0}getStore(){return this.store}run(e,n,...s){this.store=e;try{return n(...s)}finally{this.store=void 0}}exit(e,...n){const s=this.store;this.store=void 0;try{return e(...n)}finally{this.store=s}}enterWith(e){this.store=e}disable(){this.store=void 0}}function Ed(){Le.initializeGlobalInstance(new kd)}var ht=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
27
+ `,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))),xn(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(i=>{const o={};return this.examplePrompt.inputVariables.forEach(a=>{o[a]=i[a]}),o});const s=[];for(const i of r){const o=await this.examplePrompt.formatMessages(i);s.push(...o)}return s}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),i=(await Promise.all(r.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),o=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Te(o,this.templateFormat,n)}async partial(e){const n=this.inputVariables.filter(i=>!(i in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new ia(s)}},Oh=class Vn 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 i=Vn.extractRequiredInputValues(n,s.inputVariables);s instanceof qs?n[r]=await s.formatMessages(i):n[r]=await s.format(i)}return Vn.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 Vn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function Ei(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function Ih(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 $h=class oa extends qs{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(Ei(e))return super.pipe(e.withStructuredOutput(this.schema));if(Ih(e)&&Ei(e.bound))return super.pipe(new xe({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 oa.fromMessages(e,{schema:n,method:r})}},aa={};q(aa,{AIMessagePromptTemplate:()=>ra,BaseChatPromptTemplate:()=>Gs,BaseMessagePromptTemplate:()=>Tr,BaseMessageStringPromptTemplate:()=>ta,BasePromptTemplate:()=>kn,BaseStringPromptTemplate:()=>gn,ChatMessagePromptTemplate:()=>na,ChatPromptTemplate:()=>qs,DEFAULT_FORMATTER_MAPPING:()=>lr,DEFAULT_PARSER_MAPPING:()=>Qo,DictPromptTemplate:()=>cs,FewShotChatMessagePromptTemplate:()=>Nh,FewShotPromptTemplate:()=>Ph,HumanMessagePromptTemplate:()=>Js,ImagePromptTemplate:()=>Un,MessagesPlaceholder:()=>ds,PipelinePromptTemplate:()=>Oh,PromptTemplate:()=>Je,StructuredPrompt:()=>$h,SystemMessagePromptTemplate:()=>sa,checkValidTemplate:()=>xn,interpolateFString:()=>Xo,interpolateMustache:()=>Zo,parseFString:()=>wn,parseMustache:()=>ar,parseTemplate:()=>cr,renderTemplate:()=>Te});var la={};q(la,{BaseDocumentCompressor:()=>Rh});var Rh=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const Ge={and:"and",or:"or",not:"not"},R={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var ca=class{},Ys=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")}},Xs=class extends Ys{},jh=class extends Xs{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},Lh=class extends Xs{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},Dh=class extends Ys{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function ua(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Se(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 Zs(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 Qs=class extends ca{},Uh=class extends Qs{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[Ge.and,Ge.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 Ge){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)]:Zs(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Se(t)&&Se(e))){if(Se(t)||n==="replace")return Se(e)?void 0:e;if(Se(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")}}},Fh=class extends Qs{allowedOperators=[Ge.and,Ge.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 Ge.and:return(e,n)=>e&&n;case Ge.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((i,o)=>{const a=o.accept(this);if(typeof a=="function")return r(i,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 i=this.getComparatorFunction(e);return o=>{const a=o.metadata[n];return a===void 0?!!s.includes(e):i(a,Zs(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(!(Se(t)&&Se(e))){if(Se(t)||n==="replace")return Se(e)?void 0:e;if(Se(e))return n==="and"?void 0:t;if(n==="and")return r=>t(r)&&e(r);if(n==="or")return r=>t(r)||e(r);throw new Error("Unknown merge type")}}},ma={};q(ma,{BaseTranslator:()=>Qs,BasicTranslator:()=>Uh,Comparators:()=>R,Comparison:()=>jh,Expression:()=>Ys,FilterDirective:()=>Xs,FunctionalTranslator:()=>Fh,Operation:()=>Lh,Operators:()=>Ge,StructuredQuery:()=>Dh,Visitor:()=>ca,castValue:()=>Zs,isBoolean:()=>pa,isFilterEmpty:()=>Se,isFloat:()=>da,isInt:()=>ha,isObject:()=>ua,isString:()=>fa});var ga={};q(ga,{RunCollectorCallbackHandler:()=>Vh});var Vh=class extends $s{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)}},Bh={},ya={};q(ya,{EventStreamContentType:()=>Wh,convertEventStreamToIterableReadableDataStream:()=>Hh,getBytes:()=>wa,getLines:()=>_a,getMessages:()=>ba});const Wh="text/event-stream";async function wa(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(`
28
+ `))}}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 _a(t){let e,n,r,s=!1;return function(o,a){if(a){t(o,0,!0);return}e===void 0?(e=o,n=0,r=-1):e=zh(e,o);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 ba(t,e,n){let r=Lr();const s=new TextDecoder;return function(o,a,l){if(l){Gh(r)||(t?.(r),r=Lr());return}if(o.length===0)t?.(r),r=Lr();else if(a>0){const c=s.decode(o.subarray(0,a)),u=a+(o[a+1]===_t.Space?2:1),h=s.decode(o.subarray(u));switch(c){case"data":r.data=r.data?r.data+`
29
+ `+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 zh(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 Hh(t,e){const n=new ReadableStream({async start(r){const s=ba(o=>{if(o.event==="error")throw new Error(o.data??"Unspecified event streaming error.");o.event==="metadata"?e?.(o):o.data&&r.enqueue(o.data)});await wa(t,_a((o,a,l)=>{s(o,a,l),l&&r.close()}))}});return fn.fromReadableStream(n)}function Gh(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Kh={};function va(t,e){let n=0,r=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],r+=t[i]*t[i],s+=e[i]*e[i];return n/(Math.sqrt(r)*Math.sqrt(s))}function Jh(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function qh(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 Yh(t,e){return Math.sqrt(qh(t,e))}var Sa={};q(Sa,{cosineSimilarity:()=>ps,euclideanDistance:()=>Qh,innerProduct:()=>Zh,matrixFunc:()=>kr,maximalMarginalRelevance:()=>ed,normalize:()=>Xh});function kr(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 Xh(t,e=!1){const n=td(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function ps(t,e){return kr(t,e,va)}function Zh(t,e){return kr(t,e,Jh)}function Qh(t,e){return kr(t,e,Yh)}function ed(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],i=ps(s,e)[0],o=Ca(i).maxIndex,a=[e[o]],l=[o];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const h=ps(e,a);i.forEach((d,f)=>{if(l.includes(f))return;const y=Math.max(...h[f]),p=n*d-(1-n)*y;p>c&&(c=p,u=f)}),a.push(e[u]),l.push(u)}return l}function Ca(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 td(t){return t.reduce((e,n)=>Math.max(e,Ca(n).maxValue),0)}var nd=class extends Tn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new N(e.stop[0]),text:e.stop[0]}]};const r=t.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
30
+ `);return await n?.handleLLMNewToken(r),{generations:[{message:new N(r),text:r}],llmOutput:{}}}},rd=class Ta extends Tn{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:e=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:i,...o}){super(o),this.sleep=e,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=i}_llmType(){return"fake"}bindTools(e){const n=[...this.tools,...e],r=n.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:rt(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:rt(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:rt(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:rt(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,i=new Ta({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return i.tools=n,i.withConfig({tools:s})}async _generate(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new N({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const o of this.chunks){const a=new ts({message:new Vt({content:o.content,tool_calls:o.tool_calls,additional_kwargs:o.additional_kwargs??{}}),text:o.content?.toString()??""});yield a,await r?.handleLLMNewToken(o.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new N(typeof e[0].content=="string"?e[0].content:""),i=typeof s.content=="string"?s.content:"";for(const o of i){await new Promise(l=>setTimeout(l,this.sleep));const a=new ts({message:new Vt({content:o}),text:o});yield a,await r?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:a})}}},sd=class extends Tn{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;constructor(t){super(t);const{responses:e,sleep:n,emitCustomEvent:r}=t;this.responses=e,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,e,n){if(await this._sleepIfRequested(),e?.thrownErrorString)throw new Error(e.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),e?.stop?.length)return{generations:[this._formatGeneration(e.stop[0])]};{const r=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(r)],llmOutput:{}}}}_formatGeneration(t){return{message:new N(t),text:t}}async*_streamResponseChunks(t,e,n){const r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});for await(const s of r){if(await this._sleepIfRequested(),e?.thrownErrorString)throw new Error(e.thrownErrorString);yield this._createResponseChunk(s),n?.handleLLMNewToken(s)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t){return new ts({message:new Vt({content:t}),text:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}withStructuredOutput(t,e){return Bt.from(async n=>{const r=await this.invoke(n);if(r.tool_calls?.[0]?.args)return r.tool_calls[0].args;if(typeof r.content=="string")return JSON.parse(r.content);throw new Error("No structured output found")})}},id=class extends ho{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 i=e.length/this.vectorSize,o=[];for(let l=0;l<e.length;l+=i)o.push(e.slice(l,l+i));return o.map(l=>{let c=0;for(let h=0;h<l.length;h+=1)c+=l===" "?0:l.charCodeAt(h);return c%26/26})}},od=class extends ho{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},ad=class extends no{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}},ld=class extends no{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(i=>setTimeout(i,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},cd=class extends Co{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 oe(t))}async addAIMessage(t){this.messages.push(new N(t))}async clear(){this.messages=[]}},ud=class extends Vs{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},hd=class extends $s{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},dd=class extends ac{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},fd=class extends Bs{lc_namespace=["test","fake"];output=[new De({pageContent:"foo"}),new De({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},pd=class extends ee{lc_namespace=["tests","fake"];returnOptions;constructor(t){super(t),this.returnOptions=t.returnOptions}async invoke(t,e){return this.returnOptions?e??{}:{input:t}}},md=class extends vr{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)}},gd=class extends $s{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}},yd=class ka extends Ws{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??va}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,i)=>({content:n[i].pageContent,embedding:s,metadata:n[i].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,n,r){const s=l=>{if(!r)return!0;const c=new De({metadata:l.metadata,pageContent:l.content});return r(c)},i=this.memoryVectors.filter(s);return i.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 De({metadata:i[l.index].metadata,pageContent:i[l.index].content}),l.similarity])}static async fromTexts(e,n,r,s){const i=[];for(let o=0;o<e.length;o+=1){const a=Array.isArray(n)?n[o]:n,l=new De({pageContent:e[o],metadata:a});i.push(l)}return ka.fromDocuments(i,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)}},Ea={};q(Ea,{FakeChatMessageHistory:()=>cd,FakeChatModel:()=>nd,FakeEmbeddings:()=>od,FakeLLM:()=>ad,FakeListChatMessageHistory:()=>ud,FakeListChatModel:()=>sd,FakeRetriever:()=>fd,FakeRunnable:()=>pd,FakeSplitIntoListParser:()=>dd,FakeStreamingChatModel:()=>rd,FakeStreamingLLM:()=>ld,FakeTool:()=>md,FakeTracer:()=>hd,FakeVectorStore:()=>yd,SingleRunExtractor:()=>gd,SyntheticEmbeddings:()=>id});var xa={};q(xa,{agents:()=>zu,caches:()=>wc,callbacks__base:()=>Hc,callbacks__manager:()=>zc,callbacks__promises:()=>Wc,chat_history:()=>So,document_loaders__base:()=>No,document_loaders__langsmith:()=>Io,documents:()=>Ro,embeddings:()=>fu,example_selectors:()=>Uo,index:()=>Gu,indexing:()=>Ho,language_models__base:()=>yc,language_models__chat_models:()=>gc,language_models__llms:()=>Xl,load__serializable:()=>Bc,memory:()=>To,messages:()=>Vc,messages__tool:()=>Fc,output_parsers:()=>mc,output_parsers__openai_functions:()=>Jo,output_parsers__openai_tools:()=>Yl,outputs:()=>Uc,prompt_values:()=>pc,prompts:()=>aa,retrievers:()=>Mo,retrievers__document_compressors:()=>la,runnables:()=>fc,runnables__graph:()=>Dc,singletons:()=>Lc,stores:()=>Eo,structured_query:()=>ma,tools:()=>ql,tracers__base:()=>jc,tracers__console:()=>Rc,tracers__log_stream:()=>$c,tracers__run_collector:()=>ga,tracers__tracer_langchain:()=>Ic,types__stream:()=>Bh,utils__async_caller:()=>Oc,utils__chunk_array:()=>du,utils__env:()=>Nc,utils__event_source_parse:()=>ya,utils__format:()=>Kh,utils__function_calling:()=>dc,utils__hash:()=>hc,utils__json_patch:()=>uc,utils__json_schema:()=>Pc,utils__math:()=>Sa,utils__stream:()=>Mc,utils__testing:()=>Ea,utils__tiktoken:()=>cc,utils__types:()=>lc,vectorstores:()=>Po});function wd(t){const e={};for(let n=t;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n.prototype,"lc_aliases"));return Object.entries(e).reduce((n,[r,s])=>(n[s]=r,n),{})}async function Bn(t){const{optionalImportsMap:e={},optionalImportEntrypoints:n=[],importMap:r={},secretsMap:s={},path:i=["$"]}=this,o=i.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=Gc(l);if(c)return c;throw new Error(`Missing key "${l}" for ${o} 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: ${o} -> ${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 y=[h.join("/")];h[0]==="langchain_community"&&y.push(["langchain",...h.slice(1)].join("/"));const p=y.find(m=>m in e);if(Wu.concat(n).includes(h.join("/"))||p)if(p!==void 0)f=await e[p];else throw new Error(`Missing key "${h.join("/")}" for ${o} in load(optionalImportsMap={})`);else{let m;if(h[0]==="langchain"||h[0]==="langchain_core")m=d[h[0]],h.shift();else throw new Error(`Invalid namespace: ${o} -> ${l}`);if(h.length===0)throw new Error(`Invalid namespace: ${o} -> ${l}`);let w;do{if(w=h.join("__"),w in m)break;h.pop()}while(h.length>0);w in m&&(f=m[w])}if(typeof f!="object"||f===null)throw new Error(`Invalid namespace: ${o} -> ${l}`);const S=f[c]??Object.values(f).find(m=>typeof m=="function"&&Kc(m)===c);if(typeof S!="function")throw new Error(`Invalid identifer: ${o} -> ${l}`);const C=await Bn.call({...this,path:[...i,"kwargs"]},a.kwargs);if(a.type==="constructor"){const m=new S(Jc(C,qc,wd(S)));return Object.defineProperty(m.constructor,"name",{value:c}),m}else throw new Error(`Invalid type: ${o} -> ${l}`)}else if(typeof t=="object"&&t!==null)return Array.isArray(t)?Promise.all(t.map((a,l)=>Bn.call({...this,path:[...i,`${l}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,l])=>[a,await Bn.call({...this,path:[...i,a]},l)])));return t}async function _d(t,e){const n=JSON.parse(t);return Bn.call({...e},n)}function bd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function ms(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>ms(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await ms(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(bd(e))return _d(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 vd(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 Sd=class{_dumps(t){return new TextEncoder().encode(Vu(t,(n,r)=>vd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return ms(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 Aa(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]=Aa(t[n]));return e}function Ma(){return{v:4,id:vo(-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:Aa(t.versions_seen)}}function Pa(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function Cd(...t){return t.reduce((e,n,r)=>r===0?n:Pa(e,n)>=0?e:n)}const Td={[ju]:-1,[Ln]:-2,[Lu]:-3,[Du]:-4};var tn=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function kd(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 Ed=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:i}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:i}]))[0]}async put(t,e,n,r){kd(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:i=0}=t,o=[];return e&&o.push({matchType:"prefix",path:e}),n&&o.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:s,offset:i}]))[0]}start(){}stop(){}};const xd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var Ad=class extends Ed{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=xd(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:i}=e||{};return this.enqueueOperation({namespacePrefix:t,filter:n,limit:r,offset:s,query:i})}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 i=Array.from(t.keys()).indexOf(s);r(n[i])})}catch(e){t.forEach(({reject:n})=>{n(e)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},Md=class{serde=new Sd;constructor(t){this.serde=t||this.serde}},Pd=class Na extends Tn{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:n="openai",index:r=0,structuredResponse:s,indexRef:i,...o}={}){super(o),this.toolCalls=e,this.toolStyle=n,this.indexRef=i??{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 Na({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 i=e[e.length-1].content;e.length>1&&(i=e.map(h=>h.content).filter(Boolean).join("-")),(e.length===1||e.length===2&&e.every(oe.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 N({content:i,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:i,message:c}],llmOutput:{}}}};class Nd{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 Od(){Le.initializeGlobalInstance(new Nd)}var ht=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
31
31
 
32
32
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${e.lc_error_code}/
33
- `),super(n),this.lc_error_code=e?.lc_error_code}},Na=class extends ht{get is_bubble_up(){return!0}},xd=class extends ht{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Wn=class extends ht{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},St=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"}},Oa=class extends St{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Ia=class extends Na{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function Ad(t){return t!==void 0&&t.name===Ia.unminifiable_name}function Hn(t){return t!==void 0&&t.is_bubble_up===!0}function it(t){return t!==void 0&&[St.unminifiable_name,Oa.unminifiable_name].includes(t.name)}var Ei=class extends ht{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Q=class extends ht{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ht{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Md=class extends ht{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 dt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===Q.unminifiable_name)return!1;throw t}}};const gr=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function ei(t){if(t[gr]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const s=t[n];Ra(s)&&(e[n]=s)}return Object.assign(e,{[gr]:!0}),e}function hs(t,e){const n=ei(t),s={};for(const r in n){if(!Object.prototype.hasOwnProperty.call(n,r))continue;const i=e.channel_values[r];s[r]=n[r].fromCheckpoint(i)}return Object.assign(s,{[gr]:!0}),s}function nt(t,e,n,s){let r;if(e===void 0)r=t.channel_values;else{r={};for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i))try{r[i]=e[i].checkpoint()}catch(o){if(o.name!==Q.unminifiable_name)throw o}}return{v:4,id:s?.id??bo(n),ts:new Date().toISOString(),channel_values:r,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var yr=class $a extends dt{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 $a(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 s of n)this.value!==void 0&&(this.value=this.operator(this.value,s));return!0}get(){if(this.value===void 0)throw new Q;return this.value}checkpoint(){if(this.value===void 0)throw new Q;return this.value}isAvailable(){return this.value!==void 0}},ti=class ja extends dt{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 Q;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Q;return this.value[0]}isAvailable(){return this.value.length!==0}},Pd=class La extends dt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new La;if(typeof e<"u"){const[s,r]=e;n.value=[s],n.finished=r}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 Q;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}},Nd=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const wr=function(t){return t?_r(t):new ti};wr.Root=t=>new Nd(t);function _r(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new yr(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new yr(t.value,t.default):new ti}const L="__start__",M="__end__",Ie="__input__",Od="__copy__",ae="__error__",Us="__pregel_ns_writes",qe="__pregel_send",ni="__pregel_call",at="__pregel_read",z="__pregel_checkpointer",We="__pregel_resuming",cn="__pregel_task_id",ds="__pregel_stream",Id="__pregel_resume_value",zn="__pregel_resume_map",Ye="__pregel_scratchpad",Gn="__pregel_previous",Da="__pregel_durability",br="checkpoint_id",Ee="checkpoint_ns",Rd="__pregel_node_finished",ge="checkpoint_map",xi="__pregel_abort_signals",j="__interrupt__",ce="__resume__",si="__no_writes__",Gt="__return__",Fs="__previous__",G="langsmith:hidden",$d="langsmith:nostream",Ai="__self__",ye="__pregel_tasks",de="__pregel_push",Kn="__pregel_pull",we="00000000-0000-0000-0000-000000000000",jd=[G,Ie,j,ce,ae,si,qe,at,z,Da,ds,We,cn,ni,Id,Ye,Gn,ge,Ee,br],J="|",Ue=":",Mi=Symbol.for("langgraph.command");var Ld=class{[Mi];constructor(t){this[Mi]=t}};function vr(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=_n(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function pe(t){return t instanceof se}function Ua(t){return!t||typeof t!="object"||!(j in t)?!1:Array.isArray(t[j])}var K=class extends Ld{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(t){super(t),this.resume=t.resume,this.graph=t.graph,this.update=t.update,t.goto&&(this.goto=Array.isArray(t.goto)?_n(t.goto):[_n(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:pe(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function Y(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function _n(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((s,r)=>{n[r]=_n(s,e)});else if(Y(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(vr(t)&&!(t instanceof se))n=new se(t.node,t.args),e.set(t,n);else if(Y(t)||pe(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[s,r]of Object.entries(t))n[s]=_n(r,e)}return n}return t}const Dd=["tags","metadata","callbacks","configurable"],Ud=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Fd=25;function Fa(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Fd,configurable:{}},n=Le.getRunnableConfig();if(n!==void 0){for(const[s,r]of Object.entries(n))if(r!==void 0)if(Dd.includes(s)){let i;Array.isArray(r)?i=[...r]:typeof r=="object"?s==="callbacks"&&"copy"in r&&typeof r.copy=="function"?i=r.copy():i={...r}:i=r,e[s]=i}else e[s]=r}for(const s of t)if(s!==void 0)for(const[r,i]of Object.entries(s))i!==void 0&&Ud.includes(r)&&(e[r]=i);for(const[s,r]of Object.entries(e.configurable))e.metadata=e.metadata??{},!s.startsWith("__")&&(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&!(s in e.metadata)&&(e.metadata[s]=r);return e}function Vd(){return Le.getRunnableConfig()}function Vs(t){return t.split(J).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(Ue)[0]).join(J)}function Bd(t){const e=t.split(J);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(J)}const k=t=>BigInt(t),D=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Va=k("0x9E3779B1"),Ba=k("0x85EBCA77"),Wd=k("0xC2B2AE3D"),Qe=k("0x9E3779B185EBCA87"),ct=k("0xC2B2AE3D27D4EB4F"),Wa=k("0x165667B19E3779F9"),ri=k("0x85EBCA77C2B2AE63"),Hd=k("0x27D4EB2F165667C5"),zd=k("0x165667919E3779F9"),Gd=k("0x9FB21C651E98DF25"),Kd=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,s=new Uint8Array(n);let r=0,i=0;for(;i<n;){const o=t.slice(r,r+=2);s[i]=Number.parseInt(o,16),i+=1}return D(s)},ke=Kd("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Ct=(k(1)<<k(128))-k(1),I=(k(1)<<k(64))-k(1),fs=(k(1)<<k(32))-k(1),Re=64,Ha=Re/8,Jd=8,Mn=4;function Kt(t){if(!t)throw new Error("Assert failed")}function qd(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Yd(t){let e=t;return e=(e&k(65535))<<k(16)|(e&k(4294901760))>>k(16),e=(e&k(16711935))<<k(8)|(e&k(4278255360))>>k(8),e}function Xd(t,e){return(t&fs)*(e&fs)&I}function Zd(t,e){return(t<<e|t>>k(32)-e)&fs}function za(t,e,n){for(let s=0;s<Ha;s+=1){const r=e.getBigUint64(s*8,!0),i=r^n.getBigUint64(s*8,!0);t[s^1]+=r,t[s]+=Xd(i,i>>k(32))}return t}function Pi(t,e,n,s){for(let r=0;r<s;r+=1)za(t,D(e,r*Re),D(n,r*8));return t}function Qd(t,e){for(let n=0;n<Ha;n+=1){const s=e.getBigUint64(n*8,!0);let r=t[n];r=Sr(r,k(47)),r^=s,r*=Va,t[n]=r&I}return t}function Pn(t,e){return Ga(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Jd,!0))}function Ni(t,e,n){let s=n;return s+=Pn(t.slice(0),D(e,0*Mn)),s+=Pn(t.slice(2),D(e,4*Mn)),s+=Pn(t.slice(4),D(e,8*Mn)),s+=Pn(t.slice(6),D(e,12*Mn)),Ae(s&I)}function ef(t,e,n,s,r){let i=t;const o=Math.floor((n.byteLength-Re)/8),a=Re*o,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)i=Pi(i,D(e,c*a),n,o),i=r(i,D(n,n.byteLength-Re));{const c=Math.floor((e.byteLength-1-a*l)/Re);i=Pi(i,D(e,l*a),n,c),i=s(i,D(e,e.byteLength-Re),D(n,n.byteLength-Re-7))}return i}function tf(t,e){let n=new BigUint64Array([Wd,Qe,ct,Wa,ri,Ba,Hd,Va]);Kt(t.byteLength>128),n=ef(n,t,e,za,Qd),Kt(n.length*8===64);{const s=Ni(n,D(e,11),k(t.byteLength)*Qe&I);return Ni(n,D(e,e.byteLength-Re-11),~(k(t.byteLength)*ct)&I)<<k(64)|s}}function Ga(t,e){const n=t*e&Ct;return n&I^n>>k(64)}function Oi(t,e,n){return Ga((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&I,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&I)}function Jn(t,e,n,s,r){let i=t&I,o=t>>k(64)&I;return i+=Oi(e,s,r),i^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),i&=I,o+=Oi(n,D(s,16),r),o^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),o&=I,o<<k(64)|i}function Ae(t){let e=t;return e^=e>>k(37),e*=zd,e&=I,e^=e>>k(32),e}function ps(t){let e=t;return e^=e>>k(33),e*=ct,e&=I,e^=e>>k(29),e*=Wa,e&=I,e^=e>>k(32),e}function nf(t,e,n){const s=t.byteLength;Kt(s>0&&s<=3);const r=k(t.getUint8(s-1))|k(s<<8)|k(t.getUint8(0)<<16)|k(t.getUint8(s>>1)<<24),i=(k(e.getUint32(0,!0))^k(e.getUint32(4,!0)))+n,o=(r^i)&I,a=(k(e.getUint32(8,!0))^k(e.getUint32(12,!0)))-n,l=(Zd(Yd(r),k(13))^a)&I;return(ps(l)&I)<<k(64)|ps(o)}function Sr(t,e){return t^t>>e}function sf(t,e,n){const s=t.byteLength;Kt(s>=4&&s<=8);{const r=t.getUint32(0,!0),i=t.getUint32(s-4,!0),o=k(r)|k(i)<<k(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&I;let c=(o^a)*(Qe+(k(s)<<k(2)))&Ct;return c+=(c&I)<<k(65),c&=Ct,c^=c>>k(67),Sr(Sr(c&I,k(35))*Gd&I,k(28))|Ae(c>>k(64))<<k(64)}}function rf(t,e,n){const s=t.byteLength;Kt(s>=9&&s<=16);{const r=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&I,i=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&I,o=t.getBigUint64(0,!0);let a=t.getBigUint64(s-8,!0),l=(o^a^r)*Qe;const c=(l&I)+(k(s-1)<<k(54));l=l&(Ct^I)|c,a^=i,l+=a+(a&fs)*(Ba-k(1))<<k(64),l&=Ct,l^=qd(l>>k(64));let u=(l&I)*ct;return u+=(l>>k(64))*ct<<k(64),u&=Ct,Ae(u&I)|Ae(u>>k(64))<<k(64)}}function of(t,e){const n=t.byteLength;return Kt(n<=16),n>8?rf(t,ke,e):n>=4?sf(t,ke,e):n>0?nf(t,ke,e):ps(e^ke.getBigUint64(64,!0)^ke.getBigUint64(72,!0))|ps(e^ke.getBigUint64(80,!0)^ke.getBigUint64(88,!0))<<k(64)}function Cr(t){return~t+k(1)&I}function af(t,e,n){let s=k(t.byteLength)*Qe&I,r=k(t.byteLength-1)/k(32);for(;r>=0;){const a=Number(r);s=Jn(s,D(t,16*a),D(t,t.byteLength-16*(a+1)),D(e,32*a),n),r-=k(1)}let i=s+(s>>k(64))&I;i=Ae(i);let o=(s&I)*Qe+(s>>k(64))*ri+(k(t.byteLength)-n&I)*ct;return o&=I,o=Cr(Ae(o)),i|o<<k(64)}function lf(t,e,n){let s=k(t.byteLength)*Qe&I;for(let o=32;o<160;o+=32)s=Jn(s,D(t,o-32),D(t,o-16),D(e,o-32),n);s=Ae(s&I)|Ae(s>>k(64))<<k(64);for(let o=160;o<=t.byteLength;o+=32)s=Jn(s,D(t,o-32),D(t,o-16),D(e,3+o-160),n);s=Jn(s,D(t,t.byteLength-16),D(t,t.byteLength-32),D(e,103),Cr(n));let r=s+(s>>k(64))&I;r=Ae(r);let i=(s&I)*Qe+(s>>k(64))*ri+(k(t.byteLength)-n&I)*ct;return i&=I,i=Cr(Ae(i)),r|i<<k(64)}function tt(t,e=k(0)){const n=new TextEncoder,s=D(typeof t=="string"?n.encode(t):t),r=s.byteLength,i=o=>o.toString(16).padStart(32,"0");return r<=16?i(of(s,e)):r<=128?i(af(s,ke,e)):r<=240?i(lf(s,ke,e)):i(tf(s,ke))}function Ka(t){return/^[0-9a-f]{32}$/.test(t)}function Ja(t){const e=Le.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[z])throw new Wn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=n[Ye];r.interruptCounter+=1;const i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[qe]?.([[ce,r.resume]]),r.resume[i];if(r.nullResume!==void 0){if(r.resume.length!==i)throw new Error(`Resume length mismatch: ${r.resume.length} !== ${i}`);const l=r.consumeNullResume();return r.resume.push(l),n[qe]?.([[ce,r.resume]]),l}const o=n[Ee]?.split(J),a=o?tt(o.join(J)):void 0;throw new St([{id:a,value:t}])}var ft=class extends ee{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,s){return new Promise((r,i)=>{const o=ln(n,{callbacks:s?.getChild()});Le.runWithConfig(o,async()=>{try{const a=await this.func(e,o);r(a)}catch(a){i(a)}})})}async invoke(e,n){let s;const r=Fa(n),i=$e(this.config,r);return this.trace?s=await this._callWithConfig(this._tracedInvoke,e,i):s=await Le.runWithConfig(i,async()=>this.func(e,i)),ee.isRunnable(s)&&this.recurse?await Le.runWithConfig(i,async()=>s.invoke(e,i)):s}};function*Ve(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function He(t){const e=[];for await(const n of await t)e.push(n);return e}function rn(t){const e=[];for(const n of t)e.push(n);return e}function pt(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function cf(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const lt={[Symbol.for("LG_PASSTHROUGH")]:!0};function Nn(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Bs=Symbol("IS_WRITER");var re=class Tr extends ft{writes;constructor(e,n){const s=`ChannelWrite<${e.map(r=>pe(r)?r.node:"channel"in r?r.channel:"...").join(",")}>`;super({writes:e,name:s,tags:n,func:async(r,i)=>this._write(r,i??{})}),this.writes=e}async _write(e,n){const s=this.writes.map(r=>Ws(r)&&Nn(r.value)?{mapper:r.mapper,value:e}:qn(r)&&Nn(r.value)?{channel:r.channel,value:e,skipNone:r.skipNone,mapper:r.mapper}:r);return await Tr.doWrite(n,s),e}static async doWrite(e,n){for(const i of n){if(qn(i)){if(i.channel===ye)throw new B("Cannot write to the reserved channel TASKS");if(Nn(i.value))throw new B("PASSTHROUGH value must be replaced")}if(Ws(i)&&Nn(i.value))throw new B("PASSTHROUGH value must be replaced")}const s=[];for(const i of n)if(pe(i))s.push([ye,i]);else if(Ws(i)){const o=await i.mapper.invoke(i.value,e);o!=null&&o.length>0&&s.push(...o)}else if(qn(i)){const o=i.mapper!==void 0?await i.mapper.invoke(i.value,e):i.value;if(cf(o)||i.skipNone&&o===void 0)continue;s.push([i.channel,o])}else throw new Error(`Invalid write entry: ${JSON.stringify(i)}`);const r=e.configurable?.[qe];r(s)}static isWriter(e){return e instanceof Tr||Bs in e&&!!e[Bs]}static registerWriter(e){return Object.defineProperty(e,Bs,{value:!0})}};function qn(t){return t!==void 0&&typeof t.channel=="string"}function Ws(t){return t!==void 0&&!qn(t)&&ee.isRunnable(t.mapper)}var uf=class qa extends ft{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,s=!1){super({func:(r,i)=>qa.doRead(i,this.channel,this.fresh,this.mapper)}),this.fresh=s,this.mapper=n,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,n,s,r){const i=e.configurable?.[at];if(!i)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return r?r(i(n,s)):i(n,s)}};const mt=new gc;var bn=class on extends xe{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=mt;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:s,mapper:r,writers:i,bound:o,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:h,subgraphs:d,ends:f}=e,y=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??mt,config:{...e.config?e.config:{},tags:y}}),this.channels=n,this.triggers=s,this.mapper=r,this.writers=i??this.writers,this.bound=o??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=y,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 re&&e[e.length-2]instanceof re;){const n=e.slice(-2),s=n[0].writes.concat(n[1].writes);e[e.length-2]=new re(s,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===mt&&e.length===0))return this.bound===mt&&e.length===1?e[0]:this.bound===mt?new Ze({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Ze({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 re.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===mt?new on({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Wt(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 hf(t){return"steps"in t&&Array.isArray(t.steps)}function ii(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Ya(t){const e=[t];for(const n of e){if(ii(n))return n;hf(n)&&e.push(...n.steps)}}function Tt(t,e,n=!0,s=!1){try{return t[e].get()}catch(r){if(r.name===Q.unminifiable_name){if(s)return r;if(n)return null}throw r}}function ut(t,e,n=!0){if(Array.isArray(e)){const s={};for(const r of e)try{s[r]=Tt(t,r,!n)}catch(i){if(i.name===Q.unminifiable_name)continue}return s}else return Tt(t,e)}function*df(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 s of n)if(pe(s))yield[we,ye,s];else if(typeof s=="string")yield[we,`branch:to:${s}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof s}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(Ka))for(const[n,s]of Object.entries(t.resume)){const r=e.filter(i=>i[0]===n&&i[1]===ce).map(i=>i[2]).slice(0,1)??[];r.push(s),yield[n,ce,r]}else yield[we,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,s]of t.update)yield[we,n,s];else for(const[n,s]of Object.entries(t.update))yield[we,n,s]}}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*Hs(t,e,n){Array.isArray(t)?(e===!0||e.find(([s,r])=>t.includes(s)))&&(yield ut(n,t)):(e===!0||e.some(([s,r])=>s===t))&&(yield Tt(n,t))}function*ff(t,e,n){const s=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(G))&&l[0][0]!==ae&&l[0][0]!==j);if(!s.length)return;let r;s.some(([a])=>a.writes.some(([l,c])=>l===Gt))?r=s.flatMap(([a])=>a.writes.filter(([l,c])=>l===Gt).map(([l,c])=>[a.name,c])):Array.isArray(t)?r=s.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)))]]}):r=s.flatMap(([a])=>a.writes.filter(([l,c])=>l===t).map(([l,c])=>[a.name,c]));const i={};for(const[a,l]of r)a in i||(i[a]=[]),i[a].push(l);const o={};for(const a in i)if(i[a].length===1){const[l]=i[a];o[a]=l}else o[a]=i[a];n&&(o.__metadata__={cached:n}),yield o}function oi(t){const e=typeof t[L];if(e==="number")return 0;if(e==="string")return"";for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const s=typeof t[n];if(s==="number")return 0;if(s==="string")return"";break}}function Yn(t,e){if(Object.keys(t).length>0){const n=oi(e);return Object.fromEntries(Object.entries(e).filter(([s,r])=>r>(t[s]??n)))}else return e}function pf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function be(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function et(t,e){const n=e?.parents??{};return Object.keys(n).length>0?be(t,{[ge]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function ms(...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,s=()=>{const i=e.find(o=>o.aborted)?.reason;n.abort(i),e.forEach(o=>o.removeEventListener("abort",s))};e.forEach(i=>i.addEventListener("abort",s,{once:!0}));const r=e.find(i=>i.aborted);return r&&n.abort(r.reason),{signal:n.signal,dispose:()=>{e.forEach(i=>i.removeEventListener("abort",s))}}}const mf=(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 gf=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:t,name:e,input:n,retry:s,cache:r,callbacks:i}){this.func=t,this.name=e,this.input=n,this.retry=s,this.cache=r,this.callbacks=i}};function yf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function wf(t,e){const n=new ft({func:s=>e(...s),name:t,trace:!1,recurse:!1});return new Ze({name:t,first:n,last:new re([{channel:Gt,value:lt}],[G])})}const _f=t=>t!==void 0?t+1:1;function bf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function vf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=yd(e,t[n]));return e}function On(t,e,n){const s=oi(t.channel_versions),r=t.versions_seen[j]??{};let i=!1;if((t.channel_versions[L]??s)>(r[L]??s))i=!0;else for(const a in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,a)&&t.channel_versions[a]>(r[a]??s)){i=!0;break}const o=n.some(a=>e==="*"?!a.config?.tags?.includes(G):e.includes(a.name));return i&&o}function Xn(t,e,n,s,r=!1){let i=new Set;if(Array.isArray(s))i=new Set(s.filter(a=>n.writes.some(([l,c])=>l===a)));else{for(const[a]of n.writes)if(a===s){i=new Set([a]);break}i=i||new Set}let o;if(r&&i.size>0){const a=Object.fromEntries(Object.entries(e).filter(([u,h])=>i.has(u))),l=nt(t,a,-1),c=hs(a,l);he(us(l),c,[n],void 0,void 0),o=ut({...e,...c},s)}else o=ut(e,s);return o}function zs(t,e,n){for(const[s,r]of n)if([de,ye].includes(s)&&r!=null){if(!pe(r))throw new B(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in e))throw new B(`Invalid node name "${r.node}" in Send packet`)}t(n)}const Sf=new Set([si,de,ce,j,Gt,ae]);function he(t,e,n,s,r){n.sort((d,f)=>{const y=d.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let S=0;S<Math.min(y.length,p.length);S+=1){if(y[S]<p[S])return-1;if(y[S]>p[S])return 1}return y.length-p.length});const i=n.some(d=>d.triggers.length>0),o=ei(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=vf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!jd.includes(d)));let c=!1;for(const d of l)d in o&&o[d].consume()&&s!==void 0&&(t.channel_versions[d]=s(a),c=!0);const u={};for(const d of n)for(const[f,y]of d.writes)Sf.has(f)||f in o&&(u[f]??=[],u[f].push(y));a!=null&&s!=null&&(a=c?s(a):a);const h=new Set;for(const[d,f]of Object.entries(u))if(d in o){const y=o[d];let p;try{p=y.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&&s!==void 0&&(t.channel_versions[d]=s(a),y.isAvailable()&&h.add(d))}if(i)for(const d in o){if(!Object.prototype.hasOwnProperty.call(o,d))continue;const f=o[d];f.isAvailable()&&!h.has(d)&&f.update([])&&s!==void 0&&(t.channel_versions[d]=s(a),f.isAvailable()&&h.add(d))}if(i&&!bf(h,r))for(const d in o){if(!Object.prototype.hasOwnProperty.call(o,d))continue;const f=o[d];f.finish()&&s!==void 0&&(t.channel_versions[d]=s(a),f.isAvailable()&&h.add(d))}return h}function*Cf(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const r=new Set;for(const i of n.updatedChannels){const o=n.triggerToNodes[i];for(const a of o??[])r.add(a)}yield*[...r].sort();return}if(!(()=>{for(const r in t.channel_versions)if(t.channel_versions[r]!==null)return!1;return!0})())for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(yield r)}function bt(t,e,n,s,r,i,o){const a={},l=s[ye];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const h=kr([de,u],t,e,n,s,r,i,o);h!==void 0&&(a[h.id]=h)}}for(const c of Cf(t,n,o)){const u=kr([Kn,c],t,e,n,s,r,i,o);u!==void 0&&(a[u.id]=u)}return a}function kr(t,e,n,s,r,i,o,a){const{step:l,checkpointer:c,manager:u}=a,h=i.configurable??{},d=h.checkpoint_ns??"";if(t[0]===de&&yf(t[t.length-1])){const f=t[t.length-1],y=wf(f.name,f.func),p=[de],S=d===""?f.name:`${d}${J}${f.name}`,C=yt(JSON.stringify([S,l.toString(),f.name,de,t[1],t[2]]),e.id),m=`${S}${Ue}${C}`,w=[...t.slice(0,3),!0],b={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:w,langgraph_checkpoint_ns:m};if(o){const T=[];return{name:f.name,input:f.input,proc:y,writes:T,config:ln($e(i,{metadata:b,store:a.store??i.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:C,[qe]:_=>zs(v=>T.push(...v),s,_),[at]:(_,v=!1)=>Xn(e,r,{name:f.name,writes:T,triggers:p,path:w},_,v),[z]:c??h[z],[ge]:{...h[ge],[d]:e.id},[Ye]:Gs({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:i.configurable?.[zn],namespaceHash:tt(m)}),[Gn]:e.channel_values[Fs],checkpoint_id:void 0,checkpoint_ns:m}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:tt((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Us,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:C,path:w,writers:[]}}else return{id:C,name:f.name,interrupts:[],path:w}}else if(t[0]===de){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!r[ye]?.isAvailable())return;const y=r[ye].get();if(f<0||f>=y.length)return;const p=vr(y[f])&&!pe(y[f])?new se(y[f].node,y[f].args):y[f];if(!vr(p)){console.warn(`Ignoring invalid packet ${JSON.stringify(p)} in pending sends.`);return}if(!(p.node in s)){console.warn(`Ignoring unknown node name ${p.node} in pending sends.`);return}const S=[de],C=d===""?p.node:`${d}${J}${p.node}`,m=yt(JSON.stringify([C,l.toString(),p.node,de,f.toString()]),e.id),w=`${C}${Ue}${m}`;let b={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:S,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:w};if(o){const T=s[p.node],x=T.getNode();if(x!==void 0){T.metadata!==void 0&&(b={...b,...T.metadata});const _=[];return{name:p.node,input:p.args,proc:x,subgraphs:T.subgraphs,writes:_,config:ln($e(i,{metadata:b,tags:T.tags,store:a.store??i.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:m,[qe]:v=>zs(A=>_.push(...A),s,v),[at]:(v,A=!1)=>Xn(e,r,{name:p.node,writes:_,triggers:S,path:t},v,A),[z]:c??h[z],[ge]:{...h[ge],[d]:e.id},[Ye]:Gs({pendingWrites:n??[],taskId:m,currentTaskInput:p.args,resumeMap:i.configurable?.[zn],namespaceHash:tt(w)}),[Gn]:e.channel_values[Fs],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:S,retry_policy:T.retryPolicy,cache_key:T.cachePolicy?{key:tt((T.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[Us,T.name??"__dynamic__",p.node],ttl:T.cachePolicy.ttl}:void 0,id:m,path:t,writers:T.getWriters()}}}else return{id:m,name:p.node,interrupts:[],path:t}}else if(t[0]===Kn){const f=t[1].toString(),y=s[f];if(y===void 0)return;if(n?.length){const m=d===""?f:`${d}${J}${f}`,w=yt(JSON.stringify([m,l.toString(),f,Kn,f]),e.id);if(n.some(T=>T[0]===w&&T[1]!==ae))return}const p=oi(e.channel_versions);if(p===void 0)return;const S=e.versions_seen[f]??{},C=y.triggers.find(m=>r[m].isAvailable()?(e.channel_versions[m]??p)>(S[m]??p):!1);if(C!==void 0){const m=Tf(y,r,o);if(m===void 0)return;const w=d===""?f:`${d}${J}${f}`,b=yt(JSON.stringify([w,l.toString(),f,Kn,[C]]),e.id),T=`${w}${Ue}${b}`;let x={langgraph_step:l,langgraph_node:f,langgraph_triggers:[C],langgraph_path:t,langgraph_checkpoint_ns:T};if(o){const _=y.getNode();if(_!==void 0){y.metadata!==void 0&&(x={...x,...y.metadata});const v=[];return{name:f,input:m,proc:_,subgraphs:y.subgraphs,writes:v,config:ln($e(i,{metadata:x,tags:y.tags,store:a.store??i.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:b,[qe]:A=>zs(E=>{v.push(...E)},s,A),[at]:(A,E=!1)=>Xn(e,r,{name:f,writes:v,triggers:[C],path:t},A,E),[z]:c??h[z],[ge]:{...h[ge],[d]:e.id},[Ye]:Gs({pendingWrites:n??[],taskId:b,currentTaskInput:m,resumeMap:i.configurable?.[zn],namespaceHash:tt(T)}),[Gn]:e.channel_values[Fs],checkpoint_id:void 0,checkpoint_ns:T}}),triggers:[C],retry_policy:y.retryPolicy,cache_key:y.cachePolicy?{key:tt((y.cachePolicy.keyFunc??JSON.stringify)([m])),ns:[Us,y.name??"__dynamic__",f],ttl:y.cachePolicy.ttl}:void 0,id:b,path:t,writers:y.getWriters()}}}else return{id:b,name:f,interrupts:[],path:t}}}}function Tf(t,e,n){let s;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){s={};for(const[r,i]of Object.entries(t.channels))if(t.triggers.includes(i))try{s[r]=Tt(e,i,!1)}catch(o){if(o.name===Q.unminifiable_name)return;throw o}else if(i in e)try{s[r]=Tt(e,i,!1)}catch(o){if(o.name===Q.unminifiable_name)continue;throw o}}else if(Array.isArray(t.channels)){let r=!1;for(const i of t.channels)try{s=Tt(e,i,!1),r=!0;break}catch(o){if(o.name===Q.unminifiable_name)continue;throw o}if(!r)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(s=t.mapper(s)),s}function Gs({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:s,namespaceHash:r}){const i=t.find(([l,c])=>l===we&&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(s!=null&&r in s){const c=s[r];l.push(c)}return l})(),nullResume:i,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,t.splice(t.findIndex(([l,c])=>l===we&&c===ce),1),i}};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"}},Sn=(t,e)=>`${t.start}${e}${t.end}`;function*Ii(t){for(const{id:e,name:n,input:s,config:r,triggers:i,writes:o}of t){if(r?.tags?.includes(G))continue;const a=o.filter(([l,c])=>l===e&&c===j).map(([,l])=>l);yield{id:e,name:n,input:s,triggers:i,interrupts:a}}}function kf(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Za(t){const e={};for(const[n,s]of t){const r=String(n);if(r in e){const i=kf(e[r])?e[r].$writes:[e[r]];i.push(s),e[r]={$writes:i}}else e[r]=s}return e}function*Ef(t,e){for(const[{id:n,name:s,config:r},i]of t)r?.tags?.includes(G)||(yield{id:n,name:s,result:Za(i.filter(([o])=>Array.isArray(e)?e.includes(o):o===e)),interrupts:i.filter(o=>o[0]===j).map(o=>o[1])})}function*xf(t,e,n,s,r,i,o,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 r){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:ut(e,n),metadata:s,next:r.map(h=>h.name),tasks:Qa(r,i,u,a),parentConfig:o?l(o):void 0}}function Qa(t,e,n,s){return t.map(r=>{const i=e.find(([c,u])=>c===r.id&&u===ae)?.[2],o=e.filter(([c,u])=>c===r.id&&u===j).map(([,,c])=>c),a=(()=>{if(i||o.length||!e.length)return;const c=e.findIndex(([u,h])=>u===r.id&&h===Gt);if(c>=0)return e[c][2];if(typeof s=="string")return e.find(([u,h])=>u===r.id&&h===s)?.[2];if(Array.isArray(s)){const u=e.filter(([h,d])=>h===r.id&&s.includes(d)).map(([,h,d])=>[h,d]);return u.length?Za(u):void 0}})();if(i)return{id:r.id,name:r.name,path:r.path,error:i,interrupts:o,result:a};const l=n?.[r.id];return{id:r.id,name:r.name,path:r.path,interrupts:o,...l!==void 0?{state:l}:{},result:a}})}function Af(t,e,n){console.log([`${Sn(vn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
34
- `,JSON.stringify(ut(e,n),null,2)].join(""))}function el(t,e){const n=e.length;console.log([`${Sn(vn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
35
- `,e.map(s=>`- ${Sn(vn.green,String(s.name))} -> ${JSON.stringify(s.input,null,2)}`).join(`
36
- `)].join(""))}function Mf(t,e,n){const s={};for(const[r,i]of e)n.includes(r)&&(s[r]||(s[r]=[]),s[r].push(i));console.log([`${Sn(vn.blue,`[${t}:writes]`)}`,`\x1B[1m Finished step ${t} with writes to ${Object.keys(s).length} channel${Object.keys(s).length!==1?"s":""}:\x1B[0m
37
- `,Object.entries(s).map(([r,i])=>`- ${Sn(vn.yellow,r)} -> ${i.map(o=>JSON.stringify(o)).join(", ")}`).join(`
38
- `)].join(""))}var Ri=class extends fn{_abortController;_innerReader;constructor(t,e){const n=t.getReader(),s=e??new AbortController;super({start(r){return i();function i(){return n.read().then(({done:o,value:a})=>{if(o){r.close();return}return r.enqueue(a),i()})}}}),this._abortController=s,this._innerReader=n}async cancel(t){this._abortController.abort(t),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},tl=class extends fn{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(t){let e;const n=new Promise(s=>{e=s});super({start:s=>{e(s)}}),n.then(s=>{this.controller=s}),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 Pf(t){return JSON.stringify(t,function(e,n){const s=this[e];if(s!=null&&typeof s=="object"&&"toDict"in s&&typeof s.toDict=="function"){const{type:r,data:i}=s.toDict();return{...i,type:r}}return n})}function Nf(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function ai(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Ks(t){return!ai(t)||!t.configurable.thread_id?null:{thread_id:t.configurable.thread_id,checkpoint_ns:t.configurable.checkpoint_ns||"",checkpoint_id:t.configurable.checkpoint_id||null,checkpoint_map:t.configurable.checkpoint_map||null}}function $i(t){if(ai(t)){const e=Object.fromEntries(Object.entries(t.configurable).filter(([s])=>!s.startsWith("__"))),n={...t,configurable:e};return delete n.callbacks,n}return t}function ji(t){const e={...t,checkpoint:Ks(t.config),parent_checkpoint:Ks(t.parentConfig),config:$i(t.config),parent_config:$i(t.parentConfig),tasks:t.tasks.map(n=>{if(ai(n.state)){const s=Ks(n.state);if(s!=null){const r={...n,checkpoint:s};return delete r.state,r}}return n})};return delete e.parentConfig,e}function Of(t){const e=new TextEncoder;return new ReadableStream({async start(n){const s=r=>{n.enqueue(e.encode(`event: ${r.event}
39
- data: ${Pf(r.data)}
40
-
41
- `))};try{for await(const r of t){const[i,o,a]=r;let l=a;if(o==="debug"){const u=a;u.type==="checkpoint"&&(l={...u,payload:ji(u.payload)})}o==="checkpoints"&&(l=ji(a));const c=i?.length?`${o}|${i.join("|")}`:o;s({event:c,data:l})}}catch(r){s({event:"error",data:Nf(r)})}n.close()}})}const In=Symbol.for("INPUT_DONE"),Js=Symbol.for("INPUT_RESUMING"),If=25;function Rf(...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 $f=class extends Cd{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}},jf=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(L 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 s=this.config.configurable?.[We]!==void 0&&this.config.configurable?.[We],r=this.input===null||this.input===void 0,i=Y(this.input)&&this.input.resume!=null,o=this.input===Js,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&&(s||r||i||o||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 $f(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:s}=e;s!==void 0&&n.configurable?.[ds]!==void 0&&(s=Rf(s,n.configurable[ds]));const r=n.configurable?!("checkpoint_id"in n.configurable):!0,i=n.configurable?.[Ye];n.configurable&&i&&(i.subgraphCounter>0&&(n=be(n,{[Ee]:[n.configurable[Ee],i.subgraphCounter.toString()].join(J)})),i.subgraphCounter+=1);const o=at in(n.configurable??{});!o&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=be(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ge]!==void 0&&n.configurable?.[ge]?.[n.configurable?.checkpoint_ns]&&(a=be(n,{checkpoint_id:n.configurable[ge][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(J)??[],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=us(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],y=hs(e.channelSpecs,h),p=(d.step??0)+1,S=p+(n.recursionLimit??If)+1,C={...h.channel_versions},m=e.store?new Sd(e.store):void 0;return m&&await m.start(),new nl({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:y,isNested:o,manager:e.manager,skipDoneTasks:r,step:p,stop:S,checkpointPreviousVersions:C,checkpointPendingWrites:f,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:s,store:m,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 s=n;if(s.length===0)return;s.every(([o])=>o in wd)&&(s=Array.from(new Map(s.map(o=>[o[0],o])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(o=>o[0]!==e);for(const[o,a]of s)this.checkpointPendingWrites.push([e,o,a]);const r=be(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??"",[br]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(r,s,e)),this.tasks&&this._outputWrites(e,s),!n.length||!this.cache||!this.tasks)return;const i=this.tasks[e];i==null||i.cache_key==null||n[0][0]===ae||n[0][0]===j||this.cache.set([{key:[i.cache_key.ns,i.cache_key.key],value:i.writes,ttl:i.cache_key.ttl}])}_outputWrites(e,n,s=!1){const r=this.tasks[e];if(r!==void 0){if(r.config!==void 0&&(r.config.tags??[]).includes(G))return;if(n.length>0)if(n[0][0]===j){if(r.path?.[0]===de&&r.path?.at(-1)===!0)return;const i=n.filter(o=>o[0]===j).flatMap(o=>o[1]);this._emit([["updates",{[j]:i}],["values",{[j]:i}]])}else n[0][0]!==ae&&this._emit(rn(Ve(ff(this.outputKeys,[[r,n]],s),"updates")));s||this._emit(rn(Ve(Ef([[r,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([o,a])=>`ns:${o.join(",")}|key:${a}`,s=[],r={};for(const o of Object.values(this.tasks))o.cache_key!=null&&!o.writes.length&&(s.push([o.cache_key.ns,o.cache_key.key]),r[n([o.cache_key.ns,o.cache_key.key])]=o);if(s.length===0)return[];const i=await this.cache.get(s);for(const{key:o,value:a}of i){const l=r[n(o)];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,Js].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new St;if(Object.values(this.tasks).every(i=>i.writes.length>0)){const i=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const o=await He(Ve(Hs(this.outputKeys,i,this.channels),"values"));if(this._emit(o),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),On(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new St;this.config.configurable?.[We]!==void 0&&delete this.config.configurable?.[We]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const s=bt(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=s,this.checkpointer&&this._emit(await He(Ve(xf(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[i,o,a]of this.checkpointPendingWrites){if(o===ae||o===j||o===ce)continue;const l=Object.values(this.tasks).find(c=>c.id===i);l&&l.writes.push([o,a])}for(const i of Object.values(this.tasks))i.writes.length>0&&this._outputWrites(i.id,i.writes,!0)}if(Object.values(this.tasks).every(i=>i.writes.length>0))return this.tick({inputKeys:n});if(On(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new St;const r=await He(Ve(Ii(Object.values(this.tasks)),"tasks"));return this._emit(r),!0}async finishAndHandleError(e){this.durability==="exit"&&(!this.isNested||typeof e<"u"||this.checkpointNamespace.every(s=>!s.includes(Ue)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=ut(this.channels,this.outputKeys)),n&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(s=>s.writes.length>0)&&(this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(rn(Ve(Hs(this.outputKeys,Object.values(this.tasks).flatMap(s=>s.writes),this.channels),"values")))),it(e)&&!e.interrupts.length&&this._emit([["updates",{[j]:[]}],["values",{[j]:[]}]])),n}async acceptPush(e,n,s){if(this.interruptAfter?.length>0&&On(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const r=kr([de,e.path??[],n,e.id,s],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(!r)return;if(this.interruptBefore?.length>0&&On(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}this._emit(rn(Ve(Ii([r]),"tasks"))),this.debug&&el(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r});const i=await this._matchCachedWrites();for(const{task:o}of i)this._outputWrites(o.id,o.writes,!0);return r}_suppressInterrupt(e){return it(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,s=n?.[Ye];if(s&&s.nullResume!==void 0&&this.putWrites(we,[[ce,s.nullResume]]),Y(this.input)){const o=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[zn]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of df(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new Ei("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const r=(this.checkpointPendingWrites??[]).filter(o=>o[0]===we).map(o=>o.slice(1));r.length>0&&he(this.checkpoint,this.channels,[{name:Ie,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const i=Y(this.input)&&r.length>0;if(this.isResuming||i){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[j]={...this.checkpoint.versions_seen[j],[a]:l}}const o=await He(Ve(Hs(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=Js;else if(i)await this._putCheckpoint({source:"input"}),this.input=In;else{const o=await He(Xa(e,this.input));if(o.length>0){const a=bt(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:Ie,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=In}else if(We in(this.config.configurable??{}))this.input=In;else throw new Ei(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=be(this.config,{[We]:this.isResuming}))}_emit(e){for(const[n,s]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,s]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const r=n==="checkpoints"?this.step-1:this.step,i=new Date().toISOString(),o=n==="checkpoints"?"checkpoint":typeof s=="object"&&s!=null&&"result"in s?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:r,type:o,timestamp:i,payload:s}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,s=this.checkpointer!=null&&(this.durability!=="exit"||n),r=i=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=be(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??""});const o={...this.checkpoint.channel_versions},a=Yn(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:us(i),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?.[ge]??{}}),this.checkpoint=nt(this.checkpoint,s?this.channels:void 0,this.step,n?{id:this.checkpoint.id}:void 0),s&&r(this.checkpoint),n||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;const e=be(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??"",[br]:this.checkpoint.id}),n={};for(const[s,r,i]of this.checkpointPendingWrites)n[s]??=[],n[s].push([r,i]);for(const[s,r]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,r,s))}_matchWrites(e){for(const[n,s,r]of this.checkpointPendingWrites){if(s===ae||s===j||s===ce)continue;const i=Object.values(e).find(o=>o.id===n);i&&i.writes.push([s,r])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function Lf(t){return Oe(t?.message)}var Df=class extends Kc{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(t){super(),this.streamFn=t}_emit(t,e,n,s=!1){if(s&&e.id!==void 0&&this.seen[e.id]!==void 0)return;let r=e.id;n!=null&&(Jc(e)?r??=`run-${n}-tool-${e.tool_call_id}`:((r==null||r===`run-${n}`)&&(r=this.stableMessageIdMap[n]??r??`run-${n}`),this.stableMessageIdMap[n]??=r)),r!==e.id&&(e.id=r,e.lc_kwargs.id=r),e.id!=null&&(this.seen[e.id]=e),this.streamFn([t[0],"messages",[e,t[1]]])}handleChatModelStart(t,e,n,s,r,i,o,a){o&&(!i||!i.includes($d)&&!i.includes("nostream"))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:i,name:a,...o}])}handleLLMNewToken(t,e,n,s,r,i){const o=i?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(Lf(o)?this._emit(this.metadatas[n],o.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];Oe(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,s,r,i,o,a){if(i!==void 0&&a===i.langgraph_node&&(r===void 0||!r.includes(G))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:r,name:a,...i}],typeof e=="object")){for(const l of Object.values(e))if((Oe(l)||pi(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(Oe(c)||pi(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(Oe(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const s of t)Oe(s)&&this._emit(n,s,e,!0);else if(t!=null&&typeof t=="object"){for(const s of Object.values(t))if(Oe(s))this._emit(n,s,e,!0);else if(Array.isArray(s))for(const r of s)Oe(r)&&this._emit(n,r,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const Uf=500,Ff=2,Vf=128e3,Bf=3,Wf=[400,401,402,403,404,405,406,407,409],Hf=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&&Wf.includes(+e)||t?.error?.code==="insufficient_quota")};async function sl(t,e,n,s){const r=t.retry_policy??e;let i=r!==void 0?r.initialInterval??Uf:0,o=0,a,l,{config:c}=t;for(n&&(c=be(c,n)),c={...c,signal:s};!s?.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,Ad(a)){const y=c?.configurable?.checkpoint_ns,p=a.command;if(p.graph===y){for(const S of t.writers)await S.invoke(p,c);a=void 0;break}else if(p.graph===K.PARENT){const S=Bd(y);a.command=new K({...a.command,graph:S})}}if(Hn(a)||r===void 0||(o+=1,o>=(r.maxAttempts??Bf))||!(r.retryOn??Hf)(a))break;i=Math.min(r.maxInterval??Vf,i*(r.backoffFactor??Ff));const d=r.jitter?Math.floor(i+Math.random()*1e3):i;await new Promise(y=>setTimeout(y,d));const f=a.name??a.constructor.unminifiable_name??a.constructor.name;(r?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${i.toFixed(2)}ms (attempt ${o}) after ${f}: ${a}`),c=be(c,{[We]:!0})}}return{task:t,result:l,error:a,signalAborted:s?.aborted}}const Er=Symbol.for("promiseAdded");function zf(){const t={next:()=>{},wait:Promise.resolve(Er)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Er)}}return t.wait=new Promise(e),t}var Gf=class{nodeFinished;loop;constructor({loop:t,nodeFinished:e}){this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:s,maxConcurrency:r}=t,i=new Set;let o;const a=new AbortController,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(y=>y.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:r});for await(const{task:y,error:p,signalAborted:S}of f)this._commit(y,p),it(p)||Hn(p)&&!it(o)?o=p:p&&(i.size===0||!S)&&(a.abort(),i.add(p));if(d?.(),s?.(this.loop.step,Object.values(this.loop.tasks).map(y=>y.writes).flat()),i.size===1)throw Array.from(i)[0];if(i.size>1)throw new AggregateError(Array.from(i),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(it(o)||Hn(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const s=this.loop.config.configurable?.[xi]??{},r=s.externalAbortSignal??n,i=e??s.timeoutAbortSignal,{signal:o,dispose:a}=ms(r,i,t),l={externalAbortSignal:r,timeoutAbortSignal:i,composedAbortSignal:o};return this.loop.config=be(this.loop.config,{[xi]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:s,signals:r}=e??{},i=zf(),o={},a={executingTasksMap:o,barrier:i,retryPolicy:n,scheduleTask:async(d,f,y)=>this.loop.acceptPush(d,f,y)};if(r?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=ms(r?.externalAbortSignal,r?.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(o).length>0)&&t.length;){for(;Object.values(o).length<(s??t.length)&&l<t.length;l+=1){const f=t[l];o[f.id]=sl(f,n,{[ni]:rl?.bind(a,this,f)},r?.composedAbortSignal).catch(y=>({task:f,error:y,signalAborted:r?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(o),...h?[h]:[],i.wait]);d!==Er&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete o[d.task.id])}}_commit(t,e){if(e!==void 0)if(it(e)){if(e.interrupts.length){const n=e.interrupts.map(r=>[j,r]),s=t.writes.filter(r=>r[0]===ce);s.length&&n.push(...s),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([si,null]),this.loop.putWrites(t.id,t.writes)}};async function rl(t,e,n,s,r,i={}){const o=e.config?.configurable?.[Ye];if(!o)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=o.callCounter;o.callCounter+=1;const l=new gf({func:n,name:s,input:r,cache:i.cache,retry:i.retry,callbacks:i.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],y=f instanceof Error?f:new Error(String(f));return Promise.reject(y)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=sl(c,i.retry,{[ni]:rl.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 Pe=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function Kf({nodes:t,channels:e,inputChannels:n,outputChannels:s,streamChannels:r,interruptAfterNodes:i,interruptBeforeNodes:o}){if(!e)throw new Pe("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===j)throw new Pe(`"Node name ${j} is reserved"`);if(u.constructor===bn)u.triggers.forEach(h=>a.add(h));else throw new Pe(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Pe(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Pe(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Pe(`Input channel ${String(n)} is not subscribed to by any node`);Array.isArray(s)?s.forEach(c=>l.add(c)):l.add(s),r&&!Array.isArray(r)?l.add(r):Array.isArray(r)&&r.forEach(c=>l.add(c));for(const c of l)if(!(c in e))throw new Pe(`Output channel '${String(c)}' not in channels`);if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Pe(`Node ${String(c)} not in nodes`)}if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Pe(`Node ${String(c)} not in nodes`)}}function Li(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 Jf=class il extends dt{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 s=e.flat();if(s.length>0)if(this.unique)for(const r of s)this.seen.has(r)||(n=!0,this.seen.add(r),this.values.push(r));else n=!0,this.values.push(...s);return n}get(){if(this.values.length===0)throw new Q;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},qf=class{static subscribeTo(t,e){const{key:n,tags:s}={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 r;typeof t=="string"?n?r={[n]:t}:r=[t]:r=Object.fromEntries(t.map(o=>[o,o]));const i=Array.isArray(t)?t:[t];return new bn({channels:r,triggers:i,tags:s})}static writeTo(t,e){const n=[];for(const s of t)n.push({channel:s,value:lt,skipNone:!1});for(const[s,r]of Object.entries(e??{}))ee.isRunnable(r)||typeof r=="function"?n.push({channel:s,value:lt,skipNone:!0,mapper:Wt(r)}):n.push({channel:s,value:r,skipNone:!1});return new re(n)}},Yf=class extends ee{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)}},Xf=class extends Yf{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,ye in this.channels&&"lc_graph_name"in this.channels[ye]&&this.channels[ye].lc_graph_name!=="Topic")throw new Error(`Channel '${ye}' is reserved and cannot be used in the graph.`);this.channels[ye]=new Jf({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=$e(this.config,t);return new this.constructor({...this,config:e})}validate(){Kf({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,s]of Object.entries(this.nodes)){if(t!==void 0&&!t.startsWith(n))continue;const r=s.subgraphs?.length?s.subgraphs:[s.bound];for(const i of r){const o=Ya(i);if(o!==void 0){if(n===t){yield[n,o];return}if(t===void 0&&(yield[n,o]),e){let a=t;t!==void 0&&(a=t.slice(n.length+1));for(const[l,c]of o.getSubgraphs(a,e))yield[`${n}${J}${l}`,c]}}}}}async*getSubgraphsAsync(t,e){yield*this.getSubgraphs(t,e)}async _prepareStateSnapshot({config:t,saved:e,subgraphCheckpointer:n,applyPendingWrites:s=!1}){if(e===void 0)return{values:{},next:[],config:t,tasks:[]};const r=hs(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===we).map(([d,f,y])=>[String(f),y]);h.length>0&&he(e.checkpoint,r,[{name:Ie,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const i=Object.values(bt(e.checkpoint,e.pendingWrites,this.nodes,r,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),o=await He(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of i){const d=o.find(([y])=>y===h.name);if(!d)continue;let f=`${String(h.name)}${Ue}${h.id}`;if(a&&(f=`${a}${J}${f}`),n===void 0){const y={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=y}else{const y={configurable:{[z]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=d[1];l[h.id]=await p.getState(y,{subgraphs:!0})}}if(s&&e.pendingWrites?.length){const h=Object.fromEntries(i.map(f=>[f.id,f]));for(const[f,y,p]of e.pendingWrites)[ae,j,Ln].includes(y)||f in h&&h[f].writes.push([String(y),p]);const d=i.filter(f=>f.writes.length>0);d.length>0&&he(e.checkpoint,r,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=i.filter(h=>h.writes.length===0).map(h=>h.name);return{values:ut(r,this.streamChannelsAsIs),next:u,tasks:Qa(i,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:et(e.config,e.metadata),createdAt:e.checkpoint.ts,parentConfig:e.parentConfig}}async getState(t,e){const n=t.configurable?.[z]??this.checkpointer;if(!n)throw new Wn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=t.configurable?.checkpoint_ns??"";if(s!==""&&t.configurable?.[z]===void 0){const a=Vs(s);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(pt(t,{[z]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const r=$e(this.config,t),i=await n.getTuple(t);return await this._prepareStateSnapshot({config:r,saved:i,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[z]??this.checkpointer;if(!n)throw new Wn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=t.configurable?.checkpoint_ns??"";if(s!==""&&t.configurable?.[z]===void 0){const i=Vs(s);for await(const[o,a]of this.getSubgraphsAsync(i,!0))if(o===i){yield*a.getStateHistory(pt(t,{[z]:n}),e);return}throw new Error(`Subgraph with namespace "${i}" not found.`)}const r=$e(this.config,t,{configurable:{checkpoint_ns:s}});for await(const i of n.list(r,e))yield this._prepareStateSnapshot({config:i.config,saved:i})}async bulkUpdateState(t,e){const n=t.configurable?.[z]??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(o=>o.updates.length===0))throw new Error("No updates provided");const s=t.configurable?.checkpoint_ns??"";if(s!==""&&t.configurable?.[z]===void 0){const o=Vs(s);for await(const[,a]of this.getSubgraphsAsync(o,!0))return await a.bulkUpdateState(pt(t,{[z]:n}),e);throw new Error(`Subgraph "${o}" not found`)}const r=async(o,a)=>{const l=this.config?$e(this.config,o):o,c=await n.getTuple(l),u=c!==void 0?us(c.checkpoint):Aa(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=pt(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),y=l.metadata??{};c?.config.configurable&&(f=pt(l,c.config.configurable),y={...c.metadata,...y});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 _=await n.put(f,nt(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return et(_,c?c.metadata:void 0)}const C=hs(this.channels,u);if(p===null&&S===M){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const v=bt(u,c.pendingWrites||[],this.nodes,C,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),A=(c.pendingWrites||[]).filter(E=>E[0]===we).map(E=>E.slice(1));A.length>0&&he(u,C,[{name:Ie,writes:A,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[E,P,R]of c.pendingWrites||[])[ae,j,Ln].includes(P)||E in v&&v[E].writes.push([P,R]);he(u,C,Object.values(v),n.getNextVersion.bind(n),this.triggerToNodes)}const _=await n.put(f,nt(u,C,d),{...y,source:"update",step:d+1,parents:c?.metadata?.parents??{}},Yn(h,u.channel_versions));return et(_,c?c.metadata:void 0)}if(S===Od){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 _=E=>!Array.isArray(E)||E.length===0?!1:E.every(P=>Array.isArray(P)&&P.length===2),v=nt(u,void 0,d),A=await n.put(c.parentConfig??pt(c.config,{checkpoint_id:void 0}),v,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(_(p)){const E=bt(v,c.pendingWrites,this.nodes,C,A,!1,{step:d+2}),P=Object.values(E).reduce((V,{name:X,id:As})=>(V[X]??=[],V[X].push({id:As}),V),{}),R=p.reduce((V,X)=>{const[As,en]=X;V[en]??=[];const $l=V[en].length,jl=P[en]?.[$l]?.id;return V[en].push({values:As,asNode:en,taskId:jl}),V},{});return r(et(A,c.metadata),Object.values(R).flat())}return et(A,c.metadata)}if(S===Ie){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const _=await He(Xa(this.inputChannels,p));if(_.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);he(u,C,[{name:Ie,writes:_,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const v=c?.metadata?.step!=null?c.metadata.step+1:-1,A=await n.put(f,nt(u,C,v),{source:"input",step:v,parents:c?.metadata?.parents??{}},Yn(h,u.channel_versions));return await n.putWrites(A,_,yt(Ie,u.id)),et(A,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const _=bt(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(E=>E[0]===we).map(E=>E.slice(1));v.length>0&&he(c.checkpoint,C,[{name:Ie,writes:v,triggers:[]}],void 0,this.triggerToNodes);for(const[E,P,R]of c.pendingWrites)[ae,j,Ln].includes(P)||_[E]===void 0||_[E].writes.push([P,R]);const A=Object.values(_).filter(E=>E.writes.length>0);A.length>0&&he(u,C,A,void 0,this.triggerToNodes)}const m=Object.values(u.versions_seen).map(_=>Object.values(_)).flat().find(_=>!!_),w=[];if(a.length===1){let{values:_,asNode:v,taskId:A}=a[0];if(v===void 0&&Object.keys(this.nodes).length===1)[v]=Object.keys(this.nodes);else if(v===void 0&&m===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(v=this.inputChannels);else if(v===void 0){const E=Object.entries(u.versions_seen).map(([P,R])=>Object.values(R).map(V=>[V,P])).flat().filter(([P,R])=>R!==j).sort(([P],[R])=>Ma(P,R));E&&(E.length===1?v=E[0][1]:E[E.length-1][0]!==E[E.length-2][0]&&(v=E[E.length-1][1]))}if(v===void 0)throw new B('Ambiguous update, specify "asNode"');w.push({values:_,asNode:v,taskId:A})}else for(const{asNode:_,values:v,taskId:A}of a){if(_==null)throw new B('"asNode" is required when applying multiple updates');w.push({values:v,asNode:_,taskId:A})}const b=[];for(const{asNode:_,values:v,taskId:A}of w){if(this.nodes[_]===void 0)throw new B(`Node "${_.toString()}" does not exist`);const E=this.nodes[_].getWriters();if(!E.length)throw new B(`No writers found for node "${_.toString()}"`);b.push({name:_,input:v,proc:E.length>1?Ze.from(E,{omitSequenceTags:!0}):E[0],writes:[],triggers:[j],id:A??yt(j,u.id),writers:[]})}for(const _ of b)await _.proc.invoke(_.input,ln({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[qe]:v=>_.writes.push(...v),[at]:(v,A=!1)=>Xn(u,C,_,v,A)}}));for(const _ of b){const v=_.writes.filter(A=>A[0]!==de);c!==void 0&&v.length>0&&await n.putWrites(f,v,_.id)}he(u,C,b,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const T=Yn(h,u.channel_versions),x=await n.put(f,nt(u,C,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},T);for(const _ of b){const v=_.writes.filter(A=>A[0]===de);v.length>0&&await n.putWrites(x,v,_.id)}return et(x,c?c.metadata:void 0)};let i=t;for(const{updates:o}of e)i=await r(i,o);return i}async updateState(t,e,n){return this.bulkUpdateState(t,[{updates:[{values:e,asNode:n}]}])}_defaults(t){const{debug:e,streamMode:n,inputKeys:s,outputKeys:r,interruptAfter:i,interruptBefore:o,...a}=t;let l=!0;const c=e!==void 0?e:this.debug;let u=r;u===void 0?u=this.streamChannelsAsIs:Li(u,this.channels);let h=s;h===void 0?h=this.inputChannels:Li(h,this.channels);const d=o??this.interruptBefore??[],f=i??this.interruptAfter??[];let y;n!==void 0?(y=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[cn]!==void 0?y=["values"]:y=this.streamMode,l=!0);let p;if(this.checkpointer===!1)p=void 0;else if(t!==void 0&&t.configurable?.[z]!==void 0)p=t.configurable[z];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 m=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),w=t.durability??m??t?.configurable?.[Da]??"async";return[c,y,h,u,a,d,f,p,S,l,C,w]}async stream(t,e){const n=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,signal:ms(e?.signal,n.signal).signal},r=await super.stream(t,s);return new Ri(e?.encoding==="text/event-stream"?Of(r):r,n)}streamEvents(t,e,n){const s=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,callbacks:mf(this.config?.callbacks,e?.callbacks),signal:ms(e?.signal,s.signal).signal};return new Ri(super.streamEvents(t,r,n),s)}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,s=e?.subgraphs,r=Fa(this.config,e);if(r.recursionLimit===void 0||r.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&r.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const i=await this._validateInput(t),{runId:o,...a}=r,[l,c,,u,h,d,f,y,p,S,C,m]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const w=new tl({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[Ee]??"";h.configurable[Ee]=P.split(J).map(R=>R.split(Ue)[0]).join(J)}if(c.includes("messages")){const P=new Df(V=>w.push(V)),{callbacks:R}=h;if(R===void 0)h.callbacks=[P];else if(Array.isArray(R))h.callbacks=R.concat(P);else{const V=R.copy();V.addHandler(P,!0),h.callbacks=V}}h.writer??=P=>{if(!c.includes("custom"))return;const R=Vd()?.configurable?.[Ee]?.split(J).slice(0,-1);w.push([R??[],"custom",P])},h.interrupt??=this.userInterrupt??Ja;const T=await(await qc(h))?.handleChainStart(this.toJSON(),pf(t,"input"),o,void 0,void 0,void 0,h?.runName??this.getName()),x=ei(this.channels);let _,v;const E=(async()=>{try{_=await jf.initialize({input:i,config:h,checkpointer:y,nodes:this.nodes,channelSpecs:x,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:C,stream:w,interruptAfter:f,interruptBefore:d,manager:T,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:m});const P=new Gf({loop:_,nodeFinished:h.configurable?.[Rd]});e?.subgraphs&&(_.config.configurable={..._.config.configurable,[ds]:_.stream}),await this._runLoop({loop:_,runner:P,debug:l,config:h}),m==="sync"&&await Promise.all(_?.checkpointerPromises??[])}catch(P){v=P}finally{try{_&&(await _.store?.stop(),await _.cache?.stop()),await Promise.all(_?.checkpointerPromises??[])}catch(P){v=v??P}v?w.error(v):w.close()}})();try{for await(const P of w){if(P===void 0)throw new Error("Data structure error.");const[R,V,X]=P;if(c.includes(V)){if(n==="text/event-stream"){s?yield[R,V,X]:yield[null,V,X];continue}s&&!S?yield[R,V,X]:S?s?yield[R,X]:yield X:yield[V,X]}}}catch(P){throw await T?.handleChainError(v),P}finally{await E}await T?.handleChainEnd(_?.output??{},o,void 0,void 0,void 0)}async invoke(t,e){const n=e?.streamMode??"values",s={...e,outputKeys:e?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},r=[],i=await this.stream(t,s),o=[];let a;for await(const l of i)n==="values"?Ua(l)?o.push(l[j]):a=l:r.push(l);if(n==="values"){if(o.length>0){const l=o.flat(1);if(a==null)return{[j]:l};if(typeof a=="object")return{...a,[j]:l}}return a}return r}async _runLoop(t){const{loop:e,runner:n,debug:s,config:r}=t;let i;try{for(;await e.tick({inputKeys:this.inputChannels});){for(const{task:o}of await e._matchCachedWrites())e._outputWrites(o.id,o.writes,!0);s&&Af(e.checkpointMetadata.step,e.channels,this.streamChannelsList),s&&el(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,a)=>{s&&Mf(o,a,this.streamChannelsList)},maxConcurrency:r.maxConcurrency,signal:r.signal})}if(e.status==="out_of_steps")throw new xd([`Recursion limit of ${r.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(o){if(i=o,!await e.finishAndHandleError(i))throw o}finally{i===void 0&&await e.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Jt=class ol extends dt{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new ol(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 Q;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Q;return this.value[0]}isAvailable(){return this.value.length!==0}},al=class{path;ends;constructor(t){ee.isRunnable(t.path)?this.path=t.path:this.path=Wt(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 re.registerWriter(new ft({name:"<branch_run>",trace:!1,func:async(n,s)=>{try{return await this._route(n,s,t,e)}catch(r){throw r.name===Oa.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
42
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),r}}}))}async _route(t,e,n,s){let r=await this.path.invoke(s?s(e):t,e);Array.isArray(r)||(r=[r]);let i;if(this.ends?i=r.map(a=>pe(a)?a:this.ends[a]):i=r,i.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(i.filter(pe).some(a=>a.node===M))throw new B("Cannot send a packet to the END node");return await n(i,e)??t}},Zf=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(s){return s.length>=1&&typeof s[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[s,r,i]of n){for(const a of[J,Ue])if(s.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."),s in this.nodes)throw new Error(`Node \`${s}\` already present.`);if(s===M)throw new Error(`Node \`${s}\` is reserved.`);const o=Wt(r);this.nodes[s]={runnable:o,metadata:i?.metadata,subgraphs:ii(o)?[o]:i?.subgraphs,ends:i?.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===M)throw new Error("END cannot be a start node");if(e===L)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 s=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."),!ee.isRunnable(s.path)){const i=Array.isArray(s.pathMap)?s.pathMap.join(","):Object.keys(s.pathMap??{}).join(",");s.path=Wt(s.path).withConfig({runName:`Branch<${s.source}${i!==""?`,${i}`:""}>`.slice(0,63)})}const r=s.path.getName()==="RunnableLambda"?"condition":s.path.getName();if(this.branches[s.source]&&this.branches[s.source][r])throw new Error(`Condition \`${r}\` already present for node \`${t}\``);return this.branches[s.source]??={},this.branches[s.source][r]=new al(s),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(L,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,M)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:s}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const r=new ll({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[L]:new Jt,[M]:new Jt},inputChannels:L,outputChannels:M,streamChannels:[],streamMode:"values",name:s});for(const[i,o]of Object.entries(this.nodes))r.attachNode(i,o);for(const[i,o]of this.edges)r.attachEdge(i,o);for(const[i,o]of Object.entries(this.branches))for(const[a,l]of Object.entries(o))r.attachBranch(i,a,l);return r.validate()}validate(t){const e=new Set([...this.allEdges].map(([s,r])=>s));for(const[s]of Object.entries(this.branches))e.add(s);for(const s of e)if(s!==L&&!(s in this.nodes))throw new Error(`Found edge starting at unknown node \`${s}\``);const n=new Set([...this.allEdges].map(([s,r])=>r));for(const[s,r]of Object.entries(this.branches))for(const i of Object.values(r))if(i.ends!=null)for(const o of Object.values(i.ends))n.add(o);else{n.add(M);for(const o of Object.keys(this.nodes))o!==s&&n.add(o)}for(const s of Object.values(this.nodes))for(const r of s.ends??[])n.add(r);for(const s of Object.keys(this.nodes))if(!n.has(s))throw new Md([`Node \`${s}\` 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(`
43
- `),{lc_error_code:"UNREACHABLE_NODE"});for(const s of n)if(s!==M&&!(s in this.nodes))throw new Error(`Found edge ending at unknown node \`${s}\``);if(t){for(const s of t)if(!(s in this.nodes))throw new Error(`Interrupt node \`${s}\` is not present`)}this.compiled=!0}},ll=class extends Xf{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new Jt,this.nodes[t]=new bn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new re([{channel:t,value:lt}],[G])),this.streamChannels.push(t)}attachEdge(t,e){if(e===M){if(t===L)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new re([{channel:M,value:lt}],[G]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===L&&!this.nodes[L]&&(this.nodes[L]=qf.subscribeTo(L,{tags:[G]})),this.nodes[t].pipe(n.run(r=>{const i=r.map(o=>pe(o)?o:{channel:o===M?M:`branch:${t}:${e}:${o}`,value:lt});return new re(i,[G])}));const s=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const r of s)if(r!==M){const i=`branch:${t}:${e}:${r}`;this.channels[i]=new Jt,this.nodes[r].triggers.push(i),this.nodes[r].channels.push(i)}}async getGraphAsync(t){const e=t?.xray,n=new mi,s={[L]:n.addNode({schema:ve()},L)},r={};let i={};e&&(i=Object.fromEntries((await He(this.getSubgraphsAsync())).filter(l=>Di(l[1]))));function o(l,c,u,h=!1){if(c===M&&r[M]===void 0&&(r[M]=n.addNode({schema:ve()},M)),s[l]!==void 0){if(r[c]===void 0)throw new Error(`End node ${c} not found!`);return n.addEdge(s[l],r[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,y=i[l]!==void 0?await i[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let C=function(w){return w?w.lc_runnable:!1},m=function(w,b){if(w!==void 0&&!gi(w))return w;if(C(b))try{let T=b.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return b.getName()}else return b.name??"UnknownSchema"};const[p,S]=n.extend(y,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(s[u]={name:m(S.id,S.data),...S}),r[u]={name:m(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);s[u]=p,r[u]=p}}else{const f=n.addNode(h,u,d);s[u]=f,r[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)o(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)])),[M]:M};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,y]of Object.entries(d))o(te(l),te(y),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)o(te(l),te(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new mi,s={[L]:n.addNode({schema:ve()},L)},r={};let i={};e&&(i=Object.fromEntries(rn(this.getSubgraphs()).filter(l=>Di(l[1]))));function o(l,c,u,h=!1){return c===M&&r[M]===void 0&&(r[M]=n.addNode({schema:ve()},M)),n.addEdge(s[l],r[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,y=i[l]!==void 0?i[l].getGraph({...t,xray:f}):h.getGraph(t);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let C=function(w){return w?w.lc_runnable:!1},m=function(w,b){if(w!==void 0&&!gi(w))return w;if(C(b))try{let T=b.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return b.getName()}else return b.name??"UnknownSchema"};const[p,S]=n.extend(y,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(s[u]={name:m(S.id,S.data),...S}),r[u]={name:m(p.id,p.data),...p}}else{const p=n.addNode(h,u,d);s[u]=p,r[u]=p}}else{const f=n.addNode(h,u,d);s[u]=f,r[u]=f}}const a=[...this.builder.allEdges].sort(([l],[c])=>l<c?-1:c>l?1:0);for(const[l,c]of a)o(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)])),[M]:M};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,y]of Object.entries(d))o(te(l),te(y),f,!0)}}return n}};function Di(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function te(t){return t==="subgraph"?`"${t}"`:t}const ot=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Qf=class cl extends dt{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 s of e)if(this.names.has(s))this.seen.has(s)||(this.seen.add(s),n=!0);else throw new B(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!ot(this.names,this.seen))throw new Q}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&ot(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&ot(this.names,this.seen)}},ep=class ul extends dt{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[s,r]=e;n.seen=new Set(s),n.finished=r}return n}update(e){let n=!1;for(const s of e)if(this.names.has(s)&&!this.seen.has(s))this.seen.add(s),n=!0;else if(!this.names.has(s))throw new B(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return n}get(){if(!this.finished||!ot(this.names,this.seen))throw new Q}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&ot(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&ot(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&ot(this.names,this.seen)}};const tp="lg:";var np=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=yi(t);for(const[s,r]of Object.entries(n)){const i=this.get(r);i?.reducer?e[s]=new yr(i.reducer.fn,i.default):e[s]=new ti}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,i])=>i===!0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${i}:${o}`).join("|"),s=this._extensionCache.get(n)??new WeakMap;if(s.has(t))return s.get(t);let r=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const i=Object.entries(yi(t)).map(([o,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=nr(c)??nr(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${tp}${h}`)}return[o,c]});r=Yc(t,Object.fromEntries(i)),Xc(r)&&(r._def.unknownKeys="strip")}return e.asPartial&&(r=jr(r)),s.set(t,r),this._extensionCache.set(n,s),r}};const qt=new np;function Yt(t,e){if(e.reducer&&!e.default){const n=$r(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return qt.extend(n,()=>e),n}else return qt.extend(t,()=>e),t}const je="__root__",xr=Symbol.for("langgraph.state.partial");var sp=class extends Zf{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=qt;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),up(t)){const s=this._metaRegistry.getChannelsForSchema(t.state),r=t.input!=null?this._metaRegistry.getChannelsForSchema(t.input):s,i=t.output!=null?this._metaRegistry.getChannelsForSchema(t.output):s;this._schemaDefinition=s,this._schemaRuntimeDefinition=t.state,this._inputDefinition=r,this._inputRuntimeDefinition=t.input??xr,this._outputDefinition=i,this._outputRuntimeDefinition=t.output??t.state}else if(fe(t)){const s=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=s,this._schemaRuntimeDefinition=t,this._inputDefinition=s,this._inputRuntimeDefinition=xr,this._outputDefinition=s,this._outputRuntimeDefinition=t}else if(cp(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(lp(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(op(t)||Ui(t)){const s=Ui(t)?t.spec:t;this._schemaDefinition=s}else if(ap(t)){const s=rp(t.channels);this._schemaDefinition=s}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(s){return typeof s=="object"&&s!=null&&!("spec"in s)&&!fe(s)}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 s;if(typeof n=="function"?s=n():s=n,this.channels[e]!==void 0){if(this.channels[e]!==s&&s.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=s}}}addNode(...t){function e(s){return s.length>=1&&typeof s[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([s,r])=>[s,r]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[s,r,i]of n){if(s in this.channels)throw new Error(`${s} 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[J,Ue])if(s.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."),s in this.nodes)throw new Error(`Node \`${s}\` already present.`);if(s===M||s===L)throw new Error(`Node \`${s}\` is reserved.`);let o=this._schemaDefinition;i?.input!==void 0&&(fe(i.input)?o=this._metaRegistry.getChannelsForSchema(i.input):i.input.spec!==void 0&&(o=i.input.spec)),o!==void 0&&this._addSchema(o);let a;ee.isRunnable(r)?a=r:typeof r=="function"?a=new ft({func:r,name:s,trace:!1}):a=Wt(r);let l=i?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:i?.retryPolicy,cachePolicy:l,metadata:i?.metadata,input:o??this._schemaDefinition,subgraphs:ii(a)?[a]:i?.subgraphs,ends:i?.ends,defer:i?.defer};this.nodes[s]=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===M)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(s=>s===n))throw new Error(`Need to add a node named "${n}" first`)}if(e===M)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[s,r,i]of e){if(s in this.nodes)throw new Error(`Node names must be unique: node with the name "${s}" already exists.`);const o=s;this.addNode(o,r,i),n!=null&&this.addEdge(n,o),n=o}return this}compile({checkpointer:t,store:e,cache:n,interruptBefore:s,interruptAfter:r,name:i,description:o}={}){this.validate([...Array.isArray(s)?s:[],...Array.isArray(r)?r:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),l=a.length===1&&a[0]===je?je:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===je?je:c,h=this._interrupt,d=new ip({builder:this,checkpointer:t,interruptAfter:r,interruptBefore:s,autoValidate:!1,nodes:{},channels:{...this.channels,[L]:new Jt},inputChannels:L,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:i,description:o,userInterrupt:h});d.attachNode(L);for(const[f,y]of Object.entries(this.nodes))d.attachNode(f,y);d.attachBranch(L,Ai,Fi(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,Ai,Fi(),{withReader:!1});for(const[f,y]of this.edges)d.attachEdge(f,y);for(const[f,y]of this.waitingEdges)d.attachEdge(f,y);for(const[f,y]of Object.entries(this.branches))for(const[p,S]of Object.entries(y))d.attachBranch(f,p,S);return d.validate()}};function rp(t){const e={};for(const[n,s]of Object.entries(t))e[n]=_r(s);return e}var ip=class extends ll{description;_metaRegistry=qt;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===L?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function s(a){if(Y(a))return a.graph===K.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>Y(l))){const l=[];for(const c of a)if(Y(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([je,c]);return l}else if(a!=null)return[[je,a]];return null}const r=t;function i(a){if(a){if(Y(a))return a.graph===K.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(Y)){const l=[];for(const c of a)if(Y(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=i(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 "${r.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 o=[{value:lt,mapper:new ft({func:n.length&&n[0]===je?s:i,trace:!1,recurse:!1})}];if(t===L)this.nodes[t]=new bn({tags:[G],triggers:[L],channels:[L],writers:[new re(o,[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&&je in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new Pd:new Jt(!1),this.nodes[t]=new bn({triggers:[u],channels:c?Object.keys(l):l,writers:[new re(o,[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!==M){if(typeof t=="string")this.nodes[t].writers.push(new re([{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 ep(new Set(t)):new Qf(new Set(t)),this.nodes[e].triggers.push(n);for(const s of t)this.nodes[s].writers.push(new re([{channel:n,value:s}],[G]))}}}attachBranch(t,e,n,s={withReader:!0}){const r=async(i,o)=>{const a=i.filter(c=>c!==M);if(!a.length)return;const l=a.map(c=>pe(c)?c:{channel:c===M?c:`branch:to:${c}`,value:t});await re.doWrite({...o,tags:(o.tags??[]).concat([G])},l)};this.nodes[t].writers.push(n.run(r,s.withReader?i=>uf.doRead(i,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=(()=>{const n=this.builder._inputRuntimeDefinition,s=this.builder._schemaRuntimeDefinition,r=i=>{if(i!=null)return this._metaRegistry.getExtendedChannelSchemas(i,{withReducerSchema:!0})};if(fe(n))return r(n);if(n===xr)return jr(r(s))})();if(Y(t)){const n=t;return t.update&&e!=null&&(n.update=Ke(e,t.update)),n}return e!=null?Ke(e,t):t}isInterrupted(t){return Ua(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return fe(e)&&Ke(e,t),t}};function op(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 Ui(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function ap(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function lp(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function cp(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function up(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 hp(t){if(pe(t))return[t];const e=[];Y(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Y));const n=[];for(const s of e){if(s.graph===K.PARENT)throw new Ia(s);pe(s.goto)||typeof s.goto=="string"?n.push(s.goto):Array.isArray(s.goto)&&n.push(...s.goto)}return n}function Fi(){const t=new ft({func:hp,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],s=Array.isArray(e)?e:[e],r=n.map(pn),i=s.map(pn);for(const u of r)(u.id===null||u.id===void 0)&&(u.id=ts(),u.lc_kwargs.id=u.id);let o;for(let u=0;u<i.length;u+=1){const h=i[u];(h.id===null||h.id===void 0)&&(h.id=ts(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===hl&&(o=u)}if(o!=null)return i.slice(o+1);const a=[...r],l=new Map(a.map((u,h)=>[u.id,h])),c=new Set;for(const u of i){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))}wr.Root({messages:wr({reducer:dl,default:()=>[]})});const gs={reducer:{fn:dl},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};W({messages:Yt(le(),gs)});Ed();const Ar=Symbol.for("langgraph-zod");Ar in globalThis||(globalThis[Ar]=new WeakSet);function Vi(t){const e=globalThis[Ar];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(s){return Yt(n,{jsonSchemaExtra:s})},reducer(s,r){const i=$r(n);return Yt(n,{default:i,reducer:{schema:r,fn:s}})}}}}),e.add(t))}try{Vi(Zc.prototype),Vi(Ul.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var dp=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 s=$r(t);s!=null&&(n.default=s)}return super.add(t,...e)}};new dp(qt);function fp(t=!0,e,n=[]){const s={messages:Yt(le(),gs),jumpTo:Me([vt("model_request"),vt("tools"),vt("end"),Qc()]).optional()},r=a=>{const{shape:l}=a;for(const[c,u]of Object.entries(l))c.startsWith("_")||c in s||(s[c]=u)};e&&"shape"in e&&r(e);for(const a of n)a.stateSchema&&r(a.stateSchema);t&&(s.structuredResponse=Lr().optional());const i=W(s);return qt.getChannelsForSchema(i)}W({llmInputMessages:Yt(le(),{reducer:{fn:(t,e)=>gs.reducer.fn([],e)},default:()=>[]}),messages:Yt(le(),gs)});const Bi="prompt",qs=/<name>(.*?)<\/name>/s,Ys=/<content>(.*?)<\/content>/s;function pp(t){if(!N.isInstance(t)||Vt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new N({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let s=0;for(const r of t.content)typeof r=="string"?(s+=1,n.push(`<name>${e}</name><content>${r}</content>`)):typeof r=="object"&&"type"in r&&r.type==="text"?(s+=1,n.push({...r,text:`<name>${e}</name><content>${r.text}</content>`})):n.push(r);return s||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new N({...t.lc_kwargs,content:n,name:void 0})}function mp(t){if(!N.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(s=>{if(s.type==="text"&&typeof s.text=="string"){const r=s.text.match(qs),i=s.text.match(Ys);return r&&(!i||i[1]==="")?(n=r[1],!1):!0}return!0}).map(s=>{if(s.type==="text"&&typeof s.text=="string"){const r=s.text.match(qs),i=s.text.match(Ys);return!r||!i?s:(n=r[1],{...s,text:i[1]})}return s});else{const s=t.content,r=s.match(qs),i=s.match(Ys);if(!r||!i)return t;n=r[1],e=i[1]}return new N({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function H(t){return ee.isRunnable(t)}function Wi(t){return Ur(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const Xs=(t,e,n={})=>{if(Wi(t))return t.bindTools(e,n);if(xe.isRunnableBinding(t)&&Wi(t.bound)){const s=t.bound.bindTools(e,n);return xe.isRunnableBinding(s)?new xe({bound:s.bound,config:{...t.config,...s.config},kwargs:{...t.kwargs,...s.kwargs},configFactories:s.configFactories??t.configFactories}):new xe({bound:s,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function fl(t){if(typeof t=="function")return;let e=t;if(Ze.isRunnableSequence(e)&&(e=e.steps.find(n=>xe.isRunnableBinding(n))||e),!is(e)){if(xe.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,s=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(n||s)throw new rr}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new rr}}function Mr(t){return!!(N.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function gp(t){let e;if(t==null)e=Bt.from(n=>n.messages).withConfig({runName:Bi});else if(typeof t=="string"){const n=new _e(t);e=Bt.from(s=>[n,...s.messages??[]]).withConfig({runName:Bi})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function yp(t,e,n={}){const s=Xs(t,e,n);if(s)return s;if(is(t)){const r=Xs(await t._model(),e,n);if(r)return r}if(Ze.isRunnableSequence(t)){const r=t.steps.findIndex(i=>xe.isRunnableBinding(i)||Ur(i)||is(i));if(r>=0){const i=Xs(t.steps[r],e,n);if(i){const o=t.steps.slice();return o.splice(r,1,i),Ze.from(o)}}}throw new Error(`llm ${t} must define bindTools method.`)}function wp(t){if(t.length===0)return;if(t.length===1)return t[0];function e(s,r){return async(i,o)=>s(i,async()=>r(i,async()=>o(i)))}let n=t[t.length-1];for(let s=t.length-2;s>=0;s--)n=e(t[s],n);return n}function _p(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return wp(e.map(n=>{const s=n.wrapToolCall;return async(i,o)=>{try{const a=await s({...i,state:{messages:i.state.messages,...n.stateSchema?Ke(n.stateSchema,{...i.state}):{}}},o);if(!U.isInstance(a)&&!Y(a))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof a}`);return a}catch(a){throw a instanceof Error&&!a.message.includes(`middleware "${n.name}"`)&&(a.message=`Error in middleware "${n.name}": ${a.message}`),a}}}))}async function bp(t,e){const n={};for(const s of t){if(!s.stateSchema)continue;const r=eu(s.stateSchema,a=>a.startsWith("_")),i=await tu(r,e);if(i.success){Object.assign(n,i.data);continue}const o=i.error.issues.filter(a=>a.code==="invalid_type"&&a.message==="Required").map(a=>` - ${a.path.join(".")}: ${a.message}`).join(`
44
- `);throw new Error(`Middleware "${s.name}" has required state fields that must be initialized:
33
+ `),super(n),this.lc_error_code=e?.lc_error_code}},Oa=class extends ht{get is_bubble_up(){return!0}},Id=class extends ht{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Wn=class extends ht{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},St=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"}},Ia=class extends St{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},$a=class extends Oa{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function $d(t){return t!==void 0&&t.name===$a.unminifiable_name}function zn(t){return t!==void 0&&t.is_bubble_up===!0}function it(t){return t!==void 0&&[St.unminifiable_name,Ia.unminifiable_name].includes(t.name)}var xi=class extends ht{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Q=class extends ht{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ht{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Rd=class extends ht{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 dt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(t){if(t.name===Q.unminifiable_name)return!1;throw t}}};const gs=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function ei(t){if(t[gs]===!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,{[gs]:!0}),e}function hr(t,e){const n=ei(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const i=e.channel_values[s];r[s]=n[s].fromCheckpoint(i)}return Object.assign(r,{[gs]:!0}),r}function nt(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i))try{s[i]=e[i].checkpoint()}catch(o){if(o.name!==Q.unminifiable_name)throw o}}return{v:4,id:r?.id??vo(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var ys=class ja extends dt{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 Q;return this.value}checkpoint(){if(this.value===void 0)throw new Q;return this.value}isAvailable(){return this.value!==void 0}},ti=class La extends dt{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 Q;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Q;return this.value[0]}isAvailable(){return this.value.length!==0}},jd=class Da extends dt{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 Q;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}},Ld=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const ws=function(t){return t?_s(t):new ti};ws.Root=t=>new Ld(t);function _s(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new ys(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new ys(t.value,t.default):new ti}const L="__start__",M="__end__",Ie="__input__",Dd="__copy__",ae="__error__",Ur="__pregel_ns_writes",qe="__pregel_send",ni="__pregel_call",at="__pregel_read",H="__pregel_checkpointer",We="__pregel_resuming",cn="__pregel_task_id",dr="__pregel_stream",Ud="__pregel_resume_value",Hn="__pregel_resume_map",Ye="__pregel_scratchpad",Gn="__pregel_previous",Ua="__pregel_durability",bs="checkpoint_id",Ee="checkpoint_ns",Fd="__pregel_node_finished",ge="checkpoint_map",Ai="__pregel_abort_signals",j="__interrupt__",ce="__resume__",ri="__no_writes__",Gt="__return__",Fr="__previous__",G="langsmith:hidden",Vd="langsmith:nostream",Mi="__self__",ye="__pregel_tasks",de="__pregel_push",Kn="__pregel_pull",we="00000000-0000-0000-0000-000000000000",Bd=[G,Ie,j,ce,ae,ri,qe,at,H,Ua,dr,We,cn,ni,Ud,Ye,Gn,ge,Ee,bs],J="|",Ue=":",Pi=Symbol.for("langgraph.command");var Wd=class{[Pi];constructor(t){this[Pi]=t}};function vs(t){const e=t;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var re=class{lg_name="Send";node;args;constructor(t,e){this.node=t,this.args=_n(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function pe(t){return t instanceof re}function Fa(t){return!t||typeof t!="object"||!(j in t)?!1:Array.isArray(t[j])}var K=class extends Wd{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(t){super(t),this.resume=t.resume,this.graph=t.graph,this.update=t.update,t.goto&&(this.goto=Array.isArray(t.goto)?_n(t.goto):[_n(t.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let t;return typeof this.goto=="string"?t=this.goto:pe(this.goto)?t=this.goto.toJSON():t=this.goto?.map(e=>typeof e=="string"?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:t}}};function Y(t){return typeof t!="object"||t==null?!1:"lg_name"in t&&t.lg_name==="Command"}function _n(t,e=new Map){if(t!=null&&typeof t=="object"){if(e.has(t))return e.get(t);let n;if(Array.isArray(t))n=[],e.set(t,n),t.forEach((r,s)=>{n[s]=_n(r,e)});else if(Y(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(vs(t)&&!(t instanceof re))n=new re(t.node,t.args),e.set(t,n);else if(Y(t)||pe(t))n=t,e.set(t,n);else if("lc_serializable"in t&&t.lc_serializable)n=t,e.set(t,n);else{n={},e.set(t,n);for(const[r,s]of Object.entries(t))n[r]=_n(s,e)}return n}return t}const zd=["tags","metadata","callbacks","configurable"],Hd=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Gd=25;function Va(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Gd,configurable:{}},n=Le.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(zd.includes(r)){let i;Array.isArray(s)?i=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?i=s.copy():i={...s}:i=s,e[r]=i}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,i]of Object.entries(r))i!==void 0&&Hd.includes(s)&&(e[s]=i);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 Kd(){return Le.getRunnableConfig()}function Vr(t){return t.split(J).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(Ue)[0]).join(J)}function Jd(t){const e=t.split(J);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(J)}const k=t=>BigInt(t),D=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Ba=k("0x9E3779B1"),Wa=k("0x85EBCA77"),qd=k("0xC2B2AE3D"),Qe=k("0x9E3779B185EBCA87"),ct=k("0xC2B2AE3D27D4EB4F"),za=k("0x165667B19E3779F9"),si=k("0x85EBCA77C2B2AE63"),Yd=k("0x27D4EB2F165667C5"),Xd=k("0x165667919E3779F9"),Zd=k("0x9FB21C651E98DF25"),Qd=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,i=0;for(;i<n;){const o=t.slice(s,s+=2);r[i]=Number.parseInt(o,16),i+=1}return D(r)},ke=Qd("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Ct=(k(1)<<k(128))-k(1),I=(k(1)<<k(64))-k(1),fr=(k(1)<<k(32))-k(1),$e=64,Ha=$e/8,ef=8,Mn=4;function Kt(t){if(!t)throw new Error("Assert failed")}function tf(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function nf(t){let e=t;return e=(e&k(65535))<<k(16)|(e&k(4294901760))>>k(16),e=(e&k(16711935))<<k(8)|(e&k(4278255360))>>k(8),e}function rf(t,e){return(t&fr)*(e&fr)&I}function sf(t,e){return(t<<e|t>>k(32)-e)&fr}function Ga(t,e,n){for(let r=0;r<Ha;r+=1){const s=e.getBigUint64(r*8,!0),i=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=rf(i,i>>k(32))}return t}function Ni(t,e,n,r){for(let s=0;s<r;s+=1)Ga(t,D(e,s*$e),D(n,s*8));return t}function of(t,e){for(let n=0;n<Ha;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=Ss(s,k(47)),s^=r,s*=Ba,t[n]=s&I}return t}function Pn(t,e){return Ka(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(ef,!0))}function Oi(t,e,n){let r=n;return r+=Pn(t.slice(0),D(e,0*Mn)),r+=Pn(t.slice(2),D(e,4*Mn)),r+=Pn(t.slice(4),D(e,8*Mn)),r+=Pn(t.slice(6),D(e,12*Mn)),Ae(r&I)}function af(t,e,n,r,s){let i=t;const o=Math.floor((n.byteLength-$e)/8),a=$e*o,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)i=Ni(i,D(e,c*a),n,o),i=s(i,D(n,n.byteLength-$e));{const c=Math.floor((e.byteLength-1-a*l)/$e);i=Ni(i,D(e,l*a),n,c),i=r(i,D(e,e.byteLength-$e),D(n,n.byteLength-$e-7))}return i}function lf(t,e){let n=new BigUint64Array([qd,Qe,ct,za,si,Wa,Yd,Ba]);Kt(t.byteLength>128),n=af(n,t,e,Ga,of),Kt(n.length*8===64);{const r=Oi(n,D(e,11),k(t.byteLength)*Qe&I);return Oi(n,D(e,e.byteLength-$e-11),~(k(t.byteLength)*ct)&I)<<k(64)|r}}function Ka(t,e){const n=t*e&Ct;return n&I^n>>k(64)}function Ii(t,e,n){return Ka((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&I,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&I)}function Jn(t,e,n,r,s){let i=t&I,o=t>>k(64)&I;return i+=Ii(e,r,s),i^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),i&=I,o+=Ii(n,D(r,16),s),o^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),o&=I,o<<k(64)|i}function Ae(t){let e=t;return e^=e>>k(37),e*=Xd,e&=I,e^=e>>k(32),e}function pr(t){let e=t;return e^=e>>k(33),e*=ct,e&=I,e^=e>>k(29),e*=za,e&=I,e^=e>>k(32),e}function cf(t,e,n){const r=t.byteLength;Kt(r>0&&r<=3);const s=k(t.getUint8(r-1))|k(r<<8)|k(t.getUint8(0)<<16)|k(t.getUint8(r>>1)<<24),i=(k(e.getUint32(0,!0))^k(e.getUint32(4,!0)))+n,o=(s^i)&I,a=(k(e.getUint32(8,!0))^k(e.getUint32(12,!0)))-n,l=(sf(nf(s),k(13))^a)&I;return(pr(l)&I)<<k(64)|pr(o)}function Ss(t,e){return t^t>>e}function uf(t,e,n){const r=t.byteLength;Kt(r>=4&&r<=8);{const s=t.getUint32(0,!0),i=t.getUint32(r-4,!0),o=k(s)|k(i)<<k(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&I;let c=(o^a)*(Qe+(k(r)<<k(2)))&Ct;return c+=(c&I)<<k(65),c&=Ct,c^=c>>k(67),Ss(Ss(c&I,k(35))*Zd&I,k(28))|Ae(c>>k(64))<<k(64)}}function hf(t,e,n){const r=t.byteLength;Kt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&I,i=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&I,o=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(o^a^s)*Qe;const c=(l&I)+(k(r-1)<<k(54));l=l&(Ct^I)|c,a^=i,l+=a+(a&fr)*(Wa-k(1))<<k(64),l&=Ct,l^=tf(l>>k(64));let u=(l&I)*ct;return u+=(l>>k(64))*ct<<k(64),u&=Ct,Ae(u&I)|Ae(u>>k(64))<<k(64)}}function df(t,e){const n=t.byteLength;return Kt(n<=16),n>8?hf(t,ke,e):n>=4?uf(t,ke,e):n>0?cf(t,ke,e):pr(e^ke.getBigUint64(64,!0)^ke.getBigUint64(72,!0))|pr(e^ke.getBigUint64(80,!0)^ke.getBigUint64(88,!0))<<k(64)}function Cs(t){return~t+k(1)&I}function ff(t,e,n){let r=k(t.byteLength)*Qe&I,s=k(t.byteLength-1)/k(32);for(;s>=0;){const a=Number(s);r=Jn(r,D(t,16*a),D(t,t.byteLength-16*(a+1)),D(e,32*a),n),s-=k(1)}let i=r+(r>>k(64))&I;i=Ae(i);let o=(r&I)*Qe+(r>>k(64))*si+(k(t.byteLength)-n&I)*ct;return o&=I,o=Cs(Ae(o)),i|o<<k(64)}function pf(t,e,n){let r=k(t.byteLength)*Qe&I;for(let o=32;o<160;o+=32)r=Jn(r,D(t,o-32),D(t,o-16),D(e,o-32),n);r=Ae(r&I)|Ae(r>>k(64))<<k(64);for(let o=160;o<=t.byteLength;o+=32)r=Jn(r,D(t,o-32),D(t,o-16),D(e,3+o-160),n);r=Jn(r,D(t,t.byteLength-16),D(t,t.byteLength-32),D(e,103),Cs(n));let s=r+(r>>k(64))&I;s=Ae(s);let i=(r&I)*Qe+(r>>k(64))*si+(k(t.byteLength)-n&I)*ct;return i&=I,i=Cs(Ae(i)),s|i<<k(64)}function tt(t,e=k(0)){const n=new TextEncoder,r=D(typeof t=="string"?n.encode(t):t),s=r.byteLength,i=o=>o.toString(16).padStart(32,"0");return s<=16?i(df(r,e)):s<=128?i(ff(r,ke,e)):s<=240?i(pf(r,ke,e)):i(lf(r,ke))}function Ja(t){return/^[0-9a-f]{32}$/.test(t)}function qa(t){const e=Le.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[Ye];s.interruptCounter+=1;const i=s.interruptCounter;if(s.resume.length>0&&i<s.resume.length)return n[qe]?.([[ce,s.resume]]),s.resume[i];if(s.nullResume!==void 0){if(s.resume.length!==i)throw new Error(`Resume length mismatch: ${s.resume.length} !== ${i}`);const l=s.consumeNullResume();return s.resume.push(l),n[qe]?.([[ce,s.resume]]),l}const o=n[Ee]?.split(J),a=o?tt(o.join(J)):void 0;throw new St([{id:a,value:t}])}var ft=class extends ee{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,i)=>{const o=ln(n,{callbacks:r?.getChild()});Le.runWithConfig(o,async()=>{try{const a=await this.func(e,o);s(a)}catch(a){i(a)}})})}async invoke(e,n){let r;const s=Va(n),i=Re(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,i):r=await Le.runWithConfig(i,async()=>this.func(e,i)),ee.isRunnable(r)&&this.recurse?await Le.runWithConfig(i,async()=>r.invoke(e,i)):r}};function*Ve(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function ze(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 pt(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function mf(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const lt={[Symbol.for("LG_PASSTHROUGH")]:!0};function Nn(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const Br=Symbol("IS_WRITER");var se=class Ts extends ft{writes;constructor(e,n){const r=`ChannelWrite<${e.map(s=>pe(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:e,name:r,tags:n,func:async(s,i)=>this._write(s,i??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>Wr(s)&&Nn(s.value)?{mapper:s.mapper,value:e}:qn(s)&&Nn(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await Ts.doWrite(n,r),e}static async doWrite(e,n){for(const i of n){if(qn(i)){if(i.channel===ye)throw new B("Cannot write to the reserved channel TASKS");if(Nn(i.value))throw new B("PASSTHROUGH value must be replaced")}if(Wr(i)&&Nn(i.value))throw new B("PASSTHROUGH value must be replaced")}const r=[];for(const i of n)if(pe(i))r.push([ye,i]);else if(Wr(i)){const o=await i.mapper.invoke(i.value,e);o!=null&&o.length>0&&r.push(...o)}else if(qn(i)){const o=i.mapper!==void 0?await i.mapper.invoke(i.value,e):i.value;if(mf(o)||i.skipNone&&o===void 0)continue;r.push([i.channel,o])}else throw new Error(`Invalid write entry: ${JSON.stringify(i)}`);const s=e.configurable?.[qe];s(r)}static isWriter(e){return e instanceof Ts||Br in e&&!!e[Br]}static registerWriter(e){return Object.defineProperty(e,Br,{value:!0})}};function qn(t){return t!==void 0&&typeof t.channel=="string"}function Wr(t){return t!==void 0&&!qn(t)&&ee.isRunnable(t.mapper)}var gf=class Ya extends ft{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,i)=>Ya.doRead(i,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 i=e.configurable?.[at];if(!i)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(i(n,r)):i(n,r)}};const mt=new _c;var bn=class on extends xe{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=mt;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:i,bound:o,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:h,subgraphs:d,ends:f}=e,y=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??mt,config:{...e.config?e.config:{},tags:y}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=i??this.writers,this.bound=o??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=y,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 se&&e[e.length-2]instanceof se;){const n=e.slice(-2),r=n[0].writes.concat(n[1].writes);e[e.length-2]=new se(r,n[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();if(!(this.bound===mt&&e.length===0))return this.bound===mt&&e.length===1?e[0]:this.bound===mt?new Ze({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Ze({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 se.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===mt?new on({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Wt(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 yf(t){return"steps"in t&&Array.isArray(t.steps)}function ii(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Xa(t){const e=[t];for(const n of e){if(ii(n))return n;yf(n)&&e.push(...n.steps)}}function Tt(t,e,n=!0,r=!1){try{return t[e].get()}catch(s){if(s.name===Q.unminifiable_name){if(r)return s;if(n)return null}throw s}}function ut(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Tt(t,s,!n)}catch(i){if(i.name===Q.unminifiable_name)continue}return r}else return Tt(t,e)}function*wf(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(pe(r))yield[we,ye,r];else if(typeof r=="string")yield[we,`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(Ja))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(i=>i[0]===n&&i[1]===ce).map(i=>i[2]).slice(0,1)??[];s.push(r),yield[n,ce,s]}else yield[we,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[we,n,r];else for(const[n,r]of Object.entries(t.update))yield[we,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*zr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield ut(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Tt(n,t))}function*_f(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]!==j);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 i={};for(const[a,l]of s)a in i||(i[a]=[]),i[a].push(l);const o={};for(const a in i)if(i[a].length===1){const[l]=i[a];o[a]=l}else o[a]=i[a];n&&(o.__metadata__={cached:n}),yield o}function oi(t){const e=typeof t[L];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 Yn(t,e){if(Object.keys(t).length>0){const n=oi(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function bf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function be(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function et(t,e){const n=e?.parents??{};return Object.keys(n).length>0?be(t,{[ge]:{...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 i=e.find(o=>o.aborted)?.reason;n.abort(i),e.forEach(o=>o.removeEventListener("abort",r))};e.forEach(i=>i.addEventListener("abort",r,{once:!0}));const s=e.find(i=>i.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(i=>i.removeEventListener("abort",r))}}}const vf=(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 Sf=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:t,name:e,input:n,retry:r,cache:s,callbacks:i}){this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.callbacks=i}};function Cf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Tf(t,e){const n=new ft({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new Ze({name:t,first:n,last:new se([{channel:Gt,value:lt}],[G])})}const kf=t=>t!==void 0?t+1:1;function Ef(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function xf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=Cd(e,t[n]));return e}function On(t,e,n){const r=oi(t.channel_versions),s=t.versions_seen[j]??{};let i=!1;if((t.channel_versions[L]??r)>(s[L]??r))i=!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)){i=!0;break}const o=n.some(a=>e==="*"?!a.config?.tags?.includes(G):e.includes(a.name));return i&&o}function Xn(t,e,n,r,s=!1){let i=new Set;if(Array.isArray(r))i=new Set(r.filter(a=>n.writes.some(([l,c])=>l===a)));else{for(const[a]of n.writes)if(a===r){i=new Set([a]);break}i=i||new Set}let o;if(s&&i.size>0){const a=Object.fromEntries(Object.entries(e).filter(([u,h])=>i.has(u))),l=nt(t,a,-1),c=hr(a,l);he(ur(l),c,[n],void 0,void 0),o=ut({...e,...c},r)}else o=ut(e,r);return o}function Hr(t,e,n){for(const[r,s]of n)if([de,ye].includes(r)&&s!=null){if(!pe(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 Af=new Set([ri,de,ce,j,Gt,ae]);function he(t,e,n,r,s){n.sort((d,f)=>{const y=d.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let S=0;S<Math.min(y.length,p.length);S+=1){if(y[S]<p[S])return-1;if(y[S]>p[S])return 1}return y.length-p.length});const i=n.some(d=>d.triggers.length>0),o=ei(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=xf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!Bd.includes(d)));let c=!1;for(const d of l)d in o&&o[d].consume()&&r!==void 0&&(t.channel_versions[d]=r(a),c=!0);const u={};for(const d of n)for(const[f,y]of d.writes)Af.has(f)||f in o&&(u[f]??=[],u[f].push(y));a!=null&&r!=null&&(a=c?r(a):a);const h=new Set;for(const[d,f]of Object.entries(u))if(d in o){const y=o[d];let p;try{p=y.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),y.isAvailable()&&h.add(d))}if(i)for(const d in o){if(!Object.prototype.hasOwnProperty.call(o,d))continue;const f=o[d];f.isAvailable()&&!h.has(d)&&f.update([])&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}if(i&&!Ef(h,s))for(const d in o){if(!Object.prototype.hasOwnProperty.call(o,d))continue;const f=o[d];f.finish()&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}return h}function*Mf(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const s=new Set;for(const i of n.updatedChannels){const o=n.triggerToNodes[i];for(const a of o??[])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 bt(t,e,n,r,s,i,o){const a={},l=r[ye];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,i,o);h!==void 0&&(a[h.id]=h)}}for(const c of Mf(t,n,o)){const u=ks([Kn,c],t,e,n,r,s,i,o);u!==void 0&&(a[u.id]=u)}return a}function ks(t,e,n,r,s,i,o,a){const{step:l,checkpointer:c,manager:u}=a,h=i.configurable??{},d=h.checkpoint_ns??"";if(t[0]===de&&Cf(t[t.length-1])){const f=t[t.length-1],y=Tf(f.name,f.func),p=[de],S=d===""?f.name:`${d}${J}${f.name}`,C=yt(JSON.stringify([S,l.toString(),f.name,de,t[1],t[2]]),e.id),m=`${S}${Ue}${C}`,w=[...t.slice(0,3),!0],b={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:w,langgraph_checkpoint_ns:m};if(o){const T=[];return{name:f.name,input:f.input,proc:y,writes:T,config:ln(Re(i,{metadata:b,store:a.store??i.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:C,[qe]:_=>Hr(v=>T.push(...v),r,_),[at]:(_,v=!1)=>Xn(e,s,{name:f.name,writes:T,triggers:p,path:w},_,v),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[Ye]:Gr({pendingWrites:n??[],taskId:C,currentTaskInput:f.input,resumeMap:i.configurable?.[Hn],namespaceHash:tt(m)}),[Gn]:e.channel_values[Fr],checkpoint_id:void 0,checkpoint_ns:m}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:tt((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Ur,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:C,path:w,writers:[]}}else return{id:C,name:f.name,interrupts:[],path:w}}else if(t[0]===de){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[ye]?.isAvailable())return;const y=s[ye].get();if(f<0||f>=y.length)return;const p=vs(y[f])&&!pe(y[f])?new re(y[f].node,y[f].args):y[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}${J}${p.node}`,m=yt(JSON.stringify([C,l.toString(),p.node,de,f.toString()]),e.id),w=`${C}${Ue}${m}`;let b={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:S,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:w};if(o){const T=r[p.node],x=T.getNode();if(x!==void 0){T.metadata!==void 0&&(b={...b,...T.metadata});const _=[];return{name:p.node,input:p.args,proc:x,subgraphs:T.subgraphs,writes:_,config:ln(Re(i,{metadata:b,tags:T.tags,store:a.store??i.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:m,[qe]:v=>Hr(A=>_.push(...A),r,v),[at]:(v,A=!1)=>Xn(e,s,{name:p.node,writes:_,triggers:S,path:t},v,A),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[Ye]:Gr({pendingWrites:n??[],taskId:m,currentTaskInput:p.args,resumeMap:i.configurable?.[Hn],namespaceHash:tt(w)}),[Gn]:e.channel_values[Fr],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:S,retry_policy:T.retryPolicy,cache_key:T.cachePolicy?{key:tt((T.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[Ur,T.name??"__dynamic__",p.node],ttl:T.cachePolicy.ttl}:void 0,id:m,path:t,writers:T.getWriters()}}}else return{id:m,name:p.node,interrupts:[],path:t}}else if(t[0]===Kn){const f=t[1].toString(),y=r[f];if(y===void 0)return;if(n?.length){const m=d===""?f:`${d}${J}${f}`,w=yt(JSON.stringify([m,l.toString(),f,Kn,f]),e.id);if(n.some(T=>T[0]===w&&T[1]!==ae))return}const p=oi(e.channel_versions);if(p===void 0)return;const S=e.versions_seen[f]??{},C=y.triggers.find(m=>s[m].isAvailable()?(e.channel_versions[m]??p)>(S[m]??p):!1);if(C!==void 0){const m=Pf(y,s,o);if(m===void 0)return;const w=d===""?f:`${d}${J}${f}`,b=yt(JSON.stringify([w,l.toString(),f,Kn,[C]]),e.id),T=`${w}${Ue}${b}`;let x={langgraph_step:l,langgraph_node:f,langgraph_triggers:[C],langgraph_path:t,langgraph_checkpoint_ns:T};if(o){const _=y.getNode();if(_!==void 0){y.metadata!==void 0&&(x={...x,...y.metadata});const v=[];return{name:f,input:m,proc:_,subgraphs:y.subgraphs,writes:v,config:ln(Re(i,{metadata:x,tags:y.tags,store:a.store??i.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[cn]:b,[qe]:A=>Hr(E=>{v.push(...E)},r,A),[at]:(A,E=!1)=>Xn(e,s,{name:f,writes:v,triggers:[C],path:t},A,E),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[Ye]:Gr({pendingWrites:n??[],taskId:b,currentTaskInput:m,resumeMap:i.configurable?.[Hn],namespaceHash:tt(T)}),[Gn]:e.channel_values[Fr],checkpoint_id:void 0,checkpoint_ns:T}}),triggers:[C],retry_policy:y.retryPolicy,cache_key:y.cachePolicy?{key:tt((y.cachePolicy.keyFunc??JSON.stringify)([m])),ns:[Ur,y.name??"__dynamic__",f],ttl:y.cachePolicy.ttl}:void 0,id:b,path:t,writers:y.getWriters()}}}else return{id:b,name:f,interrupts:[],path:t}}}}function Pf(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,i]of Object.entries(t.channels))if(t.triggers.includes(i))try{r[s]=Tt(e,i,!1)}catch(o){if(o.name===Q.unminifiable_name)return;throw o}else if(i in e)try{r[s]=Tt(e,i,!1)}catch(o){if(o.name===Q.unminifiable_name)continue;throw o}}else if(Array.isArray(t.channels)){let s=!1;for(const i of t.channels)try{r=Tt(e,i,!1),s=!0;break}catch(o){if(o.name===Q.unminifiable_name)continue;throw o}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 i=t.find(([l,c])=>l===we&&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:i,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,t.splice(t.findIndex(([l,c])=>l===we&&c===ce),1),i}};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"}},Sn=(t,e)=>`${t.start}${e}${t.end}`;function*$i(t){for(const{id:e,name:n,input:r,config:s,triggers:i,writes:o}of t){if(s?.tags?.includes(G))continue;const a=o.filter(([l,c])=>l===e&&c===j).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:i,interrupts:a}}}function Nf(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 i=Nf(e[s])?e[s].$writes:[e[s]];i.push(r),e[s]={$writes:i}}else e[s]=r}return e}function*Of(t,e){for(const[{id:n,name:r,config:s},i]of t)s?.tags?.includes(G)||(yield{id:n,name:r,result:Qa(i.filter(([o])=>Array.isArray(e)?e.includes(o):o===e)),interrupts:i.filter(o=>o[0]===j).map(o=>o[1])})}function*If(t,e,n,r,s,i,o,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:ut(e,n),metadata:r,next:s.map(h=>h.name),tasks:el(s,i,u,a),parentConfig:o?l(o):void 0}}function el(t,e,n,r){return t.map(s=>{const i=e.find(([c,u])=>c===s.id&&u===ae)?.[2],o=e.filter(([c,u])=>c===s.id&&u===j).map(([,,c])=>c),a=(()=>{if(i||o.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(i)return{id:s.id,name:s.name,path:s.path,error:i,interrupts:o,result:a};const l=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:o,...l!==void 0?{state:l}:{},result:a}})}function $f(t,e,n){console.log([`${Sn(vn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
34
+ `,JSON.stringify(ut(e,n),null,2)].join(""))}function tl(t,e){const n=e.length;console.log([`${Sn(vn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
35
+ `,e.map(r=>`- ${Sn(vn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
36
+ `)].join(""))}function Rf(t,e,n){const r={};for(const[s,i]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(i));console.log([`${Sn(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
37
+ `,Object.entries(r).map(([s,i])=>`- ${Sn(vn.yellow,s)} -> ${i.map(o=>JSON.stringify(o)).join(", ")}`).join(`
38
+ `)].join(""))}var Ri=class extends fn{_abortController;_innerReader;constructor(t,e){const n=t.getReader(),r=e??new AbortController;super({start(s){return i();function i(){return n.read().then(({done:o,value:a})=>{if(o){s.close();return}return s.enqueue(a),i()})}}}),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 fn{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(t){let e;const n=new Promise(r=>{e=r});super({start:r=>{e(r)}}),n.then(r=>{this.controller=r}),this.passthroughFn=t.passthroughFn,this.modes=t.modes}push(t){this.passthroughFn?.(t),this.controller.enqueue(t)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(t){this.controller.error(t)}};function jf(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:i}=r.toDict();return{...i,type:s}}return n})}function Lf(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function ai(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Kr(t){return!ai(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 ji(t){if(ai(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 Li(t){const e={...t,checkpoint:Kr(t.config),parent_checkpoint:Kr(t.parentConfig),config:ji(t.config),parent_config:ji(t.parentConfig),tasks:t.tasks.map(n=>{if(ai(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 Df(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
39
+ data: ${jf(s.data)}
40
+
41
+ `))};try{for await(const s of t){const[i,o,a]=s;let l=a;if(o==="debug"){const u=a;u.type==="checkpoint"&&(l={...u,payload:Li(u.payload)})}o==="checkpoints"&&(l=Li(a));const c=i?.length?`${o}|${i.join("|")}`:o;r({event:c,data:l})}}catch(s){r({event:"error",data:Lf(s)})}n.close()}})}const In=Symbol.for("INPUT_DONE"),Jr=Symbol.for("INPUT_RESUMING"),Uf=25;function Ff(...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 Vf=class extends Md{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}},Bf=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(L 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?.[We]!==void 0&&this.config.configurable?.[We],s=this.input===null||this.input===void 0,i=Y(this.input)&&this.input.resume!=null,o=this.input===Jr,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||i||o||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=kf,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 Vf(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=Ff(r,n.configurable[dr]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,i=n.configurable?.[Ye];n.configurable&&i&&(i.subgraphCounter>0&&(n=be(n,{[Ee]:[n.configurable[Ee],i.subgraphCounter.toString()].join(J)})),i.subgraphCounter+=1);const o=at in(n.configurable??{});!o&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=be(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ge]!==void 0&&n.configurable?.[ge]?.[n.configurable?.checkpoint_ns]&&(a=be(n,{checkpoint_id:n.configurable[ge][n.configurable?.checkpoint_ns]}));const l=n.configurable?.checkpoint_ns?.split(J)??[],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??[],y=hr(e.channelSpecs,h),p=(d.step??0)+1,S=p+(n.recursionLimit??Uf)+1,C={...h.channel_versions},m=e.store?new Ad(e.store):void 0;return m&&await m.start(),new rl({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:y,isNested:o,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:m,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(([o])=>o in Td)&&(r=Array.from(new Map(r.map(o=>[o[0],o])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(o=>o[0]!==e);for(const[o,a]of r)this.checkpointPendingWrites.push([e,o,a]);const s=be(this.checkpointConfig,{[Ee]: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 i=this.tasks[e];i==null||i.cache_key==null||n[0][0]===ae||n[0][0]===j||this.cache.set([{key:[i.cache_key.ns,i.cache_key.key],value:i.writes,ttl:i.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]===j){if(s.path?.[0]===de&&s.path?.at(-1)===!0)return;const i=n.filter(o=>o[0]===j).flatMap(o=>o[1]);this._emit([["updates",{[j]:i}],["values",{[j]:i}]])}else n[0][0]!==ae&&this._emit(sn(Ve(_f(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(sn(Ve(Of([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([o,a])=>`ns:${o.join(",")}|key:${a}`,r=[],s={};for(const o of Object.values(this.tasks))o.cache_key!=null&&!o.writes.length&&(r.push([o.cache_key.ns,o.cache_key.key]),s[n([o.cache_key.ns,o.cache_key.key])]=o);if(r.length===0)return[];const i=await this.cache.get(r);for(const{key:o,value:a}of i){const l=s[n(o)];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,Jr].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new St;if(Object.values(this.tasks).every(i=>i.writes.length>0)){const i=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=he(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const o=await ze(Ve(zr(this.outputKeys,i,this.channels),"values"));if(this._emit(o),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),On(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new St;this.config.configurable?.[We]!==void 0&&delete this.config.configurable?.[We]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=bt(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 ze(Ve(If(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[i,o,a]of this.checkpointPendingWrites){if(o===ae||o===j||o===ce)continue;const l=Object.values(this.tasks).find(c=>c.id===i);l&&l.writes.push([o,a])}for(const i of Object.values(this.tasks))i.writes.length>0&&this._outputWrites(i.id,i.writes,!0)}if(Object.values(this.tasks).every(i=>i.writes.length>0))return this.tick({inputKeys:n});if(On(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new St;const s=await ze(Ve($i(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(Ue)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=ut(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(Ve(zr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),it(e)&&!e.interrupts.length&&this._emit([["updates",{[j]:[]}],["values",{[j]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&On(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&&On(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(sn(Ve($i([s]),"tasks"))),this.debug&&tl(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const i=await this._matchCachedWrites();for(const{task:o}of i)this._outputWrites(o.id,o.writes,!0);return s}_suppressInterrupt(e){return it(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[Ye];if(r&&r.nullResume!==void 0&&this.putWrites(we,[[ce,r.nullResume]]),Y(this.input)){const o=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Ja)&&(this.config.configurable??={},this.config.configurable[Hn]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of wf(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new xi("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(o=>o[0]===we).map(o=>o.slice(1));s.length>0&&he(this.checkpoint,this.channels,[{name:Ie,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const i=Y(this.input)&&s.length>0;if(this.isResuming||i){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[j]={...this.checkpoint.versions_seen[j],[a]:l}}const o=await ze(Ve(zr(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=Jr;else if(i)await this._putCheckpoint({source:"input"}),this.input=In;else{const o=await ze(Za(e,this.input));if(o.length>0){const a=bt(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:Ie,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=In}else if(We in(this.config.configurable??{}))this.input=In;else throw new xi(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=be(this.config,{[We]: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,i=new Date().toISOString(),o=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:o,timestamp:i,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=i=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=be(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??""});const o={...this.checkpoint.channel_versions},a=Yn(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ur(i),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?.[ge]??{}}),this.checkpoint=nt(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=be(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??"",[bs]:this.checkpoint.id}),n={};for(const[r,s,i]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,i]);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===j||r===ce)continue;const i=Object.values(e).find(o=>o.id===n);i&&i.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function Wf(t){return Oe(t?.message)}var zf=class extends Yc{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&&(Xc(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,i,o,a){o&&(!i||!i.includes(Vd)&&!i.includes("nostream"))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:i,name:a,...o}])}handleLLMNewToken(t,e,n,r,s,i){const o=i?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(Wf(o)?this._emit(this.metadatas[n],o.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];Oe(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,i,o,a){if(i!==void 0&&a===i.langgraph_node&&(s===void 0||!s.includes(G))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...i}],typeof e=="object")){for(const l of Object.values(e))if((Oe(l)||mi(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(Oe(c)||mi(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(Oe(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)Oe(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(Oe(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)Oe(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const Hf=500,Gf=2,Kf=128e3,Jf=3,qf=[400,401,402,403,404,405,406,407,409],Yf=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&&qf.includes(+e)||t?.error?.code==="insufficient_quota")};async function sl(t,e,n,r){const s=t.retry_policy??e;let i=s!==void 0?s.initialInterval??Hf:0,o=0,a,l,{config:c}=t;for(n&&(c=be(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,$d(a)){const y=c?.configurable?.checkpoint_ns,p=a.command;if(p.graph===y){for(const S of t.writers)await S.invoke(p,c);a=void 0;break}else if(p.graph===K.PARENT){const S=Jd(y);a.command=new K({...a.command,graph:S})}}if(zn(a)||s===void 0||(o+=1,o>=(s.maxAttempts??Jf))||!(s.retryOn??Yf)(a))break;i=Math.min(s.maxInterval??Kf,i*(s.backoffFactor??Gf));const d=s.jitter?Math.floor(i+Math.random()*1e3):i;await new Promise(y=>setTimeout(y,d));const f=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${i.toFixed(2)}ms (attempt ${o}) after ${f}: ${a}`),c=be(c,{[We]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const Es=Symbol.for("promiseAdded");function Xf(){const t={next:()=>{},wait:Promise.resolve(Es)};function e(n){t.next=()=>{t.wait=new Promise(e),n(Es)}}return t.wait=new Promise(e),t}var Zf=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,i=new Set;let o;const a=new AbortController,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(y=>y.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:y,error:p,signalAborted:S}of f)this._commit(y,p),it(p)||zn(p)&&!it(o)?o=p:p&&(i.size===0||!S)&&(a.abort(),i.add(p));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(y=>y.writes).flat()),i.size===1)throw Array.from(i)[0];if(i.size>1)throw new AggregateError(Array.from(i),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(it(o)||zn(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[Ai]??{},s=r.externalAbortSignal??n,i=e??r.timeoutAbortSignal,{signal:o,dispose:a}=mr(s,i,t),l={externalAbortSignal:s,timeoutAbortSignal:i,composedAbortSignal:o};return this.loop.config=be(this.loop.config,{[Ai]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},i=Xf(),o={},a={executingTasksMap:o,barrier:i,retryPolicy:n,scheduleTask:async(d,f,y)=>this.loop.acceptPush(d,f,y)};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(o).length>0)&&t.length;){for(;Object.values(o).length<(r??t.length)&&l<t.length;l+=1){const f=t[l];o[f.id]=sl(f,n,{[ni]:il?.bind(a,this,f)},s?.composedAbortSignal).catch(y=>({task:f,error:y,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(o),...h?[h]:[],i.wait]);d!==Es&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete o[d.task.id])}}_commit(t,e){if(e!==void 0)if(it(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[j,s]),r=t.writes.filter(s=>s[0]===ce);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else zn(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[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([ri,null]),this.loop.putWrites(t.id,t.writes)}};async function il(t,e,n,r,s,i={}){const o=e.config?.configurable?.[Ye];if(!o)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=o.callCounter;o.callCounter+=1;const l=new Sf({func:n,name:r,input:s,cache:i.cache,retry:i.retry,callbacks:i.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],y=f instanceof Error?f:new Error(String(f));return Promise.reject(y)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=sl(c,i.retry,{[ni]:il.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 Pe=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function Qf({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:i,interruptBeforeNodes:o}){if(!e)throw new Pe("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===j)throw new Pe(`"Node name ${j} is reserved"`);if(u.constructor===bn)u.triggers.forEach(h=>a.add(h));else throw new Pe(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Pe(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Pe(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Pe(`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 Pe(`Output channel '${String(c)}' not in channels`);if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Pe(`Node ${String(c)} not in nodes`)}if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Pe(`Node ${String(c)} not in nodes`)}}function Di(t,e){if(Array.isArray(t)){for(const n of t)if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}else if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}var ep=class ol extends dt{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 Q;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},tp=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(o=>[o,o]));const i=Array.isArray(t)?t:[t];return new bn({channels:s,triggers:i,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:lt,skipNone:!1});for(const[r,s]of Object.entries(e??{}))ee.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:lt,skipNone:!0,mapper:Wt(s)}):n.push({channel:r,value:s,skipNone:!1});return new se(n)}},np=class extends ee{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)}},rp=class extends np{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,ye in this.channels&&"lc_graph_name"in this.channels[ye]&&this.channels[ye].lc_graph_name!=="Topic")throw new Error(`Channel '${ye}' is reserved and cannot be used in the graph.`);this.channels[ye]=new ep({accumulate:!1}),this.autoValidate=t.autoValidate??this.autoValidate,this.streamMode=e??this.streamMode,this.inputChannels=t.inputChannels,this.outputChannels=t.outputChannels,this.streamChannels=t.streamChannels??this.streamChannels,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.stepTimeout=t.stepTimeout??this.stepTimeout,this.debug=t.debug??this.debug,this.checkpointer=t.checkpointer,this.retryPolicy=t.retryPolicy,this.config=t.config,this.store=t.store,this.cache=t.cache,this.name=t.name,this.triggerToNodes=t.triggerToNodes??this.triggerToNodes,this.userInterrupt=t.userInterrupt,this.autoValidate&&this.validate()}withConfig(t){const e=Re(this.config,t);return new this.constructor({...this,config:e})}validate(){Qf({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 i of s){const o=Xa(i);if(o!==void 0){if(n===t){yield[n,o];return}if(t===void 0&&(yield[n,o]),e){let a=t;t!==void 0&&(a=t.slice(n.length+1));for(const[l,c]of o.getSubgraphs(a,e))yield[`${n}${J}${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===we).map(([d,f,y])=>[String(f),y]);h.length>0&&he(e.checkpoint,s,[{name:Ie,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const i=Object.values(bt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),o=await ze(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of i){const d=o.find(([y])=>y===h.name);if(!d)continue;let f=`${String(h.name)}${Ue}${h.id}`;if(a&&(f=`${a}${J}${f}`),n===void 0){const y={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=y}else{const y={configurable:{[H]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=d[1];l[h.id]=await p.getState(y,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(i.map(f=>[f.id,f]));for(const[f,y,p]of e.pendingWrites)[ae,j,Ln].includes(y)||f in h&&h[f].writes.push([String(y),p]);const d=i.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=i.filter(h=>h.writes.length===0).map(h=>h.name);return{values:ut(s,this.streamChannelsAsIs),next:u,tasks:el(i,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:et(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(pt(t,{[H]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Re(this.config,t),i=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:i,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 i=Vr(r);for await(const[o,a]of this.getSubgraphsAsync(i,!0))if(o===i){yield*a.getStateHistory(pt(t,{[H]:n}),e);return}throw new Error(`Subgraph with namespace "${i}" not found.`)}const s=Re(this.config,t,{configurable:{checkpoint_ns:r}});for await(const i of n.list(s,e))yield this._prepareStateSnapshot({config:i.config,saved:i})}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(o=>o.updates.length===0))throw new Error("No updates provided");const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const o=Vr(r);for await(const[,a]of this.getSubgraphsAsync(o,!0))return await a.bulkUpdateState(pt(t,{[H]:n}),e);throw new Error(`Subgraph "${o}" not found`)}const s=async(o,a)=>{const l=this.config?Re(this.config,o):o,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=pt(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),y=l.metadata??{};c?.config.configurable&&(f=pt(l,c.config.configurable),y={...c.metadata,...y});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 _=await n.put(f,nt(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return et(_,c?c.metadata:void 0)}const C=hr(this.channels,u);if(p===null&&S===M){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const v=bt(u,c.pendingWrites||[],this.nodes,C,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),A=(c.pendingWrites||[]).filter(E=>E[0]===we).map(E=>E.slice(1));A.length>0&&he(u,C,[{name:Ie,writes:A,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[E,P,$]of c.pendingWrites||[])[ae,j,Ln].includes(P)||E in v&&v[E].writes.push([P,$]);he(u,C,Object.values(v),n.getNextVersion.bind(n),this.triggerToNodes)}const _=await n.put(f,nt(u,C,d),{...y,source:"update",step:d+1,parents:c?.metadata?.parents??{}},Yn(h,u.channel_versions));return et(_,c?c.metadata:void 0)}if(S===Dd){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 _=E=>!Array.isArray(E)||E.length===0?!1:E.every(P=>Array.isArray(P)&&P.length===2),v=nt(u,void 0,d),A=await n.put(c.parentConfig??pt(c.config,{checkpoint_id:void 0}),v,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(_(p)){const E=bt(v,c.pendingWrites,this.nodes,C,A,!1,{step:d+2}),P=Object.values(E).reduce((V,{name:X,id:Ar})=>(V[X]??=[],V[X].push({id:Ar}),V),{}),$=p.reduce((V,X)=>{const[Ar,en]=X;V[en]??=[];const jl=V[en].length,Ll=P[en]?.[jl]?.id;return V[en].push({values:Ar,asNode:en,taskId:Ll}),V},{});return s(et(A,c.metadata),Object.values($).flat())}return et(A,c.metadata)}if(S===Ie){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const _=await ze(Za(this.inputChannels,p));if(_.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);he(u,C,[{name:Ie,writes:_,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const v=c?.metadata?.step!=null?c.metadata.step+1:-1,A=await n.put(f,nt(u,C,v),{source:"input",step:v,parents:c?.metadata?.parents??{}},Yn(h,u.channel_versions));return await n.putWrites(A,_,yt(Ie,u.id)),et(A,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const _=bt(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(E=>E[0]===we).map(E=>E.slice(1));v.length>0&&he(c.checkpoint,C,[{name:Ie,writes:v,triggers:[]}],void 0,this.triggerToNodes);for(const[E,P,$]of c.pendingWrites)[ae,j,Ln].includes(P)||_[E]===void 0||_[E].writes.push([P,$]);const A=Object.values(_).filter(E=>E.writes.length>0);A.length>0&&he(u,C,A,void 0,this.triggerToNodes)}const m=Object.values(u.versions_seen).map(_=>Object.values(_)).flat().find(_=>!!_),w=[];if(a.length===1){let{values:_,asNode:v,taskId:A}=a[0];if(v===void 0&&Object.keys(this.nodes).length===1)[v]=Object.keys(this.nodes);else if(v===void 0&&m===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(v=this.inputChannels);else if(v===void 0){const E=Object.entries(u.versions_seen).map(([P,$])=>Object.values($).map(V=>[V,P])).flat().filter(([P,$])=>$!==j).sort(([P],[$])=>Pa(P,$));E&&(E.length===1?v=E[0][1]:E[E.length-1][0]!==E[E.length-2][0]&&(v=E[E.length-1][1]))}if(v===void 0)throw new B('Ambiguous update, specify "asNode"');w.push({values:_,asNode:v,taskId:A})}else for(const{asNode:_,values:v,taskId:A}of a){if(_==null)throw new B('"asNode" is required when applying multiple updates');w.push({values:v,asNode:_,taskId:A})}const b=[];for(const{asNode:_,values:v,taskId:A}of w){if(this.nodes[_]===void 0)throw new B(`Node "${_.toString()}" does not exist`);const E=this.nodes[_].getWriters();if(!E.length)throw new B(`No writers found for node "${_.toString()}"`);b.push({name:_,input:v,proc:E.length>1?Ze.from(E,{omitSequenceTags:!0}):E[0],writes:[],triggers:[j],id:A??yt(j,u.id),writers:[]})}for(const _ of b)await _.proc.invoke(_.input,ln({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[qe]:v=>_.writes.push(...v),[at]:(v,A=!1)=>Xn(u,C,_,v,A)}}));for(const _ of b){const v=_.writes.filter(A=>A[0]!==de);c!==void 0&&v.length>0&&await n.putWrites(f,v,_.id)}he(u,C,b,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const T=Yn(h,u.channel_versions),x=await n.put(f,nt(u,C,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},T);for(const _ of b){const v=_.writes.filter(A=>A[0]===de);v.length>0&&await n.putWrites(x,v,_.id)}return et(x,c?c.metadata:void 0)};let i=t;for(const{updates:o}of e)i=await s(i,o);return i}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:i,interruptBefore:o,...a}=t;let l=!0;const c=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:Di(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Di(h,this.channels);const d=o??this.interruptBefore??[],f=i??this.interruptAfter??[];let y;n!==void 0?(y=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[cn]!==void 0?y=["values"]:y=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 m=(()=>{if(t.checkpointDuring!=null)return t.checkpointDuring===!1?"exit":"async"})(),w=t.durability??m??t?.configurable?.[Ua]??"async";return[c,y,h,u,a,d,f,p,S,l,C,w]}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 Ri(e?.encoding==="text/event-stream"?Df(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:vf(this.config?.callbacks,e?.callbacks),signal:mr(e?.signal,r.signal).signal};return new Ri(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 i=await this._validateInput(t),{runId:o,...a}=s,[l,c,,u,h,d,f,y,p,S,C,m]=this._defaults(a);typeof h.context<"u"?h.context=await this._validateContext(h.context):h.configurable=await this._validateContext(h.configurable);const w=new nl({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[Ee]??"";h.configurable[Ee]=P.split(J).map($=>$.split(Ue)[0]).join(J)}if(c.includes("messages")){const P=new zf(V=>w.push(V)),{callbacks:$}=h;if($===void 0)h.callbacks=[P];else if(Array.isArray($))h.callbacks=$.concat(P);else{const V=$.copy();V.addHandler(P,!0),h.callbacks=V}}h.writer??=P=>{if(!c.includes("custom"))return;const $=Kd()?.configurable?.[Ee]?.split(J).slice(0,-1);w.push([$??[],"custom",P])},h.interrupt??=this.userInterrupt??qa;const T=await(await Zc(h))?.handleChainStart(this.toJSON(),bf(t,"input"),o,void 0,void 0,void 0,h?.runName??this.getName()),x=ei(this.channels);let _,v;const E=(async()=>{try{_=await Bf.initialize({input:i,config:h,checkpointer:y,nodes:this.nodes,channelSpecs:x,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:C,stream:w,interruptAfter:f,interruptBefore:d,manager:T,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:m});const P=new Zf({loop:_,nodeFinished:h.configurable?.[Fd]});e?.subgraphs&&(_.config.configurable={..._.config.configurable,[dr]:_.stream}),await this._runLoop({loop:_,runner:P,debug:l,config:h}),m==="sync"&&await Promise.all(_?.checkpointerPromises??[])}catch(P){v=P}finally{try{_&&(await _.store?.stop(),await _.cache?.stop()),await Promise.all(_?.checkpointerPromises??[])}catch(P){v=v??P}v?w.error(v):w.close()}})();try{for await(const P of w){if(P===void 0)throw new Error("Data structure error.");const[$,V,X]=P;if(c.includes(V)){if(n==="text/event-stream"){r?yield[$,V,X]:yield[null,V,X];continue}r&&!S?yield[$,V,X]:S?r?yield[$,X]:yield X:yield[V,X]}}}catch(P){throw await T?.handleChainError(v),P}finally{await E}await T?.handleChainEnd(_?.output??{},o,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=[],i=await this.stream(t,r),o=[];let a;for await(const l of i)n==="values"?Fa(l)?o.push(l[j]):a=l:s.push(l);if(n==="values"){if(o.length>0){const l=o.flat(1);if(a==null)return{[j]:l};if(typeof a=="object")return{...a,[j]:l}}return a}return s}async _runLoop(t){const{loop:e,runner:n,debug:r,config:s}=t;let i;try{for(;await e.tick({inputKeys:this.inputChannels});){for(const{task:o}of await e._matchCachedWrites())e._outputWrites(o.id,o.writes,!0);r&&$f(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:(o,a)=>{r&&Rf(o,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new Id([`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(o){if(i=o,!await e.finishAndHandleError(i))throw o}finally{i===void 0&&await e.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Jt=class al extends dt{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 Q;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Q;return this.value[0]}isAvailable(){return this.value.length!==0}},ll=class{path;ends;constructor(t){ee.isRunnable(t.path)?this.path=t.path:this.path=Wt(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 se.registerWriter(new ft({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.
42
+ 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 i;if(this.ends?i=s.map(a=>pe(a)?a:this.ends[a]):i=s,i.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(i.filter(pe).some(a=>a.node===M))throw new B("Cannot send a packet to the END node");return await n(i,e)??t}},sp=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,i]of n){for(const a of[J,Ue])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===M)throw new Error(`Node \`${r}\` is reserved.`);const o=Wt(s);this.nodes[r]={runnable:o,metadata:i?.metadata,subgraphs:ii(o)?[o]:i?.subgraphs,ends:i?.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===M)throw new Error("END cannot be a start node");if(e===L)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."),!ee.isRunnable(r.path)){const i=Array.isArray(r.pathMap)?r.pathMap.join(","):Object.keys(r.pathMap??{}).join(",");r.path=Wt(r.path).withConfig({runName:`Branch<${r.source}${i!==""?`,${i}`:""}>`.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(L,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,M)}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:{[L]:new Jt,[M]:new Jt},inputChannels:L,outputChannels:M,streamChannels:[],streamMode:"values",name:r});for(const[i,o]of Object.entries(this.nodes))s.attachNode(i,o);for(const[i,o]of this.edges)s.attachEdge(i,o);for(const[i,o]of Object.entries(this.branches))for(const[a,l]of Object.entries(o))s.attachBranch(i,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!==L&&!(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 i of Object.values(s))if(i.ends!=null)for(const o of Object.values(i.ends))n.add(o);else{n.add(M);for(const o of Object.keys(this.nodes))o!==r&&n.add(o)}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 Rd([`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(`
43
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==M&&!(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 rp{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new Jt,this.nodes[t]=new bn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new se([{channel:t,value:lt}],[G])),this.streamChannels.push(t)}attachEdge(t,e){if(e===M){if(t===L)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new se([{channel:M,value:lt}],[G]))}else this.nodes[e].triggers.push(t),this.nodes[e].channels.push(t)}attachBranch(t,e,n){t===L&&!this.nodes[L]&&(this.nodes[L]=tp.subscribeTo(L,{tags:[G]})),this.nodes[t].pipe(n.run(s=>{const i=s.map(o=>pe(o)?o:{channel:o===M?M:`branch:${t}:${e}:${o}`,value:lt});return new se(i,[G])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==M){const i=`branch:${t}:${e}:${s}`;this.channels[i]=new Jt,this.nodes[s].triggers.push(i),this.nodes[s].channels.push(i)}}async getGraphAsync(t){const e=t?.xray,n=new gi,r={[L]:n.addNode({schema:ve()},L)},s={};let i={};e&&(i=Object.fromEntries((await ze(this.getSubgraphsAsync())).filter(l=>Ui(l[1]))));function o(l,c,u,h=!1){if(c===M&&s[M]===void 0&&(s[M]=n.addNode({schema:ve()},M)),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,y=i[l]!==void 0?await i[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let C=function(w){return w?w.lc_runnable:!1},m=function(w,b){if(w!==void 0&&!yi(w))return w;if(C(b))try{let T=b.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return b.getName()}else return b.name??"UnknownSchema"};const[p,S]=n.extend(y,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:m(S.id,S.data),...S}),s[u]={name:m(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)o(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)])),[M]:M};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,y]of Object.entries(d))o(te(l),te(y),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)o(te(l),te(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new gi,r={[L]:n.addNode({schema:ve()},L)},s={};let i={};e&&(i=Object.fromEntries(sn(this.getSubgraphs()).filter(l=>Ui(l[1]))));function o(l,c,u,h=!1){return c===M&&s[M]===void 0&&(s[M]=n.addNode({schema:ve()},M)),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,y=i[l]!==void 0?i[l].getGraph({...t,xray:f}):h.getGraph(t);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let C=function(w){return w?w.lc_runnable:!1},m=function(w,b){if(w!==void 0&&!yi(w))return w;if(C(b))try{let T=b.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return b.getName()}else return b.name??"UnknownSchema"};const[p,S]=n.extend(y,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);S!==void 0&&(r[u]={name:m(S.id,S.data),...S}),s[u]={name:m(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)o(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)])),[M]:M};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,y]of Object.entries(d))o(te(l),te(y),f,!0)}}return n}};function Ui(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function te(t){return t==="subgraph"?`"${t}"`:t}const ot=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var ip=class ul extends dt{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(!ot(this.names,this.seen))throw new Q}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&ot(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&ot(this.names,this.seen)}},op=class hl extends dt{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||!ot(this.names,this.seen))throw new Q}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&ot(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&ot(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&ot(this.names,this.seen)}};const ap="lg:";var lp=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=wi(t);for(const[r,s]of Object.entries(n)){const i=this.get(s);i?.reducer?e[r]=new ys(i.reducer.fn,i.default):e[r]=new ti}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,i])=>i===!0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${i}:${o}`).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 i=Object.entries(wi(t)).map(([o,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=ns(c)??ns(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${ap}${h}`)}return[o,c]});s=Qc(t,Object.fromEntries(i)),eu(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=js(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const qt=new lp;function Yt(t,e){if(e.reducer&&!e.default){const n=Rs(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return qt.extend(n,()=>e),n}else return qt.extend(t,()=>e),t}const je="__root__",xs=Symbol.for("langgraph.state.partial");var cp=class extends sp{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=qt;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),gp(t)){const r=this._metaRegistry.getChannelsForSchema(t.state),s=t.input!=null?this._metaRegistry.getChannelsForSchema(t.input):r,i=t.output!=null?this._metaRegistry.getChannelsForSchema(t.output):r;this._schemaDefinition=r,this._schemaRuntimeDefinition=t.state,this._inputDefinition=s,this._inputRuntimeDefinition=t.input??xs,this._outputDefinition=i,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=xs,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(mp(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(pp(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(dp(t)||Fi(t)){const r=Fi(t)?t.spec:t;this._schemaDefinition=r}else if(fp(t)){const r=up(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,i]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[J,Ue])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===M||r===L)throw new Error(`Node \`${r}\` is reserved.`);let o=this._schemaDefinition;i?.input!==void 0&&(fe(i.input)?o=this._metaRegistry.getChannelsForSchema(i.input):i.input.spec!==void 0&&(o=i.input.spec)),o!==void 0&&this._addSchema(o);let a;ee.isRunnable(s)?a=s:typeof s=="function"?a=new ft({func:s,name:r,trace:!1}):a=Wt(s);let l=i?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:i?.retryPolicy,cachePolicy:l,metadata:i?.metadata,input:o??this._schemaDefinition,subgraphs:ii(a)?[a]:i?.subgraphs,ends:i?.ends,defer:i?.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===M)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===M)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,i]of e){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const o=r;this.addNode(o,s,i),n!=null&&this.addEdge(n,o),n=o}return this}compile({checkpointer:t,store:e,cache:n,interruptBefore:r,interruptAfter:s,name:i,description:o}={}){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]===je?je:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===je?je:c,h=this._interrupt,d=new hp({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[L]:new Jt},inputChannels:L,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:i,description:o,userInterrupt:h});d.attachNode(L);for(const[f,y]of Object.entries(this.nodes))d.attachNode(f,y);d.attachBranch(L,Mi,Vi(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,Mi,Vi(),{withReader:!1});for(const[f,y]of this.edges)d.attachEdge(f,y);for(const[f,y]of this.waitingEdges)d.attachEdge(f,y);for(const[f,y]of Object.entries(this.branches))for(const[p,S]of Object.entries(y))d.attachBranch(f,p,S);return d.validate()}};function up(t){const e={};for(const[n,r]of Object.entries(t))e[n]=_s(r);return e}var hp=class extends cl{description;_metaRegistry=qt;constructor({description:t,...e}){super(e),this.description=t}attachNode(t,e){let n;t===L?n=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):n=Object.keys(this.builder.channels);function r(a){if(Y(a))return a.graph===K.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(l=>Y(l))){const l=[];for(const c of a)if(Y(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples())}else l.push([je,c]);return l}else if(a!=null)return[[je,a]];return null}const s=t;function i(a){if(a){if(Y(a))return a.graph===K.PARENT?null:a._updateAsTuples().filter(([l])=>n.includes(l));if(Array.isArray(a)&&a.length>0&&a.some(Y)){const l=[];for(const c of a)if(Y(c)){if(c.graph===K.PARENT)continue;l.push(...c._updateAsTuples().filter(([u])=>n.includes(u)))}else{const u=i(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 o=[{value:lt,mapper:new ft({func:n.length&&n[0]===je?r:i,trace:!1,recurse:!1})}];if(t===L)this.nodes[t]=new bn({tags:[G],triggers:[L],channels:[L],writers:[new se(o,[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&&je in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new jd:new Jt(!1),this.nodes[t]=new bn({triggers:[u],channels:c?Object.keys(l):l,writers:[new se(o,[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!==M){if(typeof t=="string")this.nodes[t].writers.push(new se([{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 op(new Set(t)):new ip(new Set(t)),this.nodes[e].triggers.push(n);for(const r of t)this.nodes[r].writers.push(new se([{channel:n,value:r}],[G]))}}}attachBranch(t,e,n,r={withReader:!0}){const s=async(i,o)=>{const a=i.filter(c=>c!==M);if(!a.length)return;const l=a.map(c=>pe(c)?c:{channel:c===M?c:`branch:to:${c}`,value:t});await se.doWrite({...o,tags:(o.tags??[]).concat([G])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?i=>gf.doRead(i,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=i=>{if(i!=null)return this._metaRegistry.getExtendedChannelSchemas(i,{withReducerSchema:!0})};if(fe(n))return s(n);if(n===xs)return js(s(r))})();if(Y(t)){const n=t;return t.update&&e!=null&&(n.update=Ke(e,t.update)),n}return e!=null?Ke(e,t):t}isInterrupted(t){return Fa(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return fe(e)&&Ke(e,t),t}};function dp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Ra(e))}function Fi(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function fp(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function pp(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function mp(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function gp(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 yp(t){if(pe(t))return[t];const e=[];Y(t)?e.push(t):Array.isArray(t)&&e.push(...t.filter(Y));const n=[];for(const r of e){if(r.graph===K.PARENT)throw new $a(r);pe(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Vi(){const t=new ft({func:yp,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(pn),i=r.map(pn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=tr(),u.lc_kwargs.id=u.id);let o;for(let u=0;u<i.length;u+=1){const h=i[u];(h.id===null||h.id===void 0)&&(h.id=tr(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===dl&&(o=u)}if(o!=null)return i.slice(o+1);const a=[...s],l=new Map(a.map((u,h)=>[u.id,h])),c=new Set;for(const u of i){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))}ws.Root({messages:ws({reducer:fl,default:()=>[]})});const gr={reducer:{fn:fl},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};W({messages:Yt(le(),gr)});Od();const As=Symbol.for("langgraph-zod");As in globalThis||(globalThis[As]=new WeakSet);function Bi(t){const e=globalThis[As];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Yt(n,{jsonSchemaExtra:r})},reducer(r,s){const i=Rs(n);return Yt(n,{default:i,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Bi(tu.prototype),Bi(Bl.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 wp=class extends Wl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Rs(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new wp(qt);function _p(t=!0,e,n=[]){const r={messages:Yt(le(),gr),jumpTo:Me([vt("model_request"),vt("tools"),vt("end"),nu()]).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=Ls().optional());const i=W(r);return qt.getChannelsForSchema(i)}W({llmInputMessages:Yt(le(),{reducer:{fn:(t,e)=>gr.reducer.fn([],e)},default:()=>[]}),messages:Yt(le(),gr)});const Wi="prompt",qr=/<name>(.*?)<\/name>/s,Yr=/<content>(.*?)<\/content>/s;function bp(t){if(!N.isInstance(t)||Vt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new N({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new N({...t.lc_kwargs,content:n,name:void 0})}function vp(t){if(!N.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(qr),i=r.text.match(Yr);return s&&(!i||i[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(qr),i=r.text.match(Yr);return!s||!i?r:(n=s[1],{...r,text:i[1]})}return r});else{const r=t.content,s=r.match(qr),i=r.match(Yr);if(!s||!i)return t;n=s[1],e=i[1]}return new N({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function z(t){return ee.isRunnable(t)}function zi(t){return Us(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const Xr=(t,e,n={})=>{if(zi(t))return t.bindTools(e,n);if(xe.isRunnableBinding(t)&&zi(t.bound)){const r=t.bound.bindTools(e,n);return xe.isRunnableBinding(r)?new xe({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new xe({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(Ze.isRunnableSequence(e)&&(e=e.steps.find(n=>xe.isRunnableBinding(n))||e),!ir(e)){if(xe.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 ss}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new ss}}function Ms(t){return!!(N.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Sp(t){let e;if(t==null)e=Bt.from(n=>n.messages).withConfig({runName:Wi});else if(typeof t=="string"){const n=new _e(t);e=Bt.from(r=>[n,...r.messages??[]]).withConfig({runName:Wi})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function Cp(t,e,n={}){const r=Xr(t,e,n);if(r)return r;if(ir(t)){const s=Xr(await t._model(),e,n);if(s)return s}if(Ze.isRunnableSequence(t)){const s=t.steps.findIndex(i=>xe.isRunnableBinding(i)||Us(i)||ir(i));if(s>=0){const i=Xr(t.steps[s],e,n);if(i){const o=t.steps.slice();return o.splice(s,1,i),Ze.from(o)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Tp(t){if(t.length===0)return;if(t.length===1)return t[0];function e(r,s){return async(i,o)=>r(i,async()=>s(i,async()=>o(i)))}let n=t[t.length-1];for(let r=t.length-2;r>=0;r--)n=e(t[r],n);return n}function kp(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return Tp(e.map(n=>{const r=n.wrapToolCall;return async(i,o)=>{try{const a=await r({...i,state:{messages:i.state.messages,...n.stateSchema?Ke(n.stateSchema,{...i.state}):{}}},o);if(!U.isInstance(a)&&!Y(a))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof a}`);return a}catch(a){throw a instanceof Error&&!a.message.includes(`middleware "${n.name}"`)&&(a.message=`Error in middleware "${n.name}": ${a.message}`),a}}}))}async function Ep(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=ru(r.stateSchema,a=>a.startsWith("_")),i=await su(s,e);if(i.success){Object.assign(n,i.data);continue}const o=i.error.issues.filter(a=>a.code==="invalid_type"&&a.message==="Required").map(a=>` - ${a.path.join(".")}: ${a.message}`).join(`
44
+ `);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
45
45
  ${o}
46
46
 
47
47
  To fix this, either:
@@ -59,9 +59,9 @@ To fix this, either:
59
59
  agent.invoke({
60
60
  messages: [...],
61
61
  ${i.error.issues[0]?.path.join(".")}: "value"
62
- })`)}return n}function vp(t){const e={messages:le(()=>[]),structuredResponse:Lr().optional()};if(!t)return W(e);const{shape:n}=t,s={...e};for(const[r,i]of Object.entries(n))r.startsWith("_")?s[r]=i.optional():s[r]=i;return W(s)}function Ne(t){if(t){if(["model_request","tools",M].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return M;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 li=class extends ee{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=$e(this.config,e),s=await Le.runWithConfig(n,async()=>this.func(t,n));return ee.isRunnable(s)&&this.recurse?await Le.runWithConfig(n,async()=>s.invoke(t,n)):(this.#e=s,s)}};function Sp(t,e){let n,s;if(e==="inline")n=pp,s=mp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function r(i){return i.map(n)}return Ze.from([Bt.from(r),t,Bt.from(s)])}var Cp=class extends li{#e;constructor(t){super({name:t.name??"model",func:(e,n)=>this.#r(e,n)}),this.#e=t}#n(t){if(!this.#e.responseFormat)return;const e=wo(this.#e.responseFormat,void 0,t);return e.every(s=>s instanceof rt)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(s=>s instanceof Be).reduce((s,r)=>(s[r.name]=r,s),{})}}async#r(t,e){const n=t.messages.at(-1);if(n&&U.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};const s=await this.#i(t,e);return"structuredResponse"in s?{messages:[...t.messages,...s.messages||[]],structuredResponse:s.structuredResponse}:s instanceof K?s:(s.name=this.name,s.lc_kwargs.name=this.name,this.#s(t,s)?{messages:[new N({content:"Sorry, need more steps to process this request.",name:this.name,id:s.id})]}:{messages:[s]})}#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#i(t,e,n={}){const s=await this.#t(),r=e,i=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),y={...e,signal:f},p=await h.invoke(d,y);if(u?.type==="native"){const w=u.strategy.parse(p);return w?{structuredResponse:w,messages:[p]}:p}if(!u||!p.tool_calls)return p;const S=p.tool_calls.filter(w=>w.name in u.tools);if(S.length===0)return p;if(S.length>1)return this.#a(p,S,u);const m=u.tools[S[0].name]?.options?.toolMessageContent;return this.#l(p,S[0],u,m??n.lastMessage)},o=this.#e.wrapModelCallHookMiddleware??[];let a=i;for(let c=o.length-1;c>=0;c--){const[u,h]=o[c];if(u.wrapModelCall){const d=a,f=u,y=h;a=async p=>{const S=f.contextSchema?Ke(f.contextSchema,r?.context||{}):r?.context,C=Object.freeze({context:S,writer:r.writer,interrupt:r.interrupt,signal:r.signal}),m={...p,state:{...u.stateSchema?Ke(jr(u.stateSchema),t):{},...y(),messages:t.messages},runtime:C},w=async b=>{const T=b.tools??[],x=T.filter(v=>H(v)&&!this.#e.toolClasses.some(A=>A.name===v.name));if(x.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${x.map(v=>v.name).join(", ")}. This is not supported.`);const _=T.filter(v=>H(v)&&this.#e.toolClasses.every(A=>A!==v));if(_.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${_.map(v=>v.name).join(", ")}. This is not supported.`);return d(b)};if(!f.wrapModelCall)return w(m);try{const b=await f.wrapModelCall(m,w);if(!N.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:s,systemPrompt:this.#e.systemPrompt,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:r?.context,writer:r.writer,interrupt:r.interrupt,signal:r.signal})};return a(l)}#a(t,e,n){const s=new ir(e.map(r=>r.name));return this.#o(s,t,e[0],n)}#l(t,e,n,s){const r=n.tools[e.name];try{const i=r.parse(e.args);return{structuredResponse:i,messages:[t,new U({tool_call_id:e.id??"",content:JSON.stringify(i),name:e.name}),new N(s??`Returning structured response: ${JSON.stringify(i)}`)]}}catch(i){return this.#o(i,t,e,n)}}async#o(t,e,n,s){const r=Object.values(s.tools).at(0)?.options?.handleError,i=n.id;if(!i)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(typeof r=="boolean"&&r||Array.isArray(r)&&r.some(o=>o instanceof ir))return new K({update:{messages:[e,new U({content:t.message,tool_call_id:i})]},goto:"model"});if(typeof r=="string")return new K({update:{messages:[e,new U({content:r,tool_call_id:i})]},goto:"model"});if(typeof r=="function"){const o=await r(t);if(typeof o!="string")throw new Error("Error handler must return a string.");return new K({update:{messages:[e,new U({content:o,tool_call_id:i})]},goto:"model"})}throw t}#s(t,e){const n=N.isInstance(e)&&e.tool_calls?.every(r=>this.#e.shouldReturnDirect.has(r.name)),s="remainingSteps"in t?t.remainingSteps:void 0;return!!(s&&(s<1&&n||s<2&&Mr(t.messages.at(-1))))}#c(t){const{messages:e,llmInputMessages:n,...s}=t;return n&&n.length>0?{messages:n,...s}:{messages:e,...s}}async#u(t,e,n){const s={},r=Object.values(n&&"tools"in n?n.tools:{}),i=[...e?.tools??this.#e.toolClasses,...r.map(c=>c.tool)],o=e?.toolChoice||(r.length>0?"any":void 0);if(n?.type==="native"){const c={name:n.strategy.schema?.name??"extract",description:nr(n.strategy.schema),schema:n.strategy.schema,strict:!0};Object.assign(s,{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 yp(t,i,{...s,...e?.modelSettings??{},tool_choice:o});return gp(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?Sp(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),Tp=t=>typeof t=="object"&&t!=null&&"messages"in t&&ml(t.messages),kp=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Ep(t,e){return t instanceof Dr?new U({content:t.message,tool_call_id:e.id,name:e.name}):new U({content:`${t}
63
- Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var xp=class extends li{tools;trace=!1;signal;handleToolErrors=Ep;wrapToolCall;constructor(t,e){const{name:n,tags:s,handleToolErrors:r,signal:i,wrapToolCall:o}=e??{};super({name:n,tags:s,func:(a,l)=>this.run(a,l)}),this.options=e,this.tools=t,this.handleToolErrors=r??this.handleToolErrors,this.signal=i,this.wrapToolCall=o}#e(t,e,n){if(it(t)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){const s=this.handleToolErrors(t,e);if(s&&U.isInstance(s))return s;throw t}else if(this.handleToolErrors)return new U({name:e.name,content:`${t}
64
- Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,n){const s=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)||Y(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 nu?new Dr(h,c):h}},r=e,i={context:r?.context,writer:r?.writer,interrupt:r?.interrupt,signal:r?.signal},o=this.tools.find(l=>l.name===t.name);if(!o)throw new Error(`Tool "${t.name}" not found.`);const a={toolCall:t,tool:o,state:n,runtime:i};if(this.wrapToolCall)try{return await this.wrapToolCall(a,s)}catch(l){return this.#e(l,t,!0)}try{return await s(a)}catch(l){return this.#e(l,t,!1)}}async run(t,e){let n;if(kp(t)){const{lg_tool_call:i,jumpTo:o,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let i;if(ml(t))i=t;else if(Tp(t))i=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const o=new Set(i.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=i.length-1;l>=0;l-=1){const c=i[l];if(N.isInstance(c)){a=c;break}}if(!N.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!o.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(Y))return Array.isArray(t)?n:{messages:n};const s=[];let r=null;for(const i of n)Y(i)?i.graph===K.PARENT&&Array.isArray(i.goto)&&i.goto.every(o=>Ap(o))?r?r.goto.push(...i.goto):r=new K({graph:K.PARENT,goto:i.goto}):s.push(i):s.push(Array.isArray(t)?[i]:{messages:[i]});return r&&s.push(r),s}};function Ap(t){return t instanceof se}var Mp=class{},Pp=class{},Es=class extends li{#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=Ke(this.middleware.contextSchema,c)}}const s={...this.#e.getState(),...t,messages:t.messages},r={context:n,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},i=await this.runHook(s,Object.freeze(Object.assign(new Pp,{...r,context:Object.freeze(Object.assign(new Mp,n))})));if(!i)return{...s,jumpTo:void 0};let o,a;if(this.name?.startsWith("BeforeAgentNode_")?(o=ze(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(o=ze(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(o=ze(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(o=ze(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof i.jumpTo=="string"&&!o?.includes(i.jumpTo)){const l=o&&o.length>0?`must be one of: ${o?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${i.jumpTo}, ${l}.`)}if(typeof i=="object"&&"type"in i){if(i.type==="terminate"){if(i.error)throw i.error;return{...s,...i.result||{},jumpTo:i.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(i)}`)}return{...s,...i,jumpTo:i.jumpTo}}get nodeOptions(){return{input:vp(this.middleware.stateSchema)}}},Np=class extends Es{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(n,s)=>this.invokeMiddleware(n,s)},e),this.middleware=t}runHook(t,e){return Cs(this.middleware.beforeAgent)(t,e)}},Op=class extends Es{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(n,s)=>this.invokeMiddleware(n,s)},e),this.middleware=t}runHook(t,e){return Cs(this.middleware.beforeModel)(t,e)}},Ip=class extends Es{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(n,s)=>this.invokeMiddleware(n,s)},e),this.middleware=t}runHook(t,e){return Cs(this.middleware.afterModel)(t,e)}},Rp=class extends Es{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(n,s)=>this.invokeMiddleware(n,s)},e),this.middleware=t}runHook(t,e){return Cs(this.middleware.afterAgent)(t,e)}},$p=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((s,r)=>({...s,...r.getState()??{}}),{});return delete n.jumpTo,n}},jp=class{#e;#n="v2";#r;#t=new $p;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(m=>m.tools).flatMap(m=>m.tools)??[],n=[...t.tools??[],...e],s=new Set(n.filter(H).filter(m=>"returnDirect"in m&&m.returnDirect).map(m=>m.name)),r=fp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),o=new sp(r,this.options.contextSchema),a=[],l=[],c=[],u=[],h=[];this.#r=new Cp({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:s,signal:this.options.signal,wrapModelCallHookMiddleware:h});const d=new Set,f=this.options.middleware??[];for(let m=0;m<f.length;m++){let w,b,T,x;const _=f[m];if(d.has(_.name))throw new Error(`Middleware ${_.name} is defined multiple times`);if(d.add(_.name),_.beforeAgent){w=new Np(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,w);const v=`${_.name}.before_agent`;a.push({index:m,name:v,allowed:ze(_.beforeAgent)}),o.addNode(v,w,w.nodeOptions)}if(_.beforeModel){b=new Op(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,b);const v=`${_.name}.before_model`;l.push({index:m,name:v,allowed:ze(_.beforeModel)}),o.addNode(v,b,b.nodeOptions)}if(_.afterModel){T=new Ip(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,T);const v=`${_.name}.after_model`;c.push({index:m,name:v,allowed:ze(_.afterModel)}),o.addNode(v,T,T.nodeOptions)}if(_.afterAgent){x=new Rp(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,x);const v=`${_.name}.after_agent`;u.push({index:m,name:v,allowed:ze(_.afterAgent)}),o.addNode(v,x,x.nodeOptions)}_.wrapModelCall&&h.push([_,()=>this.#t.getState(_.name)])}if(o.addNode("model_request",this.#r),n.filter(H).length>0){const m=new xp(n.filter(H),{signal:this.options.signal,wrapToolCall:_p(f)});o.addNode("tools",m)}let y;a.length>0?y=a[0].name:l.length>0?y=l[0].name:y="model_request";const p=l.length>0?l[0].name:"model_request",S=u.length>0?u[u.length-1].name:M;o.addEdge(L,y);for(let m=0;m<a.length;m++){const w=a[m],b=w.name,x=m===a.length-1?p:a[m+1].name;if(w.allowed&&w.allowed.length>0){const _=n.filter(H).length>0,v=w.allowed.map(E=>Ne(E)).filter(E=>E!=="tools"||_),A=Array.from(new Set([x,...v.map(E=>E===M?S:E)]));o.addConditionalEdges(b,this.#c(n.filter(H),x,S),A)}else o.addEdge(b,x)}for(let m=0;m<l.length;m++){const w=l[m],b=w.name,x=m===l.length-1?"model_request":l[m+1].name;if(w.allowed&&w.allowed.length>0){const _=n.filter(H).length>0,v=w.allowed.map(E=>Ne(E)).filter(E=>E!=="tools"||_),A=Array.from(new Set([x,...v]));o.addConditionalEdges(b,this.#u(n.filter(H),x),A)}else o.addEdge(b,x)}const C=c.at(-1);if(c.length>0&&C)o.addEdge("model_request",C.name);else{const w=this.#i(n.filter(H)).map(b=>b===M?S:b);w.length===1?o.addEdge("model_request",w[0]):o.addConditionalEdges("model_request",this.#l(S),w)}for(let m=c.length-1;m>0;m--){const w=c[m],b=w.name,T=c[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(H).length>0,_=w.allowed.map(A=>Ne(A)).filter(A=>A!=="tools"||x),v=Array.from(new Set([T,..._]));o.addConditionalEdges(b,this.#s(n.filter(H),w.allowed,T),v)}else o.addEdge(b,T)}if(c.length>0){const m=c[0],w=m.name,b=this.#i(n.filter(H),!0).filter(_=>_!=="tools"||n.filter(H).length>0),T=!!(m.allowed&&m.allowed.length>0),x=b.map(_=>_===M?S:_);o.addConditionalEdges(w,this.#o(n.filter(H),T,S),x)}for(let m=u.length-1;m>0;m--){const w=u[m],b=w.name,T=u[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(H).length>0,_=w.allowed.map(A=>Ne(A)).filter(A=>A!=="tools"||x),v=Array.from(new Set([T,..._]));o.addConditionalEdges(b,this.#s(n.filter(H),w.allowed,T),v)}else o.addEdge(b,T)}if(u.length>0){const m=u[0],w=m.name;if(m.allowed&&m.allowed.length>0){const b=n.filter(H).length>0,T=m.allowed.map(_=>Ne(_)).filter(_=>_!=="tools"||b),x=Array.from(new Set([M,...T]));o.addConditionalEdges(w,this.#s(n.filter(H),m.allowed,M),x)}else o.addEdge(w,M)}if(n.filter(H).length>0){const m=p;s.size>0?o.addConditionalEdges("tools",this.#a(s,S),[m,S]):o.addEdge("tools",m)}this.#e=o.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#i(t,e=!1){const n=[];return t.length>0&&n.push("tools"),e&&n.push("model_request"),n.push(M),n}#a(t,e){return n=>{const s=n.messages,r=s[s.length-1];return U.isInstance(r)&&r.name&&t.has(r.name)?this.options.responseFormat?"model_request":e:"model_request"}}#l(t=M){return e=>{const s=e.messages.at(-1);if(!N.isInstance(s)||!s.tool_calls||s.tool_calls.length===0||s.tool_calls.every(o=>o.name.startsWith("extract-")))return t;if(this.#n==="v1")return"tools";const i=s.tool_calls.filter(o=>!o.name.startsWith("extract-"));return i.length===0?t:i.map(o=>new se("tools",{...e,lg_tool_call:o}))}}#o(t,e,n){const s=!!this.options.responseFormat;return r=>{const i=r.messages,o=i.at(-1);if(N.isInstance(o)&&(!o.tool_calls||o.tool_calls.length===0))return n;if(e&&r.jumpTo)return r.jumpTo===M?n:r.jumpTo==="tools"?t.length===0?n:new se("tools",{...r,jumpTo:void 0}):new se("model_request",{...r,jumpTo:void 0});const a=i.filter(U.isInstance),l=i.filter(N.isInstance).at(-1),c=l?.tool_calls?.filter(f=>!a.some(y=>y.tool_call_id===f.id));if(c&&c.length>0)return c.map(f=>new se("tools",{...r,lg_tool_call:f}));const u=l?.tool_calls?.some(f=>f.name.startsWith("extract-"));if(c&&c.length===0&&!u&&s)return"model_request";if(!N.isInstance(o)||!o.tool_calls||o.tool_calls.length===0)return n;const h=o.tool_calls.every(f=>f.name.startsWith("extract-")),d=o.tool_calls.some(f=>!f.name.startsWith("extract-"));return h||!d?n:"tools"}}#s(t,e,n){const s=new Set(e.map(r=>Ne(r)));return r=>{if(r.jumpTo){const i=Ne(r.jumpTo);if(i===M&&s.has(M))return M;if(i==="tools"&&s.has("tools"))return t.length===0?M:new se("tools",{...r,jumpTo:void 0});if(i==="model_request"&&s.has("model_request"))return new se("model_request",{...r,jumpTo:void 0})}return n}}#c(t,e,n){return s=>{if(!s.jumpTo)return e;const r=Ne(s.jumpTo);return r===M?n:r==="tools"?t.length===0?n:new se("tools",{...s,jumpTo:void 0}):new se("model_request",{...s,jumpTo:void 0})}}#u(t,e){return n=>{if(!n.jumpTo)return e;const s=Ne(n.jumpTo);return s===M?M:s==="tools"?t.length===0?M: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 bp(this.options.middleware,t),r={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!r)return r;for(const[i,o]of Object.entries(n))i in r||(r[i]=o);return r}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 s=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(s)}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 jp(t)}const Zn=`<role>
62
+ })`)}return n}function xp(t){const e={messages:le(()=>[]),structuredResponse:Ls().optional()};if(!t)return W(e);const{shape:n}=t,r={...e};for(const[s,i]of Object.entries(n))s.startsWith("_")?r[s]=i.optional():r[s]=i;return W(r)}function Ne(t){if(t){if(["model_request","tools",M].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return M;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 li=class extends ee{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=Re(this.config,e),r=await Le.runWithConfig(n,async()=>this.func(t,n));return ee.isRunnable(r)&&this.recurse?await Le.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function Ap(t,e){let n,r;if(e==="inline")n=bp,r=vp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(i){return i.map(n)}return Ze.from([Bt.from(s),t,Bt.from(r)])}var Mp=class extends li{#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=_o(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof st)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Be).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.#i(t,e);return"structuredResponse"in r?{messages:[...t.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof K?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#r(t,r)?{messages:[new N({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#t(){if(typeof this.#e.model=="string")return 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#i(t,e,n={}){const r=await this.#t(),s=e,i=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),y={...e,signal:f},p=await h.invoke(d,y);if(u?.type==="native"){const w=u.strategy.parse(p);return w?{structuredResponse:w,messages:[p]}:p}if(!u||!p.tool_calls)return p;const S=p.tool_calls.filter(w=>w.name in u.tools);if(S.length===0)return p;if(S.length>1)return this.#a(p,S,u);const m=u.tools[S[0].name]?.options?.toolMessageContent;return this.#l(p,S[0],u,m??n.lastMessage)},o=this.#e.wrapModelCallHookMiddleware??[];let a=i;for(let c=o.length-1;c>=0;c--){const[u,h]=o[c];if(u.wrapModelCall){const d=a,f=u,y=h;a=async p=>{const S=f.contextSchema?Ke(f.contextSchema,s?.context||{}):s?.context,C=Object.freeze({context:S,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),m={...p,state:{...u.stateSchema?Ke(js(u.stateSchema),t):{},...y(),messages:t.messages},runtime:C},w=async b=>{const T=b.tools??[],x=T.filter(v=>z(v)&&!this.#e.toolClasses.some(A=>A.name===v.name));if(x.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${x.map(v=>v.name).join(", ")}. This is not supported.`);const _=T.filter(v=>z(v)&&this.#e.toolClasses.every(A=>A!==v));if(_.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${_.map(v=>v.name).join(", ")}. This is not supported.`);return d(b)};if(!f.wrapModelCall)return w(m);try{const b=await f.wrapModelCall(m,w);if(!N.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 is(e.map(s=>s.name));return this.#o(r,t,e[0],n)}#l(t,e,n,r){const s=n.tools[e.name];try{const i=s.parse(e.args);return{structuredResponse:i,messages:[t,new U({tool_call_id:e.id??"",content:JSON.stringify(i),name:e.name}),new N(r??`Returning structured response: ${JSON.stringify(i)}`)]}}catch(i){return this.#o(i,t,e,n)}}async#o(t,e,n,r){const s=Object.values(r.tools).at(0)?.options?.handleError,i=n.id;if(!i)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(o=>o instanceof is))return new K({update:{messages:[e,new U({content:t.message,tool_call_id:i})]},goto:"model"});if(typeof s=="string")return new K({update:{messages:[e,new U({content:s,tool_call_id:i})]},goto:"model"});if(typeof s=="function"){const o=await s(t);if(typeof o!="string")throw new Error("Error handler must return a string.");return new K({update:{messages:[e,new U({content:o,tool_call_id:i})]},goto:"model"})}throw t}#r(t,e){const n=N.isInstance(e)&&e.tool_calls?.every(s=>this.#e.shouldReturnDirect.has(s.name)),r="remainingSteps"in t?t.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&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:{}),i=[...e?.tools??this.#e.toolClasses,...s.map(c=>c.tool)],o=e?.toolChoice||(s.length>0?"any":void 0);if(n?.type==="native"){const c={name:n.strategy.schema?.name??"extract",description:ns(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 Cp(t,i,{...r,...e?.modelSettings??{},tool_choice:o});return Sp(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?Ap(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),Pp=t=>typeof t=="object"&&t!=null&&"messages"in t&&gl(t.messages),Np=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Op(t,e){return t instanceof Ds?new U({content:t.message,tool_call_id:e.id,name:e.name}):new U({content:`${t}
63
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var Ip=class extends li{tools;trace=!1;signal;handleToolErrors=Op;wrapToolCall;constructor(t,e){const{name:n,tags:r,handleToolErrors:s,signal:i,wrapToolCall:o}=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=i,this.wrapToolCall=o}#e(t,e,n){if(it(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}
64
+ 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)||Y(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 iu?new Ds(h,c):h}},s=e,i={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal},o=this.tools.find(l=>l.name===t.name);if(!o)throw new Error(`Tool "${t.name}" not found.`);const a={toolCall:t,tool:o,state:n,runtime:i};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(Np(t)){const{lg_tool_call:i,jumpTo:o,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let i;if(gl(t))i=t;else if(Pp(t))i=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const o=new Set(i.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=i.length-1;l>=0;l-=1){const c=i[l];if(N.isInstance(c)){a=c;break}}if(!N.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!o.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(Y))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const i of n)Y(i)?i.graph===K.PARENT&&Array.isArray(i.goto)&&i.goto.every(o=>$p(o))?s?s.goto.push(...i.goto):s=new K({graph:K.PARENT,goto:i.goto}):r.push(i):r.push(Array.isArray(t)?[i]:{messages:[i]});return s&&r.push(s),r}};function $p(t){return t instanceof re}var Rp=class{},jp=class{},Er=class extends li{#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=Ke(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},i=await this.runHook(r,Object.freeze(Object.assign(new jp,{...s,context:Object.freeze(Object.assign(new Rp,n))})));if(!i)return{...r,jumpTo:void 0};let o,a;if(this.name?.startsWith("BeforeAgentNode_")?(o=He(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(o=He(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(o=He(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(o=He(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof i.jumpTo=="string"&&!o?.includes(i.jumpTo)){const l=o&&o.length>0?`must be one of: ${o?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${i.jumpTo}, ${l}.`)}if(typeof i=="object"&&"type"in i){if(i.type==="terminate"){if(i.error)throw i.error;return{...r,...i.result||{},jumpTo:i.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(i)}`)}return{...r,...i,jumpTo:i.jumpTo}}get nodeOptions(){return{input:xp(this.middleware.stateSchema)}}},Lp=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)}},Dp=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)}},Up=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)}},Fp=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)}},Vp=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}},Bp=class{#e;#n="v2";#s;#t=new Vp;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(m=>m.tools).flatMap(m=>m.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(z).filter(m=>"returnDirect"in m&&m.returnDirect).map(m=>m.name)),s=_p(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),o=new cp(s,this.options.contextSchema),a=[],l=[],c=[],u=[],h=[];this.#s=new Mp({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 m=0;m<f.length;m++){let w,b,T,x;const _=f[m];if(d.has(_.name))throw new Error(`Middleware ${_.name} is defined multiple times`);if(d.add(_.name),_.beforeAgent){w=new Lp(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,w);const v=`${_.name}.before_agent`;a.push({index:m,name:v,allowed:He(_.beforeAgent)}),o.addNode(v,w,w.nodeOptions)}if(_.beforeModel){b=new Dp(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,b);const v=`${_.name}.before_model`;l.push({index:m,name:v,allowed:He(_.beforeModel)}),o.addNode(v,b,b.nodeOptions)}if(_.afterModel){T=new Up(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,T);const v=`${_.name}.after_model`;c.push({index:m,name:v,allowed:He(_.afterModel)}),o.addNode(v,T,T.nodeOptions)}if(_.afterAgent){x=new Fp(_,{getState:()=>this.#t.getState(_.name)}),this.#t.addNode(_,x);const v=`${_.name}.after_agent`;u.push({index:m,name:v,allowed:He(_.afterAgent)}),o.addNode(v,x,x.nodeOptions)}_.wrapModelCall&&h.push([_,()=>this.#t.getState(_.name)])}if(o.addNode("model_request",this.#s),n.filter(z).length>0){const m=new Ip(n.filter(z),{signal:this.options.signal,wrapToolCall:kp(f)});o.addNode("tools",m)}let y;a.length>0?y=a[0].name:l.length>0?y=l[0].name:y="model_request";const p=l.length>0?l[0].name:"model_request",S=u.length>0?u[u.length-1].name:M;o.addEdge(L,y);for(let m=0;m<a.length;m++){const w=a[m],b=w.name,x=m===a.length-1?p:a[m+1].name;if(w.allowed&&w.allowed.length>0){const _=n.filter(z).length>0,v=w.allowed.map(E=>Ne(E)).filter(E=>E!=="tools"||_),A=Array.from(new Set([x,...v.map(E=>E===M?S:E)]));o.addConditionalEdges(b,this.#c(n.filter(z),x,S),A)}else o.addEdge(b,x)}for(let m=0;m<l.length;m++){const w=l[m],b=w.name,x=m===l.length-1?"model_request":l[m+1].name;if(w.allowed&&w.allowed.length>0){const _=n.filter(z).length>0,v=w.allowed.map(E=>Ne(E)).filter(E=>E!=="tools"||_),A=Array.from(new Set([x,...v]));o.addConditionalEdges(b,this.#u(n.filter(z),x),A)}else o.addEdge(b,x)}const C=c.at(-1);if(c.length>0&&C)o.addEdge("model_request",C.name);else{const w=this.#i(n.filter(z)).map(b=>b===M?S:b);w.length===1?o.addEdge("model_request",w[0]):o.addConditionalEdges("model_request",this.#l(S),w)}for(let m=c.length-1;m>0;m--){const w=c[m],b=w.name,T=c[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(z).length>0,_=w.allowed.map(A=>Ne(A)).filter(A=>A!=="tools"||x),v=Array.from(new Set([T,..._]));o.addConditionalEdges(b,this.#r(n.filter(z),w.allowed,T),v)}else o.addEdge(b,T)}if(c.length>0){const m=c[0],w=m.name,b=this.#i(n.filter(z),!0).filter(_=>_!=="tools"||n.filter(z).length>0),T=!!(m.allowed&&m.allowed.length>0),x=b.map(_=>_===M?S:_);o.addConditionalEdges(w,this.#o(n.filter(z),T,S),x)}for(let m=u.length-1;m>0;m--){const w=u[m],b=w.name,T=u[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(z).length>0,_=w.allowed.map(A=>Ne(A)).filter(A=>A!=="tools"||x),v=Array.from(new Set([T,..._]));o.addConditionalEdges(b,this.#r(n.filter(z),w.allowed,T),v)}else o.addEdge(b,T)}if(u.length>0){const m=u[0],w=m.name;if(m.allowed&&m.allowed.length>0){const b=n.filter(z).length>0,T=m.allowed.map(_=>Ne(_)).filter(_=>_!=="tools"||b),x=Array.from(new Set([M,...T]));o.addConditionalEdges(w,this.#r(n.filter(z),m.allowed,M),x)}else o.addEdge(w,M)}if(n.filter(z).length>0){const m=p;r.size>0?o.addConditionalEdges("tools",this.#a(r,S),[m,S]):o.addEdge("tools",m)}this.#e=o.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#i(t,e=!1){const n=[];return t.length>0&&n.push("tools"),e&&n.push("model_request"),n.push(M),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=M){return e=>{const r=e.messages.at(-1);if(!N.isInstance(r)||!r.tool_calls||r.tool_calls.length===0||r.tool_calls.every(o=>o.name.startsWith("extract-")))return t;if(this.#n==="v1")return"tools";const i=r.tool_calls.filter(o=>!o.name.startsWith("extract-"));return i.length===0?t:i.map(o=>new re("tools",{...e,lg_tool_call:o}))}}#o(t,e,n){const r=!!this.options.responseFormat;return s=>{const i=s.messages,o=i.at(-1);if(N.isInstance(o)&&(!o.tool_calls||o.tool_calls.length===0))return n;if(e&&s.jumpTo)return s.jumpTo===M?n:s.jumpTo==="tools"?t.length===0?n:new re("tools",{...s,jumpTo:void 0}):new re("model_request",{...s,jumpTo:void 0});const a=i.filter(U.isInstance),l=i.filter(N.isInstance).at(-1),c=l?.tool_calls?.filter(f=>!a.some(y=>y.tool_call_id===f.id));if(c&&c.length>0)return c.map(f=>new re("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(!N.isInstance(o)||!o.tool_calls||o.tool_calls.length===0)return n;const h=o.tool_calls.every(f=>f.name.startsWith("extract-")),d=o.tool_calls.some(f=>!f.name.startsWith("extract-"));return h||!d?n:"tools"}}#r(t,e,n){const r=new Set(e.map(s=>Ne(s)));return s=>{if(s.jumpTo){const i=Ne(s.jumpTo);if(i===M&&r.has(M))return M;if(i==="tools"&&r.has("tools"))return t.length===0?M:new re("tools",{...s,jumpTo:void 0});if(i==="model_request"&&r.has("model_request"))return new re("model_request",{...s,jumpTo:void 0})}return n}}#c(t,e,n){return r=>{if(!r.jumpTo)return e;const s=Ne(r.jumpTo);return s===M?n:s==="tools"?t.length===0?n:new re("tools",{...r,jumpTo:void 0}):new re("model_request",{...r,jumpTo:void 0})}}#u(t,e){return n=>{if(!n.jumpTo)return e;const r=Ne(n.jumpTo);return r===M?M:r==="tools"?t.length===0?M:new re("tools",{...n,jumpTo:void 0}):new re("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 Ep(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[i,o]of Object.entries(n))i in s||(s[i]=o);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 Bp(t)}const Zn=`<role>
65
65
  Context Extraction Assistant
66
66
  </role>
67
67
 
@@ -87,13 +87,13 @@ Respond ONLY with the extracted context. Do not include any additional informati
87
87
  <messages>
88
88
  Messages to summarize:
89
89
  {messages}
90
- </messages>`,ys=20,Lp=4e3,Hi=5,Dp=ns().args(Fe(le())).returns(Me([F(),lo(F())])),ws=W({fraction:F().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:F().positive("Tokens must be greater than 0").optional(),messages:F().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=W({fraction:F().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:F().positive("Tokens must be greater than 0").optional(),messages:F().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"}),zi=W({model:le(),trigger:Me([ws,Fe(ws)]).optional(),keep:yl.optional(),tokenCounter:Dp.optional(),summaryPrompt:ne().default(Zn),trimTokensToSummarize:F().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:F().optional(),messagesToKeep:F().optional()});function ci(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 yc(n)}catch{}}function Up(t){const{data:e,error:n}=su(zi,t);if(n)throw new Error(`Invalid summarization middleware options: ${eo(n)}`);return me({name:"SummarizationMiddleware",contextSchema:zi.extend({model:le().optional()}),beforeModel:async(s,r)=>{let i=e.trigger,o=e.keep;e.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),i===void 0&&(i={tokens:e.maxTokensBeforeSummary})),e.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!o||o&&"messages"in o&&o.messages===ys)&&(o={messages:e.messagesToKeep}));const a=r.context.trigger!==void 0?r.context.trigger:i,l=r.context.keep!==void 0?r.context.keep:o??{messages:ys},c=yl.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(A=>ws.parse(A)):u=[ws.parse(a)];const h=u.some(A=>"fraction"in A)||"fraction"in c,d=typeof e.model=="string"?await Zt(e.model):e.model;if(h&&!ci(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=r.context.summaryPrompt===Zn?e.summaryPrompt??Zn:r.context.summaryPrompt??e.summaryPrompt??Zn,y=r.context.trimTokensToSummarize!==void 0?r.context.trimTokensToSummarize:e.trimTokensToSummarize??Lp;Fp(s.messages);const p=r.context.tokenCounter!==void 0?r.context.tokenCounter:e.tokenCounter??Fr,S=await p(s.messages);if(!await Wp(s.messages,S,u,d))return;const{systemPrompt:m,conversationMessages:w}=Vp(s.messages),b=await Hp(w,c,p,d);if(b<=0)return;const{messagesToSummarize:T,preservedMessages:x}=Bp(m,w,b),_=await Jp(T,d,f,p,y),v=new oe({content:`Here is a summary of the conversation to date:
90
+ </messages>`,yr=20,Wp=4e3,Hi=5,zp=nr().args(Fe(le())).returns(Me([F(),co(F())])),wr=W({fraction:F().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:F().positive("Tokens must be greater than 0").optional(),messages:F().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=W({fraction:F().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:F().positive("Tokens must be greater than 0").optional(),messages:F().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"}),Gi=W({model:le(),trigger:Me([wr,Fe(wr)]).optional(),keep:wl.optional(),tokenCounter:zp.optional(),summaryPrompt:ne().default(Zn),trimTokensToSummarize:F().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:F().optional(),messagesToKeep:F().optional()});function ci(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 bc(n)}catch{}}function Hp(t){const{data:e,error:n}=ou(Gi,t);if(n)throw new Error(`Invalid summarization middleware options: ${to(n)}`);return me({name:"SummarizationMiddleware",contextSchema:Gi.extend({model:le().optional()}),beforeModel:async(r,s)=>{let i=e.trigger,o=e.keep;e.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),i===void 0&&(i={tokens:e.maxTokensBeforeSummary})),e.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!o||o&&"messages"in o&&o.messages===yr)&&(o={messages:e.messagesToKeep}));const a=s.context.trigger!==void 0?s.context.trigger:i,l=s.context.keep!==void 0?s.context.keep:o??{messages:yr},c=wl.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(A=>wr.parse(A)):u=[wr.parse(a)];const h=u.some(A=>"fraction"in A)||"fraction"in c,d=typeof e.model=="string"?await Zt(e.model):e.model;if(h&&!ci(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context.summaryPrompt===Zn?e.summaryPrompt??Zn:s.context.summaryPrompt??e.summaryPrompt??Zn,y=s.context.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??Wp;Gp(r.messages);const p=s.context.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??Fs,S=await p(r.messages);if(!await qp(r.messages,S,u,d))return;const{systemPrompt:m,conversationMessages:w}=Kp(r.messages),b=await Yp(w,c,p,d);if(b<=0)return;const{messagesToSummarize:T,preservedMessages:x}=Jp(m,w,b),_=await em(T,d,f,p,y),v=new oe({content:`Here is a summary of the conversation to date:
91
91
 
92
- ${_}`,id:ts()});return{messages:[new $n({id:hl}),v,...x]}}})}function Fp(t){for(const e of t)e.id||(e.id=ts())}function Vp(t){return t.length>0&&_e.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Bp(t,e,n){const s=e.slice(0,n),r=e.slice(n);return t&&s.unshift(t),{messagesToSummarize:s,preservedMessages:r}}async function Wp(t,e,n,s){if(n.length===0)return!1;for(const r of n){let i=!0,o=!1;if(r.messages!==void 0&&(o=!0,t.length<r.messages&&(i=!1)),r.tokens!==void 0&&(o=!0,e<r.tokens&&(i=!1)),r.fraction!==void 0){o=!0;const a=ci(s);if(typeof a=="number"){const l=Math.floor(a*r.fraction);e<l&&(i=!1)}else i=!1}if(o&&i)return!0}return!1}async function Hp(t,e,n,s){if("tokens"in e||"fraction"in e){const r=await zp(t,e,n,s);return typeof r=="number"?r:Gi(t,ys)}return Gi(t,e.messages??ys)}async function zp(t,e,n,s){if(t.length===0)return 0;let r;if("fraction"in e&&e.fraction!==void 0){const u=ci(s);if(typeof u!="number")return;r=Math.floor(u*e.fraction)}else if("tokens"in e&&e.tokens!==void 0)r=Math.floor(e.tokens);else return;if(r<=0&&(r=1),await n(t)<=r)return 0;let o=0,a=t.length,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let u=0;u<c&&!(o>=a);u++){const h=Math.floor((o+a)/2);await n(t.slice(h))<=r?(l=h,a=h):o=h+1}if(l===t.length&&(l=o),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 Gi(t,e){if(t.length<=e)return 0;const n=t.length-e;for(let s=n;s>=0;s--)if(wl(t,s))return s;return 0}function wl(t,e){if(e>=t.length)return!0;if(e<t.length&&N.isInstance(t[e])&&Mr(t[e]))return!1;const n=Math.max(0,e-Hi),s=Math.min(t.length,e+Hi);for(let r=n;r<s;r++){if(!Mr(t[r]))continue;const i=Gp(t[r]);if(Kp(t,r,e,i))return!1}return!0}function Gp(t){const e=new Set;if(t.tool_calls)for(const n of t.tool_calls){const s=typeof n=="object"&&"id"in n?n.id:null;s&&e.add(s)}return e}function Kp(t,e,n,s){for(let r=e+1;r<t.length;r++){const i=t[r];if(U.isInstance(i)&&s.has(i.tool_call_id)){const o=e<n,a=r<n;if(o!==a)return!0}}return!1}async function Jp(t,e,n,s,r){if(!t.length)return"No previous conversation history.";const i=await qp(t,s,r);if(!i.length)return"Previous conversation was too long to summarize.";try{const o=n.replace("{messages}",JSON.stringify(i,null,2)),l=(await e.invoke(o)).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(o){return`Error generating summary: ${o}`}}async function qp(t,e,n){if(n===void 0)return t;try{return await co(t,{maxTokens:n,tokenCounter:async s=>e(s),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const Yp=ns().args(le(),le(),le()).returns(Me([ne(),lo(ne())])),_l=["approve","edit","reject"],Xp=Ht(_l),Zp=W({allowedDecisions:Fe(Xp),description:Me([ne(),Yp]).optional(),argsSchema:mn(Lr()).optional()}),Ki=W({interruptOn:mn(Me([ss(),Zp])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function Qp(t){const e=async(s,r,i,o)=>{const a=s.name,l=s.args,c=r.description;let u;typeof c=="function"?u=await c(s,i,o):c!==void 0?u=c:u=`${t.descriptionPrefix??"Tool execution requires approval"}
92
+ ${_}`,id:tr()});return{messages:[new $n({id:dl}),v,...x]}}})}function Gp(t){for(const e of t)e.id||(e.id=tr())}function Kp(t){return t.length>0&&_e.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Jp(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function qp(t,e,n,r){if(n.length===0)return!1;for(const s of n){let i=!0,o=!1;if(s.messages!==void 0&&(o=!0,t.length<s.messages&&(i=!1)),s.tokens!==void 0&&(o=!0,e<s.tokens&&(i=!1)),s.fraction!==void 0){o=!0;const a=ci(r);if(typeof a=="number"){const l=Math.floor(a*s.fraction);e<l&&(i=!1)}else i=!1}if(o&&i)return!0}return!1}async function Yp(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Xp(t,e,n,r);return typeof s=="number"?s:Ki(t,yr)}return Ki(t,e.messages??yr)}async function Xp(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const u=ci(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 o=0,a=t.length,l=t.length;const c=Math.floor(Math.log2(t.length))+1;for(let u=0;u<c&&!(o>=a);u++){const h=Math.floor((o+a)/2);await n(t.slice(h))<=s?(l=h,a=h):o=h+1}if(l===t.length&&(l=o),l>=t.length){if(t.length===1)return 0;l=t.length-1}for(let u=l;u>=0;u--)if(_l(t,u))return u;return 0}function Ki(t,e){if(t.length<=e)return 0;const n=t.length-e;for(let r=n;r>=0;r--)if(_l(t,r))return r;return 0}function _l(t,e){if(e>=t.length)return!0;if(e<t.length&&N.isInstance(t[e])&&Ms(t[e]))return!1;const n=Math.max(0,e-Hi),r=Math.min(t.length,e+Hi);for(let s=n;s<r;s++){if(!Ms(t[s]))continue;const i=Zp(t[s]);if(Qp(t,s,e,i))return!1}return!0}function Zp(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 Qp(t,e,n,r){for(let s=e+1;s<t.length;s++){const i=t[s];if(U.isInstance(i)&&r.has(i.tool_call_id)){const o=e<n,a=s<n;if(o!==a)return!0}}return!1}async function em(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const i=await tm(t,r,s);if(!i.length)return"Previous conversation was too long to summarize.";try{const o=n.replace("{messages}",JSON.stringify(i,null,2)),l=(await e.invoke(o)).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(o){return`Error generating summary: ${o}`}}async function tm(t,e,n){if(n===void 0)return t;try{return await uo(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const nm=nr().args(le(),le(),le()).returns(Me([ne(),co(ne())])),bl=["approve","edit","reject"],rm=zt(bl),sm=W({allowedDecisions:Fe(rm),description:Me([ne(),nm]).optional(),argsSchema:mn(Ls()).optional()}),Ji=W({interruptOn:mn(Me([rr(),sm])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function im(t){const e=async(r,s,i,o)=>{const a=r.name,l=r.args,c=s.description;let u;typeof c=="function"?u=await c(r,i,o):c!==void 0?u=c:u=`${t.descriptionPrefix??"Tool execution requires approval"}
93
93
 
94
94
  Tool: ${a}
95
- Args: ${JSON.stringify(l,null,2)}`;const h={name:a,args:l,description:u},d={actionName:a,allowedDecisions:r.allowedDecisions};return r.argsSchema&&(d.argsSchema=r.argsSchema),{actionRequest:h,reviewConfig:d}},n=(s,r,i)=>{const o=i.allowedDecisions;if(s.type==="approve"&&o.includes("approve"))return{revisedToolCall:r,toolMessage:null};if(s.type==="edit"&&o.includes("edit")){const l=s.editedAction;if(!l||typeof l.name!="string")throw new Error(`Invalid edited action for tool "${r.name}": name must be a string`);if(!l.args||typeof l.args!="object")throw new Error(`Invalid edited action for tool "${r.name}": args must be an object`);return{revisedToolCall:{type:"tool_call",name:l.name,args:l.args,id:r.id},toolMessage:null}}if(s.type==="reject"&&o.includes("reject")){if(s.message!==void 0&&typeof s.message!="string")throw new Error(`Tool call response for "${r.name}" must be a string, got ${typeof s.message}`);const l=s.message??`User rejected the tool call for \`${r.name}\` with id ${r.id}`,c=new U({content:l,name:r.name,tool_call_id:r.id,status:"error"});return{revisedToolCall:r,toolMessage:c}}const a=`Unexpected human decision: ${JSON.stringify(s)}. Decision type '${s.type}' is not allowed for tool '${r.name}'. Expected one of ${JSON.stringify(o)} based on the tool's configuration.`;throw new Error(a)};return me({name:"HumanInTheLoopMiddleware",contextSchema:Ki,afterModel:{canJumpTo:["model"],hook:async(s,r)=>{const i=Ke(Ki,{...t,...r.context||{}});if(!i)return;const{messages:o}=s;if(!o.length)return;const a=[...o].reverse().find(b=>N.isInstance(b));if(!a||!a.tool_calls?.length||!i.interruptOn)return;const l={};for(const[b,T]of Object.entries(i.interruptOn))typeof T=="boolean"?T===!0&&(l[b]={allowedDecisions:[..._l]}):T.allowedDecisions&&(l[b]=T);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 T=l[b.name],{actionRequest:x,reviewConfig:_}=await e(b,T,s,r);h.push(x),d.push(_)}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=[],m=p.some(b=>b.type==="reject");for(let b=0;b<p.length;b++){const T=p[b],x=c[b],_=l[x.name],{revisedToolCall:v,toolMessage:A}=n(T,x,_);v&&(!m||T.type==="reject")&&S.push(v),A&&C.push(A)}N.isInstance(a)&&(a.tool_calls=S);const w=m?"model":void 0;return{messages:[a,...C],jumpTo:w}}}})}const em=!0,tm="5m",nm=3,sm="warn",rm=W({enableCaching:ss().optional(),ttl:Ht(["5m","1h"]).optional(),minMessagesToCache:F().optional(),unsupportedModelBehavior:Ht(["ignore","warn","raise"]).optional()});var Ji=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function im(t){return me({name:"PromptCachingMiddleware",contextSchema:rm,wrapModelCall:(e,n)=>{const s=e.runtime.context.enableCaching??t?.enableCaching??em,r=e.runtime.context.ttl??t?.ttl??tm,i=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??nm,o=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??sm;if(!s||!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(o==="raise")throw new Ji(`${f} (e.g., 'anthropic:claude-4-0-sonnet').`);return o==="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)<i)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:r}}]});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:r}}]});return n({...e,messages:[...e.messages.slice(0,-1),h]})}throw new Ji("Last message content is not a string or array")}})}function om(t){return me({name:"DynamicSystemPromptMiddleware",wrapModelCall:async(e,n)=>{const s=await t(e.state,e.runtime);if(typeof s!="string")throw new Error("dynamicSystemPromptMiddleware function must return a string");return n({...e,systemPrompt:s})}})}const am="Your goal is to select the most relevant tools for answering the user's query.";function lm(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(s=>vt(s.name)),n=Me(e);return W({tools:Fe(n).describe("Tools to use. Place the most relevant tools first.")})}const cm=W({model:ne().or(rs(wc)).optional(),systemPrompt:ne().optional(),maxTools:F().optional(),alwaysInclude:Fe(ne()).optional()});function um(t){return me({name:"LLMToolSelector",contextSchema:cm,async wrapModelCall(e,n){const s=await hm(e,t,e.runtime);if(!s)return n(e);const r=lm(s.availableTools),o=await(await s.model.withStructuredOutput?.(r))?.invoke([{role:"system",content:s.systemMessage},s.lastUserMessage]);if(!o||typeof o!="object"||!("tools"in o))throw new Error(`Expected object response with tools array, got ${typeof o}`);return n(dm(o,s.availableTools,s.validToolNames,e,t))}})}async function hm(t,e,n){const s=n.context.model??e.model,r=n.context.maxTools??e.maxTools,i=n.context.alwaysInclude??e.alwaysInclude??[],o=n.context.systemPrompt??e.systemPrompt??am;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(i.length>0){const f=new Set(a.map(p=>p.name)),y=i.filter(p=>!f.has(p));if(y.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${y.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!i.includes(f.name));if(l.length===0)return;let c=o;r!==void 0&&(c+=`
96
- 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 ${r} will be used.`);let u;for(const f of t.messages)oe.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=s?typeof s=="string"?await Zt(s):s:t.model,d=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:h,validToolNames:d}}function dm(t,e,n,s,r){const i=r.maxTools,o=r.alwaysInclude??[],a=[],l=[];for(const d of t.tools){if(!n.includes(d)){l.push(d);continue}!a.includes(d)&&(i===void 0||a.length<i)&&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=(s.tools??[]).filter(d=>typeof d=="object"&&"name"in d&&typeof d.name=="string"&&o.includes(d.name));c.push(...u);const h=(s.tools??[]).filter(d=>!(typeof d=="object"&&"name"in d&&"description"in d&&typeof d.name=="string"));return{...s,tools:[...c,...h]}}const fm=W({rules:mn(ne(),rs(RegExp).describe("Regular expression pattern to match PII")).optional()});function pm(){return Math.random().toString(36).substring(2,11)}function Zs(t,e,n){let s=t;for(const[r,i]of Object.entries(e)){const o=r.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");s=s.replace(i,a=>{const l=pm();return n[l]=a,`[REDACTED_${o}_${l}]`})}return s}async function mm(t,e){if(oe.isInstance(t)||U.isInstance(t)||_e.isInstance(t)){const n=t.content,s=await Zs(n,e.rules,e.redactionMap);if(s!==n){const r=Object.getPrototypeOf(t).constructor;return new r({...t,content:s})}return t}if(N.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),s=JSON.stringify(t.tool_calls),r=await Zs(n,e.rules,e.redactionMap),i=await Zs(s,e.rules,e.redactionMap);return r!==n||i!==s?new N({...t,content:typeof t.content=="string"?r:JSON.parse(r),tool_calls:JSON.parse(i)}):t}throw new Error(`Unsupported message type: ${t.type}`)}function un(t,e){let n=t;const s=/\[REDACTED_[A-Z_]+_(\w+)\]/g;return n=n.replace(s,(r,i)=>e[i]?e[i]:r),n}function qi(t,e){if(oe.isInstance(t)||U.isInstance(t)||_e.isInstance(t)){const n=t.content,s=un(n,e);if(s!==n){const r=Object.getPrototypeOf(t).constructor;return{message:new r({...t,content:s}),changed:!0}}return{message:t,changed:!1}}if(N.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),s=JSON.stringify(t.tool_calls),r=un(n,e),i=un(s,e);return r!==n||i!==s?{message:new N({...t,content:typeof t.content=="string"?r:JSON.parse(r),tool_calls:JSON.parse(i)}),changed:!0}:{message:t,changed:!1}}throw new Error(`Unsupported message type: ${t.type}`)}function gm(t={}){const e={};return me({name:"PIIRedactionMiddleware",contextSchema:fm,wrapModelCall:async(n,s)=>{const r=n.runtime.context.rules??t.rules??{};if(Object.keys(r).length===0)return s(n);const i=await Promise.all(n.state.messages.map(o=>mm(o,{rules:r,redactionMap:e})));return s({...n,messages:i})},afterModel:async n=>{if(Object.keys(e).length===0)return;const s=n.messages.at(-1);if(!N.isInstance(s))return;const r=n.messages.at(-2),{message:i,changed:o}=qi(s,e);if(!o)return;let a;if(N.isInstance(s)&&s?.tool_calls?.length===0&&typeof s.content=="string"&&s.content.startsWith("{")&&s.content.endsWith("}"))try{a=JSON.parse(un(s.content,e))}catch{}if(N.isInstance(r)&&r?.tool_calls?.length!==0&&r?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=qi(r,e),h=r.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(un(JSON.stringify(h),e)):void 0;if(o||u)return{...n,...d?{structuredResponse:d}:{},messages:[new $n({id:r.id}),new $n({id:s.id}),c,i]}}return{...n,...a?{structuredResponse:a}:{},messages:[new $n({id:s.id}),i]}}})}const ym="[cleared]";var bl=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??ym}async apply(t){const{tokens:e,messages:n,countTokens:s}=t;if(e<=this.triggerTokens)return e;const r=[];for(let a=0;a<n.length;a++){const l=n[a];U.isInstance(l)&&r.push({idx:a,msg:l})}const i=this.keep>=r.length?[]:this.keep>0?r.slice(0,-this.keep):r;let o=0;for(const{idx:a,msg:l}of i){if(this.clearAtLeast>0&&o>=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(y=>y.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 y=n.indexOf(u);y>=0&&(n[y]=this.#n(u,l.tool_call_id))}const f=await s(n);o=Math.max(0,e-f)}return e-o}#e(t,e){for(let n=t.length-1;n>=0;n--){const s=t[n];if(N.isInstance(s)&&s.tool_calls?.some(i=>i.id===e))return s}return null}#n(t,e){const n=t.tool_calls?.map(o=>o.id===e?{...o,args:{}}:o),s={...t.response_metadata},r={...s.context_editing},i=new Set(r.cleared_tool_inputs);return i.add(e),r.cleared_tool_inputs=Array.from(i).sort(),s.context_editing=r,new N({content:t.content,tool_calls:n,response_metadata:s,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function wm(t={}){const e=t.edits??[new bl],n=t.tokenCountMethod??"approx";return me({name:"ContextEditingMiddleware",wrapModelCall:async(s,r)=>{if(!s.messages||s.messages.length===0)return r(s);const i=s.systemPrompt?[new _e(s.systemPrompt)]:[],o=n==="approx"?Fr:async l=>{const c=[...i,...l];if("getNumTokensFromMessages"in s.model)return s.model.getNumTokensFromMessages(c).then(({totalCount:u})=>u);throw new Error(`Model "${s.model.getName()}" does not support token counting`)};let a=await o(s.messages);for(const l of e)a=await l.apply({tokens:a,messages:s.messages,countTokens:o});return r(s)}})}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 bm=["continue","error","end"],vl="continue";function Sl(t,e,n,s,r){const i=r?`'${r}' tool`:"Tool",o=[];n!==void 0&&t>n&&o.push(`thread limit exceeded (${t}/${n} calls)`),s!==void 0&&e>s&&o.push(`run limit exceeded (${e}/${s} calls)`);const a=o.join(" and ");return`${i} call limit reached: ${a}.`}const Cl=Ht(bm).default(vl);var Tl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,s,r=void 0){const i=Sl(t,e,n,s,r);super(i),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=s,this.toolName=r}};W({toolName:ne().optional(),threadLimit:F().optional(),runLimit:F().optional(),exitBehavior:Cl});const vm=W({threadToolCallCount:mn(ne(),F()).default({}),runToolCallCount:mn(ne(),F()).default({})}),Sm="__all__";function Cm(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??vl,n=Cl.safeParse(e);if(!n.success)throw new Error(eo(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 s=t.toolName?`ToolCallLimitMiddleware[${t.toolName}]`:"ToolCallLimitMiddleware";return me({name:s,stateSchema:vm,afterModel:{canJumpTo:["end"],hook:r=>{const i=[...r.messages].reverse().find(N.isInstance);if(!i||!i.tool_calls)return;const o=(b,T)=>t.threadLimit!==void 0&&b+1>t.threadLimit||t.runLimit!==void 0&&T+1>t.runLimit,a=b=>t.toolName===void 0||b.name===t.toolName,l=(b,T,x)=>{const _=[],v=[];let A=T,E=x;for(const P of b)a(P)&&(o(A,E)?v.push(P):(_.push(P),A+=1,E+=1));return{allowed:_,blocked:v,finalThreadCount:A,finalRunCount:E+v.length}},c=t.toolName??Sm,u={...r.threadToolCallCount??{}},h={...r.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:y,blocked:p,finalThreadCount:S,finalRunCount:C}=l(i.tool_calls,d,f);if(u[c]=S,h[c]=C,p.length===0)return y.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 m=_m(t.toolName),w=p.map(b=>new U({content:m,tool_call_id:b.id,name:b.name,status:"error"}));if(e==="end"){let b=[];if(t.toolName!==void 0?b=i.tool_calls.filter(_=>_.name!==t.toolName):new Set(i.tool_calls.map(v=>v.name).filter(Boolean)).size>1&&(b=y.length>0?y:i.tool_calls),b.length>0){const _=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: ${_}. Use 'continue' or 'error' behavior instead.`)}const T=S+p.length,x=Sl(T,C,t.threadLimit,t.runLimit,t.toolName);return w.push(new N(x)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:w}}return{threadToolCallCount:u,runToolCallCount:h,messages:w}}},afterAgent:()=>({runToolCallCount:{}})})}const Tm=`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.
95
+ 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,i)=>{const o=i.allowedDecisions;if(r.type==="approve"&&o.includes("approve"))return{revisedToolCall:s,toolMessage:null};if(r.type==="edit"&&o.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"&&o.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(o)} based on the tool's configuration.`;throw new Error(a)};return me({name:"HumanInTheLoopMiddleware",contextSchema:Ji,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const i=Ke(Ji,{...t,...s.context||{}});if(!i)return;const{messages:o}=r;if(!o.length)return;const a=[...o].reverse().find(b=>N.isInstance(b));if(!a||!a.tool_calls?.length||!i.interruptOn)return;const l={};for(const[b,T]of Object.entries(i.interruptOn))typeof T=="boolean"?T===!0&&(l[b]={allowedDecisions:[...bl]}):T.allowedDecisions&&(l[b]=T);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 T=l[b.name],{actionRequest:x,reviewConfig:_}=await e(b,T,r,s);h.push(x),d.push(_)}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=[],m=p.some(b=>b.type==="reject");for(let b=0;b<p.length;b++){const T=p[b],x=c[b],_=l[x.name],{revisedToolCall:v,toolMessage:A}=n(T,x,_);v&&(!m||T.type==="reject")&&S.push(v),A&&C.push(A)}N.isInstance(a)&&(a.tool_calls=S);const w=m?"model":void 0;return{messages:[a,...C],jumpTo:w}}}})}const om=!0,am="5m",lm=3,cm="warn",um=W({enableCaching:rr().optional(),ttl:zt(["5m","1h"]).optional(),minMessagesToCache:F().optional(),unsupportedModelBehavior:zt(["ignore","warn","raise"]).optional()});var qi=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function hm(t){return me({name:"PromptCachingMiddleware",contextSchema:um,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??om,s=e.runtime.context.ttl??t?.ttl??am,i=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??lm,o=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??cm;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(o==="raise")throw new qi(`${f} (e.g., 'anthropic:claude-4-0-sonnet').`);return o==="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)<i)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 qi("Last message content is not a string or array")}})}function dm(t){return me({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 fm="Your goal is to select the most relevant tools for answering the user's query.";function pm(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>vt(r.name)),n=Me(e);return W({tools:Fe(n).describe("Tools to use. Place the most relevant tools first.")})}const mm=W({model:ne().or(sr(vc)).optional(),systemPrompt:ne().optional(),maxTools:F().optional(),alwaysInclude:Fe(ne()).optional()});function gm(t){return me({name:"LLMToolSelector",contextSchema:mm,async wrapModelCall(e,n){const r=await ym(e,t,e.runtime);if(!r)return n(e);const s=pm(r.availableTools),o=await(await r.model.withStructuredOutput?.(s))?.invoke([{role:"system",content:r.systemMessage},r.lastUserMessage]);if(!o||typeof o!="object"||!("tools"in o))throw new Error(`Expected object response with tools array, got ${typeof o}`);return n(wm(o,r.availableTools,r.validToolNames,e,t))}})}async function ym(t,e,n){const r=n.context.model??e.model,s=n.context.maxTools??e.maxTools,i=n.context.alwaysInclude??e.alwaysInclude??[],o=n.context.systemPrompt??e.systemPrompt??fm;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(i.length>0){const f=new Set(a.map(p=>p.name)),y=i.filter(p=>!f.has(p));if(y.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${y.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!i.includes(f.name));if(l.length===0)return;let c=o;s!==void 0&&(c+=`
96
+ 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)oe.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 wm(t,e,n,r,s){const i=s.maxTools,o=s.alwaysInclude??[],a=[],l=[];for(const d of t.tools){if(!n.includes(d)){l.push(d);continue}!a.includes(d)&&(i===void 0||a.length<i)&&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"&&o.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 _m=W({rules:mn(ne(),sr(RegExp).describe("Regular expression pattern to match PII")).optional()});function bm(){return Math.random().toString(36).substring(2,11)}function Zr(t,e,n){let r=t;for(const[s,i]of Object.entries(e)){const o=s.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,"");r=r.replace(i,a=>{const l=bm();return n[l]=a,`[REDACTED_${o}_${l}]`})}return r}async function vm(t,e){if(oe.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(N.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),i=await Zr(r,e.rules,e.redactionMap);return s!==n||i!==r?new N({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(i)}):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,i)=>e[i]?e[i]:s),n}function Yi(t,e){if(oe.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(N.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=un(n,e),i=un(r,e);return s!==n||i!==r?{message:new N({...t,content:typeof t.content=="string"?s:JSON.parse(s),tool_calls:JSON.parse(i)}),changed:!0}:{message:t,changed:!1}}throw new Error(`Unsupported message type: ${t.type}`)}function Sm(t={}){const e={};return me({name:"PIIRedactionMiddleware",contextSchema:_m,wrapModelCall:async(n,r)=>{const s=n.runtime.context.rules??t.rules??{};if(Object.keys(s).length===0)return r(n);const i=await Promise.all(n.state.messages.map(o=>vm(o,{rules:s,redactionMap:e})));return r({...n,messages:i})},afterModel:async n=>{if(Object.keys(e).length===0)return;const r=n.messages.at(-1);if(!N.isInstance(r))return;const s=n.messages.at(-2),{message:i,changed:o}=Yi(r,e);if(!o)return;let a;if(N.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(un(r.content,e))}catch{}if(N.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=Yi(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(o||u)return{...n,...d?{structuredResponse:d}:{},messages:[new $n({id:s.id}),new $n({id:r.id}),c,i]}}return{...n,...a?{structuredResponse:a}:{},messages:[new $n({id:r.id}),i]}}})}const Cm="[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??Cm}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 i=this.keep>=s.length?[]:this.keep>0?s.slice(0,-this.keep):s;let o=0;for(const{idx:a,msg:l}of i){if(this.clearAtLeast>0&&o>=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(y=>y.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 y=n.indexOf(u);y>=0&&(n[y]=this.#n(u,l.tool_call_id))}const f=await r(n);o=Math.max(0,e-f)}return e-o}#e(t,e){for(let n=t.length-1;n>=0;n--){const r=t[n];if(N.isInstance(r)&&r.tool_calls?.some(i=>i.id===e))return r}return null}#n(t,e){const n=t.tool_calls?.map(o=>o.id===e?{...o,args:{}}:o),r={...t.response_metadata},s={...r.context_editing},i=new Set(s.cleared_tool_inputs);return i.add(e),s.cleared_tool_inputs=Array.from(i).sort(),r.context_editing=s,new N({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function Tm(t={}){const e=t.edits??[new vl],n=t.tokenCountMethod??"approx";return me({name:"ContextEditingMiddleware",wrapModelCall:async(r,s)=>{if(!r.messages||r.messages.length===0)return s(r);const i=r.systemPrompt?[new _e(r.systemPrompt)]:[],o=n==="approx"?Fs:async l=>{const c=[...i,...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 o(r.messages);for(const l of e)a=await l.apply({tokens:a,messages:r.messages,countTokens:o});return s(r)}})}function km(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const Em=["continue","error","end"],Sl="continue";function Cl(t,e,n,r,s){const i=s?`'${s}' tool`:"Tool",o=[];n!==void 0&&t>n&&o.push(`thread limit exceeded (${t}/${n} calls)`),r!==void 0&&e>r&&o.push(`run limit exceeded (${e}/${r} calls)`);const a=o.join(" and ");return`${i} call limit reached: ${a}.`}const Tl=zt(Em).default(Sl);var kl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const i=Cl(t,e,n,r,s);super(i),this.name="ToolCallLimitExceededError",this.threadCount=t,this.runCount=e,this.threadLimit=n,this.runLimit=r,this.toolName=s}};W({toolName:ne().optional(),threadLimit:F().optional(),runLimit:F().optional(),exitBehavior:Tl});const xm=W({threadToolCallCount:mn(ne(),F()).default({}),runToolCallCount:mn(ne(),F()).default({})}),Am="__all__";function Mm(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=Tl.safeParse(e);if(!n.success)throw new Error(to(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 me({name:r,stateSchema:xm,afterModel:{canJumpTo:["end"],hook:s=>{const i=[...s.messages].reverse().find(N.isInstance);if(!i||!i.tool_calls)return;const o=(b,T)=>t.threadLimit!==void 0&&b+1>t.threadLimit||t.runLimit!==void 0&&T+1>t.runLimit,a=b=>t.toolName===void 0||b.name===t.toolName,l=(b,T,x)=>{const _=[],v=[];let A=T,E=x;for(const P of b)a(P)&&(o(A,E)?v.push(P):(_.push(P),A+=1,E+=1));return{allowed:_,blocked:v,finalThreadCount:A,finalRunCount:E+v.length}},c=t.toolName??Am,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:y,blocked:p,finalThreadCount:S,finalRunCount:C}=l(i.tool_calls,d,f);if(u[c]=S,h[c]=C,p.length===0)return y.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const b=S+p.length;throw new kl(b,C,t.threadLimit,t.runLimit,t.toolName)}const m=km(t.toolName),w=p.map(b=>new U({content:m,tool_call_id:b.id,name:b.name,status:"error"}));if(e==="end"){let b=[];if(t.toolName!==void 0?b=i.tool_calls.filter(_=>_.name!==t.toolName):new Set(i.tool_calls.map(v=>v.name).filter(Boolean)).size>1&&(b=y.length>0?y:i.tool_calls),b.length>0){const _=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: ${_}. Use 'continue' or 'error' behavior instead.`)}const T=S+p.length,x=Cl(T,C,t.threadLimit,t.runLimit,t.toolName);return w.push(new N(x)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:w}}return{threadToolCallCount:u,runToolCallCount:h,messages:w}}},afterAgent:()=>({runToolCallCount:{}})})}const Pm=`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
97
  It also helps the user understand the progress of the task and overall progress of their requests.
98
98
  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.
99
99
 
@@ -305,7 +305,7 @@ Using the todo list here is overkill and wastes time and tokens. These three too
305
305
  - Use clear, descriptive task names
306
306
 
307
307
  Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
308
- 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.`,kl=`## \`write_todos\`
308
+ 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\`
309
309
 
310
310
  You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
311
311
  Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
@@ -317,25 +317,25 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
317
317
 
318
318
  ## Important To-Do List Usage Notes to Remember
319
319
  - The \`write_todos\` tool should never be called multiple times in parallel.
320
- - 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.`,km=Ht(["pending","in_progress","completed"]).describe("Status of the todo"),El=W({content:ne().describe("Content of the todo item"),status:km}),Em=W({todos:Fe(El).default([])});function xm(t){const e=no(({todos:n},s)=>new K({update:{todos:n,messages:[new U({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:s.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??Tm,schema:W({todos:Fe(El).describe("List of todo items to update")})});return me({name:"todoListMiddleware",stateSchema:Em,tools:[e],wrapModelCall:(n,s)=>s({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
320
+ - 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.`,Nm=zt(["pending","in_progress","completed"]).describe("Status of the todo"),xl=W({content:ne().describe("Content of the todo item"),status:Nm}),Om=W({todos:Fe(xl).default([])});function Im(t){const e=ro(({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??Pm,schema:W({todos:Fe(xl).describe("List of todo items to update")})});return me({name:"todoListMiddleware",stateSchema:Om,tools:[e],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
321
321
 
322
- `:"")+(t?.systemPrompt??kl)})})}const Am="end",Mm=W({threadLimit:F().optional(),runLimit:F().optional(),exitBehavior:Ht(["throw","end"]).optional()}),Pm=W({threadModelCallCount:F().default(0),runModelCallCount:F().default(0)});var Yi=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:n,runCount:s}){const r=[];typeof t=="number"&&typeof n=="number"&&r.push(`thread level call limit reached with ${n} model calls`),typeof e=="number"&&typeof s=="number"&&r.push(`run level call limit reached with ${s} model calls`),super(`Model call limits exceeded${r.length>0?`: ${r.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function xl(t){return me({name:"ModelCallLimitMiddleware",contextSchema:Mm,stateSchema:Pm,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const s=n.context.exitBehavior??t?.exitBehavior??Am,r=n.context.threadLimit??t?.threadLimit,i=n.context.runLimit??t?.runLimit,o=e.threadModelCallCount,a=e.runModelCallCount;if(typeof r=="number"&&r<=o){const l=new Yi({threadLimit:r,threadCount:o});if(s==="end")return{jumpTo:"end",messages:[new N(l.message)]};throw l}if(typeof i=="number"&&i<=a){const l=new Yi({runLimit:i,runCount:a});if(s==="end")return{jumpTo:"end",messages:[new N(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function Nm(...t){return me({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(s){for(let r=0;r<t.length;r++)try{const i=t[r],o=typeof i=="string"?await Zt(i):i;return await n({...e,model:o})}catch(i){if(r===t.length-1)throw i}throw s}}})}function Om(t,e){const{backoffFactor:n,initialDelayMs:s,maxDelayMs:r,jitter:i}=t;let o;if(n===0?o=s:o=s*n**e,o=Math.min(o,r),i&&o>0){const a=o*.25;o=o+(Math.random()*2-1)*a,o=Math.max(0,o)}return o}const Xi=W({maxRetries:F().min(0).default(2),tools:Fe(Me([le(),le(),ne()])).optional(),retryOn:Me([ns().args(rs(Error)).returns(ss()),Fe(le())]).default(()=>()=>!0),onFailure:Me([vt("raise"),vt("return_message"),ns().args(rs(Error)).returns(ne())]).default("return_message"),backoffFactor:F().min(0).default(2),initialDelayMs:F().min(0).default(1e3),maxDelayMs:F().min(0).default(6e4),jitter:ss().default(!0)});function Im(t={}){const{maxRetries:e,tools:n,retryOn:s,onFailure:r,backoffFactor:i,initialDelayMs:o,maxDelayMs:a,jitter:l}=Xi.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 s=="function"?s(p):s.some(S=>p.constructor===S),d={backoffFactor:i,initialDelayMs:o,maxDelayMs:a,jitter:l},f=(p,S,C)=>{const m=S.constructor.name;return`Tool '${p}' failed after ${C} ${C===1?"attempt":"attempts"} with ${m}`},y=(p,S,C,m)=>{if(r==="raise")throw C;let w;return typeof r=="function"?w=r(C):w=f(p,C,m),new U({content:w,tool_call_id:S,name:p,status:"error"})};return me({name:"toolRetryMiddleware",contextSchema:Xi,wrapToolCall:async(p,S)=>{const C=p.tool.name;if(!u(C))return S(p);const m=p.toolCall.id??"";for(let w=0;w<=e;w++)try{return await S(p)}catch(b){const T=w+1,x=b&&typeof b=="object"&&"message"in b?b:new Error(String(b));if(!h(x))return y(C,m,x,T);if(w<e){const _=Om(d,w);_>0&&await Mu(_)}else return y(C,m,x,T)}throw new Error("Unexpected: retry loop completed without returning")}})}var Rm={};ho(Rm,{AIMessage:()=>N,AIMessageChunk:()=>Vt,BaseMessage:()=>an,BaseMessageChunk:()=>lu,ClearToolUsesEdit:()=>bl,Document:()=>De,DynamicStructuredTool:()=>so,DynamicTool:()=>Yl,FakeToolCallingModel:()=>Td,HumanMessage:()=>oe,HumanMessageChunk:()=>au,InMemoryStore:()=>xo,MultipleStructuredOutputsError:()=>ir,MultipleToolsBoundError:()=>rr,ProviderStrategy:()=>rt,StructuredOutputParsingError:()=>go,StructuredTool:()=>vs,SystemMessage:()=>_e,SystemMessageChunk:()=>ou,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>kl,Tool:()=>ql,ToolCallLimitExceededError:()=>Tl,ToolInvocationError:()=>Dr,ToolMessage:()=>U,ToolMessageChunk:()=>iu,ToolStrategy:()=>Be,anthropicPromptCachingMiddleware:()=>im,contextEditingMiddleware:()=>wm,countTokensApproximately:()=>Fr,createAgent:()=>gl,createMiddleware:()=>me,dynamicSystemPromptMiddleware:()=>om,filterMessages:()=>ru,humanInTheLoopMiddleware:()=>Qp,initChatModel:()=>Zt,llmToolSelectorMiddleware:()=>um,modelCallLimitMiddleware:()=>xl,modelFallbackMiddleware:()=>Nm,piiRedactionMiddleware:()=>gm,providerStrategy:()=>xu,summarizationMiddleware:()=>Up,todoListMiddleware:()=>xm,tool:()=>no,toolCallLimitMiddleware:()=>Cm,toolRetryMiddleware:()=>Im,toolStrategy:()=>Eu,trimMessages:()=>co});var _s={},kt,$m=(kt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const s=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(g.info("No active sessions found, creating new ones..."),await e.createAllSessions());const r=e.getAllActiveSessions(),i=Object.values(r).map(o=>o.connector);return s.createToolsFromConnectors(i)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const r=this.connectorToolMap.get(e);return g.debug(`Returning ${r.length} existing tools for connector`),r}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const r of e.tools){const i=this.convertTool(r,e);i&&n.push(i)}return this.connectorToolMap.set(e,n),g.debug(`Loaded ${n.length} new tools for connector: ${n.map(r=>r?.name??String(r)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const s of e){const r=await this.loadToolsForConnector(s);n.push(...r)}return g.debug(`Available tools: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){g.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return g.error(`Error initializing connector: ${n}`),!1}}return!0}},O(kt,"BaseAdapter"),kt),Et,jm=(Et=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 s=e;for(const[r,i]of Object.entries(n.properties)){if(!(r in s)){if("const"in i)return!1;continue}const o=s[r];if("const"in i&&o!==i.const||"minimum"in i&&typeof o=="number"&&o<i.minimum||"maximum"in i&&typeof o=="number"&&o>i.maximum)return!1}return!0}static validateConditionalSchema(e,n,s){this.validateRequiredProperties(e,n,s),this.validatePropertyPatterns(e,n,s),this.validateNestedConditions(e,n,s)}static validateRequiredProperties(e,n,s){if(n.required){if(typeof e!="object"||e===null){for(const r of n.required)s.addIssue({code:Ms.custom,message:`Required property '${r}' is missing`,path:[r]});return}for(const r of n.required)r in e||s.addIssue({code:Ms.custom,message:`Required property '${r}' is missing`,path:[r]})}}static validatePropertyPatterns(e,n,s){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const r=e;for(const[i,o]of Object.entries(n.properties)){if(!(i in r))continue;const a=r[i];o.pattern&&typeof a=="string"&&(new RegExp(o.pattern).test(a)||s.addIssue({code:Ms.custom,message:`String '${a}' does not match pattern '${o.pattern}'`,path:[i]}))}}static validateNestedConditions(e,n,s){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,s):n.else&&this.validateConditionalSchema(e,n.else,s)}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(r=>r!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const s=e.map(r=>{const i={...n,type:r};return this.parseSchema(i)});return Ps(s)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):ve();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Bl();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Wl();let s=n;return s=this.applyNumberBounds(n,e),s=this.applyNumberMultipleOf(n,e),s=this.applyNumberEnum(n,e),s=this.applyIntegerConstraint(n,e),s}static applyNumberBounds(e,n){let s=e;return n.minimum!==void 0&&(s=n.exclusiveMinimum?s.gt(n.minimum):s.gte(n.minimum)),n.maximum!==void 0&&(s=n.exclusiveMaximum?s.lt(n.maximum):s.lte(n.maximum)),s}static applyNumberMultipleOf(e,n){return n.multipleOf===void 0?e:e.refine(s=>s%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(e,n){if(!n.enum)return e;const s=n.enum.filter(r=>typeof r=="number");return s.length===0?e:e.refine(r=>s.includes(r),{message:`Number must be one of: ${s.join(", ")}`})}static applyIntegerConstraint(e,n){return n.type!=="integer"?e:e.refine(s=>Number.isInteger(s),{message:"Number must be an integer"})}static parseString(e){const n=Or();let s=n;return e.format?this.applyStringFormat(n,e):(s=this.applyStringPattern(n,e),s=this.applyStringLength(n,e),s=this.applyStringEnum(n,e),s)}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 s=new RegExp(n.pattern);return e.regex(s,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const s=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),s}static applyStringEnum(e,n){return n.enum?e.refine(s=>n.enum?.includes(s),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const i=e.items.map(o=>this.parseSchema(o));return Ps(i)}const n=e.items?this.parseSchema(e.items):ve(),s=Hl(n);let r=s;return r=this.applyArrayConstraints(s,e),r}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(s=>new Set(s).size===s.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,Xe(n))}static processObjectProperties(e,n){const s=new Set(e.required||[]);if(e.properties)for(const[r,i]of Object.entries(e.properties)){const o=this.parseSchema(i);n[r]=s.has(r)?o:o.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const s=this.parseSchema(e.additionalProperties);return n.catchall(s)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),s=e.if,r=e.then,i=e.else;return n.superRefine((o,a)=>{const l=this.applyDefaultValues(o,e);this.matchesCondition(l,s)?this.validateConditionalSchema(l,r,a):i&&this.validateConditionalSchema(l,i,a)})}static createBaseObjectSchema(e){const n={},s=new Set(e.required||[]);for(const[i,o]of Object.entries(e.properties||{})){const a=this.parseSchema(o);n[i]=s.has(i)?a:a.optional()}const r=Xe(n);return this.processAdditionalProperties(e,r)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const r={...e};if(!n.properties)return r;for(const[i,o]of Object.entries(n.properties))!(i in r)&&"default"in o&&(r[i]=o.default);return r}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 ve();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const s of e)s.type==="null"?n.push(zl()):n.push(this.parseSchema(s));return n.length>=2?Ps(n):n.length===1?n[0]:ve()}static parseAllOf(e){if(e.length===0)return ve();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((s,r)=>this.mergeSchemas(s,r));return this.parseSchema(n)}static mergeSchemas(e,n){const s={...e,...n};if(e.properties&&n.properties){const r={...e.properties,...n.properties};s.properties=r}if(e.required&&n.required){const r=[...new Set([...e.required,...n.required])];s.required=r}return s}},O(Et,"JSONSchemaToZod"),Et);function Al(t){try{return jm.convert(t)}catch(e){return g.warn(`Failed to convert JSON schema to Zod: ${e}`),ve()}}O(Al,"schemaToZod");var xt,gt=(xt=class extends $m{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const s=e.inputSchema?Al(e.inputSchema):Xe({}).optional();return new so({name:e.name??"NO NAME",description:e.description??"",schema:s,func:O(async i=>{g.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(i)}`);try{const o=await n.callTool(e.name,i);return JSON.stringify(o)}catch(o){return g.error(`Error executing MCP tool: ${o.message}`),`Error executing MCP tool: ${String(o)}`}},"func")})}},O(xt,"LangChainAdapter"),xt),At,xs=(At=class extends vs{name="mcp_server_tool";description="Base tool for MCP server operations.";schema;_manager;constructor(e){super(),this._manager=e}async _call(e,n,s){throw new Error("Method not implemented.")}get manager(){return this._manager}},O(At,"MCPServerTool"),At),Lm=Xe({}),Mt,Dm=(Mt=class extends xs{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."}},O(Mt,"AcquireActiveMCPServerTool"),Mt),Pt,Um=(Pt=class extends vs{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=Xe({serverName:Or().describe("The name for the new MCP server."),serverConfig:ve().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 s=`Server '${e}' added to the client.`;g.debug(`Connecting to new server '${e}' and discovering tools.`);const i=(await this.manager.client.createSession(e)).connector,o=await this.manager.adapter.createToolsFromConnectors([i]);this.manager.serverTools[e]=o,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=o.length;return s+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,s+=`
322
+ `:"")+(t?.systemPrompt??El)})})}const $m="end",Rm=W({threadLimit:F().optional(),runLimit:F().optional(),exitBehavior:zt(["throw","end"]).optional()}),jm=W({threadModelCallCount:F().default(0),runModelCallCount:F().default(0)});var Xi=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 Al(t){return me({name:"ModelCallLimitMiddleware",contextSchema:Rm,stateSchema:jm,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??$m,s=n.context.threadLimit??t?.threadLimit,i=n.context.runLimit??t?.runLimit,o=e.threadModelCallCount,a=e.runModelCallCount;if(typeof s=="number"&&s<=o){const l=new Xi({threadLimit:s,threadCount:o});if(r==="end")return{jumpTo:"end",messages:[new N(l.message)]};throw l}if(typeof i=="number"&&i<=a){const l=new Xi({runLimit:i,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new N(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function Lm(...t){return me({name:"modelFallbackMiddleware",wrapModelCall:async(e,n)=>{try{return await n(e)}catch(r){for(let s=0;s<t.length;s++)try{const i=t[s],o=typeof i=="string"?await Zt(i):i;return await n({...e,model:o})}catch(i){if(s===t.length-1)throw i}throw r}}})}function Dm(t,e){const{backoffFactor:n,initialDelayMs:r,maxDelayMs:s,jitter:i}=t;let o;if(n===0?o=r:o=r*n**e,o=Math.min(o,s),i&&o>0){const a=o*.25;o=o+(Math.random()*2-1)*a,o=Math.max(0,o)}return o}const Zi=W({maxRetries:F().min(0).default(2),tools:Fe(Me([le(),le(),ne()])).optional(),retryOn:Me([nr().args(sr(Error)).returns(rr()),Fe(le())]).default(()=>()=>!0),onFailure:Me([vt("raise"),vt("return_message"),nr().args(sr(Error)).returns(ne())]).default("return_message"),backoffFactor:F().min(0).default(2),initialDelayMs:F().min(0).default(1e3),maxDelayMs:F().min(0).default(6e4),jitter:rr().default(!0)});function Um(t={}){const{maxRetries:e,tools:n,retryOn:r,onFailure:s,backoffFactor:i,initialDelayMs:o,maxDelayMs:a,jitter:l}=Zi.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:i,initialDelayMs:o,maxDelayMs:a,jitter:l},f=(p,S,C)=>{const m=S.constructor.name;return`Tool '${p}' failed after ${C} ${C===1?"attempt":"attempts"} with ${m}`},y=(p,S,C,m)=>{if(s==="raise")throw C;let w;return typeof s=="function"?w=s(C):w=f(p,C,m),new U({content:w,tool_call_id:S,name:p,status:"error"})};return me({name:"toolRetryMiddleware",contextSchema:Zi,wrapToolCall:async(p,S)=>{const C=p.tool.name;if(!u(C))return S(p);const m=p.toolCall.id??"";for(let w=0;w<=e;w++)try{return await S(p)}catch(b){const T=w+1,x=b&&typeof b=="object"&&"message"in b?b:new Error(String(b));if(!h(x))return y(C,m,x,T);if(w<e){const _=Dm(d,w);_>0&&await Ru(_)}else return y(C,m,x,T)}throw new Error("Unexpected: retry loop completed without returning")}})}var Fm={};fo(Fm,{AIMessage:()=>N,AIMessageChunk:()=>Vt,BaseMessage:()=>an,BaseMessageChunk:()=>hu,ClearToolUsesEdit:()=>vl,Document:()=>De,DynamicStructuredTool:()=>so,DynamicTool:()=>Ql,FakeToolCallingModel:()=>Pd,HumanMessage:()=>oe,HumanMessageChunk:()=>uu,InMemoryStore:()=>Ao,MultipleStructuredOutputsError:()=>is,MultipleToolsBoundError:()=>ss,ProviderStrategy:()=>st,StructuredOutputParsingError:()=>yo,StructuredTool:()=>vr,SystemMessage:()=>_e,SystemMessageChunk:()=>cu,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>El,Tool:()=>Zl,ToolCallLimitExceededError:()=>kl,ToolInvocationError:()=>Ds,ToolMessage:()=>U,ToolMessageChunk:()=>lu,ToolStrategy:()=>Be,anthropicPromptCachingMiddleware:()=>hm,contextEditingMiddleware:()=>Tm,countTokensApproximately:()=>Fs,createAgent:()=>yl,createMiddleware:()=>me,dynamicSystemPromptMiddleware:()=>dm,filterMessages:()=>au,humanInTheLoopMiddleware:()=>im,initChatModel:()=>Zt,llmToolSelectorMiddleware:()=>gm,modelCallLimitMiddleware:()=>Al,modelFallbackMiddleware:()=>Lm,piiRedactionMiddleware:()=>Sm,providerStrategy:()=>Iu,summarizationMiddleware:()=>Hp,todoListMiddleware:()=>Im,tool:()=>ro,toolCallLimitMiddleware:()=>Mm,toolRetryMiddleware:()=>Um,toolStrategy:()=>Ou,trimMessages:()=>uo});var _r={},kt,Vm=(kt=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)&&(g.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),i=Object.values(s).map(o=>o.connector);return r.createToolsFromConnectors(i)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return g.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const i=this.convertTool(s,e);i&&n.push(i)}return this.connectorToolMap.set(e,n),g.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 g.debug(`Available tools: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){g.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return g.error(`Error initializing connector: ${n}`),!1}}return!0}},O(kt,"BaseAdapter"),kt),Et,Bm=(Et=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,i]of Object.entries(n.properties)){if(!(s in r)){if("const"in i)return!1;continue}const o=r[s];if("const"in i&&o!==i.const||"minimum"in i&&typeof o=="number"&&o<i.minimum||"maximum"in i&&typeof o=="number"&&o>i.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[i,o]of Object.entries(n.properties)){if(!(i in s))continue;const a=s[i];o.pattern&&typeof a=="string"&&(new RegExp(o.pattern).test(a)||r.addIssue({code:Mr.custom,message:`String '${a}' does not match pattern '${o.pattern}'`,path:[i]}))}}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 i={...n,type:s};return this.parseSchema(i)});return Pr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):ve();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Hl();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Gl();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=Os();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 i=e.items.map(o=>this.parseSchema(o));return Pr(i)}const n=e.items?this.parseSchema(e.items):ve(),r=Kl(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,Xe(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,i]of Object.entries(e.properties)){const o=this.parseSchema(i);n[s]=r.has(s)?o:o.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,i=e.else;return n.superRefine((o,a)=>{const l=this.applyDefaultValues(o,e);this.matchesCondition(l,r)?this.validateConditionalSchema(l,s,a):i&&this.validateConditionalSchema(l,i,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[i,o]of Object.entries(e.properties||{})){const a=this.parseSchema(o);n[i]=r.has(i)?a:a.optional()}const s=Xe(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[i,o]of Object.entries(n.properties))!(i in s)&&"default"in o&&(s[i]=o.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 ve();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Jl()):n.push(this.parseSchema(r));return n.length>=2?Pr(n):n.length===1?n[0]:ve()}static parseAllOf(e){if(e.length===0)return ve();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}},O(Et,"JSONSchemaToZod"),Et);function Ml(t){try{return Bm.convert(t)}catch(e){return g.warn(`Failed to convert JSON schema to Zod: ${e}`),ve()}}O(Ml,"schemaToZod");var xt,gt=(xt=class extends Vm{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?Ml(e.inputSchema):Xe({}).optional();return new so({name:e.name??"NO NAME",description:e.description??"",schema:r,func:O(async i=>{g.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(i)}`);try{const o=await n.callTool(e.name,i);return JSON.stringify(o)}catch(o){return g.error(`Error executing MCP tool: ${o.message}`),`Error executing MCP tool: ${String(o)}`}},"func")})}},O(xt,"LangChainAdapter"),xt),At,xr=(At=class extends vr{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}},O(At,"MCPServerTool"),At),Wm=Xe({}),Mt,zm=(Mt=class extends xr{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Wm;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."}},O(Mt,"AcquireActiveMCPServerTool"),Mt),Pt,Hm=(Pt=class extends vr{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=Xe({serverName:Os().describe("The name for the new MCP server."),serverConfig:ve().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.`;g.debug(`Connecting to new server '${e}' and discovering tools.`);const i=(await this.manager.client.createSession(e)).connector,o=await this.manager.adapter.createToolsFromConnectors([i]);this.manager.serverTools[e]=o,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=o.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
323
323
 
324
324
  ${o.map(l=>l.name).join(`
325
- `)}`,g.info(s),s}catch(s){return g.error(`Failed to add or connect to server '${e}': ${s.message}`),`Failed to add or connect to server '${e}': ${s.message}`}}},O(Pt,"AddMCPServerFromConfigTool"),Pt),Fm=Xe({serverName:Or().describe("The name of the MCP server.")}),Nt,Vm=(Nt=class extends xs{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=Fm;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const s=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${s}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let s=this.manager.client.getSession(e);if(g.debug(`Using existing session for server '${e}'`),s||(g.debug(`Creating new session for server '${e}'`),s=await this.manager.client.createSession(e)),this.manager.activeServer=e,this.manager.serverTools[e]){const o=s.connector,a=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=a,this.manager.initializedServers[e]=!0}const i=(this.manager.serverTools[e]||[]).length;return`Connected to MCP server '${e}'. ${i} tools are now available.`}catch(s){return g.error(`Error connecting to server '${e}': ${String(s)}`),`Failed to connect to server '${e}': ${String(s)}`}}},O(Nt,"ConnectMCPServerTool"),Nt),Bm=Xe({}),Ot,Wm=(Ot=class extends xs{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 s of e){const i=s===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${s}${i}`);try{const o=this.manager.serverTools?.[s]??[],a=Array.isArray(o)?o.length:0;n.push(`${a} tools available for this server
326
- `)}catch(o){g.error(`Unexpected error listing tools for server '${s}': ${String(o)}`)}}return n.join(`
327
- `)}},O(Ot,"ListMCPServersTool"),Ot),Hm=Xe({}),It,zm=(It=class extends xs{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Hm;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}'.`}},O(It,"ReleaseMCPServerConnectionTool"),It);function bs(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,s)=>bs(n,e[s]));if(typeof t=="object"&&typeof e=="object"){const n=Object.keys(t),s=Object.keys(e);return n.length!==s.length?!1:n.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&bs(t[r],e[r]))}return!1}O(bs,"isEqual");var Rt,Gm=(Rt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,s){this.client=e,this.adapter=n,this.overrideManagementTools=s}setManagementTools(e){this.overrideManagementTools=e,g.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),s=Object.keys(this.client.getAllActiveSessions());if(n.length===0){g.info("Server Manager State: No servers configured.");return}const r=n.map(i=>({"Server Name":i,Connected:s.includes(i)?"✅":"❌",Initialized:this.initializedServers[i]?"✅":"❌","Tool Count":this.serverTools[i]?.length??0,Active:this.activeServer===i?"✅":"❌"}));g.info(`Server Manager State: [${e}]`),console.table(r)}initialize(){(this.client.getServerNames?.()).length===0&&g.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let s=null;if(s=this.client.getSession(n),g.debug(`Using existing session for server '${n}' to prefetch tools.`),s||(s=await this.client.createSession(n).catch(r=>(g.warn(`Could not create session for '${n}' during prefetch: ${r}`),null)),g.debug(`Temporarily created session for '${n}' to prefetch tools.`)),s){const r=s.connector;let i=[];try{i=await this.adapter.createToolsFromConnectors([r])}catch(l){g.error(`Failed to create tools from connector for server '${n}': ${l}`);continue}const o=this.serverTools[n];!o||!bs(o,i)?(this.serverTools[n]=i,this.initializedServers[n]=!0,g.debug(`Prefetched ${i.length} tools for server '${n}'.`)):g.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(s){g.error(`Error prefetching tools for server '${n}': ${s}`)}}get tools(){g.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Um(this),new Wm(this),new Vm(this),new Dm(this),new zm(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return g.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},O(Rt,"ServerManager"),Rt),$t,Zi=($t=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 dn(async()=>{const{langfuseHandler:r,langfuseInitPromise:i}=await Promise.resolve().then(()=>Qi);return{langfuseHandler:r,langfuseInitPromise:i}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:r}=await dn(async()=>{const{initializeLangfuse:i}=await Promise.resolve().then(()=>Qi);return{initializeLangfuse:i}},void 0);await r(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),g.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const r=n();r&&await r}const s=e();s&&(this.availableHandlers.push(s),this.handlerNames.push("Langfuse"),g.debug("ObservabilityManager: Langfuse handler available"))}catch{g.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(g.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?g.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):g.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(g.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(),s=this.metadataProvider?this.metadataProvider():this.metadata||{},r=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:s,tags:r}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),g.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],g.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();g.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();g.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},O($t,"ObservabilityManager"),$t),jt,Km=(jt=class{},O(jt,"BaseTelemetryEvent"),jt),Lt,Jm=(Lt=class extends Km{constructor(e){super(),this.data=e}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},O(Lt,"MCPAgentExecutionEvent"),Lt);function Qn(){try{if(typeof __dirname>"u"||typeof Qs>"u")return"unknown";const t=es(__dirname,"../../package.json");return JSON.parse((void 0)(t,"utf-8")).version||"unknown"}catch{return"unknown"}}O(Qn,"getPackageVersion");function Ml(t){return t._llm_type||t.constructor.name.toLowerCase()}O(Ml,"getModelProvider");function Pl(t){if("_identifyingParams"in t){const e=t._identifyingParams;if(typeof e=="object"&&e!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in e)return String(e[n])}}return t.model||t.modelName||t.constructor.name}O(Pl,"getModelName");function Nl(t){return[Ml(t),Pl(t)]}O(Nl,"extractModelInfo");function hn(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"&&(typeof Qs<"u"&&typeof Qs<"u"&&!1)}catch{return!1}}O(hn,"isNodeJSEnvironment");var Dt,qm=(Dt=class{endpoint;timeout;constructor(e,n=3e3){this.endpoint=e,this.timeout=n}async logEvent(e){try{const n=new AbortController,s=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:n.signal});if(clearTimeout(s),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch(n){g.debug(`Failed to send Scarf event: ${n}`)}}},O(Dt,"ScarfEventLogger"),Dt);function Pr(){if(!hn())return"/tmp/mcp_use_cache";const t=_s.XDG_CACHE_HOME;if(t&&Xl(t))return t;const e=(void 0)();return es(e,".cache")}O(Pr,"getCacheHome");var Ce,Nr=(Ce=class{USER_ID_PATH=es(Pr(),"mcp_use_3","telemetry_user_id");VERSION_DOWNLOAD_PATH=es(Pr(),"mcp_use","download_version");PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="typescript";constructor(){const e=hn(),n=typeof process<"u"&&_s?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||!1;if(this._source=typeof process<"u"&&_s?.MCP_USE_TELEMETRY_SOURCE||"typescript",n)this._posthogClient=null,this._scarfClient=null,g.debug("Telemetry disabled via environment variable");else if(!e)this._posthogClient=null,this._scarfClient=null,g.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");else{g.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");try{this._posthogClient=new vu(this.PROJECT_API_KEY,{host:this.HOST,disableGeoip:!1})}catch(s){g.warn(`Failed to initialize PostHog telemetry: ${s}`),this._posthogClient=null}try{this._scarfClient=new qm(this.SCARF_GATEWAY_URL,3e3)}catch(s){g.warn(`Failed to initialize Scarf telemetry: ${s}`),this._scarfClient=null}}}static getInstance(){return Ce.instance||(Ce.instance=new Ce),Ce.instance}setSource(e){this._source=e,g.debug(`Telemetry source set to: ${e}`)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!hn())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{if(!(void 0)(this.USER_ID_PATH)){g.debug(`Creating user ID path: ${this.USER_ID_PATH}`),(void 0)(di(this.USER_ID_PATH),{recursive:!0});const n=Vl();(void 0)(this.USER_ID_PATH,n),this._currUserId=n,g.debug(`User ID path created: ${this.USER_ID_PATH}`)}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(n=>g.debug(`Failed to track package download: ${n}`))}catch(e){g.debug(`Failed to get/create user ID: ${e}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(e){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={...e.properties};n.mcp_use_version=Qn(),n.language="typescript",n.source=this._source,this._posthogClient.capture({distinctId:this.userId,event:e.name,properties:n})}catch(n){g.debug(`Failed to track PostHog event ${e.name}: ${n}`)}if(this._scarfClient)try{const n={};n.mcp_use_version=Qn(),n.user_id=this.userId,n.event=e.name,n.language="typescript",n.source=this._source,await this._scarfClient.logEvent(n)}catch(n){g.debug(`Failed to track Scarf event ${e.name}: ${n}`)}}}async trackPackageDownload(e){if(this._scarfClient&&hn())try{const n=Qn();let s=!1,r=!1;if((void 0)(this.VERSION_DOWNLOAD_PATH)||(s=!0,r=!0,(void 0)(di(this.VERSION_DOWNLOAD_PATH),{recursive:!0}),(void 0)(this.VERSION_DOWNLOAD_PATH,n)),s){g.debug(`Tracking package download event with properties: ${JSON.stringify(e)}`);const i={...e||{}};i.mcp_use_version=n,i.user_id=this.userId,i.event="package_download",i.first_download=r,i.language="typescript",i.source=this._source,await this._scarfClient.logEvent(i)}}catch(n){g.debug(`Failed to track Scarf package_download event: ${n}`)}}async trackAgentExecution(e){const n=new Jm(e);await this.capture(n)}flush(){if(this._posthogClient)try{this._posthogClient.flush(),g.debug("PostHog client telemetry queue flushed")}catch(e){g.debug(`Failed to flush PostHog client: ${e}`)}this._scarfClient&&g.debug("Scarf telemetry events sent immediately (no flush needed)")}shutdown(){if(this._posthogClient)try{this._posthogClient.shutdown(),g.debug("PostHog client shutdown successfully")}catch(e){g.debug(`Error shutting down PostHog client: ${e}`)}this._scarfClient&&g.debug("Scarf telemetry client shutdown (no action needed)")}},O(Ce,"Telemetry"),hi(Ce,"instance",null),Ce);function Ym(t){Nr.getInstance().setSource(t)}O(Ym,"setTelemetrySource");var Xm="/api/v1/chats",Zm="/api/v1/chats/{chat_id}/execute",Ut,Qm=(Ut=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??_s.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 Rn(e)}parseStructuredResponse(e,n){let s;if(typeof e=="object"&&e!==null)if("result"in e){const r=e.result;typeof r=="object"&&r!==null&&"result"in r?s=r.result:s=r}else s=e;else if(typeof e=="string")try{s=JSON.parse(e)}catch{s={content:e}}else s=e;try{return n.parse(s)}catch(r){g.warn(`Failed to parse structured output: ${r}`);const i=n._def?.shape();if(i&&"content"in i)return n.parse({content:String(s)});throw r}}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},s=`${this.baseUrl}${Xm}`;g.info(`📝 Creating chat session for agent ${this.agentId}`);try{const r=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(e)});if(!r.ok){const a=await r.text(),l=r.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 o=(await r.json()).id;return g.info(`✅ Chat session created: ${o}`),o}catch(r){throw r instanceof Error?new TypeError(`Failed to create chat session: ${r.message}`):new Error(`Failed to create chat session: ${String(r)}`)}}async run(e,n,s,r,i){r!==void 0&&g.warn("External history is not yet supported for remote execution");try{g.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const o=this.chatId,a={query:e,max_steps:n??10};i&&(a.output_schema=this.pydanticToJsonSchema(i),g.info("🔧 Using structured output with schema"));const l={"Content-Type":"application/json","x-api-key":this.apiKey},c=`${this.baseUrl}${Zm.replace("{chat_id}",o)}`;g.info(`🚀 Executing agent in chat ${o}`);const u=await fetch(c,{method:"POST",headers:l,body:JSON.stringify(a),signal:AbortSignal.timeout(3e5)});if(!u.ok){const d=await u.text(),f=u.status;throw f===401?(g.error(`❌ Authentication failed: ${d}`),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.")):f===403?(g.error(`❌ Access forbidden: ${d}`),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.`)):f===404?(g.error(`❌ Agent not found: ${d}`),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.`)):f===422?(g.error(`❌ Validation error: ${d}`),new Error(`Request validation failed: ${d}. Please check your query parameters and output schema format.`)):f===500?(g.error(`❌ Server error: ${d}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(g.error(`❌ Remote execution failed with status ${f}: ${d}`),new Error(`Remote agent execution failed: ${f} - ${d}`))}const h=await u.json();if(g.info(`🔧 Response: ${JSON.stringify(h)}`),g.info("✅ Remote execution completed successfully"),typeof h=="object"&&h!==null){if(h.status==="error"||h.error!==null){const d=h.error??String(h);throw g.error(`❌ Remote agent execution failed: ${d}`),new Error(`Remote agent execution failed: ${d}`)}if(String(h).includes("failed to initialize"))throw g.error(`❌ Agent initialization failed: ${h}`),new Error(`Agent initialization failed on remote server. This usually indicates:
325
+ `)}`,g.info(r),r}catch(r){return g.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},O(Pt,"AddMCPServerFromConfigTool"),Pt),Gm=Xe({serverName:Os().describe("The name of the MCP server.")}),Nt,Km=(Nt=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=Gm;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(g.debug(`Using existing session for server '${e}'`),r||(g.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,this.manager.serverTools[e]){const o=r.connector,a=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=a,this.manager.initializedServers[e]=!0}const i=(this.manager.serverTools[e]||[]).length;return`Connected to MCP server '${e}'. ${i} tools are now available.`}catch(r){return g.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},O(Nt,"ConnectMCPServerTool"),Nt),Jm=Xe({}),Ot,qm=(Ot=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 i=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${i}`);try{const o=this.manager.serverTools?.[r]??[],a=Array.isArray(o)?o.length:0;n.push(`${a} tools available for this server
326
+ `)}catch(o){g.error(`Unexpected error listing tools for server '${r}': ${String(o)}`)}}return n.join(`
327
+ `)}},O(Ot,"ListMCPServersTool"),Ot),Ym=Xe({}),It,Xm=(It=class extends xr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Ym;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}'.`}},O(It,"ReleaseMCPServerConnectionTool"),It);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}O(br,"isEqual");var $t,Zm=($t=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,g.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){g.info("Server Manager State: No servers configured.");return}const s=n.map(i=>({"Server Name":i,Connected:r.includes(i)?"✅":"❌",Initialized:this.initializedServers[i]?"✅":"❌","Tool Count":this.serverTools[i]?.length??0,Active:this.activeServer===i?"✅":"❌"}));g.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&g.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),g.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(g.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),g.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let i=[];try{i=await this.adapter.createToolsFromConnectors([s])}catch(l){g.error(`Failed to create tools from connector for server '${n}': ${l}`);continue}const o=this.serverTools[n];!o||!br(o,i)?(this.serverTools[n]=i,this.initializedServers[n]=!0,g.debug(`Prefetched ${i.length} tools for server '${n}'.`)):g.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){g.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){g.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Hm(this),new qm(this),new Km(this),new zm(this),new Xm(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return g.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},O($t,"ServerManager"),$t),Rt,Qi=(Rt=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 dn(async()=>{const{langfuseHandler:s,langfuseInitPromise:i}=await Promise.resolve().then(()=>eo);return{langfuseHandler:s,langfuseInitPromise:i}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await dn(async()=>{const{initializeLangfuse:i}=await Promise.resolve().then(()=>eo);return{initializeLangfuse:i}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),g.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"),g.debug("ObservabilityManager: Langfuse handler available"))}catch{g.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(g.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?g.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):g.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(g.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),g.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],g.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();g.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();g.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},O(Rt,"ObservabilityManager"),Rt),jt,Qm=(jt=class{},O(jt,"BaseTelemetryEvent"),jt),Lt,eg=(Lt=class extends Qm{constructor(e){super(),this.data=e}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},O(Lt,"MCPAgentExecutionEvent"),Lt);function Qn(){try{if(typeof __dirname>"u"||typeof Qr>"u")return"unknown";const t=er(__dirname,"../../package.json");return JSON.parse((void 0)(t,"utf-8")).version||"unknown"}catch{return"unknown"}}O(Qn,"getPackageVersion");function Pl(t){return t._llm_type||t.constructor.name.toLowerCase()}O(Pl,"getModelProvider");function Nl(t){if("_identifyingParams"in t){const e=t._identifyingParams;if(typeof e=="object"&&e!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in e)return String(e[n])}}return t.model||t.modelName||t.constructor.name}O(Nl,"getModelName");function Ol(t){return[Pl(t),Nl(t)]}O(Ol,"extractModelInfo");function hn(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"&&(typeof Qr<"u"&&typeof Qr<"u"&&!1)}catch{return!1}}O(hn,"isNodeJSEnvironment");var Dt,tg=(Dt=class{endpoint;timeout;constructor(e,n=3e3){this.endpoint=e,this.timeout=n}async logEvent(e){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:n.signal});if(clearTimeout(r),!s.ok)throw new Error(`HTTP error! status: ${s.status}`)}catch(n){g.debug(`Failed to send Scarf event: ${n}`)}}},O(Dt,"ScarfEventLogger"),Dt);function Ps(){if(!hn())return"/tmp/mcp_use_cache";const t=_r.XDG_CACHE_HOME;if(t&&ec(t))return t;const e=(void 0)();return er(e,".cache")}O(Ps,"getCacheHome");var Ce,Ns=(Ce=class{USER_ID_PATH=er(Ps(),"mcp_use_3","telemetry_user_id");VERSION_DOWNLOAD_PATH=er(Ps(),"mcp_use","download_version");PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="typescript";constructor(){const e=hn(),n=typeof process<"u"&&_r?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||!1;if(this._source=typeof process<"u"&&_r?.MCP_USE_TELEMETRY_SOURCE||"typescript",n)this._posthogClient=null,this._scarfClient=null,g.debug("Telemetry disabled via environment variable");else if(!e)this._posthogClient=null,this._scarfClient=null,g.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");else{g.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");try{this._posthogClient=new xu(this.PROJECT_API_KEY,{host:this.HOST,disableGeoip:!1})}catch(r){g.warn(`Failed to initialize PostHog telemetry: ${r}`),this._posthogClient=null}try{this._scarfClient=new tg(this.SCARF_GATEWAY_URL,3e3)}catch(r){g.warn(`Failed to initialize Scarf telemetry: ${r}`),this._scarfClient=null}}}static getInstance(){return Ce.instance||(Ce.instance=new Ce),Ce.instance}setSource(e){this._source=e,g.debug(`Telemetry source set to: ${e}`)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!hn())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{if(!(void 0)(this.USER_ID_PATH)){g.debug(`Creating user ID path: ${this.USER_ID_PATH}`),(void 0)(fi(this.USER_ID_PATH),{recursive:!0});const n=zl();(void 0)(this.USER_ID_PATH,n),this._currUserId=n,g.debug(`User ID path created: ${this.USER_ID_PATH}`)}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(n=>g.debug(`Failed to track package download: ${n}`))}catch(e){g.debug(`Failed to get/create user ID: ${e}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}async capture(e){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={...e.properties};n.mcp_use_version=Qn(),n.language="typescript",n.source=this._source,this._posthogClient.capture({distinctId:this.userId,event:e.name,properties:n})}catch(n){g.debug(`Failed to track PostHog event ${e.name}: ${n}`)}if(this._scarfClient)try{const n={};n.mcp_use_version=Qn(),n.user_id=this.userId,n.event=e.name,n.language="typescript",n.source=this._source,await this._scarfClient.logEvent(n)}catch(n){g.debug(`Failed to track Scarf event ${e.name}: ${n}`)}}}async trackPackageDownload(e){if(this._scarfClient&&hn())try{const n=Qn();let r=!1,s=!1;if((void 0)(this.VERSION_DOWNLOAD_PATH)||(r=!0,s=!0,(void 0)(fi(this.VERSION_DOWNLOAD_PATH),{recursive:!0}),(void 0)(this.VERSION_DOWNLOAD_PATH,n)),r){g.debug(`Tracking package download event with properties: ${JSON.stringify(e)}`);const i={...e||{}};i.mcp_use_version=n,i.user_id=this.userId,i.event="package_download",i.first_download=s,i.language="typescript",i.source=this._source,await this._scarfClient.logEvent(i)}}catch(n){g.debug(`Failed to track Scarf package_download event: ${n}`)}}async trackAgentExecution(e){const n=new eg(e);await this.capture(n)}flush(){if(this._posthogClient)try{this._posthogClient.flush(),g.debug("PostHog client telemetry queue flushed")}catch(e){g.debug(`Failed to flush PostHog client: ${e}`)}this._scarfClient&&g.debug("Scarf telemetry events sent immediately (no flush needed)")}shutdown(){if(this._posthogClient)try{this._posthogClient.shutdown(),g.debug("PostHog client shutdown successfully")}catch(e){g.debug(`Error shutting down PostHog client: ${e}`)}this._scarfClient&&g.debug("Scarf telemetry client shutdown (no action needed)")}},O(Ce,"Telemetry"),hi(Ce,"instance",null),Ce);function ng(t){Ns.getInstance().setSource(t)}O(ng,"setTelemetrySource");var rg="/api/v1/chats",sg="/api/v1/chats/{chat_id}/execute",Ut,ig=(Ut=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??_r.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 Rn(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){g.warn(`Failed to parse structured output: ${s}`);const i=n._def?.shape();if(i&&"content"in i)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}${rg}`;g.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 o=(await s.json()).id;return g.info(`✅ Chat session created: ${o}`),o}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,i){s!==void 0&&g.warn("External history is not yet supported for remote execution");try{g.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const o=this.chatId,a={query:e,max_steps:n??10};i&&(a.output_schema=this.pydanticToJsonSchema(i),g.info("🔧 Using structured output with schema"));const l={"Content-Type":"application/json","x-api-key":this.apiKey},c=`${this.baseUrl}${sg.replace("{chat_id}",o)}`;g.info(`🚀 Executing agent in chat ${o}`);const u=await fetch(c,{method:"POST",headers:l,body:JSON.stringify(a),signal:AbortSignal.timeout(3e5)});if(!u.ok){const d=await u.text(),f=u.status;throw f===401?(g.error(`❌ Authentication failed: ${d}`),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.")):f===403?(g.error(`❌ Access forbidden: ${d}`),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.`)):f===404?(g.error(`❌ Agent not found: ${d}`),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.`)):f===422?(g.error(`❌ Validation error: ${d}`),new Error(`Request validation failed: ${d}. Please check your query parameters and output schema format.`)):f===500?(g.error(`❌ Server error: ${d}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(g.error(`❌ Remote execution failed with status ${f}: ${d}`),new Error(`Remote agent execution failed: ${f} - ${d}`))}const h=await u.json();if(g.info(`🔧 Response: ${JSON.stringify(h)}`),g.info("✅ Remote execution completed successfully"),typeof h=="object"&&h!==null){if(h.status==="error"||h.error!==null){const d=h.error??String(h);throw g.error(`❌ Remote agent execution failed: ${d}`),new Error(`Remote agent execution failed: ${d}`)}if(String(h).includes("failed to initialize"))throw g.error(`❌ Agent initialization failed: ${h}`),new Error(`Agent initialization failed on remote server. This usually indicates:
328
328
  • Invalid agent configuration (LLM model, system prompt)
329
329
  • Missing or invalid MCP server configurations
330
330
  • Network connectivity issues with MCP servers
331
331
  • Missing environment variables or credentials
332
- Raw error: ${h}`)}return i?this.parseStructuredResponse(h,i):typeof h=="object"&&h!==null&&"result"in h?h.result:typeof h=="string"?h:String(h)}catch(o){throw o instanceof Error?o.name==="AbortError"?(g.error(`❌ Remote execution timed out: ${o}`),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.")):(g.error(`❌ Remote execution error: ${o}`),new Error(`Remote agent execution failed: ${o.message}`)):(g.error(`❌ Remote execution error: ${o}`),new Error(`Remote agent execution failed: ${String(o)}`))}}async*stream(e,n,s,r,i){return await this.run(e,n,s,r,i)}async close(){g.info("🔌 Remote agent client closed")}},O(Ut,"RemoteAgent"),Ut);function Ol(t,e){const n=new Set(e??[]),s=[];for(const r of t){if(n.has(r.name))continue;const i=r.description.replace(/\{/g,"{{").replace(/\}/g,"}}");s.push(`- ${r.name}: ${i}`)}return s}O(Ol,"generateToolDescriptions");function Il(t,e,n){const s=e.join(`
333
- `);let r;return t.includes("{tool_descriptions}")?r=t.replace("{tool_descriptions}",s):(console.warn("`{tool_descriptions}` placeholder not found; appending at end."),r=`${t}
332
+ Raw error: ${h}`)}return i?this.parseStructuredResponse(h,i):typeof h=="object"&&h!==null&&"result"in h?h.result:typeof h=="string"?h:String(h)}catch(o){throw o instanceof Error?o.name==="AbortError"?(g.error(`❌ Remote execution timed out: ${o}`),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.")):(g.error(`❌ Remote execution error: ${o}`),new Error(`Remote agent execution failed: ${o.message}`)):(g.error(`❌ Remote execution error: ${o}`),new Error(`Remote agent execution failed: ${String(o)}`))}}async*stream(e,n,r,s,i){return await this.run(e,n,r,s,i)}async close(){g.info("🔌 Remote agent client closed")}},O(Ut,"RemoteAgent"),Ut);function Il(t,e){const n=new Set(e??[]),r=[];for(const s of t){if(n.has(s.name))continue;const i=s.description.replace(/\{/g,"{{").replace(/\}/g,"}}");r.push(`- ${s.name}: ${i}`)}return r}O(Il,"generateToolDescriptions");function $l(t,e,n){const r=e.join(`
333
+ `);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}
334
334
 
335
335
  Available tools:
336
- ${s}`),n&&(r+=`
336
+ ${r}`),n&&(s+=`
337
337
 
338
- ${n}`),r}O(Il,"buildSystemPromptContent");function Rl(t,e,n,s,r,i,o){if(i)return new _e({content:i});const a=s?n:e,l=Ol(t,r),c=Il(a,l,o);return new _e({content:c})}O(Rl,"createSystemMessage");var eg=`You are a helpful AI assistant.
338
+ ${n}`),s}O($l,"buildSystemPromptContent");function Rl(t,e,n,r,s,i,o){if(i)return new _e({content:i});const a=r?n:e,l=Il(t,s),c=$l(a,l,o);return new _e({content:c})}O(Rl,"createSystemMessage");var og=`You are a helpful AI assistant.
339
339
  You have access to the following tools:
340
340
 
341
341
  {tool_descriptions}
@@ -349,7 +349,7 @@ Action Input: the input to the action
349
349
  Observation: the result of the action
350
350
  ... (this Thought/Action/Action Input/Observation can repeat N times)
351
351
  Thought: I now know the final answer
352
- Final Answer: the final answer to the original input question`,tg=`You are a helpful assistant designed to interact with MCP
352
+ Final Answer: the final answer to the original input question`,ag=`You are a helpful assistant designed to interact with MCP
353
353
  (Model Context Protocol) servers. You can manage connections to different servers and use the tools
354
354
  provided by the currently active server.
355
355
 
@@ -372,9 +372,9 @@ You can then use these server-specific tools in subsequent steps.
372
372
  Here are the tools *currently* available to you (this list includes server management tools and will
373
373
  change when you connect to a server):
374
374
  {tool_descriptions}
375
- `,Ft,gg=(Ft=class{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;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=Nr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zi({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(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],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.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");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 Gm(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Nr.getInstance(),this.llm){const[n,s]=Nl(this.llm);this.modelProvider=n,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Zi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:O(()=>this.getMetadata(),"metadataProvider"),tagsProvider:O(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:O(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:O(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:O(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}g.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&g.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const s=this.serverManager.tools;this._tools=s,this._tools.push(...this.additionalTools),g.info(`🔧 Server manager mode active with ${s.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),g.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(r=>r!=="code_mode").length===0&&(g.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),g.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const r=this.sessions.code_mode;if(r)this._tools=await this.adapter.createToolsFromConnectors([r.connector]),g.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await gt.createTools(this.client),g.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{g.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const s of this.connectors)s.isClientConnected||await s.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),g.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}g.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),g.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),g.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??eg;this.systemMessage=Rl(e,n,tg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(s=>!(s 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(i=>i.name);g.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const s=[xl({runLimit:this.maxSteps})],r=gl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:s});return g.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),r}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(),g.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&g.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},g.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])],g.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[s,r]of Object.entries(e)){if(typeof s!="string"||s.length===0){g.warn(`Invalid metadata key: ${s}. Skipping.`);continue}const i=s.replace(/[^\w-]/g,"_");if(r==null)n[i]=r;else if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")n[i]=r;else if(Array.isArray(r)){const o=r.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof r=="object")try{const o=JSON.stringify(r);o.length>1e3?(g.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=r}catch(o){g.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else g.warn(`Unsupported metadata value type for key '${i}': ${typeof r}. 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 s={};for(const r of n)try{const i=this.client.getServerConfig(r);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),s[r]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){g.warn(`Failed to get config for server '${r}': ${i}`),s[r]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=s}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){g.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 s of e)if(typeof s=="object"&&s!==null)"text"in s&&typeof s.text=="string"?n.push(s.text):"content"in s?n.push(this._normalizeOutput(s.content)):n.push(String(s));else{const r=s&&typeof s=="object"&&"text"in s?s.text:null;if(typeof r=="string")n.push(r);else{const i=s&&typeof s=="object"&&"content"in s?s.content:s;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const s=n.getType();if(s==="ai"||s==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const s=n._getType();if(s==="ai"||s==="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 oe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const s=n.getType();if(s==="human"||s==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof N||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:s}=await e.next();if(n)return s}}async run(e,n,s,r,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,s,r,i);const o=this.stream(e,n,s,r,i);return this._consumeAndReturn(o)}async*stream(e,n,s=!0,r,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,s,r,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(s&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const C=this.serverManager.tools,m=new Set(C.map(b=>b.name)),w=new Set(this._tools.map(b=>b.name));(m.size!==w.size||[...m].some(b=>!w.has(b)))&&(g.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=C,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=r??this.conversationHistory,d=[];for(const C of h)(this._isHumanMessageLike(C)||this._isAIMessageLike(C))&&d.push(C);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");g.info(`💬 Received query: '${f}'`),g.info("🏁 Starting agent execution");const y=3;let p=0;const S=[...d,new oe(e)];for(;p<=y;){const C={messages:S};let m=!1;const w=await this._agentExecutor.stream(C,{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 b of w){for(const[T,x]of Object.entries(b))if(g.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let _=x.messages;Array.isArray(_)||(_=[_]);for(const v of _)S.includes(v)||S.push(v);for(const v of _){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const A of v.tool_calls){const E=A.name||"unknown",P=A.args||{};this.toolsUsedNames.push(E),u++;let R=JSON.stringify(P);R.length>100&&(R=`${R.slice(0,97)}...`),g.info(`🔧 Tool call: ${E} with input: ${R}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const A=v.content;let E=String(A);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),g.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,R=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(R.size!==V.size||[...R].some(X=>!V.has(X))){g.info(`🔄 Tools changed during execution. New tools: ${[...R].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,g.info(`🔃 Restarting execution with updated tools (restart ${p}/${y})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),g.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>y){g.warn(`⚠️ Max restarts (${y}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new oe(e)),c&&this.addToHistory(new N(c))),i&&c)try{g.info("🔧 Attempting structured output...");const C=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(C)}`)),g.info("✅ Structured output successful"),l=!0,C}catch(C){throw g.error(`❌ Structured output failed: ${C}`),new Error(`Failed to generate structured output: ${C instanceof Error?C.message:String(C)}`)}return g.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw g.error(`❌ Error running query: ${h}`),o&&s&&(g.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,y=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:y.length,toolsAvailableNames:y.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:s,externalHistoryUsed:r!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),s&&!this.client&&o&&(g.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(g.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}g.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)g.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)g.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,g.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,s=!0,r,i){const{prettyStreamEvents:o}=await dn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-QhPf51tE.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,s,r,i)))yield;return a}async*streamEvents(e,n,s=!0,r,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{s&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);g.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(g.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new oe({content:e})));const y=r??this.conversationHistory,p=[];for(const m of y)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):g.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const S=[...p,new oe(e)];g.info("callbacks",this.callbacks);const C=d.streamEvents({messages:S},{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 m of C)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const b=this._normalizeOutput(w.content);h+=b,g.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){g.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,b=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,b=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(b)throw b;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(w)}`)),g.info("✅ Structured output successful"))}catch(m){g.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new N(h));console.log(`
375
+ `,Ft,Sg=(Ft=class{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;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new ig({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=Ns.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qi({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(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],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.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");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 Zm(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Ns.getInstance(),this.llm){const[n,r]=Ol(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Qi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:O(()=>this.getMetadata(),"metadataProvider"),tagsProvider:O(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:O(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:O(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:O(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}g.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&g.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),g.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(),g.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(g.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),g.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]),g.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await gt.createTools(this.client),g.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{g.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),g.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}g.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),g.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),g.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??og;this.systemMessage=Rl(e,n,ag,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(i=>i.name);g.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Al({runLimit:this.maxSteps})],s=yl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return g.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(),g.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&g.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},g.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])],g.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){g.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const i=r.replace(/[^\w-]/g,"_");if(s==null)n[i]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[i]=s;else if(Array.isArray(s)){const o=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof s=="object")try{const o=JSON.stringify(s);o.length>1e3?(g.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){g.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else g.warn(`Unsupported metadata value type for key '${i}': ${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 i=this.client.getServerConfig(s);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),r[s]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){g.warn(`Failed to get config for server '${s}': ${i}`),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){g.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 i=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof N||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,i);const o=this.stream(e,n,r,s,i);return this._consumeAndReturn(o)}async*stream(e,n,r=!0,s,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const C=this.serverManager.tools,m=new Set(C.map(b=>b.name)),w=new Set(this._tools.map(b=>b.name));(m.size!==w.size||[...m].some(b=>!w.has(b)))&&(g.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=C,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const C of h)(this._isHumanMessageLike(C)||this._isAIMessageLike(C))&&d.push(C);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");g.info(`💬 Received query: '${f}'`),g.info("🏁 Starting agent execution");const y=3;let p=0;const S=[...d,new oe(e)];for(;p<=y;){const C={messages:S};let m=!1;const w=await this._agentExecutor.stream(C,{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 b of w){for(const[T,x]of Object.entries(b))if(g.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let _=x.messages;Array.isArray(_)||(_=[_]);for(const v of _)S.includes(v)||S.push(v);for(const v of _){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const A of v.tool_calls){const E=A.name||"unknown",P=A.args||{};this.toolsUsedNames.push(E),u++;let $=JSON.stringify(P);$.length>100&&($=`${$.slice(0,97)}...`),g.info(`🔧 Tool call: ${E} with input: ${$}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const A=v.content;let E=String(A);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),g.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,$=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if($.size!==V.size||[...$].some(X=>!V.has(X))){g.info(`🔄 Tools changed during execution. New tools: ${[...$].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,g.info(`🔃 Restarting execution with updated tools (restart ${p}/${y})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),g.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>y){g.warn(`⚠️ Max restarts (${y}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new oe(e)),c&&this.addToHistory(new N(c))),i&&c)try{g.info("🔧 Attempting structured output...");const C=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(C)}`)),g.info("✅ Structured output successful"),l=!0,C}catch(C){throw g.error(`❌ Structured output failed: ${C}`),new Error(`Failed to generate structured output: ${C instanceof Error?C.message:String(C)}`)}return g.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw g.error(`❌ Error running query: ${h}`),o&&r&&(g.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,y=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:y.length,toolsAvailableNames:y.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),r&&!this.client&&o&&(g.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(g.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}g.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)g.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)g.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,g.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await dn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-CHcXydt4.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,r,s,i)))yield;return a}async*streamEvents(e,n,r=!0,s,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);g.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(g.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new oe({content:e})));const y=s??this.conversationHistory,p=[];for(const m of y)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):g.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const S=[...p,new oe(e)];g.info("callbacks",this.callbacks);const C=d.streamEvents({messages:S},{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 m of C)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const b=this._normalizeOutput(w.content);h+=b,g.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){g.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,b=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,b=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(b)throw b;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(w)}`)),g.info("✅ Structured output successful"))}catch(m){g.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new N(h));console.log(`
376
376
 
377
- `),g.info(`🎉 StreamEvents complete - ${c} events emitted`),l=!0}catch(d){throw g.error(`❌ Error during streamEvents: ${d}`),o&&s&&(g.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),d}finally{const d=Date.now()-a;let f=0;this.client?f=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(f=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:f,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:s,externalHistoryUsed:r!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:d,errorType:l?null:"streaming_error",conversationHistoryLength:y}),s&&!this.client&&o&&(g.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,s){g.info(`🔄 Attempting structured output with schema: ${JSON.stringify(s,null,2)}`),g.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let r=null,i="";if(g.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Rn(s),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")r=n.withStructuredOutput(s);else if(n)r=n;else throw new Error("LLM is required for structured output");const o=Rn(s),{$schema:a,additionalProperties:l,...c}=o;i=JSON.stringify(c,null,2),g.info(`🔄 Schema description: ${i}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),g.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){g.info(`🔄 Structured output attempt ${f}/${h}`);let y=`
377
+ `),g.info(`🎉 StreamEvents complete - ${c} events emitted`),l=!0}catch(d){throw g.error(`❌ Error during streamEvents: ${d}`),o&&r&&(g.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),d}finally{const d=Date.now()-a;let f=0;this.client?f=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(f=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:f,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:d,errorType:l?null:"streaming_error",conversationHistoryLength:y}),r&&!this.client&&o&&(g.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){g.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),g.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,i="";if(g.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Rn(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 o=Rn(r),{$schema:a,additionalProperties:l,...c}=o;i=JSON.stringify(c,null,2),g.info(`🔄 Schema description: ${i}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),g.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){g.info(`🔄 Structured output attempt ${f}/${h}`);let y=`
378
378
  Please format the following information according to the EXACT schema specified below.
379
379
  You must use the exact field names and types as shown in the schema.
380
380
 
@@ -396,7 +396,7 @@ Here are the tools *currently* available to you (this list includes server manag
396
396
  PREVIOUS ATTEMPT FAILED with error: ${d}
397
397
  Please fix the issues mentioned above and ensure the output matches the schema exactly.
398
398
  `);try{g.info(`🔄 Structured output attempt ${f} - using streaming approach`);const p=u.length>300?`${u.slice(0,300)}...`:u;g.info(`🔄 Content being formatted (${u.length} chars): ${p}`),g.info(`🔄 Full format prompt (${y.length} chars):
399
- ${y}`);const S=await r.stream(y);let C=null,m=0;for await(const b of S){if(m++,g.info(`Chunk ${m}: ${JSON.stringify(b,null,2)}`),typeof b=="string")try{C=JSON.parse(b)}catch{g.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{g.warn(`🔄 Failed to parse chunk as JSON: ${b}`)}m%10===0&&g.info(`🔄 Structured output streaming: ${m} chunks`)}if(g.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(C,null,2)}`),!C)throw new Error("No structured result received from stream");const w=this._validateStructuredResult(C,s);return g.info(`✅ Structured output successful on attempt ${f}`),w}catch(p){if(d=p instanceof Error?p.message:String(p),g.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw g.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 s=n.parse(e),r=n;if(r._def&&r._def.shape)for(const[i,o]of Object.entries(r._def.shape)){const a=o,l=a.isOptional?.()??a._def?.typeName==="ZodOptional",c=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!l&&!c){const u=s[i];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${i}' is missing or empty`)}}return s}catch(s){throw g.debug(`Validation details: ${s}`),s}}_enhanceQueryWithSchema(e,n){try{const s=Rn(n),{$schema:r,additionalProperties:i,...o}=s,a=JSON.stringify(o,null,2);return`
399
+ ${y}`);const S=await s.stream(y);let C=null,m=0;for await(const b of S){if(m++,g.info(`Chunk ${m}: ${JSON.stringify(b,null,2)}`),typeof b=="string")try{C=JSON.parse(b)}catch{g.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{g.warn(`🔄 Failed to parse chunk as JSON: ${b}`)}m%10===0&&g.info(`🔄 Structured output streaming: ${m} chunks`)}if(g.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(C,null,2)}`),!C)throw new Error("No structured result received from stream");const w=this._validateStructuredResult(C,r);return g.info(`✅ Structured output successful on attempt ${f}`),w}catch(p){if(d=p instanceof Error?p.message:String(p),g.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw g.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[i,o]of Object.entries(s._def.shape)){const a=o,l=a.isOptional?.()??a._def?.typeName==="ZodOptional",c=a.isNullable?.()??a._def?.typeName==="ZodNullable";if(!l&&!c){const u=r[i];if(u==null||typeof u=="string"&&!u.trim()||Array.isArray(u)&&u.length===0)throw new Error(`Required field '${i}' is missing or empty`)}}return r}catch(r){throw g.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=Rn(n),{$schema:s,additionalProperties:i,...o}=r,a=JSON.stringify(o,null,2);return`
400
400
  ${e}
401
401
 
402
402
  IMPORTANT: Your response must include sufficient information to populate the following structured output:
@@ -405,4 +405,4 @@ ${y}`);const S=await r.stream(y);let C=null,m=0;for await(const b of S){if(m++,g
405
405
 
406
406
  Make sure you gather ALL the required information during your task execution.
407
407
  If any required information is missing, continue working to find it.
408
- `}catch(s){return g.warn(`Could not extract schema details: ${s}`),e}}},O(Ft,"MCPAgent"),Ft),Z={},ng=Z.MCP_USE_LANGFUSE?.toLowerCase()==="false",Cn={handler:null,client:null,initPromise:null};async function ui(t,e,n,s){try{const r=await dn(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!r){g.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:i}=r,u=class u extends i{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,y,p,S){super(d),this.agentId=f,this.metadata=y,this.metadataProvider=p,this.tagsProvider=S,this.verbose=d?.verbose??!1}async handleChainStart(d,f,y,p,S,C,m,w){g.debug("Langfuse: Chain start intercepted");const b=this.getCustomTags(),T=this.getMetadata(),x=[...S||[],...b],_={...C||{},...T};return this.verbose&&(g.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(x)}`),g.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(_)}`)),super.handleChainStart(d,f,y,p,x,_,m,w)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const y=this.tagsProvider();y&&y.length>0&&d.push(...y)}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 y=this.metadataProvider();y&&Object.assign(d,y)}return d}getEnvironmentTag(){const d=Z.MCP_USE_AGENT_ENV;if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return g.debug("Langfuse: LLM start intercepted"),this.verbose&&g.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return g.debug("Langfuse: Tool start intercepted"),this.verbose&&g.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return g.debug("Langfuse: Retriever start intercepted"),this.verbose&&g.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return g.debug("Langfuse: Agent action intercepted"),this.verbose&&g.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return g.debug("Langfuse: Agent end intercepted"),this.verbose&&g.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};O(u,"LoggingCallbackHandler");let o=u;const a=e||(n?n():{}),l=s?s():[],c={publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||Z.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Z.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Z.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Z.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Z.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Z.LANGFUSE_ENABLED!=="false",traceName:a.trace_name||Z.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};g.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),Cn.handler=new o(c,t,e,n,s),g.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await dn(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Cn.client=new d({publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||"https://cloud.langfuse.com"}),g.debug("Langfuse client initialized")}}catch(h){g.debug(`Langfuse client initialization failed: ${h}`)}}catch(r){g.debug(`Langfuse initialization error: ${r}`)}}O(ui,"initializeLangfuse");ng?g.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Z.LANGFUSE_PUBLIC_KEY||!Z.LANGFUSE_SECRET_KEY?g.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Cn.initPromise=ui();var sg=O(()=>Cn.handler,"langfuseHandler"),rg=O(()=>Cn.initPromise,"langfuseInitPromise");const Qi=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:ui,langfuseHandler:sg,langfuseInitPromise:rg},Symbol.toStringTag,{value:"Module"}));export{$m as BaseAdapter,_g as BaseConnector,bg as BrowserOAuthClientProvider,vg as HttpConnector,gt as LangChainAdapter,Sg as Logger,gg as MCPAgent,Cg as MCPClient,Tg as MCPSession,Zi as ObservabilityManager,Qm as RemoteAgent,kg as WebSocketConnector,_u as createReadableStreamFromGenerator,g as logger,Eg as onMcpAuthorization,wu as streamEventsToAISDK,bu as streamEventsToAISDKWithTools};
408
+ `}catch(r){return g.warn(`Could not extract schema details: ${r}`),e}}},O(Ft,"MCPAgent"),Ft),Z={},lg=Z.MCP_USE_LANGFUSE?.toLowerCase()==="false",Cn={handler:null,client:null,initPromise:null};async function ui(t,e,n,r){try{const s=await dn(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){g.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:i}=s,u=class u extends i{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,y,p,S){super(d),this.agentId=f,this.metadata=y,this.metadataProvider=p,this.tagsProvider=S,this.verbose=d?.verbose??!1}async handleChainStart(d,f,y,p,S,C,m,w){g.debug("Langfuse: Chain start intercepted");const b=this.getCustomTags(),T=this.getMetadata(),x=[...S||[],...b],_={...C||{},...T};return this.verbose&&(g.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(x)}`),g.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(_)}`)),super.handleChainStart(d,f,y,p,x,_,m,w)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const y=this.tagsProvider();y&&y.length>0&&d.push(...y)}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 y=this.metadataProvider();y&&Object.assign(d,y)}return d}getEnvironmentTag(){const d=Z.MCP_USE_AGENT_ENV;if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return g.debug("Langfuse: LLM start intercepted"),this.verbose&&g.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return g.debug("Langfuse: Tool start intercepted"),this.verbose&&g.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return g.debug("Langfuse: Retriever start intercepted"),this.verbose&&g.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return g.debug("Langfuse: Agent action intercepted"),this.verbose&&g.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return g.debug("Langfuse: Agent end intercepted"),this.verbose&&g.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};O(u,"LoggingCallbackHandler");let o=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||Z.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Z.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Z.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Z.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Z.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Z.LANGFUSE_ENABLED!=="false",traceName:a.trace_name||Z.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};g.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),Cn.handler=new o(c,t,e,n,r),g.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await dn(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Cn.client=new d({publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||"https://cloud.langfuse.com"}),g.debug("Langfuse client initialized")}}catch(h){g.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){g.debug(`Langfuse initialization error: ${s}`)}}O(ui,"initializeLangfuse");lg?g.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Z.LANGFUSE_PUBLIC_KEY||!Z.LANGFUSE_SECRET_KEY?g.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Cn.initPromise=ui();var cg=O(()=>Cn.handler,"langfuseHandler"),ug=O(()=>Cn.initPromise,"langfuseInitPromise");const eo=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:ui,langfuseHandler:cg,langfuseInitPromise:ug},Symbol.toStringTag,{value:"Module"}));export{Vm as BaseAdapter,kg as BaseConnector,Eg as BrowserOAuthClientProvider,xg as HttpConnector,gt as LangChainAdapter,Ag as Logger,Sg as MCPAgent,Mg as MCPClient,Pg as MCPSession,Qi as ObservabilityManager,ig as RemoteAgent,Ng as WebSocketConnector,ku as createReadableStreamFromGenerator,g as logger,Og as onMcpAuthorization,Tu as streamEventsToAISDK,Eu as streamEventsToAISDKWithTools};