@arcgis/portal-components 6.0.0-next.2 → 6.0.0-next.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/cdn/{46BUEBWS.js → 23NXHNPU.js} +1 -1
- package/dist/cdn/{6F4SJDRR.js → 2CN754CY.js} +1 -1
- package/dist/cdn/{JL52W3Z4.js → 2FQKDFEE.js} +1 -1
- package/dist/cdn/{L64UURQB.js → 2TDHJSMP.js} +1 -1
- package/dist/cdn/3FSPL34I.js +170 -0
- package/dist/cdn/{EITRZQSC.js → BYHX3UWV.js} +1 -1
- package/dist/cdn/CFRJU6VA.js +2 -0
- package/dist/cdn/D2YQWKME.js +135 -0
- package/dist/cdn/{EQDYQOOT.js → EY5S6ICQ.js} +1 -1
- package/dist/cdn/{MLYQGIJU.js → GGDOGNH4.js} +13 -13
- package/dist/cdn/{23FS4XTG.js → HCNTXLUT.js} +1 -1
- package/dist/cdn/{TLM457Z5.js → J5NPDIZM.js} +1 -1
- package/dist/cdn/JE2376SE.js +2 -0
- package/dist/cdn/{CXXV6WJT.js → MQK63FV7.js} +1 -1
- package/dist/cdn/N4VOTJ25.js +1 -1
- package/dist/cdn/{YTODQCOG.js → QROXYP6V.js} +1 -1
- package/dist/cdn/QTAYXO5T.js +2 -0
- package/dist/cdn/{AJQT7UXB.js → QUOLQGKP.js} +1 -1
- package/dist/cdn/{66XWNGQ2.js → QWHGLE3O.js} +1 -1
- package/dist/cdn/R3PK7XOP.js +2 -0
- package/dist/cdn/{WC3FPLYQ.js → REM3KCX6.js} +1 -1
- package/dist/cdn/{4AI52H7C.js → RNWICLRH.js} +1 -1
- package/dist/cdn/S6F7U36E.js +400 -0
- package/dist/cdn/SMX2LEJB.js +2 -0
- package/dist/cdn/{ABORO35R.js → TRMFL7PT.js} +1 -1
- package/dist/cdn/{LWFACY3F.js → UEP2NYJK.js} +1 -1
- package/dist/cdn/{32BWFMTC.js → URQML7KV.js} +1 -1
- package/dist/cdn/{6RZEXOK3.js → UZP4YMTE.js} +1 -1
- package/dist/cdn/VNU4QX7M.js +41 -0
- package/dist/cdn/YB3DR4VO.js +2 -0
- package/dist/cdn/Z3HGPBOR.js +2 -0
- package/dist/cdn/ZXNF77OB.js +2 -0
- package/dist/cdn/index.js +1 -1
- package/dist/components/arcgis-portal-account-switcher/customElement.js +27 -25
- package/dist/components/arcgis-portal-account-switcher-accounts/customElement.d.ts +4 -4
- package/dist/components/arcgis-portal-account-switcher-accounts/customElement.js +8 -8
- package/dist/components/arcgis-portal-account-switcher-list/customElement.d.ts +4 -4
- package/dist/components/arcgis-portal-account-switcher-list/customElement.js +6 -6
- package/dist/components/arcgis-portal-account-switcher-signout/customElement.d.ts +5 -5
- package/dist/components/arcgis-portal-account-switcher-signout/customElement.js +3 -3
- package/dist/components/arcgis-portal-ai-assistant/customElement.d.ts +10 -2
- package/dist/components/arcgis-portal-ai-assistant/customElement.js +1354 -1037
- package/dist/components/arcgis-portal-ai-assistant/data/capability-registries/types.d.ts +1 -1
- package/dist/components/arcgis-portal-ai-assistant/types/assistantTools.d.ts +44 -0
- package/dist/components/arcgis-portal-entity-picker/customElement.d.ts +7 -0
- package/dist/components/arcgis-portal-entity-picker/customElement.js +33 -27
- package/dist/components/arcgis-portal-group-card/customElement.js +16 -16
- package/dist/components/arcgis-portal-item-card/customElement.js +58 -58
- package/dist/components/arcgis-portal-navigation/index.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/vscode.html-custom-data.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/loader.js +7 -7
- package/dist/types/lumina.d.ts +11 -11
- package/dist/types/preact.d.ts +11 -11
- package/dist/types/react.d.ts +11 -11
- package/dist/types/stencil.d.ts +11 -11
- package/package.json +7 -7
- package/dist/cdn/5PPZNVWG.js +0 -2
- package/dist/cdn/APSYZEPP.js +0 -209
- package/dist/cdn/BSTA5KI5.js +0 -2
- package/dist/cdn/GUO7HKSP.js +0 -463
- package/dist/cdn/GX7U3727.js +0 -2
- package/dist/cdn/NRMQDCM3.js +0 -2
- package/dist/cdn/RVYSVTPQ.js +0 -2
- /package/dist/components/arcgis-portal-ai-assistant/{agents/types.d.ts → types/navigation.d.ts} +0 -0
- /package/dist/components/arcgis-portal-ai-assistant/{agents → types}/portalRouteKeys.d.ts +0 -0
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
+
import{$ as Ya,A as $a,Aa as ir,B as Va,Ba as hc,C as Fa,D as Mr,Da as pc,Ea as ri,F as La,Fa as fc,G as Ua,Ga as mc,H as Ha,I as kn,Ia as dc,J as Ba,K as Zs,Ka as gc,L as G,M as En,N as $t,O as Cn,P as Be,Q as Ga,R as Wa,S as Ka,T as qa,U as za,V as Ja,_ as wt,aa as Xa,ca as Qa,da as Za,ea as ei,fa as ec,g as Oa,ga as tc,ha as rc,ia as ti,j as nr,ja as nc,k as Xs,ka as sc,l as ge,m as Rr,ma as ic,n as Na,na as oc,o as sr,p as Pa,ra as ac,s as Qs,t as Ra,va as cc,w as Ma,wa as xn,x as st,xa as lc,y as ja,z as Da,za as uc}from"./3FSPL34I.js";import{$ as Zt,$a as ke,Aa as Nr,Ba as Pr,Ca as _a,D as Ws,Ea as Js,F as Oe,Fa as ya,G as Ks,H as fa,Ha as wa,Ia as ba,J as Dt,La as yt,M as ma,Na as va,O as da,Oa as Sa,P as vn,Pa as tr,Qa as ka,Sa as Ea,Ta as Ca,Ua as xa,V as qs,Va as Ta,Wa as rr,Xa as Ys,Y as Q,Ya as Z,Za as Ia,a as O,aa as zs,ab as Aa,bb as nt,e as aa,f as ca,g as la,h as ua,i as ha,ia as _t,j as pa,k as Ae,ma as er,na as Sn,sa as Ne,x as X,za as ga}from"./GGDOGNH4.js";function _c(e,t){if(e!=null){if(typeof e!="number"||Number.isNaN(e)||e<=0)throw new Error(`${t} must be greater than 0`);return e}}function bt(e){if(e==null)return;let t=typeof e=="number"?{runTimeout:e}:e,r=t.refreshOn??"auto";if(r!=="auto"&&r!=="heartbeat")throw new Error('refreshOn must be "auto" or "heartbeat"');let n=_c(t.runTimeout,"runTimeout"),s=_c(t.idleTimeout,"idleTimeout");if(!(n===void 0&&s===void 0))return{runTimeout:n,idleTimeout:s,refreshOn:r}}var W="__start__",K="__end__",We="__input__";var vt="__error__",Dr="__error_source_node__",Tn="__pregel_ns_writes";function yc(){let e=typeof process<"u"?process.env?.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT:void 0;if(e!==void 0&&e!==""){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return 5e3}var oe="__pregel_send",Ke="__pregel_call",le="__pregel_read",Ee="__pregel_checkpointer",Ft="__pregel_resuming",or="__pregel_task_id",$r="__pregel_stream",Lh="__pregel_resume_value",Lt="__pregel_resume_map",ue="__pregel_scratchpad",St="__pregel_previous",Uh="__pregel_durability",kt="checkpoint_id",ve="checkpoint_ns",wc="__pregel_node_finished",Vr="__pregel_node_error",ae="checkpoint_map",In="__pregel_replay_state",bc="__pregel_abort_signals",L="__interrupt__",he="__resume__",Fr="__no_writes__",Et="__return__",Ct="__previous__",z="langsmith:hidden";var si="__self__",qe="__pregel_tasks",pe="__pregel_push",An="__pregel_pull",fe="00000000-0000-0000-0000-000000000000",vc=[z,We,L,he,vt,Dr,Fr,oe,le,Ee,Uh,$r,Ft,or,Ke,Lh,ue,St,ae,ve,kt,In],ni=Symbol.for("langgraph.command"),Sc=class{[ni];constructor(e){this[ni]=e}};function On(e){let t=e;return t!=null&&typeof t.node=="string"&&t.args!==void 0}var Vt=class{lg_name="Send";node;args;timeout;constructor(e,t,r){this.node=e,this.args=jr(t),this.timeout=bt(r?.timeout)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args,timeout:this.timeout}}};function ee(e){return e instanceof Vt}var Ge="__overwrite__",Hh=class{lg_name="Overwrite";[Ge];constructor(e){this[Ge]=e}get value(){return this[Ge]}toJSON(){return{[Ge]:this[Ge]}}static isInstance(e){return!e||typeof e!="object"?!1:"__overwrite__"in e||"lg_name"in e&&e.lg_name==="Overwrite"}};function Pe(e){if(typeof e=="object"&&e!==null){if("__overwrite__"in e)return[!0,e[Ge]];let t=e;if(t.type==="__overwrite__"&&"value"in t)return[!0,t.value]}return[!1,void 0]}function Ut(e){return Pe(e)[0]}function Ht(e){return!e||typeof e!="object"||!("__interrupt__"in e)?!1:Array.isArray(e[L])}var _e=class extends Sc{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?jr(e.goto):[jr(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let e;return typeof this.goto=="string"?e=this.goto:ee(this.goto)?e=this.goto.toJSON():e=this.goto?.map(t=>typeof t=="string"?t:t.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function ne(e){return typeof e!="object"||e==null?!1:"lg_name"in e&&e.lg_name==="Command"}function Bh(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function jr(e,t=new Map){if(e!=null&&typeof e=="object"){if(t.has(e))return t.get(e);let r;if(Array.isArray(e))r=[],t.set(e,r),e.forEach((n,s)=>{r[s]=jr(n,t)});else if(e instanceof _e||e instanceof Vt||!Bh(e))r=e,t.set(e,r);else if(ne(e))r=new _e(e),t.set(e,r);else if(On(e))r=new Vt(e.node,e.args,e.timeout!==void 0?{timeout:e.timeout}:void 0),t.set(e,r);else if("lc_serializable"in e&&e.lc_serializable)r=e,t.set(e,r);else{r={},t.set(e,r);for(let[n,s]of Object.entries(e))r[n]=jr(s,t)}return r}return e}var Ce=class extends Error{lc_error_code;constructor(e,t){let r=e??"";t?.lc_error_code&&(r=`${r}
|
|
3
|
+
|
|
4
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
|
|
5
|
+
`),super(r),this.lc_error_code=t?.lc_error_code}},Nn=class extends Ce{get is_bubble_up(){return!0}},ii=class extends Ce{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Bt=class extends Ce{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},Pn=class extends Nn{reason;constructor(e="shutdown",t){super(`Graph drained: ${e}`,t),this.name="GraphDrained",this.reason=e}static get unminifiable_name(){return"GraphDrained"}};function Rn(e){return e!==void 0&&e.name===Pn.unminifiable_name}var it=class extends Nn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},Mn=class extends it{constructor(e,t){super([{value:e}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},jn=class{node;error;constructor(e,t){this.node=e,this.error=t}static get unminifiable_name(){return"NodeError"}};function Gh(e){return e!=null&&typeof e=="object"&&e.constructor!=null&&e.constructor.unminifiable_name===jn.unminifiable_name}var Dn=class extends Nn{command;constructor(e){super(),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function oi(e){return e!==void 0&&e.name===Dn.unminifiable_name}function xt(e){return e!==void 0&&e.is_bubble_up===!0}function ot(e){return e!==void 0&&[it.unminifiable_name,Mn.unminifiable_name].includes(e.name)}var $n=class extends Ce{node;kind;timeout;elapsed;runTimeout;idleTimeout;constructor(e,t){let{node:r,elapsed:n,kind:s,runTimeout:i,idleTimeout:o}=e,a,c;if(s==="idle"){if(o===void 0)throw new Error("idleTimeout is required when kind='idle'");c=o,a=`Node "${r}" exceeded its idle timeout of ${o}ms without making progress (elapsed: ${n}ms).`}else{if(i===void 0)throw new Error("runTimeout is required when kind='run'");c=i,a=`Node "${r}" exceeded its run timeout of ${i}ms (elapsed: ${n}ms).`}super(a,t),this.name="NodeTimeoutError",this.node=r,this.kind=s,this.timeout=c,this.elapsed=n,this.runTimeout=i,this.idleTimeout=o}static get unminifiable_name(){return"NodeTimeoutError"}};function Wh(e){return e!==void 0&&e.name===$n.unminifiable_name}var Vn=class extends Ce{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},$=class extends Ce{constructor(e,t){let r=Error.stackTraceLimit;Error.stackTraceLimit=0,super(e,t),Error.stackTraceLimit=r,this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},R=class extends Ce{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},Kh=class extends Ce{constructor(e,t){super(e,t),this.name="MultipleSubgraphError"}static get unminifiable_name(){return"MultipleSubgraphError"}},ai=class extends Ce{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}},qh=class extends Ce{constructor(e,t){super(e,t),this.name="RemoteException"}static get unminifiable_name(){return"RemoteException"}},Lr=class extends Ce{constructor(e,t){super(e,t),this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}},zh=()=>(globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]===void 0&&(globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]=new Set),globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]);var ci=0,Ur=0;function Hr(e){let t=Date.now();return t<=ci?(Ur+=1,Ur>=1e4&&(Ur=0,t=ci+1)):Ur=0,ci=t,_a({clockseq:e,msecs:t,nsecs:Ur})}function ze(e,t){let r=t.replace(/-/g,"").match(/.{2}/g).map(n=>parseInt(n,16));return Pr(e,new Uint8Array(r))}var Br="__pregel_tasks",li="__error__",Gt="__scheduled__",ui="__interrupt__",hi="__resume__",ar=class{lg_name="DeltaSnapshot";value;constructor(e){this.value=e}};function pi(e){return e!=null&&typeof e=="object"&&e.lg_name==="DeltaSnapshot"}var kc="[...]",Jh="[Circular]",Fn=[],cr=[];function Yh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Ec(e,t,r,n){typeof n>"u"&&(n=Yh()),mi(e,"",0,[],void 0,0,n);var s;try{cr.length===0?s=JSON.stringify(e,t,r):s=JSON.stringify(e,Xh(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Fn.length!==0;){var i=Fn.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return s}function fi(e,t,r,n){var s=Object.getOwnPropertyDescriptor(n,r);s.get!==void 0?s.configurable?(Object.defineProperty(n,r,{value:e}),Fn.push([n,r,t,s])):cr.push([t,r,e]):(n[r]=e,Fn.push([n,r,t]))}function mi(e,t,r,n,s,i,o){i+=1;var a;if(typeof e=="object"&&e!==null){for(a=0;a<n.length;a++)if(n[a]===e){fi(Jh,e,t,s);return}if(typeof o.depthLimit<"u"&&i>o.depthLimit){fi(kc,e,t,s);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){fi(kc,e,t,s);return}if(n.push(e),Array.isArray(e))for(a=0;a<e.length;a++)mi(e[a],a,a,n,e,i,o);else{var c=Object.keys(e);for(a=0;a<c.length;a++){var l=c[a];mi(e[l],l,a,n,e,i,o)}}n.pop()}}function Xh(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(cr.length>0)for(var n=0;n<cr.length;n++){var s=cr[n];if(s[1]===t&&s[0]===r){r=s[2],cr.splice(n,1);break}}return e.call(this,t,r)}}var Cc=[];var xc=O({});var Tc=O({});var Ic=O({BaseChatMessageHistory:()=>di,BaseListChatMessageHistory:()=>Ln,InMemoryChatMessageHistory:()=>Qh}),di=class extends Ae{async addMessages(e){for(let t of e)await this.addMessage(t)}},Ln=class extends Ae{addUserMessage(e){return this.addMessage(new _t(e))}addAIMessage(e){return this.addMessage(new Q(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}},Qh=class extends Ln{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var Se=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}};var gi=class extends G{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},Ac=class extends gi{async transformDocuments(e){let t=[];for(let r of e){let n=await this._transformDocument(r);t.push(n)}return t}};var Oc=O({BaseDocumentTransformer:()=>gi,Document:()=>Se,MappingDocumentTransformer:()=>Ac});var Nc=O({BaseDocumentLoader:()=>_i}),_i=class{};var Pc=O({LangSmithLoader:()=>Zh}),Zh=class extends _i{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new va(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??ep,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t 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 r=t.inputs;for(let i of this.contentKey)r=r[i];let n=this.formatContent(r),s=t;["created_at","modified_at"].forEach(i=>{i in s&&typeof s[i]=="object"&&(s[i]=s[i].toString())}),e.push({pageContent:n,metadata:s})}return e}};function ep(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var lr=class extends Ae{lc_namespace=["langchain_core","example_selectors","base"]};var yi=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},Rc=class extends yi{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}};function Mc(e){return e._modelType()==="base_llm"}function jc(e){return e._modelType()==="base_chat_model"}function Dc(e){return e.split(/\n| /).length}var $c=class Vc extends lr{examples=[];examplePrompt;getTextLength=Dc;maxLength=2048;exampleTextLengths=[];constructor(t){super(t),this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??Dc}async addExample(t){this.examples.push(t);let r=await this.examplePrompt.format(t);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(t,r){if(t.length>0)return t;let{examples:n,examplePrompt:s}=r;return(await Promise.all(n.map(i=>s.format(i)))).map(i=>this.getTextLength(i))}async selectExamples(t){let r=Object.values(t).join(" "),n=this.maxLength-this.getTextLength(r),s=0,i=[];for(;n>0&&s<this.examples.length;){let o=n-this.exampleTextLengths[s];if(o<0)break;i.push(this.examples[s]),n=o,s+=1}return i}static async fromExamples(t,r){let n=new Vc(r);return await Promise.all(t.map(s=>n.addExample(s))),n}};function wi(e){return Object.keys(e).sort().map(t=>e[t])}var Fc=class Lc extends lr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(t){if(super(t),this.exampleKeys=t.exampleKeys,this.inputKeys=t.inputKeys,t.vectorStore!==void 0)this.vectorStoreRetriever=t.vectorStore.asRetriever({k:t.k??4,filter:t.filter});else if(t.vectorStoreRetriever)this.vectorStoreRetriever=t.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(t){let r=wi((this.inputKeys??Object.keys(t)).reduce((n,s)=>({...n,[s]:t[s]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Se({pageContent:r,metadata:t})])}async selectExamples(t){let r=wi((this.inputKeys??Object.keys(t)).reduce((s,i)=>({...s,[i]:t[i]}),{})).join(" "),n=(await this.vectorStoreRetriever.invoke(r)).map(s=>s.metadata);return this.exampleKeys?n.map(s=>this.exampleKeys.reduce((i,o)=>({...i,[o]:s[o]}),{})):n}static async fromExamples(t,r,n,s={}){let i=s.inputKeys??null,o=t.map(c=>wi(i?i.reduce((l,u)=>({...l,[u]:c[u]}),{}):c).join(" ")),a=await n.fromTexts(o,t,r,s);return new Lc({vectorStore:a,k:s.k??4,exampleKeys:s.exampleKeys,inputKeys:s.inputKeys})}};var Uc=O({BaseExampleSelector:()=>lr,BasePromptSelector:()=>yi,ConditionalPromptSelector:()=>Rc,LengthBasedExampleSelector:()=>$c,SemanticSimilarityExampleSelector:()=>Fc,isChatModel:()=>jc,isLLM:()=>Mc});var Gr="10f90ea3-90a4-4962-bf75-83a0f3c1c62a",Hc=class extends Ae{lc_namespace=["langchain","recordmanagers"]};var bi=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=ja;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=["hash_","content_hash","metadata_hash"];for(let r of e)if(r in this.metadata)throw new Error(`Metadata cannot contain key ${r} as it is reserved for internal use. Restricted keys: [${e.join(", ")}]`);let t=this._hashStringToUUID(this.pageContent);try{let r=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=r}catch(r){throw new Error(`Failed to hash metadata: ${r}. 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 Se({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let r=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return r.calculateHashes(),r}_hashStringToUUID(e){return Pr(this.keyEncoder(e),Gr)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return Pr(this.keyEncoder(t),Gr)}};function vi(e,t){let r=[],n=[];return t.forEach(s=>{n.push(s),n.length>=e&&(r.push(n),n=[])}),n.length>0&&r.push(n),r}function Si(e){let t=new Set,r=[];for(let n of e){if(!n.hash_)throw new Error("Hashed document does not have a hash");t.has(n.hash_)||(t.add(n.hash_),r.push(n))}return r}function ki(e){if(e===null)return t=>null;if(typeof e=="string")return t=>t.metadata[e];if(typeof e=="function")return e;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var Ei=e=>"load"in e&&typeof e.load=="function"&&"loadAndSplit"in e&&typeof e.loadAndSplit=="function";async function Bc(e){let{docsSource:t,recordManager:r,vectorStore:n,options:s}=e,{batchSize:i=100,cleanup:o,sourceIdKey:a,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=s??{};if(o==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");let u=Ei(t)?await t.load():t,h=ki(a??null),p=await r.getTime(),f=0,m=0,d=0,_=0,g=vi(i??100,u);for(let y of g){let S=Si(y.map(x=>bi.fromDocument(x))),w=S.map(x=>h(x));o==="incremental"&&S.forEach((x,F)=>{if(w[F]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});let C=await r.exists(S.map(x=>x.uid)),T=[],k=[],b=[],I=new Set;if(S.forEach((x,F)=>{if(C[F])if(l)I.add(x.uid);else{b.push(x.uid);return}T.push(x.uid),k.push(x.toDocument())}),b.length>0&&(await r.update(b,{timeAtLeast:p}),_+=b.length),k.length>0&&(await n.addDocuments(k,{ids:T}),f+=k.length-I.size,d+=I.size),await r.update(S.map(x=>x.uid),{timeAtLeast:p,groupIds:w}),o==="incremental"){w.forEach(F=>{if(!F)throw new Error("Source id cannot be null")});let x=await r.listKeys({before:p,groupIds:w});x.length>0&&(await n.delete({ids:x}),await r.deleteKeys(x),m+=x.length)}}if(o==="full"){let y=await r.listKeys({before:p,limit:c});for(;y.length>0;)await n.delete({ids:y}),await r.deleteKeys(y),m+=y.length,y=await r.listKeys({before:p,limit:c})}return{numAdded:f,numDeleted:m,numUpdated:d,numSkipped:_}}var Gc=O({RecordManager:()=>Hc,UUIDV5_NAMESPACE:()=>Gr,_HashedDocument:()=>bi,_batch:()=>vi,_deduplicateInOrder:()=>Si,_getSourceIdAssigner:()=>ki,_isBaseDocumentLoader:()=>Ei,index:()=>Bc});var Wc=O({});var Kc=O({});var qc=O({BaseMemory:()=>tp,getInputValue:()=>rp,getOutputValue:()=>np,getPromptInputKey:()=>sp}),tp=class{},zc=(e,t)=>{if(t!==void 0)return e[t];let r=Object.keys(e);if(r.length===1)return e[r[0]]},rp=(e,t)=>{let r=zc(e,t);if(!r){let n=Object.keys(e);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},np=(e,t)=>{let r=zc(e,t);if(!r&&r!==""){let n=Object.keys(e);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function sp(e,t){let r=Object.keys(e).filter(n=>!t.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var Ci=class extends ti{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if("message"in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},xi=class extends sc{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new Ci(e)}_diff(e,t){if(t)return La(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:r}=t,n=r.additional_kwargs.function_call;if(n)return this.argsOnly?qs(n.arguments):{...n,arguments:qs(n.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},Jc=class extends ti{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new xi;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}};var Yc=O({JsonKeyOutputFunctionsParser:()=>Jc,JsonOutputFunctionsParser:()=>xi,OutputFunctionsParser:()=>Ci});var Je=class extends G{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},r={};for(let[n,s]of Object.entries(t))typeof s=="string"?r[n]=s:r[n]=await s();return{...r,...e}}async invoke(e,t){let r={...this.metadata,...t?.metadata},n=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),e,{...t,tags:n,metadata:r,runType:"prompt"})}};var at=class extends Je{async formatPromptValue(e){return new Wa(await this.format(e))}};var ip=Object.prototype.toString,hr=Array.isArray||function(t){return ip.call(t)==="[object Array]"};function Ii(e){return typeof e=="function"}function op(e){return hr(e)?"array":typeof e}function Ti(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Xc(e,t){return e!=null&&typeof e=="object"&&t in e}function ap(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var cp=RegExp.prototype.test;function lp(e,t){return cp.call(e,t)}var up=/\S/;function hp(e){return!lp(up,e)}var pp={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function fp(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return pp[r]})}var mp=/\s*/,dp=/\s+/,Qc=/\s*=/,gp=/\s*\}/,_p=/#|\^|\/|>|\{|&|=|!/;function yp(e,t){if(!e)return[];var r=!1,n=[],s=[],i=[],o=!1,a=!1,c="",l=0;function u(){if(o&&!a)for(;i.length;)delete s[i.pop()];else i=[];o=!1,a=!1}var h,p,f;function m(b){if(typeof b=="string"&&(b=b.split(dp,2)),!hr(b)||b.length!==2)throw new Error("Invalid tags: "+b);h=new RegExp(Ti(b[0])+"\\s*"),p=new RegExp("\\s*"+Ti(b[1])),f=new RegExp("\\s*"+Ti("}"+b[1]))}m(t||xe.tags);for(var d=new Kr(e),_,g,y,S,w,C;!d.eos();){if(_=d.pos,y=d.scanUntil(h),y)for(var T=0,k=y.length;T<k;++T)S=y.charAt(T),hp(S)?(i.push(s.length),c+=S):(a=!0,r=!0,c+=" "),s.push(["text",S,_,_+1]),_+=1,S===`
|
|
6
|
+
`&&(u(),c="",l=0,r=!1);if(!d.scan(h))break;if(o=!0,g=d.scan(_p)||"name",d.scan(mp),g==="="?(y=d.scanUntil(Qc),d.scan(Qc),d.scanUntil(p)):g==="{"?(y=d.scanUntil(f),d.scan(gp),d.scanUntil(p),g="&"):y=d.scanUntil(p),!d.scan(p))throw new Error("Unclosed tag at "+d.pos);if(g==">"?w=[g,y,_,d.pos,c,l,r]:w=[g,y,_,d.pos],l++,s.push(w),g==="#"||g==="^")n.push(w);else if(g==="/"){if(C=n.pop(),!C)throw new Error('Unopened section "'+y+'" at '+_);if(C[1]!==y)throw new Error('Unclosed section "'+C[1]+'" at '+_)}else g==="name"||g==="{"||g==="&"?a=!0:g==="="&&m(y)}if(u(),C=n.pop(),C)throw new Error('Unclosed section "'+C[1]+'" at '+d.pos);return bp(wp(s))}function wp(e){for(var t=[],r,n,s=0,i=e.length;s<i;++s)r=e[s],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function bp(e){for(var t=[],r=t,n=[],s,i,o=0,a=e.length;o<a;++o)switch(s=e[o],s[0]){case"#":case"^":r.push(s),n.push(s),r=s[4]=[];break;case"/":i=n.pop(),i[5]=s[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(s)}return t}function Kr(e){this.string=e,this.tail=e,this.pos=0}Kr.prototype.eos=function(){return this.tail===""};Kr.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Kr.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function ur(e,t){this.view=e,this.cache={".":this.view},this.parent=t}ur.prototype.push=function(t){return new ur(t,this)};ur.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var s=this,i,o,a,c=!1;s;){if(t.indexOf(".")>0)for(i=s.view,o=t.split("."),a=0;i!=null&&a<o.length;)a===o.length-1&&(c=Xc(i,o[a])||ap(i,o[a])),i=i[o[a++]];else i=s.view[t],c=Xc(s.view,t);if(c){n=i;break}s=s.parent}r[t]=n}return Ii(n)&&(n=n.call(this.view)),n};function me(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}me.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};me.prototype.parse=function(t,r){var n=this.templateCache,s=t+":"+(r||xe.tags).join(":"),i=typeof n<"u",o=i?n.get(s):void 0;return o==null&&(o=yp(t,r),i&&n.set(s,o)),o};me.prototype.render=function(t,r,n,s){var i=this.getConfigTags(s),o=this.parse(t,i),a=r instanceof ur?r:new ur(r,void 0);return this.renderTokens(o,a,n,t,s)};me.prototype.renderTokens=function(t,r,n,s,i){for(var o="",a,c,l,u=0,h=t.length;u<h;++u)l=void 0,a=t[u],c=a[0],c==="#"?l=this.renderSection(a,r,n,s,i):c==="^"?l=this.renderInverted(a,r,n,s,i):c===">"?l=this.renderPartial(a,r,n,i):c==="&"?l=this.unescapedValue(a,r):c==="name"?l=this.escapedValue(a,r,i):c==="text"&&(l=this.rawValue(a)),l!==void 0&&(o+=l);return o};me.prototype.renderSection=function(t,r,n,s,i){var o=this,a="",c=r.lookup(t[1]);function l(p){return o.render(p,r,n,i)}if(c){if(hr(c))for(var u=0,h=c.length;u<h;++u)a+=this.renderTokens(t[4],r.push(c[u]),n,s,i);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")a+=this.renderTokens(t[4],r.push(c),n,s,i);else if(Ii(c)){if(typeof s!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(r.view,s.slice(t[3],t[5]),l),c!=null&&(a+=c)}else a+=this.renderTokens(t[4],r,n,s,i);return a}};me.prototype.renderInverted=function(t,r,n,s,i){var o=r.lookup(t[1]);if(!o||hr(o)&&o.length===0)return this.renderTokens(t[4],r,n,s,i)};me.prototype.indentPartial=function(t,r,n){for(var s=r.replace(/[^ \t]/g,""),i=t.split(`
|
|
7
|
+
`),o=0;o<i.length;o++)i[o].length&&(o>0||!n)&&(i[o]=s+i[o]);return i.join(`
|
|
8
|
+
`)};me.prototype.renderPartial=function(t,r,n,s){if(n){var i=this.getConfigTags(s),o=Ii(n)?n(t[1]):n[t[1]];if(o!=null){var a=t[6],c=t[5],l=t[4],u=o;c==0&&l&&(u=this.indentPartial(o,l,a));var h=this.parse(u,i);return this.renderTokens(h,r,n,u,s)}}};me.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};me.prototype.escapedValue=function(t,r,n){var s=this.getConfigEscape(n)||xe.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&s===xe.escape?String(i):s(i)};me.prototype.rawValue=function(t){return t[1]};me.prototype.getConfigTags=function(t){return hr(t)?t:t&&typeof t=="object"?t.tags:void 0};me.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!hr(t))return t.escape};var xe={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(e){Wr.templateCache=e},get templateCache(){return Wr.templateCache}},Wr=new me;xe.clearCache=function(){return Wr.clearCache()};xe.parse=function(t,r){return Wr.parse(t,r)};xe.render=function(t,r,n,s){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+op(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Wr.render(t,r,n,s)};xe.escape=fp;xe.Scanner=Kr;xe.Context=ur;xe.Writer=me;var Ai=xe;var vp={escape:e=>e},Wt=e=>{let t=e.split(""),r=[],n=(i,o)=>{for(let a=o;a<t.length;a+=1)if(i.includes(t[a]))return a;return-1},s=0;for(;s<t.length;)if(t[s]==="{"&&s+1<t.length&&t[s+1]==="{")r.push({type:"literal",text:"{"}),s+=2;else if(t[s]==="}"&&s+1<t.length&&t[s+1]==="}")r.push({type:"literal",text:"}"}),s+=2;else if(t[s]==="{"){let i=n("}",s);if(i<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(s+1,i).join("")}),s=i+1}else{if(t[s]==="}")throw new Error("Single '}' in template.");{let i=n("{}",s),o=(i<0?t.slice(s):t.slice(s,i)).join("");r.push({type:"literal",text:o}),s=i<0?t.length:i}}return r},Zc=(e,t=[])=>{let r=[];for(let n of e)if(n[0]==="name"){let s=n[1].includes(".")?n[1].split(".")[0]:n[1];r.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(n[0])){if(r.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let s=[...t,n[1]],i=Zc(n[4],s);r.push(...i)}}else r.push({type:"literal",text:n[1]});return r},pr=e=>{let t=Ai.parse(e);return Zc(t)},Oi=(e,t)=>Wt(e).reduce((r,n)=>{if(n.type==="variable"){if(n.name in t)return r+(typeof t[n.name]=="string"?t[n.name]:JSON.stringify(t[n.name]));throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),Ni=(e,t)=>Ai.render(e,t,void 0,vp),qr={"f-string":Oi,mustache:Ni},Pi={"f-string":Wt,mustache:pr},ce=(e,t,r)=>{try{return qr[t](e,r)}catch(n){throw vn(n,"INVALID_PROMPT_INPUT")}},Kt=(e,t)=>Pi[t](e),ct=(e,t,r)=>{if(!(t in qr)){let n=Object.keys(qr);throw new Error(`Invalid template format. Got \`${t}\`;
|
|
9
|
+
should be one of ${n}`)}try{let n=Object.fromEntries(r.map(s=>[s,"foo"]));Array.isArray(e)?e.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")ce(s.text,t,n);else if(s.type==="image_url"){if(typeof s.image_url=="string")ce(s.image_url,t,n);else if(typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"){let i=s.image_url.url;ce(i,t,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):ce(e,t,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}};var Re=class zr extends at{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ct(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(t){let r=await this.mergePartialAndUserVariables(t);return ce(this.template,this.templateFormat,r)}static fromExamples(t,r,n,s=`
|
|
10
|
+
|
|
11
|
+
`,i=""){let o=[i,...t,r].join(s);return new zr({inputVariables:n,template:o})}static fromTemplate(t,r){let{templateFormat:n="f-string",...s}=r??{},i=new Set;return Kt(t,n).forEach(o=>{o.type==="variable"&&i.add(o.name)}),new zr({inputVariables:[...i],templateFormat:n,template:t,...s})}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new zr(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(t){if(!t.template)throw new Error("Prompt template must have a template");return new zr({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}};var fr=class el extends Je{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ct([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new el(s)}async format(t){let r={};for(let[o,a]of Object.entries(this.template))typeof a=="string"?r[o]=ce(a,this.templateFormat,t):r[o]=a;let n=t.url||r.url,s=t.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let i={url:n};return s&&(i.detail=s),i}async formatPromptValue(t){return new qa(await this.format(t))}};var Jr=class extends G{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(e){let t=e.templateFormat??"f-string",r=Ri(e.template,t);super({inputVariables:r,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=r}async format(e){return Mi(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function Ri(e,t){let r=[];for(let n of Object.values(e))if(typeof n=="string")Kt(n,t).forEach(s=>{s.type==="variable"&&r.push(s.name)});else if(Array.isArray(n))for(let s of n)typeof s=="string"?Kt(s,t).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof s=="object"&&r.push(...Ri(s,t));else typeof n=="object"&&n!==null&&r.push(...Ri(n,t));return Array.from(new Set(r))}function Mi(e,t,r){let n={};for(let[s,i]of Object.entries(e))if(typeof i=="string")n[s]=ce(i,r,t);else if(Array.isArray(i)){let o=[];for(let a of i)typeof a=="string"?o.push(ce(a,r,t)):typeof a=="object"&&o.push(Mi(a,t,r));n[s]=o}else typeof i=="object"&&i!==null?n[s]=Mi(i,t,r):n[s]=i;return n}var Yr=class extends G{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(r=>this.formatMessages(r),e,{...t,runType:"prompt"})}},Hn=class extends Yr{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(e){typeof e=="string"&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t=e[this.variableName];if(this.optional&&!t)return[];if(!t){let n=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw n.name="InputFormatError",n}let r;try{Array.isArray(t)?r=t.map(Ne):r=[Ne(t)]}catch(n){let s=typeof t=="string"?t:JSON.stringify(t,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: ${n.message}`].join(`
|
|
12
|
+
|
|
13
|
+
`));throw i.name="InputFormatError",i.lc_error_code=n.lc_error_code,i}return r}},ji=class extends Yr{prompt;constructor(e){"prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Xr=class extends Je{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){return new Ka(await this.formatMessages(e))}},Di=class extends ji{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new zs(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(Re.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}};function Sp(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).length===1&&"text"in e&&typeof e.text=="string"}function kp(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:"image_url"in e&&(typeof e.image_url=="string"||typeof e.image_url=="object"&&e.image_url!==null&&"url"in e.image_url&&typeof e.image_url.url=="string")}var $i=class extends Yr{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(e,t){if("prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(n=>{"inputVariables"in n&&(r=r.concat(n.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass())return new(t._messageClass())({content:e});if(t.chatMessageClass){let r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){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(e,t){if(typeof e=="string")return new this(Re.fromTemplate(e,t));let r=[];for(let n of e)if(typeof n=="string")r.push(Re.fromTemplate(n,t));else if(n!==null)if(Sp(n)){let s="";typeof n.text=="string"&&(s=n.text??"");let i={...t,additionalContentFields:n};r.push(Re.fromTemplate(s,i))}else if(kp(n)){let s=n.image_url??"",i,o=[];if(typeof s=="string"){let a;t?.templateFormat==="mustache"?a=pr(s):a=Wt(s);let c=a.flatMap(l=>l.type==="variable"?[l.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
|
|
14
|
+
Got: ${c}
|
|
15
|
+
From: ${s}`);o=[c[0]]}else o=[];s={url:s},i=new fr({template:s,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else if(typeof s=="object"){if("url"in s){let a;t?.templateFormat==="mustache"?a=pr(s.url):a=Wt(s.url),o=a.flatMap(c=>c.type==="variable"?[c.name]:[])}else o=[];i=new fr({template:s,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else throw new Error("Invalid image template");r.push(i)}else typeof n=="object"&&r.push(new Jr({template:n,templateFormat:t?.templateFormat}));return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof at){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let s of r.inputVariables)n||(n={[s]:e[s]}),n={...n,[s]:e[s]};if(r instanceof at){let s=await r.format(n),i;"additionalContentFields"in r&&(i=r.additionalContentFields),s!==""&&t.push({...i,type:"text",text:s})}else if(r instanceof fr){let s=await r.format(n),i;"additionalContentFields"in r&&(i=r.additionalContentFields),t.push({...i,type:"image_url",image_url:s})}else if(r instanceof Jr){let s=await r.format(n),i;"additionalContentFields"in r&&(i=r.additionalContentFields),t.push({...i,...s})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},Bn=class extends $i{static _messageClass(){return _t}static lc_name(){return"HumanMessagePromptTemplate"}},Vi=class extends $i{static _messageClass(){return Q}static lc_name(){return"AIMessagePromptTemplate"}},Fi=class extends $i{static _messageClass(){return Sn}static lc_name(){return"SystemMessagePromptTemplate"}};function Ep(e){return typeof e.formatMessages=="function"}function Cp(e,t){if(Ep(e)||Oe(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){let s=e[1];if(t?.templateFormat==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}")return new Hn({variableName:s.slice(2,-2),optional:!0});if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}")return new Hn({variableName:s.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let r=Ne(e),n;if(typeof r.content=="string"?n=r.content:n=r.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),r._getType()==="human")return Bn.fromTemplate(n,t);if(r._getType()==="ai")return Vi.fromTemplate(n,t);if(r._getType()==="system")return Fi.fromTemplate(n,t);if(zs.isInstance(r))return Di.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}function xp(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var mr=class Un extends Xr{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){let r=new Set;for(let a of this.promptMessages)if(!(a instanceof X))for(let c of a.inputVariables)r.add(c);let n=this.inputVariables,s=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...s].filter(a=>!r.has(a)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let o=new Set([...r].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(t,r){return typeof t.content=="string"||(t.content=await Promise.all(t.content.map(async n=>{if(n.type!=="image_url")return n;let s="";typeof n.image_url=="string"?s=n.image_url:typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(s=n.image_url.url);let i=await Re.fromTemplate(s,{templateFormat:this.templateFormat}).format(r);return typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url?n.image_url.url=i:n.image_url=i,n}))),t}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=[];for(let s of this.promptMessages)if(s instanceof X)n.push(await this._parseImagePrompts(s,r));else{let i;this.templateFormat==="mustache"?i={...r}:i=s.inputVariables.reduce((a,c)=>{if(!(c in r)&&!(xp(s)&&s.optional))throw vn(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return a[c]=r[c],a},{});let o=await s.formatMessages(i);n=n.concat(o)}return n}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new Un(s)}static fromTemplate(t,r){let n=new Bn({prompt:Re.fromTemplate(t,r)});return this.fromMessages([n])}static fromMessages(t,r){let n=t.reduce((o,a)=>o.concat(a instanceof Un?a.promptMessages:[Cp(a,r)]),[]),s=t.reduce((o,a)=>a instanceof Un?Object.assign(o,a.partialVariables):o,Object.create(null)),i=new Set;for(let o of n)if(!(o instanceof X))for(let a of o.inputVariables)a in s||i.add(a);return new this({...r,inputVariables:[...i],promptMessages:n,partialVariables:s,templateFormat:r?.templateFormat})}};var tl=class Li extends at{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
16
|
+
|
|
17
|
+
`;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(t){if(super(t),Object.assign(this,t),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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ct(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new Li(s)}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),s=await Promise.all(n.map(i=>this.examplePrompt.format(i)));return ce([this.prefix,...s,this.suffix].join(this.exampleSeparator),this.templateFormat,r)}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(t){let{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");let n=await Re.deserialize(r),s;if(Array.isArray(t.examples))s=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new Li({inputVariables:t.input_variables,examplePrompt:n,examples:s,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},rl=class nl extends Xr{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
18
|
+
|
|
19
|
+
`;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
|
|
20
|
+
|
|
21
|
+
`,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),ct(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r);n=n.map(i=>{let o={};return this.examplePrompt.inputVariables.forEach(a=>{o[a]=i[a]}),o});let s=[];for(let i of n){let o=await this.examplePrompt.formatMessages(i);s.push(...o)}return s}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),s=(await Promise.all(n.map(i=>this.examplePrompt.formatMessages(i)))).flat().map(i=>i.content);return ce([this.prefix,...s,this.suffix].join(this.exampleSeparator),this.templateFormat,r)}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},s={...this,inputVariables:r,partialVariables:n};return new nl(s)}};var sl=class Gn extends Je{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(t){super({...t,inputVariables:[]}),this.pipelinePrompts=t.pipelinePrompts,this.finalPrompt=t.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let t=this.pipelinePrompts.map(n=>n.name),r=this.pipelinePrompts.map(n=>n.prompt.inputVariables.filter(s=>!t.includes(s))).flat();return[...new Set(r)]}static extractRequiredInputValues(t,r){return r.reduce((n,s)=>(n[s]=t[s],n),{})}async formatPipelinePrompts(t){let r=await this.mergePartialAndUserVariables(t);for(let{name:n,prompt:s}of this.pipelinePrompts){let i=Gn.extractRequiredInputValues(r,s.inputVariables);s instanceof mr?r[n]=await s.formatMessages(i):r[n]=await s.format(i)}return Gn.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(t){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(t))}async format(t){return this.finalPrompt.format(await this.formatPipelinePrompts(t))}async partial(t){let r={...this};return r.inputVariables=this.inputVariables.filter(n=>!(n in t)),r.partialVariables={...this.partialVariables??{},...t},new Gn(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function il(e){return typeof e=="object"&&e!=null&&"withStructuredOutput"in e&&typeof e.withStructuredOutput=="function"}function Tp(e){return typeof e=="object"&&e!=null&&"lc_id"in e&&Array.isArray(e.lc_id)&&e.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var ol=class al extends mr{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(t){super(t),this.schema=t.schema,this.method=t.method}pipe(t){if(il(t))return super.pipe(t.withStructuredOutput(this.schema));if(Tp(t)&&il(t.bound))return super.pipe(new En({bound:t.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:t.kwargs??{},config:t.config,configFactories:t.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(t,r,n){return al.fromMessages(t,{schema:r,method:n})}};var cl=O({AIMessagePromptTemplate:()=>Vi,BaseChatPromptTemplate:()=>Xr,BaseMessagePromptTemplate:()=>Yr,BaseMessageStringPromptTemplate:()=>ji,BasePromptTemplate:()=>Je,BaseStringPromptTemplate:()=>at,ChatMessagePromptTemplate:()=>Di,ChatPromptTemplate:()=>mr,DEFAULT_FORMATTER_MAPPING:()=>qr,DEFAULT_PARSER_MAPPING:()=>Pi,DictPromptTemplate:()=>Jr,FewShotChatMessagePromptTemplate:()=>rl,FewShotPromptTemplate:()=>tl,HumanMessagePromptTemplate:()=>Bn,ImagePromptTemplate:()=>fr,MessagesPlaceholder:()=>Hn,PipelinePromptTemplate:()=>sl,PromptTemplate:()=>Re,StructuredPrompt:()=>ol,SystemMessagePromptTemplate:()=>Fi,checkValidTemplate:()=>ct,interpolateFString:()=>Oi,interpolateMustache:()=>Ni,parseFString:()=>Wt,parseMustache:()=>pr,parseTemplate:()=>Kt,renderTemplate:()=>ce});var ll=O({BaseDocumentCompressor:()=>Ip}),Ip=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}};var ul=O({BaseRetriever:()=>Qr}),Qr=class extends G{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){let r=Aa(Ta(t)),n=await(await rr.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let s=await this._getRelevantDocuments(e,n);return await n?.handleRetrieverEnd(s),s}catch(s){throw await n?.handleRetrieverError(s),s}}};var hl=O({BaseStore:()=>pl,InMemoryStore:()=>Ap}),pl=class extends Ae{},Ap=class extends pl{lc_namespace=["langchain","storage"];store={};async mget(e){return e.map(t=>this.store[t])}async mset(e){for(let[t,r]of e)this.store[t]=r}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let r of t)(e===void 0||r.startsWith(e))&&(yield r)}};var Me={and:"and",or:"or",not:"not"},D={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},Wn=class{},Kn=class{accept(e){if(this.exprName==="Operation")return e.visitOperation(this);if(this.exprName==="Comparison")return e.visitComparison(this);if(this.exprName==="StructuredQuery")return e.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},qn=class extends Kn{},fl=class extends qn{comparator;attribute;value;exprName="Comparison";constructor(e,t,r){super(),this.comparator=e,this.attribute=t,this.value=r}},ml=class extends qn{operator;args;exprName="Operation";constructor(e,t){super(),this.operator=e,this.args=t}},dl=class extends Kn{query;filter;exprName="StructuredQuery";constructor(e,t){super(),this.query=e,this.filter=t}};function Ui(e){return e&&typeof e=="object"&&!Array.isArray(e)}function ye(e){return e?typeof e=="string"&&e.length>0||typeof e=="function"?!1:Ui(e)&&Object.keys(e).length===0:!0}function Hi(e){if(typeof e=="number")return e%1===0;if(typeof e=="string"){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1===0&&t.toString()===e}return!1}function Bi(e){if(typeof e=="number")return e%1!==0;if(typeof e=="string"){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!==0&&t.toString()===e}return!1}function Gi(e){return typeof e=="string"&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function Wi(e){return typeof e=="boolean"}function dr(e){let t;if(Gi(e))t=e;else if(Hi(e))t=parseInt(e,10);else if(Bi(e))t=parseFloat(e);else if(Wi(e))t=!!e;else throw new Error("Unsupported value type");return t}var Zr=class extends Wn{},gl=class extends Zr{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[Me.and,Me.or],this.allowedComparators=e?.allowedComparators??[D.eq,D.ne,D.gt,D.gte,D.lt,D.lte]}formatFunction(e){if(e in D){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in Me){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){let t=e.args?.map(r=>r.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:dr(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,r="and",n=!1){if(!(ye(e)&&ye(t))){if(ye(e)||r==="replace")return ye(t)?void 0:t;if(ye(t))return n?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,t]};if(r==="or")return{$or:[e,t]};throw new Error("Unknown merge type")}}};var _l=class extends Zr{allowedOperators=[Me.and,Me.or];allowedComparators=[D.eq,D.ne,D.gt,D.gte,D.lt,D.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[D.eq,D.ne,D.gt,D.gte,D.lt,D.lte];case"number":return[D.eq,D.ne,D.gt,D.gte,D.lt,D.lte];case"boolean":return[D.eq,D.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case D.eq:return(t,r)=>t===r;case D.ne:return(t,r)=>t!==r;case D.gt:return(t,r)=>t>r;case D.gte:return(t,r)=>t>=r;case D.lt:return(t,r)=>t<r;case D.lte:return(t,r)=>t<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case Me.and:return(t,r)=>t&&r;case Me.or:return(t,r)=>t||r;default:throw new Error("Unknown operator")}}visitOperation(e){let{operator:t,args:r}=e;if(this.allowedOperators.includes(t)){let n=this.getOperatorFunction(t);return s=>r?r.reduce((i,o)=>{let a=o.accept(this);if(typeof a=="function")return n(i,a(s));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){let{comparator:t,attribute:r,value:n}=e,s=[D.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof n).includes(t))throw new Error(`'${t}' comparator not allowed to be used with ${typeof n}`);let i=this.getComparatorFunction(t);return o=>{let a=o.metadata[r];return a===void 0?!!s.includes(t):i(a,dr(n))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!="function")throw new Error("Structured query filter is not a function");return{filter:t}}mergeFilters(e,t,r="and"){if(!(ye(e)&&ye(t))){if(ye(e)||r==="replace")return ye(t)?void 0:t;if(ye(t))return r==="and"?void 0:e;if(r==="and")return n=>e(n)&&t(n);if(r==="or")return n=>e(n)||t(n);throw new Error("Unknown merge type")}}};var yl=O({BaseTranslator:()=>Zr,BasicTranslator:()=>gl,Comparators:()=>D,Comparison:()=>fl,Expression:()=>Kn,FilterDirective:()=>qn,FunctionalTranslator:()=>_l,Operation:()=>ml,Operators:()=>Me,StructuredQuery:()=>dl,Visitor:()=>Wn,castValue:()=>dr,isBoolean:()=>Wi,isFilterEmpty:()=>ye,isFloat:()=>Bi,isInt:()=>Hi,isObject:()=>Ui,isString:()=>Gi});function en(e){if(e==null||typeof e!="object")return!1;let t=e;return typeof t.text<"u"&&typeof t.toolCalls<"u"&&typeof t.reasoning<"u"&&typeof t.usage<"u"&&typeof t.output<"u"&&typeof t[Symbol.asyncIterator]=="function"}function wl(e,t,r){return e==null?!1:Object.entries(t).every(([n,s])=>r(e[n],s))}function bl(e,t,r){return e==null?!1:wl(e,t,r)}function vl(e){return e.content.find(t=>t.type==="text")?.text}function Op(e,t,r){if(t.id!==void 0&&e.id!==t.id||t.text!==void 0&&vl(e)!==t.text)return!1;if(t.toolCalls!==void 0){let n=e.tool_calls??[];if(n.length!==t.toolCalls.length)return!1;for(let s=0;s<t.toolCalls.length;s++){let i=n[s],o=t.toolCalls[s];if(i?.name!==o.name||!r(i.args,o.args))return!1}}return!(t.usage!==void 0&&!bl(e.usage_metadata,t.usage,r)||t.responseMetadata!==void 0&&!wl(e.response_metadata,t.responseMetadata,r))}function tn(e,t,r){return{pass:!1,message:()=>`${r.matcherHint(t)}
|
|
22
|
+
|
|
23
|
+
Expected: ChatModelStream (return value of model.streamEvents("Hello"))
|
|
24
|
+
Received: ${r.printReceived(e)}`,actual:e,expected:"ChatModelStream"}}function rn(e,t){return t?!e:e}async function Np(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamText";if(!en(e))return tn(e,s,n);let i=await e.text;return{pass:rn(i===t,r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
|
|
25
|
+
|
|
26
|
+
Expected stream text: ${r?"not ":""}${n.printExpected(t)}
|
|
27
|
+
Received stream text: ${n.printReceived(i)}`,actual:i,expected:t}}async function Pp(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamReasoning";if(!en(e))return tn(e,s,n);let i=await e.reasoning;return{pass:rn(i===t,r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
|
|
28
|
+
|
|
29
|
+
Expected stream reasoning: ${r?"not ":""}${n.printExpected(t)}
|
|
30
|
+
Received stream reasoning: ${n.printReceived(i)}`,actual:i,expected:t}}async function Rp(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamToolCalls";if(!en(e))return tn(e,s,n);let i=await e.toolCalls,o=i.length===t.length&&t.every((a,c)=>{let l=i[c];return l?.name===a.name&&this.equals(l.args,a.args)});return o=rn(o,r),{pass:o,message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
|
|
31
|
+
|
|
32
|
+
Expected stream tool calls: ${n.printExpected(t)}
|
|
33
|
+
Received stream tool calls: ${n.printReceived(i.map(a=>({name:a.name,args:a.args})))}`,actual:i.map(a=>({name:a.name,args:a.args})),expected:t}}async function Mp(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamUsage";if(!en(e))return tn(e,s,n);let i=await e.usage;return{pass:rn(bl(i,t,this.equals),r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
|
|
34
|
+
|
|
35
|
+
Expected stream usage: ${n.printExpected(t)}
|
|
36
|
+
Received stream usage: ${n.printReceived(i)}`,actual:i,expected:t}}async function jp(e,t){let{isNot:r,utils:n}=this,s="toHaveStreamOutput";if(!en(e))return tn(e,s,n);let i=await e.output;return{pass:rn(Op(i,t,this.equals),r),message:()=>`${n.matcherHint(s,void 0,void 0,{isNot:r})}
|
|
37
|
+
|
|
38
|
+
Expected stream output: ${n.printExpected(t)}
|
|
39
|
+
Received stream output: ${n.printReceived({id:i.id,text:vl(i),tool_calls:i.tool_calls?.map(o=>({name:o.name,args:o.args})),usage_metadata:i.usage_metadata,response_metadata:i.response_metadata})}`,actual:i,expected:t}}var gr={toHaveStreamText:Np,toHaveStreamReasoning:Pp,toHaveStreamToolCalls:Rp,toHaveStreamUsage:Mp,toHaveStreamOutput:jp};function nn(e){return X.isInstance(e)?e.constructor.name||e.type:typeof e}function zn(e,t){return function(r,n){let{isNot:s,utils:i}=this;if(!t(r))return{pass:!1,message:()=>`${i.matcherHint(`toBe${e}`,void 0,void 0)}
|
|
40
|
+
|
|
41
|
+
Expected: ${s?"not ":""}${e}
|
|
42
|
+
Received: ${nn(r)}`,actual:nn(r),expected:e};if(n===void 0)return{pass:!0,message:()=>`${i.matcherHint(`toBe${e}`,void 0,void 0)}
|
|
43
|
+
|
|
44
|
+
Expected: not ${e}
|
|
45
|
+
Received: ${e}`};let o=r;return typeof n=="string"?{pass:o.content===n,message:()=>`${i.matcherHint(`toBe${e}`,void 0,void 0)}
|
|
46
|
+
|
|
47
|
+
Expected: ${e} with content ${i.printExpected(n)}
|
|
48
|
+
Received: ${e} with content ${i.printReceived(o.content)}`,actual:o.content,expected:n}:{pass:Object.entries(n).every(([a,c])=>this.equals(o[a],c)),message:()=>{let a={};for(let c of Object.keys(n))a[c]=o[c];return`${i.matcherHint(`toBe${e}`,void 0,void 0)}
|
|
49
|
+
|
|
50
|
+
Expected: ${e} matching ${i.printExpected(n)}
|
|
51
|
+
Received: ${e} with ${i.printReceived(a)}`},actual:(()=>{let a={};for(let c of Object.keys(n))a[c]=o[c];return a})(),expected:n}}}var Ki=zn("HumanMessage",_t.isInstance),qi=zn("AIMessage",Q.isInstance),zi=zn("SystemMessage",Sn.isInstance),Ji=zn("ToolMessage",Dt.isInstance);function Yi(e,t){let{isNot:r,utils:n}=this;if(!Q.isInstance(e))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCalls")}
|
|
52
|
+
|
|
53
|
+
Expected: AIMessage
|
|
54
|
+
Received: ${nn(e)}`};let s=e.tool_calls??[];if(s.length!==t.length)return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCalls")}
|
|
55
|
+
|
|
56
|
+
Expected ${r?"not ":""}${t.length} tool call(s), received ${s.length}`,actual:s.length,expected:t.length};let i=t.filter(o=>!s.some(a=>Object.entries(o).every(([c,l])=>this.equals(a[c],l))));return i.length>0?{pass:!1,message:()=>`${n.matcherHint("toHaveToolCalls")}
|
|
57
|
+
|
|
58
|
+
Could not find matching tool call(s) for:
|
|
59
|
+
${n.printExpected(i)}
|
|
60
|
+
Received tool calls: ${n.printReceived(s.map(o=>({name:o.name,id:o.id,args:o.args})))}`,actual:s.map(o=>({name:o.name,id:o.id,args:o.args})),expected:t}:{pass:!0,message:()=>`${n.matcherHint("toHaveToolCalls")}
|
|
61
|
+
|
|
62
|
+
Expected AIMessage not to have matching tool calls`}}function Xi(e,t){let{isNot:r,utils:n}=this;if(!Q.isInstance(e))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolCallCount")}
|
|
63
|
+
|
|
64
|
+
Expected: AIMessage
|
|
65
|
+
Received: ${nn(e)}`};let s=e.tool_calls?.length??0;return{pass:s===t,message:()=>`${n.matcherHint("toHaveToolCallCount")}
|
|
66
|
+
|
|
67
|
+
Expected ${r?"not ":""}${t} tool call(s)
|
|
68
|
+
Received: ${s}`,actual:s,expected:t}}function Qi(e,t){let{isNot:r,utils:n}=this;if(!Q.isInstance(e))return{pass:!1,message:()=>`${n.matcherHint("toContainToolCall")}
|
|
69
|
+
|
|
70
|
+
Expected: AIMessage
|
|
71
|
+
Received: ${nn(e)}`};let s=e.tool_calls??[];return{pass:s.some(i=>Object.entries(t).every(([o,a])=>this.equals(i[o],a))),message:()=>`${n.matcherHint("toContainToolCall")}
|
|
72
|
+
|
|
73
|
+
Expected AIMessage ${r?"not ":""}to contain a tool call matching ${n.printExpected(t)}
|
|
74
|
+
Received tool calls: ${n.printReceived(s.map(i=>({name:i.name,id:i.id})))}`,actual:s.map(i=>({name:i.name,id:i.id})),expected:t}}function Zi(e,t){let{isNot:r,utils:n}=this;if(!Array.isArray(e))return{pass:!1,message:()=>`${n.matcherHint("toHaveToolMessages")}
|
|
75
|
+
|
|
76
|
+
Expected an array of messages
|
|
77
|
+
Received: ${typeof e}`};let s=e.filter(Dt.isInstance);if(s.length!==t.length)return{pass:!1,message:()=>`${n.matcherHint("toHaveToolMessages")}
|
|
78
|
+
|
|
79
|
+
Expected ${r?"not ":""}${t.length} tool message(s), found ${s.length}`,actual:s.length,expected:t.length};for(let i=0;i<t.length;i++)if(!Object.entries(t[i]).every(([o,a])=>this.equals(s[i][o],a)))return{pass:!1,message:()=>{let o={};for(let a of Object.keys(t[i]))o[a]=s[i][a];return`${n.matcherHint("toHaveToolMessages")}
|
|
80
|
+
|
|
81
|
+
Tool message at index ${i} did not match:
|
|
82
|
+
Expected: ${n.printExpected(t[i])}
|
|
83
|
+
Received: ${n.printReceived(o)}`},actual:s[i],expected:t[i]};return{pass:!0,message:()=>`${n.matcherHint("toHaveToolMessages")}
|
|
84
|
+
|
|
85
|
+
Expected messages not to contain matching tool messages`}}function eo(e,t){let{isNot:r,utils:n}=this,s=e?.__interrupt__;if(!(Array.isArray(s)&&s.length>0))return{pass:!1,message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
|
|
86
|
+
|
|
87
|
+
Expected result ${r?"not ":""}to have been interrupted
|
|
88
|
+
Received __interrupt__: ${n.printReceived(s)}`};if(t===void 0)return{pass:!0,message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
|
|
89
|
+
|
|
90
|
+
Expected result not to have been interrupted
|
|
91
|
+
Received ${s.length} interrupt(s)`};let i=s[0]?.value;return{pass:this.equals(i,t),message:()=>`${n.matcherHint("toHaveBeenInterrupted")}
|
|
92
|
+
|
|
93
|
+
Expected interrupt value: ${n.printExpected(t)}
|
|
94
|
+
Received interrupt value: ${n.printReceived(i)}`,actual:i,expected:t}}function to(e,t){let{isNot:r,utils:n}=this,s=e?.structuredResponse;return s===void 0?{pass:!1,message:()=>`${n.matcherHint("toHaveStructuredResponse")}
|
|
95
|
+
|
|
96
|
+
Expected result ${r?"not ":""}to have a structured response
|
|
97
|
+
Received structuredResponse: undefined`}:t===void 0?{pass:!0,message:()=>`${n.matcherHint("toHaveStructuredResponse")}
|
|
98
|
+
|
|
99
|
+
Expected result not to have a structured response`}:{pass:Object.entries(t).every(([i,o])=>this.equals(s[i],o)),message:()=>`${n.matcherHint("toHaveStructuredResponse")}
|
|
100
|
+
|
|
101
|
+
Expected structured response: ${n.printExpected(t)}
|
|
102
|
+
Received structured response: ${n.printReceived(s)}`,actual:s,expected:t}}var Sl={toBeHumanMessage:Ki,toBeAIMessage:qi,toBeSystemMessage:zi,toBeToolMessage:Ji,toHaveToolCalls:Yi,toHaveToolCallCount:Xi,toContainToolCall:Qi,toHaveToolMessages:Zi,toHaveBeenInterrupted:eo,toHaveStructuredResponse:to,...gr};function Dp(e){return e.map(t=>t.text).filter(Boolean).join("-")}var kl=0;function $p(){return kl+=1,`fake_tc_${kl}`}var ro=class El extends ir{queue=[];_alwaysThrowError;_structuredResponseValue;_tools=[];_state={callIndex:0,calls:[]};get calls(){return this._state.calls}get callCount(){return this._state.calls.length}constructor(){super({})}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(t){return typeof t=="function"?this.queue.push({kind:"factory",factory:t}):X.isInstance(t)?this.queue.push({kind:"message",message:t}):this.queue.push({kind:"error",error:t}),this}respondWithTools(t){return this.queue.push({kind:"toolCalls",toolCalls:t.map(r=>({name:r.name,args:r.args,id:r.id??$p(),type:"tool_call"}))}),this}alwaysThrow(t){return this._alwaysThrowError=t,this}structuredResponse(t){return this._structuredResponseValue=t,this}bindTools(t){let r=[...this._tools,...t],n=new El;return n.queue=this.queue,n._alwaysThrowError=this._alwaysThrowError,n._structuredResponseValue=this._structuredResponseValue,n._tools=r,n._state=this._state,n.withConfig({})}withStructuredOutput(t,r){let{_structuredResponseValue:n}=this;return Cn.from(async()=>n)}async _generate(t,r,n){this._state.calls.push({messages:[...t],options:r});let s=this._state.callIndex;if(this._state.callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let i=this.queue[s];if(!i)throw new Error(`FakeModel: no response queued for invocation ${s} (${this.queue.length} total queued).`);if(i.kind==="error")throw i.error;if(i.kind==="factory"){let a=i.factory(t);if(!X.isInstance(a))throw a;return{generations:[{text:"",message:a}]}}if(i.kind==="message")return{generations:[{text:"",message:i.message}]};let o=Dp(t);return{generations:[{text:o,message:new Q({content:o,id:s.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(a=>({...a,type:"tool_call"})):void 0})}],llmOutput:{}}}};function Cl(){return new ro}function Jn(e){return{async*[Symbol.asyncIterator](){for(let t of e)yield t}}}function Yn(e="test-model"){let t=sn(e),r=t[t.length-1];return t[t.length-1]={...r,usage:{prompt_tokens:10,completion_tokens:2,total_tokens:12}},t}function sn(e="test-model"){return[{id:"chatcmpl-text",model:e,choices:[{index:0,delta:{role:"assistant",content:"Hello"},finish_reason:null}]},{id:"chatcmpl-text",model:e,choices:[{index:0,delta:{content:" world"},finish_reason:null}]},{id:"chatcmpl-text",model:e,choices:[{index:0,delta:{},finish_reason:"stop"}]}]}function Xn(e="test-model"){return[{id:"chatcmpl-reason",model:e,choices:[{index:0,delta:{role:"assistant",reasoning_content:"Let me reason..."},finish_reason:null}]},{id:"chatcmpl-reason",model:e,choices:[{index:0,delta:{content:"Answer."},finish_reason:null}]},{id:"chatcmpl-reason",model:e,choices:[{index:0,delta:{},finish_reason:"stop"}]}]}function Qn(e="test-model"){return[{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{role:"assistant",content:"Let me search."},finish_reason:null}]},{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{tool_calls:[{index:0,id:"call_abc",type:"function",function:{name:"web_search",arguments:'{"query"'}}]},finish_reason:null}]},{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{tool_calls:[{index:0,function:{arguments:':"weather"}'}}]},finish_reason:null}]},{id:"chatcmpl-tools",model:e,choices:[{index:0,delta:{},finish_reason:"tool_calls"}]}]}function Zn(e){let t=new TextEncoder;return new Response(new ReadableStream({start(r){for(let n of e)r.enqueue(t.encode(`data: ${JSON.stringify(n)}
|
|
103
|
+
|
|
104
|
+
`));r.close()}}),{status:200,headers:{"Content-Type":"text/event-stream"}})}var xl=O({FakeBuiltModel:()=>ro,asAsyncIterable:()=>Jn,fakeModel:()=>Cl,langchainMatchers:()=>Sl,openAIReasoningTextChunks:()=>Xn,openAITextOnlyChunks:()=>sn,openAITextOnlyChunksWithUsage:()=>Yn,openAIToolCallChunks:()=>Qn,sseResponseFromOpenAIChunks:()=>Zn,streamMatchers:()=>gr,toBeAIMessage:()=>qi,toBeHumanMessage:()=>Ki,toBeSystemMessage:()=>zi,toBeToolMessage:()=>Ji,toContainToolCall:()=>Qi,toHaveBeenInterrupted:()=>eo,toHaveStructuredResponse:()=>to,toHaveToolCallCount:()=>Xi,toHaveToolCalls:()=>Yi,toHaveToolMessages:()=>Zi});var Tl=O({RunCollectorCallbackHandler:()=>Vp}),Vp=class extends tr{name="run_collector";exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}};var Il=O({});var Al=O({context:()=>Fp});function Fp(e,...t){let r=e.raw,n="";for(let s=0;s<r.length;s++){let i=r[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(n+=i,s<t.length){let o=Lp(t[s],n);n+=typeof o=="string"?o:JSON.stringify(o)}}return n=Up(n),n=n.trim(),n=n.replace(/\\n/g,`
|
|
105
|
+
`),n}function Lp(e,t){if(typeof e!="string"||!e.includes(`
|
|
106
|
+
`))return e;let r=t.slice(t.lastIndexOf(`
|
|
107
|
+
`)+1).match(/^(\s+)/);if(r){let n=r[1];return e.replace(/\n/g,`
|
|
108
|
+
${n}`)}return e}function Up(e){let t=e.split(`
|
|
109
|
+
`),r=null;for(let n of t){let s=n.match(/^(\s+)\S+/);if(s){let i=s[1].length;r===null?r=i:r=Math.min(r,i)}}return r===null?e:t.map(n=>n[0]===" "||n[0]===" "?n.slice(r):n).join(`
|
|
110
|
+
`)}var Ol=O({EventStreamContentType:()=>Hp,convertEventStreamToIterableReadableDataStream:()=>Gp,getBytes:()=>Nl,getLines:()=>Pl,getMessages:()=>Rl}),Hp="text/event-stream";async function Nl(e,t){if(e instanceof ReadableStream){let r=e.getReader();for(;;){let n=await r.read();if(n.done){t(new Uint8Array,!0);break}t(n.value)}}else try{for await(let r of e)t(new Uint8Array(r));t(new Uint8Array,!0)}catch(r){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${r.message}`].join(`
|
|
111
|
+
`))}}function Pl(e){let t,r,n,s=!1;return function(o,a){if(a){e(o,0,!0);return}t===void 0?(t=o,r=0,n=-1):t=Bp(t,o);let c=t.length,l=0;for(;r<c;){s&&(t[r]===10&&(l=++r),s=!1);let u=-1;for(;r<c&&u===-1;++r)switch(t[r]){case 58:n===-1&&(n=r-l);break;case 13:s=!0;case 10:u=r;break}if(u===-1)break;e(t.subarray(l,u),n),l=r,n=-1}l===c?t=void 0:l!==0&&(t=t.subarray(l),r-=l)}}function Rl(e,t,r){let n=no(),s=new TextDecoder;return function(o,a,c){if(c){Wp(n)||(e?.(n),n=no());return}if(o.length===0)e?.(n),n=no();else if(a>0){let l=s.decode(o.subarray(0,a)),u=a+(o[a+1]===32?2:1),h=s.decode(o.subarray(u));switch(l){case"data":n.data=n.data?n.data+`
|
|
112
|
+
`+h:h;break;case"event":n.event=h;break;case"id":t?.(n.id=h);break;case"retry":{let p=parseInt(h,10);Number.isNaN(p)||r?.(n.retry=p);break}}}}}function Bp(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function no(){return{data:"",event:"",id:"",retry:void 0}}function Gp(e,t){let r=new ReadableStream({async start(n){let s=Rl(o=>{if(o.event==="error")throw new Error(o.data??"Unspecified event streaming error.");o.event==="metadata"?t?.(o):o.data&&n.enqueue(o.data)});await Nl(e,Pl((o,a,c)=>{s(o,a,c),c&&n.close()}))}});return Mr.fromReadableStream(r)}function Wp(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var Ml=O({});function es(e,t){let r=0,n=0,s=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i],n+=e[i]*e[i],s+=t[i]*t[i];return r/(Math.sqrt(n)*Math.sqrt(s))}function jl(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function Kp(e,t){let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])*(e[n]-t[n]);return r}function Dl(e,t){return Math.sqrt(Kp(e,t))}var $l=O({cosineSimilarity:()=>so,euclideanDistance:()=>Jp,innerProduct:()=>zp,matrixFunc:()=>ts,maximalMarginalRelevance:()=>Yp,normalize:()=>qp});function ts(e,t,r){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(n=>t.map(s=>r(n,s)).map(s=>Number.isNaN(s)?0:s))}function qp(e,t=!1){let r=Xp(e);return e.map(n=>n.map(s=>t?1-s/r:s/r))}function so(e,t){return ts(e,t,es)}function zp(e,t){return ts(e,t,jl)}function Jp(e,t){return ts(e,t,Dl)}function Yp(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];let s=so(Array.isArray(e[0])?e:[e],t)[0],i=Vl(s).maxIndex,o=[t[i]],a=[i];for(;a.length<Math.min(n,t.length);){let c=-1/0,l=-1,u=so(t,o);s.forEach((h,p)=>{if(a.includes(p))return;let f=Math.max(...u[p]),m=r*h-(1-r)*f;m>c&&(c=m,l=p)}),o.push(t[l]),a.push(l)}return a}function Vl(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;n<e.length;n+=1)e[n]>t&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}function Xp(e){return e.reduce((t,r)=>Math.max(t,Vl(r).maxValue),0)}var Fl=O({isCloudMetadata:()=>io,isLocalhost:()=>oo,isPrivateIp:()=>Gl,isSafeUrl:()=>of,isSameOrigin:()=>af,validateSafeUrl:()=>Wl}),Qp=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],Zp=["169.254.169.254","169.254.170.2","100.100.100.200"],ef=["metadata.google.internal","metadata","instance-data"],tf=["localhost","localhost.localdomain"],rf=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Ll(e){return rf.test(e)}function rs(e){return Bl(e)!==null}function Ul(e){return Ll(e)||rs(e)}function Hl(e){if(Ll(e))return e.split(".").map(t=>parseInt(t,10));if(rs(e)){let t=Bl(e);if(!t)return null;let r=t.split(":"),n=[];for(let s of r)n.push(parseInt(s,16));return n}return null}function Bl(e){if(!e||typeof e!="string"||!e.includes(":")||!/^[0-9a-fA-F:]+$/.test(e))return null;let t=e;if(t.includes("::")){let n=t.split("::");if(n.length>2)return null;let[s,i]=n,o=s?s.split(":"):[],a=i?i.split(":"):[],c=8-(o.length+a.length);if(c<0)return null;let l=Array(c).fill("0");t=[...o,...l,...a].filter(u=>u!=="").join(":")}let r=t.split(":");if(r.length!==8)return null;for(let n of r)if(n.length===0||n.length>4||!/^[0-9a-fA-F]+$/.test(n))return null;return r.map(n=>n.padStart(4,"0").toLowerCase()).join(":")}function nf(e){let[t,r]=e.split("/");if(!t||!r)return null;let n=Hl(t);if(!n)return null;let s=parseInt(r,10);if(isNaN(s))return null;let i=rs(t);return i&&s>128||!i&&s>32?null:{addr:n,prefixLen:s,isIpv6:i}}function sf(e,t){let r=Hl(e);if(!r)return!1;let n=nf(t);if(!n)return!1;let s=rs(e);if(s!==n.isIpv6)return!1;let{addr:i,prefixLen:o}=n;if(s)for(let a=0;a<Math.ceil(o/16);a++){let c=65535<<16-Math.min(16,o-a*16)&65535;if((r[a]&c)!==(i[a]&c))return!1}else for(let a=0;a<Math.ceil(o/8);a++){let c=255<<8-Math.min(8,o-a*8)&255;if((r[a]&c)!==(i[a]&c))return!1}return!0}function Gl(e){if(!Ul(e))return!1;for(let t of Qp)if(sf(e,t))return!0;return!1}function io(e,t){if(Zp.includes(t||""))return!0;let r=e.toLowerCase();return!!ef.includes(r)}function oo(e,t){if(t&&(t==="127.0.0.1"||t==="::1"||t==="0.0.0.0"||t.startsWith("127.")))return!0;let r=e.toLowerCase();return!!tf.includes(r)}function Wl(e,t){let r=t?.allowPrivate??!1,n=t?.allowHttp??!1;try{let s;try{s=new URL(e)}catch{throw new Error(`Invalid URL: ${e}`)}let i=s.hostname;if(!i)throw new Error("URL missing hostname.");if(io(i))throw new Error(`URL points to cloud metadata endpoint: ${i}`);if(oo(i)){if(!r)throw new Error(`URL points to localhost: ${i}`);return e}let o=s.protocol;if(o!=="http:"&&o!=="https:")throw new Error(`Invalid URL scheme: ${o}. Only http and https are allowed.`);if(o==="http:"&&!n)throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(Ul(i)){let a=i;if(oo(i,a)){if(!r)throw new Error(`URL points to localhost: ${i}`);return e}if(io(i,a))throw new Error(`URL resolves to cloud metadata IP: ${a} (${i})`);if(Gl(a)&&!r)throw new Error(`URL resolves to private IP: ${a} (${i}). Set allowPrivate: true to allow.`);return e}return e}catch(s){throw s&&typeof s=="object"&&"message"in s?s:new Error(`URL validation failed: ${s}`)}}function of(e,t){try{return Wl(e,t),!0}catch{return!1}}function af(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var Kl=O({SaveableVectorStore:()=>cf,VectorStore:()=>ss,VectorStoreRetriever:()=>ns}),ns=class extends Qr{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(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){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(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},ss=class extends Ae{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(s=>s[0])}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,s,i){if(typeof e=="number")return new ns({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:s,verbose:i,callbacks:r});{let o={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new ns({...o,searchKwargs:e.searchKwargs}):new ns({...o})}}},cf=class extends ss{static load(e,t){throw new Error("Not implemented")}};var ql=class extends ir{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,r){if(t?.stop?.length)return{generations:[{message:new Q(t.stop[0]),text:t.stop[0]}]};let n=e.map(s=>typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2)).join(`
|
|
113
|
+
`);return await r?.handleLLMNewToken(n),{generations:[{message:new Q(n),text:n}],llmOutput:{}}}},zl=class Jl extends ir{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:r=[],chunks:n=[],toolStyle:s="openai",thrownErrorString:i,...o}){super(o),this.sleep=t,this.responses=r,this.chunks=n,this.toolStyle=s,this.thrownErrorString=i}_llmType(){return"fake"}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:st(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:st(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:st(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:st(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:n}]:n,i=new Jl({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return i.tools=r,i.withConfig({tools:s})}async _generate(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new Q({content:this.responses?.[0]?.content??t[0].content??"",tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let o of this.chunks){let a=new kn({message:new Zt({content:o.content,tool_calls:o.tool_calls,additional_kwargs:o.additional_kwargs??{}}),text:o.content?.toString()??""});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o.content,void 0,void 0,void 0,void 0,{chunk:a})}return}let s=this.responses?.[0]??new Q(typeof t[0].content=="string"?t[0].content:""),i=typeof s.content=="string"?s.content:"";for(let o of i){await new Promise(c=>setTimeout(c,this.sleep));let a=new kn({message:new Zt({content:o}),text:o});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:a})}}},Yl=class Xl extends ir{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(t){super(t);let{responses:r,sleep:n,emitCustomEvent:s,generationInfo:i}=t;this.responses=r,this.sleep=n,this.emitCustomEvent=s??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,r,n){if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),r?.stop?.length)return{generations:[this._formatGeneration(r.stop[0])]};{let s=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(s)],llmOutput:{}}}}_formatGeneration(t){return{message:new Q(t),text:t}}async*_streamResponseChunks(t,r,n){let s=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});let i=[...s];for(let o=0;o<i.length;o++){let a=i[o],c=o===i.length-1;if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);let l=this._createResponseChunk(a,c?this.generationInfo:void 0);if(r.signal?.aborted)break;yield l,n?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t,r){return new kn({message:new Zt({content:t}),text:t,generationInfo:r})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:st(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:st(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:st(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:st(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),s=this.toolStyle==="google"?[{functionDeclarations:n}]:n,i=new Xl({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return i.tools=r,i.toolStyle=this.toolStyle,i.i=this.i,i.withConfig({tools:s})}withStructuredOutput(t,r){return Cn.from(async n=>{let s=await this.invoke(n);if(s.tool_calls?.[0]?.args)return s.tool_calls[0].args;if(typeof s.content=="string")return JSON.parse(s.content);throw new Error("No structured output found")})}};var Ql=class extends ei{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");let r=t.length%this.vectorSize,n=r===0?0:this.vectorSize-r,s=t.length+n;t=t.padEnd(s," ");let i=t.length/this.vectorSize,o=[];for(let a=0;a<t.length;a+=i)o.push(t.slice(a,a+i));return o.map(a=>{let c=0;for(let l=0;l<a.length;l+=1)c+=a===" "?0:a.charCodeAt(l);return c%26/26})}},Zl=class extends ei{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}};var eu=class extends ri{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.response??e;return await r?.handleLLMNewToken(n),n}},tu=class extends ri{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.responses?.[0];this.responses=this.responses?.slice(1);for(let s of n??e)await new Promise(i=>setTimeout(i,this.sleep)),yield{text:s,generationInfo:{}},await r?.handleLLMNewToken(s)}};var ru=class extends di{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new _t(e))}async addAIMessage(e){this.messages.push(new Q(e))}async clear(){this.messages=[]}},nu=class extends Ln{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},su=class extends tr{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}};var iu=class extends nc{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}};var ou=class extends Qr{lc_namespace=["test","fake"];output=[new Se({pageContent:"foo"}),new Se({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}};var au=class extends G{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}};var cu=class extends Xa{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}};var lu=class extends tr{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}};var uu=class hu extends ss{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:r,...n}={}){super(t,n),this.similarity=r??es}async addDocuments(t){let r=t.map(({pageContent:n})=>n);return this.addVectors(await this.embeddings.embedDocuments(r),t)}async addVectors(t,r){let n=t.map((s,i)=>({content:r[i].pageContent,embedding:s,metadata:r[i].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(t,r,n){let s=o=>n?n(new Se({metadata:o.metadata,pageContent:o.content})):!0,i=this.memoryVectors.filter(s);return i.map((o,a)=>({similarity:this.similarity(t,o.embedding),index:a})).sort((o,a)=>o.similarity>a.similarity?-1:0).slice(0,r).map(o=>[new Se({metadata:i[o.index].metadata,pageContent:i[o.index].content}),o.similarity])}static async fromTexts(t,r,n,s){let i=[];for(let o=0;o<t.length;o+=1){let a=Array.isArray(r)?r[o]:r,c=new Se({pageContent:t[o],metadata:a});i.push(c)}return hu.fromDocuments(i,n,s)}static async fromDocuments(t,r,n){let s=new this(r,n);return await s.addDocuments(t),s}static async fromExistingIndex(t,r){return new this(t,r)}};var pu=O({FakeChatMessageHistory:()=>ru,FakeChatModel:()=>ql,FakeEmbeddings:()=>Zl,FakeLLM:()=>eu,FakeListChatMessageHistory:()=>nu,FakeListChatModel:()=>Yl,FakeRetriever:()=>ou,FakeRunnable:()=>au,FakeSplitIntoListParser:()=>iu,FakeStreamingChatModel:()=>zl,FakeStreamingLLM:()=>tu,FakeTool:()=>cu,FakeTracer:()=>su,FakeVectorStore:()=>uu,SingleRunExtractor:()=>lu,SyntheticEmbeddings:()=>Ql,asAsyncIterable:()=>Jn,openAIReasoningTextChunks:()=>Xn,openAITextOnlyChunks:()=>sn,openAITextOnlyChunksWithUsage:()=>Yn,openAIToolCallChunks:()=>Qn,sseResponseFromOpenAIChunks:()=>Zn,streamMatchers:()=>gr});var fu=O({agents:()=>Tc,caches:()=>$a,callbacks__base:()=>ba,callbacks__manager:()=>xa,callbacks__promises:()=>Ca,chat_history:()=>Ic,document_loaders__base:()=>Nc,document_loaders__langsmith:()=>Pc,documents:()=>Oc,embeddings:()=>Za,errors:()=>da,example_selectors:()=>Uc,index:()=>xc,indexing:()=>Gc,language_models__base:()=>Ja,language_models__chat_models:()=>uc,language_models__compat:()=>lc,language_models__event:()=>Wc,language_models__llms:()=>pc,language_models__openai_completions_stream:()=>hc,language_models__profile:()=>Kc,language_models__stream:()=>cc,language_models__structured_output:()=>ac,load__serializable:()=>ha,memory:()=>qc,messages:()=>Qa,messages__tool:()=>fa,output_parsers:()=>ic,output_parsers__openai_functions:()=>Yc,output_parsers__openai_tools:()=>fc,outputs:()=>Ha,prompt_values:()=>Ga,prompts:()=>cl,retrievers:()=>ul,retrievers__document_compressors:()=>ll,runnables:()=>tc,runnables__graph:()=>Ba,singletons:()=>Ia,stores:()=>hl,structured_query:()=>yl,testing:()=>xl,tools:()=>Ya,tracers__base:()=>Sa,tracers__console:()=>ka,tracers__log_stream:()=>Ua,tracers__run_collector:()=>Tl,tracers__tracer_langchain:()=>Ea,types__stream:()=>Il,utils__async_caller:()=>Va,utils__chunk_array:()=>mc,utils__context:()=>Al,utils__env:()=>ya,utils__event_source_parse:()=>Ol,utils__format:()=>Ml,utils__function_calling:()=>dc,utils__gateway:()=>gc,utils__hash:()=>Da,utils__json_patch:()=>rc,utils__json_schema:()=>Ma,utils__math:()=>$l,utils__ssrf:()=>Fl,utils__standard_schema:()=>Ra,utils__stream:()=>Fa,utils__testing:()=>pu,utils__tiktoken:()=>za,utils__types:()=>oc,utils__uuid:()=>ga,vectorstores:()=>Kl});var lf=50;function uf(e){let t={};for(let r=e;r&&r.prototype;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r.prototype,"lc_aliases"));return Object.entries(t).reduce((r,[n,s])=>(r[s]=n,r),{})}async function is(e){let{optionalImportsMap:t,optionalImportEntrypoints:r,importMap:n,secretsMap:s,secretsFromEnv:i,path:o,depth:a,maxDepth:c}=this,l=o.join(".");if(a>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!="object"||e==null)return e;if(Array.isArray(e))return Promise.all(e.map((p,f)=>is.call({...this,path:[...o,`${f}`],depth:a+1},p)));let u=e;if(la(u))return ua(u);if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="secret"){let[p]=u.id;if(p in s)return s[p];if(i){let f=wa(p);if(f)return f}throw new Error(`Missing secret "${p}" at ${l}`)}if("lc"in u&&"type"in u&&"id"in u&&u.lc===1&&u.type==="not_implemented"){let p=JSON.stringify(u);throw new Error(`Trying to load an object that doesn't implement serialization: ${l} -> ${p}`)}if("lc"in u&&"type"in u&&"id"in u&&"kwargs"in u&&u.lc===1&&u.type==="constructor"){let p=u,f=JSON.stringify(p),[m,...d]=p.id.slice().reverse(),_=d.reverse(),g={langchain_core:fu,langchain:n},y=null,S=[_.join("/")];_[0]==="langchain_community"&&S.push(["langchain",..._.slice(1)].join("/"));let w=S.find(k=>k in t);if(Cc.concat(r).includes(_.join("/"))||w)if(w!==void 0)y=await t[w];else throw new Error(`Missing key "${_.join("/")}" for ${l} in load(optionalImportsMap={})`);else{let k;if(_[0]==="langchain"||_[0]==="langchain_core")k=g[_[0]],_.shift();else throw new Error(`Invalid namespace: ${l} -> ${f}`);if(_.length===0)throw new Error(`Invalid namespace: ${l} -> ${f}`);let b;do{if(b=_.join("__"),b in k)break;_.pop()}while(_.length>0);b in k&&(y=k[b])}if(typeof y!="object"||y===null)throw new Error(`Invalid namespace: ${l} -> ${f}`);let C=y[m]??Object.values(y).find(k=>typeof k=="function"&&pa(k)===m);if(typeof C!="function")throw new Error(`Invalid identifer: ${l} -> ${f}`);let T=new C(ca(await is.call({...this,path:[...o,"kwargs"],depth:a+1},p.kwargs),aa,uf(C)));return Object.defineProperty(T.constructor,"name",{value:m}),T}let h={};for(let[p,f]of Object.entries(u))h[p]=await is.call({...this,path:[...o,p],depth:a+1},f);return h}async function mu(e,t){let r=JSON.parse(e),n={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:["$"],depth:0,maxDepth:t?.maxDepth??lf};return is.call(n,r)}function hf(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}function pf(e){return e.lc===2&&e.type==="undefined"}function ff(e){return e.lc===2&&e.type==="delta_snapshot"&&Object.prototype.hasOwnProperty.call(e,"value")}function mf(e){return e.lc===2&&e.type==="constructor"}function on(e,t){return Array.isArray(e.id)&&e.id.length===1&&e.id[0]===t}function an(e){return e.method===void 0||e.method===null}function ao(e){return Array.isArray(e.args)&&e.args.length===1&&Array.isArray(e.args[0])}function df(e){return e.every(t=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=255)}function gf(e){if(on(e,"Set")&&an(e))return ao(e)?new Set(e.args[0]):void 0;if(on(e,"Map")&&an(e))return!ao(e)||!e.args[0].every(t=>Array.isArray(t)&&t.length===2)?void 0:new Map(e.args[0]);if(on(e,"RegExp")&&an(e)){if(!Array.isArray(e.args)||e.args.length!==2||typeof e.args[0]!="string"||typeof e.args[1]!="string")return;try{return new RegExp(e.args[0],e.args[1])}catch{return}}if(on(e,"Error")&&an(e))return!Array.isArray(e.args)||e.args.length!==1||typeof e.args[0]!="string"?void 0:new Error(e.args[0]);if(on(e,"Uint8Array")&&(an(e)||e.method==="from"))return!ao(e)||!df(e.args[0])?void 0:new Uint8Array(e.args[0])}async function co(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(t=>co(t)));{let t={};for(let[r,n]of Object.entries(e))t[r]=await co(n);return pf(t)?void 0:ff(t)?new ar(t.value):mf(t)?gf(t)??t:hf(t)?mu(JSON.stringify(t)):t}}return e}function os(e,t,r,n){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:r??[],kwargs:n??{}}}function _f(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof ar?{lc:2,type:"delta_snapshot",value:e.value}:e instanceof Set||e instanceof Map?os(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?os(RegExp,void 0,[e.source,e.flags]):e instanceof Error?os(Error,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args,...e.timeout!==void 0?{timeout:e.timeout}:{}}:e instanceof Uint8Array?os(Uint8Array,"from",[Array.from(e)]):e}var as=class{_dumps(e){return new TextEncoder().encode(Ec(e,(t,r)=>_f(r)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){return co(JSON.parse(e))}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function lo(e){if(typeof e!="object"||e===null)return e;let t=Array.isArray(e)?[]:{};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=lo(e[r]));return t}function qt(){return{v:4,id:Hr(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function je(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values??{}},channel_versions:{...e.channel_versions??{}},versions_seen:lo(e.versions_seen??{})}}var cs=class{serde=new as;constructor(e){this.serde=e||this.serde}toJSON(){return`[${this.constructor.name}]`}async get(e){let t=await this.getTuple(e);return t?t.checkpoint:void 0}async getDeltaChannelHistory(e){let{config:t,channels:r}=e;if(r.length===0)return{};let n={},s={},i=new Set(r);for(let c of r)n[c]=[];let o=(await this.getTuple(t))?.parentConfig;for(;o!=null&&i.size>0;){let c=await this.getTuple(o);if(c===void 0)break;if(c.pendingWrites&&c.pendingWrites.length>0){let l={};for(let u of c.pendingWrites){let h=u[1];i.has(h)&&(l[h]??=[]).push(u)}for(let u of Object.keys(l)){let h=l[u];h.sort((p,f)=>p[0]<f[0]?-1:p[0]>f[0]?1:0);for(let p=h.length-1;p>=0;p-=1)n[u].push(h[p])}}for(let l of Array.from(i))Object.prototype.hasOwnProperty.call(c.checkpoint.channel_values,l)&&(s[l]=c.checkpoint.channel_values[l],i.delete(l));o=c.parentConfig}let a={};for(let c of r){let l={writes:n[c].slice().reverse()};Object.prototype.hasOwnProperty.call(s,c)&&(l.seed=s[c]),a[c]=l}return a}getNextVersion(e){if(typeof e=="string")throw new Error("Please override this method to use string versions.");return e!==void 0&&typeof e=="number"?e+1:1}};function ls(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function cn(...e){return e.reduce((t,r,n)=>n===0?r:ls(t,r)>=0?t:r)}var ln={[li]:-1,[Gt]:-2,[ui]:-3,[hi]:-4},uo=new Set(["thread_id","checkpoint_id","checkpoint_ns","checkpoint_map","langgraph_step","langgraph_node","langgraph_triggers","langgraph_path","langgraph_checkpoint_ns"]);function us(e){return e.configurable?.checkpoint_id||e.configurable?.thread_ts||""}var yf=new Set(["__proto__","constructor","prototype"]);function ie(e,t,r={}){let{allowEmpty:n=!1}=r;if(typeof t!="string"){let s=t===null?"null":t===void 0?"undefined":Array.isArray(t)?"array":typeof t;throw new Error(`Invalid configurable value for key "${e}": expected a string identifier (got ${s}). This guard protects MemorySaver from prototype pollution.`)}if(!n&&t==="")throw new Error(`Invalid configurable value for key "${e}": empty string is not permitted as an in-memory storage key.`);if(yf.has(t))throw new Error(`Invalid configurable value for key "${e}": value "${t}" is reserved (would mutate Object.prototype). This guard protects MemorySaver from prototype pollution.`)}function _r(e,t,r){return JSON.stringify([e,t,r])}function wf(e){let[t,r,n]=JSON.parse(e);return{threadId:t,checkpointNamespace:r,checkpointId:n}}var du=class extends cs{storage=Object.create(null);writes=Object.create(null);constructor(e){super(e)}async _migratePendingSends(e,t,r,n){let s=e,i=_r(t,r,n),o=await Promise.all(Object.values(this.writes[i]??{}).filter(([a,c])=>c===Br).map(async([a,c,l])=>await this.serde.loadsTyped("json",l)));s.channel_values??={},s.channel_values[Br]=o,s.channel_versions??={},s.channel_versions[Br]=Object.keys(s.channel_versions).length>0?cn(...Object.values(s.channel_versions)):this.getNextVersion(void 0)}async getTuple(e){let t=e.configurable?.thread_id,r=e.configurable?.checkpoint_ns??"",n=us(e);if(t!==void 0&&ie("thread_id",t),ie("checkpoint_ns",r,{allowEmpty:!0}),n&&ie("checkpoint_id",n),n){let s=this.storage[t]?.[r]?.[n];if(s!==void 0){let[i,o,a]=s,c=_r(t,r,n),l=await this.serde.loadsTyped("json",i);l.v<4&&a!==void 0&&await this._migratePendingSends(l,t,r,a);let u=await Promise.all(Object.values(this.writes[c]||{}).map(async([p,f,m])=>[p,f,await this.serde.loadsTyped("json",m)])),h={config:e,checkpoint:l,metadata:await this.serde.loadsTyped("json",o),pendingWrites:u};return a!==void 0&&(h.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:a}}),h}}else{let s=this.storage[t]?.[r];if(s!==void 0){n=Object.keys(s).sort((p,f)=>f.localeCompare(p))[0];let[i,o,a]=s[n],c=_r(t,r,n),l=await this.serde.loadsTyped("json",i);l.v<4&&a!==void 0&&await this._migratePendingSends(l,t,r,a);let u=await Promise.all(Object.values(this.writes[c]||{}).map(async([p,f,m])=>[p,f,await this.serde.loadsTyped("json",m)])),h={config:{configurable:{thread_id:t,checkpoint_id:n,checkpoint_ns:r}},checkpoint:l,metadata:await this.serde.loadsTyped("json",o),pendingWrites:u};return a!==void 0&&(h.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:a}}),h}}}async*list(e,t){let{before:r,limit:n,filter:s}=t??{};e.configurable?.thread_id!==void 0&&ie("thread_id",e.configurable.thread_id),e.configurable?.checkpoint_ns!==void 0&&ie("checkpoint_ns",e.configurable.checkpoint_ns,{allowEmpty:!0}),e.configurable?.checkpoint_id&&ie("checkpoint_id",e.configurable.checkpoint_id),r?.configurable?.checkpoint_id&&ie("checkpoint_id",r.configurable.checkpoint_id);let i=e.configurable?.thread_id?[e.configurable?.thread_id]:Object.keys(this.storage),o=e.configurable?.checkpoint_ns,a=e.configurable?.checkpoint_id;for(let c of i)for(let l of Object.keys(this.storage[c]??{})){if(o!==void 0&&l!==o)continue;let u=this.storage[c]?.[l]??{},h=Object.entries(u).sort((p,f)=>f[0].localeCompare(p[0]));for(let[p,[f,m,d]]of h){if(a&&p!==a||r&&r.configurable?.checkpoint_id&&p>=r.configurable.checkpoint_id)continue;let _=await this.serde.loadsTyped("json",m);if(s&&!Object.entries(s).every(([T,k])=>_[T]===k))continue;if(n!==void 0){if(n<=0)break;n-=1}let g=_r(c,l,p),y=Object.values(this.writes[g]||{}),S=await Promise.all(y.map(async([T,k,b])=>[T,k,await this.serde.loadsTyped("json",b)])),w=await this.serde.loadsTyped("json",f);w.v<4&&d!==void 0&&await this._migratePendingSends(w,c,l,d);let C={config:{configurable:{thread_id:c,checkpoint_ns:l,checkpoint_id:p}},checkpoint:w,metadata:_,pendingWrites:S};d!==void 0&&(C.parentConfig={configurable:{thread_id:c,checkpoint_ns:l,checkpoint_id:d}}),yield C}}}async put(e,t,r){let n=je(t),s=e.configurable?.thread_id,i=e.configurable?.checkpoint_ns??"";if(s===void 0)throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');ie("thread_id",s),ie("checkpoint_ns",i,{allowEmpty:!0}),ie("checkpoint_id",t.id),this.storage[s]||(this.storage[s]=Object.create(null)),this.storage[s][i]||(this.storage[s][i]=Object.create(null));let[[,o],[,a]]=await Promise.all([this.serde.dumpsTyped(n),this.serde.dumpsTyped(r)]);return this.storage[s][i][t.id]=[o,a,e.configurable?.checkpoint_id],{configurable:{thread_id:s,checkpoint_ns:i,checkpoint_id:t.id}}}async putWrites(e,t,r){let n=e.configurable?.thread_id,s=e.configurable?.checkpoint_ns,i=e.configurable?.checkpoint_id;if(n===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })');if(i===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.');ie("thread_id",n),ie("checkpoint_ns",s,{allowEmpty:!0}),ie("checkpoint_id",i),ie("task_id",r);let o=_r(n,s,i),a=this.writes[o];this.writes[o]===void 0&&(this.writes[o]=Object.create(null)),await Promise.all(t.map(async([c,l],u)=>{let[,h]=await this.serde.dumpsTyped(l),p=[r,ln[c]||u],f=`${p[0]},${p[1]}`;p[1]>=0&&a&&f in a||(this.writes[o][f]=[r,c,h])}))}async deleteThread(e){ie("thread_id",e),delete this.storage[e];for(let t of Object.keys(this.writes))wf(t).threadId===e&&delete this.writes[t]}async getDeltaChannelHistory(e){let{config:t,channels:r}=e;if(r.length===0)return{};let n=t.configurable?.thread_id,s=t.configurable?.checkpoint_ns??"",i=us(t);n!==void 0&&ie("thread_id",n),ie("checkpoint_ns",s,{allowEmpty:!0});let o=this.storage[n]?.[s]??{},a=[],c=(i?o[i]:void 0)?.[2];for(;c!==void 0;){let f=o[c];if(f===void 0)break;a.push(c),c=f[2]}let l={},u={},h=new Set(r);for(let f of r)l[f]=[];for(let f of a){if(h.size===0)break;let m=o[f],d=m!==void 0?await this.serde.loadsTyped("json",m[0]):void 0,_={},g=new Set;if(d!==void 0)for(let w of h)Object.prototype.hasOwnProperty.call(d.channel_values,w)&&d.channel_values[w]!==void 0&&(_[w]=d.channel_values[w],g.add(w));let y=_r(n,s,f),S=Object.entries(this.writes[y]??{});S.sort(([w],[C])=>{let[T,k]=w.split(","),[b,I]=C.split(",");return T!==b?T<b?1:-1:Number(I)-Number(k)});for(let[,[w,C,T]]of S)h.has(C)&&l[C].push([w,C,await this.serde.loadsTyped("json",T)]);for(let w of g)u[w]=_[w],h.delete(w)}let p={};for(let f of r){let m={writes:l[f].slice().reverse()};Object.prototype.hasOwnProperty.call(u,f)&&(m.seed=u[f]),p[f]=m}return p}};var yr=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function bf(e){if(e.length===0)throw new yr("Namespace cannot be empty.");for(let t of e){if(typeof t!="string")throw new yr(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new yr(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new yr(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new yr(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var wr=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:r,limit:n=10,offset:s=0,query:i}=t;return(await this.batch([{namespacePrefix:e,filter:r,limit:n,offset:s,query:i}]))[0]}async put(e,t,r,n){bf(e),await this.batch([{namespace:e,key:t,value:r,index:n}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:r,maxDepth:n,limit:s=100,offset:i=0}=e,o=[];return t&&o.push({matchType:"prefix",path:t}),r&&o.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:n,limit:s,offset:i}]))[0]}start(){}stop(){}};var vf=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e,hs=class extends wr{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=vf(e)}get isRunning(){return this.running}async batch(e){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(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:r,limit:n=10,offset:s=0,query:i}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:n,offset:s,query:i})}async put(e,t,r){return this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,r)=>{let n=this.nextKey;this.nextKey+=1,this.queue.set(n,{operation:e,resolve:t,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:n})=>n),r=await this.store.batch(t);e.forEach(({resolve:n},s)=>{n(r[Array.from(e.keys()).indexOf(s)])})}catch(t){e.forEach(({reject:r})=>{r(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};function un(e){if(!e)return[];let t=[],r=[],n=0;for(;n<e.length;){let s=e[n];if(s==="["){r.length&&(t.push(r.join("")),r=[]);let i=1,o=["["];for(n+=1;n<e.length&&i>0;)e[n]==="["?i+=1:e[n]==="]"&&(i-=1),o.push(e[n]),n+=1;t.push(o.join(""));continue}else if(s==="{"){r.length&&(t.push(r.join("")),r=[]);let i=1,o=["{"];for(n+=1;n<e.length&&i>0;)e[n]==="{"?i+=1:e[n]==="}"&&(i-=1),o.push(e[n]),n+=1;t.push(o.join(""));continue}else s==="."?r.length&&(t.push(r.join("")),r=[]):r.push(s);n+=1}return r.length&&t.push(r.join("")),t}function Sf(e){return typeof e=="object"&&e!==null&&Object.keys(e).every(t=>t==="$eq"||t==="$ne"||t==="$gt"||t==="$gte"||t==="$lt"||t==="$lte"||t==="$in"||t==="$nin")}function gu(e,t){return Sf(t)?Object.keys(t).filter(r=>r.startsWith("$")).every(r=>{let n=t[r];switch(r){case"$eq":return e===n;case"$ne":return e!==n;case"$gt":return Number(e)>Number(n);case"$gte":return Number(e)>=Number(n);case"$lt":return Number(e)<Number(n);case"$lte":return Number(e)<=Number(n);case"$in":return Array.isArray(n)?n.includes(e):!1;case"$nin":return Array.isArray(n)?!n.includes(e):!0;default:return!1}}):e===t}function _u(e,t){if(!t||t==="$")return[JSON.stringify(e,null,2)];let r=Array.isArray(t)?t:un(t);function n(s,i,o){if(o>=i.length)return typeof s=="string"||typeof s=="number"||typeof s=="boolean"?[String(s)]:s==null?[]:Array.isArray(s)||typeof s=="object"?[JSON.stringify(s,null,2)]:[];let a=i[o],c=[];if(o===0&&a==="$"&&c.push(JSON.stringify(s,null,2)),a.startsWith("[")&&a.endsWith("]")){if(!Array.isArray(s))return[];let l=a.slice(1,-1);if(l==="*")for(let u of s)c.push(...n(u,i,o+1));else try{let u=parseInt(l,10);u<0&&(u=s.length+u),u>=0&&u<s.length&&c.push(...n(s[u],i,o+1))}catch{return[]}}else if(a.startsWith("{")&&a.endsWith("}")){if(typeof s!="object"||s===null)return[];let l=a.slice(1,-1).split(",").map(u=>u.trim());for(let u of l){let h=un(u);if(h.length){let p=s;for(let f of h)if(p&&typeof p=="object"&&f in p)p=p[f];else{p=void 0;break}p!==void 0&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean"?c.push(String(p)):(Array.isArray(p)||typeof p=="object")&&c.push(JSON.stringify(p,null,2)))}}}else if(a==="*"){if(Array.isArray(s))for(let l of s)c.push(...n(l,i,o+1));else if(typeof s=="object"&&s!==null)for(let l of Object.values(s))c.push(...n(l,i,o+1))}else typeof s=="object"&&s!==null&&a in s&&c.push(...n(s[a],i,o+1));return c}return n(e,r,0)}var yu=class extends wr{data=new Map;vectors=new Map;_indexConfig;constructor(e){super(),e?.index&&(this._indexConfig={...e.index,__tokenizedFields:(e.index.fields??["$"]).map(t=>[t,t==="$"?[t]:un(t)])})}async batch(e){let t=[],r=new Map,n=new Map;for(let s=0;s<e.length;s+=1){let i=e[s];if("key"in i&&"namespace"in i&&!("value"in i))t.push(this.getOperation(i));else if("namespacePrefix"in i){let o=this.filterItems(i);n.set(s,[i,o]),t.push(null)}else if("value"in i){let o=`${i.namespace.join(":")}:${i.key}`;r.set(o,i),t.push(null)}else"matchConditions"in i&&t.push(this.listNamespacesOperation(i))}if(n.size>0)if(this._indexConfig?.embeddings){let s=new Set;for(let[a]of n.values())a.query&&s.add(a.query);let i=s.size>0?await Promise.all(Array.from(s).map(a=>this._indexConfig.embeddings.embedQuery(a))):[],o=Object.fromEntries(Array.from(s).map((a,c)=>[a,i[c]]));for(let[a,[c,l]]of n.entries())if(c.query&&o[c.query]){let u=o[c.query];t[a]=this.scoreResults(l,u,c.offset??0,c.limit??10)}else t[a]=this.paginateResults(l.map(u=>({...u,score:void 0})),c.offset??0,c.limit??10)}else for(let[s,[i,o]]of n.entries())t[s]=this.paginateResults(o.map(a=>({...a,score:void 0})),i.offset??0,i.limit??10);if(r.size>0&&this._indexConfig?.embeddings){let s=this.extractTexts(Array.from(r.values()));if(Object.keys(s).length>0){let i=await this._indexConfig.embeddings.embedDocuments(Object.keys(s));this.insertVectors(s,i)}}for(let s of r.values())this.putOperation(s);return t}getOperation(e){let t=e.namespace.join(":");return this.data.get(t)?.get(e.key)??null}putOperation(e){let t=e.namespace.join(":");this.data.has(t)||this.data.set(t,new Map);let r=this.data.get(t);if(e.value===null)r.delete(e.key);else{let n=new Date;if(r.has(e.key)){let s=r.get(e.key);s.value=e.value,s.updatedAt=n}else r.set(e.key,{value:e.value,key:e.key,namespace:e.namespace,createdAt:n,updatedAt:n})}}listNamespacesOperation(e){let t=Array.from(this.data.keys()).map(r=>r.split(":"));return e.matchConditions&&e.matchConditions.length>0&&(t=t.filter(r=>e.matchConditions.every(n=>this.doesMatch(n,r)))),e.maxDepth!==void 0&&(t=Array.from(new Set(t.map(r=>r.slice(0,e.maxDepth).join(":")))).map(r=>r.split(":"))),t.sort((r,n)=>r.join(":").localeCompare(n.join(":"))),t.slice(e.offset??0,(e.offset??0)+(e.limit??t.length))}doesMatch(e,t){let{matchType:r,path:n}=e;if(r==="prefix")return n.length>t.length?!1:n.every((s,i)=>{let o=t[i];return s==="*"||o===s});if(r==="suffix")return n.length>t.length?!1:n.every((s,i)=>{let o=t[t.length-n.length+i];return s==="*"||o===s});throw new Error(`Unsupported match type: ${r}`)}filterItems(e){let t=[];for(let[n,s]of this.data.entries())n.startsWith(e.namespacePrefix.join(":"))&&t.push(...s.values());let r=t;return e.filter&&(r=t.filter(n=>Object.entries(e.filter).every(([s,i])=>gu(n.value[s],i)))),r}scoreResults(e,t,r=0,n=10){let s=[],i=[],o=[];for(let u of e){let h=this.getVectors(u);if(h.length)for(let p of h)s.push(u),i.push(p);else o.push(u)}let a=this.cosineSimilarity(t,i).map((u,h)=>[u,s[h]]).sort((u,h)=>h[0]-u[0]),c=new Set,l=[];for(let[u,h]of a){let p=`${h.namespace.join(":")}:${h.key}`;if(c.has(p))continue;let f=c.size;if(f>=r+n)break;if(f<r){c.add(p);continue}c.add(p),l.push([u,h])}if(o.length&&l.length<n)for(let u of o.slice(0,n-l.length)){let h=`${u.namespace.join(":")}:${u.key}`;c.has(h)||(c.add(h),l.push([void 0,u]))}return l.map(([u,h])=>({...h,score:u}))}paginateResults(e,t,r){return e.slice(t,t+r)}extractTexts(e){if(!e.length||!this._indexConfig)return{};let t={};for(let r of e)if(r.value!==null&&r.index!==!1){let n=r.index===null||r.index===void 0?this._indexConfig.__tokenizedFields??[]:r.index.map(s=>[s,un(s)]);for(let[s,i]of n){let o=_u(r.value,i);o.length&&(o.length>1?o.forEach((a,c)=>{t[a]||(t[a]=[]),t[a].push([r.namespace,r.key,`${s}.${c}`])}):(t[o[0]]||(t[o[0]]=[]),t[o[0]].push([r.namespace,r.key,s])))}}return t}insertVectors(e,t){for(let[r,n]of Object.entries(e)){let s=t.shift();if(!s)throw new Error(`No embedding found for text: ${r}`);for(let[i,o,a]of n){let c=i.join(":");this.vectors.has(c)||this.vectors.set(c,new Map);let l=this.vectors.get(c);l.has(o)||l.set(o,new Map),l.get(o).set(a,s)}}}getVectors(e){let t=e.namespace.join(":"),r=e.key;if(!this.vectors.has(t))return[];let n=this.vectors.get(t);if(!n.has(r))return[];let s=n.get(r),i=Array.from(s.values());return i.length?i:[]}cosineSimilarity(e,t){if(!t.length)return[];let r=t.map(i=>i.reduce((o,a,c)=>o+a*e[c],0)),n=Math.sqrt(e.reduce((i,o)=>i+o*o,0)),s=t.map(i=>Math.sqrt(i.reduce((o,a)=>o+a*a,0)));return r.map((i,o)=>{let a=s[o];return n&&a?i/(n*a):0})}get indexConfig(){return this._indexConfig}};var ps=class{serde=new as;constructor(e){this.serde=e||this.serde}};var kf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Te(e){return e!=null&&e.lc_graph_name==="DeltaChannel"}function po(e){return e!=null&&e.lg_is_channel===!0}var J=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===$.unminifiable_name)return!1;throw e}}equals(e){return this===e}},ho=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function br(e){if(e[ho]===!0)return e;let t={};for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=e[r];po(n)&&(t[r]=n)}return Object.assign(t,{[ho]:!0}),t}function fs(e,t){let r=br(e),n={};for(let s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let i=t.channel_values[s];n[s]=r[s].fromCheckpoint(i)}return Object.assign(n,{[ho]:!0}),n}function fo(e,t){if(!kf.test(t))throw new TypeError(`Invalid task id for exit delta: ${t}`);let r=t.toLowerCase().split("-");return`${String(e).padStart(8,"0")}-${r[1]}-${r[2]}-${r[3]}-${r[4]}`}function ms(e,t){let r=new Set,n=yc();for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=e[s];if(!Te(i)||!i.isAvailable())continue;let[o,a]=t[s]??[0,0];(o>=i.snapshotFrequency||a>=n)&&r.add(s)}return r}function De(e,t,r,n){let s=n?.channelsToSnapshot??new Set,{updatedChannels:i,getNextVersion:o}=n??{},a,c=e.channel_versions;if(t===void 0)a=e.channel_values;else{a={},c={...e.channel_versions};for(let l in t){if(!Object.prototype.hasOwnProperty.call(t,l))continue;let u=t[l];if(s.has(l)){o!==void 0&&(i===void 0||!i.has(l))&&(c[l]=o(c[l])),a[l]=new ar(u.get());continue}if(!Te(u))try{a[l]=u.checkpoint()}catch(h){if(h.name!==$.unminifiable_name)throw h}}}return{v:4,id:n?.id??Hr(r),ts:new Date().toISOString(),channel_values:a,channel_versions:c,versions_seen:e.versions_seen}}async function vr(e,t,r){let n=fs(e,t),{saver:s,config:i}=r??{},o=br(e),a=[];for(let l in o)Object.prototype.hasOwnProperty.call(o,l)&&Te(o[l])&&!Object.prototype.hasOwnProperty.call(t.channel_values,l)&&a.push(l);if(a.length===0||s===void 0||i===void 0)return n;let c=await s.getDeltaChannelHistory({config:i,channels:a});for(let l of a){let u=c[l];if(u===void 0)continue;let h=o[l].fromCheckpoint(u.seed);h.replayWrites(u.writes),n[l]=h}return n}var Ef=e=>e!=null&&e.lc_graph_name==="BinaryOperatorAggregate",lt=class wu extends J{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,r){super(),this.operator=t,this.initialValueFactory=r,this.value=r?.()}fromCheckpoint(t){let r=new wu(this.operator,this.initialValueFactory);return typeof t<"u"&&(r.value=t),r}update(t){let r=t;if(!r.length)return!1;if(this.value===void 0){let s=r[0],[i,o]=Pe(s);i?this.value=o:this.value=s,r=r.slice(1)}let n=!1;for(let s of r)if(Ut(s)){if(n)throw new R("Can receive only one Overwrite value per step.");let[,i]=Pe(s);this.value=i,n=!0;continue}else!n&&this.value!==void 0&&(this.value=this.operator(this.value,s));return!0}get(){if(this.value===void 0)throw new $;return this.value}checkpoint(){if(this.value===void 0)throw new $;return this.value}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:Ef(t)?this.operator===t.operator:!1}};var $e=class bu extends J{lc_graph_name="LastValue";value=[];constructor(t){super(),this.initialValueFactory=t,t&&(this.value=[t()])}fromCheckpoint(t){let r=new bu(this.initialValueFactory);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0)return!1;if(t.length!==1)throw new R("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new $;return this.value[0]}checkpoint(){if(this.value.length===0)throw new $;return this.value[0]}isAvailable(){return this.value.length!==0}},mo=class vu extends J{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){let r=new vu;if(typeof t<"u"){let[n,s]=t;r.value=[n],r.finished=s}return r}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new $;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}};var ds=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}static isInstance(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}},hn=function(e){return e?gs(e):new $e};hn.Root=e=>new ds(e);function gs(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new lt(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new lt(e.value,e.default):new $e}var Cf=["tags","metadata","callbacks","configurable"],xf=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal","heartbeat","executionInfo","serverInfo","control"],Tf=25,If=new Set(["thread_id","checkpoint_id","checkpoint_ns","task_id","run_id","assistant_id","graph_id"]);function Af(e,t){if(!e)return t;let r=t??{};for(let n of If){if(n in r)continue;let s=e[n];s!==void 0&&(r[n]=s)}return r}function Su(e){if(e==null||e.length===0)return;let t=e.filter(r=>!r.startsWith("seq:step"));return t.length>0?t:void 0}function Of(e,t){if(t===void 0)return e;if(e===void 0)return Array.isArray(t)?[...t]:t.copy();if(Array.isArray(t)){if(Array.isArray(e))return e.concat(t);let n=e.copy();for(let s of t)n.addHandler(Ys(s),!0);return n}if(Array.isArray(e)){let n=t.copy();for(let s of e)n.addHandler(Ys(s),!0);return n}let r=n=>n.filter((s,i)=>n.findIndex(o=>o===s||o.name==="StreamMessagesHandler"&&s.name==="StreamMessagesHandler")===i);return new rr(t._parentRunId,{handlers:r(e.handlers.concat(t.handlers)),inheritableHandlers:r(e.inheritableHandlers.concat(t.inheritableHandlers)),tags:Array.from(new Set(e.tags.concat(t.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(t.inheritableTags))),metadata:{...e.metadata,...t.metadata},inheritableMetadata:{...e.inheritableMetadata,...t.inheritableMetadata}})}function Nf(e){let t;for(let i=e.length-1;i>=0;i-=1)if(e[i]!==void 0){t=e[i];break}let r=t?.configurable?.thread_id!==void 0,n=e.some(i=>i?.configurable?.[le]!==void 0),s=Z.getRunnableConfig()?.configurable?.[le]!==void 0;return r&&!n&&!s}function Sr(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:Tf,configurable:{}},r=Nf(e),n=Z.getRunnableConfig();if(n!==void 0){for(let[s,i]of Object.entries(n))if(i!==void 0){if(s==="configurable"&&r)continue;if(Cf.includes(s)){let o;Array.isArray(i)?o=[...i]:typeof i=="object"?s==="callbacks"&&"copy"in i&&typeof i.copy=="function"?o=i.copy():o={...i}:o=i,t[s]=o}else t[s]=i}}for(let s of e)if(s!==void 0)for(let[i,o]of Object.entries(s))o===void 0||!xf.includes(i)||(i==="configurable"?t.configurable={...t.configurable,...o}:i==="metadata"?t.metadata={...t.metadata,...o}:i==="tags"?t.tags=[...t.tags??[],...o]:i==="callbacks"?t.callbacks=Of(t.callbacks,o):t[i]=o);return t.metadata=Af(t.configurable,t.metadata)??{},t}function Pf(e){let t=e??Z.getRunnableConfig();if(t===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getStore` in such environment, pass the `config` from the node function directly."].join(`
|
|
114
|
+
`));return t?.store}function Rf(e){let t=e??Z.getRunnableConfig();if(t===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join(`
|
|
115
|
+
`));return t?.writer||t?.configurable?.writer}function _s(){return Z.getRunnableConfig()}function Mf(e){let t=e??Z.getRunnableConfig();if(t===void 0)throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.","If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join(`
|
|
116
|
+
`));if(t.configurable?.__pregel_scratchpad?.currentTaskInput===void 0)throw new Error("BUG: internal scratchpad not initialized.");return t.configurable[ue].currentTaskInput}function ys(e){return e.split("|").filter(t=>!t.match(/^\d+$/)).map(t=>t.split(":")[0]).join("|")}function ku(e){let t=e.split("|");for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join("|")}var go=class{#e=void 0;requestDrain(e="shutdown"){this.#e=e}get drainRequested(){return this.#e!==void 0}get drainReason(){return this.#e}};var _o=["values","updates","messages","tools","custom","tasks"];function kr(e){if(e==null||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&("source"in t||typeof t.step=="number")&&!("values"in t)&&!("config"in t)}function jf(e){if(!Array.isArray(e)||e.length!==2)return{data:e};let[t,r]=e;if(r==null||typeof r!="object")return{data:e};let n=r,s=typeof n.langgraph_node=="string"?n.langgraph_node:void 0,i=typeof n.run_id=="string"?n.run_id:void 0;return{data:i!=null&&t!=null&&typeof t=="object"?{...t,run_id:i}:t,node:s}}function yo({namespace:e,mode:t,payload:r,seq:n}){let s=Date.now(),i={type:"event"};switch(t){case"messages":{let{data:o,node:a}=jf(r);return[{...i,seq:n,method:"messages",params:{namespace:e,timestamp:s,...a?{node:a}:{},data:o}}]}case"tools":return[{...i,seq:n,method:"tools",params:{namespace:e,timestamp:s,data:Df(r)}}];case"checkpoints":return kr(r)?[{...i,seq:n,method:"checkpoints",params:{namespace:e,timestamp:s,data:r}}]:[];case"values":return[{...i,seq:n,method:"values",params:{namespace:e,timestamp:s,data:r}}];case"updates":{let o=$f(r);return[{...i,seq:n,method:"updates",params:{namespace:e,timestamp:s,...typeof o.node=="string"?{node:o.node}:{},data:o}}]}case"custom":{let o=typeof r=="object"&&r!==null&&!Array.isArray(r)&&"name"in r?r:{payload:r};return[{...i,seq:n,method:"custom",params:{namespace:e,timestamp:s,data:o}}]}case"tasks":return[{...i,seq:n,method:"tasks",params:{namespace:e,timestamp:s,data:r}}];default:return[]}}function Df(e){if(typeof e!="object"||e===null)return{event:"tool-error",tool_call_id:"",message:"Unexpected tools payload shape"};let t=e,r=String(t.toolCallId??"");switch(t.event){case"on_tool_start":return{event:"tool-started",tool_call_id:r,tool_name:String(t.name??"unknown"),input:t.input};case"on_tool_event":return{event:"tool-output-delta",tool_call_id:r,delta:typeof t.data=="string"?t.data:JSON.stringify(t.data??"")};case"on_tool_end":return{event:"tool-finished",tool_call_id:r,output:t.output};case"on_tool_error":{let n=t.error;return{event:"tool-error",tool_call_id:r,message:typeof n=="object"&&n!==null&&"message"in n&&typeof n.message=="string"?n.message:String(n??"unknown error")}}default:return{event:"tool-error",tool_call_id:"",message:`Unknown tool event: ${String(t.event)}`}}}function $f(e){if(typeof e!="object"||e===null)return{values:{}};let t=Object.entries(e);if(t.length===0)return{values:{}};let[r,n]=t[0];return{node:r,values:typeof n=="object"&&n!==null?n:{value:n}}}var wo=Symbol.for("langgraph.stream_channel"),Ie=class bo{[wo]=!0;channelName;#e=[];#t=[];#n=!1;#i;#s;constructor(t){this.channelName=t}static local(){return new bo}static remote(t){return new bo(t)}static isInstance(t){return typeof t=="object"&&t!==null&&wo in t&&t[wo]===!0}push(t){this.#e.push(t),this.#r(),this.#s?.(t)}iterate(t=0){let r=t;return{next:async()=>{for(;;){if(r<this.#e.length)return{value:this.#e[r++],done:!1};if(this.#n){if(this.#i)throw this.#i;return{value:void 0,done:!0}}await new Promise(n=>this.#t.push(n))}}}}toAsyncIterable(t=0){return{[Symbol.asyncIterator]:()=>this.iterate(t)}}toEventStream(t={}){let r=new TextEncoder,n=this.iterate(t.startAt),s=t.event??this.channelName,i=t.serialize??(o=>JSON.stringify(o)??"null");return new ReadableStream({async pull(o){try{let a=await n.next();if(a.done){o.close();return}let c=[];s!=null&&c.push(`event: ${s}`);for(let l of i(a.value).split(/\r\n|\r|\n/))c.push(`data: ${l}`);o.enqueue(r.encode(`${c.join(`
|
|
117
|
+
`)}
|
|
118
|
+
|
|
119
|
+
`))}catch(a){o.error(a)}},async cancel(){await n.return?.()}})}get(t){if(t<0||t>=this.#e.length)throw new RangeError(`StreamChannel index ${t} out of bounds (size=${this.#e.length})`);return this.#e[t]}get size(){return this.#e.length}get done(){return this.#n}close(){this.#n=!0,this.#r()}fail(t){this.#i=t,this.#n=!0,this.#r()}_wire(t){this.#s=t}_close(){this.close()}_fail(t){this.fail(t)}[Symbol.asyncIterator](){return this.iterate()}#r(){let t=this.#t.splice(0);for(let r of t)r()}};function Eu(e){return Ie.isInstance(e)}var Vf="custom:";function Ff(e){return`${Vf}${e}`}function Lf(e){return e!=null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}var ws=Symbol("resolveValues"),vo=Symbol("rejectValues"),Cu=class{_events=Ie.local();_discoveries=Ie.local();#e=0;#t=!1;#n;#i=!1;#s=[];#r=[];#a=[];#o=new Map;#l=new Map;#c=[];#u=[];register(e,t){this.#o.set(Y(e),t)}addTransformer(e){let t=this._events.size;this.#r.push(e),e.onRegister&&e.onRegister({push:(r,n)=>this.push(r,n)});for(let r=0;r<t;r+=1)e.process(this._events.get(r));this.#t&&(this.#n!==void 0?e.fail?.(this.#n):e.finalize?.())}wireChannels(e){for(let[t,r]of Object.entries(e)){if(Eu(r)){if(this.#a.push(r),typeof r.channelName!="string")continue;let n=Ff(r.channelName);r._wire(s=>{this._events.push({type:"event",seq:this.#e++,method:n,params:{namespace:this.#s,timestamp:Date.now(),data:s}})});continue}Lf(r)&&this.#u.push({name:t,promise:Promise.resolve(r)})}}push(e,t){t.method==="values"&&this.#l.set(Y(e),t.params.data);let r=this.#s;this.#s=e;let n=!0;for(let s of this.#r)s.process(t)||(n=!1);this.#s=r,n&&this._events.push({...t,seq:this.#e++})}close(){this.#t=!0;for(let[r,n]of this.#l.entries()){let s=r?r.split("\0"):[];this.#o.get(Y(s))?.[ws](n)}let e=[];for(let r of this.#r){let n=r.finalize?.();n!=null&&typeof n.then=="function"&&e.push(n)}for(let r of this.#a)r._close();let t=this.#u;t.length===0&&e.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...e,...t.map(async({name:r,promise:n})=>{try{let s=await n;this._events.done||this._events.push({type:"event",seq:this.#e++,method:"custom",params:{namespace:[],timestamp:Date.now(),data:{name:r,payload:s}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(let r of this.#o.values())r[ws](void 0)}fail(e){this.#t=!0,this.#n=e;for(let t of this.#r)t.fail?.(e);for(let t of this.#a)t._fail(e);this._events.fail(e),this._discoveries.fail(e);for(let t of this.#o.values())t[vo](e)}markInterrupted(e){this.#i=!0,this.#c.push(...e)}get interrupted(){return this.#i}get interrupts(){return this.#c}subscribeEvents(e,t=0){let r=this._events.iterate(t);return{async next(){for(;;){let n=await r.next();if(n.done||Ye(n.value.params.namespace,e))return n}}}}};async function xu(e,t){let r=0;try{for await(let n of e){let[s,i,o]=n;if(i==="values"&&Ht(o)){let c=o[L];t.markInterrupted(c.map(l=>({interruptId:l.id??"",payload:l.value})))}let a=yo({namespace:s,mode:i,payload:o,seq:r});r+=a.length;for(let c of a)t.push(s,c)}}catch(n){t.fail(n);return}t.close()}function Y(e){return e.join("\0")}function Ye(e,t){if(t.length>e.length)return!1;for(let r=0;r<t.length;r+=1)if(e[r]!==t[r])return!1;return!0}function bs(e,t,r=0){return{[Symbol.asyncIterator](){let n=e.iterate(r);return{async next(){for(;;){let s=await n.next();if(s.done)return{value:void 0,done:!0};if(Ye(s.value.namespace,t))return{value:s.value,done:!1}}}}}}}var Tu="root";function Uf(e){if(e.length===0)return Tu;let t=e[e.length-1],r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function Hf(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Xe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bf(e){if(!Xe(e)||e.event!=="started")return;let t=e.cause;if(Xe(t)&&typeof t.type=="string")return t}function Gf(e){if(Xe(e)&&"result"in e&&typeof e.name=="string"&&typeof e.id=="string"&&!e.name.startsWith("__"))return{name:e.name,id:e.id}}function So(e={}){let t=e.rootGraphName??Tu,r=e.initialStatus??"running",n=e.emitRootOnRegister??!0,s=e.getGraphName??Uf,i=e.serializeError??Hf,o=e.getTerminalStatusOverride,a=Ie.local(),c=new Map,l=new Map,u=new Map,h=new Map,p=new Set,f=[],m,d=0,_=!1,g=E=>{if(E.length===0)return t;let A=u.get(Y(E));return typeof A=="string"&&A.length>0?A:s(E)},y=(E,A)=>{let N=Y(E);if(u.has(N))return;let P=(Xe(A)&&Xe(A.metadata)?A.metadata:void 0)?.lc_agent_name;u.set(N,typeof P=="string"?P:void 0)},S=E=>{if(!Xe(E))return;let A=E.id;if(typeof A!="string")return;let N=E.input,P;if(Xe(N)&&Xe(N.tool_call)){let H=N.tool_call.id;typeof H=="string"&&(P=H)}else if(Array.isArray(N)){for(let H of N)if(Xe(H)&&typeof H.id=="string"){P=H.id;break}}P!=null&&h.set(A,P)},w=E=>{if(E.length===0)return;let A=u.get(Y(E));if(typeof A!="string"||A.length===0)return;let N=E[E.length-1],P=N.indexOf(":");if(P===-1)return;let H=N.slice(P+1);if(H.length===0)return;let jt=h.get(H);if(!(typeof jt!="string"||jt.length===0))return{type:"toolCall",tool_call_id:jt}},C=E=>l.get(Y(E))??w(E),T=(E,A,N)=>{let P=Y(E),H=c.get(P),jt=H?.graphName??g(E);if(H!=null&&H.status===A&&H.graphName===jt&&N?.error==null)return;H==null?(H={namespace:E,graphName:jt,status:A},c.set(P,H)):H.status=A;let ia={event:A,graph_name:jt,...N?.cause!=null?{cause:N.cause}:{},...N?.error!=null?{error:N.error}:{}},oa=Date.now();if(a.push({namespace:E,timestamp:oa,...ia}),!(E.length===0&&!n)&&m!=null){d+=1;try{m.push(E,{type:"event",seq:0,method:"lifecycle",params:{namespace:E,timestamp:oa,data:ia}})}finally{d-=1}}},k=E=>{let A=Y(E),N=c.get(A);return N==null&&(N={namespace:E,graphName:g(E),status:void 0},c.set(A,N)),N},b=()=>{if(f.length===0)return;let E=f.splice(0,f.length);for(let A of E){let N=Y(A.namespace),P=c.get(N);P==null||P.status!=="started"||T(A.namespace,"completed")}},I=E=>{let A=Y(E.namespace),N=c.get(A);N==null||N.status!=="started"||f.some(P=>Y(P.namespace)===A)||f.push(E)},x=(E,A)=>{for(let N=f.length-1;N>=0;N-=1){let P=f[N];P.source.type==="node"&&P.source.node===A&&Y(P.source.parent)===Y(E)&&f.splice(N,1)}},F=E=>{for(let A=1;A<=E.length;A+=1){let N=E.slice(0,A),P=Y(N);if(c.has(P))continue;k(N);let H=C(N);T(N,"started",H!=null?{cause:H}:void 0)}},j=()=>p.size>0?"interrupted":"completed",V=E=>{for(let A of c.values())A.namespace.length!==0&&A.status==="started"&&T(A.namespace,E);T([],E),a.close()},B=async()=>{if(o==null)return j();try{return await o()??j()}catch{return j()}},be=(E,A)=>{let N=`${A}:`;for(let P of c.values()){if(P.namespace.length!==E.length+1||P.status!=="started"||!Ye(P.namespace,E))continue;let H=P.namespace[P.namespace.length-1];if(H===A||H.startsWith(N))return P.namespace}},rt=(E,A)=>{let N=[...E,`${A.name}:${A.id}`];return c.get(Y(N))?.status==="started"?N:void 0};return{__native:!0,init(){return{_lifecycleLog:a,lifecycle:bs(a,[],0)}},onRegister(E){m=E,k([]),n&&T([],r)},process(E){let A=E.params.namespace;if(d>0)return!0;let N=E.method==="tasks"?Gf(E.params.data):void 0;if(N!=null?x(A,N.name):E.method==="tasks"&&(y(A,E.params.data),S(E.params.data)),b(),E.method==="lifecycle"){let P=Bf(E.params.data);return P!=null&&l.set(Y(A),P),F(A),!1}if(F(A),E.method==="input"&&Xe(E.params.data)&&E.params.data.event==="requested"){let P=E.params.data.id;typeof P=="string"&&p.add(P)}if(N!=null){let P=rt(A,N);P!=null&&I({namespace:P,source:{type:"task"}})}if(E.method==="updates"){let P=E.params.node;if(typeof P=="string"&&!P.startsWith("__")){let H=be(A,P);H!=null&&I({namespace:H,source:{type:"node",parent:A,node:P}})}}return!0},finalize(){if(!_){if(_=!0,b(),o==null){V(j());return}return B().then(V).catch(E=>{a.fail(E)})}},fail(E){if(_)return;_=!0;let A=i(E);for(let N of c.values())N.namespace.length!==0&&N.status==="started"&&T(N.namespace,"failed");T([],"failed",{error:A}),a.fail(E)}}}function Er(e){let t=e;return typeof t.run_id=="string"?`run:${t.run_id}`:e.event==="message-start"&&typeof t.id=="string"?`message:${t.id}`:"__default__"}function pn(e,t){let r=Ie.local(),n=new Map,s=new Set;return{init:()=>({messages:r.toAsyncIterable()}),process(i){if(i.method!=="messages"||!Ye(i.params.namespace,e)||i.params.namespace.length!==e.length+1||t!==void 0&&i.params.node!==t)return!0;let o=i.params.data;switch(o.event){case"message-start":{let a=Er(o);if(o.role==="tool"){s.add(a);break}let c=Ie.local(),l=Object.assign(new xn(c.toAsyncIterable()),{namespace:i.params.namespace,node:i.params.node});n.set(a,{source:c,stream:l}),c.push(o),r.push(l);break}case"content-block-start":case"content-block-delta":case"content-block-finish":if(s.has(Er(o)))break;n.get(Er(o))?.source.push(o);break;case"message-finish":{let a=Er(o);if(s.delete(a))break;let c=n.get(a);c&&(c.source.push(o),c.source.close(),n.delete(a));break}case"error":if(s.has(Er(o)))break;n.get(Er(o))?.source.push(o);break}return!0},finalize(){for(let[i,o]of n)o.source.push({event:"message-finish"}),o.source.close(),n.delete(i);s.clear(),r.close()},fail(i){for(let[o,a]of n)a.source.fail(i),n.delete(o);s.clear(),r.fail(i)}}}function fn(e,t,r=0){let n=t.length+1;return{[Symbol.asyncIterator](){let s=e.iterate(r);return{async next(){for(;;){let i=await s.next();if(i.done)return{value:void 0,done:!0};let{ns:o,stream:a}=i.value;if(o.length===n&&Ye(o,t))return{value:a,done:!1}}}}}}}function ko(e,t){let{createStream:r}=t,n=new Set;return{__native:!0,init(){return{_discoveries:e._discoveries,subgraphs:fn(e._discoveries,[],0)}},process(s){let i=s.params.namespace;if(i.length===0)return!0;let o=i.slice(0,1),a=Y(o);if(n.has(a))return!0;n.add(a);let c=r(o,e._discoveries.size,e._events.size);return e.register(o,c),e._discoveries.push({ns:o,stream:c}),!0}}}function Eo(e){let t=Ie.local();return{init:()=>({_valuesLog:t}),process(r){return r.method!=="values"||r.params.namespace.length!==e.length||!Ye(r.params.namespace,e)||t.push(r.params.data),!0},finalize(){t.close()},fail(r){t.fail(r)}}}function vs(e){return"__native"in e&&e.__native===!0}var Iu=Symbol("setValuesLog"),Au=Symbol("setMessagesIterable"),Co=Symbol("setLifecycleIterable"),xo=Symbol("setSubgraphsIterable"),Wf={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}},To=class{path;extensions;_mux;#e;#t;#n;#i;#s;#r;#a;#o;#l;#c;constructor(e,t,r=0,n=0,s,i){this.path=e,this._mux=t,this.#t=r,this.#e=n,this.extensions=s??{},this.#n=i??new AbortController,this.#r=new Promise((o,a)=>{this.#i=o,this.#s=a}),this.#r.catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,this.#e)}get subgraphs(){return this.#c?this.#c:fn(this._mux._discoveries,this.path,this.#t)}get values(){let e=this.#a,t=this.#r,r=this._mux,n=this.#e,s=this.path,i=e?e.toAsyncIterable():{[Symbol.asyncIterator]:()=>{let o=r.subscribeEvents(s,n);return{async next(){for(;;){let a=await o.next();if(a.done)return{value:void 0,done:!0};if(a.value.method==="values"&&a.value.params.namespace.length===s.length)return{value:a.value.params.data,done:!1}}}}}};return{[Symbol.asyncIterator]:()=>i[Symbol.asyncIterator](),then:t.then.bind(t)}}get messages(){if(this.#o)return this.#o;let e=pn(this.path),t=e.init();return this._mux.addTransformer(e),this.#o=t.messages,this.#o}get lifecycle(){return this.#l??Wf}messagesFrom(e){let t=pn(this.path,e),r=t.init();return this._mux.addTransformer(t),r.messages}get output(){return this.#r}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(e){this.#n.abort(e)}get signal(){return this.#n.signal}[ws](e){this.#i?.(e),this.#i=void 0}[vo](e){this.#s?.(e),this.#s=void 0}[Iu](e){this.#a=e}[Au](e){this.#o=e}[Co](e){this.#l=e}[xo](e){this.#c=e}},Ou=class extends To{name;index;constructor(e,t,r=0,n=0,s,i){super(e,t,r,n,s,i);let o=e[e.length-1]??"",a=o.lastIndexOf(":");if(a>=0){this.name=o.slice(0,a);let c=o.slice(a+1);this.index=/^\d+$/.test(c)?Number(c):0}else this.name=o,this.index=0}};function Io(e,t=[],r){let{abortController:n}=r instanceof AbortController?{abortController:r}:r??{},s=new Cu,i=So(),o=i.init(),a=o._lifecycleLog,c=ko(s,{createStream:(g,y,S)=>{let w=new Ou(g,s,y,S);return w[xo](fn(s._discoveries,g,y)),w[Co](bs(a,g,a.size)),w}}),l=c.init();s.addTransformer(c),s.addTransformer(i);let u=Eo([]),h=pn([]);s.addTransformer(u),s.addTransformer(h);let p={},f=[];for(let g of t){let y=g();s.addTransformer(y);let S=y.init();vs(y)?f.push(S):Object.assign(p,S),typeof S=="object"&&S!==null&&!vs(y)&&s.wireChannels(S)}let m=new To([],s,0,0,p,n);for(let g of f)Object.assign(m,g);let d=u.init();m[Iu](d._valuesLog);let _=h.init();return m[Au](_.messages),m[Co](o.lifecycle),m[xo](l.subgraphs),s.register([],m),xu(e,s).catch(g=>{}),m}var v=e=>BigInt(e),U=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),Mu=v("0x9E3779B1"),ju=v("0x85EBCA77"),Kf=v("0xC2B2AE3D"),Tt=v("0x9E3779B185EBCA87"),zt=v("0xC2B2AE3D27D4EB4F"),Du=v("0x165667B19E3779F9"),No=v("0x85EBCA77C2B2AE63"),qf=v("0x27D4EB2F165667C5"),zf=v("0x165667919E3779F9"),Jf=v("0x9FB21C651E98DF25"),Yf=e=>{let t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");let r=t/2,n=new Uint8Array(r),s=0,i=0;for(;i<r;){let o=e.slice(s,s+=2);n[i]=Number.parseInt(o,16),i+=1}return U(n)},Qe=Yf("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Cr=(v(1)<<v(128))-v(1),M=(v(1)<<v(64))-v(1),Cs=(v(1)<<v(32))-v(1),ut=64,$u=ut/8,Xf=8,Ss=4;function xr(e){if(!e)throw new Error("Assert failed")}function Qf(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function Zf(e){let t=e;return t=(t&v(65535))<<v(16)|(t&v(4294901760))>>v(16),t=(t&v(16711935))<<v(8)|(t&v(4278255360))>>v(8),t}function em(e,t){return(e&Cs)*(t&Cs)&M}function tm(e,t){return(e<<t|e>>v(32)-t)&Cs}function Vu(e,t,r){for(let n=0;n<$u;n+=1){let s=t.getBigUint64(n*8,!0),i=s^r.getBigUint64(n*8,!0);e[n^1]+=s,e[n]+=em(i,i>>v(32))}return e}function Nu(e,t,r,n){for(let s=0;s<n;s+=1)Vu(e,U(t,s*ut),U(r,s*8));return e}function rm(e,t){for(let r=0;r<$u;r+=1){let n=t.getBigUint64(r*8,!0),s=e[r];s=Ao(s,v(47)),s^=n,s*=Mu,e[r]=s&M}return e}function ks(e,t){return Fu(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(Xf,!0))}function Pu(e,t,r){let n=r;return n+=ks(e.slice(0),U(t,0*Ss)),n+=ks(e.slice(2),U(t,4*Ss)),n+=ks(e.slice(4),U(t,8*Ss)),n+=ks(e.slice(6),U(t,12*Ss)),Ze(n&M)}function nm(e,t,r,n,s){let i=e,o=Math.floor((r.byteLength-ut)/8),a=ut*o,c=Math.floor((t.byteLength-1)/a);for(let l=0;l<c;l+=1)i=Nu(i,U(t,l*a),r,o),i=s(i,U(r,r.byteLength-ut));{let l=Math.floor((t.byteLength-1-a*c)/ut);i=Nu(i,U(t,c*a),r,l),i=n(i,U(t,t.byteLength-ut),U(r,r.byteLength-ut-7))}return i}function sm(e,t){let r=new BigUint64Array([Kf,Tt,zt,Du,No,ju,qf,Mu]);xr(e.byteLength>128),r=nm(r,e,t,Vu,rm),xr(r.length*8===64);{let n=Pu(r,U(t,11),v(e.byteLength)*Tt&M);return Pu(r,U(t,t.byteLength-ut-11),~(v(e.byteLength)*zt)&M)<<v(64)|n}}function Fu(e,t){let r=e*t&Cr;return r&M^r>>v(64)}function Ru(e,t,r){return Fu((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+r)&M,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-r)&M)}function Es(e,t,r,n,s){let i=e&M,o=e>>v(64)&M;return i+=Ru(t,n,s),i^=r.getBigUint64(0,!0)+r.getBigUint64(8,!0),i&=M,o+=Ru(r,U(n,16),s),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=M,o<<v(64)|i}function Ze(e){let t=e;return t^=t>>v(37),t*=zf,t&=M,t^=t>>v(32),t}function xs(e){let t=e;return t^=t>>v(33),t*=zt,t&=M,t^=t>>v(29),t*=Du,t&=M,t^=t>>v(32),t}function im(e,t,r){let n=e.byteLength;xr(n>0&&n<=3);let s=v(e.getUint8(n-1))|v(n<<8)|v(e.getUint8(0)<<16)|v(e.getUint8(n>>1)<<24),i=(s^(v(t.getUint32(0,!0))^v(t.getUint32(4,!0)))+r)&M,o=(v(t.getUint32(8,!0))^v(t.getUint32(12,!0)))-r;return(xs((tm(Zf(s),v(13))^o)&M)&M)<<v(64)|xs(i)}function Ao(e,t){return e^e>>t}function om(e,t,r){let n=e.byteLength;xr(n>=4&&n<=8);{let s=e.getUint32(0,!0),i=e.getUint32(n-4,!0),o=((v(s)|v(i)<<v(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+r&M)*(Tt+(v(n)<<v(2)))&Cr;return o+=(o&M)<<v(65),o&=Cr,o^=o>>v(67),Ao(Ao(o&M,v(35))*Jf&M,v(28))|Ze(o>>v(64))<<v(64)}}function am(e,t,r){let n=e.byteLength;xr(n>=9&&n<=16);{let s=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+r&M,i=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-r&M,o=e.getBigUint64(0,!0),a=e.getBigUint64(n-8,!0),c=(o^a^s)*Tt,l=(c&M)+(v(n-1)<<v(54));c=c&(Cr^M)|l,a^=i,c+=a+(a&Cs)*(ju-v(1))<<v(64),c&=Cr,c^=Qf(c>>v(64));let u=(c&M)*zt;return u+=(c>>v(64))*zt<<v(64),u&=Cr,Ze(u&M)|Ze(u>>v(64))<<v(64)}}function cm(e,t){let r=e.byteLength;return xr(r<=16),r>8?am(e,Qe,t):r>=4?om(e,Qe,t):r>0?im(e,Qe,t):xs(t^Qe.getBigUint64(64,!0)^Qe.getBigUint64(72,!0))|xs(t^Qe.getBigUint64(80,!0)^Qe.getBigUint64(88,!0))<<v(64)}function Oo(e){return~e+v(1)&M}function lm(e,t,r){let n=v(e.byteLength)*Tt&M,s=v(e.byteLength-1)/v(32);for(;s>=0;){let a=Number(s);n=Es(n,U(e,16*a),U(e,e.byteLength-16*(a+1)),U(t,32*a),r),s-=v(1)}let i=n+(n>>v(64))&M;i=Ze(i);let o=(n&M)*Tt+(n>>v(64))*No+(v(e.byteLength)-r&M)*zt;return o&=M,o=Oo(Ze(o)),i|o<<v(64)}function um(e,t,r){let n=v(e.byteLength)*Tt&M;for(let o=32;o<160;o+=32)n=Es(n,U(e,o-32),U(e,o-16),U(t,o-32),r);n=Ze(n&M)|Ze(n>>v(64))<<v(64);for(let o=160;o<=e.byteLength;o+=32)n=Es(n,U(e,o-32),U(e,o-16),U(t,3+o-160),r);n=Es(n,U(e,e.byteLength-16),U(e,e.byteLength-32),U(t,103),Oo(r));let s=n+(n>>v(64))&M;s=Ze(s);let i=(n&M)*Tt+(n>>v(64))*No+(v(e.byteLength)-r&M)*zt;return i&=M,i=Oo(Ze(i)),s|i<<v(64)}function et(e,t=v(0)){let r=new TextEncoder,n=U(typeof e=="string"?r.encode(e):e),s=n.byteLength,i=o=>o.toString(16).padStart(32,"0");return s<=16?i(cm(n,t)):s<=128?i(lm(n,Qe,t)):s<=240?i(um(n,Qe,t)):i(sm(n,Qe))}function Ts(e){return/^[0-9a-f]{32}$/.test(e)}function Po(e){let t=Z.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");if(!r.__pregel_checkpointer)throw new Bt("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=r[ue];n.interruptCounter+=1;let s=n.interruptCounter;if(n.resume.length>0&&s<n.resume.length)return r[oe]?.([[he,n.resume]]),n.resume[s];if(n.nullResume!==void 0){if(n.resume.length!==s)throw new Error(`Resume length mismatch: ${n.resume.length} !== ${s}`);let o=n.consumeNullResume();return n.resume.push(o),r[oe]?.([[he,n.resume]]),o}let i=r[ve]?.split("|");throw new it([{id:i?et(i.join("|")):void 0,value:e}])}var se=class extends G{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,t,r){return new Promise((n,s)=>{let i=nt(t,{callbacks:r?.getChild()});Z.runWithConfig(i,async()=>{try{n(await this.func(e,i))}catch(o){s(o)}})})}async invoke(e,t){let r,n=Sr(t),s=ke(this.config,n);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,s):r=await Z.runWithConfig(s,async()=>this.func(e,s)),G.isRunnable(r)&&this.recurse?await Z.runWithConfig(s,async()=>r.invoke(e,s)):r}};function*tt(e,t){if(t===void 0)yield*e;else for(let r of e)yield[t,r]}async function Ve(e){let t=[];for await(let r of await e)t.push(r);return t}function It(e){let t=[];for(let r of e)t.push(r);return t}function Jt(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function Ro(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(async function*(){}).constructor}function Mo(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(function*(){}).constructor}function hm(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}var we={[Symbol.for("LG_PASSTHROUGH")]:!0};function Is(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}var jo=Symbol("IS_WRITER"),q=class $o extends se{writes;constructor(t,r){let n=`ChannelWrite<${t.map(s=>ee(s)?s.node:"channel"in s?s.channel:"...").join(",")}>`;super({writes:t,name:n,tags:r,trace:!1,func:async(s,i)=>this._write(s,i??{})}),this.writes=t}async _write(t,r){let n=this.writes.map(s=>Do(s)&&Is(s.value)?{mapper:s.mapper,value:t}:As(s)&&Is(s.value)?{channel:s.channel,value:t,skipNone:s.skipNone,mapper:s.mapper}:s);return await $o.doWrite(r,n),t}static async doWrite(t,r){for(let i of r){if(As(i)){if(i.channel==="__pregel_tasks")throw new R("Cannot write to the reserved channel TASKS");if(Is(i.value))throw new R("PASSTHROUGH value must be replaced")}if(Do(i)&&Is(i.value))throw new R("PASSTHROUGH value must be replaced")}let n=[];for(let i of r)if(ee(i))n.push([qe,i]);else if(Do(i)){let o=await i.mapper.invoke(i.value,t);o!=null&&o.length>0&&n.push(...o)}else if(As(i)){let o=i.mapper!==void 0?await i.mapper.invoke(i.value,t):i.value;if(hm(o)||i.skipNone&&o===void 0)continue;n.push([i.channel,o])}else throw new Error(`Invalid write entry: ${JSON.stringify(i)}`);let s=t.configurable?.[oe];s(n)}static isWriter(t){return t instanceof $o||jo in t&&!!t[jo]}static registerWriter(t){return Object.defineProperty(t,jo,{value:!0})}};function As(e){return e!==void 0&&typeof e.channel=="string"}function Do(e){return e!==void 0&&!As(e)&&G.isRunnable(e.mapper)}var Lu=class Uu extends se{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,r,n=!1){super({trace:!1,func:(s,i)=>Uu.doRead(i,this.channel,this.fresh,this.mapper)}),this.fresh=n,this.mapper=r,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,r,n,s){let i=t.configurable?.[le];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(r,n)):i(r,n)}},Tr=new ec,Fe=class mn extends En{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=Tr;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;timeout;subgraphs;ends;isErrorHandler;errorHandlerNode;constructor(t){let{channels:r,triggers:n,mapper:s,writers:i,bound:o,kwargs:a,metadata:c,retryPolicy:l,cachePolicy:u,timeout:h,tags:p,subgraphs:f,ends:m,isErrorHandler:d,errorHandlerNode:_}=t,g=[...t.config?.tags?t.config.tags:[],...p??[]];super({...t,bound:t.bound??Tr,config:{...t.config?t.config:{},tags:g}}),this.channels=r,this.triggers=n,this.mapper=s,this.writers=i??this.writers,this.bound=o??this.bound,this.kwargs=a??this.kwargs,this.metadata=c??this.metadata,this.tags=g,this.retryPolicy=l,this.cachePolicy=u,this.timeout=h,this.subgraphs=f,this.ends=m,this.isErrorHandler=d,this.errorHandlerNode=_}getWriters(){let t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof q&&t[t.length-2]instanceof q;){let r=t.slice(-2),n=r[0].writes.concat(r[1].writes);t[t.length-2]=new q(n,r[0].config?.tags),t.pop()}return t}getNode(){let t=this.getWriters();if(!(this.bound===Tr&&t.length===0))return this.bound===Tr&&t.length===1?t[0]:this.bound===Tr?new $t({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new $t({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))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 mn({channels:{...this.channels,...Object.fromEntries(t.map(r=>[r,r]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}pipe(t){return q.isWriter(t)?new mn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):this.bound===Tr?new mn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Be(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):new mn({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}};function pm(e){return"steps"in e&&Array.isArray(e.steps)}function dn(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function Os(e){let t=[e];for(let r of t){if(dn(r))return r;pm(r)&&t.push(...r.steps)}}function Yt(e,t,r=!0,n=!1){try{return e[t].get()}catch(s){if(s.name===$.unminifiable_name){if(n)return s;if(r)return null}throw s}}function Le(e,t,r=!0){if(Array.isArray(t)){let n={};for(let s of t)try{n[s]=Yt(e,s,!r)}catch(i){if(i.name===$.unminifiable_name)continue}return n}else return Yt(e,t)}function*Hu(e,t){if(e.graph===_e.PARENT)throw new R("There is no parent graph.");if(e.goto){let r;Array.isArray(e.goto)?r=e.goto:r=[e.goto];for(let n of r)if(ee(n))yield[fe,qe,n];else if(typeof n=="string")yield[fe,`branch:to:${n}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof n}`)}if(e.resume)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(Ts))for(let[r,n]of Object.entries(e.resume)){let s=t.filter(i=>i[0]===r&&i[1]==="__resume__").map(i=>i[2]).slice(0,1)??[];s.push(n),yield[r,he,s]}else yield[fe,he,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(let[r,n]of e.update)yield[fe,r,n];else for(let[r,n]of Object.entries(e.update))yield[fe,r,n]}}function*Ns(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(let r in t)e.includes(r)&&(yield[r,t[r]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Ps(e,t,r){Array.isArray(e)?(t===!0||t.find(([n,s])=>e.includes(n)))&&(yield Le(r,e)):(t===!0||t.some(([n,s])=>n===e))&&(yield Yt(r,e))}function*Bu(e,t,r){let n=t.filter(([a,c])=>(a.config===void 0||!a.config.tags?.includes("langsmith:hidden"))&&c[0][0]!=="__error__"&&c[0][0]!=="__interrupt__");if(!n.length)return;let s;n.some(([a])=>a.writes.some(([c,l])=>c==="__return__"))?s=n.flatMap(([a])=>a.writes.filter(([c,l])=>c===Et).map(([c,l])=>[a.name,l])):Array.isArray(e)?s=n.flatMap(([a])=>{let{writes:c}=a,l={};for(let[u]of c)e.includes(u)&&(l[u]=(l[u]||0)+1);return Object.values(l).some(u=>u>1)?c.filter(([u])=>e.includes(u)).map(([u,h])=>[a.name,{[u]:h}]):[[a.name,Object.fromEntries(c.filter(([u])=>e.includes(u)))]]}):s=n.flatMap(([a])=>a.writes.filter(([c,l])=>c===e).map(([c,l])=>[a.name,l]));let i={};for(let[a,c]of s)a in i||(i[a]=[]),i[a].push(c);let o={};for(let a in i)if(i[a].length===1){let[c]=i[a];o[a]=c}else o[a]=i[a];r&&(o.__metadata__={cached:r}),yield o}function Rs(e){let t=typeof e[W];if(t==="number")return 0;if(t==="string")return"";for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=typeof e[r];if(n==="number")return 0;if(n==="string")return"";break}}function Ir(e,t){if(Object.keys(e).length>0){let r=Rs(t);return Object.fromEntries(Object.entries(t).filter(([n,s])=>s>(e[n]??r)))}else return t}function Gu(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function te(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function At(e,t){let r=t?.parents??{};return Object.keys(r).length>0?te(e,{[ae]:{...r,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function Ot(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let r=new AbortController,n=()=>{let i=t.find(o=>o.aborted)?.reason;r.abort(i),t.forEach(o=>o.removeEventListener("abort",n))};t.forEach(i=>i.addEventListener("abort",n,{once:!0}));let s=t.find(i=>i.aborted);return s&&r.abort(s.reason),{signal:r.signal,dispose:()=>{t.forEach(i=>i.removeEventListener("abort",n))}}}var Wu=class{func;name;input;retry;cache;timeout;callbacks;__lg_type="call";constructor({func:e,name:t,input:r,retry:n,cache:s,timeout:i,callbacks:o}){this.func=e,this.name=t,this.input=r,this.retry=n,this.cache=s,this.timeout=i,this.callbacks=o}};function Ku(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function qu(e,t){return new $t({name:e,first:new se({func:r=>t(...r),name:e,trace:!1,recurse:!1}),last:new q([{channel:Et,value:we}],[z])})}function zu(e,t){return new se({func:(r,n)=>t(r,n),name:e,trace:!1,recurse:!1})}function Ju({func:e,name:t,cache:r,retry:n,timeout:s},...i){let o=Z.getRunnableConfig();if(typeof o.configurable?.__pregel_call=="function")return o.configurable[Ke](e,t,i,{retry:n,cache:r,timeout:s,callbacks:o.callbacks});throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function.")}var Yu=e=>e!==void 0?e+1:1;function fm(e,t){if(t==null)return!1;for(let r of e)if(t[r])return!0;return!1}function mm(e){let t;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t==null?t=e[r]:t=cn(t,e[r]));return t}function gn(e,t,r){let n=Rs(e.channel_versions),s=e.versions_seen.__interrupt__??{},i=!1;if((e.channel_versions.__start__??n)>(s.__start__??n))i=!0;else for(let a in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,a)&&e.channel_versions[a]>(s[a]??n)){i=!0;break}let o=r.some(a=>t==="*"?!a.config?.tags?.includes(z):t.includes(a.name));return i&&o}function Ar(e,t,r,n,s=!1){let i=new Set;if(Array.isArray(n))i=new Set(n.filter(a=>r.writes.some(([c,l])=>c===a)));else{for(let[a]of r.writes)if(a===n){i=new Set([a]);break}i=i||new Set}let o;if(s&&i.size>0){let a=Object.fromEntries(Object.entries(t).filter(([h,p])=>i.has(h))),c=new Set;for(let h in a){if(!Object.prototype.hasOwnProperty.call(a,h))continue;let p=a[h];Te(p)&&p.isAvailable()&&c.add(h)}let l=De(e,a,-1,{channelsToSnapshot:c}),u=fs(a,l);de(je(l),u,[r],void 0,void 0),o=Le({...t,...u},n)}else o=Le(t,n);return o}function Ms(e,t,r){for(let[n,s]of r)if(["__pregel_push","__pregel_tasks"].includes(n)&&s!=null){if(!ee(s))throw new R(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in t))throw new R(`Invalid node name "${s.node}" in Send packet`)}e(r)}var dm=new Set([Fr,pe,he,L,Et,vt,Dr]),gm=new Set(vc);function de(e,t,r,n,s){let i=new Map;for(let m of r)i.set(m,m.path?.slice(0,3)||[]);r.sort((m,d)=>{let _=i.get(m),g=i.get(d);for(let y=0;y<Math.min(_.length,g.length);y+=1){if(_[y]<g[y])return-1;if(_[y]>g[y])return 1}return _.length-g.length});let o=br(t),a=!1,c=new Set;for(let m of r){m.triggers.length>0&&(a=!0),e.versions_seen[m.name]??={};for(let d of m.triggers)d in e.channel_versions&&(e.versions_seen[m.name][d]=e.channel_versions[d]),gm.has(d)||c.add(d)}let l=mm(e.channel_versions),u=!1;for(let m of c)m in o&&o[m].consume()&&n!==void 0&&(e.channel_versions[m]=n(l),u=!0);let h={},p={};for(let m of r){let d=m.id??"";for(let[_,g]of m.writes)dm.has(_)||_ in o&&(h[_]??=[],h[_].push(g),p[_]??=[],p[_].push(d))}for(let[m,d]of Object.entries(h)){if(d.length<2||o[m]?.lc_graph_name!=="DeltaChannel")continue;let _=p[m],g=d.map((y,S)=>({val:y,taskId:_[S]}));g.sort((y,S)=>y.taskId<S.taskId?-1:y.taskId>S.taskId?1:0),h[m]=g.map(y=>y.val)}l!=null&&n!=null&&(l=u?n(l):l);let f=new Set;for(let[m,d]of Object.entries(h))if(m in o){let _=o[m],g;try{g=_.update(d)}catch(y){if(y.name===R.unminifiable_name){let S=new R(`Invalid update for channel "${m}" with values ${JSON.stringify(d)}: ${y.message}`);throw S.lc_error_code=y.lc_error_code,S}else throw y}g&&n!==void 0&&(e.channel_versions[m]=n(l),_.isAvailable()&&f.add(m))}if(a)for(let m in o){if(!Object.prototype.hasOwnProperty.call(o,m))continue;let d=o[m];d.isAvailable()&&!f.has(m)&&d.update([])&&n!==void 0&&(e.channel_versions[m]=n(l),d.isAvailable()&&f.add(m))}if(a&&!fm(f,s))for(let m in o){if(!Object.prototype.hasOwnProperty.call(o,m))continue;let d=o[m];d.finish()&&n!==void 0&&(e.channel_versions[m]=n(l),d.isAvailable()&&f.add(m))}return f}function*_m(e,t,r){if(r.updatedChannels!=null&&r.triggerToNodes!=null){let n=new Set;for(let s of r.updatedChannels){let i=r.triggerToNodes[s];for(let o of i??[])n.add(o)}yield*[...n].sort();return}if(!(()=>{for(let n in e.channel_versions)if(e.channel_versions[n]!==null)return!1;return!0})())for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(yield n)}function ym(e){let t,r=new Map,n=new Set;if(e)for(let[s,i,o]of e){if(s==="00000000-0000-0000-0000-000000000000"&&i==="__resume__"&&t===void 0&&(t=o),i==="__resume__"&&s!=="00000000-0000-0000-0000-000000000000"){let a=r.get(s);a||(a=[],r.set(s,a)),a.push(o)}i!=="__error__"&&n.add(s)}return{nullResume:t,resumeByTaskId:r,successfulWriteTaskIds:n}}function Nt(e,t,r,n,s,i,o){let a={},c=o.pendingWritesIndex?o:{...o,pendingWritesIndex:ym(t)},l=n[qe];if(l?.isAvailable()){let u=l.get().length;for(let h=0;h<u;h+=1){let p=Ds([pe,h],e,t,r,n,s,i,c);p!==void 0&&(a[p.id]=p)}}for(let u of _m(e,r,c)){let h=Ds([An,u],e,t,r,n,s,i,c);h!==void 0&&(a[h.id]=h)}return a}function Ds(e,t,r,n,s,i,o,a){let{step:c,checkpointer:l,manager:u}=a,h=i.configurable??{},p=h.checkpoint_ns??"";if(e[0]==="__pregel_push"&&Ku(e[e.length-1])){let f=e[e.length-1],m=qu(f.name,f.func),d=[pe],_=p===""?f.name:`${p}|${f.name}`,g=ze(JSON.stringify([_,c.toString(),f.name,pe,e[1],e[2]]),t.id),y=`${_}:${g}`,S=[...e.slice(0,3),!0],w={langgraph_step:c,langgraph_node:f.name,langgraph_triggers:d,langgraph_path:S,langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let C=[],T={checkpointId:t.id,checkpointNs:y,taskId:g,threadId:h.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:f.name,input:f.input,proc:m,writes:C,config:{...nt(ke(i,{metadata:w,store:a.store??i.store}),{runName:f.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[or]:g,[oe]:k=>Ms(b=>C.push(...b),n,k),[le]:(k,b=!1)=>Ar(t,s,{name:f.name,writes:C,triggers:d,path:S},k,b),[Ee]:l??h.__pregel_checkpointer,[ae]:{...h[ae],[p]:t.id},[ue]:js({pendingWrites:r??[],taskId:g,currentTaskInput:f.input,resumeMap:i.configurable?.[Lt],namespaceHash:et(y),pendingWritesIndex:a.pendingWritesIndex}),[St]:t.channel_values[Ct],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:T},triggers:d,retry_policy:f.retry,cache_key:f.cache?{key:et((f.cache.keyFunc??JSON.stringify)([f.input])),ns:[Tn,f.name??"__dynamic__"],ttl:f.cache.ttl}:void 0,id:g,path:S,writers:[],timeout:f.timeout}}else return{id:g,name:f.name,interrupts:[],path:S}}else if(e[0]==="__pregel_push"){let f=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!s.__pregel_tasks?.isAvailable())return;let m=s[qe].get();if(f<0||f>=m.length)return;let d=On(m[f])&&!ee(m[f])?new Vt(m[f].node,m[f].args,m[f].timeout!==void 0?{timeout:m[f].timeout}:void 0):m[f];if(!On(d)){console.warn(`Ignoring invalid packet ${JSON.stringify(d)} in pending sends.`);return}if(!(d.node in n)){console.warn(`Ignoring unknown node name ${d.node} in pending sends.`);return}let _=[pe],g=p===""?d.node:`${p}|${d.node}`,y=ze(JSON.stringify([g,c.toString(),d.node,pe,f.toString()]),t.id),S=`${g}:${y}`,w={langgraph_step:c,langgraph_node:d.node,langgraph_triggers:_,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:S,checkpoint_ns:S};if(o){let C=n[d.node],T=C.getNode();if(T!==void 0){C.metadata!==void 0&&(w={...w,...C.metadata});let k=[],b={checkpointId:t.id,checkpointNs:S,taskId:y,threadId:h.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:d.node,input:d.args,proc:T,subgraphs:C.subgraphs,writes:k,config:{...nt(ke(i,{metadata:w,tags:C.tags,store:a.store??i.store}),{runName:d.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[or]:y,[oe]:I=>Ms(x=>k.push(...x),n,I),[le]:(I,x=!1)=>Ar(t,s,{name:d.node,writes:k,triggers:_,path:e},I,x),[Ee]:l??h.__pregel_checkpointer,[ae]:{...h[ae],[p]:t.id},[ue]:js({pendingWrites:r??[],taskId:y,currentTaskInput:d.args,resumeMap:i.configurable?.[Lt],namespaceHash:et(S),pendingWritesIndex:a.pendingWritesIndex}),[St]:t.channel_values[Ct],checkpoint_id:void 0,checkpoint_ns:S}}),executionInfo:b},triggers:_,retry_policy:C.retryPolicy,cache_key:C.cachePolicy?{key:et((C.cachePolicy.keyFunc??JSON.stringify)([d.args])),ns:[Tn,C.name??"__dynamic__",d.node],ttl:C.cachePolicy.ttl}:void 0,id:y,path:e,writers:C.getWriters(),timeout:d.timeout??C.timeout}}}else return{id:y,name:d.node,interrupts:[],path:e}}else if(e[0]==="__pregel_pull"){let f=e[1].toString(),m=n[f];if(m===void 0)return;if(r?.length){let y=p===""?f:`${p}|${f}`,S=ze(JSON.stringify([y,c.toString(),f,An,f]),t.id);if(a.pendingWritesIndex?a.pendingWritesIndex.successfulWriteTaskIds.has(S):r.some(w=>w[0]===S&&w[1]!=="__error__"))return}let d=Rs(t.channel_versions);if(d===void 0)return;let _=t.versions_seen[f]??{},g=m.triggers.find(y=>s[y].isAvailable()?(t.channel_versions[y]??d)>(_[y]??d):!1);if(g!==void 0){let y=wm(m,s,o);if(y===void 0)return;let S=p===""?f:`${p}|${f}`,w=ze(JSON.stringify([S,c.toString(),f,An,[g]]),t.id),C=`${S}:${w}`,T={langgraph_step:c,langgraph_node:f,langgraph_triggers:[g],langgraph_path:e,langgraph_checkpoint_ns:C,checkpoint_ns:C};if(o){let k=m.getNode();if(k!==void 0){m.metadata!==void 0&&(T={...T,...m.metadata});let b=[],I={checkpointId:t.id,checkpointNs:C,taskId:w,threadId:h.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:f,input:y,proc:k,subgraphs:m.subgraphs,writes:b,config:{...nt(ke(i,{metadata:T,tags:m.tags,store:a.store??i.store}),{runName:f,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[or]:w,[oe]:x=>Ms(F=>{b.push(...F)},n,x),[le]:(x,F=!1)=>Ar(t,s,{name:f,writes:b,triggers:[g],path:e},x,F),[Ee]:l??h.__pregel_checkpointer,[ae]:{...h[ae],[p]:t.id},[ue]:js({pendingWrites:r??[],taskId:w,currentTaskInput:y,resumeMap:i.configurable?.[Lt],namespaceHash:et(C),pendingWritesIndex:a.pendingWritesIndex}),[St]:t.channel_values[Ct],checkpoint_id:void 0,checkpoint_ns:C}}),executionInfo:I},triggers:[g],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:et((m.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[Tn,m.name??"__dynamic__",f],ttl:m.cachePolicy.ttl}:void 0,id:w,path:e,writers:m.getWriters(),timeout:m.timeout}}}else return{id:w,name:f,interrupts:[],path:e}}}}function Xu(e,t,r,n,s,i,o,a,c){let{step:l,checkpointer:u,manager:h}=c,p=i[t];if(p===void 0)return;let f=p.getNode();if(f===void 0)return;let m=a.configurable??{},d=m.checkpoint_ns??"",_=[pe],g=d===""?t:`${d}|${t}`,y=ze(JSON.stringify([g,l.toString(),t,pe,"node_error_handler",e.id]),n.id),S=`${g}:${y}`,w=[pe,String(e.name),t,!1],C={langgraph_step:l,langgraph_node:t,langgraph_triggers:_,langgraph_path:w,langgraph_checkpoint_ns:S,checkpoint_ns:S};p.metadata!==void 0&&(C={...C,...p.metadata});let T=[],k={checkpointId:n.id,checkpointNs:S,taskId:y,threadId:m.thread_id,runId:a.runId!=null?String(a.runId):void 0,nodeAttempt:1};return{name:t,input:e.input,proc:f,subgraphs:p.subgraphs,writes:T,config:{...nt(ke(a,{metadata:C,tags:p.tags,store:c.store??a.store}),{runName:t,callbacks:h?.getChild(`graph:step:${l}`),configurable:{[or]:y,[oe]:b=>Ms(I=>T.push(...I),i,b),[le]:(b,I=!1)=>Ar(n,o,{name:t,writes:T,triggers:_,path:w},b,I),[Ee]:u??m.__pregel_checkpointer,[ae]:{...m[ae],[d]:n.id},[ue]:js({pendingWrites:s??[],taskId:y,currentTaskInput:e.input,resumeMap:a.configurable?.[Lt],namespaceHash:et(S)}),[St]:n.channel_values[Ct],[Vr]:new jn(String(e.name),r),checkpoint_id:void 0,checkpoint_ns:S}}),executionInfo:k},triggers:_,retry_policy:p.retryPolicy,cache_key:void 0,id:y,path:w,writers:p.getWriters()}}function wm(e,t,r){let n;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){n={};for(let[s,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{n[s]=Yt(t,i,!1)}catch(o){if(o.name===$.unminifiable_name)return;throw o}else if(i in t)try{n[s]=Yt(t,i,!1)}catch(o){if(o.name===$.unminifiable_name)continue;throw o}}else if(Array.isArray(e.channels)){let s=!1;for(let i of e.channels)try{n=Yt(t,i,!1),s=!0;break}catch(o){if(o.name===$.unminifiable_name)continue;throw o}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return r&&e.mapper!==void 0&&(n=e.mapper(n)),n}function Qu(e,t){if(typeof e.args!="object"||e.args===null)return e;let r={};for(let[n,s]of Object.entries(e.args)){let i=t[n];(!i||i.lc_graph_name!=="UntrackedValue")&&(r[n]=s)}return new Vt(e.node,r)}function js({pendingWrites:e,taskId:t,currentTaskInput:r,resumeMap:n,namespaceHash:s,pendingWritesIndex:i}){let o=i?i.nullResume:e.find(([c,l])=>c==="00000000-0000-0000-0000-000000000000"&&l==="__resume__")?.[2],a={callCounter:0,interruptCounter:-1,resume:(()=>{let c=i?(i.resumeByTaskId.get(t)??[]).flat():e.filter(([l,u])=>l===t&&u==="__resume__").flatMap(([l,u,h])=>h);if(n!=null&&s in n){let l=n[s];c.push(l)}return c})(),nullResume:o,subgraphCounter:0,currentTaskInput:r,consumeNullResume:()=>{if(a.nullResume)return delete a.nullResume,e.splice(e.findIndex(([c,l])=>c==="00000000-0000-0000-0000-000000000000"&&l==="__resume__"),1),o}};return a}var _n={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},yn=(e,t)=>`${e.start}${t}${e.end}`;function bm(e){if(e==null)return;let t={};if(e.metadata!=null)for(let[n,s]of Object.entries(e.metadata))uo.has(n)||(t[n]=s);let r=Su(e.tags);return r!=null&&(t.tags=r),Object.keys(t).length>0?t:void 0}function*$s(e){for(let{id:t,name:r,input:n,config:s,triggers:i,writes:o}of e){if(s?.tags?.includes("langsmith:hidden"))continue;let a={id:t,name:r,input:n,triggers:i,interrupts:o.filter(([l,u])=>l===t&&u==="__interrupt__").map(([,l])=>l)},c=bm(s);c!=null&&(a.metadata=c),yield a}}function vm(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function Zu(e){let t={};for(let[r,n]of e){let s=String(r);if(s in t){let i=vm(t[s])?t[s].$writes:[t[s]];i.push(n),t[s]={$writes:i}}else t[s]=n}return t}function*eh(e,t){for(let[{id:r,name:n,config:s},i]of e)s?.tags?.includes("langsmith:hidden")||(yield{id:r,name:n,result:Zu(i.filter(([o])=>Array.isArray(t)?t.includes(o):o===t)),interrupts:i.filter(o=>o[0]===L).map(o=>o[1])})}function*th(e,t,r,n,s,i,o,a){function c(h){let p={};return h.callbacks!=null&&(p.callbacks=h.callbacks),h.configurable!=null&&(p.configurable=h.configurable),h.maxConcurrency!=null&&(p.max_concurrency=h.maxConcurrency),h.metadata!=null&&(p.metadata=h.metadata),h.recursionLimit!=null&&(p.recursion_limit=h.recursionLimit),h.runId!=null&&(p.run_id=h.runId),h.runName!=null&&(p.run_name=h.runName),h.tags!=null&&(p.tags=h.tags),p}let l=e.configurable?.checkpoint_ns,u={};for(let h of s){if(!(h.subgraphs?.length?h.subgraphs:[h.proc]).find(Os))continue;let p=`${h.name}:${h.id}`;l&&(p=`${l}|${p}`),u[h.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:p}}}yield{config:c(e),values:Le(t,r),metadata:n,next:s.map(h=>h.name),tasks:Vo(s,i,u,a),parentConfig:o?c(o):void 0}}function Vo(e,t,r,n){return e.map(s=>{let i=t.find(([l,u])=>l===s.id&&u==="__error__")?.[2],o=t.filter(([l,u])=>l===s.id&&u==="__interrupt__").map(([,,l])=>l),a=(()=>{if(i||o.length||!t.length)return;let l=t.findIndex(([u,h])=>u===s.id&&h==="__return__");if(l>=0)return t[l][2];if(typeof n=="string")return t.find(([u,h])=>u===s.id&&h===n)?.[2];if(Array.isArray(n)){let u=t.filter(([h,p])=>h===s.id&&n.includes(p)).map(([,h,p])=>[h,p]);return u.length?Zu(u):void 0}})();if(i)return{id:s.id,name:s.name,path:s.path,error:i,interrupts:o,result:a};let c=r?.[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:o,...c!==void 0?{state:c}:{},result:a}})}function rh(e,t,r){console.log([`${yn(_n.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
|
|
120
|
+
`,JSON.stringify(Le(t,r),null,2)].join(""))}function wn(e,t){let r=t.length;console.log([`${yn(_n.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${r} task${r===1?"":"s"}:\x1B[0m
|
|
121
|
+
`,t.map(n=>`- ${yn(_n.green,String(n.name))} -> ${JSON.stringify(n.input,null,2)}`).join(`
|
|
122
|
+
`)].join(""))}function nh(e,t,r){let n={};for(let[s,i]of t)r.includes(s)&&(n[s]||(n[s]=[]),n[s].push(i));console.log([`${yn(_n.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(n).length} channel${Object.keys(n).length!==1?"s":""}:\x1B[0m
|
|
123
|
+
`,Object.entries(n).map(([s,i])=>`- ${yn(_n.yellow,s)} -> ${i.map(o=>JSON.stringify(o)).join(", ")}`).join(`
|
|
124
|
+
`)].join(""))}var Vs=class extends Mr{_abortController;_innerReader;constructor(e,t){let r=e.getReader(),n=t??new AbortController;super({start(s){return i();function i(){return r.read().then(({done:o,value:a})=>{if(o){s.close();return}return s.enqueue(a),i()})}}}),this._abortController=n,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},Lo=class extends Mr{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,r=new Promise(n=>{t=n});super({start:n=>{t(n)}}),r.then(n=>{this.controller=n}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this._closed||!this.controller||(this.passthroughFn?.(e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){try{this.controller?.error(e)}finally{this._closed=!0}}},oh=class extends yt{name="StreamToolsHandler";awaitHandlers=!0;streamFn;runs={};constructor(e){super(),this.streamFn=e}handleToolStart(e,t,r,n,s,i,o,a){if(!i||s&&s.includes("langsmith:hidden"))return;let c=i.langgraph_checkpoint_ns?.split("|")??[],l={ns:c,toolCallId:a,toolName:o??"unknown",input:t};this.runs[r]=l,this.streamFn([c,"tools",{event:"on_tool_start",toolCallId:l.toolCallId,name:l.toolName,input:t}])}handleToolEvent(e,t){let r=this.runs[t];r&&this.streamFn([r.ns,"tools",{event:"on_tool_event",toolCallId:r.toolCallId,name:r.toolName,data:e}])}handleToolEnd(e,t){let r=this.runs[t];delete this.runs[t],r&&this.streamFn([r.ns,"tools",{event:"on_tool_end",toolCallId:r.toolCallId,name:r.toolName,output:e}])}handleToolError(e,t){let r=this.runs[t];delete this.runs[t],r&&this.streamFn([r.ns,"tools",{event:"on_tool_error",toolCallId:r.toolCallId,name:r.toolName,error:e}])}};function Sm(e){return JSON.stringify(e,function(t,r){let n=this[t];if(n!=null&&typeof n=="object"&&"toDict"in n&&typeof n.toDict=="function"){let{type:s,data:i}=n.toDict();return{...i,type:s}}return r})}function km(e){return e instanceof Error?{error:e.name,message:e.message}:{error:"Error",message:JSON.stringify(e)}}function Uo(e){return typeof e!="object"||e==null?!1:"configurable"in e&&typeof e.configurable=="object"&&e.configurable!=null}function Fo(e){return!Uo(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||"",checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function sh(e){if(Uo(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([n])=>!n.startsWith("__"))),r={...e,configurable:t};return delete r.callbacks,r}return e}function ih(e){let t={...e,checkpoint:Fo(e.config),parent_checkpoint:Fo(e.parentConfig),config:sh(e.config),parent_config:sh(e.parentConfig),tasks:e.tasks.map(r=>{if(Uo(r.state)){let n=Fo(r.state);if(n!=null){let s={...r,checkpoint:n};return delete s.state,s}}return r})};return delete t.parentConfig,t}function ah(e){let t=new TextEncoder;return new ReadableStream({async start(r){let n=s=>{r.enqueue(t.encode(`event: ${s.event}
|
|
125
|
+
data: ${Sm(s.data)}
|
|
126
|
+
|
|
127
|
+
`))};try{for await(let s of e){let[i,o,a]=s,c=a;if(o==="debug"){let l=a;l.type==="checkpoint"&&(c={...l,payload:ih(l.payload)})}o==="checkpoints"&&(c=ih(a)),n({event:i?.length?`${o}|${i.join("|")}`:o,data:c})}}catch(s){n({event:"error",data:km(s)})}r.close()}})}function ch(...e){return new Lo({passthroughFn:t=>{let r=t[1]==="checkpoints"&&kr(t[2]);for(let n of e)(n.modes.has(t[1])||r)&&n.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var lh=class{checkpointId;#e=new Set;constructor(e){this.checkpointId=e}#t(e){let t=e.includes(":")?e.slice(0,e.lastIndexOf(":")):e;return this.#e.has(t)?!1:(this.#e.add(t),!0)}async getCheckpoint(e,t,r){if(this.#t(e)){let n=[];for await(let s of t.list(r,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))n.push(s);return n.length>0?n[0]:void 0}return await t.getTuple(r)??void 0}};var Fs=Symbol.for("INPUT_DONE"),Ho=Symbol.for("INPUT_RESUMING"),Em=25;function uh(e){if(!(e==null||typeof e!="object")){if(X.isInstance(e)){let t=e;t.id==null&&(t.id=Nr(),t.lc_kwargs!=null&&(t.lc_kwargs.id=t.id));return}if(Array.isArray(e)){for(let t of e)uh(t);return}}}function hh(e){return e===void 0||e===""?[]:e.split("|")}function Cm(e){if(!e)return[];let t="";for(let r of Object.keys(e))r!==""&&r.length>t.length&&(t=r);return hh(t)}var xm=class extends ps{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){let r=this.queue.then(()=>this.cache[e](...t));return this.queue=r.then(()=>{},()=>{}),r}},ph=class fh{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;_exitDeltaWrites;_deltaChannelsWithOverwrite=new Set;_hasPersistedParent=!1;_initialCheckpointConfig;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";control;tasks={};stream;checkpointerPromises=new Set;isNested;resumeAtHead;_checkpointerChainedPromise=Promise.resolve();_trackCheckpointerPromise(t){let r=t.then(n=>(this.checkpointerPromises.delete(r),n),n=>{throw n});this.checkpointerPromises.add(r)}async _awaitCheckpointerPromises(){await Promise.all([...this.checkpointerPromises])}store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if("__start__"in this.checkpoint.channel_versions)t=!0;else for(let a in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,a)){t=!0;break}let r=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,s=ne(this.input)&&this.input.resume!=null,i=this.input===Ho,o=!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 t&&(r||n||s||i||o)}get isReplaying(){return!this.skipDoneTasks}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=Yu,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites,this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.resumeAtHead=t.resumeAtHead,this.manager=t.manager,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.skipDoneTasks=t.skipDoneTasks,this.store=t.store,this.cache=t.cache?new xm(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes,this.control=this.config.control,this._exitDeltaWrites=this.durability==="exit"&&this.checkpointer!=null?[]:void 0,this._hasPersistedParent=t.hasPersistedParent??!1,this._initialCheckpointConfig=t.checkpointConfig,this.checkpointIdSaved=t.checkpoint.id}static async initialize(t){let{config:r,stream:n}=t;n!==void 0&&r.configurable?.__pregel_stream!==void 0&&(n=ch(n,r.configurable[$r]));let s=r.configurable?!("checkpoint_id"in r.configurable):!0,i=r.configurable?.[ue];r.configurable&&i&&(i.subgraphCounter>0&&(r=te(r,{[ve]:[r.configurable[ve],i.subgraphCounter.toString()].join("|")})),i.subgraphCounter+=1);let o=r.configurable?.checkpoint_id,a=le in(r.configurable??{});!a&&r.configurable?.checkpoint_ns!==void 0&&r.configurable?.checkpoint_ns!==""&&(r=te(r,{checkpoint_ns:"",checkpoint_id:void 0}));let c=r;r.configurable?.checkpoint_id===void 0&&r.configurable?.checkpoint_map!==void 0&&r.configurable?.checkpoint_map?.[r.configurable?.checkpoint_ns]&&(c=te(r,{checkpoint_id:r.configurable[ae][r.configurable?.checkpoint_ns]}));let l=hh(r.configurable?.checkpoint_ns),u;t.checkpointer?c.configurable?.checkpoint_id?u=await t.checkpointer.getTuple(c):r.configurable?.__pregel_replay_state?(u=await r.configurable[In].getCheckpoint(r.configurable?.checkpoint_ns??"",t.checkpointer,c),r.configurable&&delete r.configurable[Ft]):u=await t.checkpointer.getTuple(c):u=void 0;let h=u!==void 0;u||(u={config:r,checkpoint:qt(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]}),c={...r,...u.config,configurable:{checkpoint_ns:"",...r.configurable,...u.config.configurable}};let p=u.parentConfig,f=je(u.checkpoint),m={...u.metadata},d=u.pendingWrites??[],_=r.configurable?.checkpoint_ns,g=r.configurable?.[ae];typeof _=="string"&&_!==""&&typeof g=="object"&&g!==null&&_ in g&&d.length>0&&(d=d.filter(([,x])=>x!==he));let y=!1,S=c.configurable?.thread_id,w=c.configurable?.checkpoint_ns??"";t.checkpointer&&o&&typeof S=="string"&&(y=(await t.checkpointer.getTuple({configurable:{thread_id:S,checkpoint_ns:w}}))?.config.configurable?.checkpoint_id===o&&m.source!=="update"&&m.source!=="fork");let C=await vr(t.channelSpecs,f,{saver:t.checkpointer,config:c}),T=(m.step??0)+1,k=T+(r.recursionLimit??Em)+1,b={...f.channel_versions},I=t.store?new hs(t.store):void 0;return I&&await I.start(),new fh({input:t.input,config:r,checkpointer:t.checkpointer,checkpoint:f,checkpointMetadata:m,checkpointConfig:c,prevCheckpointConfig:p,checkpointNamespace:l,channels:C,isNested:a,resumeAtHead:y,manager:t.manager,skipDoneTasks:s,step:T,stop:k,checkpointPreviousVersions:b,checkpointPendingWrites:d,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:n,store:I,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes,hasPersistedParent:h})}_checkpointerPutAfterPrevious(t){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(t,r){let n=r;if(n.length===0)return;n.every(([c])=>c in ln)&&(n=Array.from(new Map(n.map(c=>[c[0],c])).values()));let s=!1;for(let c in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,c)&&this.channels[c].lc_graph_name==="UntrackedValue"){s=!0;break}let i=n;s&&(i=n.filter(([c])=>{let l=this.channels[c];return!l||l.lc_graph_name!=="UntrackedValue"}).map(([c,l])=>c==="__pregel_tasks"&&ee(l)?[c,Qu(l,this.channels)]:[c,l])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(c=>c[0]!==t);for(let[c,l]of i)this.checkpointPendingWrites.push([t,c,l]);for(let[c,l]of i){let u=this.channels[c];u!=null&&Te(u)&&uh(l)}let o=te(this.checkpointConfig,{[ve]:this.config.configurable?.checkpoint_ns??"",[kt]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(o,i,t)),this.tasks&&this._outputWrites(t,n),!r.length||!this.cache||!this.tasks)return;let a=this.tasks[t];a==null||a.cache_key==null||r[0][0]==="__error__"||r[0][0]==="__interrupt__"||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(t,r,n=!1){let s=this.tasks[t];if(s!==void 0){if(s.config!==void 0&&(s.config.tags??[]).includes("langsmith:hidden"))return;if(r.length>0)if(r[0][0]==="__interrupt__"){if(s.path?.[0]==="__pregel_push"&&s.path?.[s.path.length-1]===!0)return;let i=r.filter(o=>o[0]===L).flatMap(o=>o[1]);this._emit([["updates",{[L]:i}],["values",{[L]:i}]])}else r[0][0]!=="__error__"&&this._emit(It(tt(Bu(this.outputKeys,[[s,r]],n),"updates")));n||this._emit(It(tt(eh([[s,r]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let t=[],r=([o,a])=>`ns:${o.join(",")}|key:${a}`,n=[],s={};for(let o of Object.values(this.tasks))o.cache_key!=null&&!o.writes.length&&(n.push([o.cache_key.ns,o.cache_key.key]),s[r([o.cache_key.ns,o.cache_key.key])]=o);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:o,value:a}of i){let c=s[r(o)];c!=null&&(c.writes.push(...a),t.push({task:c,result:a}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:r=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Fs,Ho].includes(this.input))await this._first(r);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new it;if(Object.values(this.tasks).every(s=>s.writes.length>0)){let s=Object.values(this.tasks),i=s.flatMap(a=>a.writes);this.updatedChannels=de(this.checkpoint,this.channels,s,this.checkpointerGetNextVersion,this.triggerToNodes);for(let[a,c]of i){let l=this.channels[a];l!=null&&Te(l)&&Ut(c)&&this._deltaChannelsWithOverwrite.add(a)}let o=await Ve(tt(Ps(this.outputKeys,i,this.channels),"values"));if(this._exitDeltaWrites!==void 0)for(let[a,c,l]of this.checkpointPendingWrites){let u=this.channels[c];u!=null&&Te(u)&&this._exitDeltaWrites.push([this.step,a,c,l])}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),this.durability==="sync"&&await this._awaitCheckpointerPromises(),this._emitValuesWithCheckpointMeta(o),gn(this.checkpoint,this.interruptAfter,s))throw this.status="interrupt_after",new it;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[Ft]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;this.tasks=Nt(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});let n=Object.values(this.tasks);if(this.checkpointer&&(this.stream.modes.has("checkpoints")||this.stream.modes.has("debug"))&&this._emit(await Ve(tt(th(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,n,this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),n.length===0)return this.status="done",!1;if(this.control!=null&&this.control.drainRequested)return this.status="draining",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[s,i,o]of this.checkpointPendingWrites){if(i==="__error__"||i==="__error_source_node__"||i==="__interrupt__"||i==="__resume__")continue;let a=n.find(c=>c.id===s);a&&a.writes.push([i,o])}this._resumeErrorHandlersIfApplicable(),n=Object.values(this.tasks);for(let s of n)s.writes.length>0&&this._outputWrites(s.id,s.writes,!0)}if(n.every(s=>s.writes.length>0))return this.tick({inputKeys:r});if(gn(this.checkpoint,this.interruptBefore,n))throw this.status="interrupt_before",new it;if(this.stream.modes.has("tasks")||this.stream.modes.has("debug")){let s=await Ve(tt($s(n),"tasks"));this._emit(s)}return!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(n=>!n.includes(":")))&&(await this._putExitDeltaWrites(),this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let r=this._suppressInterrupt(t);return(r||t===void 0)&&(this.output=Le(this.channels,this.outputKeys)),r&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(n=>n.writes.length>0)&&(this.updatedChannels=de(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(It(tt(Ps(this.outputKeys,Object.values(this.tasks).flatMap(n=>n.writes),this.channels),"values")))),ot(t)&&!t.interrupts.length&&this._emit([["updates",{[L]:[]}],["values",{[L]:[]}]],this.#e())),r}async acceptPush(t,r,n){if(this.interruptAfter?.length>0&&gn(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}let s=Ds([pe,t.path??[],r,t.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.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&&gn(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}(this.stream.modes.has("tasks")||this.stream.modes.has("debug"))&&this._emit(It(tt($s([s]),"tasks"))),this.debug&&wn(this.step,[s]),this.tasks[s.id]=s,this.skipDoneTasks&&this._matchWrites({[s.id]:s});let i=await this._matchCachedWrites();for(let{task:o}of i)this._outputWrites(o.id,o.writes,!0);return s}getErrorHandlerNode(t){return this.nodes[t]?.errorHandlerNode}isErrorHandlerNode(t){return this.nodes[t]?.isErrorHandler===!0}scheduleErrorHandler(t,r){let n=this.getErrorHandlerNode(String(t.name));if(!n)return;let s=Xu(t,n,r,this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??this.config,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(s!==void 0)return this.tasks[s.id]=s,this._emit(It(tt($s([s]),"tasks"))),this.debug&&wn(this.step,[s]),s}_resumeErrorHandlersIfApplicable(){let t=new Map;for(let[r,n]of this.checkpointPendingWrites){if(n!=="__error_source_node__")continue;let s=this.checkpointPendingWrites.find(([a,c])=>a===r&&c==="__error__");if(s===void 0)continue;let i=s[2],o=new Error(i?.message??String(i));i?.name&&(o.name=i.name),t.set(r,o)}for(let[r,n]of t){let s=this.tasks[r];s!==void 0&&this.getErrorHandlerNode(String(s.name))&&(s.writes.length===0&&s.writes.push([vt,{message:n.message,name:n.name}]),this.scheduleErrorHandler(s,n))}}_suppressInterrupt(t){return ot(t)&&!this.isNested}async _first(t){let{configurable:r}=this.config,n=r?.[ue];if(n&&n.nullResume!==void 0&&this.putWrites(fe,[[he,n.nullResume]]),ne(this.input)){let l=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Ts)&&(this.config.configurable??={},this.config.configurable[Lt]=this.input.resume),l&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");let u={};for(let[h,p,f]of Hu(this.input,this.checkpointPendingWrites))u[h]??=[],u[h].push([p,f]);if(Object.keys(u).length===0)throw new Vn("Received empty Command input");for(let[h,p]of Object.entries(u))this.putWrites(h,p)}let s=(this.checkpointPendingWrites??[]).filter(l=>l[0]===fe).map(l=>l.slice(1));s.length>0&&de(this.checkpoint,this.channels,[{name:We,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=ne(this.input),o=i&&s.length>0,a=this.isReplaying&&(this.isNested&&r?.checkpoint_ns!==void 0&&r?.checkpoint_ns!==""&&r?.checkpoint_map!==void 0&&r.checkpoint_ns in r.checkpoint_map||!(i&&this.input.resume!=null||r?.__pregel_resuming===!0||this.resumeAtHead));a&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(l=>l[1]!==he));let c=this.isResuming;if(c||o){let l={...this.checkpoint.versions_seen[L]};for(let h in this.channels)Object.prototype.hasOwnProperty.call(this.channels,h)&&this.checkpoint.channel_versions[h]!==void 0&&(l[h]=this.checkpoint.channel_versions[h]);this.checkpoint.versions_seen[L]=l,a&&this.checkpointMetadata.source!=="update"&&this.checkpointMetadata.source!=="fork"&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(h=>h[1]!==L),await this._putCheckpoint({source:"fork"}));let u=await Ve(tt(Ps(this.outputKeys,!0,this.channels),"values"));c?this.input=Ho:o&&(await this._putCheckpoint({source:"input"}),this.input=Fs),this._emitValuesWithCheckpointMeta(u)}else{let l=await Ve(Ns(t,this.input));if(l.length>0){let u=Nt(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=de(this.checkpoint,this.channels,Object.values(u).concat([{name:We,writes:l,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);let h=l.filter(([p])=>{let f=this.channels[p];return f!=null&&Te(f)});for(let[p,f]of h)Ut(f)&&this._deltaChannelsWithOverwrite.add(p);if(h.length>0)if(this._exitDeltaWrites!==void 0)for(let[p,f]of h)this._exitDeltaWrites.push([this.step,fe,p,f]);else this.checkpointer!=null&&this.putWrites(fe,h);await this._putCheckpoint({source:"input"}),this.input=Fs}else if("__pregel_resuming"in(this.config.configurable??{}))this.input=Fs;else throw new Vn(`Received no input writes for ${JSON.stringify(t,null,2)}`)}if(!this.isNested){let l;if(a){let u=this.checkpoint.id;(this.checkpointMetadata.source==="update"||this.checkpointMetadata.source==="fork")&&this.prevCheckpointConfig&&(u=this.prevCheckpointConfig.configurable?.checkpoint_id??u),l=new lh(u)}this.config=te(this.config,{[Ft]:this.isResuming,[In]:l})}}#e(){let t=this.checkpointNamespace;if(!(t.length===0||t.length===1&&t[0]==="")||this.config.configurable?.__pregel_stream===void 0)return t;let r=Cm(this.config.configurable?.[ae]);return r.length>0?r:t}_emit(t,r=this.checkpointNamespace){for(let[n,s]of t)if(this.stream.modes.has(n)&&this.stream.push([r,n,s]),(n==="checkpoints"||n==="tasks")&&this.stream.modes.has("debug")){let i=n==="checkpoints"?this.step-1:this.step,o=new Date().toISOString(),a=n==="checkpoints"?"checkpoint":typeof s=="object"&&s!=null&&"result"in s?"task_result":"task";this.stream.push([r,"debug",{step:i,type:a,timestamp:o,payload:s}])}}_currentCheckpointMeta(){if(!this.checkpointMetadata||!this.checkpoint?.id)return;let t=this.prevCheckpointConfig?.configurable?.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...t?{parent_id:t}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(t){let r=this._currentCheckpointMeta();for(let[n,s]of t)n==="values"&&r?.checkpoint!=null&&!this.stream.modes.has("checkpoints")&&this.stream.push([this.checkpointNamespace,"checkpoints",r.checkpoint]),this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,s])}_putCheckpoint(t){let r=this.checkpointMetadata===t,n=this.checkpointer!=null&&(this.durability!=="exit"||r),s=c=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=te(this.checkpointConfig,{[ve]:this.config.configurable?.checkpoint_ns??""});let l={...this.checkpoint.channel_versions},u=Ir(this.checkpointPreviousVersions,l);this.checkpointPreviousVersions=l,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:je(c),metadata:{...this.checkpointMetadata},newVersions:u}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}},i;if(r)i={...this.checkpointMetadata.counters_since_delta_snapshot??{}};else{let c=this.checkpointMetadata.counters_since_delta_snapshot??{};i={};let l=this.updatedChannels??new Set;for(let u in this.channels){if(!Object.prototype.hasOwnProperty.call(this.channels,u)||!Te(this.channels[u]))continue;let[h,p]=c[u]??[0,0];i[u]=[l.has(u)?h+1:h,p+1]}this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}}let o=n?ms(this.channels,i):new Set;if(n)for(let c of this._deltaChannelsWithOverwrite)o.add(c);this.checkpoint=De(this.checkpoint,n?this.channels:void 0,this.step,{id:r?this.checkpoint.id:void 0,channelsToSnapshot:o,updatedChannels:this.updatedChannels,getNextVersion:n?c=>this.checkpointerGetNextVersion(c):void 0});for(let c of o)i[c]=[0,0],this._deltaChannelsWithOverwrite.delete(c);let a={};for(let c in i){if(!Object.prototype.hasOwnProperty.call(i,c))continue;let[l,u]=i[c];(l!==0||u!==0)&&(a[c]=[l,u])}Object.keys(a).length>0?this.checkpointMetadata.counters_since_delta_snapshot=a:delete this.checkpointMetadata.counters_since_delta_snapshot,n&&s(this.checkpoint),r||(this.step+=1)}async _putExitDeltaWrites(){if(this._exitDeltaWrites===void 0||this._exitDeltaWrites.length===0||this.checkpointer==null||this._initialCheckpointConfig===void 0)return;let t=this.checkpointMetadata.counters_since_delta_snapshot??{},r=ms(this.channels,t);for(let c of this._deltaChannelsWithOverwrite)r.add(c);let n=this._exitDeltaWrites.filter(([,,c])=>!r.has(c));if(n.length===0)return;let s;if(this._hasPersistedParent)s=this._initialCheckpointConfig;else{let c=qt();c.id=this.checkpointIdSaved??c.id,c.ts=new Date().toISOString();let l=te(this._initialCheckpointConfig,{[kt]:void 0});s=te(this._initialCheckpointConfig,{[kt]:c.id}),this._trackCheckpointerPromise(this.checkpointer.put(l,c,{source:"loop",step:-2,parents:{}},{})),this.checkpointConfig=s}let i=te(s,{[ve]:this.config.configurable?.checkpoint_ns??"",[kt]:s.configurable?.[kt]}),o=new Map,a=[];for(let[c,l,u,h]of n){let p=`${c}\0${l}`,f=o.get(p);f===void 0&&(f=[],o.set(p,f),a.push({key:p,step:c,tid:l})),f.push([u,h])}for(let{key:c,step:l,tid:u}of a){let h=fo(l,u);this._trackCheckpointerPromise(this.checkpointer.putWrites(i,o.get(c),h))}}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let t=te(this.checkpointConfig,{[ve]:this.config.configurable?.checkpoint_ns??"",[kt]:this.checkpoint.id}),r={};for(let[n,s,i]of this.checkpointPendingWrites)r[n]??=[],r[n].push([s,i]);for(let[n,s]of Object.entries(r))this._trackCheckpointerPromise(this.checkpointer.putWrites(t,s,n))}_matchWrites(t){for(let[r,n,s]of this.checkpointPendingWrites){if(n==="__error__"||n==="__interrupt__"||n==="__resume__")continue;let i=Object.values(t).find(o=>o.id===r);i&&i.writes.push([n,s])}for(let r of Object.values(t))r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}};function Tm(e){return Oe(e?.message)}function mh(e,t,r){if(!e)return;let n=e.langgraph_checkpoint_ns,s=e.checkpoint_ns,i=n??s;if(i)return[i.split("|"),{tags:t,name:r,...e}]}var dh=class extends yt{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,r,n=!1){if(n&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let s=t.id;r!=null&&(ma(t)?s??=`run-${r}-tool-${t.tool_call_id}`:((s==null||s===`run-${r}`)&&(s=this.stableMessageIdMap[r]??s??`run-${r}`),this.stableMessageIdMap[r]??=s)),s!==t.id&&(t.id=s,t.lc_kwargs.id=s),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,s,i,o,a){o&&(!i||!i.includes("langsmith:nostream")&&!i.includes("nostream"))&&(this.metadatas[r]=mh(o,i,a))}handleLLMNewToken(e,t,r,n,s,i){let o=i?.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(Tm(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new Zt({content:e}),r))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let r=e.generations?.[0]?.[0];Oe(r?.message)&&this._emit(this.metadatas[t],r?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,n,s,i,o,a){if(i!==void 0&&a===i.langgraph_node&&(s===void 0||!s.includes("langsmith:hidden"))&&(this.metadatas[r]=mh(i,s,a),typeof t=="object")){for(let c of Object.values(t))if((Oe(c)||Ks(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let l of c)(Oe(l)||Ks(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){let r=this.metadatas[t];if(delete this.metadatas[t],r!==void 0){if(Oe(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(let n of e)Oe(n)&&this._emit(r,n,t,!0);else if(e!=null&&typeof e=="object"){for(let n of Object.values(e))if(Oe(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(let s of n)Oe(s)&&this._emit(r,s,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};function gh(e){if("response_metadata"in e&&typeof e.response_metadata=="object"&&e.response_metadata!=null)return e.response_metadata}function _h(e){if("usage_metadata"in e&&typeof e.usage_metadata=="object"&&e.usage_metadata!=null)return e.usage_metadata}function Im(e){switch(e.type){case"text":return{type:"text",text:""};case"reasoning":return{type:"reasoning",reasoning:""};case"tool_call":case"tool_call_chunk":return{type:"tool_call_chunk",...e.id!=null?{id:e.id}:{},...e.name!=null?{name:e.name}:{},args:""};default:return e}}function Am(e){switch(e.type){case"text":{let t=typeof e.text=="string"?e.text:"";return t.length>0?{event:"content-block-delta",index:typeof e.index=="number"?e.index:0,delta:{type:"text-delta",text:t}}:void 0}case"reasoning":{let t=typeof e.reasoning=="string"?e.reasoning:"";return t.length>0?{event:"content-block-delta",index:typeof e.index=="number"?e.index:0,delta:{type:"reasoning-delta",reasoning:t}}:void 0}case"tool_call_chunk":return{event:"content-block-delta",index:typeof e.index=="number"?e.index:0,delta:{type:"block-delta",fields:{...e,type:"tool_call_chunk"}}};default:return}}var yh=class extends yt{name="StreamProtocolMessagesHandler";streamFn;metadatas={};seen={};streamedRunIds=new Set;stableMessageIdMap={};lc_prefer_chat_model_stream_events=!0;awaitHandlers=!0;constructor(e){super(),this.streamFn=e}normalizeMessageId(e,t){let r=e.id;return t!=null&&(Dt.isInstance(e)?r??=`run-${t}-tool-${e.tool_call_id}`:((r==null||r===`run-${t}`)&&(r=this.stableMessageIdMap[t]??r??`run-${t}`),this.stableMessageIdMap[t]??=r)),r!==e.id&&(e.id=r,e.lc_kwargs.id=r),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,r){let n=r!=null?{...e[1],run_id:r}:e[1];this.streamFn([e[0],"messages",[t,n]])}emitFinalMessage(e,t,r,n=!1){let s=t.id??(r!=null?this.stableMessageIdMap[r]:void 0);if(n&&s!=null&&this.seen[s]!==void 0)return;let i=this.normalizeMessageId(t,r),o=t.type==="human"?"human":t.type==="system"?"system":t.type==="tool"?"tool":"ai",a=o==="tool"&&Dt.isInstance(t)?t.tool_call_id:void 0;this.emit(e,{event:"message-start",...i!=null?{id:i}:{},...o!=="ai"?{role:o}:{},...typeof a=="string"?{tool_call_id:a}:{}},r),(Array.isArray(t.content)?t.content:typeof t.content=="string"&&t.content.length>0?[{type:"text",text:t.content}]:[]).forEach((c,l)=>{let u=typeof c.index=="number"?c.index:l;this.emit(e,{event:"content-block-start",index:u,content:Im(c)},r);let h=Am({...c,index:u});h!=null&&this.emit(e,h,r),this.emit(e,{event:"content-block-finish",index:u,content:c},r)}),this.emit(e,{event:"message-finish",..._h(t)!=null?{usage:_h(t)}:{},...gh(t)!=null?{responseMetadata:gh(t)}:{}},r)}handleChatModelStart(e,t,r,n,s,i,o,a){o&&(!i||!i.includes("langsmith:nostream")&&!i.includes("nostream"))&&(this.metadatas[r]=[o.langgraph_checkpoint_ns.split("|"),{tags:i,name:a,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,t){let r=this.metadatas[t];if(r===void 0)return;let n=e;if(e.event==="message-start"){this.streamedRunIds.add(t);let s=e.id??`run-${t}`;this.seen[s]=!0,this.stableMessageIdMap[t]??=s,e.id==null&&(n={...e,id:s})}this.emit(r,n,t)}handleLLMEnd(e,t){let r=this.metadatas[t];if(r===void 0)return;let n=e.generations?.[0]?.[0],s=X.isInstance(n?.message)?n.message:void 0;if(s!=null)if(this.streamedRunIds.has(t)){let i=this.normalizeMessageId(s,t);i!=null&&(this.seen[i]=s)}else this.emitFinalMessage(r,s,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleChainStart(e,t,r,n,s,i,o,a){if(i!==void 0&&a===i.langgraph_node&&(s===void 0||!s.includes("langsmith:hidden"))&&(this.metadatas[r]=[i.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...i}],typeof t=="object")){for(let c of Object.values(t))if((X.isInstance(c)||Ws.isInstance(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let l of c)(X.isInstance(l)||Ws.isInstance(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){let r=this.metadatas[t];if(delete this.metadatas[t],r===void 0)return;let n=s=>{X.isInstance(s)&&!Dt.isInstance(s)&&this.emitFinalMessage(r,s,t,!0)};if(X.isInstance(e))n(e);else if(Array.isArray(e))for(let s of e)n(s);else if(e!=null&&typeof e=="object")for(let s of Object.values(e))if(Array.isArray(s))for(let i of s)n(i);else n(s);delete this.stableMessageIdMap[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}};var Om=class{active=!0;lastProgress=Date.now();refreshOn;constructor(e){this.refreshOn=e}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn==="auto"&&(this.lastProgress=Date.now())}close(){this.active=!1}},Nm=class extends yt{name="IdleProgressCallbackHandler";awaitHandlers=!1;#e;constructor(e){super(),this.#e=e}#t=()=>{this.#e.autoTouch()};handleLLMStart=this.#t;handleChatModelStart=this.#t;handleLLMNewToken=this.#t;handleLLMEnd=this.#t;handleLLMError=this.#t;handleChainStart=this.#t;handleChainEnd=this.#t;handleChainError=this.#t;handleToolStart=this.#t;handleToolEnd=this.#t;handleToolError=this.#t;handleText=this.#t;handleRetrieverStart=this.#t;handleRetrieverEnd=this.#t;handleRetrieverError=this.#t;handleCustomEvent=this.#t};function Pm(e,t,r,n){let s=e.configurable??{},i={},o=s[oe];typeof o=="function"&&(i[oe]=l=>{if(t.active)return l&&l.length&&t.autoTouch(),o(l)});let a=s[Ke];typeof a=="function"&&(i[Ke]=(...l)=>{if(!t.active)throw new Error(`Node "${n}" attempt was cancelled after its timeout fired`);return t.autoTouch(),a(...l)});let c={...Object.keys(i).length>0?te(e,i):e};if(c.heartbeat=()=>{r.idleTimeout!==void 0&&t.touch()},typeof c.writer=="function"){let l=c.writer;c.writer=(u=>{if(t.active)return t.autoTouch(),l(u)})}if((r.refreshOn??"auto")==="auto"&&r.idleTimeout!==void 0){let l=new Nm(t),u=c.callbacks;if(u===void 0)c.callbacks=[l];else if(Array.isArray(u))c.callbacks=[...u,l];else{let h=u.copy();h.addHandler(l,!0),c.callbacks=h}}return c}async function wh(e,t,r,n){let s=new Om(r.refreshOn??"auto"),i=new AbortController,{signal:o,dispose:a}=Ot(t.signal,i.signal),c=Pm({...t,signal:o},s,r,String(e.name)),l=Date.now(),u=n(c).then(g=>({type:"ok",value:g}),g=>({type:"err",error:g})),h,p,f=()=>{h!==void 0&&clearTimeout(h),p!==void 0&&clearTimeout(p)},m=new Promise(g=>{if(r.runTimeout!==void 0&&(h=setTimeout(()=>g({type:"timeout",kind:"run"}),r.runTimeout)),r.idleTimeout!==void 0){let y=r.idleTimeout,S=()=>{let w=s.lastProgress+y-Date.now();w<=0?g({type:"timeout",kind:"idle"}):p=setTimeout(S,w)};p=setTimeout(S,y)}}),d;try{d=await Promise.race([u,m])}finally{f()}if(d.type!=="timeout"){let g=Date.now();r.runTimeout!==void 0&&g-l>=r.runTimeout?d={type:"timeout",kind:"run"}:r.idleTimeout!==void 0&&g-s.lastProgress>=r.idleTimeout&&(d={type:"timeout",kind:"idle"})}if(d.type==="ok")return a?.(),d.value;if(d.type==="err")throw a?.(),d.error;let _=Date.now()-l;throw s.close(),e.writes.splice(0,e.writes.length),i.abort(),a?.(),new $n({node:String(e.name),elapsed:_,kind:d.kind,runTimeout:r.runTimeout,idleTimeout:r.idleTimeout})}var Rm=[400,401,402,403,404,405,406,407,409],Mm=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;let t=e?.response?.status??e?.status;return!(t&&Rm.includes(+t)||e?.error?.code==="insufficient_quota")};async function Ls(e,t,r,n){let s=e.retry_policy??t,i=0,o,a,c=e.config??{};r&&(c=te(c,r)),c={...c,signal:n};let l=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:l});!n?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{e.timeout!==void 0?a=await wh(e,c,e.timeout,u=>e.proc.invoke(e.input,u)):a=await e.proc.invoke(e.input,c);break}catch(u){if(o=u,o.pregelTaskId=e.id,oi(o)){let d=c?.configurable?.checkpoint_ns,_=o.command;if(_.graph===d){for(let g of e.writers)await g.invoke(_,c);o=void 0;break}else if(_.graph===_e.PARENT){let g=ku(d);o.command=new _e({...o.command,graph:g})}}if(xt(o)||s===void 0||(i+=1,i>=(s.maxAttempts??3))||!(s.retryOn??Mm)(o))break;let h=s.initialInterval??500,p=Math.min(s.maxInterval??128e3,h*(s.backoffFactor??2)**(i-1)),f=s.jitter??!0?p+Math.random()*1e3:p;await new Promise(d=>setTimeout(d,f));let m=o.name??o.constructor.unminifiable_name??o.constructor.name;(s?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${f.toFixed(2)}ms (attempt ${i}) after ${m}: ${o}`),c=te(c,{[Ft]:!0}),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:i+1,nodeFirstAttemptTime:l})}}return{task:e,result:a,error:o,signalAborted:n?.aborted}}var Bo=Symbol.for("promiseAdded");function jm(){let e={next:()=>{},wait:Promise.resolve(Bo)};function t(r){e.next=()=>{e.wait=new Promise(t),r(Bo)}}return e.wait=new Promise(t),e}var bh=class{nodeFinished;loop;handledExceptions=new WeakSet;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:s}=e,i=new Set,o,a=new AbortController,c=a.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks),h=u.filter(d=>d.writes.length===0),{signals:p,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),m=this._executeTasksWithRetry(h,{signals:p,retryPolicy:r,maxConcurrency:s});for await(let{task:d,error:_,signalAborted:g}of m)this._commit(d,_),!(_!==void 0&&this.handledExceptions.has(_))&&(ot(_)||xt(_)&&!ot(o)?o=_:_&&(i.size===0||!g)&&(a.abort(),i.add(_)));if(f?.(),n?.(this.loop.step,u.map(d=>d.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(ot(o)||Rn(o)||xt(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:r}){let n=this.loop.config.configurable?.__pregel_abort_signals??{},s=n.externalAbortSignal??r,i=t??n.timeoutAbortSignal,{signal:o,dispose:a}=Ot(s,i,e),c={externalAbortSignal:s,timeoutAbortSignal:i,composedAbortSignal:o};return this.loop.config=te(this.loop.config,{[bc]:c}),{signals:c,disposeCombinedSignal:a}}async*_executeTasksWithRetry(e,t){let{retryPolicy:r,maxConcurrency:n,signals:s}=t??{},i=jm(),o={},a={executingTasksMap:o,barrier:i,retryPolicy:r,scheduleTask:async(p,f,m)=>this.loop.acceptPush(p,f,m)};if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,l,u=Ot(s?.externalAbortSignal,s?.timeoutAbortSignal),h=u.signal?new Promise((p,f)=>{l=()=>f(new Error("Abort")),u.signal?.addEventListener("abort",l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(n??e.length)&&c<e.length;c+=1){let _=e[c];o[_.id]=Ls(_,r,{[Ke]:Go?.bind(a,this,_)},s?.composedAbortSignal).catch(g=>({task:_,error:g,signalAborted:s?.composedAbortSignal?.aborted}))}let p=await Promise.race([...Object.values(o),...h?[h]:[],i.wait]);if(p===Bo)continue;let f=p,{task:m,error:d}=f;if(d!==void 0&&!xt(d)&&!this.loop.isErrorHandlerNode(String(m.name))&&this.loop.getErrorHandlerNode(String(m.name))!==void 0){let _=this.loop.scheduleErrorHandler(m,d);_!==void 0&&(o[_.id]=Ls(_,r,{[Ke]:Go?.bind(a,this,_)},s?.composedAbortSignal).catch(g=>({task:_,error:g,signalAborted:s?.composedAbortSignal?.aborted})),i.next())}yield f,l!=null&&(u.signal?.removeEventListener("abort",l),u.dispose?.()),delete o[p.task.id]}}_shouldRouteToErrorHandler(e){let t=String(e.name);return this.loop.isErrorHandlerNode(t)?!1:this.loop.getErrorHandlerNode(t)!==void 0}_commit(e,t){if(t!==void 0)if(ot(t)){if(t.interrupts.length){let r=t.interrupts.map(s=>[L,s]),n=e.writes.filter(s=>s[0]===he);n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else Rn(t)?e.writes.length&&this.loop.putWrites(e.id,e.writes):xt(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):(e.writes.push([vt,{message:t.message,name:t.name}]),this._shouldRouteToErrorHandler(e)&&(e.writes.push([Dr,String(e.name)]),this.handledExceptions.add(t)),this.loop.putWrites(e.id,e.writes));else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes("langsmith:hidden"))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([Fr,null]),this.loop.putWrites(e.id,e.writes)}};async function Go(e,t,r,n,s,i={}){let o=t.config?.configurable?.[ue];if(!o)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let a=o.callCounter;o.callCounter+=1;let c=new Wu({func:r,name:n,input:s,cache:i.cache,retry:i.retry,timeout:i.timeout,callbacks:i.callbacks}),l=await this.scheduleTask(t,a,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let h=l.writes.filter(([f])=>f===Et),p=l.writes.filter(([f])=>f===vt);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(p.length>0){if(p.length===1){let f=p[0][1],m=f instanceof Error?f:new Error(String(f));return Promise.reject(m)}throw new Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let h=Ls(l,i.retry,{[Ke]:Go.bind(this,e,l)});return this.executingTasksMap[l.id]=h,this.barrier.next(),h.then(({result:p,error:f})=>f?Promise.reject(f):p)}}var ht=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function vh({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:s,interruptAfterNodes:i,interruptBeforeNodes:o}){if(!t)throw new ht("Channels not provided");let a=new Set,c=new Set;for(let[l,u]of Object.entries(e)){if(l==="__interrupt__")throw new ht(`"Node name ${L} is reserved"`);if(u.constructor===Fe)u.triggers.forEach(h=>a.add(h));else throw new ht(`Invalid node type ${typeof u}, expected PregelNode`)}for(let l of a)if(!(l in t))throw new ht(`Subscribed channel '${String(l)}' not in channels`);if(Array.isArray(r)){if(r.every(l=>!a.has(l)))throw new ht(`None of the input channels ${r} are subscribed to by any node`)}else if(!a.has(r))throw new ht(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach(l=>c.add(l)):c.add(n),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach(l=>c.add(l));for(let l of c)if(!(l in t))throw new ht(`Output channel '${String(l)}' not in channels`);if(i&&i!=="*"){for(let l of i)if(!(l in e))throw new ht(`Node ${String(l)} not in nodes`)}if(o&&o!=="*"){for(let l of o)if(!(l in e))throw new ht(`Node ${String(l)} not in nodes`)}}function Wo(e,t){if(Array.isArray(e)){for(let r of e)if(!(r in t))throw new Error(`Key ${String(r)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}function Dm(e){return Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1])}var Ko=class Sh extends J{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let r=new Sh({unique:this.unique,accumulate:this.accumulate});return typeof t>"u"?r:Dm(t)?(r.seen=new Set(t[0]),r.values=[...t[1]],r):(r.values=[...t],this.unique&&(r.seen=new Set(r.values)),r)}update(t){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);let n=t.flat();if(n.length>0)if(this.unique)for(let s of n)this.seen.has(s)||(r=!0,this.seen.add(s),this.values.push(s));else r=!0,this.values.push(...n);return r}get(){if(this.values.length===0)throw new $;return this.values}checkpoint(){return this.unique?[[...this.seen],[...this.values]]:[...this.values]}isAvailable(){return this.values.length!==0}};function $m(e){let t=new TextEncoder;return new ReadableStream({async start(r){try{for await(let n of e){let s=n.params.namespace,i=s.length?`${n.method}|${s.join("|")}`:n.method;r.enqueue(t.encode(`event: ${i}
|
|
128
|
+
data: ${JSON.stringify(n.params.data??{})}
|
|
129
|
+
|
|
130
|
+
`))}}catch(n){r.enqueue(t.encode(`event: error
|
|
131
|
+
data: ${JSON.stringify({message:String(n)})}
|
|
132
|
+
|
|
133
|
+
`))}finally{r.close()}}})}var kh=class{static subscribeTo(e,t){let{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&r!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof e=="string"?r?s={[r]:e}:s=[e]:s=Object.fromEntries(e.map(i=>[i,i])),new Fe({channels:s,triggers:Array.isArray(e)?e:[e],tags:n})}static writeTo(e,t){let r=[];for(let n of e)r.push({channel:n,value:we,skipNone:!1});for(let[n,s]of Object.entries(t??{}))G.isRunnable(s)||typeof s=="function"?r.push({channel:n,value:we,skipNone:!0,mapper:Be(s)}):r.push({channel:n,value:s,skipNone:!1});return new q(r)}},Vm=class extends G{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Us=class extends Vm{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;streamTransformers;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,"__pregel_tasks"in this.channels&&"lc_graph_name"in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!=="Topic")throw new Error(`Channel '${qe}' is reserved and cannot be used in the graph.`);this.channels[qe]=new Ko({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}withConfig(e){let{streamTransformers:t,...r}=e,n=ke(this.config,r),s=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:n,streamTransformers:s})}validate(){vh({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let r of t.triggers)this.triggerToNodes[r]??=[],this.triggerToNodes[r].push(e);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(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[r,n]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(r))continue;let s=n.subgraphs?.length?n.subgraphs:[n.bound];for(let i of s){let o=Os(i);if(o!==void 0){if(r===e){yield[r,o];return}if(e===void 0&&(yield[r,o]),t){let a=e;e!==void 0&&(a=e.slice(r.length+1));for(let[c,l]of o.getSubgraphs(a,t))yield[`${r}|${c}`,l]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:n=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let s=await vr(this.channels,t.checkpoint,{saver:typeof this.checkpointer=="object"?this.checkpointer:void 0,config:t.config??e});if(t.pendingWrites?.length){let h=t.pendingWrites.filter(([p,f])=>p===fe).map(([p,f,m])=>[String(f),m]);h.length>0&&de(t.checkpoint,s,[{name:We,writes:h,triggers:[]}],void 0,this.triggerToNodes)}let i=Object.values(Nt(t.checkpoint,t.pendingWrites,this.nodes,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await Ve(this.getSubgraphsAsync()),a=t.config.configurable?.checkpoint_ns??"",c={};for(let h of i){let p=o.find(([m])=>m===h.name);if(!p)continue;let f=`${String(h.name)}:${h.id}`;if(a&&(f=`${a}|${f}`),r===void 0){let m={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:f}};c[h.id]=m}else{let m={configurable:{[Ee]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:f}},d=p[1];c[h.id]=await d.getState(m,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){let h=Object.fromEntries(i.map(f=>[f.id,f]));for(let[f,m,d]of t.pendingWrites)["__error__","__interrupt__",Gt].includes(m)||f in h&&h[f].writes.push([String(m),d]);let p=i.filter(f=>f.writes.length>0);p.length>0&&de(t.checkpoint,s,p,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});let u=i.filter(h=>h.writes.length===0).map(h=>h.name);return{values:Le(s,this.streamChannelsAsIs),next:u,tasks:Vo(i,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:At(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let r=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!r)throw new Bt("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_read===void 0&&e.configurable?.__pregel_checkpointer===void 0){let o=ys(n);for await(let[a,c]of this.getSubgraphsAsync(o,!0))if(a===o)return await c.getState(Jt(e,{[Ee]:r}),{subgraphs:t?.subgraphs})}let s=ke(this.config,e),i=await r.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:i,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let r=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!r)throw new Bt("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_checkpointer===void 0){let i=ys(n);for await(let[o,a]of this.getSubgraphsAsync(i,!0))if(o===i){yield*a.getStateHistory(Jt(e,{[Ee]:r}),t);return}}let s=ke(this.config,e,{configurable:{checkpoint_ns:n}});for await(let i of r.list(s,t))yield this._prepareStateSnapshot({config:i.config,saved:i})}async bulkUpdateState(e,t){let r=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!r)throw new Bt("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(o=>o.updates.length===0))throw new Error("No updates provided");let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_checkpointer===void 0){let o=ys(n);for await(let[,a]of this.getSubgraphsAsync(o,!0))return await a.bulkUpdateState(Jt(e,{[Ee]:r}),t);throw new Error(`Subgraph "${o}" not found`)}let s=async(o,a)=>{let c=this.config?ke(this.config,o):o,l=await r.getTuple(c),u=l!==void 0?je(l.checkpoint):qt(),h={...l?.checkpoint.channel_versions},p=l?.metadata?.step??-1,f=Jt(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),m=c.metadata??{};l?.config.configurable&&(f=Jt(c,l.config.configurable),m={...l.metadata,...m});let{values:d,asNode:_}=a[0];if(d==null&&_===void 0){if(a.length>1)throw new R("Cannot create empty checkpoint with multiple updates");return At(await r.put(f,De(u,void 0,p),{source:"update",step:p+1,parents:l?.metadata?.parents??{}},{}),l?l.metadata:void 0)}let g=await vr(this.channels,u,{saver:r,config:l?.config??f});if(d===null&&_==="__end__"){if(a.length>1)throw new R("Cannot apply multiple updates when clearing state");if(l){let k=Nt(u,l.pendingWrites||[],this.nodes,g,l.config,!0,{step:(l.metadata?.step??-1)+1,checkpointer:r,store:this.store}),b=(l.pendingWrites||[]).filter(I=>I[0]===fe).map(I=>I.slice(1));b.length>0&&de(u,g,[{name:We,writes:b,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[I,x,F]of l.pendingWrites||[])["__error__","__interrupt__",Gt].includes(x)||I in k&&k[I].writes.push([x,F]);de(u,g,Object.values(k),r.getNextVersion.bind(r),this.triggerToNodes)}return At(await r.put(f,De(u,g,p),{...m,source:"update",step:p+1,parents:l?.metadata?.parents??{}},Ir(h,u.channel_versions)),l?l.metadata:void 0)}if(_==="__copy__"){if(a.length>1)throw new R("Cannot copy checkpoint with multiple updates");if(l==null)throw new R("Cannot copy a non-existent checkpoint");let k=x=>!Array.isArray(x)||x.length===0?!1:x.every(F=>Array.isArray(F)&&F.length===2),b=De(u,void 0,p),I=await r.put(l.parentConfig??Jt(l.config,{checkpoint_id:void 0}),b,{source:"fork",step:p+1,parents:l.metadata?.parents??{}},{});if(k(d)){let x=Nt(b,l.pendingWrites,this.nodes,g,I,!1,{step:p+2}),F=Object.values(x).reduce((V,{name:B,id:be})=>(V[B]??=[],V[B].push({id:be}),V),{}),j=d.reduce((V,B)=>{let[be,rt]=B;V[rt]??=[];let E=V[rt].length,A=F[rt]?.[E]?.id;return V[rt].push({values:be,asNode:rt,taskId:A}),V},{});return s(At(I,l.metadata),Object.values(j).flat())}return At(I,l.metadata)}if(_==="__input__"){if(a.length>1)throw new R("Cannot apply multiple updates when updating as input");let k=await Ve(Ns(this.inputChannels,d));if(k.length===0)throw new R(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);de(u,g,[{name:We,writes:k,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let b=l?.metadata?.step!=null?l.metadata.step+1:-1,I=await r.put(f,De(u,g,b),{source:"input",step:b,parents:l?.metadata?.parents??{}},Ir(h,u.channel_versions));return await r.putWrites(I,k,ze(We,u.id)),At(I,l?l.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&l?.pendingWrites!==void 0&&l.pendingWrites.length>0){let k=Nt(u,l.pendingWrites,this.nodes,g,l.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(l.metadata?.step??-1)+1}),b=(l.pendingWrites??[]).filter(x=>x[0]===fe).map(x=>x.slice(1));b.length>0&&de(l.checkpoint,g,[{name:We,writes:b,triggers:[]}],void 0,this.triggerToNodes);for(let[x,F,j]of l.pendingWrites)["__error__","__interrupt__",Gt].includes(F)||k[x]===void 0||k[x].writes.push([F,j]);let I=Object.values(k).filter(x=>x.writes.length>0);I.length>0&&de(u,g,I,void 0,this.triggerToNodes)}let y=Object.values(u.versions_seen).map(k=>Object.values(k)).flat().find(k=>!!k),S=[];if(a.length===1){let{values:k,asNode:b,taskId:I}=a[0];if(b===void 0&&Object.keys(this.nodes).length===1)[b]=Object.keys(this.nodes);else if(b===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(b=this.inputChannels);else if(b===void 0){let x=Object.entries(u.versions_seen).map(([F,j])=>Object.values(j).map(V=>[V,F])).flat().filter(([F,j])=>j!==L).sort(([F],[j])=>ls(F,j));x&&(x.length===1?b=x[0][1]:x[x.length-1][0]!==x[x.length-2][0]&&(b=x[x.length-1][1]))}if(b===void 0)throw new R('Ambiguous update, specify "asNode"');S.push({values:k,asNode:b,taskId:I})}else for(let{asNode:k,values:b,taskId:I}of a){if(k==null)throw new R('"asNode" is required when applying multiple updates');S.push({values:b,asNode:k,taskId:I})}let w=[];for(let{asNode:k,values:b,taskId:I}of S){if(this.nodes[k]===void 0)throw new R(`Node "${k.toString()}" does not exist`);let x=this.nodes[k].getWriters();if(!x.length)throw new R(`No writers found for node "${k.toString()}"`);w.push({name:k,input:b,proc:x.length>1?$t.from(x,{omitSequenceTags:!0}):x[0],writes:[],triggers:[L],id:I??ze("__interrupt__",u.id),writers:[]})}for(let k of w)await k.proc.invoke(k.input,nt({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[oe]:b=>k.writes.push(...b),[le]:(b,I=!1)=>Ar(u,g,k,b,I)}}));for(let k of w){let b=k.writes.filter(I=>I[0]!==pe);l!==void 0&&b.length>0&&await r.putWrites(f,b,k.id)}de(u,g,w,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let C=Ir(h,u.channel_versions),T=await r.put(f,De(u,g,p+1),{source:"update",step:p+1,parents:l?.metadata?.parents??{}},C);for(let k of w){let b=k.writes.filter(I=>I[0]===pe);b.length>0&&await r.putWrites(T,b,k.id)}return At(T,l?l.metadata:void 0)},i=e;for(let{updates:o}of t)i=await s(i,o);return i}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){let{debug:t,streamMode:r,inputKeys:n,outputKeys:s,interruptAfter:i,interruptBefore:o,...a}=e,c=!0,l=t!==void 0?t:this.debug,u=s;u===void 0?u=this.streamChannelsAsIs:Wo(u,this.channels);let h=n;h===void 0?h=this.inputChannels:Wo(h,this.channels);let p=o??this.interruptBefore??[],f=i??this.interruptAfter??[],m;r!==void 0?(m=Array.isArray(r)?r:[r],c=typeof r=="string"):(e.configurable?.__pregel_task_id!==void 0?m=["values"]:m=this.streamMode,c=!0);let d;if(this.checkpointer===!1)d=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)d=e.configurable[Ee];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");d=this.checkpointer}let _=e.store??this.store,g=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let y=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),S=e.durability??y??e?.configurable?.__pregel_durability??"async";return[l,m,h,u,a,p,f,d,_,c,g,S]}async stream(e,t){let r=new AbortController,n=_s()?.configurable;n?.__pregel_read!==void 0&&t?.configurable?.__pregel_read===void 0&&(t={...t,configurable:{...n,...t?.configurable}});let s={recursionLimit:this.config?.recursionLimit,...t,signal:Ot(t?.signal,r.signal).signal},i=await super.stream(e,s);return new Vs(t?.encoding==="text/event-stream"?ah(i):i,r)}async#e(e,t){let{version:r,encoding:n,transformers:s,...i}=t,o={recursionLimit:this.config?.recursionLimit,...i,configurable:{...this.config?.configurable,...i?.configurable},version:r,streamMode:_o,subgraphs:!0,encoding:void 0},a=this.stream(e,o),c=Io({[Symbol.asyncIterator]:async function*(){let l=await a;for await(let u of l)yield u}},[...this.streamTransformers??[],...s??[]]);if(n==="text/event-stream"){let l=new AbortController;return l.signal.addEventListener("abort",()=>c.abort(l.signal.reason),{once:!0}),new Vs($m(c),l)}return c}streamEvents(e,t,r){if(t.version==="v3")return this.#e(e,t);let n=new AbortController,s={recursionLimit:this.config?.recursionLimit,...t,signal:Ot(t?.signal,n.signal).signal};return new Vs(super.streamEvents(e,s,r),n)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let r="version"in(t??{})?void 0:t?.encoding??void 0,n=t?.subgraphs,s=t?.version==="v3",i=Sr(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');let o=await this._validateInput(e),{runId:a,...c}=i,[l,u,,h,p,f,m,d,_,g,y,S]=this._defaults(c);p.metadata={ls_integration:"langgraph",...p.metadata},typeof p.context<"u"?p.context=await this._validateContext(p.context):p.configurable=await this._validateContext(p.configurable);let w=new Lo({modes:new Set(u)});if(this.checkpointer===!0){p.configurable??={};let j=p.configurable.checkpoint_ns??"";p.configurable[ve]=j.split("|").map(V=>V.split(":")[0]).join("|")}if(u.includes("messages")){let j=s?new yh(B=>w.push(B)):new dh(B=>w.push(B)),{callbacks:V}=p;if(V===void 0)p.callbacks=[j];else if(Array.isArray(V))p.callbacks=V.concat(j);else{let B=V.copy();B.addHandler(j,!0),p.callbacks=B}}if(u.includes("tools")){let j=new oh(B=>w.push(B)),{callbacks:V}=p;if(V===void 0)p.callbacks=[j];else if(Array.isArray(V))p.callbacks=V.concat(j);else{let B=V.copy();B.addHandler(j,!0),p.callbacks=B}}p.writer??=j=>{if(!u.includes("custom"))return;let V=_s()?.configurable?.[ve]?.split("|").slice(0,-1);w.push([V??[],"custom",j])},p.interrupt??=this.userInterrupt??Po,p.serverInfo==null&&(p.serverInfo=Fm(p)),p.control??=new go;let C={tracerInheritableMetadata:Hm(p)},T=await(await rr._configureSync(p?.callbacks,void 0,p?.tags,void 0,p?.metadata,void 0,C))?.handleChainStart(this.toJSON(),Gu(e,"input"),a,void 0,void 0,void 0,p?.runName??this.getName()),k=br(this.channels),b,I,F=(async()=>{try{b=await ph.initialize({input:o,config:p,checkpointer:d,nodes:this.nodes,channelSpecs:k,outputKeys:h,streamKeys:this.streamChannelsAsIs,store:_,cache:y,stream:w,interruptAfter:m,interruptBefore:f,manager:T,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:S});let j=new bh({loop:b,nodeFinished:p.configurable?.[wc]});t?.subgraphs&&(b.config.configurable={...b.config.configurable,[$r]:b.stream}),await this._runLoop({loop:b,runner:j,debug:l,config:p}),S==="sync"&&await Promise.all(b?.checkpointerPromises??[])}catch(j){I=j}finally{try{b&&(await b.store?.stop(),await b.cache?.stop()),await Promise.all(b?.checkpointerPromises??[])}catch(j){I=I??j}I?(await new Promise(j=>{queueMicrotask(j)}),w.error(I)):w.close()}})();try{for await(let j of w){if(j===void 0)throw new Error("Data structure error.");let[V,B,be]=j,rt="version"in(t??{});if(u.includes(B)||B==="checkpoints"&&kr(be)&&(s||rt&&n&&u.includes("values"))){if(r==="text/event-stream"){n?yield[V,B,be]:yield[null,B,be];continue}n&&!g?yield[V,B,be]:g?n?yield[V,be]:yield be:yield[B,be]}}}catch(j){throw await T?.handleChainError(I),j}finally{await F}await T?.handleChainEnd(b?.output??{},a,void 0,void 0,void 0)}async invoke(e,t){let r=t?.streamMode??"values",n={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:r,encoding:void 0},s=[],i=await this.stream(e,n),o=[],a;for await(let c of i)r==="values"?Ht(c)?o.push(c[L]):a=c:s.push(c);if(r==="values"){if(o.length>0){let c=o.flat(1);if(a==null)return{[L]:c};if(typeof a=="object")return{...a,[L]:c}}return a}return s}async _runLoop(e){let{loop:t,runner:r,debug:n,config:s}=e,i;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:o}of await t._matchCachedWrites())t._outputWrites(o.id,o.writes,!0);n&&rh(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&wn(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,a)=>{n&&nh(o,a,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(t.status==="draining")throw t.control==null?new Error("Draining status requires run control"):new Pn(t.control.drainReason??"shutdown");if(t.status==="out_of_steps")throw new ii([`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 t.finishAndHandleError(i))throw o}finally{i===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};function Fm(e){let t=e.metadata??{},r=e.configurable??{},n=r.assistant_id??t.assistant_id,s=r.graph_id??t.graph_id,i=r.langgraph_auth_user,o;if(i!=null&&typeof i=="object"&&"identity"in i&&(o=i),n!=null||s!=null||o!=null)return{assistantId:n!=null?String(n):"",graphId:s!=null?String(s):"",user:o}}var Lm=new Set(["key","token","secret","password","auth"]);function Um(e,t){let r=e.toLowerCase(),n=!1;for(let s of Lm)if(r.includes(s)){n=!0;break}return e.startsWith("__")||!(typeof t=="string"||typeof t=="number"||typeof t=="boolean")||n}function Hm(e){let t=e.configurable;if(!t)return;let r=e.context,n={};for(let[s,i]of Object.entries(t)){if(r!=null&&Object.prototype.hasOwnProperty.call(r,s)&&Object.is(r[s],i)){s.startsWith("__")||(n[s]=void 0);continue}Um(s,i)||(n[s]=i)}return Object.keys(n).length>0?n:void 0}var Ue=class Eh extends J{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let r=new Eh(this.guard);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0){let r=this.value.length>0;return this.value=[],r}if(t.length!==1&&this.guard)throw new R("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new $;return this.value[0]}checkpoint(){if(this.value.length===0)throw new $;return this.value[0]}isAvailable(){return this.value.length!==0}};var qo=class{path;ends;constructor(e){G.isRunnable(e.path)?this.path=e.path:this.path=Be(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return q.registerWriter(new se({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(s){throw s.name===Mn.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
134
|
+
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(e,t,r,n){let s=await this.path.invoke(n?n(t):e,t);Array.isArray(s)||(s=[s]);let i;if(this.ends?i=s.map(o=>ee(o)?o:this.ends[o]):i=s,i.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(i.filter(ee).some(o=>o.node==="__end__"))throw new R("Cannot send a packet to the END node");return await r(i,t)??e}},zo=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,s,i]of r){for(let a of["|",":"])if(n.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."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n==="__end__")throw new Error(`Node \`${n}\` is reserved.`);let o=Be(s);this.nodes[n]={runnable:o,metadata:i?.metadata,subgraphs:dn(o)?[o]:i?.subgraphs,ends:i?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e==="__end__")throw new Error("END cannot be a start node");if(t==="__start__")throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([r])=>r===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){let n=typeof e=="object"?e:{source:e,path:t,pathMap:r};this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),G.isRunnable(n.path)||(n.path=Be(n.path));let s=n.path.getName()==="RunnableLambda"?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[n.source]??={},this.branches[n.source][s]=new qo(n),this}setEntryPoint(e){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(W,e)}setFinishPoint(e){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(e,K)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n,transformers:s}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);let i=new Jo({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[W]:new Ue,[K]:new Ue},inputChannels:W,outputChannels:K,streamChannels:[],streamMode:"values",name:n,streamTransformers:s});for(let[o,a]of Object.entries(this.nodes))i.attachNode(o,a);for(let[o,a]of this.edges)i.attachEdge(o,a);for(let[o,a]of Object.entries(this.branches))for(let[c,l]of Object.entries(a))i.attachBranch(o,c,l);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([n,s])=>n));for(let[n]of Object.entries(this.branches))t.add(n);for(let n of t)if(n!=="__start__"&&!(n in this.nodes))throw new Error(`Found edge starting at unknown node \`${n}\``);let r=new Set([...this.allEdges].map(([n,s])=>s));for(let[n,s]of Object.entries(this.branches))for(let i of Object.values(s))if(i.ends!=null)for(let o of Object.values(i.ends))r.add(o);else{r.add(K);for(let o of Object.keys(this.nodes))o!==n&&r.add(o)}for(let n of Object.values(this.nodes))for(let s of n.ends??[])r.add(s);if(Object.values(this.nodes).some(n=>n.isErrorHandler))for(let n of Object.keys(this.nodes))r.add(n);for(let n of Object.keys(this.nodes))if(!this.nodes[n].isErrorHandler&&!r.has(n))throw new ai([`Node \`${n}\` 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(`
|
|
135
|
+
`),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!=="__end__"&&!(n in this.nodes))throw new Error(`Found edge ending at unknown node \`${n}\``);if(e){for(let n of e)if(!(n in this.nodes))throw new Error(`Interrupt node \`${n}\` is not present`)}this.compiled=!0}},Jo=class extends Us{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new Ue,this.nodes[e]=new Fe({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new q([{channel:e,value:we}],[z])),this.streamChannels.push(e)}attachEdge(e,t){if(t==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new q([{channel:K,value:we}],[z]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[W]=kh.subscribeTo(W,{tags:[z]})),this.nodes[e].pipe(r.run(s=>new q(s.map(i=>ee(i)?i:{channel:i==="__end__"?K:`branch:${e}:${t}:${i}`,value:we}),[z])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let s of n)if(s!=="__end__"){let i=`branch:${e}:${t}:${s}`;this.channels[i]=new Ue,this.nodes[s].triggers.push(i),this.nodes[s].channels.push(i)}}async getGraphAsync(e){let t=e?.xray,r=new Zs,n={[W]:r.addNode({schema:wt.any()},W)},s={},i={};t&&(i=Object.fromEntries((await Ve(this.getSubgraphsAsync())).filter(l=>Ch(l[1]))));let o=[];function a(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[K]=r.addNode({schema:wt.any()},K)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return o.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=re(l),p=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?f.__interrupt="before,after":this.interruptBefore?.includes(l)?f.__interrupt="before":this.interruptAfter?.includes(l)&&(f.__interrupt="after"),t){let m=typeof t=="number"?t-1:t,d=i[l]!==void 0?await i[l].getGraphAsync({...e,xray:m}):p.getGraph(e);if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let y=function(w){return w?w.lc_runnable:!1},S=function(w,C){if(w!==void 0&&!Js(w))return w;if(y(C))try{let T=C.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return C.getName()}else return C.name??"UnknownSchema"},[_,g]=r.extend(d,h);if(_===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);g!==void 0&&(n[h]={name:S(g.id,g.data),...g}),s[h]={name:S(_.id,_.data),..._}}else{let _=r.addNode(p,h,f);n[h]=_,s[h]=_}}else{let m=r.addNode(p,h,f);n[h]=m,s[h]=m}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)a(re(l),re(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[re(p),re(p)])),[K]:K};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=h;for(let[m,d]of Object.entries(f))a(re(l),re(d),m,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)a(re(l),re(h),void 0,!0);return xh(this.builder.nodes,o,a),r}getGraph(e){let t=e?.xray,r=new Zs,n={[W]:r.addNode({schema:wt.any()},W)},s={},i={};t&&(i=Object.fromEntries(It(this.getSubgraphs()).filter(l=>Ch(l[1]))));let o=[];function a(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[K]=r.addNode({schema:wt.any()},K)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return o.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=re(l),p=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?f.__interrupt="before,after":this.interruptBefore?.includes(l)?f.__interrupt="before":this.interruptAfter?.includes(l)&&(f.__interrupt="after"),t){let m=typeof t=="number"?t-1:t,d=i[l]!==void 0?i[l].getGraph({...e,xray:m}):p.getGraph(e);if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let y=function(w){return w?w.lc_runnable:!1},S=function(w,C){if(w!==void 0&&!Js(w))return w;if(y(C))try{let T=C.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return C.getName()}else return C.name??"UnknownSchema"},[_,g]=r.extend(d,h);if(_===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);g!==void 0&&(n[h]={name:S(g.id,g.data),...g}),s[h]={name:S(_.id,_.data),..._}}else{let _=r.addNode(p,h,f);n[h]=_,s[h]=_}}else{let m=r.addNode(p,h,f);n[h]=m,s[h]=m}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)a(re(l),re(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[re(p),re(p)])),[K]:K};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=h;for(let[m,d]of Object.entries(f))a(re(l),re(d),m,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)a(re(l),re(h),void 0,!0);return xh(this.builder.nodes,o,a),r}};function Ch(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function re(e){return e==="subgraph"?`"${e}"`:e}function xh(e,t,r){let n=new Set(t.map(i=>i.src)),s=[...new Set(t.filter(i=>!i.conditional&&i.dest!=="__end__").map(i=>i.dest))].sort();for(let i of s){if(n.has(i))continue;let o=Object.keys(e).find(a=>re(a)===i);o!==void 0&&e[o]?.isErrorHandler||r(i,K)}}function pt(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function Yo(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function Bm(e){return pt(e)&&Yo(e)}function Pt(e){if(Yo(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function ft(e){if(e!=null&&pt(e))try{let t=e["~standard"].validate(void 0);if(t&&typeof t=="object"&&!("then"in t&&typeof t.then=="function")){let r=t;if(!r.issues){let n=r.value;return()=>n}}}catch{}}var Gm=e=>e!=null&&e.lc_graph_name==="DeltaChannel",Hs=class Th extends J{lc_graph_name="DeltaChannel";value;reducer;snapshotFrequency;initialValueFactory;constructor(t,r){super();let n=r?.snapshotFrequency??1e3;if(!Number.isInteger(n)||n<=0)throw new Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=t,this.snapshotFrequency=n,this.initialValueFactory=r?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let r=new Th(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?r.value=this.initialValueFactory():pi(t)?r.value=t.value:r.value=t,r}replayWrites(t){let r=t.map(o=>o[2]);if(r.length===0)return;let n=this.value,s=0;for(let o=0;o<r.length;o+=1){let[a,c]=Pe(r[o]);a&&(n=c??this.initialValueFactory(),s=o+1)}let i=r.slice(s);this.value=i.length>0?this.reducer(n,i):n}update(t){if(t.length===0)return!1;let r,n=!1;for(let i of t)if(Ut(i)){if(n)throw new R("Can receive only one Overwrite value per step.");n=!0,[,r]=Pe(i)}if(n)return this.value=r??this.initialValueFactory(),!0;let s=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(s,t),!0}get(){if(this.value===void 0)throw new $;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:!Gm(t)||this.snapshotFrequency!==t.snapshotFrequency?!1:this.reducer===t.reducer}};var Xo=Symbol.for("langgraph.channel.missing"),Bs=class Ih extends J{lc_graph_name="UntrackedValue";guard;_value=Xo;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new Ih({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new R("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=t[t.length-1],!0}get(){if(this._value===Xo)throw new $;return this._value}checkpoint(){}isAvailable(){return this._value!==Xo}};var Rt=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),Qo=class Ah extends J{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new Ah(this.names);return typeof t<"u"&&(r.seen=new Set(t)),r}update(t){let r=!1;for(let n of t)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),r=!0);else throw new R(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!Rt(this.names,this.seen))throw new $}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&Rt(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&Rt(this.names,this.seen)}},Zo=class Oh extends J{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let r=new Oh(this.names);if(typeof t<"u"){let[n,s]=t;r.seen=new Set(n),r.finished=s}return r}update(t){let r=!1;for(let n of t)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),r=!0;else if(!this.names.has(n))throw new R(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!Rt(this.names,this.seen))throw new $}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&Rt(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&Rt(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&Rt(this.names,this.seen)}};var ea=Symbol.for("langgraph.state.reduced_value"),mt=class{[ea]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&ea in e&&e[ea]===!0}};var Nh=Symbol.for("langgraph.state.untracked_value"),Xt=class{[Nh]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&Nh in e}};var ta=Symbol.for("langgraph.state.delta_value"),dt=class{[ta]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&ta in e&&e[ta]===!0}};var ra=Symbol.for("langgraph.state.state_schema"),He=class{[ra]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(dt.isInstance(r)){let n=ft(r.valueSchema);e[t]=new Hs(r.reducer,{snapshotFrequency:r.snapshotFrequency,initialValueFactory:n})}else if(mt.isInstance(r)){let n=ft(r.valueSchema);e[t]=new lt(r.reducer,n)}else if(Xt.isInstance(r)){let n=r.schema?ft(r.schema):void 0;e[t]=new Bs({guard:r.guard,initialValueFactory:n})}else if(pt(r))e[t]=new $e(ft(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let s;if(dt.isInstance(n)||mt.isInstance(n)?(s=Pt(n.valueSchema),n.jsonSchemaExtra&&(s={...s??{},...n.jsonSchemaExtra})):Xt.isInstance(n)?s=n.schema?Pt(n.schema):void 0:pt(n)&&(s=Pt(n)),s){e[r]=s;let i=!1;dt.isInstance(n)||mt.isInstance(n)?i=ft(n.valueSchema)!==void 0:Xt.isInstance(n)?i=n.schema?ft(n.schema)!==void 0:!1:i=ft(n)!==void 0,i||t.push(r)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,r]of Object.entries(this.fields)){let n;dt.isInstance(r)||mt.isInstance(r)?(n=Pt(r.inputSchema),r.jsonSchemaExtra&&(n={...n??{},...r.jsonSchemaExtra})):Xt.isInstance(r)?n=r.schema?Pt(r.schema):void 0:pt(r)&&(n=Pt(r)),n&&(e[t]=n)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e)){let s=this.fields[r];if(s===void 0){t[r]=n;continue}let i;if(dt.isInstance(s)||mt.isInstance(s)){let[o,a]=Pe(n);if(o){i=s.valueSchema;let c=await i["~standard"].validate(a);if(c.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(c.issues)}`);t[r]={[Ge]:c.value};continue}i=s.inputSchema}else Xt.isInstance(s)?i=s.schema:pt(s)&&(i=s);if(i){let o=await i["~standard"].validate(n);if(o.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(o.issues)}`);t[r]=o.value}else t[r]=n}return t}static isInstance(e){return typeof e=="object"&&e!==null&&ra in e&&e[ra]===!0}};var Wm="__remove_all__";function Mt(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],s=r.map(Ne),i=n.map(Ne);for(let u of s)(u.id===null||u.id===void 0)&&(u.id=Nr(),u.lc_kwargs.id=u.id);let o;for(let u=0;u<i.length;u+=1){let h=i[u];(h.id===null||h.id===void 0)&&(h.id=Nr(),h.lc_kwargs.id=h.id),er.isInstance(h)&&h.id==="__remove_all__"&&(o=u)}if(o!=null)return i.slice(o+1);let a=[...s],c=new Map(a.map((u,h)=>[u.id,h])),l=new Set;for(let u of i){let h=c.get(u.id);if(h!==void 0)er.isInstance(u)?l.add(u.id):(l.delete(u.id),a[h]=u);else{if(er.isInstance(u))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,a.length),a.push(u)}}return a.filter(u=>!l.has(u.id))}function na(e,t){let r=[];for(let a of t)Array.isArray(a)?r.push(...a):r.push(a);let n=e.length>0&&X.isInstance(e[0])?e:e.map(Ne),s=r.map(Ne),i=new Map;for(let a=0;a<n.length;a+=1){let c=n[a].id;c!=null&&i.set(c,a)}let o=[...n];for(let a of s){let c=a.id;er.isInstance(a)&&c==="__remove_all__"?(o.length=0,i.clear()):c==null?o.push(a):er.isInstance(a)?i.has(c)&&(o[i.get(c)]=null,i.delete(c)):i.has(c)?o[i.get(c)]=a:(i.set(c,o.length),o.push(a))}return o.filter(a=>a!==null)}var Ph=wt.custom().default(()=>[]),Rh=wt.custom(),Km=new mt(Ph,{inputSchema:Rh,reducer:Mt,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}}),qm=new dt(Ph,{inputSchema:Rh,reducer:na,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var zm=class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let r=this.get(e);this._map.set(e,t(r))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},r=Rr(e);for(let[n,s]of Object.entries(r)){let i=this.get(s);i?.reducer?t[n]=new lt(i.reducer.fn,i.default):t[n]=new $e(i?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,i])=>i===!0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${i}:${o}`).join("|"),n=this._extensionCache.get(r)??new Map;if(n.has(e))return n.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let i=Object.entries(Rr(e)).map(([o,a])=>{let c=this.get(a),l=t.withReducerSchema?c?.reducer?.schema??a:a;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let u=Xs(l)??Xs(a),h=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`lg:${h}`)}return[o,l]});s=Na(e,Object.fromEntries(i)),Oa(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=sr(s)),n.set(e,s),this._extensionCache.set(r,n),s}},bn=new zm;function Mh(e,t){if(t.reducer&&!t.default){let r=Pa(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return bn.extend(r,()=>t),r}else return bn.extend(e,()=>t),e}function Qt(e){return e==null?!1:!!(He.isInstance(e)||ge(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||po(t)))}function jh(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&Qt(t.state),n="stateSchema"in t&&Qt(t.stateSchema),s="input"in t&&Qt(t.input);return!(!r&&!n&&!s||"input"in t&&t.input!=null&&!Qt(t.input)||"output"in t&&t.output!=null&&!Qt(t.output))}var gt="__root__",Or="__default_error_handler__",Gs=Symbol.for("langgraph.state.partial"),sa=class extends zo{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=bn;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new Lr;let s=this._getChannelsFromSchema(n);this._schemaDefinition=s,He.isInstance(n)?this._schemaRuntimeDefinition=n:ge(n)&&(this._schemaRuntimeDefinition=n),r.input?He.isInstance(r.input)?this._inputRuntimeDefinition=r.input:ge(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Gs:this._inputRuntimeDefinition=Gs,r.output?He.isInstance(r.output)?this._outputRuntimeDefinition=r.output:ge(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let i=r.input?this._getChannelsFromSchema(r.input):s,o=r.output?this._getChannelsFromSchema(r.output):s;this._inputDefinition=i,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&ge(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}setNodeDefaults(e){return e.retryPolicy!==void 0&&(this._nodeDefaults.retryPolicy=e.retryPolicy),e.cachePolicy!==void 0&&(this._nodeDefaults.cachePolicy=typeof e.cachePolicy=="boolean"?e.cachePolicy?{}:void 0:e.cachePolicy),e.timeout!==void 0&&(this._nodeDefaults.timeout=bt(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new se({func:(t,r)=>{let n=r?.configurable?.[Vr];return e(t,n,r)},name:Or,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(jh(e)){if(ge(t)||ds.isInstance(t))return{...e,context:t};let r=t;return{...e,input:e.input??r?.input,output:e.output??r?.output,context:e.context??r?.context,interrupt:e.interrupt??r?.interrupt,writer:e.writer??r?.writer,nodes:e.nodes??r?.nodes}}if(Qt(e)){if(ge(t)||ds.isInstance(t))return{state:e,context:t};let r=t;return{state:e,input:r?.input,output:r?.output,context:r?.context,interrupt:r?.interrupt,writer:r?.writer,nodes:r?.nodes}}if(Ym(e))return{state:Jm(e.channels)};throw new Lr}_getChannelsFromSchema(e){if(He.isInstance(e))return e.getChannels();if(ge(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new Lr("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,r]of Object.entries(e)){let n;if(typeof r=="function"?n=r():n=r,this.channels[t]!==void 0){if(!this.channels[t].equals(n)&&n.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=n}}}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([n,s])=>[n,s]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,s,i]of r){if(n in this.channels)throw new Error(`${n} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let p of["|",":"])if(n.includes(p))throw new Error(`"${p}" 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."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n==="__end__"||n==="__start__")throw new Error(`Node \`${n}\` is reserved.`);let o=this._schemaDefinition;i?.input!==void 0&&(o=this._getChannelsFromSchema(i.input)),this._addSchema(o);let a;G.isRunnable(s)?a=s:typeof s=="function"?a=new se({func:s,name:n,trace:!1}):a=Be(s);let c=i?.cachePolicy,l;c!==void 0&&(l=typeof c=="boolean"?c?{}:!1:c);let u;if(i?.errorHandler!==void 0){if(u=`__error_handler__${n}`,u in this.nodes)throw new Error(`Cannot add error handler to node \`${n}\`: the reserved name \`${u}\` is already in use. StateGraph registers \`__error_handler__<nodeName>\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`);let p=i.errorHandler,f={runnable:new se({func:(m,d)=>{let _=d?.configurable?.[Vr];return p(m,_,d)},name:u,trace:!1}),metadata:void 0,input:o??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[u]=f}let h={runnable:a,retryPolicy:i?.retryPolicy,cachePolicy:l,timeout:bt(i?.timeout),metadata:i?.metadata,input:o??this._schemaDefinition,subgraphs:dn(a)?[a]:i?.subgraphs,ends:i?.ends,defer:i?.defer,errorHandlerNode:u};this.nodes[n]=h}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);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(let r of e){if(r==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(n=>n===r))throw new Error(`Need to add a node named "${r}" first`)}if(t==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(let[n,s,i]of t){if(n in this.nodes)throw new Error(`Node names must be unique: node with the name "${n}" already exists.`);let o=n;this.addNode(n,s,i),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:o,transformers:a}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(Or in this.nodes)throw new Error(`Cannot apply a default error handler: the reserved node name \`${Or}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[Or]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:o,transformers:a,defaultErrorHandlerNode:c!==void 0?Or:void 0})}finally{c!==void 0&&delete this.nodes[Or]}}_compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:o,transformers:a,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(s)?s:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===gt?gt:l,h=Object.keys(this.channels),p=h.length===1&&h[0]===gt?gt:h,f=this._interrupt,m=new $h({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[W]:new Ue},inputChannels:W,outputChannels:u,streamChannels:p,streamMode:"updates",store:t,cache:r,name:i,description:o,userInterrupt:f,streamTransformers:a});m.attachNode(W);let d=this._nodeDefaults,_=d.retryPolicy!==void 0||d.cachePolicy!==void 0||d.timeout!==void 0||c!==void 0;for(let[g,y]of Object.entries(this.nodes)){let S=y.isErrorHandler===!0,w=_?{...y,retryPolicy:y.retryPolicy??d.retryPolicy,cachePolicy:S||y.cachePolicy===!1?void 0:y.cachePolicy??d.cachePolicy,timeout:y.timeout??d.timeout,errorHandlerNode:!S&&c!==void 0&&y.errorHandlerNode===void 0?c:y.errorHandlerNode}:y;m.attachNode(g,w)}m.attachBranch(W,si,Dh(),{withReader:!1});for(let[g]of Object.entries(this.nodes))m.attachBranch(g,si,Dh(),{withReader:!1});for(let[g,y]of this.edges)m.attachEdge(g,y);for(let[g,y]of this.waitingEdges)m.attachEdge(g,y);for(let[g,y]of Object.entries(this.branches))for(let[S,w]of Object.entries(y))m.attachBranch(g,S,w);return m.validate()}};function Jm(e){let t={};for(let[r,n]of Object.entries(e))r===gt?t[r]=gs(n):t[r]=gs(n);return t}var $h=class extends Jo{description;_metaRegistry=bn;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e==="__start__"?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([c])=>c):r=Object.keys(this.builder.channels);function n(c){if(ne(c))return c.graph===_e.PARENT?null:c._updateAsTuples();if(Array.isArray(c)&&c.length>0&&c.some(l=>ne(l))){let l=[];for(let u of c)if(ne(u)){if(u.graph===_e.PARENT)continue;l.push(...u._updateAsTuples())}else l.push([gt,u]);return l}else if(c!=null)return[[gt,c]];return null}let s=e,i=async c=>{if(c==null||c.length===0)return c;let l=this.builder._schemaRuntimeDefinition;if(He.isInstance(l)){let u=new Set(l.getChannelKeys());return Promise.all(c.map(async([h,p])=>{if(!u.has(h))return[h,p];let f=await l.validateInput({[h]:p});return[h,Object.prototype.hasOwnProperty.call(f,h)?f[h]:p]}))}if(ge(l)){let u=new Set(Object.keys(Rr(l)));if(c.filter(([f])=>u.has(f)).length===0)return c;let h=sr(this._metaRegistry.getExtendedChannelSchemas(l,{withReducerSchema:!0})),p=sr(l);return c.map(([f,m])=>{if(!u.has(f))return[f,m];let[d,_]=Pe(m);if(d){let y=nr(p,{[f]:_});return[f,Object.prototype.hasOwnProperty.call(y,f)?{[Ge]:y[f]}:m]}let g=nr(h,{[f]:m});return[f,Object.prototype.hasOwnProperty.call(g,f)?g[f]:m]})}return c};async function o(c){if(c){if(ne(c))return c.graph===_e.PARENT?null:i(c._updateAsTuples().filter(([l])=>r.includes(l)));if(Array.isArray(c)&&c.length>0&&c.some(ne)){let l=[];for(let u of c)if(ne(u)){if(u.graph===_e.PARENT)continue;l.push(...u._updateAsTuples().filter(([h])=>r.includes(h)))}else{let h=await o(u);h&&l.push(...h??[])}return i(l)}else{if(typeof c=="object"&&!Array.isArray(c))return i(Object.entries(c).filter(([l])=>r.includes(l)));{let l=Array.isArray(c)?"array":typeof c;throw new R(`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}let a=[{value:we,mapper:new se({func:r.length&&r[0]===gt?n:o,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new Fe({tags:[z],triggers:[W],channels:[W],writers:[new q(a,[z])]});else{let c=t?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(c)).map(m=>[m,m])),u=Object.keys(l).length===1&> in l,h=`branch:to:${e}`;this.channels[h]=t?.defer?new mo:new Ue(!1);let p=t?.cachePolicy,f=p===!1?void 0:p;this.nodes[e]=new Fe({triggers:[h],channels:u?Object.keys(l):l,writers:[new q(a,[z])],mapper:u?void 0:m=>Object.fromEntries(Object.entries(m).filter(([d])=>d in l)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:f,timeout:t?.timeout,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new q([{channel:`branch:to:${t}`,value:null}],[z]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new Zo(new Set(e)):new Qo(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new q([{channel:r,value:n}],[z]))}}}attachBranch(e,t,r,n={withReader:!0}){let s=async(i,o)=>{let a=i.filter(l=>l!==K);if(!a.length)return;let c=a.map(l=>ee(l)?l:{channel:l==="__end__"?l:`branch:to:${l}`,value:e});await q.doWrite({...o,tags:(o.tags??[]).concat([z])},c)};this.nodes[e].writers.push(r.run(s,n.withReader?i=>Lu.doRead(i,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(He.isInstance(t)){if(ne(e)){let s=e;return e.update&&(s.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await t.validateInput(e)}if(t===Gs&&He.isInstance(r)){if(ne(e)){let s=e;return e.update&&(s.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await r.validateInput(e)}let n=(()=>{let s=i=>{if(i!=null)return this._metaRegistry.getExtendedChannelSchemas(i,{withReducerSchema:!0})};if(ge(t))return s(t);if(t===Gs)return ge(r)?sr(s(r)):void 0})();if(ne(e)){let s=e;if(e.update&&n!=null){let i=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,o=nr(n,i);s.update=Object.fromEntries(Object.keys(i).map(a=>[a,o[a]]))}return s}return n!=null?nr(n,e):e}isInterrupted(e){return Ht(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return ge(t)&&nr(t,e),e}};function Ym(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function Xm(e){if(ee(e))return[e];let t=[];ne(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(ne));let r=[];for(let n of t){if(n.graph===_e.PARENT)throw new Dn(n);ee(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function Dh(){return new qo({path:new se({func:Xm,tags:[z],trace:!1,recurse:!1,name:"<control_branch>"})})}var Qm=class extends sa{constructor(){super({channels:{__root__:{reducer:Mt,default:()=>[]}}})}};function Zm(e,t){let{stateKey:r,...n}=t??{},s=Sr(n),i=r??"messages";r===null&&(i=void 0);let o=Ne(e);if(!o.id)throw new Error("Message ID is required.");let a=Array.isArray(s.callbacks)?s.callbacks:typeof s.callbacks<"u"?s.callbacks.handlers:[],c=a.find(u=>"name"in u&&u.name==="StreamMessagesHandler"),l=a.find(u=>"name"in u&&u.name==="StreamProtocolMessagesHandler");if(c||l){let u=s.metadata??{},h=(u.langgraph_checkpoint_ns??"").split("|");c?c._emit([h,u],o,void 0,!1):l&&l.emitFinalMessage([h,u],o,void 0,!1)}return i&&s.configurable?.__pregel_send?.([[i,o]]),o}function ed(e,t){let r=typeof e=="string"?{name:e,retry:void 0,cachePolicy:void 0,timeout:void 0}:e,{name:n,retry:s}=r,i=bt(r.timeout);if(Ro(t)||Mo(t))throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");let o=r.cachePolicy??("cache"in r?r.cache:void 0),a;return typeof o=="boolean"?a=o?{}:void 0:a=o,(...c)=>Ju({func:t,name:n,retry:s,cache:a,timeout:i},...c)}var Vh=function(t,r){let{name:n,checkpointer:s,store:i,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t,a=bt(typeof t=="string"?void 0:t.timeout);if(Ro(r)||Mo(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let c="updates",l=zu(n,r);function u(m){return typeof m=="object"&&m!==null&&"__lg_type"in m&&m.__lg_type==="__pregel_final"}let h=new se({name:"pluckReturnValue",func:m=>u(m)?m.value:m}),p=new se({name:"pluckSaveValue",func:m=>u(m)?m.save:m}),f=new Fe({bound:l,triggers:[W],channels:[W],timeout:a,writers:[new q([{channel:K,value:we,mapper:h},{channel:Ct,value:we,mapper:p}],[z])]});return new Us({name:n,checkpointer:s,nodes:{[n]:f},channels:{[W]:new Ue,[K]:new $e,[Ct]:new $e},inputChannels:W,outputChannels:K,streamChannels:K,streamMode:c,store:i,cache:o})};Vh.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};function td(){return Z.getRunnableConfig().configurable?.[St]}var rd=hn.Root({messages:hn({reducer:Mt,default:()=>[]})}),Fh={reducer:{fn:Mt},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},nd=Qs.object({messages:Mh(Qs.custom(),Fh)});function sd(e){let t=Z.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");return r.writer?.(e)}export{W as a,K as b,L as c,ni as d,Sc as e,Vt as f,Hh as g,Ht as h,_e as i,ne as j,Ce as k,Nn as l,ii as m,Bt as n,Pn as o,Rn as p,it as q,Mn as r,jn as s,Gh as t,Dn as u,oi as v,xt as w,ot as x,$n as y,Wh as z,Vn as A,$ as B,R as C,Kh as D,ai as E,qh as F,Lr as G,zh as H,Fi as I,mr as J,qt as K,je as L,cs as M,du as N,wr as O,hs as P,yu as Q,J as R,lt as S,hn as T,Pf as U,Rf as V,_s as W,Mf as X,go as Y,_o as Z,kr as _,yo as $,Ie as aa,bs as ba,So as ca,pn as da,fn as ea,ko as fa,Eo as ga,vs as ha,To as ia,Ou as ja,Io as ka,Po as la,zo as ma,pt as na,Bm as oa,Pt as pa,ft as qa,Hs as ra,Bs as sa,mt as ta,Xt as ua,dt as va,He as wa,Wm as xa,Mt as ya,na as za,Km as Aa,qm as Ba,bn as Ca,Mh as Da,sa as Ea,$h as Fa,Qm as Ga,Zm as Ha,ed as Ia,Vh as Ja,td as Ka,rd as La,Fh as Ma,nd as Na,sd as Oa};
|