@mcp-use/inspector 0.12.1-canary.2 → 0.12.3
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-DKdwT1i-.js +408 -0
- package/dist/client/assets/{display-A5IEINAP-B40r5y0U.js → display-A5IEINAP-zQjmUskw.js} +2 -2
- package/dist/client/assets/{embeddings-BADWxMK2.js → embeddings-B7zk7f-e.js} +1 -1
- package/dist/client/assets/index-BHRzjpbc.js +1676 -0
- package/dist/client/assets/{index-DNJLqe-0.js → index-B_u5I0WU.js} +1 -1
- package/dist/client/assets/{index-BVh_1UP5.js → index-CJaf2NfG.js} +1 -1
- package/dist/client/assets/{index-D7ssHyqk.js → index-Cg0RorJp.js} +1 -1
- package/dist/client/assets/{index-D8OInqH9.js → index-Cnpr5SN0.js} +1 -1
- package/dist/client/assets/{index-BPMoHjcK.js → index-CqBG8Lal.js} +36 -38
- package/dist/client/assets/{index-DhR7GEPn.js → index-DYezzm9U.js} +4 -4
- package/dist/client/assets/{index-pUBxH7MS.js → index-Dw-QLKLZ.js} +1 -1
- package/dist/client/assets/{index-CC9etcDb.js → index-UQjlmKqn.js} +1 -1
- package/dist/client/assets/{winston-Bn4DX7J3.js → winston-BkpNs6M7.js} +1 -1
- package/dist/client/index.html +2 -2
- package/package.json +4 -4
- package/dist/client/assets/browser-DdbFE8CK.js +0 -410
- package/dist/client/assets/index-CvbOIkmz.js +0 -1674
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-zQjmUskw.js","assets/index-BHRzjpbc.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as j,q as ve,Z as Sl,s as Cl,p as Bi,u as Tl,T as ei,v as kl,w as y,a as an,t as An,x as Ye,y as vs,z as vr,A as Sr,B as El,C as xl,D as Ml,E as Al}from"./index-BHRzjpbc.js";import{F as qm,G as Ym,H as Xm,I as Zm,L as Qm,J as eg,M as tg,H as ng,V as rg,W as sg,K as ig,N as og,N as ag}from"./index-BHRzjpbc.js";import{L as zi,S as fr,t as Pl,o as Ol,l as Nl,a as Wi,T as Il,D as Rl,b as Hi}from"./index-Dw-QLKLZ.js";import{h as bn,s as $l,g as Gi,B as jl,k as Ll,l as Dl,I as Fl,C as Ul,m as Vl,t as Bl,n as zl,o as Wl,p as Hl,q as Gl,r as Kl,u as Jl,v as ql,w as Yl,x as Xl,y as Zl,R as Ql,z as ec,a as tc}from"./index-B_u5I0WU.js";import{aO as nc,aP as Ss,aQ as rc,at as Ee,e as Zt,aR as sc,aS as ln,a0 as de,x as nt,aT as Ki,g as ic,aU as Hr,_ as q,ag as Kt,ae as fe,z as O,ad as ee,d as oc,C as ac,aV as lc,p as ti,aA as Ji,aW as be,ai as cn,aX as nn,E as qi,y as Oe,aY as Cs,B as Gr,D as Lt,am as Dt,aZ as cc,a_ as uc,a$ as hc,b0 as dc,b1 as fc,b2 as pc,b3 as mc,b4 as gc,b5 as yc,b6 as wc,b7 as bc,b8 as _c,b9 as vc,ba as Sc,bb as Cc,bc as Tc,bd as kc,K as Ec,be as xc,bf as Mc,bg as Ac,t as je,r as rn,m as Re,L as Xe,aq as Ft,bh as Pc,F as Oc,aB as ni,ar as Nc,bi as ri,bj as si,ab as Ts,aa as ii,a9 as Kr,ac as Ic,S as Rc,a5 as ks,a8 as Ge,bk as Jn,o as z,bl as ae,bm as $c,bn as Me,bo as _t,bp as jc,bq as Es,l as F,a6 as Lc,i as Dc,T as Fc,br as qn,bs as Fe,bt as U,bu as Yi,s as ne,a7 as Uc,bv as Pn,bw as Xi,bx as Ut,by as un,bz as Yn,bA as Xn,bB as Vc,aK as Bc,aI as zc,aH as Wc,bC as Hc}from"./index-CqBG8Lal.js";import{E as Zi,c as Gc,e as Kc}from"./embeddings-B7zk7f-e.js";import"./index-DRz5BQNA.js";var Cr,Cn,Tr=0,kr=0;function Jc(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||nc)();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:kr+1,u=l-Tr+(c-kr)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Tr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Tr=l,kr=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 qc(t){var e=typeof t=="string"?rc(t):t,n=Yc(e);return typeof t=="string"?Ss(n):n}function Yc(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 oi(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 ai(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?oi(Object(n),!0).forEach(function(r){Xc(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):oi(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Xc(t,e,n){return(e=Zc(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Zc(t){var e=Qc(t,"string");return typeof e=="symbol"?e:e+""}function Qc(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 eu(t={},e,n=0){var r=Jc(ai(ai({},t),{},{_v6:!0}),new Uint8Array(16));return r=qc(r),Ss(r)}async function*tu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}j(tu,"streamEventsToAISDK");function nu(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(nu,"createReadableStreamFromGenerator");async function*ru(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
|
+
🔧 Using tool: ${e.name}
|
|
4
|
+
`;break;case"on_tool_end":yield`
|
|
5
|
+
✅ Tool completed: ${e.name}
|
|
6
|
+
`;break}}j(ru,"streamEventsToAISDKWithTools");var su=Object.defineProperty,Qi=(t,e)=>{for(var n in e)su(t,n,{get:e[n],enumerable:!0})},iu={};Qi(iu,{ConfigurableModel:()=>Jr,MODEL_PROVIDER_CONFIG:()=>pr,_inferModelProvider:()=>no,getChatModelByClassName:()=>to,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}},eo=Object.keys(pr);async function to(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 ou(t,e,n={}){const r=e||no(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=eo.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
|
|
7
|
+
|
|
8
|
+
Supported model providers are: ${l}`)}const{modelProvider:i,...o}=n,a=await to(s.className);return new a({model:t,...o})}function no(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 ou(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 sc({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(":")];eo.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}},ro=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 au=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-${++au}`}if(ic(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 Ki(this.schema).validate(e);if(!r.valid)throw new ro(this.name,r.errors.map(s=>s.error));return e}},rt=class so{_schemaType;constructor(e){this.schema=e}static fromSchema(e){const n=nt(e);return new so(n)}parse(e){if(!(typeof e.content!="string"||e.content===""))try{const n=JSON.parse(e.content);return new Ki(this.schema).validate(n).valid?n:void 0}catch{}}};function io(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=oo(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 lu(t,e){return io(t,e)}function cu(t){return rt.fromSchema(t)}const uu=["ChatOpenAI","ChatXAI"],li=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function oo(t){if(!t)return!1;if(typeof t=="string"){const n=t.split(":").pop();return li.some(r=>n.includes(r))}if(Zn(t))return oo(t._defaultConfig.model);if(!Ms(t))return!1;const e=t.getName();return!!(e==="FakeToolCallingChatModel"||uu.includes(e)&&("model"in t&&li.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 hu(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 ao(t){return eu({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 du="__error__",Nn="__scheduled__",fu="__interrupt__",pu="__resume__";var ci="[...]",mu="[Circular]",Qn=[],yt=[];function gu(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function yu(t,e,n,r){typeof r>"u"&&(r=gu()),Zr(t,"",0,[],void 0,0,r);var s;try{yt.length===0?s=JSON.stringify(t,e,n):s=JSON.stringify(t,wu(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(mu,t,e,s);return}if(typeof o.depthLimit<"u"&&i>o.depthLimit){Er(ci,t,e,s);return}if(typeof o.edgesLimit<"u"&&n+1>o.edgesLimit){Er(ci,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 wu(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 bu=[];var _u={},lo={};q(lo,{BaseChatMessageHistory:()=>co,BaseListChatMessageHistory:()=>Ps,InMemoryChatMessageHistory:()=>vu});var co=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.")}},vu=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=[]}},Su={},uo={};q(uo,{BaseMemory:()=>Cu,getInputValue:()=>Tu,getOutputValue:()=>ku,getPromptInputKey:()=>Eu});var Cu=class{};const ho=(t,e)=>{if(e!==void 0)return t[e];const n=Object.keys(t);if(n.length===1)return t[n[0]]},Tu=(t,e)=>{const n=ho(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},ku=(t,e)=>{const n=ho(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 Eu(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 fo={};q(fo,{BaseStore:()=>po,InMemoryStore:()=>mo});var po=class extends Kt{},mo=class extends po{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)}},go={};q(go,{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(oc(e)),s=await(await ac.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}}},yo={};q(yo,{SaveableVectorStore:()=>xu,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})}}},xu=class extends Ns{static load(t,e){throw new Error("Not implemented")}},wo={};q(wo,{BaseDocumentLoader:()=>bo});var bo=class{},_o={};q(_o,{LangSmithLoader:()=>Mu});var Mu=class extends bo{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 lc(t?.clientConfig),this.contentKey=t.contentKey?t.contentKey.split("."):[],this.formatContent=t.formatContent??Au,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 Au(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}},vo=class extends ee{lc_namespace=["langchain_core","documents","transformers"];invoke(t,e){return this.transformDocuments(t)}},Pu=class extends vo{async transformDocuments(t){const e=[];for(const n of t){const r=await this._transformDocument(n);e.push(r)}return e}},So={};q(So,{BaseDocumentTransformer:()=>vo,Document:()=>Le,MappingDocumentTransformer:()=>Pu});var Is=class extends Kt{lc_namespace=["langchain_core","example_selectors","base"]},Co=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},Ou=class extends Co{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 Nu(t){return t._modelType()==="base_llm"}function Iu(t){return t._modelType()==="base_chat_model"}function ui(t){return t.split(/\n| /).length}var Ru=class To extends Is{examples=[];examplePrompt;getTextLength=ui;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??ui}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 $u=class ko 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 ko({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}},Eo={};q(Eo,{BaseExampleSelector:()=>Is,BasePromptSelector:()=>Co,ConditionalPromptSelector:()=>Ou,LengthBasedExampleSelector:()=>Ru,SemanticSimilarityExampleSelector:()=>$u,isChatModel:()=>Iu,isLLM:()=>Nu});const Qr="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var ju=class extends Kt{lc_namespace=["langchain","recordmanagers"]},xo=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=$l;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 Mo(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 Ao(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 Po(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 Oo=t=>"load"in t&&typeof t.load=="function"&&"loadAndSplit"in t&&typeof t.loadAndSplit=="function";async function Lu(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=Oo(e)?await e.load():e,h=Po(a??null),d=await n.getTime();let f=0,g=0,p=0,C=0;const S=Mo(i??100,u);for(const m of S){const w=Ao(m.map(E=>xo.fromDocument(E))),_=w.map(E=>h(E));o==="incremental"&&w.forEach((E,P)=>{if(_[P]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const T=await n.exists(w.map(E=>E.uid)),x=[],b=[],v=[],M=new Set;if(w.forEach((E,P)=>{if(T[P])if(c)M.add(E.uid);else{v.push(E.uid);return}x.push(E.uid),b.push(E.toDocument())}),v.length>0&&(await n.update(v,{timeAtLeast:d}),C+=v.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:_}),o==="incremental"){_.forEach(P=>{if(!P)throw new Error("Source id cannot be null")});const E=await n.listKeys({before:d,groupIds:_});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 No={};q(No,{RecordManager:()=>ju,UUIDV5_NAMESPACE:()=>Qr,_HashedDocument:()=>xo,_batch:()=>Mo,_deduplicateInOrder:()=>Ao,_getSourceIdAssigner:()=>Po,_isBaseDocumentLoader:()=>Oo,index:()=>Lu});var Io=class extends Gi{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 jl{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 Io(t)}_diff(t,e){return e?Ll(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?ti(r.arguments):{...r,arguments:ti(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""}},Du=class extends Gi{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]}},$o={};q($o,{JsonKeyOutputFunctionsParser:()=>Du,JsonOutputFunctionsParser:()=>Ro,OutputFunctionsParser:()=>Io});var _n=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 _n{async formatPromptValue(t){const e=await this.format(t);return new Dl(e)}};var Fu=Object.prototype.toString,qt=Array.isArray||function(e){return Fu.call(e)==="[object Array]"};function Rs(t){return typeof t=="function"}function Uu(t){return qt(t)?"array":typeof t}function Mr(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hi(t,e){return t!=null&&typeof t=="object"&&e in t}function Vu(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}var Bu=RegExp.prototype.test;function zu(t,e){return Bu.call(t,e)}var Wu=/\S/;function Hu(t){return!zu(Wu,t)}var Gu={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function Ku(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Gu[n]})}var Ju=/\s*/,qu=/\s+/,di=/\s*=/,Yu=/\s*\}/,Xu=/#|\^|\/|>|\{|&|=|!/;function Zu(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(v){if(typeof v=="string"&&(v=v.split(qu,2)),!qt(v)||v.length!==2)throw new Error("Invalid tags: "+v);h=new RegExp(Mr(v[0])+"\\s*"),d=new RegExp("\\s*"+Mr(v[1])),f=new RegExp("\\s*"+Mr("}"+v[1]))}g(e||ce.tags);for(var p=new vn(t),C,S,m,w,_,T;!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),Hu(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(Xu)||"name",p.scan(Ju),S==="="?(m=p.scanUntil(di),p.scan(di),p.scanUntil(d)):S==="{"?(m=p.scanUntil(f),p.scan(Yu),p.scanUntil(d),S="&"):m=p.scanUntil(d),!p.scan(d))throw new Error("Unclosed tag at "+p.pos);if(S==">"?_=[S,m,C,p.pos,l,c,n]:_=[S,m,C,p.pos],c++,s.push(_),S==="#"||S==="^")r.push(_);else if(S==="/"){if(T=r.pop(),!T)throw new Error('Unopened section "'+m+'" at '+C);if(T[1]!==m)throw new Error('Unclosed section "'+T[1]+'" at '+C)}else S==="name"||S==="{"||S==="&"?a=!0:S==="="&&g(m)}if(u(),T=r.pop(),T)throw new Error('Unclosed section "'+T[1]+'" at '+p.pos);return eh(Qu(s))}function Qu(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 eh(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 vn(t){this.string=t,this.tail=t,this.pos=0}vn.prototype.eos=function(){return this.tail===""};vn.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};vn.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=hi(i,o[a])||Vu(i,o[a])),i=i[o[a++]];else i=s.view[e],l=hi(s.view,e);if(l){r=i;break}s=s.parent}n[e]=r}return Rs(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=Zu(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(Rs(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=Rs(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 "'+Uu(e)+'" was given as the first argument for mustache#render(template, view, partials)');return dn.render(e,n,r,s)};ce.escape=Ku;ce.Scanner=vn;ce.Context=Vt;ce.Writer=ie;function jo(){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},Lo=(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=Lo(r[4],s);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},er=t=>{jo();const e=ce.parse(t);return Lo(e)},Do=(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)=>(jo(),ce.render(t,e)),tr={"f-string":Do,mustache:Fo},Uo={"f-string":fn,mustache:er},Ce=(t,e,n)=>{try{return tr[e](t,n)}catch(r){throw Ji(r,"INVALID_PROMPT_INPUT")}},nr=(t,e)=>Uo[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
|
+
|
|
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})}},Rn=class Vo extends _n{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 Vo(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 Fl(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
|
+
|
|
19
|
+
`));throw i.name="InputFormatError",i.lc_error_code=r.lc_error_code,i}return n}},Bo=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)]}},$s=class extends _n{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){const e=await this.formatMessages(t);return new Ul(e)}},zo=class extends Bo{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 qi(await this.prompt.format(t),this.role)}static fromTemplate(t,e,n){return new this(Ke.fromTemplate(t,{templateFormat:n?.templateFormat}),e)}};function th(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function nh(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(th(r)){let s="";typeof r.text=="string"&&(s=r.text??"");const i={...e,additionalContentFields:r};n.push(Ke.fromTemplate(s,i))}else if(nh(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
|
+
Got: ${l}
|
|
21
|
+
From: ${s}`);o=[l[0]]}else o=[];s={url:s},i=new Rn({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 Rn({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 Rn){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"}},Wo=class extends js{static _messageClass(){return O}static lc_name(){return"AIMessagePromptTemplate"}},Ho=class extends js{static _messageClass(){return be}static lc_name(){return"SystemMessagePromptTemplate"}};function rh(t){return typeof t.formatMessages=="function"}function sh(t,e){if(rh(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 Wo.fromTemplate(r,e);if(n._getType()==="system")return Ho.fromTemplate(r,e);if(qi.isInstance(n))return zo.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function ih(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var Ds=class $n extends $s{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)&&!(ih(s)&&s.optional))throw Ji(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 $n(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 $n?a.promptMessages:[sh(a,n)]),[]),s=e.reduce((o,a)=>a instanceof $n?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})}},oh=class ss extends hn{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
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(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})}},ah=class Go extends $s{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
24
|
+
|
|
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
|
+
|
|
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 Go(s)}},lh=class jn extends _n{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const e=this.pipelinePrompts.map(r=>r.name),n=this.pipelinePrompts.map(r=>r.prompt.inputVariables.filter(s=>!e.includes(s))).flat();return[...new Set(n)]}static extractRequiredInputValues(e,n){return n.reduce((r,s)=>(r[s]=e[s],r),{})}async formatPipelinePrompts(e){const n=await this.mergePartialAndUserVariables(e);for(const{name:r,prompt:s}of this.pipelinePrompts){const 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 fi(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function ch(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var uh=class Ko 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(fi(e))return super.pipe(e.withStructuredOutput(this.schema));if(ch(e)&&fi(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 Ko.fromMessages(e,{schema:n,method:r})}},Jo={};q(Jo,{AIMessagePromptTemplate:()=>Wo,BaseChatPromptTemplate:()=>$s,BaseMessagePromptTemplate:()=>gr,BaseMessageStringPromptTemplate:()=>Bo,BasePromptTemplate:()=>_n,BaseStringPromptTemplate:()=>hn,ChatMessagePromptTemplate:()=>zo,ChatPromptTemplate:()=>Ds,DEFAULT_FORMATTER_MAPPING:()=>tr,DEFAULT_PARSER_MAPPING:()=>Uo,DictPromptTemplate:()=>es,FewShotChatMessagePromptTemplate:()=>ah,FewShotPromptTemplate:()=>oh,HumanMessagePromptTemplate:()=>Ls,ImagePromptTemplate:()=>Rn,MessagesPlaceholder:()=>rs,PipelinePromptTemplate:()=>lh,PromptTemplate:()=>Ke,StructuredPrompt:()=>uh,SystemMessagePromptTemplate:()=>Ho,checkValidTemplate:()=>Sn,interpolateFString:()=>Do,interpolateMustache:()=>Fo,parseFString:()=>fn,parseMustache:()=>er,parseTemplate:()=>nr,renderTemplate:()=>Ce});var qo={};q(qo,{BaseDocumentCompressor:()=>hh});var hh=class{static isBaseDocumentCompressor(t){return t?.compressDocuments!==void 0}};const He={and:"and",or:"or",not:"not"},R={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var Yo=class{},Fs=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")}},Us=class extends Fs{},dh=class extends Us{exprName="Comparison";constructor(t,e,n){super(),this.comparator=t,this.attribute=e,this.value=n}},fh=class extends Us{exprName="Operation";constructor(t,e){super(),this.operator=t,this.args=e}},ph=class extends Fs{exprName="StructuredQuery";constructor(t,e){super(),this.query=t,this.filter=e}};function Xo(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Se(t){return t?typeof t=="string"&&t.length>0||typeof t=="function"?!1:Xo(t)&&Object.keys(t).length===0:!0}function Zo(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 Qo(t){if(typeof t=="number")return t%1!==0;if(typeof t=="string"){const e=parseFloat(t);return!Number.isNaN(e)&&e%1!==0&&e.toString()===t}return!1}function ea(t){return typeof t=="string"&&(Number.isNaN(parseFloat(t))||parseFloat(t).toString()!==t)}function ta(t){return typeof t=="boolean"}function Vs(t){let e;if(ea(t))e=t;else if(Zo(t))e=parseInt(t,10);else if(Qo(t))e=parseFloat(t);else if(ta(t))e=!!t;else throw new Error("Unsupported value type");return e}var Bs=class extends Yo{},mh=class extends Bs{allowedOperators;allowedComparators;constructor(t){super(),this.allowedOperators=t?.allowedOperators??[He.and,He.or],this.allowedComparators=t?.allowedComparators??[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte]}formatFunction(t){if(t in R){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(t)===-1)throw new Error(`Comparator ${t} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(t in 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")}}},gh=class extends Bs{allowedOperators=[He.and,He.or];allowedComparators=[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(t){switch(t){case"string":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"number":return[R.eq,R.ne,R.gt,R.gte,R.lt,R.lte];case"boolean":return[R.eq,R.ne];default:throw new Error(`Unsupported data type: ${t}`)}}getComparatorFunction(t){switch(t){case R.eq:return(e,n)=>e===n;case R.ne:return(e,n)=>e!==n;case R.gt:return(e,n)=>e>n;case R.gte:return(e,n)=>e>=n;case R.lt:return(e,n)=>e<n;case R.lte:return(e,n)=>e<=n;default:throw new Error("Unknown comparator")}}getOperatorFunction(t){switch(t){case 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=[R.ne];if(this.allowedComparators.includes(e)){if(!this.getAllowedComparatorsForType(typeof r).includes(e))throw new Error(`'${e}' comparator not allowed to be used with ${typeof r}`);const i=this.getComparatorFunction(e);return o=>{const a=o.metadata[n];return a===void 0?!!s.includes(e):i(a,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")}}},na={};q(na,{BaseTranslator:()=>Bs,BasicTranslator:()=>mh,Comparators:()=>R,Comparison:()=>dh,Expression:()=>Fs,FilterDirective:()=>Us,FunctionalTranslator:()=>gh,Operation:()=>fh,Operators:()=>He,StructuredQuery:()=>ph,Visitor:()=>Yo,castValue:()=>Vs,isBoolean:()=>ta,isFilterEmpty:()=>Se,isFloat:()=>Qo,isInt:()=>Zo,isObject:()=>Xo,isString:()=>ea});var ra={};q(ra,{RunCollectorCallbackHandler:()=>yh});var yh=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)}},wh={},sa={};q(sa,{EventStreamContentType:()=>bh,convertEventStreamToIterableReadableDataStream:()=>vh,getBytes:()=>ia,getLines:()=>oa,getMessages:()=>aa});const bh="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 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 oa(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=_h(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 aa(t,e,n){let r=Ar();const s=new TextDecoder;return function(o,a,l){if(l){Sh(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 _h(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 vh(t,e){const n=new ReadableStream({async start(r){const s=aa(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 ia(t,oa((o,a,l)=>{s(o,a,l),l&&r.close()}))}});return ln.fromReadableStream(n)}function Sh(t){return t.data===""&&t.event===""&&t.id===""&&t.retry===void 0}var Ch={};function la(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 Th(t,e){let n=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r];return n}function kh(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 Eh(t,e){return Math.sqrt(kh(t,e))}var ca={};q(ca,{cosineSimilarity:()=>is,euclideanDistance:()=>Ah,innerProduct:()=>Mh,matrixFunc:()=>yr,maximalMarginalRelevance:()=>Ph,normalize:()=>xh});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 xh(t,e=!1){const n=Oh(t);return t.map(r=>r.map(s=>e?1-s/n:s/n))}function is(t,e){return yr(t,e,la)}function Mh(t,e){return yr(t,e,Th)}function Ah(t,e){return yr(t,e,Eh)}function Ph(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=ua(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 ua(t){if(t.length===0)return{maxIndex:-1,maxValue:NaN};let e=t[0],n=0;for(let r=1;r<t.length;r+=1)t[r]>e&&(n=r,e=t[r]);return{maxIndex:n,maxValue:e}}function Oh(t){return t.reduce((e,n)=>Math.max(e,ua(n).maxValue),0)}var Nh=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:{}}}},Ih=class ha 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 ha({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})}}},Rh=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")})}},$h=class extends Zi{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})}},jh=class extends Zi{constructor(t){super(t??{})}embedDocuments(t){return Promise.resolve(t.map(()=>[.1,.2,.3,.4]))}embedQuery(t){return Promise.resolve([.1,.2,.3,.4])}},Lh=class extends zi{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}},Dh=class extends zi{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)}},Fh=class extends co{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async addUserMessage(t){this.messages.push(new fe(t))}async addAIMessage(t){this.messages.push(new O(t))}async clear(){this.messages=[]}},Uh=class extends Ps{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(t){this.messages.push(t)}async getMessages(){return this.messages}},Vh=class extends Cs{name="fake_tracer";runs=[];constructor(){super()}persistRun(t){return this.runs.push(t),Promise.resolve()}},Bh=class extends Vl{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(t){return t.split(",").map(e=>e.trim())}},zh=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}},Wh=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}}},Hh=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)}},Gh=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}},Kh=class da extends Ns{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(e,{similarity:n,...r}={}){super(e,r),this.similarity=n??la}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 da.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)}},fa={};q(fa,{FakeChatMessageHistory:()=>Fh,FakeChatModel:()=>Nh,FakeEmbeddings:()=>jh,FakeLLM:()=>Lh,FakeListChatMessageHistory:()=>Uh,FakeListChatModel:()=>Rh,FakeRetriever:()=>zh,FakeRunnable:()=>Wh,FakeSplitIntoListParser:()=>Bh,FakeStreamingChatModel:()=>Ih,FakeStreamingLLM:()=>Dh,FakeTool:()=>Hh,FakeTracer:()=>Vh,FakeVectorStore:()=>Kh,SingleRunExtractor:()=>Gh,SyntheticEmbeddings:()=>$h});var pa={};q(pa,{agents:()=>_u,caches:()=>Zl,callbacks__base:()=>kc,callbacks__manager:()=>Tc,callbacks__promises:()=>Cc,chat_history:()=>lo,document_loaders__base:()=>wo,document_loaders__langsmith:()=>_o,documents:()=>So,embeddings:()=>Kc,example_selectors:()=>Eo,index:()=>Su,indexing:()=>No,language_models__base:()=>Xl,language_models__chat_models:()=>Yl,language_models__llms:()=>Nl,load__serializable:()=>Sc,memory:()=>uo,messages:()=>vc,messages__tool:()=>_c,output_parsers:()=>ql,output_parsers__openai_functions:()=>$o,output_parsers__openai_tools:()=>Ol,outputs:()=>bc,prompt_values:()=>Jl,prompts:()=>Jo,retrievers:()=>go,retrievers__document_compressors:()=>qo,runnables:()=>Kl,runnables__graph:()=>wc,singletons:()=>yc,stores:()=>fo,structured_query:()=>na,tools:()=>Pl,tracers__base:()=>gc,tracers__console:()=>mc,tracers__log_stream:()=>pc,tracers__run_collector:()=>ra,tracers__tracer_langchain:()=>fc,types__stream:()=>wh,utils__async_caller:()=>dc,utils__chunk_array:()=>Gc,utils__env:()=>hc,utils__event_source_parse:()=>sa,utils__format:()=>Ch,utils__function_calling:()=>Gl,utils__hash:()=>Hl,utils__json_patch:()=>Wl,utils__json_schema:()=>uc,utils__math:()=>ca,utils__stream:()=>cc,utils__testing:()=>fa,utils__tiktoken:()=>zl,utils__types:()=>Bl,vectorstores:()=>yo});function Jh(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=Ec(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:pa,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(bu.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"&&xc(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(Mc(S,Ac,Jh(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 qh(t,e){const n=JSON.parse(t);return Ln.call({...e},n)}function Yh(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(Yh(e))return qh(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 Xh(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 Zh=class{_dumps(t){return new TextEncoder().encode(yu(t,(n,r)=>Xh(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 ma(t){if(typeof t!="object"||t===null)return t;const e=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=ma(t[n]));return e}function ga(){return{v:4,id:ao(-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:ma(t.versions_seen)}}function ya(t,e){return typeof t=="number"&&typeof e=="number"?Math.sign(t-e):String(t).localeCompare(String(e))}function Qh(...t){return t.reduce((e,n,r)=>r===0?n:ya(e,n)>=0?e:n)}const ed={[du]:-1,[Nn]:-2,[fu]:-3,[pu]:-4};var Xt=class extends Error{constructor(t){super(t),this.name="InvalidNamespaceError"}};function td(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 nd=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){td(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 rd=t=>"lg_name"in t&&t.lg_name==="AsyncBatchedStore"?t.store:t;var sd=class extends nd{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(t){super(),this.store=rd(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]"}}},id=class{serde=new Zh;constructor(t){this.serde=t||this.serde}},od=class wa 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 wa({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 ad{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 ld(){je.initializeGlobalInstance(new ad)}var ut=class extends Error{lc_error_code;constructor(t,e){let n=t??"";e?.lc_error_code&&(n=`${n}
|
|
31
|
+
|
|
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}},ba=class extends ut{get is_bubble_up(){return!0}},cd=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"}},vt=class extends ba{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"}},va=class extends ba{command;constructor(t){super(),this.name="ParentCommand",this.command=t}static get unminifiable_name(){return"ParentCommand"}};function ud(t){return t!==void 0&&t.name===va.unminifiable_name}function Fn(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 pi=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"}},hd=class extends ut{constructor(t,e){super(t,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};function Sa(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];Sa(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??ao(n),ts:new Date().toISOString(),channel_values:s,channel_versions:t.channel_versions,versions_seen:t.versions_seen}}var ls=class Ca 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 Ca(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}},dd=class ka extends ht{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(e){const n=new ka;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}},fd=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 fd(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__",pd="__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",md="__pregel_resume_value",Un="__pregel_resume_map",qe="__pregel_scratchpad",Vn="__pregel_previous",Ea="__pregel_durability",hs="checkpoint_id",ke="checkpoint_ns",gd="__pregel_node_finished",ge="checkpoint_map",mi="__pregel_abort_signals",$="__interrupt__",le="__resume__",Gs="__no_writes__",Bt="__return__",Nr="__previous__",G="langsmith:hidden",yd="langsmith:nostream",gi="__self__",ye="__pregel_tasks",he="__pregel_push",Bn="__pregel_pull",we="00000000-0000-0000-0000-000000000000",wd=[G,Ne,$,le,oe,Gs,Je,ot,H,Ea,ir,Be,sn,Hs,md,qe,Vn,ge,ke,hs],J="|",De=":",yi=Symbol.for("langgraph.command");var bd=class{[yi];constructor(t){this[yi]=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 xa(t){return!t||typeof t!="object"||!($ in t)?!1:Array.isArray(t[$])}var K=class extends bd{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 _d=["tags","metadata","callbacks","configurable"],vd=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],Sd=25;function Ma(...t){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:Sd,configurable:{}},n=je.getRunnableConfig();if(n!==void 0){for(const[r,s]of Object.entries(n))if(s!==void 0)if(_d.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&&vd.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 Cd(){return je.getRunnableConfig()}function Ir(t){return t.split(J).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(De)[0]).join(J)}function Td(t){const e=t.split(J);for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join(J)}const k=t=>BigInt(t),D=(t,e=0)=>new DataView(t.buffer,t.byteOffset+e,t.byteLength-e),Aa=k("0x9E3779B1"),Pa=k("0x85EBCA77"),kd=k("0xC2B2AE3D"),Ze=k("0x9E3779B185EBCA87"),lt=k("0xC2B2AE3D27D4EB4F"),Oa=k("0x165667B19E3779F9"),Ks=k("0x85EBCA77C2B2AE63"),Ed=k("0x27D4EB2F165667C5"),xd=k("0x165667919E3779F9"),Md=k("0x9FB21C651E98DF25"),Ad=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)},Te=Ad("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),St=(k(1)<<k(128))-k(1),N=(k(1)<<k(64))-k(1),or=(k(1)<<k(32))-k(1),Ie=64,Na=Ie/8,Pd=8,Tn=4;function zt(t){if(!t)throw new Error("Assert failed")}function Od(t){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,t,!0),e.getBigUint64(0,!1)}function Nd(t){let e=t;return e=(e&k(65535))<<k(16)|(e&k(4294901760))>>k(16),e=(e&k(16711935))<<k(8)|(e&k(4278255360))>>k(8),e}function Id(t,e){return(t&or)*(e&or)&N}function Rd(t,e){return(t<<e|t>>k(32)-e)&or}function Ia(t,e,n){for(let r=0;r<Na;r+=1){const s=e.getBigUint64(r*8,!0),i=s^n.getBigUint64(r*8,!0);t[r^1]+=s,t[r]+=Id(i,i>>k(32))}return t}function wi(t,e,n,r){for(let s=0;s<r;s+=1)Ia(t,D(e,s*Ie),D(n,s*8));return t}function $d(t,e){for(let n=0;n<Na;n+=1){const r=e.getBigUint64(n*8,!0);let s=t[n];s=fs(s,k(47)),s^=r,s*=Aa,t[n]=s&N}return t}function kn(t,e){return Ra(t[0]^e.getBigUint64(0,!0),t[1]^e.getBigUint64(Pd,!0))}function bi(t,e,n){let r=n;return r+=kn(t.slice(0),D(e,0*Tn)),r+=kn(t.slice(2),D(e,4*Tn)),r+=kn(t.slice(4),D(e,8*Tn)),r+=kn(t.slice(6),D(e,12*Tn)),xe(r&N)}function jd(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=wi(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=wi(i,D(e,l*a),n,c),i=r(i,D(e,e.byteLength-Ie),D(n,n.byteLength-Ie-7))}return i}function Ld(t,e){let n=new BigUint64Array([kd,Ze,lt,Oa,Ks,Pa,Ed,Aa]);zt(t.byteLength>128),n=jd(n,t,e,Ia,$d),zt(n.length*8===64);{const r=bi(n,D(e,11),k(t.byteLength)*Ze&N);return bi(n,D(e,e.byteLength-Ie-11),~(k(t.byteLength)*lt)&N)<<k(64)|r}}function Ra(t,e){const n=t*e&St;return n&N^n>>k(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>>k(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<<k(64)|i}function xe(t){let e=t;return e^=e>>k(37),e*=xd,e&=N,e^=e>>k(32),e}function ar(t){let e=t;return e^=e>>k(33),e*=lt,e&=N,e^=e>>k(29),e*=Oa,e&=N,e^=e>>k(32),e}function Dd(t,e,n){const r=t.byteLength;zt(r>0&&r<=3);const s=k(t.getUint8(r-1))|k(r<<8)|k(t.getUint8(0)<<16)|k(t.getUint8(r>>1)<<24),i=(k(e.getUint32(0,!0))^k(e.getUint32(4,!0)))+n,o=(s^i)&N,a=(k(e.getUint32(8,!0))^k(e.getUint32(12,!0)))-n,l=(Rd(Nd(s),k(13))^a)&N;return(ar(l)&N)<<k(64)|ar(o)}function fs(t,e){return t^t>>e}function Fd(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=k(s)|k(i)<<k(32),a=(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+n&N;let c=(o^a)*(Ze+(k(r)<<k(2)))&St;return c+=(c&N)<<k(65),c&=St,c^=c>>k(67),fs(fs(c&N,k(35))*Md&N,k(28))|xe(c>>k(64))<<k(64)}}function Ud(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)+(k(r-1)<<k(54));l=l&(St^N)|c,a^=i,l+=a+(a&or)*(Pa-k(1))<<k(64),l&=St,l^=Od(l>>k(64));let u=(l&N)*lt;return u+=(l>>k(64))*lt<<k(64),u&=St,xe(u&N)|xe(u>>k(64))<<k(64)}}function Vd(t,e){const n=t.byteLength;return zt(n<=16),n>8?Ud(t,Te,e):n>=4?Fd(t,Te,e):n>0?Dd(t,Te,e):ar(e^Te.getBigUint64(64,!0)^Te.getBigUint64(72,!0))|ar(e^Te.getBigUint64(80,!0)^Te.getBigUint64(88,!0))<<k(64)}function ps(t){return~t+k(1)&N}function Bd(t,e,n){let r=k(t.byteLength)*Ze&N,s=k(t.byteLength-1)/k(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-=k(1)}let i=r+(r>>k(64))&N;i=xe(i);let o=(r&N)*Ze+(r>>k(64))*Ks+(k(t.byteLength)-n&N)*lt;return o&=N,o=ps(xe(o)),i|o<<k(64)}function zd(t,e,n){let r=k(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>>k(64))<<k(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>>k(64))&N;s=xe(s);let i=(r&N)*Ze+(r>>k(64))*Ks+(k(t.byteLength)-n&N)*lt;return i&=N,i=ps(xe(i)),s|i<<k(64)}function et(t,e=k(0)){const n=new TextEncoder,r=D(typeof t=="string"?n.encode(t):t),s=r.byteLength,i=o=>o.toString(16).padStart(32,"0");return s<=16?i(Vd(r,e)):s<=128?i(Bd(r,Te,e)):s<=240?i(zd(r,Te,e)):i(Ld(r,Te))}function $a(t){return/^[0-9a-f]{32}$/.test(t)}function ja(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[ke]?.split(J),a=o?et(o.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,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=Ma(n),i=Re(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*Ue(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 Wd(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 Rr=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=>$r(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($r(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($r(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(Wd(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||Rr in e&&!!e[Rr]}static registerWriter(e){return Object.defineProperty(e,Rr,{value:!0})}};function Wn(t){return t!==void 0&&typeof t.channel=="string"}function $r(t){return t!==void 0&&!Wn(t)&&ee.isRunnable(t.mapper)}var Hd=class La extends dt{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(e,n,r=!1){super({func:(s,i)=>La.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 Ql;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:Ft(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 Gd(t){return"steps"in t&&Array.isArray(t.steps)}function Js(t){return"lg_is_pregel"in t&&t.lg_is_pregel===!0}function Da(t){const e=[t];for(const n of e){if(Js(n))return n;Gd(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*Kd(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($a))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*Jd(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]!==$);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 qd(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 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 Yd=(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 Xd=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 Zd(t){return typeof t=="object"&&t!==null&&"__lg_type"in t&&t.__lg_type==="call"}function Qd(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 ef=t=>t!==void 0?t+1:1;function tf(t,e){if(e==null)return!1;for(const n of t)if(e[n])return!0;return!1}function nf(t){let e;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e==null?e=t[n]:e=Qh(e,t[n]));return e}function xn(t,e,n){const r=qs(t.channel_versions),s=t.versions_seen[$]??{};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 rf=new Set([Gs,he,le,$,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=nf(t.channel_versions);const l=new Set(n.flatMap(d=>d.triggers).filter(d=>!wd.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)rf.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&&!tf(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*sf(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 sf(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&&Zd(t[t.length-1])){const f=t[t.length-1],g=Qd(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],_={langgraph_step:l,langgraph_node:f.name,langgraph_triggers:p,langgraph_path:w,langgraph_checkpoint_ns:m};if(o){const T=[];return{name:f.name,input:f.input,proc:g,writes:T,config:rn(Re(i,{metadata:_,store:a.store??i.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:S,[Je]:b=>Lr(v=>T.push(...v),r,b),[ot]:(b,v=!1)=>Gn(e,s,{name:f.name,writes:T,triggers:p,path:w},b,v),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[qe]:Dr({pendingWrites:n??[],taskId:S,currentTaskInput:f.input,resumeMap:i.configurable?.[Un],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 _={langgraph_step:l,langgraph_node:p.node,langgraph_triggers:C,langgraph_path:t.slice(0,3),langgraph_checkpoint_ns:w};if(o){const T=r[p.node],x=T.getNode();if(x!==void 0){T.metadata!==void 0&&(_={..._,...T.metadata});const b=[];return{name:p.node,input:p.args,proc:x,subgraphs:T.subgraphs,writes:b,config:rn(Re(i,{metadata:_,tags:T.tags,store:a.store??i.store}),{runName:p.node,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:m,[Je]:v=>Lr(M=>b.push(...M),r,v),[ot]:(v,M=!1)=>Gn(e,s,{name:p.node,writes:b,triggers:C,path:t},v,M),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[qe]:Dr({pendingWrites:n??[],taskId:m,currentTaskInput:p.args,resumeMap:i.configurable?.[Un],namespaceHash:et(w)}),[Vn]:e.channel_values[Nr],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:C,retry_policy:T.retryPolicy,cache_key:T.cachePolicy?{key:et((T.cachePolicy.keyFunc??JSON.stringify)([p.args])),ns:[Or,T.name??"__dynamic__",p.node],ttl:T.cachePolicy.ttl}:void 0,id:m,path:t,writers:T.getWriters()}}}else return{id:m,name:p.node,interrupts:[],path:t}}else if(t[0]===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(T=>T[0]===w&&T[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=of(g,s,o);if(m===void 0)return;const w=d===""?f:`${d}${J}${f}`,_=gt(JSON.stringify([w,l.toString(),f,Bn,[S]]),e.id),T=`${w}${De}${_}`;let x={langgraph_step:l,langgraph_node:f,langgraph_triggers:[S],langgraph_path:t,langgraph_checkpoint_ns:T};if(o){const b=g.getNode();if(b!==void 0){g.metadata!==void 0&&(x={...x,...g.metadata});const v=[];return{name:f,input:m,proc:b,subgraphs:g.subgraphs,writes:v,config:rn(Re(i,{metadata:x,tags:g.tags,store:a.store??i.store}),{runName:f,callbacks:u?.getChild(`graph:step:${l}`),configurable:{[sn]:_,[Je]:M=>Lr(E=>{v.push(...E)},r,M),[ot]:(M,E=!1)=>Gn(e,s,{name:f,writes:v,triggers:[S],path:t},M,E),[H]:c??h[H],[ge]:{...h[ge],[d]:e.id},[qe]:Dr({pendingWrites:n??[],taskId:_,currentTaskInput:m,resumeMap:i.configurable?.[Un],namespaceHash:et(T)}),[Vn]:e.channel_values[Nr],checkpoint_id:void 0,checkpoint_ns:T}}),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:_,path:t,writers:g.getWriters()}}}else return{id:_,name:f,interrupts:[],path:t}}}}function of(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*vi(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===$).map(([,l])=>l);yield{id:e,name:n,input:r,triggers:i,interrupts:a}}}function af(t){return typeof t!="object"||t===null?!1:"$writes"in t&&Array.isArray(t.$writes)}function Ua(t){const e={};for(const[n,r]of t){const s=String(n);if(s in e){const i=af(e[s])?e[s].$writes:[e[s]];i.push(r),e[s]={$writes:i}}else e[s]=r}return e}function*lf(t,e){for(const[{id:n,name:r,config:s},i]of t)s?.tags?.includes(G)||(yield{id:n,name:r,result:Ua(i.filter(([o])=>Array.isArray(e)?e.includes(o):o===e)),interrupts:i.filter(o=>o[0]===$).map(o=>o[1])})}function*cf(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(Da))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:Va(s,i,u,a),parentConfig:o?l(o):void 0}}function Va(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===$).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?Ua(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 uf(t,e,n){console.log([`${yn(gn.blue,`[${t}:checkpoint]`)}`,`\x1B[1m State at the end of step ${t}:\x1B[0m
|
|
34
|
+
`,JSON.stringify(ct(e,n),null,2)].join(""))}function Ba(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
|
+
`,e.map(r=>`- ${yn(gn.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
|
|
36
|
+
`)].join(""))}function hf(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 Si=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}},za=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 df(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 ff(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 Fr(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 Ci(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:Fr(t.config),parent_checkpoint:Fr(t.parentConfig),config:Ci(t.config),parent_config:Ci(t.parentConfig),tasks:t.tasks.map(n=>{if(Ys(n.state)){const r=Fr(n.state);if(r!=null){const s={...n,checkpoint:r};return delete s.state,s}}return n})};return delete e.parentConfig,e}function pf(t){const e=new TextEncoder;return new ReadableStream({async start(n){const r=s=>{n.enqueue(e.encode(`event: ${s.event}
|
|
39
|
+
data: ${df(s.data)}
|
|
40
|
+
|
|
41
|
+
`))};try{for await(const s of t){const[i,o,a]=s;let l=a;if(o==="debug"){const u=a;u.type==="checkpoint"&&(l={...u,payload: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:ff(s)})}n.close()}})}const Mn=Symbol.for("INPUT_DONE"),Ur=Symbol.for("INPUT_RESUMING"),mf=25;function gf(...t){return new za({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 yf=class extends id{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}},wf=class Wa{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===Ur,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=ef,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 yf(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=gf(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=_e(n,{[ke]:[n.configurable[ke],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=_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:ga(),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??mf)+1,S={...h.channel_versions},m=e.store?new sd(e.store):void 0;return m&&await m.start(),new Wa({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 ed)&&(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=_e(this.checkpointConfig,{[ke]: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]===$||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]===$){if(s.path?.[0]===he&&s.path?.at(-1)===!0)return;const i=n.filter(o=>o[0]===$).flatMap(o=>o[1]);this._emit([["updates",{[$]:i}],["values",{[$]:i}]])}else n[0][0]!==oe&&this._emit(en(Ue(Jd(this.outputKeys,[[s,n]],r),"updates")));r||this._emit(en(Ue(lf([[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,Ur].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(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(Ue(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 vt;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(Ue(cf(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[i,o,a]of this.checkpointPendingWrites){if(o===oe||o===$||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 vt;const s=await ze(Ue(vi(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(Ue(jr(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),st(e)&&!e.interrupts.length&&this._emit([["updates",{[$]:[]}],["values",{[$]:[]}]])),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(Ue(vi([s]),"tasks"))),this.debug&&Ba(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($a)&&(this.config.configurable??={},this.config.configurable[Un]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const a={};for(const[l,c,u]of Kd(this.input,this.checkpointPendingWrites))a[l]??=[],a[l].push([c,u]);if(Object.keys(a).length===0)throw new pi("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[$]={...this.checkpoint.versions_seen[$],[a]:l}}const o=await ze(Ue(jr(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=Ur;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 pi(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=_e(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=_e(this.checkpointConfig,{[ke]: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=_e(this.checkpointConfig,{[ke]: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===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 bf(t){return Oe(t?.message)}var _f=class extends Pc{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&&(Oc(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(yd)&&!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&&(bf(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)||ni(l))&&l.id!==void 0)this.seen[l.id]=l;else if(Array.isArray(l))for(const c of l)(Oe(c)||ni(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 vf=500,Sf=2,Cf=128e3,Tf=3,kf=[400,401,402,403,404,405,406,407,409],Ef=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&&kf.includes(+e)||t?.error?.code==="insufficient_quota")};async function Ha(t,e,n,r){const s=t.retry_policy??e;let i=s!==void 0?s.initialInterval??vf:0,o=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,ud(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=Td(g);a.command=new K({...a.command,graph:C})}}if(Fn(a)||s===void 0||(o+=1,o>=(s.maxAttempts??Tf))||!(s.retryOn??Ef)(a))break;i=Math.min(s.maxInterval??Cf,i*(s.backoffFactor??Sf));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=_e(c,{[Be]:!0})}}return{task:t,result:l,error:a,signalAborted:r?.aborted}}const ys=Symbol.for("promiseAdded");function xf(){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 Mf=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)||Fn(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)||Fn(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:t,stepTimeoutSignal:e,signal:n}){const r=this.loop.config.configurable?.[mi]??{},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=_e(this.loop.config,{[mi]:l}),{signals:l,disposeCombinedSignal:a}}async*_executeTasksWithRetry(t,e){const{retryPolicy:n,maxConcurrency:r,signals:s}=e??{},i=xf(),o={},a={executingTasksMap:o,barrier:i,retryPolicy:n,scheduleTask:async(d,f,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]=Ha(f,n,{[Hs]:Ga?.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=>[$,s]),r=t.writes.filter(s=>s[0]===le);r.length&&n.push(...r),this.loop.putWrites(t.id,n)}}else Fn(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 Ga(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 Xd({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=Ha(c,i.retry,{[Hs]:Ga.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 Af({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===$)throw new Ae(`"Node name ${$} 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 ki(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 Pf=class Ka 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 Ka({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}},Of=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:Ft(s)}):n.push({channel:r,value:s,skipNone:!1});return new se(n)}},Nf=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)}},If=class extends Nf{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 Pf({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(){Af({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=Da(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,$,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:Va(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=Re(this.config,t),i=await n.getTuple(t);return await this._prepareStateSnapshot({config:s,saved:i,subgraphCheckpointer:e?.subgraphs?n:void 0,applyPendingWrites:!t.configurable?.checkpoint_id})}async*getStateHistory(t,e){const n=t.configurable?.[H]??this.checkpointer;if(!n)throw new 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=Re(this.config,t,{configurable:{checkpoint_ns:r}});for await(const i of n.list(s,e))yield this._prepareStateSnapshot({config:i.config,saved:i})}async bulkUpdateState(t,e){const n=t.configurable?.[H]??this.checkpointer;if(!n)throw new 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?Re(this.config,o):o,c=await n.getTuple(l),u=c!==void 0?rr(c.checkpoint):ga(),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 v=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,$,Nn].includes(P)||E in v&&v[E].writes.push([P,I]);ue(u,S,Object.values(v),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===pd){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),v=tt(u,void 0,d),M=await n.put(c.parentConfig??ft(c.config,{checkpoint_id:void 0}),v,{source:"fork",step:d+1,parents:c.metadata?.parents??{}},{});if(b(p)){const E=bt(v,c.pendingWrites,this.nodes,S,M,!1,{step:d+2}),P=Object.values(E).reduce((V,{name:X,id:_r})=>(V[X]??=[],V[X].push({id:_r}),V),{}),I=p.reduce((V,X)=>{const[_r,Yt]=X;V[Yt]??=[];const _l=V[Yt].length,vl=P[Yt]?.[_l]?.id;return V[Yt].push({values:_r,asNode:Yt,taskId:vl}),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 v=c?.metadata?.step!=null?c.metadata.step+1:-1,M=await n.put(f,tt(u,S,v),{source:"input",step:v,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}),v=(c.pendingWrites??[]).filter(E=>E[0]===we).map(E=>E.slice(1));v.length>0&&ue(c.checkpoint,S,[{name:Ne,writes:v,triggers:[]}],void 0,this.triggerToNodes);for(const[E,P,I]of c.pendingWrites)[oe,$,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:v,taskId:M}=a[0];if(v===void 0&&Object.keys(this.nodes).length===1)[v]=Object.keys(this.nodes);else if(v===void 0&&m===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(v=this.inputChannels);else if(v===void 0){const E=Object.entries(u.versions_seen).map(([P,I])=>Object.values(I).map(V=>[V,P])).flat().filter(([P,I])=>I!==$).sort(([P],[I])=>ya(P,I));E&&(E.length===1?v=E[0][1]:E[E.length-1][0]!==E[E.length-2][0]&&(v=E[E.length-1][1]))}if(v===void 0)throw new B('Ambiguous update, specify "asNode"');w.push({values:b,asNode:v,taskId:M})}else for(const{asNode:b,values:v,taskId:M}of a){if(b==null)throw new B('"asNode" is required when applying multiple updates');w.push({values:v,asNode:b,taskId:M})}const _=[];for(const{asNode:b,values:v,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()}"`);_.push({name:b,input:v,proc:E.length>1?Xe.from(E,{omitSequenceTags:!0}):E[0],writes:[],triggers:[$],id:M??gt($,u.id),writers:[]})}for(const b of _)await b.proc.invoke(b.input,rn({...l,store:l?.store??this.store},{runName:l.runName??`${this.getName()}UpdateState`,configurable:{[Je]:v=>b.writes.push(...v),[ot]:(v,M=!1)=>Gn(u,S,b,v,M)}}));for(const b of _){const v=b.writes.filter(M=>M[0]!==he);c!==void 0&&v.length>0&&await n.putWrites(f,v,b.id)}ue(u,S,_,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const T=Hn(h,u.channel_versions),x=await n.put(f,tt(u,S,d+1),{source:"update",step:d+1,parents:c?.metadata?.parents??{}},T);for(const b of _){const v=b.writes.filter(M=>M[0]===he);v.length>0&&await n.putWrites(x,v,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:ki(u,this.channels);let h=r;h===void 0?h=this.inputChannels:ki(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?.[Ea]??"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 Si(e?.encoding==="text/event-stream"?pf(s):s,n)}streamEvents(t,e,n){const r=new AbortController,s={recursionLimit:this.config?.recursionLimit,...e,callbacks:Yd(this.config?.callbacks,e?.callbacks),signal:lr(e?.signal,r.signal).signal};return new Si(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=Ma(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 za({modes:new Set(c)});if(this.checkpointer===!0){h.configurable??={};const P=h.configurable[ke]??"";h.configurable[ke]=P.split(J).map(I=>I.split(De)[0]).join(J)}if(c.includes("messages")){const P=new _f(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=Cd()?.configurable?.[ke]?.split(J).slice(0,-1);w.push([I??[],"custom",P])},h.interrupt??=this.userInterrupt??ja;const T=await(await Nc(h))?.handleChainStart(this.toJSON(),qd(t,"input"),o,void 0,void 0,void 0,h?.runName??this.getName()),x=zs(this.channels);let b,v;const E=(async()=>{try{b=await wf.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:T,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:m});const P=new Mf({loop:b,nodeFinished:h.configurable?.[gd]});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){v=P}finally{try{b&&(await b.store?.stop(),await b.cache?.stop()),await Promise.all(b?.checkpointerPromises??[])}catch(P){v=v??P}v?w.error(v):w.close()}})();try{for await(const P of w){if(P===void 0)throw new Error("Data structure error.");const[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 T?.handleChainError(v),P}finally{await E}await T?.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"?xa(l)?o.push(l[$]):a=l:s.push(l);if(n==="values"){if(o.length>0){const l=o.flat(1);if(a==null)return{[$]:l};if(typeof a=="object")return{...a,[$]: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&&uf(e.checkpointMetadata.step,e.channels,this.streamChannelsList),r&&Ba(e.step,Object.values(e.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,a)=>{r&&hf(o,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(e.status==="out_of_steps")throw new cd([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(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 Ja extends ht{lc_graph_name="EphemeralValue";guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(e){const n=new Ja(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}},qa=class{path;ends;constructor(t){ee.isRunnable(t.path)?this.path=t.path:this.path=Ft(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}},Rf=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=Ft(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=Ft(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 qa(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 Ya({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 hd([`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}},Ya=class extends If{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]=Of.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 ri,r={[L]:n.addNode({schema:ve()},L)},s={};let i={};e&&(i=Object.fromEntries((await ze(this.getSubgraphsAsync())).filter(l=>Ei(l[1]))));function o(l,c,u,h=!1){if(c===A&&s[A]===void 0&&(s[A]=n.addNode({schema:ve()},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,_){if(w!==void 0&&!si(w))return w;if(S(_))try{let T=_.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return _.getName()}else return _.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 ri,r={[L]:n.addNode({schema:ve()},L)},s={};let i={};e&&(i=Object.fromEntries(en(this.getSubgraphs()).filter(l=>Ei(l[1]))));function o(l,c,u,h=!1){return c===A&&s[A]===void 0&&(s[A]=n.addNode({schema:ve()},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,_){if(w!==void 0&&!si(w))return w;if(S(_))try{let T=_.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return _.getName()}else return _.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 Ei(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 $f=class Xa extends ht{lc_graph_name="NamedBarrierValue";names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(e){const n=new Xa(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)}},jf=class Za 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 Za(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 Lf="lg:";var Df=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=ii(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(ii(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(`${Lf}${h}`)}return[o,c]});s=Ic(t,Object.fromEntries(i)),Rc(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=ks(s)),r.set(t,s),this._extensionCache.set(n,r),s}};const Ht=new Df;function Gt(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 Ht.extend(n,()=>e),n}else return Ht.extend(t,()=>e),t}const $e="__root__",ws=Symbol.for("langgraph.state.partial");var Ff=class extends Rf{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=Ht;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(t,e){if(super(),Gf(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(Hf(t))this._schemaDefinition=t.input.spec,this._inputDefinition=t.input.spec,this._outputDefinition=t.output.spec;else if(Wf(t))this._schemaDefinition=t.stateSchema.spec,this._inputDefinition=t.input?.spec??this._schemaDefinition,this._outputDefinition=t.output?.spec??this._schemaDefinition;else if(Bf(t)||xi(t)){const r=xi(t)?t.spec:t;this._schemaDefinition=r}else if(zf(t)){const r=Uf(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=Ft(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]===$e?$e:a,c=Object.keys(this.channels),u=c.length===1&&c[0]===$e?$e:c,h=this._interrupt,d=new Vf({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,gi,Mi(),{withReader:!1});for(const[f]of Object.entries(this.nodes))d.attachBranch(f,gi,Mi(),{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 Uf(t){const e={};for(const[n,r]of Object.entries(t))e[n]=us(r);return e}var Vf=class extends Ya{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([$e,c]);return l}else if(a!=null)return[[$e,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]===$e?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&&$e in l,u=`branch:to:${t}`;this.channels[u]=e?.defer?new dd: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 jf(new Set(t)):new $f(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=>Hd.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 ks(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 xa(t)}async _validateContext(t){const e=this.builder._configRuntimeSchema;return de(e)&&Ge(e,t),t}};function Bf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0&&Object.values(t).every(e=>typeof e=="function"||Sa(e))}function xi(t){return typeof t=="object"&&t!==null&&"lc_graph_name"in t&&t.lc_graph_name==="AnnotationRoot"}function zf(t){return typeof t=="object"&&t!==null&&t.channels!==void 0}function Wf(t){return typeof t=="object"&&t!==null&&t.stateSchema!==void 0}function Hf(t){return typeof t=="object"&&t!==null&&t.stateSchema===void 0&&t.input!==void 0&&t.output!==void 0}function Gf(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 Kf(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 va(r);pe(r.goto)||typeof r.goto=="string"?n.push(r.goto):Array.isArray(r.goto)&&n.push(...r.goto)}return n}function Mi(){const t=new dt({func:Kf,tags:[G],trace:!1,recurse:!1,name:"<control_branch>"});return new qa({path:t})}const Qa="__remove_all__";function el(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===Qa&&(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:el,default:()=>[]})});const cr={reducer:{fn:el},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]};z({messages:Gt(ae(),cr)});ld();const bs=Symbol.for("langgraph-zod");bs in globalThis||(globalThis[bs]=new WeakSet);function Ai(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=Ts(n);return Gt(n,{default:i,reducer:{schema:s,fn:r}})}}}}),e.add(t))}try{Ai($c.prototype),Ai(Sl.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 Jf=class extends Cl{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 Jf(Ht);function qf(t=!0,e,n=[]){const r={messages:Gt(ae(),cr),jumpTo:Me([_t("model_request"),_t("tools"),_t("end"),jc()]).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 Pi="prompt",Vr=/<name>(.*?)<\/name>/s,Br=/<content>(.*?)<\/content>/s;function Yf(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 Xf(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 Oi(t){return Ms(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}const zr=(t,e,n={})=>{if(Oi(t))return t.bindTools(e,n);if(Ee.isRunnableBinding(t)&&Oi(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 tl(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 _s(t){return!!(O.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Zf(t){let e;if(t==null)e=Dt.from(n=>n.messages).withConfig({runName:Pi});else if(typeof t=="string"){const n=new be(t);e=Dt.from(r=>[n,...r.messages??[]]).withConfig({runName:Pi})}else throw new Error(`Got unexpected type for 'prompt': ${typeof t}`);return e}async function Qf(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 ep(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 tp(t){const e=t.filter(n=>n.wrapToolCall);if(e.length!==0)return ep(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(!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 np(t,e){const n={};for(const r of t){if(!r.stateSchema)continue;const s=Lc(r.stateSchema,a=>a.startsWith("_")),i=await Dc(s,e);if(i.success){Object.assign(n,i.data);continue}const o=i.error.issues.filter(a=>a.code==="invalid_type"&&a.message==="Required").map(a=>` - ${a.path.join(".")}: ${a.message}`).join(`
|
|
44
|
+
`);throw new Error(`Middleware "${r.name}" has required state fields that must be initialized:
|
|
45
|
+
${o}
|
|
46
|
+
|
|
47
|
+
To fix this, either:
|
|
48
|
+
1. Provide default values in your middleware's state schema using .default():
|
|
49
|
+
stateSchema: z.object({
|
|
50
|
+
myField: z.string().default("default value")
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
2. Or make the fields optional using .optional():
|
|
54
|
+
stateSchema: z.object({
|
|
55
|
+
myField: z.string().optional()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
3. Or ensure you pass these values when invoking the agent:
|
|
59
|
+
agent.invoke({
|
|
60
|
+
messages: [...],
|
|
61
|
+
${i.error.issues[0]?.path.join(".")}: "value"
|
|
62
|
+
})`)}return n}function rp(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 nl(...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=Re(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 sp(t,e){let n,r;if(e==="inline")n=Yf,r=Xf;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 ip=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=io(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&&F.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=>{tl(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=nl(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(ks(u.stateSchema),t):{},...g(),messages:t.messages},runtime:S},w=async _=>{const T=_.tools??[],x=T.filter(v=>W(v)&&!this.#e.toolClasses.some(M=>M.name===v.name));if(x.length>0)throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${f.name}": ${x.map(v=>v.name).join(", ")}. This is not supported.`);const b=T.filter(v=>W(v)&&this.#e.toolClasses.every(M=>M!==v));if(b.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${f.name}": ${b.map(v=>v.name).join(", ")}. This is not supported.`);return d(_)};if(!f.wrapModelCall)return w(m);try{const _=await f.wrapModelCall(m,w);if(!O.isInstance(_))throw new Error(`Invalid response from "wrapModelCall" in middleware "${f.name}": expected AIMessage, got ${typeof _}`);return _}catch(_){throw _ instanceof Error&&!_.message.includes(`middleware "${f.name}"`)&&(_.message=`Error in middleware "${f.name}": ${_.message}`),_}}}}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 F({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 F({content:t.message,tool_call_id:i})]},goto:"model"});if(typeof s=="string")return new K({update:{messages:[e,new F({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 F({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&&_s(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 Qf(t,i,{...r,...e?.modelSettings??{},tool_choice:o});return Zf(e?.systemPrompt??this.#e.systemPrompt).pipe(this.#e.includeAgentName==="inline"?sp(a,this.#e.includeAgentName):a)}getState(){const t=super.getState(),e=t&&!(t instanceof K)?t:{};return{messages:[],...e}}};const rl=t=>Array.isArray(t)&&t.every(nn.isInstance),op=t=>typeof t=="object"&&t!=null&&"messages"in t&&rl(t.messages),ap=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function lp(t,e){return t instanceof xs?new F({content:t.message,tool_call_id:e.id,name:e.name}):new F({content:`${t}
|
|
63
|
+
Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var cp=class extends Xs{tools;trace=!1;signal;handleToolErrors=lp;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&&F.isInstance(r))return r;throw t}else if(this.handleToolErrors)return new F({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:nl(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 Fc?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(ap(t)){const{lg_tool_call:i,jumpTo:o,...a}=t;n=[await this.runTool(t.lg_tool_call,e,a)]}else{let i;if(rl(t))i=t;else if(op(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=>up(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 up(t){return t instanceof re}var hp=class{},dp=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 dp,{...s,context:Object.freeze(Object.assign(new hp,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:rp(this.middleware.stateSchema)}}},fp=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)}},pp=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)}},mp=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)}},gp=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)}},yp=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}},wp=class{#e;#n="v2";#s;#t=new yp;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"&&tl(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=qf(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),o=new Ff(s,this.options.contextSchema),a=[],l=[],c=[],u=[],h=[];this.#s=new ip({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,_,T,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 fp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,w);const v=`${b.name}.before_agent`;a.push({index:m,name:v,allowed:We(b.beforeAgent)}),o.addNode(v,w,w.nodeOptions)}if(b.beforeModel){_=new pp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,_);const v=`${b.name}.before_model`;l.push({index:m,name:v,allowed:We(b.beforeModel)}),o.addNode(v,_,_.nodeOptions)}if(b.afterModel){T=new mp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,T);const v=`${b.name}.after_model`;c.push({index:m,name:v,allowed:We(b.afterModel)}),o.addNode(v,T,T.nodeOptions)}if(b.afterAgent){x=new gp(b,{getState:()=>this.#t.getState(b.name)}),this.#t.addNode(b,x);const v=`${b.name}.after_agent`;u.push({index:m,name:v,allowed:We(b.afterAgent)}),o.addNode(v,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 cp(n.filter(W),{signal:this.options.signal,wrapToolCall:tp(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],_=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,v=w.allowed.map(E=>Pe(E)).filter(E=>E!=="tools"||b),M=Array.from(new Set([x,...v.map(E=>E===A?C:E)]));o.addConditionalEdges(_,this.#c(n.filter(W),x,C),M)}else o.addEdge(_,x)}for(let m=0;m<l.length;m++){const w=l[m],_=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,v=w.allowed.map(E=>Pe(E)).filter(E=>E!=="tools"||b),M=Array.from(new Set([x,...v]));o.addConditionalEdges(_,this.#u(n.filter(W),x),M)}else o.addEdge(_,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(_=>_===A?C:_);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],_=w.name,T=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),v=Array.from(new Set([T,...b]));o.addConditionalEdges(_,this.#r(n.filter(W),w.allowed,T),v)}else o.addEdge(_,T)}if(c.length>0){const m=c[0],w=m.name,_=this.#i(n.filter(W),!0).filter(b=>b!=="tools"||n.filter(W).length>0),T=!!(m.allowed&&m.allowed.length>0),x=_.map(b=>b===A?C:b);o.addConditionalEdges(w,this.#o(n.filter(W),T,C),x)}for(let m=u.length-1;m>0;m--){const w=u[m],_=w.name,T=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),v=Array.from(new Set([T,...b]));o.addConditionalEdges(_,this.#r(n.filter(W),w.allowed,T),v)}else o.addEdge(_,T)}if(u.length>0){const m=u[0],w=m.name;if(m.allowed&&m.allowed.length>0){const _=n.filter(W).length>0,T=m.allowed.map(b=>Pe(b)).filter(b=>b!=="tools"||_),x=Array.from(new Set([A,...T]));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 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(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(F.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 np(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 sl(t){return new wp(t)}const Kn=`<role>
|
|
65
|
+
Context Extraction Assistant
|
|
66
|
+
</role>
|
|
67
|
+
|
|
68
|
+
<primary_objective>
|
|
69
|
+
Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
|
|
70
|
+
</primary_objective>
|
|
71
|
+
|
|
72
|
+
<objective_information>
|
|
73
|
+
You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
|
|
74
|
+
This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
|
|
75
|
+
</objective_information>
|
|
76
|
+
|
|
77
|
+
<instructions>
|
|
78
|
+
The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
|
|
79
|
+
You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
|
|
80
|
+
</instructions>
|
|
81
|
+
|
|
82
|
+
The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
|
|
83
|
+
|
|
84
|
+
With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
|
|
85
|
+
Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
|
|
86
|
+
|
|
87
|
+
<messages>
|
|
88
|
+
Messages to summarize:
|
|
89
|
+
{messages}
|
|
90
|
+
</messages>`,ur=20,bp=4e3,Ni=5,_p=qn().args(Fe(ae())).returns(Me([U(),Yi(U())])),hr=z({fraction:U().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:U().positive("Tokens must be greater than 0").optional(),messages:U().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"}),il=z({fraction:U().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:U().positive("Tokens must be greater than 0").optional(),messages:U().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"}),Ii=z({model:ae(),trigger:Me([hr,Fe(hr)]).optional(),keep:il.optional(),tokenCounter:_p.optional(),summaryPrompt:ne().default(Kn),trimTokensToSummarize:U().optional(),summaryPrefix:ne().optional(),maxTokensBeforeSummary:U().optional(),messagesToKeep:U().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 ec(n)}catch{}}function vp(t){const{data:e,error:n}=Uc(Ii,t);if(n)throw new Error(`Invalid summarization middleware options: ${Bi(n)}`);return me({name:"SummarizationMiddleware",contextSchema:Ii.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=il.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??bp;Sp(r.messages);const p=s.context.tokenCounter!==void 0?s.context.tokenCounter:e.tokenCounter??As,C=await p(r.messages);if(!await kp(r.messages,C,u,d))return;const{systemPrompt:m,conversationMessages:w}=Cp(r.messages),_=await Ep(w,c,p,d);if(_<=0)return;const{messagesToSummarize:T,preservedMessages:x}=Tp(m,w,_),b=await Pp(T,d,f,p,g),v=new fe({content:`Here is a summary of the conversation to date:
|
|
91
|
+
|
|
92
|
+
${b}`,id:Jn()});return{messages:[new Pn({id:Qa}),v,...x]}}})}function Sp(t){for(const e of t)e.id||(e.id=Jn())}function Cp(t){return t.length>0&&be.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Tp(t,e,n){const r=e.slice(0,n),s=e.slice(n);return t&&r.unshift(t),{messagesToSummarize:r,preservedMessages:s}}async function kp(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 Ep(t,e,n,r){if("tokens"in e||"fraction"in e){const s=await xp(t,e,n,r);return typeof s=="number"?s:Ri(t,ur)}return Ri(t,e.messages??ur)}async function xp(t,e,n,r){if(t.length===0)return 0;let s;if("fraction"in e&&e.fraction!==void 0){const u=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(ol(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(ol(t,r))return r;return 0}function ol(t,e){if(e>=t.length)return!0;if(e<t.length&&O.isInstance(t[e])&&_s(t[e]))return!1;const n=Math.max(0,e-Ni),r=Math.min(t.length,e+Ni);for(let s=n;s<r;s++){if(!_s(t[s]))continue;const i=Mp(t[s]);if(Ap(t,s,e,i))return!1}return!0}function Mp(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 Ap(t,e,n,r){for(let s=e+1;s<t.length;s++){const i=t[s];if(F.isInstance(i)&&r.has(i.tool_call_id)){const o=e<n,a=s<n;if(o!==a)return!0}}return!1}async function Pp(t,e,n,r,s){if(!t.length)return"No previous conversation history.";const i=await Op(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 Op(t,e,n){if(n===void 0)return t;try{return await Xi(t,{maxTokens:n,tokenCounter:async r=>e(r),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-15)}}const Np=qn().args(ae(),ae(),ae()).returns(Me([ne(),Yi(ne())])),al=["approve","edit","reject"],Ip=Ut(al),Rp=z({allowedDecisions:Fe(Ip),description:Me([ne(),Np]).optional(),argsSchema:un(Es()).optional()}),$i=z({interruptOn:un(Me([Yn(),Rp])).optional(),descriptionPrefix:ne().default("Tool execution requires approval")});function $p(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
|
+
|
|
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,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 F({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:$i,afterModel:{canJumpTo:["model"],hook:async(r,s)=>{const i=Ge($i,{...t,...s.context||{}});if(!i)return;const{messages:o}=r;if(!o.length)return;const a=[...o].reverse().find(_=>O.isInstance(_));if(!a||!a.tool_calls?.length||!i.interruptOn)return;const l={};for(const[_,T]of Object.entries(i.interruptOn))typeof T=="boolean"?T===!0&&(l[_]={allowedDecisions:[...al]}):T.allowedDecisions&&(l[_]=T);const c=[],u=[];for(const _ of a.tool_calls)_.name in l?c.push(_):u.push(_);if(!c.length)return;const h=[],d=[];for(const _ of c){const T=l[_.name],{actionRequest:x,reviewConfig:b}=await e(_,T,r,s);h.push(x),d.push(b)}const p=(await ja({actionRequests:h,reviewConfigs:d})).decisions;if(!p||!Array.isArray(p))throw new Error("Invalid HITLResponse: decisions must be a non-empty array");if(p.length!==c.length)throw new Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${c.length}).`);const C=[...u],S=[],m=p.some(_=>_.type==="reject");for(let _=0;_<p.length;_++){const T=p[_],x=c[_],b=l[x.name],{revisedToolCall:v,toolMessage:M}=n(T,x,b);v&&(!m||T.type==="reject")&&C.push(v),M&&S.push(M)}O.isInstance(a)&&(a.tool_calls=C);const w=m?"model":void 0;return{messages:[a,...S],jumpTo:w}}}})}const jp=!0,Lp="5m",Dp=3,Fp="warn",Up=z({enableCaching:Yn().optional(),ttl:Ut(["5m","1h"]).optional(),minMessagesToCache:U().optional(),unsupportedModelBehavior:Ut(["ignore","warn","raise"]).optional()});var ji=class extends Error{constructor(t){super(t),this.name="PromptCachingMiddlewareError"}};function Vp(t){return me({name:"PromptCachingMiddleware",contextSchema:Up,wrapModelCall:(e,n)=>{const r=e.runtime.context.enableCaching??t?.enableCaching??jp,s=e.runtime.context.ttl??t?.ttl??Lp,i=e.runtime.context.minMessagesToCache??t?.minMessagesToCache??Dp,o=e.runtime.context.unsupportedModelBehavior??t?.unsupportedModelBehavior??Fp;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 ji(`${f} (e.g., 'anthropic:claude-4-0-sonnet').`);return o==="warn"&&console.warn(`PromptCachingMiddleware: Skipping caching for ${h}. Consider switching to an Anthropic model for caching benefits.`),n(e)}if(e.state.messages.length+(e.systemPrompt?1:0)<i)return n(e);const c=e.messages.at(-1);if(!c)return n(e);const u=Object.getPrototypeOf(c).constructor;if(Array.isArray(c.content)){const h=new u({...c,content:[...c.content.slice(0,-1),{...c.content.at(-1),cache_control:{type:"ephemeral",ttl: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 ji("Last message content is not a string or array")}})}function Bp(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 zp="Your goal is to select the most relevant tools for answering the user's query.";function Wp(t){if(!t||t.length===0)throw new Error("Invalid usage: tools must be non-empty");const e=t.map(r=>_t(r.name)),n=Me(e);return z({tools:Fe(n).describe("Tools to use. Place the most relevant tools first.")})}const Hp=z({model:ne().or(Xn(tc)).optional(),systemPrompt:ne().optional(),maxTools:U().optional(),alwaysInclude:Fe(ne()).optional()});function Gp(t){return me({name:"LLMToolSelector",contextSchema:Hp,async wrapModelCall(e,n){const r=await Kp(e,t,e.runtime);if(!r)return n(e);const s=Wp(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(Jp(o,r.availableTools,r.validToolNames,e,t))}})}async function Kp(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??zp;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 Jp(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 qp=z({rules:un(ne(),Xn(RegExp).describe("Regular expression pattern to match PII")).optional()});function Yp(){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=Yp();return n[l]=a,`[REDACTED_${o}_${l}]`})}return r}async function Xp(t,e){if(fe.isInstance(t)||F.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 Li(t,e){if(fe.isInstance(t)||F.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 Zp(t={}){const e={};return me({name:"PIIRedactionMiddleware",contextSchema:qp,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=>Xp(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}=Li(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}=Li(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 Pn({id:s.id}),new Pn({id:r.id}),c,i]}}return{...n,...a?{structuredResponse:a}:{},messages:[new Pn({id:r.id}),i]}}})}const Qp="[cleared]";var ll=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??Qp}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];F.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 F({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 em(t={}){const e=t.edits??[new ll],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 tm(t){return t?`Tool call limit exceeded. Do not call '${t}' again.`:"Tool call limit exceeded. Do not make additional tool calls."}const nm=["continue","error","end"],cl="continue";function ul(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 hl=Ut(nm).default(cl);var dl=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(t,e,n,r,s=void 0){const i=ul(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:U().optional(),runLimit:U().optional(),exitBehavior:hl});const rm=z({threadToolCallCount:un(ne(),U()).default({}),runToolCallCount:un(ne(),U()).default({})}),sm="__all__";function im(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??cl,n=hl.safeParse(e);if(!n.success)throw new Error(Bi(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:rm,afterModel:{canJumpTo:["end"],hook:s=>{const i=[...s.messages].reverse().find(O.isInstance);if(!i||!i.tool_calls)return;const o=(_,T)=>t.threadLimit!==void 0&&_+1>t.threadLimit||t.runLimit!==void 0&&T+1>t.runLimit,a=_=>t.toolName===void 0||_.name===t.toolName,l=(_,T,x)=>{const b=[],v=[];let M=T,E=x;for(const P of _)a(P)&&(o(M,E)?v.push(P):(b.push(P),M+=1,E+=1));return{allowed:b,blocked:v,finalThreadCount:M,finalRunCount:E+v.length}},c=t.toolName??sm,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 _=C+p.length;throw new dl(_,S,t.threadLimit,t.runLimit,t.toolName)}const m=tm(t.toolName),w=p.map(_=>new F({content:m,tool_call_id:_.id,name:_.name,status:"error"}));if(e==="end"){let _=[];if(t.toolName!==void 0?_=i.tool_calls.filter(b=>b.name!==t.toolName):new Set(i.tool_calls.map(v=>v.name).filter(Boolean)).size>1&&(_=g.length>0?g:i.tool_calls),_.length>0){const b=Array.from(new Set(_.map(v=>v.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 T=C+p.length,x=ul(T,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 om=`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
|
+
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
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
|
+
|
|
100
|
+
## When to Use This Tool
|
|
101
|
+
Use this tool in these scenarios:
|
|
102
|
+
|
|
103
|
+
1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
|
|
104
|
+
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
|
|
105
|
+
3. User explicitly requests todo list - When the user directly asks you to use the todo list
|
|
106
|
+
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
|
|
107
|
+
5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful.
|
|
108
|
+
|
|
109
|
+
## How to Use This Tool
|
|
110
|
+
1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
|
|
111
|
+
2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
|
|
112
|
+
3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.
|
|
113
|
+
4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.
|
|
114
|
+
|
|
115
|
+
## When NOT to Use This Tool
|
|
116
|
+
It is important to skip using this tool when:
|
|
117
|
+
1. There is only a single, straightforward task
|
|
118
|
+
2. The task is trivial and tracking it provides no benefit
|
|
119
|
+
3. The task can be completed in less than 3 trivial steps
|
|
120
|
+
4. The task is purely conversational or informational
|
|
121
|
+
|
|
122
|
+
## Examples of When to Use the Todo List
|
|
123
|
+
|
|
124
|
+
<example>
|
|
125
|
+
User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
|
|
126
|
+
Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
|
|
127
|
+
*Creates todo list with the following items:*
|
|
128
|
+
1. Create dark mode toggle component in Settings page
|
|
129
|
+
2. Add dark mode state management (context/store)
|
|
130
|
+
3. Implement CSS-in-JS styles for dark theme
|
|
131
|
+
4. Update existing components to support theme switching
|
|
132
|
+
5. Run tests and build process, addressing any failures or errors that occur
|
|
133
|
+
*Begins working on the first task*
|
|
134
|
+
|
|
135
|
+
<reasoning>
|
|
136
|
+
The assistant used the todo list because:
|
|
137
|
+
1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
|
|
138
|
+
2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
|
|
139
|
+
3. Both of the user's requests are complex and require multiple steps to complete.
|
|
140
|
+
</reasoning>
|
|
141
|
+
</example>
|
|
142
|
+
|
|
143
|
+
<example>
|
|
144
|
+
User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
|
|
145
|
+
Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.
|
|
146
|
+
*Creates todo list with the following items:*
|
|
147
|
+
1. Define target audience and key messaging
|
|
148
|
+
2. Create social media content calendar and posting schedule
|
|
149
|
+
3. Design email marketing sequence and automation flows
|
|
150
|
+
4. Draft press release and identify media contacts
|
|
151
|
+
5. Set up tracking and analytics for campaign performance
|
|
152
|
+
6. Create visual assets and brand materials
|
|
153
|
+
7. Coordinate launch timeline and deliverables
|
|
154
|
+
*Begins working on the first task*
|
|
155
|
+
|
|
156
|
+
<reasoning>
|
|
157
|
+
The assistant used the todo list because:
|
|
158
|
+
1. Marketing campaign planning involves multiple distinct channels and activities
|
|
159
|
+
2. Each component requires careful coordination and planning
|
|
160
|
+
3. The systematic approach ensures all aspects of the launch are covered
|
|
161
|
+
</reasoning>
|
|
162
|
+
</example>
|
|
163
|
+
|
|
164
|
+
<example>
|
|
165
|
+
User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
|
|
166
|
+
Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
|
|
167
|
+
*Uses search tools to locate all instances of getCwd in the codebase*
|
|
168
|
+
Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
|
|
169
|
+
*Creates todo list with specific items for each file that needs updating*
|
|
170
|
+
|
|
171
|
+
<reasoning>
|
|
172
|
+
The assistant used the todo list because:
|
|
173
|
+
1. The assistant searched to understand the scope of the task
|
|
174
|
+
2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
|
|
175
|
+
3. The todo list helps ensure every instance is tracked and updated systematically
|
|
176
|
+
4. This approach prevents missing any occurrences and maintains consistency.
|
|
177
|
+
</reasoning>
|
|
178
|
+
</example>
|
|
179
|
+
|
|
180
|
+
<example>
|
|
181
|
+
User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
|
|
182
|
+
Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
|
|
183
|
+
*Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines*
|
|
184
|
+
Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
|
|
185
|
+
|
|
186
|
+
<reasoning>
|
|
187
|
+
The assistant used the todo list because:
|
|
188
|
+
1. The user provided multiple distinct organizational tasks
|
|
189
|
+
2. Each area requires different approaches and careful planning
|
|
190
|
+
3. Home organization benefits from systematic, step-by-step completion
|
|
191
|
+
4. Progress tracking ensures all areas are addressed thoroughly
|
|
192
|
+
</reasoning>
|
|
193
|
+
</example>
|
|
194
|
+
|
|
195
|
+
## Examples of When NOT to Use the Todo List
|
|
196
|
+
|
|
197
|
+
<example>
|
|
198
|
+
User: How do I print 'Hello World' in Python?
|
|
199
|
+
Assistant: In Python, you can print "Hello World" with this simple code:
|
|
200
|
+
|
|
201
|
+
\`\`\`python
|
|
202
|
+
print("Hello World")
|
|
203
|
+
\`\`\`
|
|
204
|
+
|
|
205
|
+
This will output the text "Hello World" to the console when executed.</assistant>
|
|
206
|
+
|
|
207
|
+
<reasoning>
|
|
208
|
+
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
|
|
209
|
+
</reasoning>
|
|
210
|
+
</example>
|
|
211
|
+
|
|
212
|
+
<example>
|
|
213
|
+
User: What's the best way to water houseplants?
|
|
214
|
+
Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
|
|
215
|
+
|
|
216
|
+
- Check soil moisture by inserting your finger about 1-2 inches into the soil
|
|
217
|
+
- Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
|
|
218
|
+
- Use room temperature water and water in the morning when possible
|
|
219
|
+
- Avoid overwatering, which is more harmful than underwatering for most plants
|
|
220
|
+
|
|
221
|
+
Different plants have different needs, so it's important to research your specific varieties for optimal care.
|
|
222
|
+
|
|
223
|
+
<reasoning>
|
|
224
|
+
The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities.
|
|
225
|
+
</reasoning>
|
|
226
|
+
</example>
|
|
227
|
+
|
|
228
|
+
<example>
|
|
229
|
+
User: Can you add a comment to the calculateTotal function to explain what it does?
|
|
230
|
+
Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
|
|
231
|
+
* Uses the Edit tool to add a comment to the calculateTotal function *
|
|
232
|
+
|
|
233
|
+
<reasoning>
|
|
234
|
+
The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization.
|
|
235
|
+
</reasoning>
|
|
236
|
+
</example>
|
|
237
|
+
|
|
238
|
+
<example>
|
|
239
|
+
User: What time is it in Tokyo right now?
|
|
240
|
+
Assistant: I'll check the current time in Tokyo for you.
|
|
241
|
+
|
|
242
|
+
*Searches for current time in Tokyo*
|
|
243
|
+
|
|
244
|
+
The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
|
|
245
|
+
|
|
246
|
+
<reasoning>
|
|
247
|
+
The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request.
|
|
248
|
+
</reasoning>
|
|
249
|
+
</example>
|
|
250
|
+
|
|
251
|
+
<example>
|
|
252
|
+
User: I need to write a function that checks if a number is prime and then test it out.
|
|
253
|
+
Assistant: I'll help you write a function that checks if a number is prime and then test it out.
|
|
254
|
+
*Writes function that checks if a number is prime*
|
|
255
|
+
*Tests the function*
|
|
256
|
+
|
|
257
|
+
<reasoning>
|
|
258
|
+
Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens.
|
|
259
|
+
</reasoning>
|
|
260
|
+
</example>
|
|
261
|
+
|
|
262
|
+
<example>
|
|
263
|
+
User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
|
|
264
|
+
Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
|
|
265
|
+
*Orders a pizza from Dominos*
|
|
266
|
+
*Orders a burger from McDonald's*
|
|
267
|
+
*Orders a salad from Subway*
|
|
268
|
+
|
|
269
|
+
<reasoning>
|
|
270
|
+
Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls.
|
|
271
|
+
Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
|
|
272
|
+
</reasoning>
|
|
273
|
+
</example>
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
## Task States and Management
|
|
277
|
+
|
|
278
|
+
1. **Task States**: Use these states to track progress:
|
|
279
|
+
- pending: Task not yet started
|
|
280
|
+
- in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)
|
|
281
|
+
- completed: Task finished successfully
|
|
282
|
+
|
|
283
|
+
2. **Task Management**:
|
|
284
|
+
- Update task status in real-time as you work
|
|
285
|
+
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
|
|
286
|
+
- Complete current tasks before starting new ones
|
|
287
|
+
- Remove tasks that are no longer relevant from the list entirely
|
|
288
|
+
- IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
|
|
289
|
+
- IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something.
|
|
290
|
+
|
|
291
|
+
3. **Task Completion Requirements**:
|
|
292
|
+
- ONLY mark a task as completed when you have FULLY accomplished it
|
|
293
|
+
- If you encounter errors, blockers, or cannot finish, keep the task as in_progress
|
|
294
|
+
- When blocked, create a new task describing what needs to be resolved
|
|
295
|
+
- Never mark a task as completed if:
|
|
296
|
+
- There are unresolved issues or errors
|
|
297
|
+
- Work is partial or incomplete
|
|
298
|
+
- You encountered blockers that prevent completion
|
|
299
|
+
- You couldn't find necessary resources or dependencies
|
|
300
|
+
- Quality standards haven't been met
|
|
301
|
+
|
|
302
|
+
4. **Task Breakdown**:
|
|
303
|
+
- Create specific, actionable items
|
|
304
|
+
- Break complex tasks into smaller, manageable steps
|
|
305
|
+
- Use clear, descriptive task names
|
|
306
|
+
|
|
307
|
+
Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
|
|
308
|
+
Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`,fl=`## \`write_todos\`
|
|
309
|
+
|
|
310
|
+
You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
|
|
311
|
+
Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
|
|
312
|
+
This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
|
|
313
|
+
|
|
314
|
+
It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.
|
|
315
|
+
For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.
|
|
316
|
+
Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.
|
|
317
|
+
|
|
318
|
+
## Important To-Do List Usage Notes to Remember
|
|
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.`,am=Ut(["pending","in_progress","completed"]).describe("Status of the todo"),pl=z({content:ne().describe("Content of the todo item"),status:am}),lm=z({todos:Fe(pl).default([])});function cm(t){const e=Wi(({todos:n},r)=>new K({update:{todos:n,messages:[new F({content:`Updated todo list to ${JSON.stringify(n)}`,tool_call_id:r.toolCall?.id})]}}),{name:"write_todos",description:t?.toolDescription??om,schema:z({todos:Fe(pl).describe("List of todo items to update")})});return me({name:"todoListMiddleware",stateSchema:lm,tools:[e],wrapModelCall:(n,r)=>r({...n,systemPrompt:(n.systemPrompt?`${n.systemPrompt}
|
|
321
|
+
|
|
322
|
+
`:"")+(t?.systemPrompt??fl)})})}const um="end",hm=z({threadLimit:U().optional(),runLimit:U().optional(),exitBehavior:Ut(["throw","end"]).optional()}),dm=z({threadModelCallCount:U().default(0),runModelCallCount:U().default(0)});var Di=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:n,runCount:r}){const s=[];typeof t=="number"&&typeof n=="number"&&s.push(`thread level call limit reached with ${n} model calls`),typeof e=="number"&&typeof r=="number"&&s.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${s.length>0?`: ${s.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function ml(t){return me({name:"ModelCallLimitMiddleware",contextSchema:hm,stateSchema:dm,beforeModel:{canJumpTo:["end"],hook:(e,n)=>{const r=n.context.exitBehavior??t?.exitBehavior??um,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 Di({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 Di({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 fm(...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 pm(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:U().min(0).default(2),tools:Fe(Me([ae(),ae(),ne()])).optional(),retryOn:Me([qn().args(Xn(Error)).returns(Yn()),Fe(ae())]).default(()=>()=>!0),onFailure:Me([_t("raise"),_t("return_message"),qn().args(Xn(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:Yn().default(!0)});function mm(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 F({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(_){const T=w+1,x=_&&typeof _=="object"&&"message"in _?_:new Error(String(_));if(!h(x))return g(S,m,x,T);if(w<e){const b=pm(d,w);b>0&&await hu(b)}else return g(S,m,x,T)}throw new Error("Unexpected: retry loop completed without returning")}})}var gm={};Qi(gm,{AIMessage:()=>O,AIMessageChunk:()=>Lt,BaseMessage:()=>nn,BaseMessageChunk:()=>Hc,ClearToolUsesEdit:()=>ll,Document:()=>Le,DynamicStructuredTool:()=>Hi,DynamicTool:()=>Rl,FakeToolCallingModel:()=>od,HumanMessage:()=>fe,HumanMessageChunk:()=>Wc,InMemoryStore:()=>mo,MultipleStructuredOutputsError:()=>Yr,MultipleToolsBoundError:()=>qr,ProviderStrategy:()=>rt,StructuredOutputParsingError:()=>ro,StructuredTool:()=>fr,SystemMessage:()=>be,SystemMessageChunk:()=>zc,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>fl,Tool:()=>Il,ToolCallLimitExceededError:()=>dl,ToolInvocationError:()=>xs,ToolMessage:()=>F,ToolMessageChunk:()=>Bc,ToolStrategy:()=>Ve,anthropicPromptCachingMiddleware:()=>Vp,contextEditingMiddleware:()=>em,countTokensApproximately:()=>As,createAgent:()=>sl,createMiddleware:()=>me,dynamicSystemPromptMiddleware:()=>Bp,filterMessages:()=>Vc,humanInTheLoopMiddleware:()=>$p,initChatModel:()=>Jt,llmToolSelectorMiddleware:()=>Gp,modelCallLimitMiddleware:()=>ml,modelFallbackMiddleware:()=>fm,piiRedactionMiddleware:()=>Zp,providerStrategy:()=>cu,summarizationMiddleware:()=>vp,todoListMiddleware:()=>cm,tool:()=>Wi,toolCallLimitMiddleware:()=>im,toolRetryMiddleware:()=>mm,toolStrategy:()=>lu,trimMessages:()=>Xi});var ym={},Tt,wm=(Tt=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(Tt,"BaseAdapter"),Tt),kt,bm=(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,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:vr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:vr.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:vr.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):ve();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return El();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=xl();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=vs();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):ve(),r=Ml(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 ve();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Al()):n.push(this.parseSchema(r));return n.length>=2?Sr(n):n.length===1?n[0]:ve()}static parseAllOf(e){if(e.length===0)return ve();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(e,n){const r={...e,...n};if(e.properties&&n.properties){const s={...e.properties,...n.properties};r.properties=s}if(e.required&&n.required){const s=[...new Set([...e.required,...n.required])];r.required=s}return r}},j(kt,"JSONSchemaToZod"),kt);function gl(t){try{return bm.convert(t)}catch(e){return y.warn(`Failed to convert JSON schema to Zod: ${e}`),ve()}}j(gl,"schemaToZod");var Et,mt=(Et=class extends wm{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?gl(e.inputSchema):Ye({}).optional();return new Hi({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),_m=Ye({}),Mt,vm=(Mt=class extends br{name="get_active_mcp_server";description="Get the currently active MCP (Model Context Protocol) server";schema=_m;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,Sm=(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:vs().describe("The name for the new MCP server."),serverConfig:ve().describe('The configuration object for the server. This should not include the top-level "mcpServers" key.')});manager;constructor(e){super(),this.manager=e}async _call({serverName:e,serverConfig:n}){try{this.manager.client.addServer(e,n);let r=`Server '${e}' added to the client.`;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+=`
|
|
323
|
+
|
|
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),Cm=Ye({serverName:vs().describe("The name of the MCP server.")}),Pt,Tm=(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=Cm;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),km=Ye({}),Ot,Em=(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=km;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),xm=Ye({}),Nt,Mm=(Nt=class extends br{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=xm;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,Am=(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 Sm(this),new Em(this),new Tm(this),new vm(this),new Mm(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),Rt,Ui=(Rt=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:n}=await an(async()=>{const{langfuseHandler:s,langfuseInitPromise:i}=await Promise.resolve().then(()=>Vi);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(()=>Vi);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(Rt,"ObservabilityManager"),Rt),Pm="/api/v1/chats",Om="/api/v1/chats/{chat_id}/execute",$t,Nm=($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??ym.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 An(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}${Pm}`;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}${Om.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:
|
|
328
|
+
• Invalid agent configuration (LLM model, system prompt)
|
|
329
|
+
• Missing or invalid MCP server configurations
|
|
330
|
+
• Network connectivity issues with MCP servers
|
|
331
|
+
• Missing environment variables or credentials
|
|
332
|
+
Raw error: ${h}`)}return i?this.parseStructuredResponse(h,i):typeof h=="object"&&h!==null&&"result"in h?h.result:typeof h=="string"?h:String(h)}catch(o){throw o instanceof Error?o.name==="AbortError"?(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($t,"RemoteAgent"),$t);function yl(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(yl,"generateToolDescriptions");function wl(t,e,n){const r=e.join(`
|
|
333
|
+
`);let s;return t.includes("{tool_descriptions}")?s=t.replace("{tool_descriptions}",r):(console.warn("`{tool_descriptions}` placeholder not found; appending at end."),s=`${t}
|
|
334
|
+
|
|
335
|
+
Available tools:
|
|
336
|
+
${r}`),n&&(s+=`
|
|
337
|
+
|
|
338
|
+
${n}`),s}j(wl,"buildSystemPromptContent");function bl(t,e,n,r,s,i,o){if(i)return new be({content:i});const a=r?n:e,l=yl(t,s),c=wl(a,l,o);return new be({content:c})}j(bl,"createSystemMessage");var Im=`You are a helpful AI assistant.
|
|
339
|
+
You have access to the following tools:
|
|
340
|
+
|
|
341
|
+
{tool_descriptions}
|
|
342
|
+
|
|
343
|
+
Use the following format:
|
|
344
|
+
|
|
345
|
+
Question: the input question you must answer
|
|
346
|
+
Thought: you should always think about what to do
|
|
347
|
+
Action: the action to take, should be one of the available tools
|
|
348
|
+
Action Input: the input to the action
|
|
349
|
+
Observation: the result of the action
|
|
350
|
+
... (this Thought/Action/Action Input/Observation can repeat N times)
|
|
351
|
+
Thought: I now know the final answer
|
|
352
|
+
Final Answer: the final answer to the original input question`,Rm=`You are a helpful assistant designed to interact with MCP
|
|
353
|
+
(Model Context Protocol) servers. You can manage connections to different servers and use the tools
|
|
354
|
+
provided by the currently active server.
|
|
355
|
+
|
|
356
|
+
Important: The available tools change depending on which server is active.
|
|
357
|
+
If a request requires tools not listed below (e.g., file operations, web browsing,
|
|
358
|
+
image manipulation), you MUST first connect to the appropriate server using
|
|
359
|
+
'connect_to_mcp_server'.
|
|
360
|
+
Use 'list_mcp_servers' to find the relevant server if you are unsure.
|
|
361
|
+
Only after successfully connecting and seeing the new tools listed in
|
|
362
|
+
the response should you attempt to use those server-specific tools.
|
|
363
|
+
Before attempting a task that requires specific tools, you should
|
|
364
|
+
ensure you are connected to the correct server and aware of its
|
|
365
|
+
available tools. If unsure, use 'list_mcp_servers' to see options
|
|
366
|
+
or 'get_active_mcp_server' to check the current connection.
|
|
367
|
+
|
|
368
|
+
When you connect to a server using 'connect_to_mcp_server',
|
|
369
|
+
you will be informed about the new tools that become available.
|
|
370
|
+
You can then use these server-specific tools in subsequent steps.
|
|
371
|
+
|
|
372
|
+
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
373
|
+
change when you connect to a server):
|
|
374
|
+
{tool_descriptions}
|
|
375
|
+
`,jt,Gm=(jt=class{static getPackageVersion(){return Tl()}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 Nm({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=ei.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Ui({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(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 Am(this.client,this.adapter)}else this.adapter=e.adapter??new mt(this.disallowedTools);if(this.telemetry=ei.getInstance(),this.llm){const[n,r]=kl(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Ui({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??Im;this.systemMessage=bl(e,n,Rm,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=[ml({runLimit:this.maxSteps})],s=sl({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 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,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(_=>_.name)),w=new Set(this._tools.map(_=>_.name));(m.size!==w.size||[...m].some(_=>!w.has(_)))&&(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 _ of w){for(const[T,x]of Object.entries(_))if(y.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let b=x.messages;Array.isArray(b)||(b=[b]);for(const v of b)C.includes(v)||C.push(v);for(const v of b){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const M of v.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(v)){const M=v.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(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),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-zQjmUskw.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 _=this._normalizeOutput(w.content);h+=_,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,_=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,_=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(_)throw _;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(`
|
|
376
|
+
|
|
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(An(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=An(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=`
|
|
378
|
+
Please format the following information according to the EXACT schema specified below.
|
|
379
|
+
You must use the exact field names and types as shown in the schema.
|
|
380
|
+
|
|
381
|
+
Required schema format:
|
|
382
|
+
${i}
|
|
383
|
+
|
|
384
|
+
Content to extract from:
|
|
385
|
+
${u}
|
|
386
|
+
|
|
387
|
+
IMPORTANT:
|
|
388
|
+
- Use ONLY the field names specified in the schema
|
|
389
|
+
- Match the data types exactly (string, number, boolean, array, etc.)
|
|
390
|
+
- Include ALL required fields
|
|
391
|
+
- Return valid JSON that matches the schema structure exactly
|
|
392
|
+
- For missing data: use null for nullable fields, omit optional fields entirely
|
|
393
|
+
- Do NOT use empty strings ("") or zero (0) as placeholders for missing data
|
|
394
|
+
`;f>1&&(g+=`
|
|
395
|
+
|
|
396
|
+
PREVIOUS ATTEMPT FAILED with error: ${d}
|
|
397
|
+
Please fix the issues mentioned above and ensure the output matches the schema exactly.
|
|
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 _ of C){if(m++,y.debug(`Chunk ${m}: ${JSON.stringify(_,null,2)}`),typeof _=="string")try{S=JSON.parse(_)}catch{y.warn(`🔄 Failed to parse string chunk as JSON: ${_}`)}else if(_&&typeof _=="object")S=_;else try{S=JSON.parse(String(_))}catch{y.warn(`🔄 Failed to parse chunk as JSON: ${_}`)}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=An(n),{$schema:s,additionalProperties:i,...o}=r,a=JSON.stringify(o,null,2);return`
|
|
400
|
+
${e}
|
|
401
|
+
|
|
402
|
+
IMPORTANT: Your response must include sufficient information to populate the following structured output:
|
|
403
|
+
|
|
404
|
+
${a}
|
|
405
|
+
|
|
406
|
+
Make sure you gather ALL the required information during your task execution.
|
|
407
|
+
If any required information is missing, continue working to find it.
|
|
408
|
+
`}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},j(jt,"MCPAgent"),jt),Z={},$m=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 _=this.getCustomTags(),T=this.getMetadata(),x=[...C||[],..._],b={...S||{},...T};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");$m?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 jm=j(()=>wn.handler,"langfuseHandler"),Lm=j(()=>wn.initPromise,"langfuseInitPromise");const Vi=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Qs,langfuseHandler:jm,langfuseInitPromise:Lm},Symbol.toStringTag,{value:"Module"}));export{wm as BaseAdapter,qm as BaseConnector,Ym as BrowserOAuthClientProvider,Xm as BrowserTelemetry,Zm as HttpConnector,mt as LangChainAdapter,Qm as Logger,Gm as MCPAgent,eg as MCPClient,tg as MCPSession,Ui as ObservabilityManager,Nm as RemoteAgent,ng as Tel,ei as Telemetry,rg as VERSION,sg as WebSocketConnector,nu as createReadableStreamFromGenerator,Tl as getPackageVersion,y as logger,ig as onMcpAuthorization,og as setBrowserTelemetrySource,ag as setTelemetrySource,tu as streamEventsToAISDK,ru as streamEventsToAISDKWithTools};
|