@mcp-use/inspector 0.12.1-canary.1 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{browser-DhQAQTLS.js → browser-BkEQm5XA.js} +51 -53
- package/dist/client/assets/{display-A5IEINAP-BjtA5bgX.js → display-A5IEINAP-DpBhpnVp.js} +2 -2
- package/dist/client/assets/{embeddings-DWqXM9cI.js → embeddings-BjqR6j1c.js} +1 -1
- package/dist/client/assets/{index-C522z4fg.js → index-0X1YJN4v.js} +1 -1
- package/dist/client/assets/{index-Dsn6bJ_W.js → index-B1PreNe0.js} +1 -1
- package/dist/client/assets/{index-Dx3O2_mP.js → index-BC5u-13_.js} +6 -6
- package/dist/client/assets/{index-I27vQsLz.js → index-CFtKkx0H.js} +1 -1
- package/dist/client/assets/{index-XUbcs2v4.js → index-Cqz7K5OL.js} +1 -1
- package/dist/client/assets/{index-CppzqsxT.js → index-CwYT935A.js} +1 -1
- package/dist/client/assets/{index-H8hjVEcK.js → index-D6vvHfT9.js} +1 -1
- package/dist/client/assets/{index-FYQEmRnY.js → index-VkukvMUC.js} +1 -1
- package/dist/client/assets/{index-ZgUrgLDI.js → index-ev3-8tlr.js} +1 -1
- package/dist/client/assets/{winston-Cj1D1cto.js → winston-rar8s7Ad.js} +1 -1
- package/dist/client/index.html +2 -2
- package/package.json +4 -4
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-
|
|
2
|
-
import{t as
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-DpBhpnVp.js","assets/index-BC5u-13_.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as ei,u as Cl,v as kl,_ as j,w as _e,Z as Tl,$ as El,p as zi,x as xl,T as ti,y as Ml,z as y,a as an,A as Ye,B as _s,C as _r,D as Sr,E as Al,F as Pl,G as Ol,H as Nl}from"./index-BC5u-13_.js";import{I as tg,J as ng,K as rg,L as sg,M as ig,N as og,O as ag,K as lg,V as cg,W as ug,P as hg,Q as dg,Q as fg}from"./index-BC5u-13_.js";import{L as Wi,S as fr,t as Il,o as $l,l as Rl,a as Hi,T as jl,D as Ll,b as Gi}from"./index-Cqz7K5OL.js";import{h as bn,s as Dl,g as Ki,B as Ul,k as Fl,l as Vl,I as Bl,C as zl,m as Wl,t as Hl,n as Gl,o as Kl,p as Jl,q as ql,r as Yl,u as Xl,v as Zl,w as Ql,x as ec,y as tc,R as nc,z as rc,a as sc}from"./index-VkukvMUC.js";import{aP as ic,aQ as Ss,aR as oc,at as Ee,e as Zt,aS as ac,aT as ln,a0 as de,x as nt,aU as Ji,g as lc,aV as Hr,_ as q,ag as Kt,ae as fe,z as O,ad as ee,d as cc,C as uc,aW as hc,p as ni,aA as qi,aX as be,ai as cn,aY as nn,E as Yi,y as Oe,aZ as Cs,B as Gr,D as Lt,am as Dt,a_ as dc,a$ as fc,b0 as pc,b1 as mc,b2 as gc,b3 as yc,b4 as wc,b5 as bc,b6 as vc,b7 as _c,b8 as Sc,b9 as Cc,ba as kc,bb as Tc,bc as Ec,bd as xc,be as Mc,K as Ac,bf as Pc,bg as Oc,bh as Nc,t as je,r as rn,m as $e,L as Xe,aq as Ut,bi as Ic,F as $c,aB as ri,ar as Rc,bj as si,bk as ii,ab as ks,aa as oi,a9 as Kr,ac as jc,S as Lc,a5 as Ts,a8 as Ge,bl as Jn,o as z,bm as ae,bn as Dc,bo as Me,bp as vt,bq as Uc,br as Es,l as U,a6 as Fc,i as Vc,T as Bc,bs as qn,bt as Ue,bu as F,bv as Xi,s as ne,a7 as zc,bw as An,bx as Zi,by as Ft,bz as un,bA as Yn,bB as Xn,bC as Wc,aL as Hc,aJ as Gc,aI as Kc,bD as Jc,aH as Pn}from"./index-CFtKkx0H.js";import{E as Qi,c as qc,e as Yc}from"./embeddings-BjqR6j1c.js";import"./index-DRz5BQNA.js";const Xc=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},Zc=()=>{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 ${Xc(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Cl(r.values[0])}`:`Invalid option: expected one of ${ei(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":""}: ${ei(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 Qc(){return{localeError:Zc()}}kl(Qc());var Cr,Cn,kr=0,Tr=0;function eu(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=Cr),o==null&&(o=Cn)),i==null||o==null){var a=t.random||(t.rng||ic)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Cr&&!t._v6&&(i[0]|=1,Cr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,Cn===void 0&&!t._v6&&(Cn=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Tr+1,u=l-kr+(c-Tr)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>kr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");kr=l,Tr=c,Cn=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||Ss(s)}function tu(t){var e=typeof t=="string"?oc(t):t,n=nu(e);return typeof t=="string"?Ss(n):n}function nu(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 ai(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 li(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?ai(Object(n),!0).forEach(function(r){ru(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ai(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function ru(t,e,n){return(e=su(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function su(t){var e=iu(t,"string");return typeof e=="symbol"?e:e+""}function iu(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 ou(t={},e,n=0){var r=eu(li(li({},t),{},{_v6:!0}),new Uint8Array(16));return r=tu(r),Ss(r)}async function*au(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)}}j(au,"streamEventsToAISDK");function lu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}j(lu,"createReadableStreamFromGenerator");async function*cu(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}}
|
|
6
|
+
`;break}}j(cu,"streamEventsToAISDKWithTools");var uu=Object.defineProperty,eo=(t,e)=>{for(var n in e)uu(t,n,{get:e[n],enumerable:!0})},hu={};eo(hu,{ConfigurableModel:()=>Jr,MODEL_PROVIDER_CONFIG:()=>pr,_inferModelProvider:()=>ro,getChatModelByClassName:()=>no,initChatModel:()=>Jt});const pr={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}},to=Object.keys(pr);async function no(t){const e=Object.entries(pr).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 du(t,e,n={}){const r=e||ro(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=pr[r];if(!s){const l=to.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
|
|
7
7
|
|
|
8
|
-
Supported model providers are: ${l}`)}const{modelProvider:o
|
|
9
|
-
- ${n}`).join("")}.`),this.toolName=t,this.errors=e}},
|
|
10
|
-
Please fix the error and try again.`),this.toolCall=e,this.toolError=n}};function
|
|
11
|
-
All items must be either InteropZodObject or plain JSON schema objects.`)}if(t instanceof Be||t instanceof rt)return[t];const r=li(n);if(de(t))return r?[rt.fromSchema(t)]:[Be.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[rt.fromSchema(t)]:[Be.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function pu(t,e){return ai(t,e)}function mu(t){return rt.fromSchema(t)}const gu=["ChatOpenAI","ChatXAI"],uo=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function li(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return uo.some(r=>n.includes(r))}if(Qn(t))return li(t._defaultConfig.model);if(!As(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||gu.includes(e)&&("model"in t&&uo.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function Ps(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 yr(t){return typeof t=="function"?t:t.hook}function yu(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 ci(t){return iu({clockseq:t})}function mt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Kr(t,new Uint8Array(n))}const wu="__error__",In="__scheduled__",bu="__interrupt__",vu="__resume__";var ho="[...]",_u="[Circular]",er=[],gt=[];function Su(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Cu(t,e,n,r){typeof r>"u"&&(r=Su()),es(t,"",0,[],void 0,0,r);var s;try{gt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,ku(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;er.length!==0;){var o=er.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return s}function Mr(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),er.push([r,n,e,s])):gt.push([e,n,t]):(r[n]=t,er.push([r,n,e]))}function es(t,e,n,r,s,o,i){o+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){Mr(_u,t,e,s);return}if(typeof i.depthLimit<"u"&&o>i.depthLimit){Mr(ho,t,e,s);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){Mr(ho,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)es(t[a],a,a,r,t,o,i);else{var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];es(t[c],c,a,r,t,o,i)}}r.pop()}}function ku(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(gt.length>0)for(var r=0;r<gt.length;r++){var s=gt[r];if(s[1]===e&&s[0]===n){n=s[2],gt.splice(r,1);break}}return t.call(this,e,n)}}const Tu=[];var Eu={},ui={};q(ui,{BaseChatMessageHistory:()=>hi,BaseListChatMessageHistory:()=>Os,InMemoryChatMessageHistory:()=>xu});var hi=class extends Gt{async addMessages(t){for(const e of t)await this.addMessage(e)}},Os=class extends Gt{addUserMessage(t){return this.addMessage(new fe(t))}addAIMessage(t){return this.addMessage(new O(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},xu=class extends Os{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=[]}},Mu={},di={};q(di,{BaseMemory:()=>Au,getInputValue:()=>Pu,getOutputValue:()=>Ou,getPromptInputKey:()=>Nu});var Au=class{};const fi=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Pu=(t,e)=>{const n=fi(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},Ou=(t,e)=>{const n=fi(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 Nu(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 pi={};q(pi,{BaseStore:()=>mi,InMemoryStore:()=>gi});var mi=class extends Gt{},gi=class extends mi{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)}},yi={};q(yi,{BaseRetriever:()=>Ns});var Ns=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=Zt(cc(e)),s=await(await uc.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),t,n.runId,void 0,void 0,void 0,n.runName);try{const o=await this._getRelevantDocuments(t,s);return await s?.handleRetrieverEnd(o),o}catch(o){throw await s?.handleRetrieverError(o),o}}},wi={};q(wi,{SaveableVectorStore:()=>Iu,VectorStore:()=>Is,VectorStoreRetriever:()=>$n});var $n=class extends Ns{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)}},Is=class extends Gt{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(t,e){super(e),this.embeddings=t}async delete(t){throw new Error("Not implemented.")}async similaritySearch(t,e=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)).map(o=>o[0])}async similaritySearchWithScore(t,e=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(t),e,n)}static fromTexts(t,e,n,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(t,e,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(t,e,n,r,s,o){if(typeof t=="number")return new $n({vectorStore:this,k:t,filter:e,tags:[...r??[],this._vectorstoreType()],metadata:s,verbose:o,callbacks:n});{const i={vectorStore:this,k:t?.k,filter:t?.filter,tags:[...t?.tags??[],this._vectorstoreType()],metadata:t?.metadata,verbose:t?.verbose,callbacks:t?.callbacks,searchType:t?.searchType};return t?.searchType==="mmr"?new $n({...i,searchKwargs:t.searchKwargs}):new $n({...i})}}},Iu=class extends Is{static load(t,e){throw new Error("Not implemented")}},bi={};q(bi,{BaseDocumentLoader:()=>vi});var vi=class{},_i={};q(_i,{LangSmithLoader:()=>$u});var $u=class extends vi{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 hc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Ru,this.datasetId=t.datasetId,this.datasetName=t.datasetName,this.exampleIds=t.exampleIds,this.asOf=t.asOf,this.splits=t.splits,this.inlineS3Urls=t.inlineS3Urls,this.offset=t.offset,this.limit=t.limit,this.metadata=t.metadata,this.filter=t.filter}async load(){const t=[];for await(const e of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=e.inputs;for(const o of this.contentKey)n=n[o];const r=this.formatContent(n),s=e;["created_at","modified_at"].forEach(o=>{o in s&&typeof s[o]=="object"&&(s[o]=s[o].toString())}),t.push({pageContent:r,metadata:s})}return t}};function Ru(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}},Si=class extends ee{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},ju=class extends Si{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},Ci={};q(Ci,{BaseDocumentTransformer:()=>Si,Document:()=>De,MappingDocumentTransformer:()=>ju});var $s=class extends Gt{lc_namespace=["langchain_core","example_selectors","base"]},ki=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Lu=class extends ki{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 Du(t){return t._modelType()==="base_llm"}function Fu(t){return t._modelType()==="base_chat_model"}function fo(t){return t.split(/\n| /).length}var Uu=class Ti extends $s{examples=[];examplePrompt;getTextLength=fo;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??fo}async addExample(e){this.examples.push(e);const n=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(n))}async calculateExampleTextLengths(e,n){if(e.length>0)return e;const{examples:r,examplePrompt:s}=n;return(await Promise.all(r.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(e){const n=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(n),s=0;const o=[];for(;r>0&&s<this.examples.length;){const i=r-this.exampleTextLengths[s];if(i<0)break;o.push(this.examples[s]),r=i,s+=1}return o}static async fromExamples(e,n){const r=new Ti(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function Ar(t){return Object.keys(t).sort().map(e=>t[e])}var Vu=class Ei extends $s{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=Ar(n.reduce((s,o)=>({...s,[o]:e[o]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new De({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=Ar(n.reduce((i,a)=>({...i,[a]:e[a]}),{})).join(" "),o=(await this.vectorStoreRetriever.invoke(r)).map(i=>i.metadata);return this.exampleKeys?o.map(i=>this.exampleKeys.reduce((a,l)=>({...a,[l]:i[l]}),{})):o}static async fromExamples(e,n,r,s={}){const o=s.inputKeys??null,i=e.map(l=>Ar(o?o.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(i,e,n,s);return new Ei({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},xi={};q(xi,{BaseExampleSelector:()=>$s,BasePromptSelector:()=>ki,ConditionalPromptSelector:()=>Lu,LengthBasedExampleSelector:()=>Uu,SemanticSimilarityExampleSelector:()=>Vu,isChatModel:()=>Fu,isLLM:()=>Du});const ts="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Bu=class extends Gt{lc_namespace=["langchain","recordmanagers"]},Mi=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Dl;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 Kr(e,ts)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return Kr(n,ts)}};function Ai(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 Pi(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 Oi(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 Ni=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function zu(t){const{docsSource:e,recordManager:n,vectorStore:r,options:s}=t,{batchSize:o=100,cleanup:i,sourceIdKey:a,cleanupBatchSize:l=1e3,forceUpdate:c=!1}=s??{};if(i==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");const u=Ni(e)?await e.load():e,h=Oi(a??null),d=await n.getTime();let f=0,y=0,p=0,C=0;const S=Ai(o??100,u);for(const m of S){const w=Pi(m.map(E=>Mi.fromDocument(E))),v=w.map(E=>h(E));i==="incremental"&&w.forEach((E,P)=>{if(v[P]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const k=await n.exists(w.map(E=>E.uid)),x=[],b=[],_=[],M=new Set;if(w.forEach((E,P)=>{if(k[P])if(c)M.add(E.uid);else{_.push(E.uid);return}x.push(E.uid),b.push(E.toDocument())}),_.length>0&&(await n.update(_,{timeAtLeast:d}),C+=_.length),b.length>0&&(await r.addDocuments(b,{ids:x}),f+=b.length-M.size,p+=M.size),await n.update(w.map(E=>E.uid),{timeAtLeast:d,groupIds:v}),i==="incremental"){v.forEach(P=>{if(!P)throw new Error("Source id cannot be null")});const E=await n.listKeys({before:d,groupIds:v});E.length>0&&(await r.delete({ids:E}),await n.deleteKeys(E),y+=E.length)}}if(i==="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:C}}var Ii={};q(Ii,{RecordManager:()=>Bu,UUIDV5_NAMESPACE:()=>ts,_HashedDocument:()=>Mi,_batch:()=>Ai,_deduplicateInOrder:()=>Pi,_getSourceIdAssigner:()=>Oi,_isBaseDocumentLoader:()=>Ni,index:()=>zu});var $i=class extends Jo{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)}`)}},Ri=class extends Fl{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 $i(t)}_diff(t,e){return e?Ul(t??{},e):void 0}async parsePartialResult(t){const e=t[0];if(!e.message)return;const{message:n}=e,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?ro(r.arguments):{...r,arguments:ro(r.arguments)}}async parseResult(t){const e=await this.outputParser.parseResult(t);if(!e)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(t)}`);return this.parse(e)}async parse(t){const e=JSON.parse(t);return this.argsOnly||(e.arguments=JSON.parse(e.arguments)),e}getFormatInstructions(){return""}},Wu=class extends Jo{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Ri;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]}},ji={};q(ji,{JsonKeyOutputFunctionsParser:()=>Wu,JsonOutputFunctionsParser:()=>Ri,OutputFunctionsParser:()=>$i});var vn=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,o]of Object.entries(e))typeof o=="string"?n[s]=o:n[s]=await o();return{...n,...t}}async invoke(t,e){const n={...this.metadata,...e?.metadata},r=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),t,{...e,tags:r,metadata:n,runType:"prompt"})}},hn=class extends vn{async formatPromptValue(t){const e=await this.format(t);return new Vl(e)}};var Hu=Object.prototype.toString,Jt=Array.isArray||function(e){return Hu.call(e)==="[object Array]"};function Rs(t){return typeof t=="function"}function Gu(t){return Jt(t)?"array":typeof t}function Pr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function po(t,e){return t!=null&&typeof t=="object"&&e in t}function Ku(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Ju=RegExp.prototype.test;function qu(t,e){return Ju.call(t,e)}var Yu=/\S/;function Xu(t){return!qu(Yu,t)}var Zu={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function Qu(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Zu[n]})}var eh=/\s*/,th=/\s+/,mo=/\s*=/,nh=/\s*\}/,rh=/#|\^|\/|>|\{|&|=|!/;function sh(t,e){if(!t)return[];var n=!1,r=[],s=[],o=[],i=!1,a=!1,l="",c=0;function u(){if(i&&!a)for(;o.length;)delete s[o.pop()];else o=[];i=!1,a=!1}var h,d,f;function y(_){if(typeof _=="string"&&(_=_.split(th,2)),!Jt(_)||_.length!==2)throw new Error("Invalid tags: "+_);h=new RegExp(Pr(_[0])+"\\s*"),d=new RegExp("\\s*"+Pr(_[1])),f=new RegExp("\\s*"+Pr("}"+_[1]))}y(e||ce.tags);for(var p=new _n(t),C,S,m,w,v,k;!p.eos();){if(C=p.pos,m=p.scanUntil(h),m)for(var x=0,b=m.length;x<b;++x)w=m.charAt(x),Xu(w)?(o.push(s.length),l+=w):(a=!0,n=!0,l+=" "),s.push(["text",w,C,C+1]),C+=1,w===`
|
|
12
|
-
`&&(u(),l="",c=0,n=!1);if(!p.scan(h))break;if(
|
|
13
|
-
`),
|
|
14
|
-
`)};
|
|
15
|
-
should be one of ${r}`)}try{const r=n.reduce((s,
|
|
8
|
+
Supported model providers are: ${l}`)}const{modelProvider:i,...o}=n,a=await no(s.className);return new a({model:t,...o})}function ro(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 Jr=class On extends bn{_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 du(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 On({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(e,...n)=>{const r={...this._queuedMethodOperations};return r.withStructuredOutput=[e,...n],new On({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 On({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations});return new Ee({config:n,bound:i})}async invoke(e,n){const r=await this._model(n),s=Zt(n);return r.invoke(e,s)}async stream(e,n){const r=await this._model(n),s=new ac({generator:await r.stream(e,n),config:n});return await s.setup,ln.fromAsyncGenerator(s)}async batch(e,n,r){return super.batch(e,n,r)}async*transform(e,n){const r=await this._model(n),s=Zt(n);yield*r.transform(e,s)}async*streamLog(e,n,r){const s=await this._model(n),i=Zt(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=Zt(n),l=o.streamEvents(e,a,r);for await(const c of l)yield c}return ln.fromAsyncGenerator(i())}};async function Jt(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(":")];to.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 Jr({defaultConfig:{...a,model:t,modelProvider:s},configPrefix:r}):(t&&(a.model=t),s&&(a.modelProvider=s),new Jr({defaultConfig:a,configPrefix:r,configurableFields:o}))}var qr=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.")}},Yr=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}},so=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}},xs=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 Ms(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function Zn(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_model"in t&&typeof t._model=="function"}let fu=0;var Ve=class Xr{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-${++fu}`}if(lc(e)){const a=nt(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 Xr(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=nt(e),o={type:"function",function:s};return new Xr(i,o,n)}parse(e){const r=new Ji(this.schema).validate(e);if(!r.valid)throw new so(this.name,r.errors.map(s=>s.error));return e}},rt=class io{_schemaType;constructor(e){this.schema=e}static fromSchema(e){const n=nt(e);return new io(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new Ji(this.schema).validate(n).valid?n:void 0}catch{}}};function oo(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 Ve||s instanceof rt))return t;if(t.every(s=>de(s)))return t.map(s=>Ve.fromSchema(s,e));if(t.every(s=>typeof s=="object"&&s!==null&&!de(s)))return t.map(s=>Ve.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 Ve||t instanceof rt)return[t];const r=ao(n);if(de(t))return r?[rt.fromSchema(t)]:[Ve.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return r?[rt.fromSchema(t)]:[Ve.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function pu(t,e){return oo(t,e)}function mu(t){return rt.fromSchema(t)}const gu=["ChatOpenAI","ChatXAI"],ci=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function ao(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return ci.some(r=>n.includes(r))}if(Zn(t))return ao(t._defaultConfig.model);if(!Ms(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||gu.includes(e)&&("model"in t&&ci.some(n=>typeof t.model=="string"&&t.model.includes(n))||e==="FakeToolCallingModel"&&"structuredResponse"in t))}function As(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 We(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function mr(t){return typeof t=="function"?t:t.hook}function yu(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 lo(t){return ou({clockseq:t})}function gt(t,e){const n=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return Hr(t,new Uint8Array(n))}const wu="__error__",Nn="__scheduled__",bu="__interrupt__",vu="__resume__";var ui="[...]",_u="[Circular]",Qn=[],yt=[];function Su(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Cu(t,e,n,r){typeof r>"u"&&(r=Su()),Zr(t,"",0,[],void 0,0,r);var s;try{yt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,ku(e),n)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Qn.length!==0;){var i=Qn.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return s}function Er(t,e,n,r){var s=Object.getOwnPropertyDescriptor(r,n);s.get!==void 0?s.configurable?(Object.defineProperty(r,n,{value:t}),Qn.push([r,n,e,s])):yt.push([e,n,t]):(r[n]=t,Qn.push([r,n,e]))}function Zr(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){Er(_u,t,e,s);return}if(typeof o.depthLimit<"u"&&i>o.depthLimit){Er(ui,t,e,s);return}if(typeof o.edgesLimit<"u"&&n+1>o.edgesLimit){Er(ui,t,e,s);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)Zr(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];Zr(t[c],c,a,r,t,i,o)}}r.pop()}}function ku(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(yt.length>0)for(var r=0;r<yt.length;r++){var s=yt[r];if(s[1]===e&&s[0]===n){n=s[2],yt.splice(r,1);break}}return t.call(this,e,n)}}const Tu=[];var Eu={},co={};q(co,{BaseChatMessageHistory:()=>uo,BaseListChatMessageHistory:()=>Ps,InMemoryChatMessageHistory:()=>xu});var uo=class extends Kt{async addMessages(t){for(const e of t)await this.addMessage(e)}},Ps=class extends Kt{addUserMessage(t){return this.addMessage(new fe(t))}addAIMessage(t){return this.addMessage(new O(t))}async addMessages(t){for(const e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},xu=class extends Ps{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=[]}},Mu={},ho={};q(ho,{BaseMemory:()=>Au,getInputValue:()=>Pu,getOutputValue:()=>Ou,getPromptInputKey:()=>Nu});var Au=class{};const fo=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Pu=(t,e)=>{const n=fo(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},Ou=(t,e)=>{const n=fo(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 Nu(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 po={};q(po,{BaseStore:()=>mo,InMemoryStore:()=>go});var mo=class extends Kt{},go=class extends mo{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)}},yo={};q(yo,{BaseRetriever:()=>Os});var Os=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=Zt(cc(e)),s=await(await uc.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}}},wo={};q(wo,{SaveableVectorStore:()=>Iu,VectorStore:()=>Ns,VectorStoreRetriever:()=>In});var In=class extends Os{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)}},Ns=class extends Kt{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 In({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 In({...o,searchKwargs:t.searchKwargs}):new In({...o})}}},Iu=class extends Ns{static load(t,e){throw new Error("Not implemented")}},bo={};q(bo,{BaseDocumentLoader:()=>vo});var vo=class{},_o={};q(_o,{LangSmithLoader:()=>$u});var $u=class extends vo{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 hc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Ru,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 Ru(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch{return String(t)}}var Le=class{pageContent;metadata;id;constructor(t){this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}},So=class extends ee{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},ju=class extends So{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},Co={};q(Co,{BaseDocumentTransformer:()=>So,Document:()=>Le,MappingDocumentTransformer:()=>ju});var Is=class extends Kt{lc_namespace=["langchain_core","example_selectors","base"]},ko=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Lu=class extends ko{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 Du(t){return t._modelType()==="base_llm"}function Uu(t){return t._modelType()==="base_chat_model"}function hi(t){return t.split(/\n| /).length}var Fu=class To extends Is{examples=[];examplePrompt;getTextLength=hi;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??hi}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 To(n);return await Promise.all(e.map(s=>r.addExample(s))),r}};function xr(t){return Object.keys(t).sort().map(e=>t[e])}var Vu=class Eo extends Is{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=xr(n.reduce((s,i)=>({...s,[i]:e[i]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Le({pageContent:r,metadata:e})])}async selectExamples(e){const n=this.inputKeys??Object.keys(e),r=xr(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=>xr(i?i.reduce((c,u)=>({...c,[u]:l[u]}),{}):l).join(" ")),a=await r.fromTexts(o,e,n,s);return new Eo({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},xo={};q(xo,{BaseExampleSelector:()=>Is,BasePromptSelector:()=>ko,ConditionalPromptSelector:()=>Lu,LengthBasedExampleSelector:()=>Fu,SemanticSimilarityExampleSelector:()=>Vu,isChatModel:()=>Uu,isLLM:()=>Du});const Qr="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var Bu=class extends Kt{lc_namespace=["langchain","recordmanagers"]},Mo=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Dl;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 Le({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 Hr(e,Qr)}_hashNestedDictToUUID(t){const e=JSON.stringify(t,Object.keys(t).sort()),n=this.keyEncoder(e);return Hr(n,Qr)}};function Ao(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 Po(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 Oo(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 No=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function zu(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=No(e)?await e.load():e,h=Oo(a??null),d=await n.getTime();let f=0,g=0,p=0,C=0;const S=Ao(i??100,u);for(const m of S){const w=Po(m.map(E=>Mo.fromDocument(E))),v=w.map(E=>h(E));o==="incremental"&&w.forEach((E,P)=>{if(v[P]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const k=await n.exists(w.map(E=>E.uid)),x=[],b=[],_=[],M=new Set;if(w.forEach((E,P)=>{if(k[P])if(c)M.add(E.uid);else{_.push(E.uid);return}x.push(E.uid),b.push(E.toDocument())}),_.length>0&&(await n.update(_,{timeAtLeast:d}),C+=_.length),b.length>0&&(await r.addDocuments(b,{ids:x}),f+=b.length-M.size,p+=M.size),await n.update(w.map(E=>E.uid),{timeAtLeast:d,groupIds:v}),o==="incremental"){v.forEach(P=>{if(!P)throw new Error("Source id cannot be null")});const E=await n.listKeys({before:d,groupIds:v});E.length>0&&(await r.delete({ids:E}),await n.deleteKeys(E),g+=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),g+=m.length,m=await n.listKeys({before:d,limit:l})}return{numAdded:f,numDeleted:g,numUpdated:p,numSkipped:C}}var Io={};q(Io,{RecordManager:()=>Bu,UUIDV5_NAMESPACE:()=>Qr,_HashedDocument:()=>Mo,_batch:()=>Ao,_deduplicateInOrder:()=>Po,_getSourceIdAssigner:()=>Oo,_isBaseDocumentLoader:()=>No,index:()=>zu});var $o=class extends Ki{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)}`)}},Ro=class extends Ul{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 $o(t)}_diff(t,e){return e?Fl(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?ni(r.arguments):{...r,arguments:ni(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""}},Wu=class extends Ki{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Ro;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:()=>Wu,JsonOutputFunctionsParser:()=>Ro,OutputFunctionsParser:()=>$o});var vn=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"})}},hn=class extends vn{async formatPromptValue(t){const e=await this.format(t);return new Vl(e)}};var Hu=Object.prototype.toString,qt=Array.isArray||function(e){return Hu.call(e)==="[object Array]"};function $s(t){return typeof t=="function"}function Gu(t){return qt(t)?"array":typeof t}function Mr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function di(t,e){return t!=null&&typeof t=="object"&&e in t}function Ku(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Ju=RegExp.prototype.test;function qu(t,e){return Ju.call(t,e)}var Yu=/\S/;function Xu(t){return!qu(Yu,t)}var Zu={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function Qu(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Zu[n]})}var eh=/\s*/,th=/\s+/,fi=/\s*=/,nh=/\s*\}/,rh=/#|\^|\/|>|\{|&|=|!/;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 g(_){if(typeof _=="string"&&(_=_.split(th,2)),!qt(_)||_.length!==2)throw new Error("Invalid tags: "+_);h=new RegExp(Mr(_[0])+"\\s*"),d=new RegExp("\\s*"+Mr(_[1])),f=new RegExp("\\s*"+Mr("}"+_[1]))}g(e||ce.tags);for(var p=new _n(t),C,S,m,w,v,k;!p.eos();){if(C=p.pos,m=p.scanUntil(h),m)for(var x=0,b=m.length;x<b;++x)w=m.charAt(x),Xu(w)?(i.push(s.length),l+=w):(a=!0,n=!0,l+=" "),s.push(["text",w,C,C+1]),C+=1,w===`
|
|
12
|
+
`&&(u(),l="",c=0,n=!1);if(!p.scan(h))break;if(o=!0,S=p.scan(rh)||"name",p.scan(eh),S==="="?(m=p.scanUntil(fi),p.scan(fi),p.scanUntil(d)):S==="{"?(m=p.scanUntil(f),p.scan(nh),p.scanUntil(d),S="&"):m=p.scanUntil(d),!p.scan(d))throw new Error("Unclosed tag at "+p.pos);if(S==">"?v=[S,m,C,p.pos,l,c,n]:v=[S,m,C,p.pos],c++,s.push(v),S==="#"||S==="^")r.push(v);else if(S==="/"){if(k=r.pop(),!k)throw new Error('Unopened section "'+m+'" at '+C);if(k[1]!==m)throw new Error('Unclosed section "'+k[1]+'" at '+C)}else S==="name"||S==="{"||S==="&"?a=!0:S==="="&&g(m)}if(u(),k=r.pop(),k)throw new Error('Unclosed section "'+k[1]+'" at '+p.pos);return oh(ih(s))}function ih(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 oh(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 _n(t){this.string=t,this.tail=t,this.pos=0}_n.prototype.eos=function(){return this.tail===""};_n.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};_n.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};function Vt(t,e){this.view=t,this.cache={".":this.view},this.parent=e}Vt.prototype.push=function(e){return new Vt(e,this)};Vt.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=di(i,o[a])||Ku(i,o[a])),i=i[o[a++]];else i=s.view[e],l=di(s.view,e);if(l){r=i;break}s=s.parent}n[e]=r}return $s(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||ce.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 Vt?n:new Vt(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($s(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=$s(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)||ce.escape,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&s===ce.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 ce={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){dn.templateCache=t},get templateCache(){return dn.templateCache}},dn=new ie;ce.clearCache=function(){return dn.clearCache()};ce.parse=function(e,n){return dn.parse(e,n)};ce.render=function(e,n,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Gu(e)+'" was given as the first argument for mustache#render(template, view, partials)');return dn.render(e,n,r,s)};ce.escape=Qu;ce.Scanner=_n;ce.Context=Vt;ce.Writer=ie;function Lo(){ce.escape=t=>t}const fn=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},Do=(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=Do(r[4],s);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},er=t=>{Lo();const e=ce.parse(t);return Do(e)},Uo=(t,e)=>fn(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},""),Fo=(t,e)=>(Lo(),ce.render(t,e)),tr={"f-string":Uo,mustache:Fo},Vo={"f-string":fn,mustache:er},Ce=(t,e,n)=>{try{return tr[e](t,n)}catch(r){throw qi(r,"INVALID_PROMPT_INPUT")}},nr=(t,e)=>Vo[e](t),Sn=(t,e,n)=>{if(!(e in tr)){const r=Object.keys(tr);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")Ce(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Ce(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;Ce(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Ce(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Ke=class Qt extends hn{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))),Sn(this.template,this.templateFormat,n)}}_getPromptType(){return"prompt"}async format(e){const n=await this.mergePartialAndUserVariables(e);return Ce(this.template,this.templateFormat,n)}static fromExamples(e,n,r,s=`
|
|
16
16
|
|
|
17
|
-
`,
|
|
17
|
+
`,i=""){const o=[i,...e,n].join(s);return new Qt({inputVariables:r,template:o})}static fromTemplate(e,n){const{templateFormat:r="f-string",...s}=n??{},i=new Set;return nr(e,r).forEach(o=>{o.type==="variable"&&i.add(o.name)}),new Qt({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 Qt(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 Qt({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}},$n=class Bo extends vn{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))),Sn([{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 Bo(s)}async format(e){const n={};for(const[o,a]of Object.entries(this.template))typeof a=="string"?n[o]=Ce(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 Bl(n)}},es=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=ts(t.template,e);super({inputVariables:n,...t}),this.template=t.template,this.templateFormat=e,this.inputVariables=n}async format(t){return ns(this.template,t,this.templateFormat)}async invoke(t){return await this._callWithConfig(this.format.bind(this),t,{runType:"prompt"})}};function ts(t,e){const n=[];for(const r of Object.values(t))if(typeof r=="string")nr(r,e).forEach(s=>{s.type==="variable"&&n.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?nr(s,e).forEach(i=>{i.type==="variable"&&n.push(i.name)}):typeof s=="object"&&n.push(...ts(s,e));else typeof r=="object"&&r!==null&&n.push(...ts(r,e));return Array.from(new Set(n))}function ns(t,e,n){const r={};for(const[s,i]of Object.entries(t))if(typeof i=="string")r[s]=Ce(i,n,e);else if(Array.isArray(i)){const o=[];for(const a of i)typeof a=="string"?o.push(Ce(a,n,e)):typeof a=="object"&&o.push(ns(a,e,n));r[s]=o}else typeof i=="object"&&i!==null?r[s]=ns(i,e,n):r[s]=i;return r}var gr=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"})}},rs=class extends gr{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(cn):n=[cn(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
|
|
19
|
+
`));throw i.name="InputFormatError",i.lc_error_code=r.lc_error_code,i}return n}},zo=class extends gr{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)]}},Rs=class extends vn{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new zl(e)}},Wo=class extends zo{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(t,e){"prompt"in t||(t={prompt:t,role:e}),super(t),this.role=t.role}async format(t){return new Yi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Ke.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function ah(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function lh(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 js=class extends gr{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(Ke.fromTemplate(t,e));const n=[];for(const r of t)if(typeof r=="string")n.push(Ke.fromTemplate(r,e));else if(r!==null)if(ah(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const i={...e,additionalContentFields:r};n.push(Ke.fromTemplate(s,i))}else if(lh(r)){let s=r.image_url??"",i,o=[];if(typeof s=="string"){let a;e?.templateFormat==="mustache"?a=er(s):a=fn(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: ${s}`);
|
|
21
|
+
From: ${s}`);o=[l[0]]}else o=[];s={url:s},i=new $n({template:s,inputVariables:o,templateFormat:e?.templateFormat,additionalContentFields:r})}else if(typeof s=="object"){if("url"in s){let a;e?.templateFormat==="mustache"?a=er(s.url):a=fn(s.url),o=a.flatMap(l=>l.type==="variable"?[l.name]:[])}else o=[];i=new $n({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 es({template:r,templateFormat:e?.templateFormat}));return new this({prompt:n,additionalOptions:e})}async format(t){if(this.prompt instanceof hn){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 hn){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 $n){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 es){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)]}},Ls=class extends js{static _messageClass(){return fe}static lc_name(){return"HumanMessagePromptTemplate"}},Ho=class extends js{static _messageClass(){return O}static lc_name(){return"AIMessagePromptTemplate"}},Go=class extends js{static _messageClass(){return be}static lc_name(){return"SystemMessagePromptTemplate"}};function ch(t){return typeof t.formatMessages=="function"}function uh(t,e){if(ch(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 rs({variableName:i,optional:!0})}else if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}"){const i=s.slice(1,-1);return new rs({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=cn(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 Ls.fromTemplate(r,e);if(n._getType()==="ai")return Ho.fromTemplate(r,e);if(n._getType()==="system")return Go.fromTemplate(r,e);if(Yi.isInstance(n))return Wo.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function hh(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var Ds=class Rn extends Rs{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 nn))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 Ke.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 nn)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)&&!(hh(s)&&s.optional))throw qi(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 Rn(s)}static fromTemplate(e,n){const r=Ke.fromTemplate(e,n),s=new Ls({prompt:r});return this.fromMessages([s])}static fromMessages(e,n){const r=e.reduce((o,a)=>o.concat(a instanceof Rn?a.promptMessages:[uh(a,n)]),[]),s=e.reduce((o,a)=>a instanceof Rn?Object.assign(o,a.partialVariables):o,Object.create(null)),i=new Set;for(const o of r)if(!(o instanceof nn))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})}},dh=class ss extends hn{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))),Sn(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(
|
|
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))),Sn(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 ss(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 Ce(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 Ke.deserialize(n);let s;if(Array.isArray(e.examples))s=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new ss({inputVariables:e.input_variables,examplePrompt:r,examples:s,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},fh=class Ko extends Rs{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))),Sn(this.prefix+this.suffix,this.templateFormat,n)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const n=await this.mergePartialAndUserVariables(e);let r=await this.getExamples(n);r=r.map(o=>{const i={};return this.examplePrompt.inputVariables.forEach(a=>{i[a]=o[a]}),i});const s=[];for(const o of r){const i=await this.examplePrompt.formatMessages(o);s.push(...i)}return s}async format(e){const n=await this.mergePartialAndUserVariables(e),r=await this.getExamples(n),o=(await Promise.all(r.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return ke(i,this.templateFormat,n)}async partial(e){const n=this.inputVariables.filter(o=>!(o in e)),r={...this.partialVariables??{},...e},s={...this,inputVariables:n,partialVariables:r};return new Ki(s)}},ph=class Ln extends vn{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const e=this.pipelinePrompts.map(r=>r.name),n=this.pipelinePrompts.map(r=>r.prompt.inputVariables.filter(s=>!e.includes(s))).flat();return[...new Set(n)]}static extractRequiredInputValues(e,n){return n.reduce((r,s)=>(r[s]=e[s],r),{})}async formatPipelinePrompts(e){const n=await this.mergePartialAndUserVariables(e);for(const{name:r,prompt:s}of this.pipelinePrompts){const o=Ln.extractRequiredInputValues(n,s.inputVariables);s instanceof Fs?n[r]=await s.formatMessages(o):n[r]=await s.format(o)}return Ln.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 Ln(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function go(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function mh(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 gh=class Ji extends Fs{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(go(e))return super.pipe(e.withStructuredOutput(this.schema));if(mh(e)&&go(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 Ji.fromMessages(e,{schema:n,method:r})}},qi={};q(qi,{AIMessagePromptTemplate:()=>Hi,BaseChatPromptTemplate:()=>js,BaseMessagePromptTemplate:()=>wr,BaseMessageStringPromptTemplate:()=>zi,BasePromptTemplate:()=>vn,BaseStringPromptTemplate:()=>hn,ChatMessagePromptTemplate:()=>Wi,ChatPromptTemplate:()=>Fs,DEFAULT_FORMATTER_MAPPING:()=>nr,DEFAULT_PARSER_MAPPING:()=>Vi,DictPromptTemplate:()=>ns,FewShotChatMessagePromptTemplate:()=>fh,FewShotPromptTemplate:()=>dh,HumanMessagePromptTemplate:()=>Ds,ImagePromptTemplate:()=>Rn,MessagesPlaceholder:()=>os,PipelinePromptTemplate:()=>ph,PromptTemplate:()=>Je,StructuredPrompt:()=>gh,SystemMessagePromptTemplate:()=>Gi,checkValidTemplate:()=>Sn,interpolateFString:()=>Fi,interpolateMustache:()=>Ui,parseFString:()=>fn,parseMustache:()=>tr,parseTemplate:()=>rr,renderTemplate:()=>ke});var Yi={};q(Yi,{BaseDocumentCompressor:()=>yh});var yh=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 Xi=class{},Us=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")}},Vs=class extends Us{},wh=class extends Vs{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},bh=class extends Vs{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},vh=class extends Us{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function Zi(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Ce(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:Zi(t)&&Object.keys(t).length===0:!0}function Qi(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 ea(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 ta(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function na(t){return typeof t=="boolean"}function Bs(t){let e;if(ta(t))e=t;else if(Qi(t))e=parseInt(t,10);else if(ea(t))e=parseFloat(t);else if(na(t))e=!!t;else throw new Error("Unsupported value type");return e}var zs=class extends Xi{},_h=class extends zs{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)]:Bs(t.value)}}}visitStructuredQuery(t){let e={};return t.filter&&(e={filter:t.filter.accept(this)}),e}mergeFilters(t,e,n="and",r=!1){if(!(Ce(t)&&Ce(e))){if(Ce(t)||n==="replace")return Ce(e)?void 0:e;if(Ce(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")}}},Sh=class extends zs{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 r=this.getOperatorFunction(e);return s=>n?n.reduce((o,i)=>{const a=i.accept(this);if(typeof a=="function")return r(o,a(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(t){const{comparator:e,attribute:n,value:r}=t,s=[$.ne];if(this.allowedComparators.includes(e)){if(!this.getAllowedComparatorsForType(typeof r).includes(e))throw new Error(`'${e}' comparator not allowed to be used with ${typeof r}`);const o=this.getComparatorFunction(e);return i=>{const a=i.metadata[n];return a===void 0?!!s.includes(e):o(a,Bs(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(!(Ce(t)&&Ce(e))){if(Ce(t)||n==="replace")return Ce(e)?void 0:e;if(Ce(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")}}},ra={};q(ra,{BaseTranslator:()=>zs,BasicTranslator:()=>_h,Comparators:()=>$,Comparison:()=>wh,Expression:()=>Us,FilterDirective:()=>Vs,FunctionalTranslator:()=>Sh,Operation:()=>bh,Operators:()=>Ge,StructuredQuery:()=>vh,Visitor:()=>Xi,castValue:()=>Bs,isBoolean:()=>na,isFilterEmpty:()=>Ce,isFloat:()=>ea,isInt:()=>Qi,isObject:()=>Zi,isString:()=>ta});var sa={};q(sa,{RunCollectorCallbackHandler:()=>Ch});var Ch=class extends ks{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)}},kh={},oa={};q(oa,{EventStreamContentType:()=>Th,convertEventStreamToIterableReadableDataStream:()=>xh,getBytes:()=>ia,getLines:()=>aa,getMessages:()=>la});const Th="text/event-stream";async function ia(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
|
|
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 Eh(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function
|
|
30
|
-
`);return await n?.handleLLMNewToken(r),{generations:[{message:new O(r),text:r}],llmOutput:{}}}},Fh=class da extends bn{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:e=50,responses:n=[],chunks:r=[],toolStyle:s="openai",thrownErrorString:o,...i}){super(i),this.sleep=e,this.responses=n,this.chunks=r,this.toolStyle=s,this.thrownErrorString=o}_llmType(){return"fake"}bindTools(e){const n=[...this.tools,...e],r=n.map(i=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:i.name,description:i.description,parameters:nt(i.schema)}};case"anthropic":return{name:i.name,description:i.description,input_schema:nt(i.schema)};case"bedrock":return{toolSpec:{name:i.name,description:i.description,inputSchema:nt(i.schema)}};case"google":return{name:i.name,description:i.description,parameters:nt(i.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,o=new da({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return o.tools=n,o.withConfig({tools:s})}async _generate(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new O({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const i of this.chunks){const a=new Jr({message:new jt({content:i.content,tool_calls:i.tool_calls,additional_kwargs:i.additional_kwargs??{}}),text:i.content?.toString()??""});yield a,await r?.handleLLMNewToken(i.content,void 0,void 0,void 0,void 0,{chunk:a})}return}const s=this.responses?.[0]??new O(typeof e[0].content=="string"?e[0].content:""),o=typeof s.content=="string"?s.content:"";for(const i of o){await new Promise(l=>setTimeout(l,this.sleep));const a=new Jr({message:new jt({content:i}),text:i});yield a,await r?.handleLLMNewToken(i,void 0,void 0,void 0,void 0,{chunk:a})}}},Uh=class extends bn{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 O(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 Jr({message:new jt({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 Lt.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")})}},Vh=class extends ei{vectorSize;constructor(t){super(t??{}),this.vectorSize=t?.vectorSize??4}async embedDocuments(t){return Promise.all(t.map(e=>this.embedQuery(e)))}async embedQuery(t){let e=t;e=e.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=e.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=e.length+r;e=e.padEnd(s," ");const o=e.length/this.vectorSize,i=[];for(let l=0;l<e.length;l+=o)i.push(e.slice(l,l+o));return i.map(l=>{let c=0;for(let h=0;h<l.length;h+=1)c+=l===" "?0:l.charCodeAt(h);return c%26/26})}},Bh=class extends ei{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},zh=class extends Go{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}},Wh=class extends Go{sleep=50;responses;thrownErrorString;constructor(t){super(t),this.sleep=t.sleep??this.sleep,this.responses=t.responses,this.thrownErrorString=t.thrownErrorString}_llmType(){return"fake"}async _call(t){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const e=this.responses?.[0];return this.responses=this.responses?.slice(1),e??t}async*_streamResponseChunks(t,e,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const r=this.responses?.[0];this.responses=this.responses?.slice(1);for(const s of r??t)await new Promise(o=>setTimeout(o,this.sleep)),yield{text:s,generationInfo:{}},await n?.handleLLMNewToken(s)}},Hh=class extends hi{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 fe(t))}async addAIMessage(t){this.messages.push(new O(t))}async clear(){this.messages=[]}},Gh=class extends Os{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},Kh=class extends ks{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Jh=class extends Wl{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},qh=class extends Ns{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}},Yh=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}}},Xh=class extends mr{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)}},Zh=class extends ks{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}},Qh=class fa extends Is{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??ca}async addDocuments(e){const n=e.map(({pageContent:r})=>r);return this.addVectors(await this.embeddings.embedDocuments(n),e)}async addVectors(e,n){const r=e.map((s,o)=>({content:n[o].pageContent,embedding:s,metadata:n[o].metadata}));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,n,r){const s=l=>{if(!r)return!0;const c=new De({metadata:l.metadata,pageContent:l.content});return r(c)},o=this.memoryVectors.filter(s);return o.map((l,c)=>({similarity:this.similarity(e,l.embedding),index:c})).sort((l,c)=>l.similarity>c.similarity?-1:0).slice(0,n).map(l=>[new De({metadata:o[l.index].metadata,pageContent:o[l.index].content}),l.similarity])}static async fromTexts(e,n,r,s){const o=[];for(let i=0;i<e.length;i+=1){const a=Array.isArray(n)?n[i]:n,l=new De({pageContent:e[i],metadata:a});o.push(l)}return fa.fromDocuments(o,r,s)}static async fromDocuments(e,n,r){const s=new this(n,r);return await s.addDocuments(e),s}static async fromExistingIndex(e,n){return new this(e,n)}},pa={};q(pa,{FakeChatMessageHistory:()=>Hh,FakeChatModel:()=>Dh,FakeEmbeddings:()=>Bh,FakeLLM:()=>zh,FakeListChatMessageHistory:()=>Gh,FakeListChatModel:()=>Uh,FakeRetriever:()=>qh,FakeRunnable:()=>Yh,FakeSplitIntoListParser:()=>Jh,FakeStreamingChatModel:()=>Fh,FakeStreamingLLM:()=>Wh,FakeTool:()=>Xh,FakeTracer:()=>Kh,FakeVectorStore:()=>Qh,SingleRunExtractor:()=>Zh,SyntheticEmbeddings:()=>Vh});var ma={};q(ma,{agents:()=>Eu,caches:()=>tc,callbacks__base:()=>Mc,callbacks__manager:()=>xc,callbacks__promises:()=>Ec,chat_history:()=>ui,document_loaders__base:()=>bi,document_loaders__langsmith:()=>_i,documents:()=>Ci,embeddings:()=>Yc,example_selectors:()=>xi,index:()=>Mu,indexing:()=>Ii,language_models__base:()=>ec,language_models__chat_models:()=>Ql,language_models__llms:()=>Rl,load__serializable:()=>Tc,memory:()=>di,messages:()=>kc,messages__tool:()=>Cc,output_parsers:()=>Zl,output_parsers__openai_functions:()=>ji,output_parsers__openai_tools:()=>$l,outputs:()=>Sc,prompt_values:()=>Xl,prompts:()=>qi,retrievers:()=>yi,retrievers__document_compressors:()=>Yi,runnables:()=>Yl,runnables__graph:()=>_c,singletons:()=>vc,stores:()=>pi,structured_query:()=>ra,tools:()=>Il,tracers__base:()=>bc,tracers__console:()=>wc,tracers__log_stream:()=>yc,tracers__run_collector:()=>sa,tracers__tracer_langchain:()=>gc,types__stream:()=>kh,utils__async_caller:()=>mc,utils__chunk_array:()=>qc,utils__env:()=>pc,utils__event_source_parse:()=>oa,utils__format:()=>Ah,utils__function_calling:()=>ql,utils__hash:()=>Jl,utils__json_patch:()=>Kl,utils__json_schema:()=>fc,utils__math:()=>ua,utils__stream:()=>dc,utils__testing:()=>pa,utils__tiktoken:()=>Gl,utils__types:()=>Hl,vectorstores:()=>wi});function ed(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 Dn(t){const{optionalImportsMap:e={},optionalImportEntrypoints:n=[],importMap:r={},secretsMap:s={},path:o=["$"]}=this,i=o.join(".");if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="secret"){const a=t,[l]=a.id;if(l in s)return s[l];{const c=Ac(l);if(c)return c;throw new Error(`Missing key "${l}" for ${i} in load(secretsMap={})`)}}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&t.lc===1&&t.type==="not_implemented"){const l=JSON.stringify(t);throw new Error(`Trying to load an object that doesn't implement serialization: ${i} -> ${l}`)}else if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"lc"in t&&"type"in t&&"id"in t&&"kwargs"in t&&t.lc===1){const a=t,l=JSON.stringify(a),[c,...u]=a.id.slice().reverse(),h=u.reverse(),d={langchain_core:ma,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(Tu.concat(n).includes(h.join("/"))||p)if(p!==void 0)f=await e[p];else throw new Error(`Missing key "${h.join("/")}" for ${i} in load(optionalImportsMap={})`);else{let m;if(h[0]==="langchain"||h[0]==="langchain_core")m=d[h[0]],h.shift();else throw new Error(`Invalid namespace: ${i} -> ${l}`);if(h.length===0)throw new Error(`Invalid namespace: ${i} -> ${l}`);let 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: ${i} -> ${l}`);const C=f[c]??Object.values(f).find(m=>typeof m=="function"&&Pc(m)===c);if(typeof C!="function")throw new Error(`Invalid identifer: ${i} -> ${l}`);const S=await Dn.call({...this,path:[...o,"kwargs"]},a.kwargs);if(a.type==="constructor"){const m=new C(Oc(S,Nc,ed(C)));return Object.defineProperty(m.constructor,"name",{value:c}),m}else throw new Error(`Invalid type: ${i} -> ${l}`)}else if(typeof t=="object"&&t!==null)return Array.isArray(t)?Promise.all(t.map((a,l)=>Dn.call({...this,path:[...o,`${l}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,l])=>[a,await Dn.call({...this,path:[...o,a]},l)])));return t}async function td(t,e){const n=JSON.parse(t);return Dn.call({...e},n)}function nd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function ls(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>ls(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await ls(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(nd(e))return td(JSON.stringify(e));return e}}return t}function Nr(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function rd(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Nr(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Nr(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Nr(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(Cu(t,(n,r)=>rd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return ls(e)}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function ga(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=ga(t[n]));return e}function ya(){return{v:4,id:ci(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function sr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:ga(t.versions_seen)}}function wa(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function od(...t){return t.reduce((e,n,r)=>r===0?n:wa(e,n)>=0?e:n)}const id={[wu]:-1,[In]:-2,[bu]:-3,[vu]:-4};var Yt=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function ad(t){if(t.length===0)throw new Yt("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new Yt(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new Yt(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new Yt(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new Yt(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var ld=class{async get(t,e){return(await this.batch([{namespace:t,key:e}]))[0]}async search(t,e={}){const{filter:n,limit:r=10,offset:s=0,query:o}=e;return(await this.batch([{namespacePrefix:t,filter:n,limit:r,offset:s,query:o}]))[0]}async put(t,e,n,r){ad(t),await this.batch([{namespace:t,key:e,value:n,index:r}])}async delete(t,e){await this.batch([{namespace:t,key:e,value:null}])}async listNamespaces(t={}){const{prefix:e,suffix:n,maxDepth:r,limit:s=100,offset:o=0}=t,i=[];return e&&i.push({matchType:"prefix",path:e}),n&&i.push({matchType:"suffix",path:n}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:r,limit:s,offset:o}]))[0]}start(){}stop(){}};const cd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var ud=class extends ld{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=cd(t)}get isRunning(){return this.running}async batch(t){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(t,e){return this.enqueueOperation({namespace:t,key:e})}async search(t,e){const{filter:n,limit:r=10,offset:s=0,query:o}=e||{};return this.enqueueOperation({namespacePrefix:t,filter:n,limit:r,offset:s,query:o})}async put(t,e,n){return this.enqueueOperation({namespace:t,key:e,value:n})}async delete(t,e){return this.enqueueOperation({namespace:t,key:e,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(t){return new Promise((e,n)=>{const r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:t,resolve:e,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;const t=new Map(this.queue);this.queue.clear();try{const e=Array.from(t.values()).map(({operation:r})=>r),n=await this.store.batch(e);t.forEach(({resolve:r},s)=>{const o=Array.from(t.keys()).indexOf(s);r(n[o])})}catch(e){t.forEach(({reject:n})=>{n(e)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},hd=class{serde=new sd;constructor(t){this.serde=t||this.serde}},dd=class ba extends bn{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:n="openai",index:r=0,structuredResponse:s,indexRef:o,...i}={}){super(i),this.toolCalls=e,this.toolStyle=n,this.indexRef=o??{current:r},this.structuredResponse=s}get index(){return this.indexRef.current}set index(e){this.indexRef.current=e}_llmType(){return"fake-tool-calling"}_combineLLMOutput(){return[]}bindTools(e){const n=new ba({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new Lt({func:async()=>this.structuredResponse})}async _generate(e,n,r){let o=e[e.length-1].content;e.length>1&&(o=e.map(h=>h.content).filter(Boolean).join("-")),(e.length===1||e.length===2&&e.every(fe.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new O({content:o,id:l,tool_calls:a.length>0?a.map(u=>({...u,type:"tool_call"})):void 0});return{generations:[{text:o,message:c}],llmOutput:{}}}};class fd{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 pd(){Le.initializeGlobalInstance(new fd)}var ut=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))),Sn(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 Ce(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 Ko(s)}},ph=class jn extends vn{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=jn.extractRequiredInputValues(n,s.inputVariables);s instanceof Ds?n[r]=await s.formatMessages(i):n[r]=await s.format(i)}return jn.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 jn(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function pi(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function mh(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 gh=class Jo extends Ds{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(pi(e))return super.pipe(e.withStructuredOutput(this.schema));if(mh(e)&&pi(e.bound))return super.pipe(new Ee({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 Jo.fromMessages(e,{schema:n,method:r})}},qo={};q(qo,{AIMessagePromptTemplate:()=>Ho,BaseChatPromptTemplate:()=>Rs,BaseMessagePromptTemplate:()=>gr,BaseMessageStringPromptTemplate:()=>zo,BasePromptTemplate:()=>vn,BaseStringPromptTemplate:()=>hn,ChatMessagePromptTemplate:()=>Wo,ChatPromptTemplate:()=>Ds,DEFAULT_FORMATTER_MAPPING:()=>tr,DEFAULT_PARSER_MAPPING:()=>Vo,DictPromptTemplate:()=>es,FewShotChatMessagePromptTemplate:()=>fh,FewShotPromptTemplate:()=>dh,HumanMessagePromptTemplate:()=>Ls,ImagePromptTemplate:()=>$n,MessagesPlaceholder:()=>rs,PipelinePromptTemplate:()=>ph,PromptTemplate:()=>Ke,StructuredPrompt:()=>gh,SystemMessagePromptTemplate:()=>Go,checkValidTemplate:()=>Sn,interpolateFString:()=>Uo,interpolateMustache:()=>Fo,parseFString:()=>fn,parseMustache:()=>er,parseTemplate:()=>nr,renderTemplate:()=>Ce});var Yo={};q(Yo,{BaseDocumentCompressor:()=>yh});var yh=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const He={and:"and",or:"or",not:"not"},$={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var Xo=class{},Us=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")}},Fs=class extends Us{},wh=class extends Fs{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},bh=class extends Fs{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},vh=class extends Us{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function Zo(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Se(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:Zo(t)&&Object.keys(t).length===0:!0}function Qo(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 ea(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 ta(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function na(t){return typeof t=="boolean"}function Vs(t){let e;if(ta(t))e=t;else if(Qo(t))e=parseInt(t,10);else if(ea(t))e=parseFloat(t);else if(na(t))e=!!t;else throw new Error("Unsupported value type");return e}var Bs=class extends Xo{},_h=class extends Bs{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[He.and,He.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 He){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)]:Vs(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")}}},Sh=class extends Bs{allowedOperators=[He.and,He.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 He.and:return(e,n)=>e&&n;case He.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=[$.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,Vs(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")}}},ra={};q(ra,{BaseTranslator:()=>Bs,BasicTranslator:()=>_h,Comparators:()=>$,Comparison:()=>wh,Expression:()=>Us,FilterDirective:()=>Fs,FunctionalTranslator:()=>Sh,Operation:()=>bh,Operators:()=>He,StructuredQuery:()=>vh,Visitor:()=>Xo,castValue:()=>Vs,isBoolean:()=>na,isFilterEmpty:()=>Se,isFloat:()=>ea,isInt:()=>Qo,isObject:()=>Zo,isString:()=>ta});var sa={};q(sa,{RunCollectorCallbackHandler:()=>Ch});var Ch=class extends Cs{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)}},kh={},ia={};q(ia,{EventStreamContentType:()=>Th,convertEventStreamToIterableReadableDataStream:()=>xh,getBytes:()=>oa,getLines:()=>aa,getMessages:()=>la});const Th="text/event-stream";async function oa(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 wt=(function(t){return t[t.NewLine=10]="NewLine",t[t.CarriageReturn=13]="CarriageReturn",t[t.Space=32]="Space",t[t.Colon=58]="Colon",t})(wt||{});function aa(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=Eh(e,o);const l=e.length;let c=0;for(;n<l;){s&&(e[n]===wt.NewLine&&(c=++n),s=!1);let u=-1;for(;n<l&&u===-1;++n)switch(e[n]){case wt.Colon:r===-1&&(r=n-c);break;case wt.CarriageReturn:s=!0;case wt.NewLine:u=n;break}if(u===-1)break;t(e.subarray(c,u),r),c=n,r=-1}c===l?e=void 0:c!==0&&(e=e.subarray(c),n-=c)}}function la(t,e,n){let r=Ar();const s=new TextDecoder;return function(o,a,l){if(l){Mh(r)||(t?.(r),r=Ar());return}if(o.length===0)t?.(r),r=Ar();else if(a>0){const c=s.decode(o.subarray(0,a)),u=a+(o[a+1]===wt.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 Eh(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function Ar(){return{data:"",event:"",id:"",retry:void 0}}function xh(t,e){const n=new ReadableStream({async start(r){const s=la(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 oa(t,aa((o,a,l)=>{s(o,a,l),l&&r.close()}))}});return ln.fromReadableStream(n)}function Mh(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Ah={};function ca(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 Ph(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function Oh(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 Nh(t,e){return Math.sqrt(Oh(t,e))}var ua={};q(ua,{cosineSimilarity:()=>is,euclideanDistance:()=>Rh,innerProduct:()=>$h,matrixFunc:()=>yr,maximalMarginalRelevance:()=>jh,normalize:()=>Ih});function yr(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 Ih(t,e=!1){const n=Lh(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function is(t,e){return yr(t,e,ca)}function $h(t,e){return yr(t,e,Ph)}function Rh(t,e){return yr(t,e,Nh)}function jh(t,e,n=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=Array.isArray(t[0])?t:[t],i=is(s,e)[0],o=ha(i).maxIndex,a=[e[o]],l=[o];for(;l.length<Math.min(r,e.length);){let c=-1/0,u=-1;const h=is(e,a);i.forEach((d,f)=>{if(l.includes(f))return;const g=Math.max(...h[f]),p=n*d-(1-n)*g;p>c&&(c=p,u=f)}),a.push(e[u]),l.push(u)}return l}function ha(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 Lh(t){return t.reduce((e,n)=>Math.max(e,ha(n).maxValue),0)}var Dh=class extends bn{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(t,e,n){if(e?.stop?.length)return{generations:[{message:new O(e.stop[0]),text:e.stop[0]}]};const r=t.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
|
|
30
|
+
`);return await n?.handleLLMNewToken(r),{generations:[{message:new O(r),text:r}],llmOutput:{}}}},Uh=class da extends bn{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:nt(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:nt(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:nt(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:nt(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:r}]:r,i=new da({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 O({content:s,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,n,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const o of this.chunks){const a=new Gr({message:new Lt({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 O(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 Gr({message:new Lt({content:o}),text:o});yield a,await r?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:a})}}},Fh=class extends bn{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 O(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 Gr({message:new Lt({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 Dt.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")})}},Vh=class extends Qi{vectorSize;constructor(t){super(t??{}),this.vectorSize=t?.vectorSize??4}async embedDocuments(t){return Promise.all(t.map(e=>this.embedQuery(e)))}async embedQuery(t){let e=t;e=e.toLowerCase().replaceAll(/[^a-z ]/g,"");const n=e.length%this.vectorSize,r=n===0?0:this.vectorSize-n,s=e.length+r;e=e.padEnd(s," ");const 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})}},Bh=class extends Qi{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},zh=class extends Wi{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}},Wh=class extends Wi{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)}},Hh=class extends uo{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 fe(t))}async addAIMessage(t){this.messages.push(new O(t))}async clear(){this.messages=[]}},Gh=class extends Ps{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},Kh=class extends Cs{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Jh=class extends Wl{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},qh=class extends Os{lc_namespace=["test","fake"];output=[new Le({pageContent:"foo"}),new Le({pageContent:"bar"})];constructor(t){super(),this.output=t?.output??this.output}async _getRelevantDocuments(t){return this.output}},Yh=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}}},Xh=class extends fr{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)}},Zh=class extends Cs{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}},Qh=class fa extends Ns{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??ca}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 Le({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 Le({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 Le({pageContent:e[o],metadata:a});i.push(l)}return fa.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)}},pa={};q(pa,{FakeChatMessageHistory:()=>Hh,FakeChatModel:()=>Dh,FakeEmbeddings:()=>Bh,FakeLLM:()=>zh,FakeListChatMessageHistory:()=>Gh,FakeListChatModel:()=>Fh,FakeRetriever:()=>qh,FakeRunnable:()=>Yh,FakeSplitIntoListParser:()=>Jh,FakeStreamingChatModel:()=>Uh,FakeStreamingLLM:()=>Wh,FakeTool:()=>Xh,FakeTracer:()=>Kh,FakeVectorStore:()=>Qh,SingleRunExtractor:()=>Zh,SyntheticEmbeddings:()=>Vh});var ma={};q(ma,{agents:()=>Eu,caches:()=>tc,callbacks__base:()=>Mc,callbacks__manager:()=>xc,callbacks__promises:()=>Ec,chat_history:()=>co,document_loaders__base:()=>bo,document_loaders__langsmith:()=>_o,documents:()=>Co,embeddings:()=>Yc,example_selectors:()=>xo,index:()=>Mu,indexing:()=>Io,language_models__base:()=>ec,language_models__chat_models:()=>Ql,language_models__llms:()=>Rl,load__serializable:()=>Tc,memory:()=>ho,messages:()=>kc,messages__tool:()=>Cc,output_parsers:()=>Zl,output_parsers__openai_functions:()=>jo,output_parsers__openai_tools:()=>$l,outputs:()=>Sc,prompt_values:()=>Xl,prompts:()=>qo,retrievers:()=>yo,retrievers__document_compressors:()=>Yo,runnables:()=>Yl,runnables__graph:()=>_c,singletons:()=>vc,stores:()=>po,structured_query:()=>ra,tools:()=>Il,tracers__base:()=>bc,tracers__console:()=>wc,tracers__log_stream:()=>yc,tracers__run_collector:()=>sa,tracers__tracer_langchain:()=>gc,types__stream:()=>kh,utils__async_caller:()=>mc,utils__chunk_array:()=>qc,utils__env:()=>pc,utils__event_source_parse:()=>ia,utils__format:()=>Ah,utils__function_calling:()=>ql,utils__hash:()=>Jl,utils__json_patch:()=>Kl,utils__json_schema:()=>fc,utils__math:()=>ua,utils__stream:()=>dc,utils__testing:()=>pa,utils__tiktoken:()=>Gl,utils__types:()=>Hl,vectorstores:()=>wo});function ed(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 Ln(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=Ac(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:ma,langchain:r};let f=null;const g=[h.join("/")];h[0]==="langchain_community"&&g.push(["langchain",...h.slice(1)].join("/"));const p=g.find(m=>m in e);if(Tu.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 C=f[c]??Object.values(f).find(m=>typeof m=="function"&&Pc(m)===c);if(typeof C!="function")throw new Error(`Invalid identifer: ${o} -> ${l}`);const S=await Ln.call({...this,path:[...i,"kwargs"]},a.kwargs);if(a.type==="constructor"){const m=new C(Oc(S,Nc,ed(C)));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)=>Ln.call({...this,path:[...i,`${l}`]},a))):Object.fromEntries(await Promise.all(Object.entries(t).map(async([a,l])=>[a,await Ln.call({...this,path:[...i,a]},l)])));return t}async function td(t,e){const n=JSON.parse(t);return Ln.call({...e},n)}function nd(t){return t!==null&&t.lc===1&&t.type==="constructor"&&Array.isArray(t.id)}async function os(t){if(t&&typeof t=="object"){if(Array.isArray(t))return await Promise.all(t.map(n=>os(n)));{const e={};for(const[n,r]of Object.entries(t))e[n]=await os(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(nd(e))return td(JSON.stringify(e));return e}}return t}function Pr(t,e,n,r){return{lc:2,type:"constructor",id:[t.name],method:e??null,args:n??[],kwargs:r??{}}}function rd(t){return t===void 0?{lc:2,type:"undefined"}:t instanceof Set||t instanceof Map?Pr(t.constructor,void 0,[Array.from(t)]):t instanceof RegExp?Pr(RegExp,void 0,[t.source,t.flags]):t instanceof Error?Pr(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(Cu(t,(n,r)=>rd(r)))}async dumpsTyped(t){return t instanceof Uint8Array?["bytes",t]:["json",this._dumps(t)]}async _loads(t){const e=JSON.parse(t);return os(e)}async loadsTyped(t,e){if(t==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(t==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${t}`)}};function ga(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=ga(t[n]));return e}function ya(){return{v:4,id:lo(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function rr(t){return{v:t.v,id:t.id,ts:t.ts,channel_values:{...t.channel_values},channel_versions:{...t.channel_versions},versions_seen:ga(t.versions_seen)}}function wa(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function id(...t){return t.reduce((e,n,r)=>r===0?n:wa(e,n)>=0?e:n)}const od={[wu]:-1,[Nn]:-2,[bu]:-3,[vu]:-4};var Xt=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function ad(t){if(t.length===0)throw new Xt("Namespace cannot be empty.");for(const e of t){if(typeof e!="string")throw new Xt(`Invalid namespace label '${e}' found in ${t}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new Xt(`Invalid namespace label '${e}' found in ${t}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new Xt(`Namespace labels cannot be empty strings. Got ${e} in ${t}`)}if(t[0]==="langgraph")throw new Xt(`Root label for namespace cannot be "langgraph". Got: ${t}`)}var ld=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){ad(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 cd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var ud=class extends ld{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=cd(t)}get isRunning(){return this.running}async batch(t){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(t,e){return this.enqueueOperation({namespace:t,key:e})}async search(t,e){const{filter:n,limit:r=10,offset:s=0,query: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]"}}},hd=class{serde=new sd;constructor(t){this.serde=t||this.serde}},dd=class ba extends bn{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 ba({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...e],n}withStructuredOutput(e){return new Dt({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(fe.isInstance))&&this.index!==0&&(this.index=0);const a=this.toolCalls[this.index]||[],l=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);const c=new O({content: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 fd{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 pd(){je.initializeGlobalInstance(new fd)}var ut=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}},va=class extends ut{get is_bubble_up(){return!0}},md=class extends ut{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Fn=class extends ut{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},vt=class extends va{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},_a=class extends vt{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Sa=class extends va{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function gd(t){return t!==void 0&&t.name===Sa.unminifiable_name}function Un(t){return t!==void 0&&t.is_bubble_up===!0}function st(t){return t!==void 0&&[vt.unminifiable_name,_a.unminifiable_name].includes(t.name)}var yo=class extends ut{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Q=class extends ut{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ut{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},yd=class extends ut{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function Ca(t){return t!=null&&t.lg_is_channel===!0}var ht=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 cs=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function Ws(t){if(t[cs]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];Ca(r)&&(e[n]=r)}return Object.assign(e,{[cs]:!0}),e}function or(t,e){const n=Ws(t),r={};for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=e.channel_values[s];r[s]=n[s].fromCheckpoint(o)}return Object.assign(r,{[cs]:!0}),r}function tt(t,e,n,r){let s;if(e===void 0)s=t.channel_values;else{s={};for(const o in e)if(Object.prototype.hasOwnProperty.call(e,o))try{s[o]=e[o].checkpoint()}catch(i){if(i.name!==Q.unminifiable_name)throw i}}return{v:4,id:r?.id??ci(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var us=class ka extends ht{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 ka(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}},Hs=class Ta extends ht{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new Ta;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}},wd=class Ea extends ht{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new Ea;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}},bd=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const hs=function(t){return t?ds(t):new Hs};hs.Root=t=>new bd(t);function ds(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new us(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new us(t.value,t.default):new Hs}const L="__start__",A="__end__",Ie="__input__",vd="__copy__",ie="__error__",Ir="__pregel_ns_writes",qe="__pregel_send",Gs="__pregel_call",it="__pregel_read",H="__pregel_checkpointer",ze="__pregel_resuming",sn="__pregel_task_id",ir="__pregel_stream",_d="__pregel_resume_value",Vn="__pregel_resume_map",Ye="__pregel_scratchpad",Bn="__pregel_previous",xa="__pregel_durability",fs="checkpoint_id",Ee="checkpoint_ns",Sd="__pregel_node_finished",ge="checkpoint_map",wo="__pregel_abort_signals",j="__interrupt__",le="__resume__",Ks="__no_writes__",Vt="__return__",$r="__previous__",G="langsmith:hidden",Cd="langsmith:nostream",bo="__self__",we="__pregel_tasks",he="__pregel_push",zn="__pregel_pull",be="00000000-0000-0000-0000-000000000000",kd=[G,Ie,j,le,ie,Ks,qe,it,H,xa,ir,ze,sn,Gs,_d,Ye,Bn,ge,Ee,fs],J="|",Fe=":",vo=Symbol.for("langgraph.command");var Td=class{[vo];constructor(t){this[vo]=t}};function ps(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=pn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function pe(t){return t instanceof re}function Ma(t){return!t||typeof t!="object"||!(j in t)?!1:Array.isArray(t[j])}var K=class extends Td{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)?pn(t.goto):[pn(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 pn(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]=pn(r,e)});else if(Y(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(ps(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]=pn(s,e)}return n}return t}const Ed=["tags","metadata","callbacks","configurable"],xd=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Md=25;function Aa(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Md,configurable:{}},n=Le.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(Ed.includes(r)){let o;Array.isArray(s)?o=[...s]:typeof s=="object"?r==="callbacks"&&"copy"in s&&typeof s.copy=="function"?o=s.copy():o={...s}:o=s,e[r]=o}else e[r]=s}for(const r of t)if(r!==void 0)for(const[s,o]of Object.entries(r))o!==void 0&&xd.includes(s)&&(e[s]=o);for(const[r,s]of Object.entries(e.configurable))e.metadata=e.metadata??{},!r.startsWith("__")&&(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&!(r in e.metadata)&&(e.metadata[r]=s);return e}function Ad(){return Le.getRunnableConfig()}function Rr(t){return t.split(J).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(Fe)[0]).join(J)}function Pd(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 T=t=>BigInt(t),D=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Pa=T("0x9E3779B1"),Oa=T("0x85EBCA77"),Od=T("0xC2B2AE3D"),Ze=T("0x9E3779B185EBCA87"),lt=T("0xC2B2AE3D27D4EB4F"),Na=T("0x165667B19E3779F9"),Js=T("0x85EBCA77C2B2AE63"),Nd=T("0x27D4EB2F165667C5"),Id=T("0x165667919E3779F9"),$d=T("0x9FB21C651E98DF25"),Rd=t=>{const e=t.length;if(e%2!==0)throw new Error("String should have an even number of characters");const n=e/2,r=new Uint8Array(n);let s=0,o=0;for(;o<n;){const i=t.slice(s,s+=2);r[o]=Number.parseInt(i,16),o+=1}return D(r)},Te=Rd("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),_t=(T(1)<<T(128))-T(1),N=(T(1)<<T(64))-T(1),ar=(T(1)<<T(32))-T(1),$e=64,Ia=$e/8,jd=8,kn=4;function Bt(t){if(!t)throw new Error("Assert failed")}function Ld(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Dd(t){let e=t;return e=(e&T(65535))<<T(16)|(e&T(4294901760))>>T(16),e=(e&T(16711935))<<T(8)|(e&T(4278255360))>>T(8),e}function Fd(t,e){return(t&ar)*(e&ar)&N}function Ud(t,e){return(t<<e|t>>T(32)-e)&ar}function $a(t,e,n){for(let r=0;r<Ia;r+=1){const s=e.getBigUint64(r*8,!0),o=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Fd(o,o>>T(32))}return t}function _o(t,e,n,r){for(let s=0;s<r;s+=1)$a(t,D(e,s*$e),D(n,s*8));return t}function Vd(t,e){for(let n=0;n<Ia;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=ms(s,T(47)),s^=r,s*=Pa,t[n]=s&N}return t}function Tn(t,e){return Ra(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(jd,!0))}function So(t,e,n){let r=n;return r+=Tn(t.slice(0),D(e,0*kn)),r+=Tn(t.slice(2),D(e,4*kn)),r+=Tn(t.slice(4),D(e,8*kn)),r+=Tn(t.slice(6),D(e,12*kn)),Me(r&N)}function Bd(t,e,n,r,s){let o=t;const i=Math.floor((n.byteLength-$e)/8),a=$e*i,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)o=_o(o,D(e,c*a),n,i),o=s(o,D(n,n.byteLength-$e));{const c=Math.floor((e.byteLength-1-a*l)/$e);o=_o(o,D(e,l*a),n,c),o=r(o,D(e,e.byteLength-$e),D(n,n.byteLength-$e-7))}return o}function zd(t,e){let n=new BigUint64Array([Od,Ze,lt,Na,Js,Oa,Nd,Pa]);Bt(t.byteLength>128),n=Bd(n,t,e,$a,Vd),Bt(n.length*8===64);{const r=So(n,D(e,11),T(t.byteLength)*Ze&N);return So(n,D(e,e.byteLength-$e-11),~(T(t.byteLength)*lt)&N)<<T(64)|r}}function Ra(t,e){const n=t*e&_t;return n&N^n>>T(64)}function Co(t,e,n){return Ra((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&N,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&N)}function Wn(t,e,n,r,s){let o=t&N,i=t>>T(64)&N;return o+=Co(e,r,s),o^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),o&=N,i+=Co(n,D(r,16),s),i^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),i&=N,i<<T(64)|o}function Me(t){let e=t;return e^=e>>T(37),e*=Id,e&=N,e^=e>>T(32),e}function lr(t){let e=t;return e^=e>>T(33),e*=lt,e&=N,e^=e>>T(29),e*=Na,e&=N,e^=e>>T(32),e}function Wd(t,e,n){const r=t.byteLength;Bt(r>0&&r<=3);const s=T(t.getUint8(r-1))|T(r<<8)|T(t.getUint8(0)<<16)|T(t.getUint8(r>>1)<<24),o=(T(e.getUint32(0,!0))^T(e.getUint32(4,!0)))+n,i=(s^o)&N,a=(T(e.getUint32(8,!0))^T(e.getUint32(12,!0)))-n,l=(Ud(Dd(s),T(13))^a)&N;return(lr(l)&N)<<T(64)|lr(i)}function ms(t,e){return t^t>>e}function Hd(t,e,n){const r=t.byteLength;Bt(r>=4&&r<=8);{const s=t.getUint32(0,!0),o=t.getUint32(r-4,!0),i=T(s)|T(o)<<T(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&N;let c=(i^a)*(Ze+(T(r)<<T(2)))&_t;return c+=(c&N)<<T(65),c&=_t,c^=c>>T(67),ms(ms(c&N,T(35))*$d&N,T(28))|Me(c>>T(64))<<T(64)}}function Gd(t,e,n){const r=t.byteLength;Bt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&N,o=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&N,i=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(i^a^s)*Ze;const c=(l&N)+(T(r-1)<<T(54));l=l&(_t^N)|c,a^=o,l+=a+(a&ar)*(Oa-T(1))<<T(64),l&=_t,l^=Ld(l>>T(64));let u=(l&N)*lt;return u+=(l>>T(64))*lt<<T(64),u&=_t,Me(u&N)|Me(u>>T(64))<<T(64)}}function Kd(t,e){const n=t.byteLength;return Bt(n<=16),n>8?Gd(t,Te,e):n>=4?Hd(t,Te,e):n>0?Wd(t,Te,e):lr(e^Te.getBigUint64(64,!0)^Te.getBigUint64(72,!0))|lr(e^Te.getBigUint64(80,!0)^Te.getBigUint64(88,!0))<<T(64)}function gs(t){return~t+T(1)&N}function Jd(t,e,n){let r=T(t.byteLength)*Ze&N,s=T(t.byteLength-1)/T(32);for(;s>=0;){const a=Number(s);r=Wn(r,D(t,16*a),D(t,t.byteLength-16*(a+1)),D(e,32*a),n),s-=T(1)}let o=r+(r>>T(64))&N;o=Me(o);let i=(r&N)*Ze+(r>>T(64))*Js+(T(t.byteLength)-n&N)*lt;return i&=N,i=gs(Me(i)),o|i<<T(64)}function qd(t,e,n){let r=T(t.byteLength)*Ze&N;for(let i=32;i<160;i+=32)r=Wn(r,D(t,i-32),D(t,i-16),D(e,i-32),n);r=Me(r&N)|Me(r>>T(64))<<T(64);for(let i=160;i<=t.byteLength;i+=32)r=Wn(r,D(t,i-32),D(t,i-16),D(e,3+i-160),n);r=Wn(r,D(t,t.byteLength-16),D(t,t.byteLength-32),D(e,103),gs(n));let s=r+(r>>T(64))&N;s=Me(s);let o=(r&N)*Ze+(r>>T(64))*Js+(T(t.byteLength)-n&N)*lt;return o&=N,o=gs(Me(o)),s|o<<T(64)}function et(t,e=T(0)){const n=new TextEncoder,r=D(typeof t=="string"?n.encode(t):t),s=r.byteLength,o=i=>i.toString(16).padStart(32,"0");return s<=16?o(Kd(r,e)):s<=128?o(Jd(r,Te,e)):s<=240?o(qd(r,Te,e)):o(zd(r,Te))}function ja(t){return/^[0-9a-f]{32}$/.test(t)}function La(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 Fn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[Ye];s.interruptCounter+=1;const o=s.interruptCounter;if(s.resume.length>0&&o<s.resume.length)return n[qe]?.([[le,s.resume]]),s.resume[o];if(s.nullResume!==void 0){if(s.resume.length!==o)throw new Error(`Resume length mismatch: ${s.resume.length} !== ${o}`);const l=s.consumeNullResume();return s.resume.push(l),n[qe]?.([[le,s.resume]]),l}const i=n[Ee]?.split(J),a=i?et(i.join(J)):void 0;throw new vt([{id:a,value:t}])}var dt=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,o)=>{const i=rn(n,{callbacks:r?.getChild()});Le.runWithConfig(i,async()=>{try{const a=await this.func(e,i);s(a)}catch(a){o(a)}})})}async invoke(e,n){let r;const s=Aa(n),o=Re(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,o):r=await Le.runWithConfig(o,async()=>this.func(e,o)),ee.isRunnable(r)&&this.recurse?await Le.runWithConfig(o,async()=>r.invoke(e,o)):r}};function*Ve(t,e){if(e===void 0)yield*t;else for(const n of t)yield[e,n]}async function We(t){const e=[];for await(const n of await t)e.push(n);return e}function en(t){const e=[];for(const n of t)e.push(n);return e}function ft(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function Yd(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const at={[Symbol.for("LG_PASSTHROUGH")]:!0};function En(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const jr=Symbol("IS_WRITER");var se=class ys extends dt{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,o)=>this._write(s,o??{})}),this.writes=e}async _write(e,n){const r=this.writes.map(s=>Lr(s)&&En(s.value)?{mapper:s.mapper,value:e}:Hn(s)&&En(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await ys.doWrite(n,r),e}static async doWrite(e,n){for(const o of n){if(Hn(o)){if(o.channel===we)throw new B("Cannot write to the reserved channel TASKS");if(En(o.value))throw new B("PASSTHROUGH value must be replaced")}if(Lr(o)&&En(o.value))throw new B("PASSTHROUGH value must be replaced")}const r=[];for(const o of n)if(pe(o))r.push([we,o]);else if(Lr(o)){const i=await o.mapper.invoke(o.value,e);i!=null&&i.length>0&&r.push(...i)}else if(Hn(o)){const i=o.mapper!==void 0?await o.mapper.invoke(o.value,e):o.value;if(Yd(i)||o.skipNone&&i===void 0)continue;r.push([o.channel,i])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);const s=e.configurable?.[qe];s(r)}static isWriter(e){return e instanceof ys||jr in e&&!!e[jr]}static registerWriter(e){return Object.defineProperty(e,jr,{value:!0})}};function Hn(t){return t!==void 0&&typeof t.channel=="string"}function Lr(t){return t!==void 0&&!Hn(t)&&ee.isRunnable(t.mapper)}var Xd=class Da extends dt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,o)=>Da.doRead(o,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,n,r,s){const o=e.configurable?.[it];if(!o)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return s?s(o(n,r)):o(n,r)}};const pt=new nc;var mn=class tn extends xe{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=pt;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){const{channels:n,triggers:r,mapper:s,writers:o,bound:i,kwargs:a,metadata:l,retryPolicy:c,cachePolicy:u,tags:h,subgraphs:d,ends:f}=e,y=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??pt,config:{...e.config?e.config:{},tags:y}}),this.channels=n,this.triggers=r,this.mapper=s,this.writers=o??this.writers,this.bound=i??this.bound,this.kwargs=a??this.kwargs,this.metadata=l??this.metadata,this.tags=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===pt&&e.length===0))return this.bound===pt&&e.length===1?e[0]:this.bound===pt?new Xe({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Xe({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 tn({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 tn({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===pt?new tn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Dt(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new tn({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 Zd(t){return"steps"in t&&Array.isArray(t.steps)}function qs(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Fa(t){const e=[t];for(const n of e){if(qs(n))return n;Zd(n)&&e.push(...n.steps)}}function St(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 ct(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=St(t,s,!n)}catch(o){if(o.name===Q.unminifiable_name)continue}return r}else return St(t,e)}function*Qd(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[be,we,r];else if(typeof r=="string")yield[be,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(t.resume)if(typeof t.resume=="object"&&Object.keys(t.resume).length&&Object.keys(t.resume).every(ja))for(const[n,r]of Object.entries(t.resume)){const s=e.filter(o=>o[0]===n&&o[1]===le).map(o=>o[2]).slice(0,1)??[];s.push(r),yield[n,le,s]}else yield[be,le,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[be,n,r];else for(const[n,r]of Object.entries(t.update))yield[be,n,r]}}function*Ua(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*Dr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield ct(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield St(n,t))}function*ef(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(G))&&l[0][0]!==ie&&l[0][0]!==j);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===Vt))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===Vt).map(([l,c])=>[a.name,c])):Array.isArray(t)?s=r.flatMap(([a])=>{const{writes:l}=a,c={};for(const[u]of l)t.includes(u)&&(c[u]=(c[u]||0)+1);return Object.values(c).some(u=>u>1)?l.filter(([u])=>t.includes(u)).map(([u,h])=>[a.name,{[u]:h}]):[[a.name,Object.fromEntries(l.filter(([u])=>t.includes(u)))]]}):s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===t).map(([l,c])=>[a.name,c]));const o={};for(const[a,l]of s)a in o||(o[a]=[]),o[a].push(l);const i={};for(const a in o)if(o[a].length===1){const[l]=o[a];i[a]=l}else i[a]=o[a];n&&(i.__metadata__={cached:n}),yield i}function Ys(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 Gn(t,e){if(Object.keys(t).length>0){const n=Ys(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function tf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function _e(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function Qe(t,e){const n=e?.parents??{};return Object.keys(n).length>0?_e(t,{[ge]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function cr(...t){const e=[...new Set(t.filter(Boolean))];if(e.length===0)return{signal:void 0,dispose:void 0};if(e.length===1)return{signal:e[0],dispose:void 0};const n=new AbortController,r=()=>{const o=e.find(i=>i.aborted)?.reason;n.abort(o),e.forEach(i=>i.removeEventListener("abort",r))};e.forEach(o=>o.addEventListener("abort",r,{once:!0}));const s=e.find(o=>o.aborted);return s&&n.abort(s.reason),{signal:n.signal,dispose:()=>{e.forEach(o=>o.removeEventListener("abort",r))}}}const nf=(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 rf=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:t,name:e,input:n,retry:r,cache:s,callbacks:o}){this.func=t,this.name=e,this.input=n,this.retry=r,this.cache=s,this.callbacks=o}};function sf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function of(t,e){const n=new dt({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new Xe({name:t,first:n,last:new se([{channel:Vt,value:at}],[G])})}const af=t=>t!==void 0?t+1:1;function lf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function cf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=od(e,t[n]));return e}function xn(t,e,n){const r=Ys(t.channel_versions),s=t.versions_seen[j]??{};let o=!1;if((t.channel_versions[L]??r)>(s[L]??r))o=!0;else for(const a in t.channel_versions)if(Object.prototype.hasOwnProperty.call(t.channel_versions,a)&&t.channel_versions[a]>(s[a]??r)){o=!0;break}const i=n.some(a=>e==="*"?!a.config?.tags?.includes(G):e.includes(a.name));return o&&i}function Kn(t,e,n,r,s=!1){let o=new Set;if(Array.isArray(r))o=new Set(r.filter(a=>n.writes.some(([l,c])=>l===a)));else{for(const[a]of n.writes)if(a===r){o=new Set([a]);break}o=o||new Set}let i;if(s&&o.size>0){const a=Object.fromEntries(Object.entries(e).filter(([u,h])=>o.has(u))),l=tt(t,a,-1),c=or(a,l);ue(sr(l),c,[n],void 0,void 0),i=ct({...e,...c},r)}else i=ct(e,r);return i}function Fr(t,e,n){for(const[r,s]of n)if([he,we].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 uf=new Set([Ks,he,le,j,Vt,ie]);function ue(t,e,n,r,s){n.sort((d,f)=>{const y=d.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let C=0;C<Math.min(y.length,p.length);C+=1){if(y[C]<p[C])return-1;if(y[C]>p[C])return 1}return y.length-p.length});const o=n.some(d=>d.triggers.length>0),i=Ws(e);for(const d of n){t.versions_seen[d.name]??={};for(const f of d.triggers)f in t.channel_versions&&(t.versions_seen[d.name][f]=t.channel_versions[f])}let a=cf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!kd.includes(d)));let c=!1;for(const d of l)d in i&&i[d].consume()&&r!==void 0&&(t.channel_versions[d]=r(a),c=!0);const u={};for(const d of n)for(const[f,y]of d.writes)uf.has(f)||f in i&&(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 i){const y=i[d];let p;try{p=y.update(f)}catch(C){if(C.name===B.unminifiable_name){const S=new B(`Invalid update for channel "${d}" with values ${JSON.stringify(f)}: ${C.message}`);throw S.lc_error_code=C.lc_error_code,S}else throw C}p&&r!==void 0&&(t.channel_versions[d]=r(a),y.isAvailable()&&h.add(d))}if(o)for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.isAvailable()&&!h.has(d)&&f.update([])&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}if(o&&!lf(h,s))for(const d in i){if(!Object.prototype.hasOwnProperty.call(i,d))continue;const f=i[d];f.finish()&&r!==void 0&&(t.channel_versions[d]=r(a),f.isAvailable()&&h.add(d))}return h}function*hf(t,e,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){const s=new Set;for(const o of n.updatedChannels){const i=n.triggerToNodes[o];for(const a of i??[])s.add(a)}yield*[...s].sort();return}if(!(()=>{for(const s in t.channel_versions)if(t.channel_versions[s]!==null)return!1;return!0})())for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(yield s)}function wt(t,e,n,r,s,o,i){const a={},l=r[we];if(l?.isAvailable()){const c=l.get().length;for(let u=0;u<c;u+=1){const h=ws([he,u],t,e,n,r,s,o,i);h!==void 0&&(a[h.id]=h)}}for(const c of hf(t,n,i)){const u=ws([zn,c],t,e,n,r,s,o,i);u!==void 0&&(a[u.id]=u)}return a}function ws(t,e,n,r,s,o,i,a){const{step:l,checkpointer:c,manager:u}=a,h=o.configurable??{},d=h.checkpoint_ns??"";if(t[0]===he&&sf(t[t.length-1])){const f=t[t.length-1],y=of(f.name,f.func),p=[he],C=d===""?f.name:`${d}${J}${f.name}`,S=mt(JSON.stringify([C,l.toString(),f.name,he,t[1],t[2]]),e.id),m=`${C}${Fe}${S}`,w=[...t.slice(0,3),!0],v={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:w,langgraph_checkpoint_ns:m};if(i){const k=[];return{name:f.name,input:f.input,proc:y,writes:k,config:rn(Re(o,{metadata:v,store:a.store??o.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:S,[qe]:b=>Fr(_=>k.push(..._),r,b),[it]:(b,_=!1)=>Kn(e,s,{name:f.name,writes:k,triggers:p,path:w},b,_),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[Ye]:Ur({pendingWrites:n??[],taskId:S,currentTaskInput:f.input,resumeMap:o.configurable?.[Vn],namespaceHash:et(m)}),[Bn]:e.channel_values[$r],checkpoint_id:void 0,checkpoint_ns:m}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:et((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Ir,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:S,path:w,writers:[]}}else return{id:S,name:f.name,interrupts:[],path:w}}else if(t[0]===he){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[we]?.isAvailable())return;const y=s[we].get();if(f<0||f>=y.length)return;const p=ps(y[f])&&!pe(y[f])?new re(y[f].node,y[f].args):y[f];if(!ps(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 C=[he],S=d===""?p.node:`${d}${J}${p.node}`,m=mt(JSON.stringify([S,l.toString(),p.node,he,f.toString()]),e.id),w=`${S}${Fe}${m}`;let v={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:C,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:w};if(i){const k=r[p.node],x=k.getNode();if(x!==void 0){k.metadata!==void 0&&(v={...v,...k.metadata});const b=[];return{name:p.node,input:p.args,proc:x,subgraphs:k.subgraphs,writes:b,config:rn(Re(o,{metadata:v,tags:k.tags,store:a.store??o.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:m,[qe]:_=>Fr(M=>b.push(...M),r,_),[it]:(_,M=!1)=>Kn(e,s,{name:p.node,writes:b,triggers:C,path:t},_,M),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[Ye]:Ur({pendingWrites:n??[],taskId:m,currentTaskInput:p.args,resumeMap:o.configurable?.[Vn],namespaceHash:et(w)}),[Bn]:e.channel_values[$r],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:C,retry_policy:k.retryPolicy,cache_key:k.cachePolicy?{key:et((k.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[Ir,k.name??"__dynamic__",p.node],ttl:k.cachePolicy.ttl}:void 0,id:m,path:t,writers:k.getWriters()}}}else return{id:m,name:p.node,interrupts:[],path:t}}else if(t[0]===zn){const f=t[1].toString(),y=r[f];if(y===void 0)return;if(n?.length){const m=d===""?f:`${d}${J}${f}`,w=mt(JSON.stringify([m,l.toString(),f,zn,f]),e.id);if(n.some(k=>k[0]===w&&k[1]!==ie))return}const p=Ys(e.channel_versions);if(p===void 0)return;const C=e.versions_seen[f]??{},S=y.triggers.find(m=>s[m].isAvailable()?(e.channel_versions[m]??p)>(C[m]??p):!1);if(S!==void 0){const m=df(y,s,i);if(m===void 0)return;const w=d===""?f:`${d}${J}${f}`,v=mt(JSON.stringify([w,l.toString(),f,zn,[S]]),e.id),k=`${w}${Fe}${v}`;let x={langgraph_step:l,langgraph_node:f,langgraph_triggers:[S],langgraph_path:t,langgraph_checkpoint_ns:k};if(i){const b=y.getNode();if(b!==void 0){y.metadata!==void 0&&(x={...x,...y.metadata});const _=[];return{name:f,input:m,proc:b,subgraphs:y.subgraphs,writes:_,config:rn(Re(o,{metadata:x,tags:y.tags,store:a.store??o.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:v,[qe]:M=>Fr(E=>{_.push(...E)},r,M),[it]:(M,E=!1)=>Kn(e,s,{name:f,writes:_,triggers:[S],path:t},M,E),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[Ye]:Ur({pendingWrites:n??[],taskId:v,currentTaskInput:m,resumeMap:o.configurable?.[Vn],namespaceHash:et(k)}),[Bn]:e.channel_values[$r],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:[S],retry_policy:y.retryPolicy,cache_key:y.cachePolicy?{key:et((y.cachePolicy.keyFunc??JSON.stringify)([m])),ns:[Ir,y.name??"__dynamic__",f],ttl:y.cachePolicy.ttl}:void 0,id:v,path:t,writers:y.getWriters()}}}else return{id:v,name:f,interrupts:[],path:t}}}}function df(t,e,n){let r;if(typeof t.channels=="object"&&!Array.isArray(t.channels)){r={};for(const[s,o]of Object.entries(t.channels))if(t.triggers.includes(o))try{r[s]=St(e,o,!1)}catch(i){if(i.name===Q.unminifiable_name)return;throw i}else if(o in e)try{r[s]=St(e,o,!1)}catch(i){if(i.name===Q.unminifiable_name)continue;throw i}}else if(Array.isArray(t.channels)){let s=!1;for(const o of t.channels)try{r=St(e,o,!1),s=!0;break}catch(i){if(i.name===Q.unminifiable_name)continue;throw i}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);return n&&t.mapper!==void 0&&(r=t.mapper(r)),r}function Ur({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const o=t.find(([l,c])=>l===be&&c===le)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const l=t.filter(([c,u])=>c===e&&u===le).flatMap(([c,u,h])=>h);if(r!=null&&s in r){const c=r[s];l.push(c)}return l})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,t.splice(t.findIndex(([l,c])=>l===be&&c===le),1),o}};return a}const gn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},yn=(t,e)=>`${t.start}${e}${t.end}`;function*ko(t){for(const{id:e,name:n,input:r,config:s,triggers:o,writes:i}of t){if(s?.tags?.includes(G))continue;const a=i.filter(([l,c])=>l===e&&c===j).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:o,interrupts:a}}}function ff(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Va(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const o=ff(e[s])?e[s].$writes:[e[s]];o.push(r),e[s]={$writes:o}}else e[s]=r}return e}function*pf(t,e){for(const[{id:n,name:r,config:s},o]of t)s?.tags?.includes(G)||(yield{id:n,name:r,result:Va(o.filter(([i])=>Array.isArray(e)?e.includes(i):i===e)),interrupts:o.filter(i=>i[0]===j).map(i=>i[1])})}function*mf(t,e,n,r,s,o,i,a){function l(h){const d={};return h.callbacks!=null&&(d.callbacks=h.callbacks),h.configurable!=null&&(d.configurable=h.configurable),h.maxConcurrency!=null&&(d.max_concurrency=h.maxConcurrency),h.metadata!=null&&(d.metadata=h.metadata),h.recursionLimit!=null&&(d.recursion_limit=h.recursionLimit),h.runId!=null&&(d.run_id=h.runId),h.runName!=null&&(d.run_name=h.runName),h.tags!=null&&(d.tags=h.tags),d}const c=t.configurable?.checkpoint_ns,u={};for(const h of s){if(!(h.subgraphs?.length?h.subgraphs:[h.proc]).find(Fa))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:ct(e,n),metadata:r,next:s.map(h=>h.name),tasks:Ba(s,o,u,a),parentConfig:i?l(i):void 0}}function Ba(t,e,n,r){return t.map(s=>{const o=e.find(([c,u])=>c===s.id&&u===ie)?.[2],i=e.filter(([c,u])=>c===s.id&&u===j).map(([,,c])=>c),a=(()=>{if(o||i.length||!e.length)return;const c=e.findIndex(([u,h])=>u===s.id&&h===Vt);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?Va(u):void 0}})();if(o)return{id:s.id,name:s.name,path:s.path,error:o,interrupts:i,result:a};const l=n?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:i,...l!==void 0?{state:l}:{},result:a}})}function gf(t,e,n){console.log([`${yn(gn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
|
|
33
|
+
`),super(n),this.lc_error_code=e?.lc_error_code}},va=class extends ut{get is_bubble_up(){return!0}},md=class extends ut{constructor(t,e){super(t,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Dn=class extends ut{constructor(t,e){super(t,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},_t=class extends va{interrupts;constructor(t,e){super(JSON.stringify(t,null,2),e),this.name="GraphInterrupt",this.interrupts=t??[]}static get unminifiable_name(){return"GraphInterrupt"}},_a=class extends _t{constructor(t,e){super([{value:t}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Sa=class extends va{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function gd(t){return t!==void 0&&t.name===Sa.unminifiable_name}function Un(t){return t!==void 0&&t.is_bubble_up===!0}function st(t){return t!==void 0&&[_t.unminifiable_name,_a.unminifiable_name].includes(t.name)}var mi=class extends ut{constructor(t,e){super(t,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Q=class extends ut{constructor(t,e){super(t,e),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},B=class extends ut{constructor(t,e){super(t,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},yd=class extends ut{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function Ca(t){return t!=null&&t.lg_is_channel===!0}var ht=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 as=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function zs(t){if(t[as]===!0)return t;const e={};for(const n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const r=t[n];Ca(r)&&(e[n]=r)}return Object.assign(e,{[as]:!0}),e}function sr(t,e){const n=zs(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,{[as]:!0}),r}function tt(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??lo(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var ls=class ka extends ht{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 ka(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}},Ws=class Ta extends ht{lc_graph_name="LastValue";value=[];fromCheckpoint(e){const n=new Ta;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}},wd=class Ea extends ht{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new Ea;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}},bd=class{lc_graph_name="AnnotationRoot";spec;constructor(t){this.spec=t}};const cs=function(t){return t?us(t):new Ws};cs.Root=t=>new bd(t);function us(t){return typeof t=="object"&&t&&"reducer"in t&&t.reducer?new ls(t.reducer,t.default):typeof t=="object"&&t&&"value"in t&&t.value?new ls(t.value,t.default):new Ws}const L="__start__",A="__end__",Ne="__input__",vd="__copy__",oe="__error__",Or="__pregel_ns_writes",Je="__pregel_send",Hs="__pregel_call",ot="__pregel_read",H="__pregel_checkpointer",Be="__pregel_resuming",sn="__pregel_task_id",ir="__pregel_stream",_d="__pregel_resume_value",Fn="__pregel_resume_map",qe="__pregel_scratchpad",Vn="__pregel_previous",xa="__pregel_durability",hs="checkpoint_id",Te="checkpoint_ns",Sd="__pregel_node_finished",ge="checkpoint_map",gi="__pregel_abort_signals",R="__interrupt__",le="__resume__",Gs="__no_writes__",Bt="__return__",Nr="__previous__",G="langsmith:hidden",Cd="langsmith:nostream",yi="__self__",ye="__pregel_tasks",he="__pregel_push",Bn="__pregel_pull",we="00000000-0000-0000-0000-000000000000",kd=[G,Ne,R,le,oe,Gs,Je,ot,H,xa,ir,Be,sn,Hs,_d,qe,Vn,ge,Te,hs],J="|",De=":",wi=Symbol.for("langgraph.command");var Td=class{[wi];constructor(t){this[wi]=t}};function ds(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=pn(e)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function pe(t){return t instanceof re}function Ma(t){return!t||typeof t!="object"||!(R in t)?!1:Array.isArray(t[R])}var K=class extends Td{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)?pn(t.goto):[pn(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 pn(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]=pn(r,e)});else if(Y(t)&&!(t instanceof K))n=new K(t),e.set(t,n);else if(ds(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]=pn(s,e)}return n}return t}const Ed=["tags","metadata","callbacks","configurable"],xd=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Md=25;function Aa(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Md,configurable:{}},n=je.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(Ed.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&&xd.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 Ad(){return je.getRunnableConfig()}function Ir(t){return t.split(J).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(De)[0]).join(J)}function Pd(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 T=t=>BigInt(t),D=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Pa=T("0x9E3779B1"),Oa=T("0x85EBCA77"),Od=T("0xC2B2AE3D"),Ze=T("0x9E3779B185EBCA87"),lt=T("0xC2B2AE3D27D4EB4F"),Na=T("0x165667B19E3779F9"),Ks=T("0x85EBCA77C2B2AE63"),Nd=T("0x27D4EB2F165667C5"),Id=T("0x165667919E3779F9"),$d=T("0x9FB21C651E98DF25"),Rd=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=Rd("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),St=(T(1)<<T(128))-T(1),N=(T(1)<<T(64))-T(1),or=(T(1)<<T(32))-T(1),Ie=64,Ia=Ie/8,jd=8,kn=4;function zt(t){if(!t)throw new Error("Assert failed")}function Ld(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Dd(t){let e=t;return e=(e&T(65535))<<T(16)|(e&T(4294901760))>>T(16),e=(e&T(16711935))<<T(8)|(e&T(4278255360))>>T(8),e}function Ud(t,e){return(t&or)*(e&or)&N}function Fd(t,e){return(t<<e|t>>T(32)-e)&or}function $a(t,e,n){for(let r=0;r<Ia;r+=1){const s=e.getBigUint64(r*8,!0),i=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Ud(i,i>>T(32))}return t}function bi(t,e,n,r){for(let s=0;s<r;s+=1)$a(t,D(e,s*Ie),D(n,s*8));return t}function Vd(t,e){for(let n=0;n<Ia;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=fs(s,T(47)),s^=r,s*=Pa,t[n]=s&N}return t}function Tn(t,e){return Ra(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(jd,!0))}function vi(t,e,n){let r=n;return r+=Tn(t.slice(0),D(e,0*kn)),r+=Tn(t.slice(2),D(e,4*kn)),r+=Tn(t.slice(4),D(e,8*kn)),r+=Tn(t.slice(6),D(e,12*kn)),xe(r&N)}function Bd(t,e,n,r,s){let i=t;const o=Math.floor((n.byteLength-Ie)/8),a=Ie*o,l=Math.floor((e.byteLength-1)/a);for(let c=0;c<l;c+=1)i=bi(i,D(e,c*a),n,o),i=s(i,D(n,n.byteLength-Ie));{const c=Math.floor((e.byteLength-1-a*l)/Ie);i=bi(i,D(e,l*a),n,c),i=r(i,D(e,e.byteLength-Ie),D(n,n.byteLength-Ie-7))}return i}function zd(t,e){let n=new BigUint64Array([Od,Ze,lt,Na,Ks,Oa,Nd,Pa]);zt(t.byteLength>128),n=Bd(n,t,e,$a,Vd),zt(n.length*8===64);{const r=vi(n,D(e,11),T(t.byteLength)*Ze&N);return vi(n,D(e,e.byteLength-Ie-11),~(T(t.byteLength)*lt)&N)<<T(64)|r}}function Ra(t,e){const n=t*e&St;return n&N^n>>T(64)}function _i(t,e,n){return Ra((t.getBigUint64(0,!0)^e.getBigUint64(0,!0)+n)&N,(t.getBigUint64(8,!0)^e.getBigUint64(8,!0)-n)&N)}function zn(t,e,n,r,s){let i=t&N,o=t>>T(64)&N;return i+=_i(e,r,s),i^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),i&=N,o+=_i(n,D(r,16),s),o^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),o&=N,o<<T(64)|i}function xe(t){let e=t;return e^=e>>T(37),e*=Id,e&=N,e^=e>>T(32),e}function ar(t){let e=t;return e^=e>>T(33),e*=lt,e&=N,e^=e>>T(29),e*=Na,e&=N,e^=e>>T(32),e}function Wd(t,e,n){const r=t.byteLength;zt(r>0&&r<=3);const s=T(t.getUint8(r-1))|T(r<<8)|T(t.getUint8(0)<<16)|T(t.getUint8(r>>1)<<24),i=(T(e.getUint32(0,!0))^T(e.getUint32(4,!0)))+n,o=(s^i)&N,a=(T(e.getUint32(8,!0))^T(e.getUint32(12,!0)))-n,l=(Fd(Dd(s),T(13))^a)&N;return(ar(l)&N)<<T(64)|ar(o)}function fs(t,e){return t^t>>e}function Hd(t,e,n){const r=t.byteLength;zt(r>=4&&r<=8);{const s=t.getUint32(0,!0),i=t.getUint32(r-4,!0),o=T(s)|T(i)<<T(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&N;let c=(o^a)*(Ze+(T(r)<<T(2)))&St;return c+=(c&N)<<T(65),c&=St,c^=c>>T(67),fs(fs(c&N,T(35))*$d&N,T(28))|xe(c>>T(64))<<T(64)}}function Gd(t,e,n){const r=t.byteLength;zt(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+n&N,i=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-n&N,o=t.getBigUint64(0,!0);let a=t.getBigUint64(r-8,!0),l=(o^a^s)*Ze;const c=(l&N)+(T(r-1)<<T(54));l=l&(St^N)|c,a^=i,l+=a+(a&or)*(Oa-T(1))<<T(64),l&=St,l^=Ld(l>>T(64));let u=(l&N)*lt;return u+=(l>>T(64))*lt<<T(64),u&=St,xe(u&N)|xe(u>>T(64))<<T(64)}}function Kd(t,e){const n=t.byteLength;return zt(n<=16),n>8?Gd(t,ke,e):n>=4?Hd(t,ke,e):n>0?Wd(t,ke,e):ar(e^ke.getBigUint64(64,!0)^ke.getBigUint64(72,!0))|ar(e^ke.getBigUint64(80,!0)^ke.getBigUint64(88,!0))<<T(64)}function ps(t){return~t+T(1)&N}function Jd(t,e,n){let r=T(t.byteLength)*Ze&N,s=T(t.byteLength-1)/T(32);for(;s>=0;){const a=Number(s);r=zn(r,D(t,16*a),D(t,t.byteLength-16*(a+1)),D(e,32*a),n),s-=T(1)}let i=r+(r>>T(64))&N;i=xe(i);let o=(r&N)*Ze+(r>>T(64))*Ks+(T(t.byteLength)-n&N)*lt;return o&=N,o=ps(xe(o)),i|o<<T(64)}function qd(t,e,n){let r=T(t.byteLength)*Ze&N;for(let o=32;o<160;o+=32)r=zn(r,D(t,o-32),D(t,o-16),D(e,o-32),n);r=xe(r&N)|xe(r>>T(64))<<T(64);for(let o=160;o<=t.byteLength;o+=32)r=zn(r,D(t,o-32),D(t,o-16),D(e,3+o-160),n);r=zn(r,D(t,t.byteLength-16),D(t,t.byteLength-32),D(e,103),ps(n));let s=r+(r>>T(64))&N;s=xe(s);let i=(r&N)*Ze+(r>>T(64))*Ks+(T(t.byteLength)-n&N)*lt;return i&=N,i=ps(xe(i)),s|i<<T(64)}function et(t,e=T(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(Kd(r,e)):s<=128?i(Jd(r,ke,e)):s<=240?i(qd(r,ke,e)):i(zd(r,ke))}function ja(t){return/^[0-9a-f]{32}$/.test(t)}function La(t){const e=je.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 Dn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const s=n[qe];s.interruptCounter+=1;const i=s.interruptCounter;if(s.resume.length>0&&i<s.resume.length)return n[Je]?.([[le,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[Je]?.([[le,s.resume]]),l}const o=n[Te]?.split(J),a=o?et(o.join(J)):void 0;throw new _t([{id:a,value:t}])}var dt=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=rn(n,{callbacks:r?.getChild()});je.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=Aa(n),i=$e(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,i):r=await je.runWithConfig(i,async()=>this.func(e,i)),ee.isRunnable(r)&&this.recurse?await je.runWithConfig(i,async()=>r.invoke(e,i)):r}};function*Fe(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 en(t){const e=[];for(const n of t)e.push(n);return e}function ft(t,e){return t?"configurable"in t?{...t,configurable:{...t.configurable,...e}}:{...t,configurable:e}:{configurable:e}}function Yd(t){return typeof t=="object"&&t?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}const at={[Symbol.for("LG_PASSTHROUGH")]:!0};function En(t){return typeof t=="object"&&t?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}const $r=Symbol("IS_WRITER");var se=class ms extends dt{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=>Rr(s)&&En(s.value)?{mapper:s.mapper,value:e}:Wn(s)&&En(s.value)?{channel:s.channel,value:e,skipNone:s.skipNone,mapper:s.mapper}:s);return await ms.doWrite(n,r),e}static async doWrite(e,n){for(const i of n){if(Wn(i)){if(i.channel===ye)throw new B("Cannot write to the reserved channel TASKS");if(En(i.value))throw new B("PASSTHROUGH value must be replaced")}if(Rr(i)&&En(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(Rr(i)){const o=await i.mapper.invoke(i.value,e);o!=null&&o.length>0&&r.push(...o)}else if(Wn(i)){const o=i.mapper!==void 0?await i.mapper.invoke(i.value,e):i.value;if(Yd(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?.[Je];s(r)}static isWriter(e){return e instanceof ms||$r in e&&!!e[$r]}static registerWriter(e){return Object.defineProperty(e,$r,{value:!0})}};function Wn(t){return t!==void 0&&typeof t.channel=="string"}function Rr(t){return t!==void 0&&!Wn(t)&&ee.isRunnable(t.mapper)}var Xd=class Da extends dt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,i)=>Da.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?.[ot];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 pt=new nc;var mn=class tn extends Ee{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=pt;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,g=[...e.config?.tags?e.config.tags:[],...h??[]];super({...e,bound:e.bound??pt,config:{...e.config?e.config:{},tags:g}}),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=g,this.retryPolicy=c,this.cachePolicy=u,this.subgraphs=d,this.ends=f}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof 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===pt&&e.length===0))return this.bound===pt&&e.length===1?e[0]:this.bound===pt?new Xe({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Xe({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 tn({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 tn({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===pt?new tn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Ut(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new tn({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 Zd(t){return"steps"in t&&Array.isArray(t.steps)}function Js(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Ua(t){const e=[t];for(const n of e){if(Js(n))return n;Zd(n)&&e.push(...n.steps)}}function Ct(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 ct(t,e,n=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Ct(t,s,!n)}catch(i){if(i.name===Q.unminifiable_name)continue}return r}else return Ct(t,e)}function*Qd(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]===le).map(i=>i[2]).slice(0,1)??[];s.push(r),yield[n,le,s]}else yield[we,le,t.resume];if(t.update){if(typeof t.update!="object"||!t.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(t.update))for(const[n,r]of t.update)yield[we,n,r];else for(const[n,r]of Object.entries(t.update))yield[we,n,r]}}function*Fa(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*jr(t,e,n){Array.isArray(t)?(e===!0||e.find(([r,s])=>t.includes(r)))&&(yield ct(n,t)):(e===!0||e.some(([r,s])=>r===t))&&(yield Ct(n,t))}function*ef(t,e,n){const r=e.filter(([a,l])=>(a.config===void 0||!a.config.tags?.includes(G))&&l[0][0]!==oe&&l[0][0]!==R);if(!r.length)return;let s;r.some(([a])=>a.writes.some(([l,c])=>l===Bt))?s=r.flatMap(([a])=>a.writes.filter(([l,c])=>l===Bt).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 qs(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 Hn(t,e){if(Object.keys(t).length>0){const n=qs(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(t[r]??n)))}else return e}function tf(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function ve(t,e){return t===null?{configurable:e}:t?.configurable===void 0?{...t,configurable:e}:{...t,configurable:{...t.configurable,...e}}}function Qe(t,e){const n=e?.parents??{};return Object.keys(n).length>0?ve(t,{[ge]:{...n,[t.configurable?.checkpoint_ns??""]:t.configurable?.checkpoint_id}}):t}function lr(...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 nf=(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 rf=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 sf(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function of(t,e){const n=new dt({func:r=>e(...r),name:t,trace:!1,recurse:!1});return new Xe({name:t,first:n,last:new se([{channel:Bt,value:at}],[G])})}const af=t=>t!==void 0?t+1:1;function lf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function cf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=id(e,t[n]));return e}function xn(t,e,n){const r=qs(t.channel_versions),s=t.versions_seen[R]??{};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 Gn(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=tt(t,a,-1),c=sr(a,l);ue(rr(l),c,[n],void 0,void 0),o=ct({...e,...c},r)}else o=ct(e,r);return o}function Lr(t,e,n){for(const[r,s]of n)if([he,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 uf=new Set([Gs,he,le,R,Bt,oe]);function ue(t,e,n,r,s){n.sort((d,f)=>{const g=d.path?.slice(0,3)||[],p=f.path?.slice(0,3)||[];for(let C=0;C<Math.min(g.length,p.length);C+=1){if(g[C]<p[C])return-1;if(g[C]>p[C])return 1}return g.length-p.length});const i=n.some(d=>d.triggers.length>0),o=zs(e);for(const d of n){t.versions_seen[d.name]??={};for(const f of d.triggers)f in t.channel_versions&&(t.versions_seen[d.name][f]=t.channel_versions[f])}let a=cf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!kd.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,g]of d.writes)uf.has(f)||f in o&&(u[f]??=[],u[f].push(g));a!=null&&r!=null&&(a=c?r(a):a);const h=new Set;for(const[d,f]of Object.entries(u))if(d in o){const g=o[d];let p;try{p=g.update(f)}catch(C){if(C.name===B.unminifiable_name){const S=new B(`Invalid update for channel "${d}" with values ${JSON.stringify(f)}: ${C.message}`);throw S.lc_error_code=C.lc_error_code,S}else throw C}p&&r!==void 0&&(t.channel_versions[d]=r(a),g.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&&!lf(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*hf(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=gs([he,u],t,e,n,r,s,i,o);h!==void 0&&(a[h.id]=h)}}for(const c of hf(t,n,o)){const u=gs([Bn,c],t,e,n,r,s,i,o);u!==void 0&&(a[u.id]=u)}return a}function gs(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]===he&&sf(t[t.length-1])){const f=t[t.length-1],g=of(f.name,f.func),p=[he],C=d===""?f.name:`${d}${J}${f.name}`,S=gt(JSON.stringify([C,l.toString(),f.name,he,t[1],t[2]]),e.id),m=`${C}${De}${S}`,w=[...t.slice(0,3),!0],v={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:w,langgraph_checkpoint_ns:m};if(o){const k=[];return{name:f.name,input:f.input,proc:g,writes:k,config:rn($e(i,{metadata:v,store:a.store??i.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:S,[Je]:b=>Lr(_=>k.push(..._),r,b),[ot]:(b,_=!1)=>Gn(e,s,{name:f.name,writes:k,triggers:p,path:w},b,_),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[qe]:Dr({pendingWrites:n??[],taskId:S,currentTaskInput:f.input,resumeMap:i.configurable?.[Fn],namespaceHash:et(m)}),[Vn]:e.channel_values[Nr],checkpoint_id:void 0,checkpoint_ns:m}}),triggers:p,retry_policy:f.retry,cache_key:f.cache?{key:et((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Or,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:S,path:w,writers:[]}}else return{id:S,name:f.name,interrupts:[],path:w}}else if(t[0]===he){const f=typeof t[1]=="number"?t[1]:parseInt(t[1],10);if(!s[ye]?.isAvailable())return;const g=s[ye].get();if(f<0||f>=g.length)return;const p=ds(g[f])&&!pe(g[f])?new re(g[f].node,g[f].args):g[f];if(!ds(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 C=[he],S=d===""?p.node:`${d}${J}${p.node}`,m=gt(JSON.stringify([S,l.toString(),p.node,he,f.toString()]),e.id),w=`${S}${De}${m}`;let v={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:C,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:w};if(o){const k=r[p.node],x=k.getNode();if(x!==void 0){k.metadata!==void 0&&(v={...v,...k.metadata});const b=[];return{name:p.node,input:p.args,proc:x,subgraphs:k.subgraphs,writes:b,config:rn($e(i,{metadata:v,tags:k.tags,store:a.store??i.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:m,[Je]:_=>Lr(M=>b.push(...M),r,_),[ot]:(_,M=!1)=>Gn(e,s,{name:p.node,writes:b,triggers:C,path:t},_,M),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[qe]:Dr({pendingWrites:n??[],taskId:m,currentTaskInput:p.args,resumeMap:i.configurable?.[Fn],namespaceHash:et(w)}),[Vn]:e.channel_values[Nr],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:C,retry_policy:k.retryPolicy,cache_key:k.cachePolicy?{key:et((k.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[Or,k.name??"__dynamic__",p.node],ttl:k.cachePolicy.ttl}:void 0,id:m,path:t,writers:k.getWriters()}}}else return{id:m,name:p.node,interrupts:[],path:t}}else if(t[0]===Bn){const f=t[1].toString(),g=r[f];if(g===void 0)return;if(n?.length){const m=d===""?f:`${d}${J}${f}`,w=gt(JSON.stringify([m,l.toString(),f,Bn,f]),e.id);if(n.some(k=>k[0]===w&&k[1]!==oe))return}const p=qs(e.channel_versions);if(p===void 0)return;const C=e.versions_seen[f]??{},S=g.triggers.find(m=>s[m].isAvailable()?(e.channel_versions[m]??p)>(C[m]??p):!1);if(S!==void 0){const m=df(g,s,o);if(m===void 0)return;const w=d===""?f:`${d}${J}${f}`,v=gt(JSON.stringify([w,l.toString(),f,Bn,[S]]),e.id),k=`${w}${De}${v}`;let x={langgraph_step:l,langgraph_node:f,langgraph_triggers:[S],langgraph_path:t,langgraph_checkpoint_ns:k};if(o){const b=g.getNode();if(b!==void 0){g.metadata!==void 0&&(x={...x,...g.metadata});const _=[];return{name:f,input:m,proc:b,subgraphs:g.subgraphs,writes:_,config:rn($e(i,{metadata:x,tags:g.tags,store:a.store??i.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:v,[Je]:M=>Lr(E=>{_.push(...E)},r,M),[ot]:(M,E=!1)=>Gn(e,s,{name:f,writes:_,triggers:[S],path:t},M,E),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[qe]:Dr({pendingWrites:n??[],taskId:v,currentTaskInput:m,resumeMap:i.configurable?.[Fn],namespaceHash:et(k)}),[Vn]:e.channel_values[Nr],checkpoint_id:void 0,checkpoint_ns:k}}),triggers:[S],retry_policy:g.retryPolicy,cache_key:g.cachePolicy?{key:et((g.cachePolicy.keyFunc??JSON.stringify)([m])),ns:[Or,g.name??"__dynamic__",f],ttl:g.cachePolicy.ttl}:void 0,id:v,path:t,writers:g.getWriters()}}}else return{id:v,name:f,interrupts:[],path:t}}}}function df(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]=Ct(e,i,!1)}catch(o){if(o.name===Q.unminifiable_name)return;throw o}else if(i in e)try{r[s]=Ct(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=Ct(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 Dr({pendingWrites:t,taskId:e,currentTaskInput:n,resumeMap:r,namespaceHash:s}){const i=t.find(([l,c])=>l===we&&c===le)?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{const l=t.filter(([c,u])=>c===e&&u===le).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===le),1),i}};return a}const gn={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},yn=(t,e)=>`${t.start}${e}${t.end}`;function*Si(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===R).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:i,interrupts:a}}}function ff(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Va(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const i=ff(e[s])?e[s].$writes:[e[s]];i.push(r),e[s]={$writes:i}}else e[s]=r}return e}function*pf(t,e){for(const[{id:n,name:r,config:s},i]of t)s?.tags?.includes(G)||(yield{id:n,name:r,result:Va(i.filter(([o])=>Array.isArray(e)?e.includes(o):o===e)),interrupts:i.filter(o=>o[0]===R).map(o=>o[1])})}function*mf(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(Ua))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:ct(e,n),metadata:r,next:s.map(h=>h.name),tasks:Ba(s,i,u,a),parentConfig:o?l(o):void 0}}function Ba(t,e,n,r){return t.map(s=>{const i=e.find(([c,u])=>c===s.id&&u===oe)?.[2],o=e.filter(([c,u])=>c===s.id&&u===R).map(([,,c])=>c),a=(()=>{if(i||o.length||!e.length)return;const c=e.findIndex(([u,h])=>u===s.id&&h===Bt);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?Va(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 gf(t,e,n){console.log([`${yn(gn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
|
|
34
34
|
`,JSON.stringify(ct(e,n),null,2)].join(""))}function za(t,e){const n=e.length;console.log([`${yn(gn.blue,`[${t}:tasks]`)}`,`\x1B[1m Starting step ${t} with ${n} task${n===1?"":"s"}:\x1B[0m
|
|
35
35
|
`,e.map(r=>`- ${yn(gn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
|
|
36
|
-
`)].join(""))}function yf(t,e,n){const r={};for(const[s,
|
|
37
|
-
`,Object.entries(r).map(([s,
|
|
38
|
-
`)].join(""))}var
|
|
36
|
+
`)].join(""))}function yf(t,e,n){const r={};for(const[s,i]of e)n.includes(s)&&(r[s]||(r[s]=[]),r[s].push(i));console.log([`${yn(gn.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])=>`- ${yn(gn.yellow,s)} -> ${i.map(o=>JSON.stringify(o)).join(", ")}`).join(`
|
|
38
|
+
`)].join(""))}var Ci=class extends ln{_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}},Wa=class extends ln{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 wf(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 bf(t){return t instanceof Error?{error:t.name,message:t.message}:{error:"Error",message:JSON.stringify(t)}}function Ys(t){return typeof t!="object"||t==null?!1:"configurable"in t&&typeof t.configurable=="object"&&t.configurable!=null}function Ur(t){return!Ys(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 ki(t){if(Ys(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 Ti(t){const e={...t,checkpoint:Ur(t.config),parent_checkpoint:Ur(t.parentConfig),config:ki(t.config),parent_config:ki(t.parentConfig),tasks:t.tasks.map(n=>{if(Ys(n.state)){const r=Ur(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function vf(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
|
|
39
39
|
data: ${wf(s.data)}
|
|
40
40
|
|
|
41
|
-
`))};try{for await(const s of t){const[o,i,a]=s;let l=a;if(i==="debug"){const u=a;u.type==="checkpoint"&&(l={...u,payload:xo(u.payload)})}i==="checkpoints"&&(l=xo(a));const c=o?.length?`${i}|${o.join("|")}`:i;r({event:c,data:l})}}catch(s){r({event:"error",data:bf(s)})}n.close()}})}const Mn=Symbol.for("INPUT_DONE"),Br=Symbol.for("INPUT_RESUMING"),_f=25;function Sf(...t){return new Wa({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 Cf=class extends hd{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}},kf=class Ha{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?.[ze]!==void 0&&this.config.configurable?.[ze],s=this.input===null||this.input===void 0,o=Y(this.input)&&this.input.resume!=null,i=this.input===Br,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(r||s||o||i||a)}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=af,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 Cf(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?.[ir]!==void 0&&(r=Sf(r,n.configurable[ir]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,o=n.configurable?.[Ye];n.configurable&&o&&(o.subgraphCounter>0&&(n=_e(n,{[Ee]:[n.configurable[Ee],o.subgraphCounter.toString()].join(J)})),o.subgraphCounter+=1);const i=it in(n.configurable??{});!i&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=_e(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ge]!==void 0&&n.configurable?.[ge]?.[n.configurable?.checkpoint_ns]&&(a=_e(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:ya(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,h=sr(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],y=or(e.channelSpecs,h),p=(d.step??0)+1,C=p+(n.recursionLimit??_f)+1,S={...h.channel_versions},m=e.store?new ud(e.store):void 0;return m&&await m.start(),new Ha({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:y,isNested:i,manager:e.manager,skipDoneTasks:s,step:p,stop:C,checkpointPreviousVersions:S,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(([i])=>i in id)&&(r=Array.from(new Map(r.map(i=>[i[0],i])).values())),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(i=>i[0]!==e);for(const[i,a]of r)this.checkpointPendingWrites.push([e,i,a]);const s=_e(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??"",[fs]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(s,r,e)),this.tasks&&this._outputWrites(e,r),!n.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||n[0][0]===ie||n[0][0]===j||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,n,r=!1){const s=this.tasks[e];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes(G))return;if(n.length>0)if(n[0][0]===j){if(s.path?.[0]===he&&s.path?.at(-1)===!0)return;const o=n.filter(i=>i[0]===j).flatMap(i=>i[1]);this._emit([["updates",{[j]:o}],["values",{[j]:o}]])}else n[0][0]!==ie&&this._emit(en(Ve(ef(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(en(Ve(pf([[s,n]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],n=([i,a])=>`ns:${i.join(",")}|key:${a}`,r=[],s={};for(const i of Object.values(this.tasks))i.cache_key!=null&&!i.writes.length&&(r.push([i.cache_key.ns,i.cache_key.key]),s[n([i.cache_key.ns,i.cache_key.key])]=i);if(r.length===0)return[];const o=await this.cache.get(r);for(const{key:i,value:a}of o){const l=s[n(i)];l!=null&&(l.writes.push(...a),e.push({task:l,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();const{inputKeys:n=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Mn,Br].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new vt;if(Object.values(this.tasks).every(o=>o.writes.length>0)){const o=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=ue(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const i=await We(Ve(Dr(this.outputKeys,o,this.channels),"values"));if(this._emit(i),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),xn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new vt;this.config.configurable?.[ze]!==void 0&&delete this.config.configurable?.[ze]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;const r=wt(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 We(Ve(mf(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[o,i,a]of this.checkpointPendingWrites){if(i===ie||i===j||i===le)continue;const l=Object.values(this.tasks).find(c=>c.id===o);l&&l.writes.push([i,a])}for(const o of Object.values(this.tasks))o.writes.length>0&&this._outputWrites(o.id,o.writes,!0)}if(Object.values(this.tasks).every(o=>o.writes.length>0))return this.tick({inputKeys:n});if(xn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new vt;const s=await We(Ve(ko(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(Fe)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=ct(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=ue(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(en(Ve(Dr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),st(e)&&!e.interrupts.length&&this._emit([["updates",{[j]:[]}],["values",{[j]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&xn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=ws([he,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&&xn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(en(Ve(ko([s]),"tasks"))),this.debug&&za(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});const o=await this._matchCachedWrites();for(const{task:i}of o)this._outputWrites(i.id,i.writes,!0);return s}_suppressInterrupt(e){return st(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[Ye];if(r&&r.nullResume!==void 0&&this.putWrites(be,[[le,r.nullResume]]),Y(this.input)){const i=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(ja)&&(this.config.configurable??={},this.config.configurable[Vn]=this.input.resume),i&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of Qd(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new yo("Received empty Command input");for(const[l,c]of Object.entries(a))this.putWrites(l,c)}const s=(this.checkpointPendingWrites??[]).filter(i=>i[0]===be).map(i=>i.slice(1));s.length>0&&ue(this.checkpoint,this.channels,[{name:Ie,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const o=Y(this.input)&&s.length>0;if(this.isResuming||o){for(const a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){const l=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[j]={...this.checkpoint.versions_seen[j],[a]:l}}const i=await We(Ve(Dr(this.outputKeys,!0,this.channels),"values"));this._emit(i)}if(this.isResuming)this.input=Br;else if(o)await this._putCheckpoint({source:"input"}),this.input=Mn;else{const i=await We(Ua(e,this.input));if(i.length>0){const a=wt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=ue(this.checkpoint,this.channels,Object.values(a).concat([{name:Ie,writes:i,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Mn}else if(ze in(this.config.configurable??{}))this.input=Mn;else throw new yo(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=_e(this.config,{[ze]:this.isResuming}))}_emit(e){for(const[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){const s=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),i=n==="checkpoints"?"checkpoint":typeof r=="object"&&r!=null&&"result"in r?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:s,type:i,timestamp:o,payload:r}])}}_putCheckpoint(e){const n=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||n),s=o=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=_e(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??""});const i={...this.checkpoint.channel_versions},a=Gn(this.checkpointPreviousVersions,i);this.checkpointPreviousVersions=i,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:sr(o),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};n||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.[ge]??{}}),this.checkpoint=tt(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=_e(this.checkpointConfig,{[Ee]:this.config.configurable?.checkpoint_ns??"",[fs]:this.checkpoint.id}),n={};for(const[r,s,o]of this.checkpointPendingWrites)n[r]??=[],n[r].push([s,o]);for(const[r,s]of Object.entries(n))this.checkpointerPromises.push(this.checkpointer.putWrites(e,s,r))}_matchWrites(e){for(const[n,r,s]of this.checkpointPendingWrites){if(r===ie||r===j||r===le)continue;const o=Object.values(e).find(i=>i.id===n);o&&o.writes.push([r,s])}for(const n of Object.values(e))n.writes.length>0&&this._outputWrites(n.id,n.writes,!0)}};function Tf(t){return Ne(t?.message)}var Ef=class extends Ic{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&&($c(e)?s??=`run-${n}-tool-${e.tool_call_id}`:((s==null||s===`run-${n}`)&&(s=this.stableMessageIdMap[n]??s??`run-${n}`),this.stableMessageIdMap[n]??=s)),s!==e.id&&(e.id=s,e.lc_kwargs.id=s),e.id!=null&&(this.seen[e.id]=e),this.streamFn([t[0],"messages",[e,t[1]]])}handleChatModelStart(t,e,n,r,s,o,i,a){i&&(!o||!o.includes(Cd)&&!o.includes("nostream"))&&(this.metadatas[n]=[i.langgraph_checkpoint_ns.split("|"),{tags:o,name:a,...i}])}handleLLMNewToken(t,e,n,r,s,o){const i=o?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(Tf(i)?this._emit(this.metadatas[n],i.message,n):this._emit(this.metadatas[n],new jt({content:t}),n))}handleLLMEnd(t,e){if(this.metadatas[e]!==void 0){if(!this.emittedChatModelRunIds[e]){const n=t.generations?.[0]?.[0];Ne(n?.message)&&this._emit(this.metadatas[e],n?.message,e,!0),delete this.emittedChatModelRunIds[e]}delete this.metadatas[e],delete this.stableMessageIdMap[e]}}handleLLMError(t,e){delete this.metadatas[e]}handleChainStart(t,e,n,r,s,o,i,a){if(o!==void 0&&a===o.langgraph_node&&(s===void 0||!s.includes(G))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}],typeof e=="object")){for(const l of Object.values(e))if((Ne(l)||so(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(Ne(c)||so(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(Ne(t))this._emit(n,t,e,!0);else if(Array.isArray(t))for(const r of t)Ne(r)&&this._emit(n,r,e,!0);else if(t!=null&&typeof t=="object"){for(const r of Object.values(t))if(Ne(r))this._emit(n,r,e,!0);else if(Array.isArray(r))for(const s of r)Ne(s)&&this._emit(n,s,e,!0)}}}handleChainError(t,e){delete this.metadatas[e]}};const xf=500,Mf=2,Af=128e3,Pf=3,Of=[400,401,402,403,404,405,406,407,409],Nf=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&&Of.includes(+e)||t?.error?.code==="insufficient_quota")};async function Ga(t,e,n,r){const s=t.retry_policy??e;let o=s!==void 0?s.initialInterval??xf:0,i=0,a,l,{config:c}=t;for(n&&(c=_e(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,gd(a)){const y=c?.configurable?.checkpoint_ns,p=a.command;if(p.graph===y){for(const C of t.writers)await C.invoke(p,c);a=void 0;break}else if(p.graph===K.PARENT){const C=Pd(y);a.command=new K({...a.command,graph:C})}}if(Un(a)||s===void 0||(i+=1,i>=(s.maxAttempts??Pf))||!(s.retryOn??Nf)(a))break;o=Math.min(s.maxInterval??Af,o*(s.backoffFactor??Mf));const d=s.jitter?Math.floor(o+Math.random()*1e3):o;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 ${o.toFixed(2)}ms (attempt ${i}) after ${f}: ${a}`),c=_e(c,{[ze]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const bs=Symbol.for("promiseAdded");function If(){const t={next:()=>{},wait:Promise.resolve(bs)};function e(n){t.next=()=>{t.wait=new Promise(e),n(bs)}}return t.wait=new Promise(e),t}var $f=class{nodeFinished;loop;constructor({loop:t,nodeFinished:e}){this.loop=t,this.nodeFinished=e}async tick(t={}){const{timeout:e,retryPolicy:n,onStepWrite:r,maxConcurrency:s}=t,o=new Set;let i;const a=new AbortController,l=a.signal,c=e?AbortSignal.timeout(e):void 0,u=Object.values(this.loop.tasks).filter(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:C}of f)this._commit(y,p),st(p)||Un(p)&&!st(i)?i=p:p&&(o.size===0||!C)&&(a.abort(),o.add(p));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(y=>y.writes).flat()),o.size===1)throw Array.from(o)[0];if(o.size>1)throw new AggregateError(Array.from(o),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(st(i)||Un(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[wo]??{},s=r.externalAbortSignal??n,o=e??r.timeoutAbortSignal,{signal:i,dispose:a}=cr(s,o,t),l={externalAbortSignal:s,timeoutAbortSignal:o,composedAbortSignal:i};return this.loop.config=_e(this.loop.config,{[wo]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},o=If(),i={},a={executingTasksMap:i,barrier:o,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=cr(s?.externalAbortSignal,s?.timeoutAbortSignal),h=u.signal?new Promise((d,f)=>{c=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",c,{once:!0})}):void 0;for(;(l===0||Object.keys(i).length>0)&&t.length;){for(;Object.values(i).length<(r??t.length)&&l<t.length;l+=1){const f=t[l];i[f.id]=Ga(f,n,{[Gs]:Ka?.bind(a,this,f)},s?.composedAbortSignal).catch(y=>({task:f,error:y,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(i),...h?[h]:[],o.wait]);d!==bs&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete i[d.task.id])}}_commit(t,e){if(e!==void 0)if(st(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[j,s]),r=t.writes.filter(s=>s[0]===le);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Un(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[ie,{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([Ks,null]),this.loop.putWrites(t.id,t.writes)}};async function Ka(t,e,n,r,s,o={}){const i=e.config?.configurable?.[Ye];if(!i)throw new Error(`BUG: No scratchpad found on task ${e.name}__${e.id}`);const a=i.callCounter;i.callCounter+=1;const l=new rf({func:n,name:r,input:s,cache:o.cache,retry:o.retry,callbacks:o.callbacks}),c=await this.scheduleTask(e,a,l);if(!c)return;const u=this.executingTasksMap[c.id];if(u!==void 0)return u;if(c.writes.length>0){const h=c.writes.filter(([f])=>f===Vt),d=c.writes.filter(([f])=>f===ie);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=Ga(c,o.retry,{[Gs]:Ka.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 Rf({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:o,interruptBeforeNodes:i}){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===mn)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(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Pe(`Node ${String(c)} not in nodes`)}if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Pe(`Node ${String(c)} not in nodes`)}}function Mo(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 Ja extends ht{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 Ja({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}},Lf=class{static subscribeTo(t,e){const{key:n,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(t)&&n!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;typeof t=="string"?n?s={[n]:t}:s=[t]:s=Object.fromEntries(t.map(i=>[i,i]));const o=Array.isArray(t)?t:[t];return new mn({channels:s,triggers:o,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:at,skipNone:!1});for(const[r,s]of Object.entries(e??{}))ee.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:at,skipNone:!0,mapper:Dt(s)}):n.push({channel:r,value:s,skipNone:!1});return new se(n)}},Df=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)}},Ff=class extends Df{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,we in this.channels&&"lc_graph_name"in this.channels[we]&&this.channels[we].lc_graph_name!=="Topic")throw new Error(`Channel '${we}' is reserved and cannot be used in the graph.`);this.channels[we]=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=Re(this.config,t);return new this.constructor({...this,config:e})}validate(){Rf({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[t,e]of Object.entries(this.nodes))for(const n of e.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(t);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(t){return this.getGraph(t)}*getSubgraphs(t,e){for(const[n,r]of Object.entries(this.nodes)){if(t!==void 0&&!t.startsWith(n))continue;const s=r.subgraphs?.length?r.subgraphs:[r.bound];for(const o of s){const i=Fa(o);if(i!==void 0){if(n===t){yield[n,i];return}if(t===void 0&&(yield[n,i]),e){let a=t;t!==void 0&&(a=t.slice(n.length+1));for(const[l,c]of i.getSubgraphs(a,e))yield[`${n}${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=or(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===be).map(([d,f,y])=>[String(f),y]);h.length>0&&ue(e.checkpoint,s,[{name:Ie,writes:h,triggers:[]}],void 0,this.triggerToNodes)}const o=Object.values(wt(e.checkpoint,e.pendingWrites,this.nodes,s,e.config,!0,{step:(e.metadata?.step??-1)+1,store:this.store})),i=await We(this.getSubgraphsAsync()),a=e.config.configurable?.checkpoint_ns??"",l={};for(const h of o){const d=i.find(([y])=>y===h.name);if(!d)continue;let f=`${String(h.name)}${Fe}${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(o.map(f=>[f.id,f]));for(const[f,y,p]of e.pendingWrites)[ie,j,In].includes(y)||f in h&&h[f].writes.push([String(y),p]);const d=o.filter(f=>f.writes.length>0);d.length>0&&ue(e.checkpoint,s,d,void 0,this.triggerToNodes)}let c=e?.metadata;c&&e?.config?.configurable?.thread_id&&(c={...c,thread_id:e.config.configurable.thread_id});const u=o.filter(h=>h.writes.length===0).map(h=>h.name);return{values:ct(s,this.streamChannelsAsIs),next:u,tasks:Ba(o,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:Qe(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 Fn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const a=Rr(r);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(ft(t,{[H]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=Re(this.config,t),o=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:o,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[H]??this.checkpointer;if(!n)throw new Fn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const o=Rr(r);for await(const[i,a]of this.getSubgraphsAsync(o,!0))if(i===o){yield*a.getStateHistory(ft(t,{[H]:n}),e);return}throw new Error(`Subgraph with namespace "${o}" not found.`)}const s=Re(this.config,t,{configurable:{checkpoint_ns:r}});for await(const o of n.list(s,e))yield this._prepareStateSnapshot({config:o.config,saved:o})}async bulkUpdateState(t,e){const n=t.configurable?.[H]??this.checkpointer;if(!n)throw new Fn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(e.length===0)throw new Error("No supersteps provided");if(e.some(i=>i.updates.length===0))throw new Error("No updates provided");const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const i=Rr(r);for await(const[,a]of this.getSubgraphsAsync(i,!0))return await a.bulkUpdateState(ft(t,{[H]:n}),e);throw new Error(`Subgraph "${i}" not found`)}const s=async(i,a)=>{const l=this.config?Re(this.config,i):i,c=await n.getTuple(l),u=c!==void 0?sr(c.checkpoint):ya(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=ft(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),y=l.metadata??{};c?.config.configurable&&(f=ft(l,c.config.configurable),y={...c.metadata,...y});const{values:p,asNode:C}=a[0];if(p==null&&C===void 0){if(a.length>1)throw new B("Cannot create empty checkpoint with multiple updates");const b=await n.put(f,tt(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return Qe(b,c?c.metadata:void 0)}const S=or(this.channels,u);if(p===null&&C===A){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const _=wt(u,c.pendingWrites||[],this.nodes,S,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),M=(c.pendingWrites||[]).filter(E=>E[0]===be).map(E=>E.slice(1));M.length>0&&ue(u,S,[{name:Ie,writes:M,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[E,P,I]of c.pendingWrites||[])[ie,j,In].includes(P)||E in _&&_[E].writes.push([P,I]);ue(u,S,Object.values(_),n.getNextVersion.bind(n),this.triggerToNodes)}const b=await n.put(f,tt(u,S,d),{...y,source:"update",step:d+1,parents:c?.metadata?.parents??{}},Gn(h,u.channel_versions));return Qe(b,c?c.metadata:void 0)}if(C===vd){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 b=E=>!Array.isArray(E)||E.length===0?!1:E.every(P=>Array.isArray(P)&&P.length===2),_=tt(u,void 0,d),M=await n.put(c.parentConfig??ft(c.config,{checkpoint_id:void 0}),_,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(b(p)){const E=wt(_,c.pendingWrites,this.nodes,S,M,!1,{step:d+2}),P=Object.values(E).reduce((V,{name:X,id:Sr})=>(V[X]??=[],V[X].push({id:Sr}),V),{}),I=p.reduce((V,X)=>{const[Sr,qt]=X;V[qt]??=[];const _l=V[qt].length,Sl=P[qt]?.[_l]?.id;return V[qt].push({values:Sr,asNode:qt,taskId:Sl}),V},{});return s(Qe(M,c.metadata),Object.values(I).flat())}return Qe(M,c.metadata)}if(C===Ie){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const b=await We(Ua(this.inputChannels,p));if(b.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);ue(u,S,[{name:Ie,writes:b,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const _=c?.metadata?.step!=null?c.metadata.step+1:-1,M=await n.put(f,tt(u,S,_),{source:"input",step:_,parents:c?.metadata?.parents??{}},Gn(h,u.channel_versions));return await n.putWrites(M,b,mt(Ie,u.id)),Qe(M,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const b=wt(u,c.pendingWrites,this.nodes,S,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),_=(c.pendingWrites??[]).filter(E=>E[0]===be).map(E=>E.slice(1));_.length>0&&ue(c.checkpoint,S,[{name:Ie,writes:_,triggers:[]}],void 0,this.triggerToNodes);for(const[E,P,I]of c.pendingWrites)[ie,j,In].includes(P)||b[E]===void 0||b[E].writes.push([P,I]);const M=Object.values(b).filter(E=>E.writes.length>0);M.length>0&&ue(u,S,M,void 0,this.triggerToNodes)}const m=Object.values(u.versions_seen).map(b=>Object.values(b)).flat().find(b=>!!b),w=[];if(a.length===1){let{values:b,asNode:_,taskId:M}=a[0];if(_===void 0&&Object.keys(this.nodes).length===1)[_]=Object.keys(this.nodes);else if(_===void 0&&m===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(_=this.inputChannels);else if(_===void 0){const E=Object.entries(u.versions_seen).map(([P,I])=>Object.values(I).map(V=>[V,P])).flat().filter(([P,I])=>I!==j).sort(([P],[I])=>wa(P,I));E&&(E.length===1?_=E[0][1]:E[E.length-1][0]!==E[E.length-2][0]&&(_=E[E.length-1][1]))}if(_===void 0)throw new B('Ambiguous update, specify "asNode"');w.push({values:b,asNode:_,taskId:M})}else for(const{asNode:b,values:_,taskId:M}of a){if(b==null)throw new B('"asNode" is required when applying multiple updates');w.push({values:_,asNode:b,taskId:M})}const v=[];for(const{asNode:b,values:_,taskId:M}of w){if(this.nodes[b]===void 0)throw new B(`Node "${b.toString()}" does not exist`);const E=this.nodes[b].getWriters();if(!E.length)throw new B(`No writers found for node "${b.toString()}"`);v.push({name:b,input:_,proc:E.length>1?Xe.from(E,{omitSequenceTags:!0}):E[0],writes:[],triggers:[j],id:M??mt(j,u.id),writers:[]})}for(const b of v)await b.proc.invoke(b.input,rn({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[qe]:_=>b.writes.push(..._),[it]:(_,M=!1)=>Kn(u,S,b,_,M)}}));for(const b of v){const _=b.writes.filter(M=>M[0]!==he);c!==void 0&&_.length>0&&await n.putWrites(f,_,b.id)}ue(u,S,v,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const k=Gn(h,u.channel_versions),x=await n.put(f,tt(u,S,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},k);for(const b of v){const _=b.writes.filter(M=>M[0]===he);_.length>0&&await n.putWrites(x,_,b.id)}return Qe(x,c?c.metadata:void 0)};let o=t;for(const{updates:i}of e)o=await s(o,i);return o}async updateState(t,e,n){return this.bulkUpdateState(t,[{updates:[{values:e,asNode:n}]}])}_defaults(t){const{debug:e,streamMode:n,inputKeys:r,outputKeys:s,interruptAfter:o,interruptBefore:i,...a}=t;let l=!0;const c=e!==void 0?e:this.debug;let u=s;u===void 0?u=this.streamChannelsAsIs:Mo(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Mo(h,this.channels);const d=i??this.interruptBefore??[],f=o??this.interruptAfter??[];let y;n!==void 0?(y=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[sn]!==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 C=t.store??this.store,S=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?.[xa]??"async";return[c,y,h,u,a,d,f,p,C,l,S,w]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:cr(e?.signal,n.signal).signal},s=await super.stream(t,r);return new To(e?.encoding==="text/event-stream"?vf(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:nf(this.config?.callbacks,e?.callbacks),signal:cr(e?.signal,r.signal).signal};return new To(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=Aa(this.config,e);if(s.recursionLimit===void 0||s.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&s.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const o=await this._validateInput(t),{runId:i,...a}=s,[l,c,,u,h,d,f,y,p,C,S,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 Wa({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[Ee]??"";h.configurable[Ee]=P.split(J).map(I=>I.split(Fe)[0]).join(J)}if(c.includes("messages")){const P=new Ef(V=>w.push(V)),{callbacks:I}=h;if(I===void 0)h.callbacks=[P];else if(Array.isArray(I))h.callbacks=I.concat(P);else{const V=I.copy();V.addHandler(P,!0),h.callbacks=V}}h.writer??=P=>{if(!c.includes("custom"))return;const I=Ad()?.configurable?.[Ee]?.split(J).slice(0,-1);w.push([I??[],"custom",P])},h.interrupt??=this.userInterrupt??La;const k=await(await Rc(h))?.handleChainStart(this.toJSON(),tf(t,"input"),i,void 0,void 0,void 0,h?.runName??this.getName()),x=Ws(this.channels);let b,_;const E=(async()=>{try{b=await kf.initialize({input:o,config:h,checkpointer:y,nodes:this.nodes,channelSpecs:x,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:S,stream:w,interruptAfter:f,interruptBefore:d,manager:k,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:m});const P=new $f({loop:b,nodeFinished:h.configurable?.[Sd]});e?.subgraphs&&(b.config.configurable={...b.config.configurable,[ir]:b.stream}),await this._runLoop({loop:b,runner:P,debug:l,config:h}),m==="sync"&&await Promise.all(b?.checkpointerPromises??[])}catch(P){_=P}finally{try{b&&(await b.store?.stop(),await b.cache?.stop()),await Promise.all(b?.checkpointerPromises??[])}catch(P){_=_??P}_?w.error(_):w.close()}})();try{for await(const P of w){if(P===void 0)throw new Error("Data structure error.");const[I,V,X]=P;if(c.includes(V)){if(n==="text/event-stream"){r?yield[I,V,X]:yield[null,V,X];continue}r&&!C?yield[I,V,X]:C?r?yield[I,X]:yield X:yield[V,X]}}}catch(P){throw await k?.handleChainError(_),P}finally{await E}await k?.handleChainEnd(b?.output??{},i,void 0,void 0,void 0)}async invoke(t,e){const n=e?.streamMode??"values",r={...e,outputKeys:e?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},s=[],o=await this.stream(t,r),i=[];let a;for await(const l of o)n==="values"?Ma(l)?i.push(l[j]):a=l:s.push(l);if(n==="values"){if(i.length>0){const l=i.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 o;try{for(;await e.tick({inputKeys:this.inputChannels});){for(const{task:i}of await e._matchCachedWrites())e._outputWrites(i.id,i.writes,!0);r&&gf(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&za(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(i,a)=>{r&&yf(i,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new md([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(i){if(o=i,!await e.finishAndHandleError(o))throw i}finally{o===void 0&&await e.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},zt=class qa extends ht{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new qa(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}},Ya=class{path;ends;constructor(t){ee.isRunnable(t.path)?this.path=t.path:this.path=Dt(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 dt({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===_a.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
|
|
43
|
-
`),{lc_error_code:"UNREACHABLE_NODE"});for(const r of n)if(r!==A&&!(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}},Xa=class extends Ff{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new zt,this.nodes[t]=new mn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new se([{channel:t,value:at}],[G])),this.streamChannels.push(t)}attachEdge(t,e){if(e===A){if(t===L)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new se([{channel:A,value:at}],[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]=Lf.subscribeTo(L,{tags:[G]})),this.nodes[t].pipe(n.run(s=>{const o=s.map(i=>pe(i)?i:{channel:i===A?A:`branch:${t}:${e}:${i}`,value:at});return new se(o,[G])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==A){const o=`branch:${t}:${e}:${s}`;this.channels[o]=new zt,this.nodes[s].triggers.push(o),this.nodes[s].channels.push(o)}}async getGraphAsync(t){const e=t?.xray,n=new oo,r={[L]:n.addNode({schema:Se()},L)},s={};let o={};e&&(o=Object.fromEntries((await We(this.getSubgraphsAsync())).filter(l=>Ao(l[1]))));function i(l,c,u,h=!1){if(c===A&&s[A]===void 0&&(s[A]=n.addNode({schema:Se()},A)),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=o[l]!==void 0?await o[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let S=function(w){return w?w.lc_runnable:!1},m=function(w,v){if(w!==void 0&&!io(w))return w;if(S(v))try{let k=v.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return v.getName()}else return v.name??"UnknownSchema"};const[p,C]=n.extend(y,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:m(C.id,C.data),...C}),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)i(te(l),te(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[te(h),te(h)])),[A]:A};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))i(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)i(te(l),te(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new oo,r={[L]:n.addNode({schema:Se()},L)},s={};let o={};e&&(o=Object.fromEntries(en(this.getSubgraphs()).filter(l=>Ao(l[1]))));function i(l,c,u,h=!1){return c===A&&s[A]===void 0&&(s[A]=n.addNode({schema:Se()},A)),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=o[l]!==void 0?o[l].getGraph({...t,xray:f}):h.getGraph(t);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let S=function(w){return w?w.lc_runnable:!1},m=function(w,v){if(w!==void 0&&!io(w))return w;if(S(v))try{let k=v.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return v.getName()}else return v.name??"UnknownSchema"};const[p,C]=n.extend(y,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:m(C.id,C.data),...C}),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)i(te(l),te(c));for(const[l,c]of Object.entries(this.builder.branches)){const u={...Object.fromEntries(Object.keys(this.builder.nodes).filter(h=>h!==l).map(h=>[te(h),te(h)])),[A]:A};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))i(te(l),te(y),f,!0)}}return n}};function Ao(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 Vf=class Za extends ht{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new Za(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)}},Bf=class Qa extends ht{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 Qa(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 zf="lg:";var Wf=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=ao(t);for(const[r,s]of Object.entries(n)){const o=this.get(s);o?.reducer?e[r]=new us(o.reducer.fn,o.default):e[r]=new Hs}return e}getExtendedChannelSchemas(t,e){if(Object.keys(e).length===0)return t;const n=Object.entries(e).filter(([,o])=>o===!0).sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>`${o}:${i}`).join("|"),r=this._extensionCache.get(n)??new WeakMap;if(r.has(t))return r.get(t);let s=t;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const o=Object.entries(ao(t)).map(([i,a])=>{const l=this.get(a);let c=e.withReducerSchema?l?.reducer?.schema??a:a;if(e.withJsonSchemaExtrasAsDescription&&l?.jsonSchemaExtra){const u=qr(c)??qr(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${zf}${h}`)}return[i,c]});s=jc(t,Object.fromEntries(o)),Lc(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=Es(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const Wt=new Wf;function Ht(t,e){if(e.reducer&&!e.default){const n=Ts(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return Wt.extend(n,()=>e),n}else return Wt.extend(t,()=>e),t}const je="__root__",vs=Symbol.for("langgraph.state.partial");var Hf=class extends Uf{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Wt;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Zf(t)){const r=this._metaRegistry.getChannelsForSchema(t.state),s=t.input!=null?this._metaRegistry.getChannelsForSchema(t.input):r,o=t.output!=null?this._metaRegistry.getChannelsForSchema(t.output):r;this._schemaDefinition=r,this._schemaRuntimeDefinition=t.state,this._inputDefinition=s,this._inputRuntimeDefinition=t.input??vs,this._outputDefinition=o,this._outputRuntimeDefinition=t.output??t.state}else if(de(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=vs,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(Xf(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Yf(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Jf(t)||Po(t)){const r=Po(t)?t.spec:t;this._schemaDefinition=r}else if(qf(t)){const r=Gf(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)&&!de(r)}n(e)?(de(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):de(e)&&(this._configRuntimeSchema=e)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([t,e])=>t.map(n=>[n,e]))])}_addSchema(t){if(!this._schemaDefinitions.has(t)){this._schemaDefinitions.set(t,t);for(const[e,n]of Object.entries(t)){let r;if(typeof n=="function"?r=n():r=n,this.channels[e]!==void 0){if(this.channels[e]!==r&&r.lc_graph_name!=="LastValue")throw new Error(`Channel "${e}" already exists with a different type.`)}else this.channels[e]=r}}}addNode(...t){function e(r){return r.length>=1&&typeof r[0]!="string"}const n=e(t)?Array.isArray(t[0])?t[0]:Object.entries(t[0]).map(([r,s])=>[r,s]):[[t[0],t[1],t[2]]];if(n.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,o]of n){if(r in this.channels)throw new Error(`${r} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const u of[J,Fe])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===A||r===L)throw new Error(`Node \`${r}\` is reserved.`);let i=this._schemaDefinition;o?.input!==void 0&&(de(o.input)?i=this._metaRegistry.getChannelsForSchema(o.input):o.input.spec!==void 0&&(i=o.input.spec)),i!==void 0&&this._addSchema(i);let a;ee.isRunnable(s)?a=s:typeof s=="function"?a=new dt({func:s,name:r,trace:!1}):a=Dt(s);let l=o?.cachePolicy;typeof l=="boolean"&&(l=l?{}:void 0);const c={runnable:a,retryPolicy:o?.retryPolicy,cachePolicy:l,metadata:o?.metadata,input:i??this._schemaDefinition,subgraphs:qs(a)?[a]:o?.subgraphs,ends:o?.ends,defer:o?.defer};this.nodes[r]=c}return this}addEdge(t,e){if(typeof t=="string")return super.addEdge(t,e);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const n of t){if(n===A)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===A)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(n=>n===e))throw new Error(`Need to add a node named "${e}" first`);return this.waitingEdges.add([t,e]),this}addSequence(t){const e=Array.isArray(t)?t:Object.entries(t);if(e.length===0)throw new Error("Sequence requires at least one node.");let n;for(const[r,s,o]of e){if(r in this.nodes)throw new Error(`Node names must be unique: node with the name "${r}" already exists.`);const i=r;this.addNode(i,s,o),n!=null&&this.addEdge(n,i),n=i}return this}compile({checkpointer:t,store:e,cache:n,interruptBefore:r,interruptAfter:s,name:o,description:i}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(s)?s:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),l=a.length===1&&a[0]===je?je:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===je?je:c,h=this._interrupt,d=new Kf({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[L]:new zt},inputChannels:L,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:o,description:i,userInterrupt:h});d.attachNode(L);for(const[f,y]of Object.entries(this.nodes))d.attachNode(f,y);d.attachBranch(L,bo,Oo(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,bo,Oo(),{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,C]of Object.entries(y))d.attachBranch(f,p,C);return d.validate()}};function Gf(t){const e={};for(const[n,r]of Object.entries(t))e[n]=ds(r);return e}var Kf=class extends Xa{description;_metaRegistry=Wt;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 o(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=o(c);u&&l.push(...u??[])}return l}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([l])=>n.includes(l));{const l=Array.isArray(a)?"array":typeof a;throw new B(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}const i=[{value:at,mapper:new dt({func:n.length&&n[0]===je?r:o,trace:!1,recurse:!1})}];if(t===L)this.nodes[t]=new mn({tags:[G],triggers:[L],channels:[L],writers:[new se(i,[G])]});else{const a=e?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(h=>[h,h])),c=Object.keys(l).length===1&&je in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new wd:new zt(!1),this.nodes[t]=new mn({triggers:[u],channels:c?Object.keys(l):l,writers:[new se(i,[G])],mapper:c?void 0:h=>Object.fromEntries(Object.entries(h).filter(([d])=>d in l)),bound:e?.runnable,metadata:e?.metadata,retryPolicy:e?.retryPolicy,cachePolicy:e?.cachePolicy,subgraphs:e?.subgraphs,ends:e?.ends})}}attachEdge(t,e){if(e!==A){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 Bf(new Set(t)):new Vf(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(o,i)=>{const a=o.filter(c=>c!==A);if(!a.length)return;const l=a.map(c=>pe(c)?c:{channel:c===A?c:`branch:to:${c}`,value:t});await se.doWrite({...i,tags:(i.tags??[]).concat([G])},l)};this.nodes[t].writers.push(n.run(s,r.withReader?o=>Xd.doRead(o,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(t){if(t==null)return t;const e=(()=>{const n=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition,s=o=>{if(o!=null)return this._metaRegistry.getExtendedChannelSchemas(o,{withReducerSchema:!0})};if(de(n))return s(n);if(n===vs)return Es(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 Ma(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return de(e)&&Ke(e,t),t}};function Jf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Ca(e))}function Po(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function qf(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Yf(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function Xf(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Zf(t){return!(typeof t!="object"||t==null||!("state"in t)||!de(t.state)||"input"in t&&!de(t.input)||"output"in t&&!de(t.output))}function Qf(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 Sa(r);pe(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Oo(){const t=new dt({func:Qf,tags:[G],trace:!1,recurse:!1,name:"<control_branch>"});return new Ya({path:t})}const el="__remove_all__";function tl(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(cn),o=r.map(cn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=qn(),u.lc_kwargs.id=u.id);let i;for(let u=0;u<o.length;u+=1){const h=o[u];(h.id===null||h.id===void 0)&&(h.id=qn(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===el&&(i=u)}if(i!=null)return o.slice(i+1);const a=[...s],l=new Map(a.map((u,h)=>[u.id,h])),c=new Set;for(const u of o){const h=l.get(u.id);if(h!==void 0)u.getType()==="remove"?c.add(u.id):(c.delete(u.id),a[h]=u);else{if(u.getType()==="remove")throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);l.set(u.id,a.length),a.push(u)}}return a.filter(u=>!c.has(u.id))}hs.Root({messages:hs({reducer:tl,default:()=>[]})});const ur={reducer:{fn:tl},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:Ht(ae(),ur)});pd();const _s=Symbol.for("langgraph-zod");_s in globalThis||(globalThis[_s]=new WeakSet);function No(t){const e=globalThis[_s];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Ht(n,{jsonSchemaExtra:r})},reducer(r,s){const o=Ts(n);return Ht(n,{default:o,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{No(Dc.prototype),No(Tl.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 ep=class extends El{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=Ts(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new ep(Wt);function tp(t=!0,e,n=[]){const r={messages:Ht(ae(),ur),jumpTo:Ae([bt("model_request"),bt("tools"),bt("end"),Fc()]).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=xs().optional());const o=z(r);return Wt.getChannelsForSchema(o)}z({llmInputMessages:Ht(ae(),{reducer:{fn:(t,e)=>ur.reducer.fn([],e)},default:()=>[]}),messages:Ht(ae(),ur)});const Io="prompt",zr=/<name>(.*?)<\/name>/s,Wr=/<content>(.*?)<\/content>/s;function np(t){if(!O.isInstance(t)||jt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new O({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new O({...t.lc_kwargs,content:n,name:void 0})}function rp(t){if(!O.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(zr),o=r.text.match(Wr);return s&&(!o||o[1]==="")?(n=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(zr),o=r.text.match(Wr);return!s||!o?r:(n=s[1],{...r,text:o[1]})}return r});else{const r=t.content,s=r.match(zr),o=r.match(Wr);if(!s||!o)return t;n=s[1],e=o[1]}return new O({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function W(t){return ee.isRunnable(t)}function $o(t){return As(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const Hr=(t,e,n={})=>{if($o(t))return t.bindTools(e,n);if(xe.isRunnableBinding(t)&&$o(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 nl(t){if(typeof t=="function")return;let e=t;if(Xe.isRunnableSequence(e)&&(e=e.steps.find(n=>xe.isRunnableBinding(n))||e),!Qn(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 Xr}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new Xr}}function Ss(t){return!!(O.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function sp(t){let e;if(t==null)e=Lt.from(n=>n.messages).withConfig({runName:Io});else if(typeof t=="string"){const n=new ve(t);e=Lt.from(r=>[n,...r.messages??[]]).withConfig({runName:Io})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function op(t,e,n={}){const r=Hr(t,e,n);if(r)return r;if(Qn(t)){const s=Hr(await t._model(),e,n);if(s)return s}if(Xe.isRunnableSequence(t)){const s=t.steps.findIndex(o=>xe.isRunnableBinding(o)||As(o)||Qn(o));if(s>=0){const o=Hr(t.steps[s],e,n);if(o){const i=t.steps.slice();return i.splice(s,1,o),Xe.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function ip(t){if(t.length===0)return;if(t.length===1)return t[0];function e(r,s){return async(o,i)=>r(o,async()=>s(o,async()=>i(o)))}let n=t[t.length-1];for(let r=t.length-2;r>=0;r--)n=e(t[r],n);return n}function ap(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return ip(e.map(n=>{const r=n.wrapToolCall;return async(o,i)=>{try{const a=await r({...o,state:{messages:o.state.messages,...n.stateSchema?Ke(n.stateSchema,{...o.state}):{}}},i);if(!F.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 lp(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=Uc(r.stateSchema,a=>a.startsWith("_")),o=await Vc(s,e);if(o.success){Object.assign(n,o.data);continue}const i=o.error.issues.filter(a=>a.code==="invalid_type"&&a.message==="Required").map(a=>` - ${a.path.join(".")}: ${a.message}`).join(`
|
|
41
|
+
`))};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:Ti(u.payload)})}o==="checkpoints"&&(l=Ti(a));const c=i?.length?`${o}|${i.join("|")}`:o;r({event:c,data:l})}}catch(s){r({event:"error",data:bf(s)})}n.close()}})}const Mn=Symbol.for("INPUT_DONE"),Fr=Symbol.for("INPUT_RESUMING"),_f=25;function Sf(...t){return new Wa({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 Cf=class extends hd{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}},kf=class Ha{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?.[Be]!==void 0&&this.config.configurable?.[Be],s=this.input===null||this.input===void 0,i=Y(this.input)&&this.input.resume!=null,o=this.input===Fr,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=af,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 Cf(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?.[ir]!==void 0&&(r=Sf(r,n.configurable[ir]));const s=n.configurable?!("checkpoint_id"in n.configurable):!0,i=n.configurable?.[qe];n.configurable&&i&&(i.subgraphCounter>0&&(n=ve(n,{[Te]:[n.configurable[Te],i.subgraphCounter.toString()].join(J)})),i.subgraphCounter+=1);const o=ot in(n.configurable??{});!o&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==""&&(n=ve(n,{checkpoint_ns:"",checkpoint_id:void 0}));let a=n;n.configurable?.[ge]!==void 0&&n.configurable?.[ge]?.[n.configurable?.checkpoint_ns]&&(a=ve(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:ya(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...n,...c.config,configurable:{checkpoint_ns:"",...n.configurable,...c.config.configurable}};const u=c.parentConfig,h=rr(c.checkpoint),d={...c.metadata},f=c.pendingWrites??[],g=sr(e.channelSpecs,h),p=(d.step??0)+1,C=p+(n.recursionLimit??_f)+1,S={...h.channel_versions},m=e.store?new ud(e.store):void 0;return m&&await m.start(),new Ha({input:e.input,config:n,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:d,checkpointConfig:a,prevCheckpointConfig:u,checkpointNamespace:l,channels:g,isNested:o,manager:e.manager,skipDoneTasks:s,step:p,stop:C,checkpointPreviousVersions:S,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 od)&&(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=ve(this.checkpointConfig,{[Te]:this.config.configurable?.checkpoint_ns??"",[hs]: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]===oe||n[0][0]===R||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]===R){if(s.path?.[0]===he&&s.path?.at(-1)===!0)return;const i=n.filter(o=>o[0]===R).flatMap(o=>o[1]);this._emit([["updates",{[R]:i}],["values",{[R]:i}]])}else n[0][0]!==oe&&this._emit(en(Fe(ef(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(en(Fe(pf([[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(![Mn,Fr].includes(this.input))await this._first(n);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new _t;if(Object.values(this.tasks).every(i=>i.writes.length>0)){const i=Object.values(this.tasks).flatMap(a=>a.writes);this.updatedChannels=ue(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);const o=await ze(Fe(jr(this.outputKeys,i,this.channels),"values"));if(this._emit(o),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),xn(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new _t;this.config.configurable?.[Be]!==void 0&&delete this.config.configurable?.[Be]}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(Fe(mf(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===oe||o===R||o===le)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(xn(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new _t;const s=await ze(Fe(Si(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(De)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());const n=this._suppressInterrupt(e);return(n||e===void 0)&&(this.output=ct(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=ue(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(en(Fe(jr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),st(e)&&!e.interrupts.length&&this._emit([["updates",{[R]:[]}],["values",{[R]:[]}]])),n}async acceptPush(e,n,r){if(this.interruptAfter?.length>0&&xn(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=gs([he,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&&xn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}this._emit(en(Fe(Si([s]),"tasks"))),this.debug&&za(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 st(e)&&!this.isNested}async _first(e){const{configurable:n}=this.config,r=n?.[qe];if(r&&r.nullResume!==void 0&&this.putWrites(we,[[le,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[Fn]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of Qd(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new mi("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&&ue(this.checkpoint,this.channels,[{name:Ne,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[R]={...this.checkpoint.versions_seen[R],[a]:l}}const o=await ze(Fe(jr(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=Fr;else if(i)await this._putCheckpoint({source:"input"}),this.input=Mn;else{const o=await ze(Fa(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=ue(this.checkpoint,this.channels,Object.values(a).concat([{name:Ne,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Mn}else if(Be in(this.config.configurable??{}))this.input=Mn;else throw new mi(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=ve(this.config,{[Be]: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=ve(this.checkpointConfig,{[Te]:this.config.configurable?.checkpoint_ns??""});const o={...this.checkpoint.channel_versions},a=Hn(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:rr(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=tt(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=ve(this.checkpointConfig,{[Te]:this.config.configurable?.checkpoint_ns??"",[hs]: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===oe||r===R||r===le)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 Tf(t){return Oe(t?.message)}var Ef=class extends Ic{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&&($c(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(Cd)&&!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&&(Tf(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new Lt({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)||ri(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(Oe(c)||ri(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 xf=500,Mf=2,Af=128e3,Pf=3,Of=[400,401,402,403,404,405,406,407,409],Nf=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&&Of.includes(+e)||t?.error?.code==="insufficient_quota")};async function Ga(t,e,n,r){const s=t.retry_policy??e;let i=s!==void 0?s.initialInterval??xf:0,o=0,a,l,{config:c}=t;for(n&&(c=ve(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,gd(a)){const g=c?.configurable?.checkpoint_ns,p=a.command;if(p.graph===g){for(const C of t.writers)await C.invoke(p,c);a=void 0;break}else if(p.graph===K.PARENT){const C=Pd(g);a.command=new K({...a.command,graph:C})}}if(Un(a)||s===void 0||(o+=1,o>=(s.maxAttempts??Pf))||!(s.retryOn??Nf)(a))break;i=Math.min(s.maxInterval??Af,i*(s.backoffFactor??Mf));const d=s.jitter?Math.floor(i+Math.random()*1e3):i;await new Promise(g=>setTimeout(g,d));const f=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(t.name)}" after ${i.toFixed(2)}ms (attempt ${o}) after ${f}: ${a}`),c=ve(c,{[Be]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const ys=Symbol.for("promiseAdded");function If(){const t={next:()=>{},wait:Promise.resolve(ys)};function e(n){t.next=()=>{t.wait=new Promise(e),n(ys)}}return t.wait=new Promise(e),t}var $f=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(g=>g.writes.length===0),{signals:h,disposeCombinedSignal:d}=this._initializeAbortSignals({exceptionSignal:l,stepTimeoutSignal:c,signal:t.signal}),f=this._executeTasksWithRetry(u,{signals:h,retryPolicy:n,maxConcurrency:s});for await(const{task:g,error:p,signalAborted:C}of f)this._commit(g,p),st(p)||Un(p)&&!st(o)?o=p:p&&(i.size===0||!C)&&(a.abort(),i.add(p));if(d?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(g=>g.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(st(o)||Un(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[gi]??{},s=r.externalAbortSignal??n,i=e??r.timeoutAbortSignal,{signal:o,dispose:a}=lr(s,i,t),l={externalAbortSignal:s,timeoutAbortSignal:i,composedAbortSignal:o};return this.loop.config=ve(this.loop.config,{[gi]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},i=If(),o={},a={executingTasksMap:o,barrier:i,retryPolicy:n,scheduleTask:async(d,f,g)=>this.loop.acceptPush(d,f,g)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let l=0,c;const u=lr(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]=Ga(f,n,{[Hs]:Ka?.bind(a,this,f)},s?.composedAbortSignal).catch(g=>({task:f,error:g,signalAborted:s?.composedAbortSignal?.aborted}))}const d=await Promise.race([...Object.values(o),...h?[h]:[],i.wait]);d!==ys&&(yield d,c!=null&&(u.signal?.removeEventListener("abort",c),u.dispose?.()),delete o[d.task.id])}}_commit(t,e){if(e!==void 0)if(st(e)){if(e.interrupts.length){const n=e.interrupts.map(s=>[R,s]),r=t.writes.filter(s=>s[0]===le);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Un(e)&&t.writes.length?this.loop.putWrites(t.id,t.writes):this.loop.putWrites(t.id,[[oe,{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([Gs,null]),this.loop.putWrites(t.id,t.writes)}};async function Ka(t,e,n,r,s,i={}){const o=e.config?.configurable?.[qe];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 rf({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===Bt),d=c.writes.filter(([f])=>f===oe);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${c.name}__${c.id}`)}if(d.length>0){if(d.length===1){const f=d[0][1],g=f instanceof Error?f:new Error(String(f));return Promise.reject(g)}throw new Error(`BUG: multiple errors found for task ${c.name}__${c.id}`)}return}else{const h=Ga(c,i.retry,{[Hs]:Ka.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 Ae=class extends Error{constructor(t){super(t),this.name="GraphValidationError"}};function Rf({nodes:t,channels:e,inputChannels:n,outputChannels:r,streamChannels:s,interruptAfterNodes:i,interruptBeforeNodes:o}){if(!e)throw new Ae("Channels not provided");const a=new Set,l=new Set;for(const[c,u]of Object.entries(t)){if(c===R)throw new Ae(`"Node name ${R} is reserved"`);if(u.constructor===mn)u.triggers.forEach(h=>a.add(h));else throw new Ae(`Invalid node type ${typeof u}, expected PregelNode`)}for(const c of a)if(!(c in e))throw new Ae(`Subscribed channel '${String(c)}' not in channels`);if(Array.isArray(n)){if(n.every(c=>!a.has(c)))throw new Ae(`None of the input channels ${n} are subscribed to by any node`)}else if(!a.has(n))throw new Ae(`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 Ae(`Output channel '${String(c)}' not in channels`);if(i&&i!=="*"){for(const c of i)if(!(c in t))throw new Ae(`Node ${String(c)} not in nodes`)}if(o&&o!=="*"){for(const c of o)if(!(c in t))throw new Ae(`Node ${String(c)} not in nodes`)}}function Ei(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 Ja extends ht{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 Ja({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}},Lf=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 mn({channels:s,triggers:i,tags:r})}static writeTo(t,e){const n=[];for(const r of t)n.push({channel:r,value:at,skipNone:!1});for(const[r,s]of Object.entries(e??{}))ee.isRunnable(s)||typeof s=="function"?n.push({channel:r,value:at,skipNone:!0,mapper:Ut(s)}):n.push({channel:r,value:s,skipNone:!1});return new se(n)}},Df=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)}},Uf=class extends Df{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(){Rf({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=Ua(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=sr(this.channels,e.checkpoint);if(e.pendingWrites?.length){const h=e.pendingWrites.filter(([d,f])=>d===we).map(([d,f,g])=>[String(f),g]);h.length>0&&ue(e.checkpoint,s,[{name:Ne,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(([g])=>g===h.name);if(!d)continue;let f=`${String(h.name)}${De}${h.id}`;if(a&&(f=`${a}${J}${f}`),n===void 0){const g={configurable:{thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}};l[h.id]=g}else{const g={configurable:{[H]:n,thread_id:e.config.configurable?.thread_id,checkpoint_ns:f}},p=d[1];l[h.id]=await p.getState(g,{subgraphs:!0})}}if(r&&e.pendingWrites?.length){const h=Object.fromEntries(i.map(f=>[f.id,f]));for(const[f,g,p]of e.pendingWrites)[oe,R,Nn].includes(g)||f in h&&h[f].writes.push([String(g),p]);const d=i.filter(f=>f.writes.length>0);d.length>0&&ue(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:ct(s,this.streamChannelsAsIs),next:u,tasks:Ba(i,e?.pendingWrites??[],l,this.streamChannelsAsIs),metadata:c,config:Qe(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 Dn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const a=Ir(r);for await(const[l,c]of this.getSubgraphsAsync(a,!0))if(l===a)return await c.getState(ft(t,{[H]:n}),{subgraphs:e?.subgraphs});throw new Error(`Subgraph with namespace "${a}" not found.`)}const s=$e(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 Dn("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t.configurable?.checkpoint_ns??"";if(r!==""&&t.configurable?.[H]===void 0){const i=Ir(r);for await(const[o,a]of this.getSubgraphsAsync(i,!0))if(o===i){yield*a.getStateHistory(ft(t,{[H]:n}),e);return}throw new Error(`Subgraph with namespace "${i}" not found.`)}const s=$e(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 Dn("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=Ir(r);for await(const[,a]of this.getSubgraphsAsync(o,!0))return await a.bulkUpdateState(ft(t,{[H]:n}),e);throw new Error(`Subgraph "${o}" not found`)}const s=async(o,a)=>{const l=this.config?$e(this.config,o):o,c=await n.getTuple(l),u=c!==void 0?rr(c.checkpoint):ya(),h={...c?.checkpoint.channel_versions},d=c?.metadata?.step??-1;let f=ft(l,{checkpoint_ns:l.configurable?.checkpoint_ns??""}),g=l.metadata??{};c?.config.configurable&&(f=ft(l,c.config.configurable),g={...c.metadata,...g});const{values:p,asNode:C}=a[0];if(p==null&&C===void 0){if(a.length>1)throw new B("Cannot create empty checkpoint with multiple updates");const b=await n.put(f,tt(u,void 0,d),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},{});return Qe(b,c?c.metadata:void 0)}const S=sr(this.channels,u);if(p===null&&C===A){if(a.length>1)throw new B("Cannot apply multiple updates when clearing state");if(c){const _=bt(u,c.pendingWrites||[],this.nodes,S,c.config,!0,{step:(c.metadata?.step??-1)+1,checkpointer:n,store:this.store}),M=(c.pendingWrites||[]).filter(E=>E[0]===we).map(E=>E.slice(1));M.length>0&&ue(u,S,[{name:Ne,writes:M,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(const[E,P,I]of c.pendingWrites||[])[oe,R,Nn].includes(P)||E in _&&_[E].writes.push([P,I]);ue(u,S,Object.values(_),n.getNextVersion.bind(n),this.triggerToNodes)}const b=await n.put(f,tt(u,S,d),{...g,source:"update",step:d+1,parents:c?.metadata?.parents??{}},Hn(h,u.channel_versions));return Qe(b,c?c.metadata:void 0)}if(C===vd){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 b=E=>!Array.isArray(E)||E.length===0?!1:E.every(P=>Array.isArray(P)&&P.length===2),_=tt(u,void 0,d),M=await n.put(c.parentConfig??ft(c.config,{checkpoint_id:void 0}),_,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(b(p)){const E=bt(_,c.pendingWrites,this.nodes,S,M,!1,{step:d+2}),P=Object.values(E).reduce((V,{name:X,id:vr})=>(V[X]??=[],V[X].push({id:vr}),V),{}),I=p.reduce((V,X)=>{const[vr,Yt]=X;V[Yt]??=[];const _l=V[Yt].length,Sl=P[Yt]?.[_l]?.id;return V[Yt].push({values:vr,asNode:Yt,taskId:Sl}),V},{});return s(Qe(M,c.metadata),Object.values(I).flat())}return Qe(M,c.metadata)}if(C===Ne){if(a.length>1)throw new B("Cannot apply multiple updates when updating as input");const b=await ze(Fa(this.inputChannels,p));if(b.length===0)throw new B(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);ue(u,S,[{name:Ne,writes:b,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const _=c?.metadata?.step!=null?c.metadata.step+1:-1,M=await n.put(f,tt(u,S,_),{source:"input",step:_,parents:c?.metadata?.parents??{}},Hn(h,u.channel_versions));return await n.putWrites(M,b,gt(Ne,u.id)),Qe(M,c?c.metadata:void 0)}if(l.configurable?.checkpoint_id===void 0&&c?.pendingWrites!==void 0&&c.pendingWrites.length>0){const b=bt(u,c.pendingWrites,this.nodes,S,c.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(c.metadata?.step??-1)+1}),_=(c.pendingWrites??[]).filter(E=>E[0]===we).map(E=>E.slice(1));_.length>0&&ue(c.checkpoint,S,[{name:Ne,writes:_,triggers:[]}],void 0,this.triggerToNodes);for(const[E,P,I]of c.pendingWrites)[oe,R,Nn].includes(P)||b[E]===void 0||b[E].writes.push([P,I]);const M=Object.values(b).filter(E=>E.writes.length>0);M.length>0&&ue(u,S,M,void 0,this.triggerToNodes)}const m=Object.values(u.versions_seen).map(b=>Object.values(b)).flat().find(b=>!!b),w=[];if(a.length===1){let{values:b,asNode:_,taskId:M}=a[0];if(_===void 0&&Object.keys(this.nodes).length===1)[_]=Object.keys(this.nodes);else if(_===void 0&&m===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(_=this.inputChannels);else if(_===void 0){const E=Object.entries(u.versions_seen).map(([P,I])=>Object.values(I).map(V=>[V,P])).flat().filter(([P,I])=>I!==R).sort(([P],[I])=>wa(P,I));E&&(E.length===1?_=E[0][1]:E[E.length-1][0]!==E[E.length-2][0]&&(_=E[E.length-1][1]))}if(_===void 0)throw new B('Ambiguous update, specify "asNode"');w.push({values:b,asNode:_,taskId:M})}else for(const{asNode:b,values:_,taskId:M}of a){if(b==null)throw new B('"asNode" is required when applying multiple updates');w.push({values:_,asNode:b,taskId:M})}const v=[];for(const{asNode:b,values:_,taskId:M}of w){if(this.nodes[b]===void 0)throw new B(`Node "${b.toString()}" does not exist`);const E=this.nodes[b].getWriters();if(!E.length)throw new B(`No writers found for node "${b.toString()}"`);v.push({name:b,input:_,proc:E.length>1?Xe.from(E,{omitSequenceTags:!0}):E[0],writes:[],triggers:[R],id:M??gt(R,u.id),writers:[]})}for(const b of v)await b.proc.invoke(b.input,rn({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[Je]:_=>b.writes.push(..._),[ot]:(_,M=!1)=>Gn(u,S,b,_,M)}}));for(const b of v){const _=b.writes.filter(M=>M[0]!==he);c!==void 0&&_.length>0&&await n.putWrites(f,_,b.id)}ue(u,S,v,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const k=Hn(h,u.channel_versions),x=await n.put(f,tt(u,S,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},k);for(const b of v){const _=b.writes.filter(M=>M[0]===he);_.length>0&&await n.putWrites(x,_,b.id)}return Qe(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:Ei(u,this.channels);let h=r;h===void 0?h=this.inputChannels:Ei(h,this.channels);const d=o??this.interruptBefore??[],f=i??this.interruptAfter??[];let g;n!==void 0?(g=Array.isArray(n)?n:[n],l=typeof n=="string"):(t.configurable?.[sn]!==void 0?g=["values"]:g=this.streamMode,l=!0);let p;if(this.checkpointer===!1)p=void 0;else if(t!==void 0&&t.configurable?.[H]!==void 0)p=t.configurable[H];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");p=this.checkpointer}const C=t.store??this.store,S=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?.[xa]??"async";return[c,g,h,u,a,d,f,p,C,l,S,w]}async stream(t,e){const n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...e,signal:lr(e?.signal,n.signal).signal},s=await super.stream(t,r);return new Ci(e?.encoding==="text/event-stream"?vf(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:nf(this.config?.callbacks,e?.callbacks),signal:lr(e?.signal,r.signal).signal};return new Ci(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=Aa(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,g,p,C,S,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 Wa({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[Te]??"";h.configurable[Te]=P.split(J).map(I=>I.split(De)[0]).join(J)}if(c.includes("messages")){const P=new Ef(V=>w.push(V)),{callbacks:I}=h;if(I===void 0)h.callbacks=[P];else if(Array.isArray(I))h.callbacks=I.concat(P);else{const V=I.copy();V.addHandler(P,!0),h.callbacks=V}}h.writer??=P=>{if(!c.includes("custom"))return;const I=Ad()?.configurable?.[Te]?.split(J).slice(0,-1);w.push([I??[],"custom",P])},h.interrupt??=this.userInterrupt??La;const k=await(await Rc(h))?.handleChainStart(this.toJSON(),tf(t,"input"),o,void 0,void 0,void 0,h?.runName??this.getName()),x=zs(this.channels);let b,_;const E=(async()=>{try{b=await kf.initialize({input:i,config:h,checkpointer:g,nodes:this.nodes,channelSpecs:x,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:p,cache:S,stream:w,interruptAfter:f,interruptBefore:d,manager:k,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:m});const P=new $f({loop:b,nodeFinished:h.configurable?.[Sd]});e?.subgraphs&&(b.config.configurable={...b.config.configurable,[ir]:b.stream}),await this._runLoop({loop:b,runner:P,debug:l,config:h}),m==="sync"&&await Promise.all(b?.checkpointerPromises??[])}catch(P){_=P}finally{try{b&&(await b.store?.stop(),await b.cache?.stop()),await Promise.all(b?.checkpointerPromises??[])}catch(P){_=_??P}_?w.error(_):w.close()}})();try{for await(const P of w){if(P===void 0)throw new Error("Data structure error.");const[I,V,X]=P;if(c.includes(V)){if(n==="text/event-stream"){r?yield[I,V,X]:yield[null,V,X];continue}r&&!C?yield[I,V,X]:C?r?yield[I,X]:yield X:yield[V,X]}}}catch(P){throw await k?.handleChainError(_),P}finally{await E}await k?.handleChainEnd(b?.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"?Ma(l)?o.push(l[R]):a=l:s.push(l);if(n==="values"){if(o.length>0){const l=o.flat(1);if(a==null)return{[R]:l};if(typeof a=="object")return{...a,[R]: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&&gf(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&za(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,a)=>{r&&yf(o,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new md([`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([])}},Wt=class qa extends ht{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new qa(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}},Ya=class{path;ends;constructor(t){ee.isRunnable(t.path)?this.path=t.path:this.path=Ut(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 dt({name:"<branch_run>",trace:!1,func:async(n,r)=>{try{return await this._route(n,r,t,e)}catch(s){throw s.name===_a.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===A))throw new B("Cannot send a packet to the END node");return await n(i,e)??t}},Ff=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,De])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===A)throw new Error(`Node \`${r}\` is reserved.`);const o=Ut(s);this.nodes[r]={runnable:o,metadata:i?.metadata,subgraphs:Js(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===A)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=Ut(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 Ya(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,A)}compile({checkpointer:t,interruptBefore:e,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(n)?n:[]]);const s=new Xa({builder:this,checkpointer:t,interruptAfter:n,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[L]:new Wt,[A]:new Wt},inputChannels:L,outputChannels:A,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(A);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 yd([`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!==A&&!(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}},Xa=class extends Uf{builder;constructor({builder:t,...e}){super(e),this.builder=t}attachNode(t,e){this.channels[t]=new Wt,this.nodes[t]=new mn({channels:[],triggers:[],metadata:e.metadata,subgraphs:e.subgraphs,ends:e.ends}).pipe(e.runnable).pipe(new se([{channel:t,value:at}],[G])),this.streamChannels.push(t)}attachEdge(t,e){if(e===A){if(t===L)throw new Error("Cannot have an edge from START to END");this.nodes[t].writers.push(new se([{channel:A,value:at}],[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]=Lf.subscribeTo(L,{tags:[G]})),this.nodes[t].pipe(n.run(s=>{const i=s.map(o=>pe(o)?o:{channel:o===A?A:`branch:${t}:${e}:${o}`,value:at});return new se(i,[G])}));const r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(const s of r)if(s!==A){const i=`branch:${t}:${e}:${s}`;this.channels[i]=new Wt,this.nodes[s].triggers.push(i),this.nodes[s].channels.push(i)}}async getGraphAsync(t){const e=t?.xray,n=new si,r={[L]:n.addNode({schema:_e()},L)},s={};let i={};e&&(i=Object.fromEntries((await ze(this.getSubgraphsAsync())).filter(l=>xi(l[1]))));function o(l,c,u,h=!1){if(c===A&&s[A]===void 0&&(s[A]=n.addNode({schema:_e()},A)),r[l]!==void 0){if(s[c]===void 0)throw new Error(`End node ${c} not found!`);return n.addEdge(r[l],s[c],u!==c?u:void 0,h)}}for(const[l,c]of Object.entries(this.builder.nodes)){const u=te(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,g=i[l]!==void 0?await i[l].getGraphAsync({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let S=function(w){return w?w.lc_runnable:!1},m=function(w,v){if(w!==void 0&&!ii(w))return w;if(S(v))try{let k=v.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return v.getName()}else return v.name??"UnknownSchema"};const[p,C]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:m(C.id,C.data),...C}),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)])),[A]:A};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))o(te(l),te(g),f,!0)}}for(const[l,c]of Object.entries(this.builder.nodes))if(c.ends!==void 0)for(const u of c.ends)o(te(l),te(u),void 0,!0);return n}getGraph(t){const e=t?.xray,n=new si,r={[L]:n.addNode({schema:_e()},L)},s={};let i={};e&&(i=Object.fromEntries(en(this.getSubgraphs()).filter(l=>xi(l[1]))));function o(l,c,u,h=!1){return c===A&&s[A]===void 0&&(s[A]=n.addNode({schema:_e()},A)),n.addEdge(r[l],s[c],u!==c?u:void 0,h)}for(const[l,c]of Object.entries(this.builder.nodes)){const u=te(l),h=c.runnable,d=c.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?d.__interrupt="before,after":this.interruptBefore?.includes(l)?d.__interrupt="before":this.interruptAfter?.includes(l)&&(d.__interrupt="after"),e){const f=typeof e=="number"?e-1:e,g=i[l]!==void 0?i[l].getGraph({...t,xray:f}):h.getGraph(t);if(g.trimFirstNode(),g.trimLastNode(),Object.keys(g.nodes).length>1){let S=function(w){return w?w.lc_runnable:!1},m=function(w,v){if(w!==void 0&&!ii(w))return w;if(S(v))try{let k=v.getName();return k=k.startsWith("Runnable")?k.slice(8):k,k}catch{return v.getName()}else return v.name??"UnknownSchema"};const[p,C]=n.extend(g,u);if(p===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);C!==void 0&&(r[u]={name:m(C.id,C.data),...C}),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)])),[A]:A};for(const h of Object.values(c)){let d;h.ends!==void 0?d=h.ends:d=u;for(const[f,g]of Object.entries(d))o(te(l),te(g),f,!0)}}return n}};function xi(t){return typeof t.attachNode=="function"&&typeof t.attachEdge=="function"}function te(t){return t==="subgraph"?`"${t}"`:t}const it=(t,e)=>t.size===e.size&&[...t].every(n=>e.has(n));var Vf=class Za extends ht{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new Za(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(!it(this.names,this.seen))throw new Q}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&it(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&it(this.names,this.seen)}},Bf=class Qa extends ht{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 Qa(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||!it(this.names,this.seen))throw new Q}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&it(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&it(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&it(this.names,this.seen)}};const zf="lg:";var Wf=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=oi(t);for(const[r,s]of Object.entries(n)){const i=this.get(s);i?.reducer?e[r]=new ls(i.reducer.fn,i.default):e[r]=new Ws}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(oi(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=Kr(c)??Kr(a),h=JSON.stringify({...l.jsonSchemaExtra,description:u});c=c.describe(`${zf}${h}`)}return[o,c]});s=jc(t,Object.fromEntries(i)),Lc(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=Ts(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const Ht=new Wf;function Gt(t,e){if(e.reducer&&!e.default){const n=ks(t);n!=null&&(e.default=n)}if(e.reducer){const n=Object.assign(t,{lg_reducer_schema:e.reducer?.schema??t});return Ht.extend(n,()=>e),n}else return Ht.extend(t,()=>e),t}const Re="__root__",ws=Symbol.for("langgraph.state.partial");var Hf=class extends Ff{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Ht;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Zf(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??ws,this._outputDefinition=i,this._outputRuntimeDefinition=t.output??t.state}else if(de(t)){const r=this._metaRegistry.getChannelsForSchema(t);this._schemaDefinition=r,this._schemaRuntimeDefinition=t,this._inputDefinition=r,this._inputRuntimeDefinition=ws,this._outputDefinition=r,this._outputRuntimeDefinition=t}else if(Xf(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Yf(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Jf(t)||Mi(t)){const r=Mi(t)?t.spec:t;this._schemaDefinition=r}else if(qf(t)){const r=Gf(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)&&!de(r)}n(e)?(de(e.context)&&(this._configRuntimeSchema=e.context),this._interrupt=e.interrupt,this._writer=e.writer):de(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,De])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===A||r===L)throw new Error(`Node \`${r}\` is reserved.`);let o=this._schemaDefinition;i?.input!==void 0&&(de(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 dt({func:s,name:r,trace:!1}):a=Ut(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:Js(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===A)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===A)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]===Re?Re:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===Re?Re:c,h=this._interrupt,d=new Kf({builder:this,checkpointer:t,interruptAfter:s,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[L]:new Wt},inputChannels:L,outputChannels:l,streamChannels:u,streamMode:"updates",store:e,cache:n,name:i,description:o,userInterrupt:h});d.attachNode(L);for(const[f,g]of Object.entries(this.nodes))d.attachNode(f,g);d.attachBranch(L,yi,Ai(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,yi,Ai(),{withReader:!1});for(const[f,g]of this.edges)d.attachEdge(f,g);for(const[f,g]of this.waitingEdges)d.attachEdge(f,g);for(const[f,g]of Object.entries(this.branches))for(const[p,C]of Object.entries(g))d.attachBranch(f,p,C);return d.validate()}};function Gf(t){const e={};for(const[n,r]of Object.entries(t))e[n]=us(r);return e}var Kf=class extends Xa{description;_metaRegistry=Ht;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([Re,c]);return l}else if(a!=null)return[[Re,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:at,mapper:new dt({func:n.length&&n[0]===Re?r:i,trace:!1,recurse:!1})}];if(t===L)this.nodes[t]=new mn({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&&Re in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new wd:new Wt(!1),this.nodes[t]=new mn({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!==A){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 Bf(new Set(t)):new Vf(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!==A);if(!a.length)return;const l=a.map(c=>pe(c)?c:{channel:c===A?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=>Xd.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(de(n))return s(n);if(n===ws)return Ts(s(r))})();if(Y(t)){const n=t;return t.update&&e!=null&&(n.update=Ge(e,t.update)),n}return e!=null?Ge(e,t):t}isInterrupted(t){return Ma(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return de(e)&&Ge(e,t),t}};function Jf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Ca(e))}function Mi(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function qf(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Yf(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function Xf(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Zf(t){return!(typeof t!="object"||t==null||!("state"in t)||!de(t.state)||"input"in t&&!de(t.input)||"output"in t&&!de(t.output))}function Qf(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 Sa(r);pe(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Ai(){const t=new dt({func:Qf,tags:[G],trace:!1,recurse:!1,name:"<control_branch>"});return new Ya({path:t})}const el="__remove_all__";function tl(t,e){const n=Array.isArray(t)?t:[t],r=Array.isArray(e)?e:[e],s=n.map(cn),i=r.map(cn);for(const u of s)(u.id===null||u.id===void 0)&&(u.id=Jn(),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=Jn(),h.lc_kwargs.id=h.id),h.getType()==="remove"&&h.id===el&&(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))}cs.Root({messages:cs({reducer:tl,default:()=>[]})});const cr={reducer:{fn:tl},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:Gt(ae(),cr)});pd();const bs=Symbol.for("langgraph-zod");bs in globalThis||(globalThis[bs]=new WeakSet);function Pi(t){const e=globalThis[bs];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){const n=this;return{metadata(r){return Gt(n,{jsonSchemaExtra:r})},reducer(r,s){const i=ks(n);return Gt(n,{default:i,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Pi(Dc.prototype),Pi(Tl.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 ep=class extends El{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){const n=e[0];if(n&&!n?.default){const r=ks(t);r!=null&&(n.default=r)}return super.add(t,...e)}};new ep(Ht);function tp(t=!0,e,n=[]){const r={messages:Gt(ae(),cr),jumpTo:Me([vt("model_request"),vt("tools"),vt("end"),Uc()]).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=Es().optional());const i=z(r);return Ht.getChannelsForSchema(i)}z({llmInputMessages:Gt(ae(),{reducer:{fn:(t,e)=>cr.reducer.fn([],e)},default:()=>[]}),messages:Gt(ae(),cr)});const Oi="prompt",Vr=/<name>(.*?)<\/name>/s,Br=/<content>(.*?)<\/content>/s;function np(t){if(!O.isInstance(t)||Lt.isInstance(t)||!t.name)return t;const{name:e}=t;if(typeof t.content=="string")return new O({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});const n=[];let r=0;for(const s of t.content)typeof s=="string"?(r+=1,n.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,n.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):n.push(s);return r||n.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new O({...t.lc_kwargs,content:n,name:void 0})}function rp(t){if(!O.isInstance(t)||!t.content)return t;let e=[],n;if(Array.isArray(t.content))e=t.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(Vr),i=r.text.match(Br);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(Vr),i=r.text.match(Br);return!s||!i?r:(n=s[1],{...r,text:i[1]})}return r});else{const r=t.content,s=r.match(Vr),i=r.match(Br);if(!s||!i)return t;n=s[1],e=i[1]}return new O({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:n})}function W(t){return ee.isRunnable(t)}function Ni(t){return Ms(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const zr=(t,e,n={})=>{if(Ni(t))return t.bindTools(e,n);if(Ee.isRunnableBinding(t)&&Ni(t.bound)){const r=t.bound.bindTools(e,n);return Ee.isRunnableBinding(r)?new Ee({bound:r.bound,config:{...t.config,...r.config},kwargs:{...t.kwargs,...r.kwargs},configFactories:r.configFactories??t.configFactories}):new Ee({bound:r,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function nl(t){if(typeof t=="function")return;let e=t;if(Xe.isRunnableSequence(e)&&(e=e.steps.find(n=>Ee.isRunnableBinding(n))||e),!Zn(e)){if(Ee.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 qr}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new qr}}function vs(t){return!!(O.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function sp(t){let e;if(t==null)e=Dt.from(n=>n.messages).withConfig({runName:Oi});else if(typeof t=="string"){const n=new be(t);e=Dt.from(r=>[n,...r.messages??[]]).withConfig({runName:Oi})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function ip(t,e,n={}){const r=zr(t,e,n);if(r)return r;if(Zn(t)){const s=zr(await t._model(),e,n);if(s)return s}if(Xe.isRunnableSequence(t)){const s=t.steps.findIndex(i=>Ee.isRunnableBinding(i)||Ms(i)||Zn(i));if(s>=0){const i=zr(t.steps[s],e,n);if(i){const o=t.steps.slice();return o.splice(s,1,i),Xe.from(o)}}}throw new Error(`llm ${t} must define bindTools method.`)}function op(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 ap(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return op(e.map(n=>{const r=n.wrapToolCall;return async(i,o)=>{try{const a=await r({...i,state:{messages:i.state.messages,...n.stateSchema?Ge(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 lp(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=Fc(r.stateSchema,a=>a.startsWith("_")),i=await Vc(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
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:
|
|
48
48
|
1. Provide default values in your middleware's state schema using .default():
|
|
@@ -58,10 +58,10 @@ To fix this, either:
|
|
|
58
58
|
3. Or ensure you pass these values when invoking the agent:
|
|
59
59
|
agent.invoke({
|
|
60
60
|
messages: [...],
|
|
61
|
-
${
|
|
62
|
-
})`)}return n}function cp(t){const e={messages:ae(()=>[]),structuredResponse:
|
|
63
|
-
Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var mp=class extends
|
|
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:rl(this.signal,e.signal)});return F.isInstance(h)||Y(h)?h:new F({name:u.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:c.id})}catch(h){throw h instanceof Bc?new Ms(h,c):h}},s=e,o={context:s?.context,writer:s?.writer,interrupt:s?.interrupt,signal:s?.signal},i=this.tools.find(l=>l.name===t.name);if(!i)throw new Error(`Tool "${t.name}" not found.`);const a={toolCall:t,tool:i,state:n,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(a,r)}catch(l){return this.#e(l,t,!0)}try{return await r(a)}catch(l){return this.#e(l,t,!1)}}async run(t,e){let n;if(fp(t)){const{lg_tool_call:o,jumpTo:i,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let o;if(sl(t))o=t;else if(dp(t))o=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");const i=new Set(o.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id));let a;for(let l=o.length-1;l>=0;l-=1){const c=o[l];if(O.isInstance(c)){a=c;break}}if(!O.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!i.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!n.some(Y))return Array.isArray(t)?n:{messages:n};const r=[];let s=null;for(const o of n)Y(o)?o.graph===K.PARENT&&Array.isArray(o.goto)&&o.goto.every(i=>gp(i))?s?s.goto.push(...o.goto):s=new K({graph:K.PARENT,goto:o.goto}):r.push(o):r.push(Array.isArray(t)?[o]:{messages:[o]});return s&&r.push(s),r}};function gp(t){return t instanceof re}var yp=class{},wp=class{},vr=class extends Zs{#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},o=await this.runHook(r,Object.freeze(Object.assign(new wp,{...s,context:Object.freeze(Object.assign(new yp,n))})));if(!o)return{...r,jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=He(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=He(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=He(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=He(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof o.jumpTo=="string"&&!i?.includes(o.jumpTo)){const l=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${o.jumpTo}, ${l}.`)}if(typeof o=="object"&&"type"in o){if(o.type==="terminate"){if(o.error)throw o.error;return{...r,...o.result||{},jumpTo:o.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(o)}`)}return{...r,...o,jumpTo:o.jumpTo}}get nodeOptions(){return{input:cp(this.middleware.stateSchema)}}},bp=class extends vr{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 yr(this.middleware.beforeAgent)(t,e)}},vp=class extends vr{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 yr(this.middleware.beforeModel)(t,e)}},_p=class extends vr{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 yr(this.middleware.afterModel)(t,e)}},Sp=class extends vr{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 yr(this.middleware.afterAgent)(t,e)}},Cp=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}},kp=class{#e;#n="v2";#s;#t=new Cp;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"&&nl(t.model);const e=this.options.middleware?.filter(m=>m.tools).flatMap(m=>m.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(W).filter(m=>"returnDirect"in m&&m.returnDirect).map(m=>m.name)),s=tp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),i=new Hf(s,this.options.contextSchema),a=[],l=[],c=[],u=[],h=[];this.#s=new hp({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,v,k,x;const b=f[m];if(d.has(b.name))throw new Error(`Middleware ${b.name} is defined multiple times`);if(d.add(b.name),b.beforeAgent){w=new bp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,w);const _=`${b.name}.before_agent`;a.push({index:m,name:_,allowed:He(b.beforeAgent)}),i.addNode(_,w,w.nodeOptions)}if(b.beforeModel){v=new vp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,v);const _=`${b.name}.before_model`;l.push({index:m,name:_,allowed:He(b.beforeModel)}),i.addNode(_,v,v.nodeOptions)}if(b.afterModel){k=new _p(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,k);const _=`${b.name}.after_model`;c.push({index:m,name:_,allowed:He(b.afterModel)}),i.addNode(_,k,k.nodeOptions)}if(b.afterAgent){x=new Sp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,x);const _=`${b.name}.after_agent`;u.push({index:m,name:_,allowed:He(b.afterAgent)}),i.addNode(_,x,x.nodeOptions)}b.wrapModelCall&&h.push([b,()=>this.#t.getState(b.name)])}if(i.addNode("model_request",this.#s),n.filter(W).length>0){const m=new mp(n.filter(W),{signal:this.options.signal,wrapToolCall:ap(f)});i.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",C=u.length>0?u[u.length-1].name:A;i.addEdge(L,y);for(let m=0;m<a.length;m++){const w=a[m],v=w.name,x=m===a.length-1?p:a[m+1].name;if(w.allowed&&w.allowed.length>0){const b=n.filter(W).length>0,_=w.allowed.map(E=>Oe(E)).filter(E=>E!=="tools"||b),M=Array.from(new Set([x,..._.map(E=>E===A?C:E)]));i.addConditionalEdges(v,this.#c(n.filter(W),x,C),M)}else i.addEdge(v,x)}for(let m=0;m<l.length;m++){const w=l[m],v=w.name,x=m===l.length-1?"model_request":l[m+1].name;if(w.allowed&&w.allowed.length>0){const b=n.filter(W).length>0,_=w.allowed.map(E=>Oe(E)).filter(E=>E!=="tools"||b),M=Array.from(new Set([x,..._]));i.addConditionalEdges(v,this.#u(n.filter(W),x),M)}else i.addEdge(v,x)}const S=c.at(-1);if(c.length>0&&S)i.addEdge("model_request",S.name);else{const w=this.#o(n.filter(W)).map(v=>v===A?C:v);w.length===1?i.addEdge("model_request",w[0]):i.addConditionalEdges("model_request",this.#l(C),w)}for(let m=c.length-1;m>0;m--){const w=c[m],v=w.name,k=c[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(W).length>0,b=w.allowed.map(M=>Oe(M)).filter(M=>M!=="tools"||x),_=Array.from(new Set([k,...b]));i.addConditionalEdges(v,this.#r(n.filter(W),w.allowed,k),_)}else i.addEdge(v,k)}if(c.length>0){const m=c[0],w=m.name,v=this.#o(n.filter(W),!0).filter(b=>b!=="tools"||n.filter(W).length>0),k=!!(m.allowed&&m.allowed.length>0),x=v.map(b=>b===A?C:b);i.addConditionalEdges(w,this.#i(n.filter(W),k,C),x)}for(let m=u.length-1;m>0;m--){const w=u[m],v=w.name,k=u[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(W).length>0,b=w.allowed.map(M=>Oe(M)).filter(M=>M!=="tools"||x),_=Array.from(new Set([k,...b]));i.addConditionalEdges(v,this.#r(n.filter(W),w.allowed,k),_)}else i.addEdge(v,k)}if(u.length>0){const m=u[0],w=m.name;if(m.allowed&&m.allowed.length>0){const v=n.filter(W).length>0,k=m.allowed.map(b=>Oe(b)).filter(b=>b!=="tools"||v),x=Array.from(new Set([A,...k]));i.addConditionalEdges(w,this.#r(n.filter(W),m.allowed,A),x)}else i.addEdge(w,A)}if(n.filter(W).length>0){const m=p;r.size>0?i.addConditionalEdges("tools",this.#a(r,C),[m,C]):i.addEdge("tools",m)}this.#e=i.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#o(t,e=!1){const n=[];return t.length>0&&n.push("tools"),e&&n.push("model_request"),n.push(A),n}#a(t,e){return n=>{const r=n.messages,s=r[r.length-1];return F.isInstance(s)&&s.name&&t.has(s.name)?this.options.responseFormat?"model_request":e:"model_request"}}#l(t=A){return e=>{const r=e.messages.at(-1);if(!O.isInstance(r)||!r.tool_calls||r.tool_calls.length===0||r.tool_calls.every(i=>i.name.startsWith("extract-")))return t;if(this.#n==="v1")return"tools";const o=r.tool_calls.filter(i=>!i.name.startsWith("extract-"));return o.length===0?t:o.map(i=>new re("tools",{...e,lg_tool_call:i}))}}#i(t,e,n){const r=!!this.options.responseFormat;return s=>{const o=s.messages,i=o.at(-1);if(O.isInstance(i)&&(!i.tool_calls||i.tool_calls.length===0))return n;if(e&&s.jumpTo)return s.jumpTo===A?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=o.filter(F.isInstance),l=o.filter(O.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(!O.isInstance(i)||!i.tool_calls||i.tool_calls.length===0)return n;const h=i.tool_calls.every(f=>f.name.startsWith("extract-")),d=i.tool_calls.some(f=>!f.name.startsWith("extract-"));return h||!d?n:"tools"}}#r(t,e,n){const r=new Set(e.map(s=>Oe(s)));return s=>{if(s.jumpTo){const o=Oe(s.jumpTo);if(o===A&&r.has(A))return A;if(o==="tools"&&r.has("tools"))return t.length===0?A:new re("tools",{...s,jumpTo:void 0});if(o==="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=Oe(r.jumpTo);return s===A?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=Oe(n.jumpTo);return r===A?A:r==="tools"?t.length===0?A: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 lp(this.options.middleware,t),s={...(await this.#e.getState(e).catch(()=>({values:{}}))).values,...t};if(!s)return s;for(const[o,i]of Object.entries(n))o in s||(s[o]=i);return s}async invoke(t,e){const n=await this.#h(t,e);return this.#e.invoke(n,e)}async stream(t,e){const n=await this.#h(t,e);return this.#e.stream(n,e)}async drawMermaidPng(t){const r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,e,n){return this.#e.streamEvents(t,{...e,version:e?.version??"v2"},n)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,e){return this.#e.getState(t,e)}getStateHistory(t,e){return this.#e.getStateHistory(t,e)}getSubgraphs(t,e){return this.#e.getSubgraphs(t,e)}getSubgraphAsync(t,e){return this.#e.getSubgraphsAsync(t,e)}updateState(t,e,n){return this.#e.updateState(t,e,n)}};function ol(t){return new kp(t)}const Jn=`<role>
|
|
61
|
+
${i.error.issues[0]?.path.join(".")}: "value"
|
|
62
|
+
})`)}return n}function cp(t){const e={messages:ae(()=>[]),structuredResponse:Es().optional()};if(!t)return z(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 z(r)}function Pe(t){if(t){if(["model_request","tools",A].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return A;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function rl(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var Xs=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),r=await je.runWithConfig(n,async()=>this.func(t,n));return ee.isRunnable(r)&&this.recurse?await je.runWithConfig(n,async()=>r.invoke(t,n)):(this.#e=r,r)}};function up(t,e){let n,r;if(e==="inline")n=np,r=rp;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(i){return i.map(n)}return Xe.from([Dt.from(s),t,Dt.from(r)])}var hp=class extends Xs{#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=oo(this.#e.responseFormat,void 0,t);return e.every(r=>r instanceof rt)?{type:"native",strategy:e[0]}:{type:"tool",tools:e.filter(r=>r instanceof Ve).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 O({content:"Sorry, need more steps to process this request.",name:this.name,id:r.id})]}:{messages:[r]})}#t(){if(typeof this.#e.model=="string")return Jt(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=>{nl(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=rl(this.#e.signal,e.signal),g={...e,signal:f},p=await h.invoke(d,g);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 C=p.tool_calls.filter(w=>w.name in u.tools);if(C.length===0)return p;if(C.length>1)return this.#a(p,C,u);const m=u.tools[C[0].name]?.options?.toolMessageContent;return this.#l(p,C[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,g=h;a=async p=>{const C=f.contextSchema?Ge(f.contextSchema,s?.context||{}):s?.context,S=Object.freeze({context:C,writer:s.writer,interrupt:s.interrupt,signal:s.signal}),m={...p,state:{...u.stateSchema?Ge(Ts(u.stateSchema),t):{},...g(),messages:t.messages},runtime:S},w=async v=>{const k=v.tools??[],x=k.filter(_=>W(_)&&!this.#e.toolClasses.some(M=>M.name===_.name));if(x.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${x.map(_=>_.name).join(", ")}. This is not supported.`);const b=k.filter(_=>W(_)&&this.#e.toolClasses.every(M=>M!==_));if(b.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${b.map(_=>_.name).join(", ")}. This is not supported.`);return d(v)};if(!f.wrapModelCall)return w(m);try{const v=await f.wrapModelCall(m,w);if(!O.isInstance(v))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof v}`);return v}catch(v){throw v instanceof Error&&!v.message.includes(`middleware "${f.name}"`)&&(v.message=`Error in middleware "${f.name}": ${v.message}`),v}}}}const l={model:r,systemPrompt:this.#e.systemPrompt,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:s?.context,writer:s.writer,interrupt:s.interrupt,signal:s.signal})};return a(l)}#a(t,e,n){const r=new Yr(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 O(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 Yr))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=O.isInstance(e)&&e.tool_calls?.every(s=>this.#e.shouldReturnDirect.has(s.name)),r="remainingSteps"in t?t.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&vs(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:Kr(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 ip(t,i,{...r,...e?.modelSettings??{},tool_choice:o});return sp(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?up(a,this.#e.includeAgentName):a)}getState(){const t=super.getState(),e=t&&!(t instanceof K)?t:{};return{messages:[],...e}}};const sl=t=>Array.isArray(t)&&t.every(nn.isInstance),dp=t=>typeof t=="object"&&t!=null&&"messages"in t&&sl(t.messages),fp=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function pp(t,e){return t instanceof xs?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 mp=class extends Xs{tools;trace=!1;signal;handleToolErrors=pp;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(st(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:rl(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 Bc?new xs(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(fp(t)){const{lg_tool_call:i,jumpTo:o,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let i;if(sl(t))i=t;else if(dp(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(O.isInstance(c)){a=c;break}}if(!O.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!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=>gp(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 gp(t){return t instanceof re}var yp=class{},wp=class{},wr=class extends Xs{#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=Ge(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 wp,{...s,context:Object.freeze(Object.assign(new yp,n))})));if(!i)return{...r,jumpTo:void 0};let o,a;if(this.name?.startsWith("BeforeAgentNode_")?(o=We(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(o=We(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(o=We(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(o=We(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:cp(this.middleware.stateSchema)}}},bp=class extends wr{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return mr(this.middleware.beforeAgent)(t,e)}},vp=class extends wr{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return mr(this.middleware.beforeModel)(t,e)}},_p=class extends wr{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return mr(this.middleware.afterModel)(t,e)}},Sp=class extends wr{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(n,r)=>this.invokeMiddleware(n,r)},e),this.middleware=t}runHook(t,e){return mr(this.middleware.afterAgent)(t,e)}},Cp=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}},kp=class{#e;#n="v2";#s;#t=new Cp;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"&&nl(t.model);const e=this.options.middleware?.filter(m=>m.tools).flatMap(m=>m.tools)??[],n=[...t.tools??[],...e],r=new Set(n.filter(W).filter(m=>"returnDirect"in m&&m.returnDirect).map(m=>m.name)),s=tp(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),o=new Hf(s,this.options.contextSchema),a=[],l=[],c=[],u=[],h=[];this.#s=new hp({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,v,k,x;const b=f[m];if(d.has(b.name))throw new Error(`Middleware ${b.name} is defined multiple times`);if(d.add(b.name),b.beforeAgent){w=new bp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,w);const _=`${b.name}.before_agent`;a.push({index:m,name:_,allowed:We(b.beforeAgent)}),o.addNode(_,w,w.nodeOptions)}if(b.beforeModel){v=new vp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,v);const _=`${b.name}.before_model`;l.push({index:m,name:_,allowed:We(b.beforeModel)}),o.addNode(_,v,v.nodeOptions)}if(b.afterModel){k=new _p(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,k);const _=`${b.name}.after_model`;c.push({index:m,name:_,allowed:We(b.afterModel)}),o.addNode(_,k,k.nodeOptions)}if(b.afterAgent){x=new Sp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,x);const _=`${b.name}.after_agent`;u.push({index:m,name:_,allowed:We(b.afterAgent)}),o.addNode(_,x,x.nodeOptions)}b.wrapModelCall&&h.push([b,()=>this.#t.getState(b.name)])}if(o.addNode("model_request",this.#s),n.filter(W).length>0){const m=new mp(n.filter(W),{signal:this.options.signal,wrapToolCall:ap(f)});o.addNode("tools",m)}let g;a.length>0?g=a[0].name:l.length>0?g=l[0].name:g="model_request";const p=l.length>0?l[0].name:"model_request",C=u.length>0?u[u.length-1].name:A;o.addEdge(L,g);for(let m=0;m<a.length;m++){const w=a[m],v=w.name,x=m===a.length-1?p:a[m+1].name;if(w.allowed&&w.allowed.length>0){const b=n.filter(W).length>0,_=w.allowed.map(E=>Pe(E)).filter(E=>E!=="tools"||b),M=Array.from(new Set([x,..._.map(E=>E===A?C:E)]));o.addConditionalEdges(v,this.#c(n.filter(W),x,C),M)}else o.addEdge(v,x)}for(let m=0;m<l.length;m++){const w=l[m],v=w.name,x=m===l.length-1?"model_request":l[m+1].name;if(w.allowed&&w.allowed.length>0){const b=n.filter(W).length>0,_=w.allowed.map(E=>Pe(E)).filter(E=>E!=="tools"||b),M=Array.from(new Set([x,..._]));o.addConditionalEdges(v,this.#u(n.filter(W),x),M)}else o.addEdge(v,x)}const S=c.at(-1);if(c.length>0&&S)o.addEdge("model_request",S.name);else{const w=this.#i(n.filter(W)).map(v=>v===A?C:v);w.length===1?o.addEdge("model_request",w[0]):o.addConditionalEdges("model_request",this.#l(C),w)}for(let m=c.length-1;m>0;m--){const w=c[m],v=w.name,k=c[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(W).length>0,b=w.allowed.map(M=>Pe(M)).filter(M=>M!=="tools"||x),_=Array.from(new Set([k,...b]));o.addConditionalEdges(v,this.#r(n.filter(W),w.allowed,k),_)}else o.addEdge(v,k)}if(c.length>0){const m=c[0],w=m.name,v=this.#i(n.filter(W),!0).filter(b=>b!=="tools"||n.filter(W).length>0),k=!!(m.allowed&&m.allowed.length>0),x=v.map(b=>b===A?C:b);o.addConditionalEdges(w,this.#o(n.filter(W),k,C),x)}for(let m=u.length-1;m>0;m--){const w=u[m],v=w.name,k=u[m-1].name;if(w.allowed&&w.allowed.length>0){const x=n.filter(W).length>0,b=w.allowed.map(M=>Pe(M)).filter(M=>M!=="tools"||x),_=Array.from(new Set([k,...b]));o.addConditionalEdges(v,this.#r(n.filter(W),w.allowed,k),_)}else o.addEdge(v,k)}if(u.length>0){const m=u[0],w=m.name;if(m.allowed&&m.allowed.length>0){const v=n.filter(W).length>0,k=m.allowed.map(b=>Pe(b)).filter(b=>b!=="tools"||v),x=Array.from(new Set([A,...k]));o.addConditionalEdges(w,this.#r(n.filter(W),m.allowed,A),x)}else o.addEdge(w,A)}if(n.filter(W).length>0){const m=p;r.size>0?o.addConditionalEdges("tools",this.#a(r,C),[m,C]):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(A),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=A){return e=>{const r=e.messages.at(-1);if(!O.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(O.isInstance(o)&&(!o.tool_calls||o.tool_calls.length===0))return n;if(e&&s.jumpTo)return s.jumpTo===A?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(O.isInstance).at(-1),c=l?.tool_calls?.filter(f=>!a.some(g=>g.tool_call_id===f.id));if(c&&c.length>0)return c.map(f=>new 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(!O.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=>Pe(s)));return s=>{if(s.jumpTo){const i=Pe(s.jumpTo);if(i===A&&r.has(A))return A;if(i==="tools"&&r.has("tools"))return t.length===0?A: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=Pe(r.jumpTo);return s===A?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=Pe(n.jumpTo);return r===A?A:r==="tools"?t.length===0?A: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 lp(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 il(t){return new kp(t)}const Kn=`<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>`,
|
|
90
|
+
</messages>`,ur=20,Tp=4e3,Ii=5,Ep=qn().args(Ue(ae())).returns(Me([F(),Xi(F())])),hr=z({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"}),ol=z({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"}),$i=z({model:ae(),trigger:Me([hr,Ue(hr)]).optional(),keep:ol.optional(),tokenCounter:Ep.optional(),summaryPrompt:ne().default(Kn),trimTokensToSummarize:F().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:F().optional(),messagesToKeep:F().optional()});function Zs(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 rc(n)}catch{}}function xp(t){const{data:e,error:n}=zc($i,t);if(n)throw new Error(`Invalid summarization middleware options: ${zi(n)}`);return me({name:"SummarizationMiddleware",contextSchema:$i.extend({model:ae().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===ur)&&(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:ur},c=ol.parse(l);let u=[];a===void 0?u=[]:Array.isArray(a)?u=a.map(M=>hr.parse(M)):u=[hr.parse(a)];const h=u.some(M=>"fraction"in M)||"fraction"in c,d=typeof e.model=="string"?await Jt(e.model):e.model;if(h&&!Zs(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");const f=s.context.summaryPrompt===Kn?e.summaryPrompt??Kn:s.context.summaryPrompt??e.summaryPrompt??Kn,g=s.context.trimTokensToSummarize!==void 0?s.context.trimTokensToSummarize:e.trimTokensToSummarize??Tp;Mp(r.messages);const p=s.context.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??As,C=await p(r.messages);if(!await Op(r.messages,C,u,d))return;const{systemPrompt:m,conversationMessages:w}=Ap(r.messages),v=await Np(w,c,p,d);if(v<=0)return;const{messagesToSummarize:k,preservedMessages:x}=Pp(m,w,v),b=await jp(k,d,f,p,g),_=new fe({content:`Here is a summary of the conversation to date:
|
|
91
91
|
|
|
92
|
-
${b}`,id:
|
|
92
|
+
${b}`,id:Jn()});return{messages:[new An({id:el}),_,...x]}}})}function Mp(t){for(const e of t)e.id||(e.id=Jn())}function Ap(t){return t.length>0&&be.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Pp(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function Op(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=Zs(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 Np(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await Ip(t,e,n,r);return typeof s=="number"?s:Ri(t,ur)}return Ri(t,e.messages??ur)}async function Ip(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const u=Zs(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(al(t,u))return u;return 0}function Ri(t,e){if(t.length<=e)return 0;const n=t.length-e;for(let r=n;r>=0;r--)if(al(t,r))return r;return 0}function al(t,e){if(e>=t.length)return!0;if(e<t.length&&O.isInstance(t[e])&&vs(t[e]))return!1;const n=Math.max(0,e-Ii),r=Math.min(t.length,e+Ii);for(let s=n;s<r;s++){if(!vs(t[s]))continue;const i=$p(t[s]);if(Rp(t,s,e,i))return!1}return!0}function $p(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 Rp(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 jp(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const i=await Lp(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 Lp(t,e,n){if(n===void 0)return t;try{return await Zi(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const Dp=qn().args(ae(),ae(),ae()).returns(Me([ne(),Xi(ne())])),ll=["approve","edit","reject"],Up=Ft(ll),Fp=z({allowedDecisions:Ue(Up),description:Me([ne(),Dp]).optional(),argsSchema:un(Es()).optional()}),ji=z({interruptOn:un(Me([Yn(),Fp])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function Vp(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:s.allowedDecisions};return s.argsSchema&&(d.argsSchema=s.argsSchema),{actionRequest:h,reviewConfig:d}},n=(r,s,
|
|
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)fe.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await
|
|
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=Ge(ji,{...t,...s.context||{}});if(!i)return;const{messages:o}=r;if(!o.length)return;const a=[...o].reverse().find(v=>O.isInstance(v));if(!a||!a.tool_calls?.length||!i.interruptOn)return;const l={};for(const[v,k]of Object.entries(i.interruptOn))typeof k=="boolean"?k===!0&&(l[v]={allowedDecisions:[...ll]}):k.allowedDecisions&&(l[v]=k);const c=[],u=[];for(const v of a.tool_calls)v.name in l?c.push(v):u.push(v);if(!c.length)return;const h=[],d=[];for(const v of c){const k=l[v.name],{actionRequest:x,reviewConfig:b}=await e(v,k,r,s);h.push(x),d.push(b)}const p=(await La({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 C=[...u],S=[],m=p.some(v=>v.type==="reject");for(let v=0;v<p.length;v++){const k=p[v],x=c[v],b=l[x.name],{revisedToolCall:_,toolMessage:M}=n(k,x,b);_&&(!m||k.type==="reject")&&C.push(_),M&&S.push(M)}O.isInstance(a)&&(a.tool_calls=C);const w=m?"model":void 0;return{messages:[a,...S],jumpTo:w}}}})}const Bp=!0,zp="5m",Wp=3,Hp="warn",Gp=z({enableCaching:Yn().optional(),ttl:Ft(["5m","1h"]).optional(),minMessagesToCache:F().optional(),unsupportedModelBehavior:Ft(["ignore","warn","raise"]).optional()});var Li=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function Kp(t){return me({name:"PromptCachingMiddleware",contextSchema:Gp,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??Bp,s=e.runtime.context.ttl??t?.ttl??zp,i=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??Wp,o=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??Hp;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 Li(`${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 Li("Last message content is not a string or array")}})}function Jp(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 qp="Your goal is to select the most relevant tools for answering the user's query.";function Yp(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 z({tools:Ue(n).describe("Tools to use. Place the most relevant tools first.")})}const Xp=z({model:ne().or(Xn(sc)).optional(),systemPrompt:ne().optional(),maxTools:F().optional(),alwaysInclude:Ue(ne()).optional()});function Zp(t){return me({name:"LLMToolSelector",contextSchema:Xp,async wrapModelCall(e,n){const r=await Qp(e,t,e.runtime);if(!r)return n(e);const s=Yp(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(em(o,r.availableTools,r.validToolNames,e,t))}})}async function Qp(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??qp;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)),g=i.filter(p=>!f.has(p));if(g.length>0)throw new Error(`Tools in alwaysInclude not found in request: ${g.join(", ")}. Available tools: ${Array.from(f).sort().join(", ")}`)}const l=a.filter(f=>!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)fe.isInstance(f)&&(u=f);if(!u)throw new Error("No user message found in request messages");const h=r?typeof r=="string"?await Jt(r):r:t.model,d=l.map(f=>f.name);return{availableTools:l,systemMessage:c,lastUserMessage:u,model:h,validToolNames:d}}function em(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 tm=z({rules:un(ne(),Xn(RegExp).describe("Regular expression pattern to match PII")).optional()});function nm(){return Math.random().toString(36).substring(2,11)}function Wr(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=nm();return n[l]=a,`[REDACTED_${o}_${l}]`})}return r}async function rm(t,e){if(fe.isInstance(t)||U.isInstance(t)||be.isInstance(t)){const n=t.content,r=await Wr(n,e.rules,e.redactionMap);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return new s({...t,content:r})}return t}if(O.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=await Wr(n,e.rules,e.redactionMap),i=await Wr(r,e.rules,e.redactionMap);return s!==n||i!==r?new O({...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 on(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 Di(t,e){if(fe.isInstance(t)||U.isInstance(t)||be.isInstance(t)){const n=t.content,r=on(n,e);if(r!==n){const s=Object.getPrototypeOf(t).constructor;return{message:new s({...t,content:r}),changed:!0}}return{message:t,changed:!1}}if(O.isInstance(t)){const n=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=JSON.stringify(t.tool_calls),s=on(n,e),i=on(r,e);return s!==n||i!==r?{message:new O({...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:tm,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=>rm(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(!O.isInstance(r))return;const s=n.messages.at(-2),{message:i,changed:o}=Di(r,e);if(!o)return;let a;if(O.isInstance(r)&&r?.tool_calls?.length===0&&typeof r.content=="string"&&r.content.startsWith("{")&&r.content.endsWith("}"))try{a=JSON.parse(on(r.content,e))}catch{}if(O.isInstance(s)&&s?.tool_calls?.length!==0&&s?.tool_calls?.some(c=>c.name.startsWith("extract-"))){const{message:c,changed:u}=Di(s,e),h=s.tool_calls?.find(f=>f.name.startsWith("extract-"))?.args,d=h?JSON.parse(on(JSON.stringify(h),e)):void 0;if(o||u)return{...n,...d?{structuredResponse:d}:{},messages:[new An({id:s.id}),new An({id:r.id}),c,i]}}return{...n,...a?{structuredResponse:a}:{},messages:[new An({id:r.id}),i]}}})}const im="[cleared]";var cl=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??im}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(g=>g.id===l.tool_call_id);if(!h)continue;const d=l.name||h.name;if(this.excludeTools.has(d))continue;if(n[a]=new U({tool_call_id:l.tool_call_id,content:this.placeholder,name:l.name,artifact:void 0,response_metadata:{...l.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){const g=n.indexOf(u);g>=0&&(n[g]=this.#n(u,l.tool_call_id))}const f=await r(n);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(O.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 O({content:t.content,tool_calls:n,response_metadata:r,id:t.id,name:t.name,additional_kwargs:t.additional_kwargs})}};function om(t={}){const e=t.edits??[new cl],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 be(r.systemPrompt)]:[],o=n==="approx"?As: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 am(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const lm=["continue","error","end"],ul="continue";function hl(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 dl=Ft(lm).default(ul);var fl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const i=hl(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}};z({toolName:ne().optional(),threadLimit:F().optional(),runLimit:F().optional(),exitBehavior:dl});const cm=z({threadToolCallCount:un(ne(),F()).default({}),runToolCallCount:un(ne(),F()).default({})}),um="__all__";function hm(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??ul,n=dl.safeParse(e);if(!n.success)throw new Error(zi(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:cm,afterModel:{canJumpTo:["end"],hook:s=>{const i=[...s.messages].reverse().find(O.isInstance);if(!i||!i.tool_calls)return;const o=(v,k)=>t.threadLimit!==void 0&&v+1>t.threadLimit||t.runLimit!==void 0&&k+1>t.runLimit,a=v=>t.toolName===void 0||v.name===t.toolName,l=(v,k,x)=>{const b=[],_=[];let M=k,E=x;for(const P of v)a(P)&&(o(M,E)?_.push(P):(b.push(P),M+=1,E+=1));return{allowed:b,blocked:_,finalThreadCount:M,finalRunCount:E+_.length}},c=t.toolName??um,u={...s.threadToolCallCount??{}},h={...s.runToolCallCount??{}},d=u[c]??0,f=h[c]??0,{allowed:g,blocked:p,finalThreadCount:C,finalRunCount:S}=l(i.tool_calls,d,f);if(u[c]=C,h[c]=S,p.length===0)return g.length>0?{threadToolCallCount:u,runToolCallCount:h}:void 0;if(e==="error"){const v=C+p.length;throw new fl(v,S,t.threadLimit,t.runLimit,t.toolName)}const m=am(t.toolName),w=p.map(v=>new U({content:m,tool_call_id:v.id,name:v.name,status:"error"}));if(e==="end"){let v=[];if(t.toolName!==void 0?v=i.tool_calls.filter(b=>b.name!==t.toolName):new Set(i.tool_calls.map(_=>_.name).filter(Boolean)).size>1&&(v=g.length>0?g:i.tool_calls),v.length>0){const b=Array.from(new Set(v.map(_=>_.name).filter(Boolean))).join(", ");throw new Error(`Cannot end execution with other tool calls pending. Found calls to: ${b}. Use 'continue' or 'error' behavior instead.`)}const k=C+p.length,x=hl(k,S,t.threadLimit,t.runLimit,t.toolName);return w.push(new O(x)),{threadToolCallCount:u,runToolCallCount:h,jumpTo:"end",messages:w}}return{threadToolCallCount:u,runToolCallCount:h,messages:w}}},afterAgent:()=>({runToolCallCount:{}})})}const dm=`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
|
|
|
@@ -317,27 +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.`,fm=Ft(["pending","in_progress","completed"]).describe("Status of the todo"),ml=z({content:ne().describe("Content of the todo item"),status:fm}),pm=z({todos:Ue(ml).default([])});function mm(t){const e=
|
|
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.`,fm=Ft(["pending","in_progress","completed"]).describe("Status of the todo"),ml=z({content:ne().describe("Content of the todo item"),status:fm}),pm=z({todos:Ue(ml).default([])});function mm(t){const e=Hi(({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??dm,schema:z({todos:Ue(ml).describe("List of todo items to update")})});return me({name:"todoListMiddleware",stateSchema:pm,tools:[e],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
|
|
321
321
|
|
|
322
|
-
`:"")+(t?.systemPrompt??pl)})})}const gm="end",ym=z({threadLimit:U().optional(),runLimit:U().optional(),exitBehavior:Ft(["throw","end"]).optional()}),wm=z({threadModelCallCount:U().default(0),runModelCallCount:U().default(0)});var Vo=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 gl(t){return me({name:"ModelCallLimitMiddleware",contextSchema:ym,stateSchema:wm,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??gm,s=n.context.threadLimit??t?.threadLimit,o=n.context.runLimit??t?.runLimit,i=e.threadModelCallCount,a=e.runModelCallCount;if(typeof s=="number"&&s<=i){const l=new Vo({threadLimit:s,threadCount:i});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}if(typeof o=="number"&&o<=a){const l=new Vo({runLimit:o,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function bm(...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 o=t[s],i=typeof o=="string"?await Kt(o):o;return await n({...e,model:i})}catch(o){if(s===t.length-1)throw o}throw r}}})}function vm(t,e){const{backoffFactor:n,initialDelayMs:r,maxDelayMs:s,jitter:o}=t;let i;if(n===0?i=r:i=r*n**e,i=Math.min(i,s),o&&i>0){const a=i*.25;i=i+(Math.random()*2-1)*a,i=Math.max(0,i)}return i}const Bo=z({maxRetries:U().min(0).default(2),tools:Ue(Ae([ae(),ae(),ne()])).optional(),retryOn:Ae([Yn().args(Zn(Error)).returns(Xn()),Ue(ae())]).default(()=>()=>!0),onFailure:Ae([bt("raise"),bt("return_message"),Yn().args(Zn(Error)).returns(ne())]).default("return_message"),backoffFactor:U().min(0).default(2),initialDelayMs:U().min(0).default(1e3),maxDelayMs:U().min(0).default(6e4),jitter:Xn().default(!0)});function _m(t={}){const{maxRetries:e,tools:n,retryOn:r,onFailure:s,backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:l}=Bo.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(C=>p.constructor===C),d={backoffFactor:o,initialDelayMs:i,maxDelayMs:a,jitter:l},f=(p,C,S)=>{const m=C.constructor.name;return`Tool '${p}' failed after ${S} ${S===1?"attempt":"attempts"} with ${m}`},y=(p,C,S,m)=>{if(s==="raise")throw S;let w;return typeof s=="function"?w=s(S):w=f(p,S,m),new F({content:w,tool_call_id:C,name:p,status:"error"})};return me({name:"toolRetryMiddleware",contextSchema:Bo,wrapToolCall:async(p,C)=>{const S=p.tool.name;if(!u(S))return C(p);const m=p.toolCall.id??"";for(let w=0;w<=e;w++)try{return await C(p)}catch(v){const k=w+1,x=v&&typeof v=="object"&&"message"in v?v:new Error(String(v));if(!h(x))return y(S,m,x,k);if(w<e){const b=vm(d,w);b>0&&await yu(b)}else return y(S,m,x,k)}throw new Error("Unexpected: retry loop completed without returning")}})}var Sm={};ti(Sm,{AIMessage:()=>O,AIMessageChunk:()=>jt,BaseMessage:()=>nn,BaseMessageChunk:()=>Jc,ClearToolUsesEdit:()=>cl,Document:()=>De,DynamicStructuredTool:()=>An,DynamicTool:()=>Ll,FakeToolCallingModel:()=>dd,HumanMessage:()=>fe,HumanMessageChunk:()=>Kc,InMemoryStore:()=>gi,MultipleStructuredOutputsError:()=>Zr,MultipleToolsBoundError:()=>Xr,ProviderStrategy:()=>rt,StructuredOutputParsingError:()=>oi,StructuredTool:()=>mr,SystemMessage:()=>ve,SystemMessageChunk:()=>Gc,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>pl,Tool:()=>jl,ToolCallLimitExceededError:()=>fl,ToolInvocationError:()=>Ms,ToolMessage:()=>F,ToolMessageChunk:()=>Hc,ToolStrategy:()=>Be,anthropicPromptCachingMiddleware:()=>Kp,contextEditingMiddleware:()=>im,countTokensApproximately:()=>Ps,createAgent:()=>ol,createMiddleware:()=>me,dynamicSystemPromptMiddleware:()=>Jp,filterMessages:()=>Wc,humanInTheLoopMiddleware:()=>Vp,initChatModel:()=>Kt,llmToolSelectorMiddleware:()=>Zp,modelCallLimitMiddleware:()=>gl,modelFallbackMiddleware:()=>bm,piiRedactionMiddleware:()=>sm,providerStrategy:()=>mu,summarizationMiddleware:()=>xp,todoListMiddleware:()=>mm,tool:()=>Ko,toolCallLimitMiddleware:()=>hm,toolRetryMiddleware:()=>_m,toolStrategy:()=>pu,trimMessages:()=>Qo});var Cm={},Ct,km=(Ct=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(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return 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 o=this.convertTool(s,e);o&&n.push(o)}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}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}g.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){g.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}g.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){g.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return g.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return g.debug(`Available prompts: ${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}},R(Ct,"BaseAdapter"),Ct),kt,Tm=(kt=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,n){if(!n.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[s,o]of Object.entries(n.properties)){if(!(s in r)){if("const"in o)return!1;continue}const i=r[s];if("const"in o&&i!==o.const||"minimum"in o&&typeof i=="number"&&i<o.minimum||"maximum"in o&&typeof i=="number"&&i>o.maximum)return!1}return!0}static validateConditionalSchema(e,n,r){this.validateRequiredProperties(e,n,r),this.validatePropertyPatterns(e,n,r),this.validateNestedConditions(e,n,r)}static validateRequiredProperties(e,n,r){if(n.required){if(typeof e!="object"||e===null){for(const s of n.required)r.addIssue({code:Cr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:Cr.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[o,i]of Object.entries(n.properties)){if(!(o in s))continue;const a=s[o];i.pattern&&typeof a=="string"&&(new RegExp(i.pattern).test(a)||r.addIssue({code:Cr.custom,message:`String '${a}' does not match pattern '${i.pattern}'`,path:[o]}))}}static validateNestedConditions(e,n,r){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,r):n.else&&this.validateConditionalSchema(e,n.else,r)}static parseSchema(e){return Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then?this.parseObject(e):e.properties&&(!e.type||e.type==="object")?this.parseObject(e):this.handleSingleType(e)}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const n={...e};return n.type=e.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const r=e.map(s=>{const o={...n,type:s};return this.parseSchema(o)});return kr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):Se();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Al();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Pl();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=pr();let r=n;return e.format?this.applyStringFormat(n,e):(r=this.applyStringPattern(n,e),r=this.applyStringLength(n,e),r=this.applyStringEnum(n,e),r)}static applyStringFormat(e,n){if(!n.format)return e;switch(n.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,n){if(!n.pattern)return e;const r=new RegExp(n.pattern);return e.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const r=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),r}static applyStringEnum(e,n){return n.enum?e.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const o=e.items.map(i=>this.parseSchema(i));return kr(o)}const n=e.items?this.parseSchema(e.items):Se(),r=Ol(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,ye(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const l=this.applyDefaultValues(i,e);this.matchesCondition(l,r)?this.validateConditionalSchema(l,s,a):o&&this.validateConditionalSchema(l,o,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[o,i]of Object.entries(e.properties||{})){const a=this.parseSchema(i);n[o]=r.has(o)?a:a.optional()}const s=ye(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return Se();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Nl()):n.push(this.parseSchema(r));return n.length>=2?kr(n):n.length===1?n[0]:Se()}static parseAllOf(e){if(e.length===0)return Se();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}},R(kt,"JSONSchemaToZod"),kt);function yl(t){try{return Tm.convert(t)}catch(e){return g.warn(`Failed to convert JSON schema to Zod: ${e}`),Se()}}R(yl,"schemaToZod");var Tt,Xt=(Tt=class extends km{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?yl(e.inputSchema):ye({}).optional();return new An({name:e.name??"NO NAME",description:e.description??"",schema:r,func:R(async o=>{g.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return g.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=R(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new An({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:ye({}).optional(),func:R(async()=>{g.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(l=>typeof l=="string"?l:l.text?l.text:l.uri?l.uri:JSON.stringify(l)).join(`
|
|
323
|
-
`):"Resource is empty or unavailable"}catch(a){return g.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=ye({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=pr();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?ye(o):ye({}).optional()}return new An({name:e.name,description:e.description||"",schema:r,func:R(async o=>{g.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
|
|
324
|
-
`):"Prompt returned no messages"}catch(i){return g.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},R(Tt,"LangChainAdapter"),Tt),Et,_r=(Et=class extends mr{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}},R(Et,"MCPServerTool"),Et),Em=ye({}),xt,xm=(xt=class extends _r{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Em;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."}},R(xt,"AcquireActiveMCPServerTool"),xt),Mt,Mm=(Mt=class extends mr{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=ye({serverName:pr().describe("The name for the new MCP server."),serverConfig:Se().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 o=(await this.manager.client.createSession(e)).connector,i=await this.manager.adapter.createToolsFromConnectors([o]);this.manager.serverTools[e]=i,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;const a=i.length;return r+=` Session created and connected. '${e}' is now the active server with ${a} tools available.`,r+=`
|
|
322
|
+
`:"")+(t?.systemPrompt??pl)})})}const gm="end",ym=z({threadLimit:F().optional(),runLimit:F().optional(),exitBehavior:Ft(["throw","end"]).optional()}),wm=z({threadModelCallCount:F().default(0),runModelCallCount:F().default(0)});var Ui=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 gl(t){return me({name:"ModelCallLimitMiddleware",contextSchema:ym,stateSchema:wm,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??gm,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 Ui({threadLimit:s,threadCount:o});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}if(typeof i=="number"&&i<=a){const l=new Ui({runLimit:i,runCount:a});if(r==="end")return{jumpTo:"end",messages:[new O(l.message)]};throw l}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function bm(...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 Jt(i):i;return await n({...e,model:o})}catch(i){if(s===t.length-1)throw i}throw r}}})}function vm(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 Fi=z({maxRetries:F().min(0).default(2),tools:Ue(Me([ae(),ae(),ne()])).optional(),retryOn:Me([qn().args(Xn(Error)).returns(Yn()),Ue(ae())]).default(()=>()=>!0),onFailure:Me([vt("raise"),vt("return_message"),qn().args(Xn(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:Yn().default(!0)});function _m(t={}){const{maxRetries:e,tools:n,retryOn:r,onFailure:s,backoffFactor:i,initialDelayMs:o,maxDelayMs:a,jitter:l}=Fi.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(C=>p.constructor===C),d={backoffFactor:i,initialDelayMs:o,maxDelayMs:a,jitter:l},f=(p,C,S)=>{const m=C.constructor.name;return`Tool '${p}' failed after ${S} ${S===1?"attempt":"attempts"} with ${m}`},g=(p,C,S,m)=>{if(s==="raise")throw S;let w;return typeof s=="function"?w=s(S):w=f(p,S,m),new U({content:w,tool_call_id:C,name:p,status:"error"})};return me({name:"toolRetryMiddleware",contextSchema:Fi,wrapToolCall:async(p,C)=>{const S=p.tool.name;if(!u(S))return C(p);const m=p.toolCall.id??"";for(let w=0;w<=e;w++)try{return await C(p)}catch(v){const k=w+1,x=v&&typeof v=="object"&&"message"in v?v:new Error(String(v));if(!h(x))return g(S,m,x,k);if(w<e){const b=vm(d,w);b>0&&await yu(b)}else return g(S,m,x,k)}throw new Error("Unexpected: retry loop completed without returning")}})}var Sm={};eo(Sm,{AIMessage:()=>O,AIMessageChunk:()=>Lt,BaseMessage:()=>nn,BaseMessageChunk:()=>Jc,ClearToolUsesEdit:()=>cl,Document:()=>Le,DynamicStructuredTool:()=>Gi,DynamicTool:()=>Ll,FakeToolCallingModel:()=>dd,HumanMessage:()=>fe,HumanMessageChunk:()=>Kc,InMemoryStore:()=>go,MultipleStructuredOutputsError:()=>Yr,MultipleToolsBoundError:()=>qr,ProviderStrategy:()=>rt,StructuredOutputParsingError:()=>so,StructuredTool:()=>fr,SystemMessage:()=>be,SystemMessageChunk:()=>Gc,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>pl,Tool:()=>jl,ToolCallLimitExceededError:()=>fl,ToolInvocationError:()=>xs,ToolMessage:()=>U,ToolMessageChunk:()=>Hc,ToolStrategy:()=>Ve,anthropicPromptCachingMiddleware:()=>Kp,contextEditingMiddleware:()=>om,countTokensApproximately:()=>As,createAgent:()=>il,createMiddleware:()=>me,dynamicSystemPromptMiddleware:()=>Jp,filterMessages:()=>Wc,humanInTheLoopMiddleware:()=>Vp,initChatModel:()=>Jt,llmToolSelectorMiddleware:()=>Zp,modelCallLimitMiddleware:()=>gl,modelFallbackMiddleware:()=>bm,piiRedactionMiddleware:()=>sm,providerStrategy:()=>mu,summarizationMiddleware:()=>xp,todoListMiddleware:()=>mm,tool:()=>Hi,toolCallLimitMiddleware:()=>hm,toolRetryMiddleware:()=>_m,toolStrategy:()=>pu,trimMessages:()=>Zi});var Cm={},kt,km=(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)&&(y.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 y.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const i=this.convertTool(s,e);i&&n.push(i)}return this.connectorToolMap.set(e,n),y.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return y.debug(`Available tools: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){y.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return y.error(`Error initializing connector: ${n}`),!1}}return!0}},j(kt,"BaseAdapter"),kt),Tt,Tm=(Tt=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:_r.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:_r.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[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:_r.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 Sr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):_e();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Al();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Pl();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=_s();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 Sr(i)}const n=e.items?this.parseSchema(e.items):_e(),r=Ol(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,Ye(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=Ye(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 _e();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Nl()):n.push(this.parseSchema(r));return n.length>=2?Sr(n):n.length===1?n[0]:_e()}static parseAllOf(e){if(e.length===0)return _e();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}},j(Tt,"JSONSchemaToZod"),Tt);function yl(t){try{return Tm.convert(t)}catch(e){return y.warn(`Failed to convert JSON schema to Zod: ${e}`),_e()}}j(yl,"schemaToZod");var Et,mt=(Et=class extends km{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?yl(e.inputSchema):Ye({}).optional();return new Gi({name:e.name??"NO NAME",description:e.description??"",schema:r,func:j(async i=>{y.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 y.error(`Error executing MCP tool: ${o.message}`),`Error executing MCP tool: ${String(o)}`}},"func")})}},j(Et,"LangChainAdapter"),Et),xt,br=(xt=class extends fr{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}},j(xt,"MCPServerTool"),xt),Em=Ye({}),Mt,xm=(Mt=class extends br{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=Em;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."}},j(Mt,"AcquireActiveMCPServerTool"),Mt),At,Mm=(At=class extends fr{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=Ye({serverName:_s().describe("The name for the new MCP server."),serverConfig:_e().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(e){super(),this.manager=e}async _call({serverName:e,serverConfig:n}){try{this.manager.client.addServer(e,n);let r=`Server '${e}' added to the client.`;y.debug(`Connecting to new server '${e}' and discovering tools.`);const 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+=`
|
|
325
323
|
|
|
326
|
-
${
|
|
327
|
-
`)}`,
|
|
328
|
-
`)}catch(
|
|
329
|
-
`)}},R(Pt,"ListMCPServersTool"),Pt),Im=ye({}),Ot,$m=(Ot=class extends _r{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Im;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}'.`}},R(Ot,"ReleaseMCPServerConnectionTool"),Ot);function fr(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)=>fr(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)&&fr(t[s],e[s]))}return!1}R(fr,"isEqual");var Nt,Rm=(Nt=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(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));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 o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(h){g.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const l=[...o,...i,...a],c=this.serverTools[n];!c||!fr(c,l)?(this.serverTools[n]=l,this.initializedServers[n]=!0,g.debug(`Prefetched ${l.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):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 Mm(this),new Nm(this),new Pm(this),new xm(this),new $m(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}},R(Nt,"ServerManager"),Nt),It,zo=(It=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 an(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await Promise.resolve().then(()=>Wo);return{langfuseHandler:s,langfuseInitPromise:o}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await an(async()=>{const{initializeLangfuse:o}=await Promise.resolve().then(()=>Wo);return{initializeLangfuse:o}},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)"}},R(It,"ObservabilityManager"),It),jm="/api/v1/chats",Lm="/api/v1/chats/{chat_id}/execute",$t,Dm=($t=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??Cm.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 On(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 o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${jm}`;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 i=(await s.json()).id;return g.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){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 i=this.chatId,a={query:e,max_steps:n??10};o&&(a.output_schema=this.pydanticToJsonSchema(o),g.info("🔧 Using structured output with schema"));const l={"Content-Type":"application/json","x-api-key":this.apiKey},c=`${this.baseUrl}${Lm.replace("{chat_id}",i)}`;g.info(`🚀 Executing agent in chat ${i}`);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:
|
|
324
|
+
${o.map(l=>l.name).join(`
|
|
325
|
+
`)}`,y.info(r),r}catch(r){return y.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},j(At,"AddMCPServerFromConfigTool"),At),Am=Ye({serverName:_s().describe("The name of the MCP server.")}),Pt,Pm=(Pt=class extends br{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=Am;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(y.debug(`Using existing session for server '${e}'`),r||(y.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,this.manager.serverTools[e]){const 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 y.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},j(Pt,"ConnectMCPServerTool"),Pt),Om=Ye({}),Ot,Nm=(Ot=class extends br{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=Om;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){y.error(`Unexpected error listing tools for server '${r}': ${String(o)}`)}}return n.join(`
|
|
327
|
+
`)}},j(Ot,"ListMCPServersTool"),Ot),Im=Ye({}),Nt,$m=(Nt=class extends br{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=Im;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}'.`}},j(Nt,"ReleaseMCPServerConnectionTool"),Nt);function dr(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)=>dr(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)&&dr(t[s],e[s]))}return!1}j(dr,"isEqual");var It,Rm=(It=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,y.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){y.info("Server Manager State: No servers configured.");return}const s=n.map(i=>({"Server Name":i,Connected:r.includes(i)?"✅":"❌",Initialized:this.initializedServers[i]?"✅":"❌","Tool Count":this.serverTools[i]?.length??0,Active:this.activeServer===i?"✅":"❌"}));y.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&y.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),y.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(y.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),y.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let i=[];try{i=await this.adapter.createToolsFromConnectors([s])}catch(l){y.error(`Failed to create tools from connector for server '${n}': ${l}`);continue}const o=this.serverTools[n];!o||!dr(o,i)?(this.serverTools[n]=i,this.initializedServers[n]=!0,y.debug(`Prefetched ${i.length} tools for server '${n}'.`)):y.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){y.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){y.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new Mm(this),new Nm(this),new Pm(this),new xm(this),new $m(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return y.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},j(It,"ServerManager"),It),$t,Vi=($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 an(async()=>{const{langfuseHandler:s,langfuseInitPromise:i}=await Promise.resolve().then(()=>Bi);return{langfuseHandler:s,langfuseInitPromise:i}},[]);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await an(async()=>{const{initializeLangfuse:i}=await Promise.resolve().then(()=>Bi);return{initializeLangfuse:i}},void 0);await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),y.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),y.debug("ObservabilityManager: Langfuse handler available"))}catch{y.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(y.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?y.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):y.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(y.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),y.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],y.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();y.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();y.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},j($t,"ObservabilityManager"),$t),jm="/api/v1/chats",Lm="/api/v1/chats/{chat_id}/execute",Rt,Dm=(Rt=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??Cm.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 Pn(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){y.warn(`Failed to parse structured output: ${s}`);const 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}${jm}`;y.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),l=s.status;throw l===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${l} - ${a}`)}const o=(await s.json()).id;return y.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&&y.warn("External history is not yet supported for remote execution");try{y.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const o=this.chatId,a={query:e,max_steps:n??10};i&&(a.output_schema=this.pydanticToJsonSchema(i),y.info("🔧 Using structured output with schema"));const l={"Content-Type":"application/json","x-api-key":this.apiKey},c=`${this.baseUrl}${Lm.replace("{chat_id}",o)}`;y.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?(y.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?(y.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?(y.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?(y.error(`❌ Validation error: ${d}`),new Error(`Request validation failed: ${d}. Please check your query parameters and output schema format.`)):f===500?(y.error(`❌ Server error: ${d}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(y.error(`❌ Remote execution failed with status ${f}: ${d}`),new Error(`Remote agent execution failed: ${f} - ${d}`))}const h=await u.json();if(y.info(`🔧 Response: ${JSON.stringify(h)}`),y.info("✅ Remote execution completed successfully"),typeof h=="object"&&h!==null){if(h.status==="error"||h.error!==null){const d=h.error??String(h);throw y.error(`❌ Remote agent execution failed: ${d}`),new Error(`Remote agent execution failed: ${d}`)}if(String(h).includes("failed to initialize"))throw y.error(`❌ Agent initialization failed: ${h}`),new Error(`Agent initialization failed on remote server. This usually indicates:
|
|
330
328
|
• Invalid agent configuration (LLM model, system prompt)
|
|
331
329
|
• Missing or invalid MCP server configurations
|
|
332
330
|
• Network connectivity issues with MCP servers
|
|
333
331
|
• Missing environment variables or credentials
|
|
334
|
-
Raw error: ${h}`)}return
|
|
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"?(y.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.")):(y.error(`❌ Remote execution error: ${o}`),new Error(`Remote agent execution failed: ${o.message}`)):(y.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(){y.info("🔌 Remote agent client closed")}},j(Rt,"RemoteAgent"),Rt);function wl(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}j(wl,"generateToolDescriptions");function bl(t,e,n){const r=e.join(`
|
|
335
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}
|
|
336
334
|
|
|
337
335
|
Available tools:
|
|
338
336
|
${r}`),n&&(s+=`
|
|
339
337
|
|
|
340
|
-
${n}`),s}
|
|
338
|
+
${n}`),s}j(bl,"buildSystemPromptContent");function vl(t,e,n,r,s,i,o){if(i)return new be({content:i});const a=r?n:e,l=wl(t,s),c=bl(a,l,o);return new be({content:c})}j(vl,"createSystemMessage");var Um=`You are a helpful AI assistant.
|
|
341
339
|
You have access to the following tools:
|
|
342
340
|
|
|
343
341
|
{tool_descriptions}
|
|
@@ -351,7 +349,7 @@ Action Input: the input to the action
|
|
|
351
349
|
Observation: the result of the action
|
|
352
350
|
... (this Thought/Action/Action Input/Observation can repeat N times)
|
|
353
351
|
Thought: I now know the final answer
|
|
354
|
-
Final Answer: the final answer to the original input question`,
|
|
352
|
+
Final Answer: the final answer to the original input question`,Fm=`You are a helpful assistant designed to interact with MCP
|
|
355
353
|
(Model Context Protocol) servers. You can manage connections to different servers and use the tools
|
|
356
354
|
provided by the currently active server.
|
|
357
355
|
|
|
@@ -374,14 +372,14 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
374
372
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
375
373
|
change when you connect to a server):
|
|
376
374
|
{tool_descriptions}
|
|
377
|
-
`,Rt,Zm=(Rt=class{static getPackageVersion(){return xl()}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 Dm({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 Xt,this.telemetry=no.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new zo({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(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 Xt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Rm(this.client,this.adapter)}else this.adapter=e.adapter??new Xt(this.disallowedTools);if(this.telemetry=no.getInstance(),this.llm){const[n,r]=Ml(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new zo({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:R(()=>this.getMetadata(),"metadataProvider"),tagsProvider:R(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:R(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:R(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:R(()=>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{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],g.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{g.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),g.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}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??Fm;this.systemMessage=vl(e,n,Um,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof ve))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);g.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[gl({runLimit:this.maxSteps})],s=ol({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 ve(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof ve)),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 Xt(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 o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(g.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){g.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else g.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){g.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){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 o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof fe)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 F)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,o);const i=this.stream(e,n,r,s,o);return this._consumeAndReturn(i)}async*stream(e,n,r=!0,s,o){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,o);let i=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,m=new Set(S.map(v=>v.name)),w=new Set(this._tools.map(v=>v.name));(m.size!==w.size||[...m].some(v=>!w.has(v)))&&(g.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const S of h)(this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S))&&d.push(S);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 C=[...d,new fe(e)];for(;p<=y;){const S={messages:C};let m=!1;const w=await this._agentExecutor.stream(S,{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 v of w){for(const[k,x]of Object.entries(v))if(g.debug(`📦 Node '${k}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let b=x.messages;Array.isArray(b)||(b=[b]);for(const _ of b)C.includes(_)||C.push(_);for(const _ of b){if("tool_calls"in _&&Array.isArray(_.tool_calls)&&_.tool_calls.length>0)for(const M of _.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let I=JSON.stringify(P);I.length>100&&(I=`${I.slice(0,97)}...`),g.info(`🔧 Tool call: ${E} with input: ${I}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(_)){const M=_.content;let E=String(M);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,I=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(I.size!==V.size||[...I].some(X=>!V.has(X))){g.info(`🔄 Tools changed during execution. New tools: ${[...I].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(_)&&!this._messageHasToolCalls(_)&&(c=this._normalizeOutput(this._getMessageContent(_)),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){const S=C.slice(d.length);for(const m of S)this.addToHistory(m)}if(o&&c)try{g.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(c,this.llm,o);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(S)}`)),g.info("✅ Structured output successful"),l=!0,S}catch(S){throw g.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}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}`),i&&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&&i&&(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 Xt)}finally{this._initialized=!1,g.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await an(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-BjtA5bgX.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){let i=!1;const a=Date.now();let l=!1,c=0,u=0,h="";o&&(e=this._enhanceQueryWithSchema(e,o));try{r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!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 fe({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 C=[...p,new fe(e)];g.info("callbacks",this.callbacks);const S=d.streamEvents({messages:C},{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 S)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 v=this._normalizeOutput(w.content);h+=v,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(o&&h){g.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,v=null;this._attemptStructuredOutput(h,this.llm,o).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,v=x,x});let k=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(k++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${k*2}s)`,elapsed:k*2}});if(v)throw v;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new O(`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 O(h));console.log(`
|
|
375
|
+
`,jt,Zm=(jt=class{static getPackageVersion(){return xl()}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 Dm({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 mt,this.telemetry=ti.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Vi({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 mt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Rm(this.client,this.adapter)}else this.adapter=e.adapter??new mt(this.disallowedTools);if(this.telemetry=ti.getInstance(),this.llm){const[n,r]=Ml(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Vi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:j(()=>this.getMetadata(),"metadataProvider"),tagsProvider:j(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:j(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:j(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:j(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}y.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await mt.createTools(this.client),y.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{y.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),y.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Um;this.systemMessage=vl(e,n,Fm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof be))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[gl({runLimit:this.maxSteps})],s=il({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new be(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof be)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new mt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const 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?(y.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){y.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else y.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){y.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){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const 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 O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof fe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,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 S=this.serverManager.tools,m=new Set(S.map(v=>v.name)),w=new Set(this._tools.map(v=>v.name));(m.size!==w.size||[...m].some(v=>!w.has(v)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const S of h)(this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S))&&d.push(S);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");y.info(`💬 Received query: '${f}'`),y.info("🏁 Starting agent execution");const g=3;let p=0;const C=[...d,new fe(e)];for(;p<=g;){const S={messages:C};let m=!1;const w=await this._agentExecutor.stream(S,{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 v of w){for(const[k,x]of Object.entries(v))if(y.debug(`📦 Node '${k}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let b=x.messages;Array.isArray(b)||(b=[b]);for(const _ of b)C.includes(_)||C.push(_);for(const _ of b){if("tool_calls"in _&&Array.isArray(_.tool_calls)&&_.tool_calls.length>0)for(const M of _.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let I=JSON.stringify(P);I.length>100&&(I=`${I.slice(0,97)}...`),y.info(`🔧 Tool call: ${E} with input: ${I}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(_)){const M=_.content;let E=String(M);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),y.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,I=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(I.size!==V.size||[...I].some(X=>!V.has(X))){y.info(`🔄 Tools changed during execution. New tools: ${[...I].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,y.info(`🔃 Restarting execution with updated tools (restart ${p}/${g})`);break}}}this._isAIMessageLike(_)&&!this._messageHasToolCalls(_)&&(c=this._normalizeOutput(this._getMessageContent(_)),y.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>g){y.warn(`⚠️ Max restarts (${g}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const S=C.slice(d.length);for(const m of S)this.addToHistory(m)}if(i&&c)try{y.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(S)}`)),y.info("✅ Structured output successful"),l=!0,S}catch(S){throw y.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw y.error(`❌ Error running query: ${h}`),o&&r&&(y.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,g=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:g.length,toolsAvailableNames:g.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&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new mt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await an(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-DpBhpnVp.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);y.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new fe({content:e})));const g=s??this.conversationHistory,p=[];for(const m of g)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):y.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const C=[...p,new fe(e)];y.info("callbacks",this.callbacks);const S=d.streamEvents({messages:C},{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 S)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 v=this._normalizeOutput(w.content);h+=v,y.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){y.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,v=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,v=x,x});let k=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(k++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${k*2}s)`,elapsed:k*2}});if(v)throw v;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(w)}`)),y.info("✅ Structured output successful"))}catch(m){y.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 O(h));console.log(`
|
|
378
376
|
|
|
379
|
-
`),
|
|
377
|
+
`),y.info(`🎉 StreamEvents complete - ${c} events emitted`),l=!0}catch(d){throw y.error(`❌ Error during streamEvents: ${d}`),o&&r&&(y.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 g=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:g}),r&&!this.client&&o&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,i="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Pn(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=Pn(r),{$schema:a,additionalProperties:l,...c}=o;i=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${i}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){y.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
|
|
380
378
|
Please format the following information according to the EXACT schema specified below.
|
|
381
379
|
You must use the exact field names and types as shown in the schema.
|
|
382
380
|
|
|
383
381
|
Required schema format:
|
|
384
|
-
${
|
|
382
|
+
${i}
|
|
385
383
|
|
|
386
384
|
Content to extract from:
|
|
387
385
|
${u}
|
|
@@ -393,12 +391,12 @@ Here are the tools *currently* available to you (this list includes server manag
|
|
|
393
391
|
- Return valid JSON that matches the schema structure exactly
|
|
394
392
|
- For missing data: use null for nullable fields, omit optional fields entirely
|
|
395
393
|
- Do NOT use empty strings ("") or zero (0) as placeholders for missing data
|
|
396
|
-
`;f>1&&(
|
|
394
|
+
`;f>1&&(g+=`
|
|
397
395
|
|
|
398
396
|
PREVIOUS ATTEMPT FAILED with error: ${d}
|
|
399
397
|
Please fix the issues mentioned above and ensure the output matches the schema exactly.
|
|
400
|
-
`);try{
|
|
401
|
-
${
|
|
398
|
+
`);try{y.info(`🔄 Structured output attempt ${f} - using streaming approach`);const p=u.length>300?`${u.slice(0,300)}...`:u;y.info(`🔄 Content being formatted (${u.length} chars): ${p}`),y.info(`🔄 Full format prompt (${g.length} chars):
|
|
399
|
+
${g}`);const C=await s.stream(g);let S=null,m=0;for await(const v of C){if(m++,y.debug(`Chunk ${m}: ${JSON.stringify(v,null,2)}`),typeof v=="string")try{S=JSON.parse(v)}catch{y.warn(`🔄 Failed to parse string chunk as JSON: ${v}`)}else if(v&&typeof v=="object")S=v;else try{S=JSON.parse(String(v))}catch{y.warn(`🔄 Failed to parse chunk as JSON: ${v}`)}m%10===0&&y.debug(`🔄 Structured output streaming: ${m} chunks`)}if(y.info(`🔄 Structured result attempt ${f}: ${JSON.stringify(S,null,2)}`),!S)throw new Error("No structured result received from stream");const w=this._validateStructuredResult(S,r);return y.info(`✅ Structured output successful on attempt ${f}`),w}catch(p){if(d=p instanceof Error?p.message:String(p),y.warn(`⚠️ Structured output attempt ${f} failed: ${d}`),f===h)throw y.error(`❌ All ${h} structured output attempts failed`),new Error(`Failed to generate valid structured output after ${h} attempts. Last error: ${d}`);continue}}throw new Error("Unexpected error in structured output generation")}_validateStructuredResult(e,n){try{const r=n.parse(e),s=n;if(s._def&&s._def.shape)for(const[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 y.debug(`Validation details: ${r}`),r}}_enhanceQueryWithSchema(e,n){try{const r=Pn(n),{$schema:s,additionalProperties:i,...o}=r,a=JSON.stringify(o,null,2);return`
|
|
402
400
|
${e}
|
|
403
401
|
|
|
404
402
|
IMPORTANT: Your response must include sufficient information to populate the following structured output:
|
|
@@ -407,4 +405,4 @@ ${y}`);const C=await s.stream(y);let S=null,m=0;for await(const v of C){if(m++,g
|
|
|
407
405
|
|
|
408
406
|
Make sure you gather ALL the required information during your task execution.
|
|
409
407
|
If any required information is missing, continue working to find it.
|
|
410
|
-
`}catch(r){return
|
|
408
|
+
`}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},j(jt,"MCPAgent"),jt),Z={},Vm=Z.MCP_USE_LANGFUSE?.toLowerCase()==="false",wn={handler:null,client:null,initPromise:null};async function Qs(t,e,n,r){try{const s=await an(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.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,g,p,C){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=C,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,C,S,m,w){y.debug("Langfuse: Chain start intercepted");const v=this.getCustomTags(),k=this.getMetadata(),x=[...C||[],...v],b={...S||{},...k};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(x)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(b)}`)),super.handleChainStart(d,f,g,p,x,b,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 g=this.tagsProvider();g&&g.length>0&&d.push(...g)}return d}getMetadata(){const d={},f=this.getEnvironmentTag();if(f&&(d.env=f),this.agentId&&(d.agent_id=this.agentId),this.metadata&&Object.assign(d,this.metadata),this.metadataProvider){const g=this.metadataProvider();g&&Object.assign(d,g)}return d}getEnvironmentTag(){const d=Z.MCP_USE_AGENT_ENV;if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};j(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};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),wn.handler=new o(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await an(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;wn.client=new d({publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(h){y.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}j(Qs,"initializeLangfuse");Vm?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Z.LANGFUSE_PUBLIC_KEY||!Z.LANGFUSE_SECRET_KEY?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):wn.initPromise=Qs();var Bm=j(()=>wn.handler,"langfuseHandler"),zm=j(()=>wn.initPromise,"langfuseInitPromise");const Bi=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Qs,langfuseHandler:Bm,langfuseInitPromise:zm},Symbol.toStringTag,{value:"Module"}));export{km as BaseAdapter,tg as BaseConnector,ng as BrowserOAuthClientProvider,rg as BrowserTelemetry,sg as HttpConnector,mt as LangChainAdapter,ig as Logger,Zm as MCPAgent,og as MCPClient,ag as MCPSession,Vi as ObservabilityManager,Dm as RemoteAgent,lg as Tel,ti as Telemetry,cg as VERSION,ug as WebSocketConnector,lu as createReadableStreamFromGenerator,xl as getPackageVersion,y as logger,hg as onMcpAuthorization,dg as setBrowserTelemetrySource,fg as setTelemetrySource,au as streamEventsToAISDK,cu as streamEventsToAISDKWithTools};
|