@arcgis/portal-components 5.1.0-next.115 → 5.1.0-next.117

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.
@@ -394,4 +394,4 @@ data: ${aB(i.data)}
394
394
 
395
395
  `))};try{for await(let i of e){let[a,o,s]=i,c=s;if(o==="debug"){let u=s;u.type==="checkpoint"&&(c={...u,payload:FN(u.payload)})}o==="checkpoints"&&(c=FN(s)),n({event:a?.length?`${o}|${a.join("|")}`:o,data:c})}}catch(i){n({event:"error",data:oB(i)})}r.close()}})}var Gm=Symbol.for("INPUT_DONE"),T0=Symbol.for("INPUT_RESUMING"),sB=25;function cB(...e){return new Vm({passthroughFn:t=>{for(let r of e)r.modes.has(t[1])&&r.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var uB=class extends Em{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}},VN=class GN{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=new Set;isNested;_checkpointerChainedPromise=Promise.resolve();_trackCheckpointerPromise(t){let r=t.then(n=>(this.checkpointerPromises.delete(r),n),n=>{throw n});this.checkpointerPromises.add(r)}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 s in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,s)){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,i=ft(this.input)&&this.input.resume!=null,a=this.input===T0,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||i||a||o)}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=NN,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.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 uB(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}static async initialize(t){let{config:r,stream:n}=t;n!==void 0&&r.configurable?.__pregel_stream!==void 0&&(n=cB(n,r.configurable[fc]));let i=r.configurable?!("checkpoint_id"in r.configurable):!0,a=r.configurable?.[tr];r.configurable&&a&&(a.subgraphCounter>0&&(r=fr(r,{[Ir]:[r.configurable[Ir],a.subgraphCounter.toString()].join("|")})),a.subgraphCounter+=1);let o=Gr in(r.configurable??{});!o&&r.configurable?.checkpoint_ns!==void 0&&r.configurable?.checkpoint_ns!==""&&(r=fr(r,{checkpoint_ns:"",checkpoint_id:void 0}));let s=r;r.configurable?.checkpoint_map!==void 0&&r.configurable?.checkpoint_map?.[r.configurable?.checkpoint_ns]&&(s=fr(r,{checkpoint_id:r.configurable[Tr][r.configurable?.checkpoint_ns]}));let c=r.configurable?.checkpoint_ns?.split("|")??[],u=await t.checkpointer?.getTuple(s)??{config:r,checkpoint:Ys(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};s={...r,...u.config,configurable:{checkpoint_ns:"",...r.configurable,...u.config.configurable}};let l=u.parentConfig,d=ln(u.checkpoint),f={...u.metadata},p=u.pendingWrites??[],m=ra(t.channelSpecs,d),g=(f.step??0)+1,v=g+(r.recursionLimit??sB)+1,S={...d.channel_versions},w=t.store?new $m(t.store):void 0;return w&&await w.start(),new GN({input:t.input,config:r,checkpointer:t.checkpointer,checkpoint:d,checkpointMetadata:f,checkpointConfig:s,prevCheckpointConfig:l,checkpointNamespace:c,channels:m,isNested:o,manager:t.manager,skipDoneTasks:i,step:g,stop:v,checkpointPreviousVersions:S,checkpointPendingWrites:p,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:n,store:w,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_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 Xu)&&(n=Array.from(new Map(n.map(c=>[c[0],c])).values()));let i=!1;for(let c in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,c)&&this.channels[c].lc_graph_name==="UntrackedValue"){i=!0;break}let a=n;i&&(a=n.filter(([c])=>{let u=this.channels[c];return!u||u.lc_graph_name!=="UntrackedValue"}).map(([c,u])=>c==="__pregel_tasks"&&ct(u)?[c,RN(u,this.channels)]:[c,u])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(c=>c[0]!==t);for(let[c,u]of a)this.checkpointPendingWrites.push([t,c,u]);let o=fr(this.checkpointConfig,{[Ir]:this.config.configurable?.checkpoint_ns??"",[dl]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(o,a,t)),this.tasks&&this._outputWrites(t,n),!r.length||!this.cache||!this.tasks)return;let s=this.tasks[t];s==null||s.cache_key==null||r[0][0]==="__error__"||r[0][0]==="__interrupt__"||this.cache.set([{key:[s.cache_key.ns,s.cache_key.key],value:s.writes,ttl:s.cache_key.ttl}])}_outputWrites(t,r,n=!1){let i=this.tasks[t];if(i!==void 0){if(i.config!==void 0&&(i.config.tags??[]).includes("langsmith:hidden"))return;if(r.length>0)if(r[0][0]==="__interrupt__"){if(i.path?.[0]==="__pregel_push"&&i.path?.[i.path.length-1]===!0)return;let a=r.filter(o=>o[0]===Be).flatMap(o=>o[1]);this._emit([["updates",{[Be]:a}],["values",{[Be]:a}]])}else r[0][0]!=="__error__"&&this._emit(vo(vi($N(this.outputKeys,[[i,r]],n),"updates")));n||this._emit(vo(vi(jN([[i,r]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let t=[],r=([o,s])=>`ns:${o.join(",")}|key:${s}`,n=[],i={};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]),i[r([o.cache_key.ns,o.cache_key.key])]=o);if(n.length===0)return[];let a=await this.cache.get(n);for(let{key:o,value:s}of a){let c=i[r(o)];c!=null&&(c.writes.push(...s),t.push({task:c,result:s}))}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(![Gm,T0].includes(this.input))await this._first(r);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Wn;if(Object.values(this.tasks).every(i=>i.writes.length>0)){let i=Object.values(this.tasks).flatMap(o=>o.writes);this.updatedChannels=Yt(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let a=await pn(vi(Lm(this.outputKeys,i,this.channels),"values"));if(this._emit(a),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),al(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Wn;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[To]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=aa(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}),this.checkpointer&&this._emit(await pn(vi(zN(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[i,a,o]of this.checkpointPendingWrites){if(a==="__error__"||a==="__interrupt__"||a==="__resume__")continue;let s=Object.values(this.tasks).find(c=>c.id===i);s&&s.writes.push([a,o])}for(let i of Object.values(this.tasks))i.writes.length>0&&this._outputWrites(i.id,i.writes,!0)}if(Object.values(this.tasks).every(i=>i.writes.length>0))return this.tick({inputKeys:r});if(al(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Wn;let n=await pn(vi(S0(Object.values(this.tasks)),"tasks"));return this._emit(n),!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(n=>!n.includes(":")))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let r=this._suppressInterrupt(t);return(r||t===void 0)&&(this.output=hn(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=Yt(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(vo(vi(Lm(this.outputKeys,Object.values(this.tasks).flatMap(n=>n.writes),this.channels),"values")))),qn(t)&&!t.interrupts.length&&this._emit([["updates",{[Be]:[]}],["values",{[Be]:[]}]])),r}async acceptPush(t,r,n){if(this.interruptAfter?.length>0&&al(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}let i=Bm([Ar,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(!i)return;if(this.interruptBefore?.length>0&&al(this.checkpoint,this.interruptBefore,[i])){this.toInterrupt.push(i);return}this._emit(vo(vi(S0([i]),"tasks"))),this.debug&&Zm(this.step,[i]),this.tasks[i.id]=i,this.skipDoneTasks&&this._matchWrites({[i.id]:i});let a=await this._matchCachedWrites();for(let{task:o}of a)this._outputWrites(o.id,o.writes,!0);return i}_suppressInterrupt(t){return qn(t)&&!this.isNested}async _first(t){let{configurable:r}=this.config,n=r?.[tr];if(n&&n.nullResume!==void 0&&this.putWrites(mr,[[pr,n.nullResume]]),ft(this.input)){let o=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Mm)&&(this.config.configurable??={},this.config.configurable[Ao]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");let s={};for(let[c,u,l]of kN(this.input,this.checkpointPendingWrites))s[c]??=[],s[c].push([u,l]);if(Object.keys(s).length===0)throw new _l("Received empty Command input");for(let[c,u]of Object.entries(s))this.putWrites(c,u)}let i=(this.checkpointPendingWrites??[]).filter(o=>o[0]===mr).map(o=>o.slice(1));i.length>0&&Yt(this.checkpoint,this.channels,[{name:wn,writes:i,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let a=ft(this.input)&&i.length>0;if(this.isResuming||a){for(let s in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,s)&&this.checkpoint.channel_versions[s]!==void 0){let c=this.checkpoint.channel_versions[s];this.checkpoint.versions_seen[Be]={...this.checkpoint.versions_seen[Be],[s]:c}}let o=await pn(vi(Lm(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=T0;else if(a)await this._putCheckpoint({source:"input"}),this.input=Gm;else{let o=await pn(Um(t,this.input));if(o.length>0){let s=aa(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Yt(this.checkpoint,this.channels,Object.values(s).concat([{name:wn,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Gm}else if("__pregel_resuming"in(this.config.configurable??{}))this.input=Gm;else throw new _l(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=fr(this.config,{[To]:this.isResuming}))}_emit(t){for(let[r,n]of t)if(this.stream.modes.has(r)&&this.stream.push([this.checkpointNamespace,r,n]),(r==="checkpoints"||r==="tasks")&&this.stream.modes.has("debug")){let i=r==="checkpoints"?this.step-1:this.step,a=new Date().toISOString(),o=r==="checkpoints"?"checkpoint":typeof n=="object"&&n!=null&&"result"in n?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:i,type:o,timestamp:a,payload:n}])}}_putCheckpoint(t){let r=this.checkpointMetadata===t,n=this.checkpointer!=null&&(this.durability!=="exit"||r),i=a=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=fr(this.checkpointConfig,{[Ir]:this.config.configurable?.checkpoint_ns??""});let o={...this.checkpoint.channel_versions},s=ac(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ln(a),metadata:{...this.checkpointMetadata},newVersions:s}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};r||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}),this.checkpoint=dn(this.checkpoint,n?this.channels:void 0,this.step,r?{id:this.checkpoint.id}:void 0),n&&i(this.checkpoint),r||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let t=fr(this.checkpointConfig,{[Ir]:this.config.configurable?.checkpoint_ns??"",[dl]:this.checkpoint.id}),r={};for(let[n,i,a]of this.checkpointPendingWrites)r[n]??=[],r[n].push([i,a]);for(let[n,i]of Object.entries(r))this._trackCheckpointerPromise(this.checkpointer.putWrites(t,i,n))}_matchWrites(t){for(let[r,n,i]of this.checkpointPendingWrites){if(n==="__error__"||n==="__interrupt__"||n==="__resume__")continue;let a=Object.values(t).find(o=>o.id===r);a&&a.writes.push([n,i])}for(let r of Object.values(t))r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}};function lB(e){return Je(e?.message)}var HN=class extends Yr{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 i=t.id;r!=null&&(xc(t)?i??=`run-${r}-tool-${t.tool_call_id}`:((i==null||i===`run-${r}`)&&(i=this.stableMessageIdMap[r]??i??`run-${r}`),this.stableMessageIdMap[r]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,i,a,o,s){o&&(!a||!a.includes("langsmith:nostream")&&!a.includes("nostream"))&&(this.metadatas[r]=[o.langgraph_checkpoint_ns.split("|"),{tags:a,name:s,...o}])}handleLLMNewToken(e,t,r,n,i,a){let o=a?.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(lB(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new mt({content:e}),r))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let r=e.generations?.[0]?.[0];Je(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,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes("langsmith:hidden"))&&(this.metadatas[r]=[a.langgraph_checkpoint_ns.split("|"),{tags:i,name:s,...a}],typeof t=="object")){for(let c of Object.values(t))if((Je(c)||Qn(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let u of c)(Je(u)||Qn(u))&&u.id!==void 0&&(this.seen[u.id]=u)}}handleChainEnd(e,t){let r=this.metadatas[t];if(delete this.metadatas[t],r!==void 0){if(Je(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(let n of e)Je(n)&&this._emit(r,n,t,!0);else if(e!=null&&typeof e=="object"){for(let n of Object.values(e))if(Je(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(let i of n)Je(i)&&this._emit(r,i,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};var dB=[400,401,402,403,404,405,406,407,409],fB=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&&dB.includes(+t)||e?.error?.code==="insufficient_quota")};async function A0(e,t,r,n){let i=e.retry_policy??t,a=i!==void 0?i.initialInterval??500:0,o=0,s,c,u=e.config??{};r&&(u=fr(u,r)),u={...u,signal:n};let l=Date.now();for(u.executionInfo!=null&&(u.executionInfo={...u.executionInfo,nodeFirstAttemptTime:l});!n?.aborted;){e.writes.splice(0,e.writes.length),s=void 0;try{c=await e.proc.invoke(e.input,u);break}catch(d){if(s=d,s.pregelTaskId=e.id,Qm(s)){let m=u?.configurable?.checkpoint_ns,g=s.command;if(g.graph===m){for(let v of e.writers)await v.invoke(g,u);s=void 0;break}else if(g.graph===er.PARENT){let v=fN(m);s.command=new er({...s.command,graph:v})}}if(ya(s)||i===void 0||(o+=1,o>=(i.maxAttempts??3))||!(i.retryOn??fB)(s))break;a=Math.min(i.maxInterval??128e3,a*(i.backoffFactor??2));let f=i.jitter?Math.floor(a+Math.random()*1e3):a;await new Promise(m=>setTimeout(m,f));let p=s.name??s.constructor.unminifiable_name??s.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${a.toFixed(2)}ms (attempt ${o}) after ${p}: ${s}`),u=fr(u,{[To]:!0}),u.executionInfo!=null&&(u.executionInfo={...u.executionInfo,nodeAttempt:o+1,nodeFirstAttemptTime:l})}}return{task:e,result:c,error:s,signalAborted:n?.aborted}}var C0=Symbol.for("promiseAdded");function pB(){let e={next:()=>{},wait:Promise.resolve(C0)};function t(r){e.next=()=>{e.wait=new Promise(t),r(C0)}}return e.wait=new Promise(t),e}var JN=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:i}=e,a=new Set,o,s=new AbortController,c=s.signal,u=t?AbortSignal.timeout(t):void 0,l=Object.values(this.loop.tasks).filter(m=>m.writes.length===0),{signals:d,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:u,signal:e.signal}),p=this._executeTasksWithRetry(l,{signals:d,retryPolicy:r,maxConcurrency:i});for await(let{task:m,error:g,signalAborted:v}of p)this._commit(m,g),qn(g)||ya(g)&&!qn(o)?o=g:g&&(a.size===0||!v)&&(s.abort(),a.add(g));if(f?.(),n?.(this.loop.step,Object.values(this.loop.tasks).map(m=>m.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw new AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(qn(o)||ya(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:r}){let n=this.loop.config.configurable?.__pregel_abort_signals??{},i=n.externalAbortSignal??r,a=t??n.timeoutAbortSignal,{signal:o,dispose:s}=oc(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=fr(this.loop.config,{[H0]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:r,maxConcurrency:n,signals:i}=t??{},a=pB(),o={},s={executingTasksMap:o,barrier:a,retryPolicy:r,scheduleTask:async(f,p,m)=>this.loop.acceptPush(f,p,m)};if(i?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,u,l=oc(i?.externalAbortSignal,i?.timeoutAbortSignal),d=l.signal?new Promise((f,p)=>{u=()=>p(new Error("Abort")),l.signal?.addEventListener("abort",u,{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 p=e[c];o[p.id]=A0(p,r,{[Io]:KN?.bind(s,this,p)},i?.composedAbortSignal).catch(m=>({task:p,error:m,signalAborted:i?.composedAbortSignal?.aborted}))}let f=await Promise.race([...Object.values(o),...d?[d]:[],a.wait]);f!==C0&&(yield f,u!=null&&(l.signal?.removeEventListener("abort",u),l.dispose?.()),delete o[f.task.id])}}_commit(e,t){if(t!==void 0)if(qn(t)){if(t.interrupts.length){let r=t.interrupts.map(i=>[Be,i]),n=e.writes.filter(i=>i[0]===pr);n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else ya(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[Eo,{message:t.message,name:t.name}]]);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([pc,null]),this.loop.putWrites(e.id,e.writes)}};async function KN(e,t,r,n,i,a={}){let o=t.config?.configurable?.[tr];if(!o)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new TN({func:r,name:n,input:i,cache:a.cache,retry:a.retry,callbacks:a.callbacks}),u=await this.scheduleTask(t,s,c);if(!u)return;let l=this.executingTasksMap[u.id];if(l!==void 0)return l;if(u.writes.length>0){let d=u.writes.filter(([p])=>p===ki),f=u.writes.filter(([p])=>p===Eo);if(d.length>0){if(d.length===1)return Promise.resolve(d[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(f.length>0){if(f.length===1){let p=f[0][1],m=p instanceof Error?p:new Error(String(p));return Promise.reject(m)}throw new Error(`BUG: multiple errors found for task ${u.name}__${u.id}`)}return}else{let d=A0(u,a.retry,{[Io]:KN.bind(this,e,u)});return this.executingTasksMap[u.id]=d,this.barrier.next(),d.then(({result:f,error:p})=>p?Promise.reject(p):f)}}var bi=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function WN({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new bi("Channels not provided");let s=new Set,c=new Set;for(let[u,l]of Object.entries(e)){if(u==="__interrupt__")throw new bi(`"Node name ${Be} is reserved"`);if(l.constructor===mn)l.triggers.forEach(d=>s.add(d));else throw new bi(`Invalid node type ${typeof l}, expected PregelNode`)}for(let u of s)if(!(u in t))throw new bi(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(r)){if(r.every(u=>!s.has(u)))throw new bi(`None of the input channels ${r} are subscribed to by any node`)}else if(!s.has(r))throw new bi(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach(u=>c.add(u)):c.add(n),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(u=>c.add(u));for(let u of c)if(!(u in t))throw new bi(`Output channel '${String(u)}' not in channels`);if(a&&a!=="*"){for(let u of a)if(!(u in e))throw new bi(`Node ${String(u)} not in nodes`)}if(o&&o!=="*"){for(let u of o)if(!(u in e))throw new bi(`Node ${String(u)} not in nodes`)}}function O0(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`)}var P0=class qN extends wt{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 qN({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(r.seen=new Set(t[0]),r.values=t[1]),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 i of n)this.seen.has(i)||(r=!0,this.seen.add(i),this.values.push(i));else r=!0,this.values.push(...n);return r}get(){if(this.values.length===0)throw new Ae;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};var XN=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 i;return typeof e=="string"?r?i={[r]:e}:i=[e]:i=Object.fromEntries(e.map(a=>[a,a])),new mn({channels:i,triggers:Array.isArray(e)?e:[e],tags:n})}static writeTo(e,t){let r=[];for(let n of e)r.push({channel:n,value:dr,skipNone:!1});for(let[n,i]of Object.entries(t??{}))re.isRunnable(i)||typeof i=="function"?r.push({channel:n,value:dr,skipNone:!0,mapper:Xe(i)}):r.push({channel:n,value:i,skipNone:!1});return new rt(r)}},mB=class extends re{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)}},Hm=class extends mB{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(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 '${xn}' is reserved and cannot be used in the graph.`);this.channels[xn]=new P0({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.autoValidate&&this.validate()}withConfig(e){let t=vt(this.config,e);return new this.constructor({...this,config:t})}validate(){WN({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 i=n.subgraphs?.length?n.subgraphs:[n.bound];for(let a of i){let o=Dm(a);if(o!==void 0){if(r===e){yield[r,o];return}if(e===void 0&&(yield[r,o]),t){let s=e;e!==void 0&&(s=e.slice(r.length+1));for(let[c,u]of o.getSubgraphs(s,t))yield[`${r}|${c}`,u]}}}}}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 i=ra(this.channels,t.checkpoint);if(t.pendingWrites?.length){let d=t.pendingWrites.filter(([f,p])=>f===mr).map(([f,p,m])=>[String(p),m]);d.length>0&&Yt(t.checkpoint,i,[{name:wn,writes:d,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(aa(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await pn(this.getSubgraphsAsync()),s=t.config.configurable?.checkpoint_ns??"",c={};for(let d of a){let f=o.find(([m])=>m===d.name);if(!f)continue;let p=`${String(d.name)}:${d.id}`;if(s&&(p=`${s}|${p}`),r===void 0){let m={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:p}};c[d.id]=m}else{let m={configurable:{[Hr]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:p}},g=f[1];c[d.id]=await g.getState(m,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){let d=Object.fromEntries(a.map(p=>[p.id,p]));for(let[p,m,g]of t.pendingWrites)["__error__","__interrupt__",va].includes(m)||p in d&&d[p].writes.push([String(m),g]);let f=a.filter(p=>p.writes.length>0);f.length>0&&Yt(t.checkpoint,i,f,void 0,this.triggerToNodes)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});let l=a.filter(d=>d.writes.length===0).map(d=>d.name);return{values:hn(i,this.streamChannelsAsIs),next:l,tasks:k0(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:u,config:ia(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 _a("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_checkpointer===void 0){let o=Am(n);for await(let[s,c]of this.getSubgraphsAsync(o,!0))if(s===o)return await c.getState(bo(e,{[Hr]:r}),{subgraphs:t?.subgraphs})}let i=vt(this.config,e),a=await r.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,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 _a("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_checkpointer===void 0){let a=Am(n);for await(let[o,s]of this.getSubgraphsAsync(a,!0))if(o===a){yield*s.getStateHistory(bo(e,{[Hr]:r}),t);return}}let i=vt(this.config,e,{configurable:{checkpoint_ns:n}});for await(let a of r.list(i,t))yield this._prepareStateSnapshot({config:a.config,saved:a})}async bulkUpdateState(e,t){let r=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!r)throw new _a("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=Am(n);for await(let[,s]of this.getSubgraphsAsync(o,!0))return await s.bulkUpdateState(bo(e,{[Hr]:r}),t);throw new Error(`Subgraph "${o}" not found`)}let i=async(o,s)=>{let c=this.config?vt(this.config,o):o,u=await r.getTuple(c),l=u!==void 0?ln(u.checkpoint):Ys(),d={...u?.checkpoint.channel_versions},f=u?.metadata?.step??-1,p=bo(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),m=c.metadata??{};u?.config.configurable&&(p=bo(c,u.config.configurable),m={...u.metadata,...m});let{values:g,asNode:v}=s[0];if(g==null&&v===void 0){if(s.length>1)throw new ye("Cannot create empty checkpoint with multiple updates");return ia(await r.put(p,dn(l,void 0,f),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},{}),u?u.metadata:void 0)}let S=ra(this.channels,l);if(g===null&&v==="__end__"){if(s.length>1)throw new ye("Cannot apply multiple updates when clearing state");if(u){let A=aa(l,u.pendingWrites||[],this.nodes,S,u.config,!0,{step:(u.metadata?.step??-1)+1,checkpointer:r,store:this.store}),y=(u.pendingWrites||[]).filter(W=>W[0]===mr).map(W=>W.slice(1));y.length>0&&Yt(l,S,[{name:wn,writes:y,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[W,O,F]of u.pendingWrites||[])["__error__","__interrupt__",va].includes(O)||W in A&&A[W].writes.push([O,F]);Yt(l,S,Object.values(A),r.getNextVersion.bind(r),this.triggerToNodes)}return ia(await r.put(p,dn(l,S,f),{...m,source:"update",step:f+1,parents:u?.metadata?.parents??{}},ac(d,l.channel_versions)),u?u.metadata:void 0)}if(v==="__copy__"){if(s.length>1)throw new ye("Cannot copy checkpoint with multiple updates");if(u==null)throw new ye("Cannot copy a non-existent checkpoint");let A=O=>!Array.isArray(O)||O.length===0?!1:O.every(F=>Array.isArray(F)&&F.length===2),y=dn(l,void 0,f),W=await r.put(u.parentConfig??bo(u.config,{checkpoint_id:void 0}),y,{source:"fork",step:f+1,parents:u.metadata?.parents??{}},{});if(A(g)){let O=aa(y,u.pendingWrites,this.nodes,S,W,!1,{step:f+2}),F=Object.values(O).reduce((Le,{name:Lt,id:_n})=>(Le[Lt]??=[],Le[Lt].push({id:_n}),Le),{}),de=g.reduce((Le,Lt)=>{let[_n,we]=Lt;Le[we]??=[];let la=Le[we].length,Jn=F[we]?.[la]?.id;return Le[we].push({values:_n,asNode:we,taskId:Jn}),Le},{});return i(ia(W,u.metadata),Object.values(de).flat())}return ia(W,u.metadata)}if(v==="__input__"){if(s.length>1)throw new ye("Cannot apply multiple updates when updating as input");let A=await pn(Um(this.inputChannels,g));if(A.length===0)throw new ye(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Yt(l,S,[{name:wn,writes:A,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let y=u?.metadata?.step!=null?u.metadata.step+1:-1,W=await r.put(p,dn(l,S,y),{source:"input",step:y,parents:u?.metadata?.parents??{}},ac(d,l.channel_versions));return await r.putWrites(W,A,Xn(wn,l.id)),ia(W,u?u.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&u?.pendingWrites!==void 0&&u.pendingWrites.length>0){let A=aa(l,u.pendingWrites,this.nodes,S,u.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(u.metadata?.step??-1)+1}),y=(u.pendingWrites??[]).filter(O=>O[0]===mr).map(O=>O.slice(1));y.length>0&&Yt(u.checkpoint,S,[{name:wn,writes:y,triggers:[]}],void 0,this.triggerToNodes);for(let[O,F,de]of u.pendingWrites)["__error__","__interrupt__",va].includes(F)||A[O]===void 0||A[O].writes.push([F,de]);let W=Object.values(A).filter(O=>O.writes.length>0);W.length>0&&Yt(l,S,W,void 0,this.triggerToNodes)}let w=Object.values(l.versions_seen).map(A=>Object.values(A)).flat().find(A=>!!A),x=[];if(s.length===1){let{values:A,asNode:y,taskId:W}=s[0];if(y===void 0&&Object.keys(this.nodes).length===1)[y]=Object.keys(this.nodes);else if(y===void 0&&w===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(y=this.inputChannels);else if(y===void 0){let O=Object.entries(l.versions_seen).map(([F,de])=>Object.values(de).map(Le=>[Le,F])).flat().filter(([F,de])=>de!==Be).sort(([F],[de])=>km(F,de));O&&(O.length===1?y=O[0][1]:O[O.length-1][0]!==O[O.length-2][0]&&(y=O[O.length-1][1]))}if(y===void 0)throw new ye('Ambiguous update, specify "asNode"');x.push({values:A,asNode:y,taskId:W})}else for(let{asNode:A,values:y,taskId:W}of s){if(A==null)throw new ye('"asNode" is required when applying multiple updates');x.push({values:y,asNode:A,taskId:W})}let $=[];for(let{asNode:A,values:y,taskId:W}of x){if(this.nodes[A]===void 0)throw new ye(`Node "${A.toString()}" does not exist`);let O=this.nodes[A].getWriters();if(!O.length)throw new ye(`No writers found for node "${A.toString()}"`);$.push({name:A,input:y,proc:O.length>1?Sr.from(O,{omitSequenceTags:!0}):O[0],writes:[],triggers:[Be],id:W??Xn("__interrupt__",l.id),writers:[]})}for(let A of $)await A.proc.invoke(A.input,Se({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[Er]:y=>A.writes.push(...y),[Gr]:(y,W=!1)=>il(l,S,A,y,W)}}));for(let A of $){let y=A.writes.filter(W=>W[0]!==Ar);u!==void 0&&y.length>0&&await r.putWrites(p,y,A.id)}Yt(l,S,$,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let T=ac(d,l.channel_versions),B=await r.put(p,dn(l,S,f+1),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},T);for(let A of $){let y=A.writes.filter(W=>W[0]===Ar);y.length>0&&await r.putWrites(B,y,A.id)}return ia(B,u?u.metadata:void 0)},a=e;for(let{updates:o}of t)a=await i(a,o);return a}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){let{debug:t,streamMode:r,inputKeys:n,outputKeys:i,interruptAfter:a,interruptBefore:o,...s}=e,c=!0,u=t!==void 0?t:this.debug,l=i;l===void 0?l=this.streamChannelsAsIs:O0(l,this.channels);let d=n;d===void 0?d=this.inputChannels:O0(d,this.channels);let f=o??this.interruptBefore??[],p=a??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 g;if(this.checkpointer===!1)g=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)g=e.configurable[Hr];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");g=this.checkpointer}let v=e.store??this.store,S=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 w=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),x=e.durability??w??e?.configurable?.__pregel_durability??"async";return[u,m,d,l,s,f,p,g,v,c,S,x]}async stream(e,t){let r=new AbortController,n={recursionLimit:this.config?.recursionLimit,...t,signal:oc(t?.signal,r.signal).signal},i=await super.stream(e,n);return new E0(t?.encoding==="text/event-stream"?ZN(i):i,r)}streamEvents(e,t,r){let n=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:IN(this.config?.callbacks,t?.callbacks),signal:oc(t?.signal,n.signal).signal};return new E0(super.streamEvents(e,i,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,i=tc(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 a=await this._validateInput(e),{runId:o,...s}=i,[c,u,,l,d,f,p,m,g,v,S,w]=this._defaults(s);d.metadata={ls_integration:"langgraph",...d.metadata},typeof d.context<"u"?d.context=await this._validateContext(d.context):d.configurable=await this._validateContext(d.configurable);let x=new Vm({modes:new Set(u)});if(this.checkpointer===!0){d.configurable??={};let O=d.configurable.checkpoint_ns??"";d.configurable[Ir]=O.split("|").map(F=>F.split(":")[0]).join("|")}if(u.includes("messages")){let O=new HN(de=>x.push(de)),{callbacks:F}=d;if(F===void 0)d.callbacks=[O];else if(Array.isArray(F))d.callbacks=F.concat(O);else{let de=F.copy();de.addHandler(O,!0),d.callbacks=de}}if(u.includes("tools")){let O=new BN(de=>x.push(de)),{callbacks:F}=d;if(F===void 0)d.callbacks=[O];else if(Array.isArray(F))d.callbacks=F.concat(O);else{let de=F.copy();de.addHandler(O,!0),d.callbacks=de}}d.writer??=O=>{if(!u.includes("custom"))return;let F=d0()?.configurable?.[Ir]?.split("|").slice(0,-1);x.push([F??[],"custom",O])},d.interrupt??=this.userInterrupt??h0,d.serverInfo==null&&(d.serverInfo=hB(d));let $=await(await yt(d))?.handleChainStart(this.toJSON(),EN(e,"input"),o,void 0,void 0,void 0,d?.runName??this.getName()),T=el(this.channels),B,A,W=(async()=>{try{B=await VN.initialize({input:a,config:d,checkpointer:m,nodes:this.nodes,channelSpecs:T,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:g,cache:S,stream:x,interruptAfter:p,interruptBefore:f,manager:$,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:w});let O=new JN({loop:B,nodeFinished:d.configurable?.[G0]});t?.subgraphs&&(B.config.configurable={...B.config.configurable,[fc]:B.stream}),await this._runLoop({loop:B,runner:O,debug:c,config:d}),w==="sync"&&await Promise.all(B?.checkpointerPromises??[])}catch(O){A=O}finally{try{B&&(await B.store?.stop(),await B.cache?.stop()),await Promise.all(B?.checkpointerPromises??[])}catch(O){A=A??O}A?x.error(A):x.close()}})();try{for await(let O of x){if(O===void 0)throw new Error("Data structure error.");let[F,de,Le]=O;if(u.includes(de)){if(r==="text/event-stream"){n?yield[F,de,Le]:yield[null,de,Le];continue}n&&!v?yield[F,de,Le]:v?n?yield[F,Le]:yield Le:yield[de,Le]}}}catch(O){throw await $?.handleChainError(A),O}finally{await W}await $?.handleChainEnd(B?.output??{},o,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},i=[],a=await this.stream(e,n),o=[],s;for await(let c of a)r==="values"?mc(c)?o.push(c[Be]):s=c:i.push(c);if(r==="values"){if(o.length>0){let c=o.flat(1);if(s==null)return{[Be]:c};if(typeof s=="object")return{...s,[Be]:c}}return s}return i}async _runLoop(e){let{loop:t,runner:r,debug:n,config:i}=e,a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:o}of await t._matchCachedWrites())t._outputWrites(o.id,o.writes,!0);n&&DN(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&Zm(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,s)=>{n&&UN(o,s,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status==="out_of_steps")throw new Ym([`Recursion limit of ${i.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(a=o,!await t.finishAndHandleError(a))throw o}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};function hB(e){let t=e.metadata??{},r=e.configurable??{},n=t.assistant_id,i=t.graph_id,a=r.langgraph_auth_user,o;if(a!=null&&typeof a=="object"&&"identity"in a&&(o=a),n!=null||i!=null||o!=null)return{assistantId:n!=null?String(n):"",graphId:i!=null?String(i):"",user:o}}var gn=class YN extends wt{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let r=new YN(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 ye("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Ae;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Ae;return this.value[0]}isAvailable(){return this.value.length!==0}};var N0=class{path;ends;constructor(e){re.isRunnable(e.path)?this.path=e.path:this.path=Xe(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return rt.registerWriter(new Dt({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(i){throw i.name===hl.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
396
396
  NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}}))}async _route(e,t,r,n){let i=await this.path.invoke(n?n(t):e,t);Array.isArray(i)||(i=[i]);let a;if(this.ends?a=i.map(o=>ct(o)?o:this.ends[o]):a=i,a.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(a.filter(ct).some(o=>o.node==="__end__"))throw new ye("Cannot send a packet to the END node");return await r(a,t)??e}},R0=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,i,a]of r){for(let s of["|",":"])if(n.includes(s))throw new Error(`"${s}" 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=Xe(i);this.nodes[n]={runnable:o,metadata:a?.metadata,subgraphs:nl(o)?[o]:a?.subgraphs,ends:a?.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."),re.isRunnable(n.path)||(n.path=Xe(n.path));let i=n.path.getName()==="RunnableLambda"?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][i])throw new Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[n.source]??={},this.branches[n.source][i]=new N0(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(Fe,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,We)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);let i=new M0({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Fe]:new gn,[We]:new gn},inputChannels:Fe,outputChannels:We,streamChannels:[],streamMode:"values",name:n});for(let[a,o]of Object.entries(this.nodes))i.attachNode(a,o);for(let[a,o]of this.edges)i.attachEdge(a,o);for(let[a,o]of Object.entries(this.branches))for(let[s,c]of Object.entries(o))i.attachBranch(a,s,c);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([n,i])=>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,i])=>i));for(let[n,i]of Object.entries(this.branches))for(let a of Object.values(i))if(a.ends!=null)for(let o of Object.values(a.ends))r.add(o);else{r.add(We);for(let o of Object.keys(this.nodes))o!==n&&r.add(o)}for(let n of Object.values(this.nodes))for(let i of n.ends??[])r.add(i);for(let n of Object.keys(this.nodes))if(!r.has(n))throw new eh([`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(`
397
- `),{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}},M0=class extends Hm{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new gn,this.nodes[e]=new mn({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new rt([{channel:e,value:dr}],[st])),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 rt([{channel:We,value:dr}],[st]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[Fe]=XN.subscribeTo(Fe,{tags:[st]})),this.nodes[e].pipe(r.run(i=>new rt(i.map(a=>ct(a)?a:{channel:a==="__end__"?We:`branch:${e}:${t}:${a}`,value:dr}),[st])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let i of n)if(i!=="__end__"){let a=`branch:${e}:${t}:${i}`;this.channels[a]=new gn,this.nodes[i].triggers.push(a),this.nodes[i].channels.push(a)}}async getGraphAsync(e){let t=e?.xray,r=new lo,n={[Fe]:r.addNode({schema:Br.any()},Fe)},i={},a={};t&&(a=Object.fromEntries((await pn(this.getSubgraphsAsync())).filter(c=>QN(c[1]))));function o(c,u,l,d=!1){if(u==="__end__"&&i.__end__===void 0&&(i[We]=r.addNode({schema:Br.any()},We)),n[c]!==void 0){if(i[u]===void 0)throw new Error(`End node ${u} not found!`);return r.addEdge(n[c],i[u],l!==u?l:void 0,d)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=Ut(c),d=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let p=typeof t=="number"?t-1:t,m=a[c]!==void 0?await a[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let S=function(x){return x?x.lc_runnable:!1},w=function(x,$){if(x!==void 0&&!Co(x))return x;if(S($))try{let T=$.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return $.getName()}else return $.name??"UnknownSchema"},[g,v]=r.extend(m,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);v!==void 0&&(n[l]={name:w(v.id,v.data),...v}),i[l]={name:w(g.id,g.data),...g}}else{let g=r.addNode(d,l,f);n[l]=g,i[l]=g}}else{let p=r.addNode(d,l,f);n[l]=p,i[l]=p}}let s=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of s)o(Ut(c),Ut(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[Ut(d),Ut(d)])),[We]:We};for(let d of Object.values(u)){let f;d.ends!==void 0?f=d.ends:f=l;for(let[p,m]of Object.entries(f))o(Ut(c),Ut(m),p,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)o(Ut(c),Ut(l),void 0,!0);return r}getGraph(e){let t=e?.xray,r=new lo,n={[Fe]:r.addNode({schema:Br.any()},Fe)},i={},a={};t&&(a=Object.fromEntries(vo(this.getSubgraphs()).filter(c=>QN(c[1]))));function o(c,u,l,d=!1){return u==="__end__"&&i.__end__===void 0&&(i[We]=r.addNode({schema:Br.any()},We)),r.addEdge(n[c],i[u],l!==u?l:void 0,d)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=Ut(c),d=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let p=typeof t=="number"?t-1:t,m=a[c]!==void 0?a[c].getGraph({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let S=function(x){return x?x.lc_runnable:!1},w=function(x,$){if(x!==void 0&&!Co(x))return x;if(S($))try{let T=$.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return $.getName()}else return $.name??"UnknownSchema"},[g,v]=r.extend(m,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);v!==void 0&&(n[l]={name:w(v.id,v.data),...v}),i[l]={name:w(g.id,g.data),...g}}else{let g=r.addNode(d,l,f);n[l]=g,i[l]=g}}else{let p=r.addNode(d,l,f);n[l]=p,i[l]=p}}let s=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of s)o(Ut(c),Ut(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[Ut(d),Ut(d)])),[We]:We};for(let d of Object.values(u)){let f;d.ends!==void 0?f=d.ends:f=l;for(let[p,m]of Object.entries(f))o(Ut(c),Ut(m),p,!0)}}return r}};function QN(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function Ut(e){return e==="subgraph"?`"${e}"`:e}function wi(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function j0(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function gB(e){return wi(e)&&j0(e)}function oa(e){if(j0(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function sa(e){if(e!=null&&wi(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 z0=Symbol.for("langgraph.channel.missing"),Jm=class eR extends wt{lc_graph_name="UntrackedValue";guard;_value=z0;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new eR({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new ye("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===z0)throw new Ae;return this._value}checkpoint(){}isAvailable(){return this._value!==z0}};var ca=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),D0=class tR extends wt{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new tR(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 ye(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!ca(this.names,this.seen))throw new Ae}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&ca(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&ca(this.names,this.seen)}},U0=class rR extends wt{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 rR(this.names);if(typeof t<"u"){let[n,i]=t;r.seen=new Set(n),r.finished=i}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 ye(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!ca(this.names,this.seen))throw new Ae}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&ca(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&ca(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&ca(this.names,this.seen)}};var L0=Symbol.for("langgraph.state.reduced_value"),xi=class{[L0]=!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&&L0 in e&&e[L0]===!0}};var nR=Symbol.for("langgraph.state.untracked_value"),xo=class{[nR]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&nR in e}};var F0=Symbol.for("langgraph.state.state_schema"),Hn=class{[F0]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(xi.isInstance(r)){let n=sa(r.valueSchema);e[t]=new gi(r.reducer,n)}else if(xo.isInstance(r)){let n=r.schema?sa(r.schema):void 0;e[t]=new Jm({guard:r.guard,initialValueFactory:n})}else if(wi(r))e[t]=new fn(sa(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let i;if(xi.isInstance(n)?(i=oa(n.valueSchema),n.jsonSchemaExtra&&(i={...i??{},...n.jsonSchemaExtra})):xo.isInstance(n)?i=n.schema?oa(n.schema):void 0:wi(n)&&(i=oa(n)),i){e[r]=i;let a=!1;xi.isInstance(n)?a=sa(n.valueSchema)!==void 0:xo.isInstance(n)?a=n.schema?sa(n.schema)!==void 0:!1:a=sa(n)!==void 0,a||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;xi.isInstance(r)?(n=oa(r.inputSchema),r.jsonSchemaExtra&&(n={...n??{},...r.jsonSchemaExtra})):xo.isInstance(r)?n=r.schema?oa(r.schema):void 0:wi(r)&&(n=oa(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 i=this.fields[r];if(i===void 0){t[r]=n;continue}let a;if(xi.isInstance(i)?a=i.inputSchema:xo.isInstance(i)?a=i.schema:wi(i)&&(a=i),a){let o=await a["~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&&F0 in e&&e[F0]===!0}};var _B="__remove_all__";function ua(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],i=r.map(St),a=n.map(St);for(let l of i)(l.id===null||l.id===void 0)&&(l.id=xl(),l.lc_kwargs.id=l.id);let o;for(let l=0;l<a.length;l+=1){let d=a[l];(d.id===null||d.id===void 0)&&(d.id=xl(),d.lc_kwargs.id=d.id),Xr.isInstance(d)&&d.id==="__remove_all__"&&(o=l)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((l,d)=>[l.id,d])),u=new Set;for(let l of a){let d=c.get(l.id);if(d!==void 0)Xr.isInstance(l)?u.add(l.id):(u.delete(l.id),s[d]=l);else{if(Xr.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,s.length),s.push(l)}}return s.filter(l=>!u.has(l.id))}var yB=new xi(Br.custom().default(()=>[]),{inputSchema:Br.custom(),reducer:ua,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var vB=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=Ja(e);for(let[n,i]of Object.entries(r)){let a=this.get(i);a?.reducer?t[n]=new gi(a.reducer.fn,a.default):t[n]=new fn(a?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,a])=>a===!0).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>`${a}:${o}`).join("|"),n=this._extensionCache.get(r)??new Map;if(n.has(e))return n.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let a=Object.entries(Ja(e)).map(([o,s])=>{let c=this.get(s),u=t.withReducerSchema?c?.reducer?.schema??s:s;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=si(u)??si(s),d=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`lg:${d}`)}return[o,u]});i=Gf(e,Object.fromEntries(a)),tt(i)&&(i._def.unknownKeys="strip")}return t.asPartial&&(i=$s(i)),n.set(e,i),this._extensionCache.set(r,n),i}},cl=new vB;function iR(e,t){if(t.reducer&&!t.default){let r=Hf(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return cl.extend(r,()=>t),r}else return cl.extend(e,()=>t),e}function So(e){return e==null?!1:!!(Hn.isInstance(e)||Wt(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"||u0(t)))}function aR(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&So(t.state),n="stateSchema"in t&&So(t.stateSchema),i="input"in t&&So(t.input);return!(!r&&!n&&!i||"input"in t&&t.input!=null&&!So(t.input)||"output"in t&&t.output!=null&&!So(t.output))}var Si="__root__",Km=Symbol.for("langgraph.state.partial"),B0=class extends R0{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=cl;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new hc;let i=this._getChannelsFromSchema(n);this._schemaDefinition=i,Hn.isInstance(n)?this._schemaRuntimeDefinition=n:Wt(n)&&(this._schemaRuntimeDefinition=n),r.input?Hn.isInstance(r.input)?this._inputRuntimeDefinition=r.input:Wt(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Km:this._inputRuntimeDefinition=Km,r.output?Hn.isInstance(r.output)?this._outputRuntimeDefinition=r.output:Wt(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=r.input?this._getChannelsFromSchema(r.input):i,o=r.output?this._getChannelsFromSchema(r.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&Wt(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}_normalizeToStateGraphInit(e,t){if(aR(e)){if(Wt(t)||Im.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(So(e)){if(Wt(t)||Im.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(wB(e))return{state:bB(e.channels)};throw new hc}_getChannelsFromSchema(e){if(Hn.isInstance(e))return e.getChannels();if(Wt(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 hc("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,i])=>[n,i]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,i,a]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 l of["|",":"])if(n.includes(l))throw new Error(`"${l}" 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;a?.input!==void 0&&(o=this._getChannelsFromSchema(a.input)),this._addSchema(o);let s;re.isRunnable(i)?s=i:typeof i=="function"?s=new Dt({func:i,name:n,trace:!1}):s=Xe(i);let c=a?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:s,retryPolicy:a?.retryPolicy,cachePolicy:c,metadata:a?.metadata,input:o??this._schemaDefinition,subgraphs:nl(s)?[s]:a?.subgraphs,ends:a?.ends,defer:a?.defer};this.nodes[n]=u}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,i,a]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(o,i,a),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:i,name:a,description:o}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(i)?i:[]]);let s=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=s.length===1&&s[0]===Si?Si:s,u=Object.keys(this.channels),l=u.length===1&&u[0]===Si?Si:u,d=this._interrupt,f=new sR({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Fe]:new gn},inputChannels:Fe,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:r,name:a,description:o,userInterrupt:d});f.attachNode(Fe);for(let[p,m]of Object.entries(this.nodes))f.attachNode(p,m);f.attachBranch(Fe,qm,oR(),{withReader:!1});for(let[p]of Object.entries(this.nodes))f.attachBranch(p,qm,oR(),{withReader:!1});for(let[p,m]of this.edges)f.attachEdge(p,m);for(let[p,m]of this.waitingEdges)f.attachEdge(p,m);for(let[p,m]of Object.entries(this.branches))for(let[g,v]of Object.entries(m))f.attachBranch(p,g,v);return f.validate()}};function bB(e){let t={};for(let[r,n]of Object.entries(e))r===Si?t[r]=Tm(n):t[r]=Tm(n);return t}var sR=class extends M0{description;_metaRegistry=cl;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(([s])=>s):r=Object.keys(this.builder.channels);function n(s){if(ft(s))return s.graph===er.PARENT?null:s._updateAsTuples();if(Array.isArray(s)&&s.length>0&&s.some(c=>ft(c))){let c=[];for(let u of s)if(ft(u)){if(u.graph===er.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([Si,u]);return c}else if(s!=null)return[[Si,s]];return null}let i=e;function a(s){if(s){if(ft(s))return s.graph===er.PARENT?null:s._updateAsTuples().filter(([c])=>r.includes(c));if(Array.isArray(s)&&s.length>0&&s.some(ft)){let c=[];for(let u of s)if(ft(u)){if(u.graph===er.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>r.includes(l)))}else{let l=a(u);l&&c.push(...l??[])}return c}else{if(typeof s=="object"&&!Array.isArray(s))return Object.entries(s).filter(([c])=>r.includes(c));{let c=Array.isArray(s)?"array":typeof s;throw new ye(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let o=[{value:dr,mapper:new Dt({func:r.length&&r[0]===Si?n:a,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new mn({tags:[st],triggers:[Fe],channels:[Fe],writers:[new rt(o,[st])]});else{let s=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(s)).map(d=>[d,d])),u=Object.keys(c).length===1&&Si in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new l0:new gn(!1),this.nodes[e]=new mn({triggers:[l],channels:u?Object.keys(c):c,writers:[new rt(o,[st])],mapper:u?void 0:d=>Object.fromEntries(Object.entries(d).filter(([f])=>f in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new rt([{channel:`branch:to:${t}`,value:null}],[st]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new U0(new Set(e)):new D0(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new rt([{channel:r,value:n}],[st]))}}}attachBranch(e,t,r,n={withReader:!0}){let i=async(a,o)=>{let s=a.filter(u=>u!==We);if(!s.length)return;let c=s.map(u=>ct(u)?u:{channel:u==="__end__"?u:`branch:to:${u}`,value:e});await rt.doWrite({...o,tags:(o.tags??[]).concat([st])},c)};this.nodes[e].writers.push(r.run(i,n.withReader?a=>xN.doRead(a,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(Hn.isInstance(t)){if(ft(e)){let i=e;return e.update&&(i.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await t.validateInput(e)}if(t===Km&&Hn.isInstance(r)){if(ft(e)){let i=e;return e.update&&(i.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await r.validateInput(e)}let n=(()=>{let i=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(Wt(t))return i(t);if(t===Km)return Wt(r)?$s(i(r)):void 0})();if(ft(e)){let i=e;return e.update&&n!=null&&(i.update=Ss(n,e.update)),i}return n!=null?Ss(n,e):e}isInterrupted(e){return mc(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Wt(t)&&Ss(t,e),e}};function wB(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function xB(e){if(ct(e))return[e];let t=[];ft(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(ft));let r=[];for(let n of t){if(n.graph===er.PARENT)throw new gl(n);ct(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function oR(){return new N0({path:new Dt({func:xB,tags:[st],trace:!1,recurse:!1,name:"<control_branch>"})})}var SB=class extends B0{constructor(){super({channels:{__root__:{reducer:ua,default:()=>[]}}})}};function kB(e,t){let{stateKey:r,...n}=t??{},i=tc(n),a=r??"messages";r===null&&(a=void 0);let o=St(e);if(!o.id)throw new Error("Message ID is required.");let s=(Array.isArray(i.callbacks)?i.callbacks:typeof i.callbacks<"u"?i.callbacks.handlers:[]).find(c=>"name"in c&&c.name==="StreamMessagesHandler");if(s){let c=i.metadata??{},u=(c.langgraph_checkpoint_ns??"").split("|");s._emit([u,c],o,void 0,!1)}return a&&i.configurable?.__pregel_send?.([[a,o]]),o}function $B(e,t){let r=typeof e=="string"?{name:e,retry:void 0,cachePolicy:void 0}:e,{name:n,retry:i}=r;if(g0(t)||_0(t))throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");let a=r.cachePolicy??("cache"in r?r.cache:void 0),o;return typeof a=="boolean"?o=a?{}:void 0:o=a,(...s)=>PN({func:t,name:n,retry:i,cache:o},...s)}var cR=function(t,r){let{name:n,checkpointer:i,store:a,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t;if(g0(r)||_0(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let s="updates",c=ON(n,r);function u(p){return typeof p=="object"&&p!==null&&"__lg_type"in p&&p.__lg_type==="__pregel_final"}let l=new Dt({name:"pluckReturnValue",func:p=>u(p)?p.value:p}),d=new Dt({name:"pluckSaveValue",func:p=>u(p)?p.save:p}),f=new mn({bound:c,triggers:[Fe],channels:[Fe],writers:[new rt([{channel:We,value:dr,mapper:l},{channel:ga,value:dr,mapper:d}],[st])]});return new Hm({name:n,checkpointer:i,nodes:{[n]:f},channels:{[Fe]:new gn,[We]:new fn,[ga]:new fn},inputChannels:Fe,outputChannels:We,streamChannels:We,streamMode:s,store:a,cache:o})};cR.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};function EB(){return $e.getRunnableConfig().configurable?.[ha]}var IB=tl.Root({messages:tl({reducer:ua,default:()=>[]})}),uR={reducer:{fn:ua},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},TB=bt.object({messages:iR(bt.custom(),uR)});function AB(e){let t=$e.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{Fe as a,We as b,Be as c,Wm as d,K0 as e,ma as f,fR as g,mc as h,er as i,ft as j,Jr as k,Xm as l,Ym as m,_a as n,Wn as o,hl as p,gl as q,Qm as r,ya as s,qn as t,_l as u,Ae as v,ye as w,pR as x,eh as y,mR as z,hc as A,hR as B,ES as C,Ft as D,JR as E,kn as F,jS as G,vc as H,zS as I,je as J,Zt as K,jo as L,zo as M,Ie as N,Uo as O,mt as P,qr as Q,wa as R,Sa as S,ka as T,Vt as U,ei as V,Ik as W,$e as X,yt as Y,vt as Z,ve as _,_r as $,ut as aa,Ri as ba,zi as ca,ja as da,Zi as ea,ff as fa,Ga as ga,De as ha,tt as ia,or as ja,Vf as ka,Ss as la,si as ma,Wt as na,Ja as oa,$s as pa,Hf as qa,FT as ra,D as sa,bt as ta,ip as ua,ht as va,re as wa,Ur as xa,Sr as ya,Rt as za,VL as Aa,bu as Ba,bp as Ca,dw as Da,oO as Ea,sO as Fa,WL as Ga,qL as Ha,pw as Ia,ta as Ja,Tw as Ka,Bs as La,ju as Ma,Br as Na,B6 as Oa,eF as Pa,Ys as Qa,ln as Ra,Sm as Sa,aN as Ta,ec as Ua,$m as Va,cN as Wa,wt as Xa,gi as Ya,tl as Za,AF as _a,CF as $a,d0 as ab,OF as bb,h0 as cb,R0 as db,wi as eb,gB as fb,oa as gb,sa as hb,Jm as ib,xi as jb,xo as kb,Hn as lb,_B as mb,ua as nb,yB as ob,cl as pb,iR as qb,B0 as rb,sR as sb,SB as tb,kB as ub,$B as vb,cR as wb,EB as xb,IB as yb,uR as zb,TB as Ab,AB as Bb};
397
+ `),{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}},M0=class extends Hm{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new gn,this.nodes[e]=new mn({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new rt([{channel:e,value:dr}],[st])),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 rt([{channel:We,value:dr}],[st]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[Fe]=XN.subscribeTo(Fe,{tags:[st]})),this.nodes[e].pipe(r.run(i=>new rt(i.map(a=>ct(a)?a:{channel:a==="__end__"?We:`branch:${e}:${t}:${a}`,value:dr}),[st])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let i of n)if(i!=="__end__"){let a=`branch:${e}:${t}:${i}`;this.channels[a]=new gn,this.nodes[i].triggers.push(a),this.nodes[i].channels.push(a)}}async getGraphAsync(e){let t=e?.xray,r=new lo,n={[Fe]:r.addNode({schema:Br.any()},Fe)},i={},a={};t&&(a=Object.fromEntries((await pn(this.getSubgraphsAsync())).filter(c=>QN(c[1]))));function o(c,u,l,d=!1){if(u==="__end__"&&i.__end__===void 0&&(i[We]=r.addNode({schema:Br.any()},We)),n[c]!==void 0){if(i[u]===void 0)throw new Error(`End node ${u} not found!`);return r.addEdge(n[c],i[u],l!==u?l:void 0,d)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=Ut(c),d=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let p=typeof t=="number"?t-1:t,m=a[c]!==void 0?await a[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let S=function(x){return x?x.lc_runnable:!1},w=function(x,$){if(x!==void 0&&!Co(x))return x;if(S($))try{let T=$.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return $.getName()}else return $.name??"UnknownSchema"},[g,v]=r.extend(m,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);v!==void 0&&(n[l]={name:w(v.id,v.data),...v}),i[l]={name:w(g.id,g.data),...g}}else{let g=r.addNode(d,l,f);n[l]=g,i[l]=g}}else{let p=r.addNode(d,l,f);n[l]=p,i[l]=p}}let s=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of s)o(Ut(c),Ut(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[Ut(d),Ut(d)])),[We]:We};for(let d of Object.values(u)){let f;d.ends!==void 0?f=d.ends:f=l;for(let[p,m]of Object.entries(f))o(Ut(c),Ut(m),p,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)o(Ut(c),Ut(l),void 0,!0);return r}getGraph(e){let t=e?.xray,r=new lo,n={[Fe]:r.addNode({schema:Br.any()},Fe)},i={},a={};t&&(a=Object.fromEntries(vo(this.getSubgraphs()).filter(c=>QN(c[1]))));function o(c,u,l,d=!1){return u==="__end__"&&i.__end__===void 0&&(i[We]=r.addNode({schema:Br.any()},We)),r.addEdge(n[c],i[u],l!==u?l:void 0,d)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=Ut(c),d=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let p=typeof t=="number"?t-1:t,m=a[c]!==void 0?a[c].getGraph({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let S=function(x){return x?x.lc_runnable:!1},w=function(x,$){if(x!==void 0&&!Co(x))return x;if(S($))try{let T=$.getName();return T=T.startsWith("Runnable")?T.slice(8):T,T}catch{return $.getName()}else return $.name??"UnknownSchema"},[g,v]=r.extend(m,l);if(g===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);v!==void 0&&(n[l]={name:w(v.id,v.data),...v}),i[l]={name:w(g.id,g.data),...g}}else{let g=r.addNode(d,l,f);n[l]=g,i[l]=g}}else{let p=r.addNode(d,l,f);n[l]=p,i[l]=p}}let s=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of s)o(Ut(c),Ut(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(d=>d!==c).map(d=>[Ut(d),Ut(d)])),[We]:We};for(let d of Object.values(u)){let f;d.ends!==void 0?f=d.ends:f=l;for(let[p,m]of Object.entries(f))o(Ut(c),Ut(m),p,!0)}}return r}};function QN(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function Ut(e){return e==="subgraph"?`"${e}"`:e}function wi(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function j0(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function gB(e){return wi(e)&&j0(e)}function oa(e){if(j0(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function sa(e){if(e!=null&&wi(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 z0=Symbol.for("langgraph.channel.missing"),Jm=class eR extends wt{lc_graph_name="UntrackedValue";guard;_value=z0;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new eR({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new ye("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===z0)throw new Ae;return this._value}checkpoint(){}isAvailable(){return this._value!==z0}};var ca=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),D0=class tR extends wt{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new tR(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 ye(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!ca(this.names,this.seen))throw new Ae}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&ca(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&ca(this.names,this.seen)}},U0=class rR extends wt{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 rR(this.names);if(typeof t<"u"){let[n,i]=t;r.seen=new Set(n),r.finished=i}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 ye(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!ca(this.names,this.seen))throw new Ae}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&ca(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&ca(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&ca(this.names,this.seen)}};var L0=Symbol.for("langgraph.state.reduced_value"),xi=class{[L0]=!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&&L0 in e&&e[L0]===!0}};var nR=Symbol.for("langgraph.state.untracked_value"),xo=class{[nR]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&nR in e}};var F0=Symbol.for("langgraph.state.state_schema"),Hn=class{[F0]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(xi.isInstance(r)){let n=sa(r.valueSchema);e[t]=new gi(r.reducer,n)}else if(xo.isInstance(r)){let n=r.schema?sa(r.schema):void 0;e[t]=new Jm({guard:r.guard,initialValueFactory:n})}else if(wi(r))e[t]=new fn(sa(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let i;if(xi.isInstance(n)?(i=oa(n.valueSchema),n.jsonSchemaExtra&&(i={...i??{},...n.jsonSchemaExtra})):xo.isInstance(n)?i=n.schema?oa(n.schema):void 0:wi(n)&&(i=oa(n)),i){e[r]=i;let a=!1;xi.isInstance(n)?a=sa(n.valueSchema)!==void 0:xo.isInstance(n)?a=n.schema?sa(n.schema)!==void 0:!1:a=sa(n)!==void 0,a||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;xi.isInstance(r)?(n=oa(r.inputSchema),r.jsonSchemaExtra&&(n={...n??{},...r.jsonSchemaExtra})):xo.isInstance(r)?n=r.schema?oa(r.schema):void 0:wi(r)&&(n=oa(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 i=this.fields[r];if(i===void 0){t[r]=n;continue}let a;if(xi.isInstance(i)?a=i.inputSchema:xo.isInstance(i)?a=i.schema:wi(i)&&(a=i),a){let o=await a["~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&&F0 in e&&e[F0]===!0}};var _B="__remove_all__";function ua(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],i=r.map(St),a=n.map(St);for(let l of i)(l.id===null||l.id===void 0)&&(l.id=xl(),l.lc_kwargs.id=l.id);let o;for(let l=0;l<a.length;l+=1){let d=a[l];(d.id===null||d.id===void 0)&&(d.id=xl(),d.lc_kwargs.id=d.id),Xr.isInstance(d)&&d.id==="__remove_all__"&&(o=l)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((l,d)=>[l.id,d])),u=new Set;for(let l of a){let d=c.get(l.id);if(d!==void 0)Xr.isInstance(l)?u.add(l.id):(u.delete(l.id),s[d]=l);else{if(Xr.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,s.length),s.push(l)}}return s.filter(l=>!u.has(l.id))}var yB=new xi(Br.custom().default(()=>[]),{inputSchema:Br.custom(),reducer:ua,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var vB=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=Ja(e);for(let[n,i]of Object.entries(r)){let a=this.get(i);a?.reducer?t[n]=new gi(a.reducer.fn,a.default):t[n]=new fn(a?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,a])=>a===!0).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>`${a}:${o}`).join("|"),n=this._extensionCache.get(r)??new Map;if(n.has(e))return n.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let a=Object.entries(Ja(e)).map(([o,s])=>{let c=this.get(s),u=t.withReducerSchema?c?.reducer?.schema??s:s;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=si(u)??si(s),d=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`lg:${d}`)}return[o,u]});i=Gf(e,Object.fromEntries(a)),tt(i)&&(i._def.unknownKeys="strip")}return t.asPartial&&(i=$s(i)),n.set(e,i),this._extensionCache.set(r,n),i}},cl=new vB;function iR(e,t){if(t.reducer&&!t.default){let r=Hf(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return cl.extend(r,()=>t),r}else return cl.extend(e,()=>t),e}function So(e){return e==null?!1:!!(Hn.isInstance(e)||Wt(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"||u0(t)))}function aR(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&So(t.state),n="stateSchema"in t&&So(t.stateSchema),i="input"in t&&So(t.input);return!(!r&&!n&&!i||"input"in t&&t.input!=null&&!So(t.input)||"output"in t&&t.output!=null&&!So(t.output))}var Si="__root__",Km=Symbol.for("langgraph.state.partial"),B0=class extends R0{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=cl;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new hc;let i=this._getChannelsFromSchema(n);this._schemaDefinition=i,Hn.isInstance(n)?this._schemaRuntimeDefinition=n:Wt(n)&&(this._schemaRuntimeDefinition=n),r.input?Hn.isInstance(r.input)?this._inputRuntimeDefinition=r.input:Wt(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Km:this._inputRuntimeDefinition=Km,r.output?Hn.isInstance(r.output)?this._outputRuntimeDefinition=r.output:Wt(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=r.input?this._getChannelsFromSchema(r.input):i,o=r.output?this._getChannelsFromSchema(r.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&Wt(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}_normalizeToStateGraphInit(e,t){if(aR(e)){if(Wt(t)||Im.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(So(e)){if(Wt(t)||Im.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(wB(e))return{state:bB(e.channels)};throw new hc}_getChannelsFromSchema(e){if(Hn.isInstance(e))return e.getChannels();if(Wt(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 hc("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,i])=>[n,i]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,i,a]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 l of["|",":"])if(n.includes(l))throw new Error(`"${l}" 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;a?.input!==void 0&&(o=this._getChannelsFromSchema(a.input)),this._addSchema(o);let s;re.isRunnable(i)?s=i:typeof i=="function"?s=new Dt({func:i,name:n,trace:!1}):s=Xe(i);let c=a?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:s,retryPolicy:a?.retryPolicy,cachePolicy:c,metadata:a?.metadata,input:o??this._schemaDefinition,subgraphs:nl(s)?[s]:a?.subgraphs,ends:a?.ends,defer:a?.defer};this.nodes[n]=u}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,i,a]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(o,i,a),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:i,name:a,description:o}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(i)?i:[]]);let s=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=s.length===1&&s[0]===Si?Si:s,u=Object.keys(this.channels),l=u.length===1&&u[0]===Si?Si:u,d=this._interrupt,f=new sR({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Fe]:new gn},inputChannels:Fe,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:r,name:a,description:o,userInterrupt:d});f.attachNode(Fe);for(let[p,m]of Object.entries(this.nodes))f.attachNode(p,m);f.attachBranch(Fe,qm,oR(),{withReader:!1});for(let[p]of Object.entries(this.nodes))f.attachBranch(p,qm,oR(),{withReader:!1});for(let[p,m]of this.edges)f.attachEdge(p,m);for(let[p,m]of this.waitingEdges)f.attachEdge(p,m);for(let[p,m]of Object.entries(this.branches))for(let[g,v]of Object.entries(m))f.attachBranch(p,g,v);return f.validate()}};function bB(e){let t={};for(let[r,n]of Object.entries(e))r===Si?t[r]=Tm(n):t[r]=Tm(n);return t}var sR=class extends M0{description;_metaRegistry=cl;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(([s])=>s):r=Object.keys(this.builder.channels);function n(s){if(ft(s))return s.graph===er.PARENT?null:s._updateAsTuples();if(Array.isArray(s)&&s.length>0&&s.some(c=>ft(c))){let c=[];for(let u of s)if(ft(u)){if(u.graph===er.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([Si,u]);return c}else if(s!=null)return[[Si,s]];return null}let i=e;function a(s){if(s){if(ft(s))return s.graph===er.PARENT?null:s._updateAsTuples().filter(([c])=>r.includes(c));if(Array.isArray(s)&&s.length>0&&s.some(ft)){let c=[];for(let u of s)if(ft(u)){if(u.graph===er.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>r.includes(l)))}else{let l=a(u);l&&c.push(...l??[])}return c}else{if(typeof s=="object"&&!Array.isArray(s))return Object.entries(s).filter(([c])=>r.includes(c));{let c=Array.isArray(s)?"array":typeof s;throw new ye(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let o=[{value:dr,mapper:new Dt({func:r.length&&r[0]===Si?n:a,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new mn({tags:[st],triggers:[Fe],channels:[Fe],writers:[new rt(o,[st])]});else{let s=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(s)).map(d=>[d,d])),u=Object.keys(c).length===1&&Si in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new l0:new gn(!1),this.nodes[e]=new mn({triggers:[l],channels:u?Object.keys(c):c,writers:[new rt(o,[st])],mapper:u?void 0:d=>Object.fromEntries(Object.entries(d).filter(([f])=>f in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new rt([{channel:`branch:to:${t}`,value:null}],[st]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new U0(new Set(e)):new D0(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new rt([{channel:r,value:n}],[st]))}}}attachBranch(e,t,r,n={withReader:!0}){let i=async(a,o)=>{let s=a.filter(u=>u!==We);if(!s.length)return;let c=s.map(u=>ct(u)?u:{channel:u==="__end__"?u:`branch:to:${u}`,value:e});await rt.doWrite({...o,tags:(o.tags??[]).concat([st])},c)};this.nodes[e].writers.push(r.run(i,n.withReader?a=>xN.doRead(a,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(Hn.isInstance(t)){if(ft(e)){let i=e;return e.update&&(i.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await t.validateInput(e)}if(t===Km&&Hn.isInstance(r)){if(ft(e)){let i=e;return e.update&&(i.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await r.validateInput(e)}let n=(()=>{let i=a=>{if(a!=null)return this._metaRegistry.getExtendedChannelSchemas(a,{withReducerSchema:!0})};if(Wt(t))return i(t);if(t===Km)return Wt(r)?$s(i(r)):void 0})();if(ft(e)){let i=e;return e.update&&n!=null&&(i.update=Ss(n,e.update)),i}return n!=null?Ss(n,e):e}isInterrupted(e){return mc(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Wt(t)&&Ss(t,e),e}};function wB(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function xB(e){if(ct(e))return[e];let t=[];ft(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(ft));let r=[];for(let n of t){if(n.graph===er.PARENT)throw new gl(n);ct(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function oR(){return new N0({path:new Dt({func:xB,tags:[st],trace:!1,recurse:!1,name:"<control_branch>"})})}var SB=class extends B0{constructor(){super({channels:{__root__:{reducer:ua,default:()=>[]}}})}};function kB(e,t){let{stateKey:r,...n}=t??{},i=tc(n),a=r??"messages";r===null&&(a=void 0);let o=St(e);if(!o.id)throw new Error("Message ID is required.");let s=(Array.isArray(i.callbacks)?i.callbacks:typeof i.callbacks<"u"?i.callbacks.handlers:[]).find(c=>"name"in c&&c.name==="StreamMessagesHandler");if(s){let c=i.metadata??{},u=(c.langgraph_checkpoint_ns??"").split("|");s._emit([u,c],o,void 0,!1)}return a&&i.configurable?.__pregel_send?.([[a,o]]),o}function $B(e,t){let r=typeof e=="string"?{name:e,retry:void 0,cachePolicy:void 0}:e,{name:n,retry:i}=r;if(g0(t)||_0(t))throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");let a=r.cachePolicy??("cache"in r?r.cache:void 0),o;return typeof a=="boolean"?o=a?{}:void 0:o=a,(...s)=>PN({func:t,name:n,retry:i,cache:o},...s)}var cR=function(t,r){let{name:n,checkpointer:i,store:a,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t;if(g0(r)||_0(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let s="updates",c=ON(n,r);function u(p){return typeof p=="object"&&p!==null&&"__lg_type"in p&&p.__lg_type==="__pregel_final"}let l=new Dt({name:"pluckReturnValue",func:p=>u(p)?p.value:p}),d=new Dt({name:"pluckSaveValue",func:p=>u(p)?p.save:p}),f=new mn({bound:c,triggers:[Fe],channels:[Fe],writers:[new rt([{channel:We,value:dr,mapper:l},{channel:ga,value:dr,mapper:d}],[st])]});return new Hm({name:n,checkpointer:i,nodes:{[n]:f},channels:{[Fe]:new gn,[We]:new fn,[ga]:new fn},inputChannels:Fe,outputChannels:We,streamChannels:We,streamMode:s,store:a,cache:o})};cR.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};function EB(){return $e.getRunnableConfig().configurable?.[ha]}var IB=tl.Root({messages:tl({reducer:ua,default:()=>[]})}),uR={reducer:{fn:ua},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},TB=bt.object({messages:iR(bt.custom(),uR)});function AB(e){let t=$e.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{Fe as a,We as b,Be as c,Wm as d,K0 as e,ma as f,ct as g,fR as h,mc as i,er as j,ft as k,Jr as l,Xm as m,Ym as n,_a as o,Wn as p,hl as q,gl as r,Qm as s,ya as t,qn as u,_l as v,Ae as w,ye as x,pR as y,eh as z,mR as A,hc as B,hR as C,ES as D,Ft as E,JR as F,kn as G,jS as H,vc as I,zS as J,je as K,Je as L,Zt as M,jo as N,zo as O,Ie as P,Uo as Q,mt as R,qr as S,wa as T,Sa as U,ka as V,Vt as W,ei as X,Ik as Y,$e as Z,yt as _,vt as $,ve as aa,_r as ba,ut as ca,Ri as da,zi as ea,ja as fa,Zi as ga,ff as ha,Ga as ia,De as ja,tt as ka,or as la,Vf as ma,Ss as na,si as oa,Wt as pa,Ja as qa,$s as ra,Hf as sa,FT as ta,D as ua,bt as va,ip as wa,ht as xa,re as ya,Ur as za,Sr as Aa,Rt as Ba,VL as Ca,bu as Da,bp as Ea,dw as Fa,oO as Ga,sO as Ha,WL as Ia,qL as Ja,pw as Ka,ta as La,Tw as Ma,Bs as Na,ju as Oa,Br as Pa,B6 as Qa,eF as Ra,Ys as Sa,ln as Ta,Sm as Ua,aN as Va,ec as Wa,$m as Xa,cN as Ya,wt as Za,gi as _a,tl as $a,AF as ab,CF as bb,d0 as cb,OF as db,h0 as eb,Dt as fb,R0 as gb,wi as hb,gB as ib,oa as jb,sa as kb,Jm as lb,xi as mb,xo as nb,Hn as ob,_B as pb,ua as qb,yB as rb,cl as sb,iR as tb,B0 as ub,sR as vb,SB as wb,kB as xb,$B as yb,cR as zb,EB as Ab,IB as Bb,uR as Cb,TB as Db,AB as Eb};
@@ -0,0 +1,31 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import"./CFDTXKJ6.js";var e=`# ArcgisKnowledge Tool Instructions
3
+
4
+ You are an assistant that helps users answer questions and perform operations on their knowledge graph, map or link chart. You have been assigned the task below, which must be achieved by calling a single tool.
5
+
6
+ ## Task Details:
7
+
8
+ Assigned task:
9
+ {assignedTask}
10
+
11
+ User Request:
12
+ {userRequest}
13
+
14
+ Prior steps:
15
+ {priorSteps}
16
+
17
+ Context type:
18
+ {contextType}
19
+
20
+ ## Rules:
21
+
22
+ 1. Use the provided context type above for the following rule. If the context type is a map, you may never call any of the following arcgisKnowledge tools: changeNonspatialVisibility, applyLayout, createLinkChart.
23
+
24
+ 2. Use the provided context type above for the following rule. If the context type is a knowledgeGraph, you may never call any of the following arcgisKnowledge tools: changeNonspatialVisibility, applyLayout, createLinkChart, addRecords.
25
+
26
+ 3. If no tools apply to the assigned task, return zero tool calls and an empty message.
27
+
28
+ 4. If a tool is found for the assigned task, call exactly one arcgisKnowledge tool, with the appropriate arguments given the assigned task. Use the provided user request or prior steps only if needed for context based on the assigned task.
29
+
30
+ 5. CRITICAL: You are FORBIDDEN from making multiple tool calls. You MUST make exactly ONE tool call or ZERO tool calls.
31
+ `;export{e as default};
@@ -0,0 +1,43 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import"./CFDTXKJ6.js";var e=`## Navigation Agent - Tool Intent Classifier
3
+
4
+ You are an assistant that classifies the assigned task intent for navigation agent.
5
+
6
+ You are given the following tool options:
7
+ {tools}
8
+
9
+ Bookmarks: {bookmarks}
10
+
11
+ Assigned task:
12
+ {assignedTask}
13
+
14
+ Latest user request:
15
+ {userRequest}
16
+
17
+ Prior steps:
18
+ {priorSteps}
19
+
20
+ Use the assigned task as the primary instruction for the current query. The question will **not** be restated again here.
21
+ Use the latest user request as supporting context when needed.
22
+ Use prior steps only when the assigned task clearly depends on earlier results.
23
+
24
+ Return exactly one intent (tool name) based on the assigned task.
25
+ If none apply, return an **empty string**.
26
+
27
+ Choose only from provided tools.
28
+
29
+ ## Note:
30
+
31
+ This is the order of preference in case of overlap:
32
+
33
+ 1. Bookmark (if exists)
34
+ 2. Feature (if exists)
35
+ 3. Geocode / Address
36
+
37
+ For example, "Where is Yosemite National Park". This is an address, but:
38
+ A map that contains a bookmark with Yosemite National Park should prefer the bookmark.
39
+ A map that has the National Parks layer, for example, should prefer the feature.
40
+ If these do not exist, geocode and go to that address.
41
+
42
+ Return the name of the tool as a string.
43
+ `;export{e as default};