@arcgis/ai-components 5.1.0-next.20 → 5.1.0-next.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import b from"./E77IJ3SU.js";import a from"./EH66ASBE.js";import{a as e,b as i}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as s,z as r}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{e:a}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=e(this,"arcgis-assistant-layer-styling-agent"),i(this)}};r("arcgis-assistant-layer-styling-agent",t);return t},a,b)
2
+ import b from"./F2UO6SO4.js";import a from"./PTDPFR7R.js";import{a as e,b as i}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as s,z as r}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{e:a}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=e(this,"arcgis-assistant-layer-styling-agent"),i(this)}};r("arcgis-assistant-layer-styling-agent",t);return t},a,b)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import{a as k}from"./D6OOXTNF.js";import c from"./PTDPFR7R.js";import{a as C}from"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{g as b,h,l as v,n as a,t as u,u as m,v as f,z as w}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([S,{whenOnce:I,watch:L,when:P},O,M,{property:p,subclass:x},{y:E}])=>{var R=b`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%)}`,A=Object.defineProperty,z=Object.getOwnPropertyDescriptor,l=(c,t,e,i)=>{for(var s=i>1?void 0:i?z(t,e):t,r=c.length-1,n;r>=0;r--)(n=c[r])&&(s=(i?n(t,e,s):n(s))||s);return i&&s&&A(t,e,s),s},o=class extends M{constructor(c){super(c),this.view=null,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await I(()=>!this.view.updating),this._set("orchestrator",await E.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([L(()=>[this.view,this.agents],()=>void this._initialize())])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(c,t){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let e=[];try{let i=this.orchestrator.ask(c);for await(let s of i){let r=s.runId;if(t?.aborted){yield{type:"cancelled",runId:r};break}switch(s.type){case"trace":{this._set("processingStep",s.data.text),e.push(s.data.text);break}case"completed":{if(!s.result.content.length){yield{type:"completed",error:"Could not process the request.",log:e,runId:r};return}let n=s.result.content;this._set("processingStep",""),yield{type:"completed",response:n,log:e,runId:r};return}case"interrupt":{let{kind:n,message:g,metadata:_}=s.interrupt,d=Array.isArray(_)?[..._]:[],$=(()=>{switch(n){case"booleanChoice":return{type:"boolean-choice",message:g,options:d};case"singleSelection":return{type:"single-select",message:g,options:d};case"multipleSelection":return{type:"multi-select",message:g,options:d};case"textInput":return{type:"text-input",message:g};default:return{type:n,message:g,options:d}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:$,runId:r};break}case"cancelled":{yield{type:"cancelled",runId:r};return}case"error":{yield{type:"completed",error:s.error.message,log:e,runId:r};return}default:{console.warn("Unknown event type:",s);break}}}}catch(i){console.warn("Error during message processing:",i),yield{type:"completed",error:"An error occurred during message processing.",log:e,runId:"error"};return}finally{this._set("processing",!1)}}};l([p({readOnly:!0})],o.prototype,"orchestrator",2);l([p()],o.prototype,"agents",2);l([p()],o.prototype,"portal",2);l([p()],o.prototype,"view",2);l([p({readOnly:!0})],o.prototype,"loading",2);l([p({readOnly:!0})],o.prototype,"processing",2);l([p({readOnly:!0})],o.prototype,"processingStep",2);o=l([x("OrchestratorController")],o);var H="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",j="Embeddings not found for this web map.",F="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",y=class extends f{constructor(){super(...arguments),this._messages=k({blocking:!0}),this.#t=u(),this.#e=u(),this.#s=null,this.#a=new Map,this.#r=O.getDefault(),this.#i=t=>{t.stopPropagation(),this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null},this.#o=t=>{t.stopPropagation();let e=t.detail;this.arcgisInterruptSubmit.emit(e),this.orchestrator?.resumeInterrupt(e),this._interrupt=null},this.#n=t=>{t.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let e=t.detail;this.arcgisSubmit.emit(e),this.submitMessage(e)},this.#l=t=>{if(t.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this.#s?.abort()},this.#c=t=>{t.stopPropagation();let e=t.detail;this.arcgisFeedback.emit(e)},this._orchestratorController=null,this._interrupt=null,this._error=null,this.messages=new S([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.logEnabled=!1,this.copyEnabled=!1,this.arcgisCancel=a(),this.arcgisError=a(),this.arcgisFeedback=a(),this.arcgisInterrupt=a(),this.arcgisInterruptCancel=a(),this.arcgisInterruptSubmit=a(),this.arcgisReady=a(),this.arcgisSubmit=a()}static{this.properties={_orchestratorController:16,_interrupt:16,_error:16,_user:16,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,logEnabled:5,copyEnabled:5}}static{this.styles=R}#t;#e;#s;#a;#r;#i;#o;#n;#l;#c;async#h(){try{let t=C(this.el,this.referenceElement);await t?.componentOnReady();let e=[...this.#a.values()];return e.length?(this._orchestratorController=new o({agents:e,portal:this.#r,view:t?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(t){return this._error=t?.message??"Error initializing orchestrator.",v(this)(t),!1}}get _user(){return this.#r?.user?.fullName||this.#r?.user?.username}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}register(t){this.#a.set(t.agent.id,t)}async submitMessage(t){let e=t.trim();if(!e||(this.messages.push({id:Date.now().toString(),role:"user",content:e}),!this._orchestratorController))return;let i=this._orchestratorController.ask(e,this.#s?.signal);for await(let s of i){let r=s.runId;switch(s.type){case"completed":this.messages.push({role:"assistant",content:s.response,log:s.log,error:s.error,id:r});break;case"interrupt":this._interrupt={...s.payload,id:r};break;case"cancelled":this.messages.push({role:"assistant",error:"Request cancelled.",id:r});break}}}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#t.value?.addEventListener("arcgisSubmit",this.#n),this.#t.value?.addEventListener("arcgisCancel",this.#l),this.#t.value?.addEventListener("arcgisFeedback",this.#c);let t=P(()=>!!this._interrupt&&!!this.#e.value,()=>{let e=this.#e.value;e.removeEventListener("arcgisSubmit",this.#o),e.removeEventListener("arcgisCancel",this.#i),e.addEventListener("arcgisSubmit",this.#o,{once:!0}),e.addEventListener("arcgisCancel",this.#i,{once:!0}),this._interrupt&&this.arcgisInterrupt.emit(this._interrupt)});return queueMicrotask(()=>{this.#h().then(e=>{e?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{t.remove(),this.#e.value?.removeEventListener("arcgisSubmit",this.#o),this.#e.value?.removeEventListener("arcgisCancel",this.#i),this.#t.value?.removeEventListener("arcgisSubmit",this.#n),this.#t.value?.removeEventListener("arcgisCancel",this.#l),this.#t.value?.removeEventListener("arcgisFeedback",this.#c),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this.#s?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null}_renderErrorNotice(){return this._error?h`<calcite-notice closable slot=entry-message open kind=danger icon width=full>${this._error===H?h`<div slot=message>${j}</div><calcite-link slot=link .href=${F} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:h`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}render(){return h`<arcgis-assistant-shell .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} .entryMessage=${this.entryMessage} .entryMessageClosed=${this.messages.length>0} .awaitingResponse=${this._orchestratorController?.processing} .suggestedPrompts=${this.suggestedPrompts} .messages=${this.messages} ${m(this.#t)}>${this._renderErrorNotice()}${this._interrupt?h`<arcgis-assistant-interrupt slot=entry-message .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${m(this.#e)}></arcgis-assistant-interrupt>`:null}<arcgis-assistant-chat .loading=${this._orchestratorController?.processing} .loadingMessage=${this._orchestratorController?.processingStep||""} .messages=${this.messages} .user=${this._user} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled}><slot></slot></arcgis-assistant-chat><slot name=header-actions-end slot=header-actions-end></slot>${this.entryMessage?null:h`<slot name=entry-message slot=entry-message></slot>`}<slot name=entry-actions-start slot=entry-actions-start></slot><slot name=footer-content slot=footer-content></slot></arcgis-assistant-shell>`}};w("arcgis-assistant",y);return y},"core/Collection","core/reactiveUtils","portal/Portal","core/Accessor","core/accessorSupport/decorators",c)
@@ -221,14 +221,14 @@ data: ${VG(i.data)}
221
221
 
222
222
  `))};try{for await(let i of e){let[s,o,a]=i,c=a;if(o==="debug"){let u=a;u.type==="checkpoint"&&(c={...u,payload:CM(u.payload)})}o==="checkpoints"&&(c=CM(a)),n({event:s?.length?`${o}|${s.join("|")}`:o,data:c})}}catch(i){n({event:"error",data:ZG(i)})}r.close()}})}var Rg=Symbol.for("INPUT_DONE"),NS=Symbol.for("INPUT_RESUMING"),GG=25;function KG(...e){return new Ng({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 qG=class extends dg{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}},NM=class RM{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if(Ae in this.checkpoint.channel_versions)t=!0;else for(let a in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,a)){t=!0;break}let r=this.config.configurable?.[yi]!==void 0&&this.config.configurable?.[yi],n=this.input===null||this.input===void 0,i=Pt(this.input)&&this.input.resume!=null,s=this.input===NS,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||s||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=IM,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 qG(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?.[nu]!==void 0&&(n=KG(n,r.configurable[nu]));let i=r.configurable?!("checkpoint_id"in r.configurable):!0,s=r.configurable?.[Wr];r.configurable&&s&&(s.subgraphCounter>0&&(r=zr(r,{[Jr]:[r.configurable[Jr],s.subgraphCounter.toString()].join(et)})),s.subgraphCounter+=1);let o=Vn in(r.configurable??{});!o&&r.configurable?.checkpoint_ns!==void 0&&r.configurable?.checkpoint_ns!==""&&(r=zr(r,{checkpoint_ns:"",checkpoint_id:void 0}));let a=r;r.configurable?.[xr]!==void 0&&r.configurable?.[xr]?.[r.configurable?.checkpoint_ns]&&(a=zr(r,{checkpoint_id:r.configurable[xr][r.configurable?.checkpoint_ns]}));let c=r.configurable?.checkpoint_ns?.split(et)??[],u=await t.checkpointer?.getTuple(a)??{config:r,checkpoint:tu(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...r,...u.config,configurable:{checkpoint_ns:"",...r.configurable,...u.config.configurable}};let l=u.parentConfig,p=zn(u.checkpoint),f={...u.metadata},d=u.pendingWrites??[],m=no(t.channelSpecs,p),h=(f.step??0)+1,b=h+(r.recursionLimit??GG)+1,_={...p.channel_versions},y=t.store?new pg(t.store):void 0;return y&&await y.start(),new RM({input:t.input,config:r,checkpointer:t.checkpointer,checkpoint:p,checkpointMetadata:f,checkpointConfig:a,prevCheckpointConfig:l,checkpointNamespace:c,channels:m,isNested:o,manager:t.manager,skipDoneTasks:i,step:h,stop:b,checkpointPreviousVersions:_,checkpointPendingWrites:d,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:n,store:y,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.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(t,r){let n=r;if(n.length===0)return;n.every(([c])=>c in Yp)&&(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 s=n;i&&(s=n.filter(([c])=>{let u=this.channels[c];return!u||u.lc_graph_name!=="UntrackedValue"}).map(([c,u])=>c===Ut&&$t(u)?[c,SM(u,this.channels)]:[c,u])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(c=>c[0]!==t);for(let[c,u]of s)this.checkpointPendingWrites.push([t,c,u]);let o=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??"",[gg]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(o,s,t)),this.tasks&&this._outputWrites(t,n),!r.length||!this.cache||!this.tasks)return;let a=this.tasks[t];a==null||a.cache_key==null||r[0][0]===Ot||r[0][0]===ke||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(t,r,n=!1){let i=this.tasks[t];if(i!==void 0){if(i.config!==void 0&&(i.config.tags??[]).includes(Be))return;if(r.length>0)if(r[0][0]===ke){if(i.path?.[0]===nr&&i.path?.[i.path.length-1]===!0)return;let s=r.filter(o=>o[0]===ke).flatMap(o=>o[1]);this._emit([["updates",{[ke]:s}],["values",{[ke]:s}]])}else r[0][0]!==Ot&&this._emit(Aa(as(gM(this.outputKeys,[[i,r]],n),"updates")));n||this._emit(Aa(as(kM([[i,r]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let t=[],r=([o,a])=>`ns:${o.join(",")}|key:${a}`,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 s=await this.cache.get(n);for(let{key:o,value:a}of s){let c=i[r(o)];c!=null&&(c.writes.push(...a),t.push({task:c,result:a}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:r=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Rg,NS].includes(this.input))await this._first(r);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Ni;if(Object.values(this.tasks).every(i=>i.writes.length>0)){let i=Object.values(this.tasks).flatMap(o=>o.writes);this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let s=await Gn(as(Og(this.outputKeys,i,this.channels),"values"));if(this._emit(s),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),pd(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Ni;this.config.configurable?.[yi]!==void 0&&delete this.config.configurable?.[yi]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=oo(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 Gn(as(AM(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,s,o]of this.checkpointPendingWrites){if(s===Ot||s===ke||s===Nt)continue;let a=Object.values(this.tasks).find(c=>c.id===i);a&&a.writes.push([s,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(pd(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Ni;let n=await Gn(as(TS(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(Ir)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let r=this._suppressInterrupt(t);return(r||t===void 0)&&(this.output=qn(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=Sr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(Aa(as(Og(this.outputKeys,Object.values(this.tasks).flatMap(n=>n.writes),this.channels),"values")))),Ri(t)&&!t.interrupts.length&&this._emit([["updates",{[ke]:[]}],["values",{[ke]:[]}]])),r}async acceptPush(t,r,n){if(this.interruptAfter?.length>0&&pd(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}let i=Cg([nr,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&&pd(this.checkpoint,this.interruptBefore,[i])){this.toInterrupt.push(i);return}this._emit(Aa(as(TS([i]),"tasks"))),this.debug&&Pg(this.step,[i]),this.tasks[i.id]=i,this.skipDoneTasks&&this._matchWrites({[i.id]:i});let s=await this._matchCachedWrites();for(let{task:o}of s)this._outputWrites(o.id,o.writes,!0);return i}_suppressInterrupt(t){return Ri(t)&&!this.isNested}async _first(t){let{configurable:r}=this.config,n=r?.[Wr];if(n&&n.nullResume!==void 0&&this.putWrites(ir,[[Nt,n.nullResume]]),Pt(this.input)){let o=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Ag)&&(this.config.configurable??={},this.config.configurable[iu]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");let a={};for(let[c,u,l]of hM(this.input,this.checkpointPendingWrites))a[c]??=[],a[c].push([u,l]);if(Object.keys(a).length===0)throw new Gd("Received empty Command input");for(let[c,u]of Object.entries(a))this.putWrites(c,u)}let i=(this.checkpointPendingWrites??[]).filter(o=>o[0]===ir).map(o=>o.slice(1));i.length>0&&Sr(this.checkpoint,this.channels,[{name:Bn,writes:i,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let s=Pt(this.input)&&i.length>0;if(this.isResuming||s){for(let a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){let c=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[ke]={...this.checkpoint.versions_seen[ke],[a]:c}}let o=await Gn(as(Og(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=NS;else if(s)await this._putCheckpoint({source:"input"}),this.input=Rg;else{let o=await Gn(Tg(t,this.input));if(o.length>0){let a=oo(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(a).concat([{name:Bn,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Rg}else if(yi in(this.config.configurable??{}))this.input=Rg;else throw new Gd(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=zr(this.config,{[yi]: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,s=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:s,payload:n}])}}_putCheckpoint(t){let r=this.checkpointMetadata===t,n=this.checkpointer!=null&&(this.durability!=="exit"||r),i=s=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??""});let o={...this.checkpoint.channel_versions},a=uu(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:zn(s),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};r||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.[xr]??{}}),this.checkpoint=Ln(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=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??"",[gg]:this.checkpoint.id}),r={};for(let[n,i,s]of this.checkpointPendingWrites)r[n]??=[],r[n].push([i,s]);for(let[n,i]of Object.entries(r))this.checkpointerPromises.push(this.checkpointer.putWrites(t,i,n))}_matchWrites(t){for(let[r,n,i]of this.checkpointPendingWrites){if(n===Ot||n===ke||n===Nt)continue;let s=Object.values(t).find(o=>o.id===r);s&&s.writes.push([n,i])}for(let r of Object.values(t))r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}};function HG(e){return ot(e?.message)}var MM=class extends zi{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&&(Mo(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,s,o,a){o&&(!s||!s.includes(Y1)&&!s.includes("nostream"))&&(this.metadatas[r]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}])}handleLLMNewToken(e,t,r,n,i,s){let o=s?.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(HG(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new nt({content:e}),r))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let r=e.generations?.[0]?.[0];ot(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,s,o,a){if(s!==void 0&&a===s.langgraph_node&&(i===void 0||!i.includes(Be))&&(this.metadatas[r]=[s.langgraph_checkpoint_ns.split("|"),{tags:i,name:a,...s}],typeof t=="object")){for(let c of Object.values(t))if((ot(c)||Di(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let u of c)(ot(u)||Di(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(ot(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(let n of e)ot(n)&&this._emit(r,n,t,!0);else if(e!=null&&typeof e=="object"){for(let n of Object.values(e))if(ot(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(let i of n)ot(i)&&this._emit(r,i,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};var WG=500,JG=2,XG=128e3,YG=3,QG=[400,401,402,403,404,405,406,407,409],e5=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&&QG.includes(+t)||e?.error?.code==="insufficient_quota")};async function RS(e,t,r,n){let i=e.retry_policy??t,s=i!==void 0?i.initialInterval??WG:0,o=0,a,c,{config:u}=e;for(r&&(u=zr(u,r)),u={...u,signal:n};!n?.aborted;){e.writes.splice(0,e.writes.length),a=void 0;try{c=await e.proc.invoke(e.input,u);break}catch(l){if(a=l,a.pregelTaskId=e.id,$_(a)){let d=u?.configurable?.checkpoint_ns,m=a.command;if(m.graph===d){for(let h of e.writers)await h.invoke(m,u);a=void 0;break}else if(m.graph===jr.PARENT){let h=tM(d);a.command=new jr({...a.command,graph:h})}}if(Co(a)||i===void 0||(o+=1,o>=(i.maxAttempts??YG))||!(i.retryOn??e5)(a))break;s=Math.min(i.maxInterval??XG,s*(i.backoffFactor??JG));let p=i.jitter?Math.floor(s+Math.random()*1e3):s;await new Promise(d=>setTimeout(d,p));let f=a.name??a.constructor.unminifiable_name??a.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${o}) after ${f}: ${a}`),u=zr(u,{[yi]:!0})}}return{task:e,result:c,error:a,signalAborted:n?.aborted}}var MS=Symbol.for("promiseAdded");function t5(){let e={next:()=>{},wait:Promise.resolve(MS)};function t(r){e.next=()=>{e.wait=new Promise(t),r(MS)}}return e.wait=new Promise(t),e}var jM=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,s=new Set,o,a=new AbortController,c=a.signal,u=t?AbortSignal.timeout(t):void 0,l=Object.values(this.loop.tasks).filter(m=>m.writes.length===0),{signals:p,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:u,signal:e.signal}),d=this._executeTasksWithRetry(l,{signals:p,retryPolicy:r,maxConcurrency:i});for await(let{task:m,error:h,signalAborted:b}of d)this._commit(m,h),Ri(h)||Co(h)&&!Ri(o)?o=h:h&&(s.size===0||!b)&&(a.abort(),s.add(h));if(f?.(),n?.(this.loop.step,Object.values(this.loop.tasks).map(m=>m.writes).flat()),s.size===1)throw Array.from(s)[0];if(s.size>1)throw new AggregateError(Array.from(s),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Ri(o)||Co(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:r}){let n=this.loop.config.configurable?.[yS]??{},i=n.externalAbortSignal??r,s=t??n.timeoutAbortSignal,{signal:o,dispose:a}=lu(i,s,e),c={externalAbortSignal:i,timeoutAbortSignal:s,composedAbortSignal:o};return this.loop.config=zr(this.loop.config,{[yS]:c}),{signals:c,disposeCombinedSignal:a}}async*_executeTasksWithRetry(e,t){let{retryPolicy:r,maxConcurrency:n,signals:i}=t??{},s=t5(),o={},a={executingTasksMap:o,barrier:s,retryPolicy:r,scheduleTask:async(f,d,m)=>this.loop.acceptPush(f,d,m)};if(i?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,u,l=lu(i?.externalAbortSignal,i?.timeoutAbortSignal),p=l.signal?new Promise((f,d)=>{u=()=>d(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 d=e[c];o[d.id]=RS(d,r,{[nd]:DM?.bind(a,this,d)},i?.composedAbortSignal).catch(m=>({task:d,error:m,signalAborted:i?.composedAbortSignal?.aborted}))}let f=await Promise.race([...Object.values(o),...p?[p]:[],s.wait]);f!==MS&&(yield f,u!=null&&(l.signal?.removeEventListener("abort",u),l.dispose?.()),delete o[f.task.id])}}_commit(e,t){if(t!==void 0)if(Ri(t)){if(t.interrupts.length){let r=t.interrupts.map(i=>[ke,i]),n=e.writes.filter(i=>i[0]===Nt);n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else Co(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[Ot,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(Be))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([id,null]),this.loop.putWrites(e.id,e.writes)}};async function DM(e,t,r,n,i,s={}){let o=t.config?.configurable?.[Wr];if(!o)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let a=o.callCounter;o.callCounter+=1;let c=new vM({func:r,name:n,input:i,cache:s.cache,retry:s.retry,callbacks:s.callbacks}),u=await this.scheduleTask(t,a,c);if(!u)return;let l=this.executingTasksMap[u.id];if(l!==void 0)return l;if(u.writes.length>0){let p=u.writes.filter(([d])=>d===Zn),f=u.writes.filter(([d])=>d===Ot);if(p.length>0){if(p.length===1)return Promise.resolve(p[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(f.length>0){if(f.length===1){let d=f[0][1],m=d instanceof Error?d:new Error(String(d));return Promise.reject(m)}throw new Error(`BUG: multiple errors found for task ${u.name}__${u.id}`)}return}else{let p=RS(u,s.retry,{[nd]:DM.bind(this,e,u)});return this.executingTasksMap[u.id]=p,this.barrier.next(),p.then(({result:f,error:d})=>d?Promise.reject(d):f)}}var ls=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function zM({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:i,interruptAfterNodes:s,interruptBeforeNodes:o}){if(!t)throw new ls("Channels not provided");let a=new Set,c=new Set;for(let[u,l]of Object.entries(e)){if(u===ke)throw new ls(`"Node name ${ke} is reserved"`);if(l.constructor===Kn)l.triggers.forEach(p=>a.add(p));else throw new ls(`Invalid node type ${typeof l}, expected PregelNode`)}for(let u of a)if(!(u in t))throw new ls(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(r)){if(r.every(u=>!a.has(u)))throw new ls(`None of the input channels ${r} are subscribed to by any node`)}else if(!a.has(r))throw new ls(`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 ls(`Output channel '${String(u)}' not in channels`);if(s&&s!=="*"){for(let u of s)if(!(u in e))throw new ls(`Node ${String(u)} not in nodes`)}if(o&&o!=="*"){for(let u of o)if(!(u in e))throw new ls(`Node ${String(u)} not in nodes`)}}function jS(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 DS=class LM extends Lt{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 LM({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 Ve;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function UM(e){let t=Ze.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");if(!r[ft])throw new $o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=r[Wr];n.interruptCounter+=1;let i=n.interruptCounter;if(n.resume.length>0&&i<n.resume.length)return r[bn]?.([[Nt,n.resume]]),n.resume[i];if(n.nullResume!==void 0){if(n.resume.length!==i)throw new Error(`Resume length mismatch: ${n.resume.length} !== ${i}`);let o=n.consumeNullResume();return n.resume.push(o),r[bn]?.([[Nt,n.resume]]),o}let s=r[Jr]?.split(et);throw new Ni([{id:s?us(s.join(et)):void 0,value:e}])}var FM=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(s=>[s,s])),new Kn({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??{}))ue.isRunnable(i)||typeof i=="function"?r.push({channel:n,value:Dr,skipNone:!0,mapper:dt(i)}):r.push({channel:n,value:i,skipNone:!1});return new _t(r)}},r5=class extends ue{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)}},Mg=class extends r5{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,Ut in this.channels&&"lc_graph_name"in this.channels[Ut]&&this.channels[Ut].lc_graph_name!=="Topic")throw new Error(`Channel '${Ut}' is reserved and cannot be used in the graph.`);this.channels[Ut]=new DS({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=Dt(this.config,e);return new this.constructor({...this,config:t})}validate(){zM({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 s of i){let o=wg(s);if(o!==void 0){if(r===e){yield[r,o];return}if(e===void 0&&(yield[r,o]),t){let a=e;e!==void 0&&(a=e.slice(r.length+1));for(let[c,u]of o.getSubgraphs(a,t))yield[`${r}${et}${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=no(this.channels,t.checkpoint);if(t.pendingWrites?.length){let p=t.pendingWrites.filter(([f,d])=>f===ir).map(([f,d,m])=>[String(d),m]);p.length>0&&Sr(t.checkpoint,i,[{name:Bn,writes:p,triggers:[]}],void 0,this.triggerToNodes)}let s=Object.values(oo(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await Gn(this.getSubgraphsAsync()),a=t.config.configurable?.checkpoint_ns??"",c={};for(let p of s){let f=o.find(([m])=>m===p.name);if(!f)continue;let d=`${String(p.name)}${Ir}${p.id}`;if(a&&(d=`${a}${et}${d}`),r===void 0){let m={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:d}};c[p.id]=m}else{let m={configurable:{[ft]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:d}},h=f[1];c[p.id]=await h.getState(m,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){let p=Object.fromEntries(s.map(d=>[d.id,d]));for(let[d,m,h]of t.pendingWrites)[Ot,ke,No].includes(m)||d in p&&p[d].writes.push([String(m),h]);let f=s.filter(d=>d.writes.length>0);f.length>0&&Sr(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=s.filter(p=>p.writes.length===0).map(p=>p.name);return{values:qn(i,this.streamChannelsAsIs),next:l,tasks:OS(s,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:u,config:so(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new $o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let o=yg(n);for await(let[a,c]of this.getSubgraphsAsync(o,!0))if(a===o)return await c.getState(Ta(e,{[ft]:r}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${o}" not found.`)}let i=Dt(this.config,e),s=await r.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:s,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new $o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let s=yg(n);for await(let[o,a]of this.getSubgraphsAsync(s,!0))if(o===s){yield*a.getStateHistory(Ta(e,{[ft]:r}),t);return}throw new Error(`Subgraph with namespace "${s}" not found.`)}let i=Dt(this.config,e,{configurable:{checkpoint_ns:n}});for await(let s of r.list(i,t))yield this._prepareStateSnapshot({config:s.config,saved:s})}async bulkUpdateState(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new $o("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?.[ft]===void 0){let o=yg(n);for await(let[,a]of this.getSubgraphsAsync(o,!0))return await a.bulkUpdateState(Ta(e,{[ft]:r}),t);throw new Error(`Subgraph "${o}" not found`)}let i=async(o,a)=>{let c=this.config?Dt(this.config,o):o,u=await r.getTuple(c),l=u!==void 0?zn(u.checkpoint):tu(),p={...u?.checkpoint.channel_versions},f=u?.metadata?.step??-1,d=Ta(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),m=c.metadata??{};u?.config.configurable&&(d=Ta(c,u.config.configurable),m={...u.metadata,...m});let{values:h,asNode:b}=a[0];if(h==null&&b===void 0){if(a.length>1)throw new De("Cannot create empty checkpoint with multiple updates");return so(await r.put(d,Ln(l,void 0,f),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},{}),u?u.metadata:void 0)}let _=no(this.channels,l);if(h===null&&b===xe){if(a.length>1)throw new De("Cannot apply multiple updates when clearing state");if(u){let O=oo(l,u.pendingWrites||[],this.nodes,_,u.config,!0,{step:(u.metadata?.step??-1)+1,checkpointer:r,store:this.store}),w=(u.pendingWrites||[]).filter(U=>U[0]===ir).map(U=>U.slice(1));w.length>0&&Sr(l,_,[{name:Bn,writes:w,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[U,P,V]of u.pendingWrites||[])[Ot,ke,No].includes(P)||U in O&&O[U].writes.push([P,V]);Sr(l,_,Object.values(O),r.getNextVersion.bind(r),this.triggerToNodes)}return so(await r.put(d,Ln(l,_,f),{...m,source:"update",step:f+1,parents:u?.metadata?.parents??{}},uu(p,l.channel_versions)),u?u.metadata:void 0)}if(b===J1){if(a.length>1)throw new De("Cannot copy checkpoint with multiple updates");if(u==null)throw new De("Cannot copy a non-existent checkpoint");let O=P=>!Array.isArray(P)||P.length===0?!1:P.every(V=>Array.isArray(V)&&V.length===2),w=Ln(l,void 0,f),U=await r.put(u.parentConfig??Ta(u.config,{checkpoint_id:void 0}),w,{source:"fork",step:f+1,parents:u.metadata?.parents??{}},{});if(O(h)){let P=oo(w,u.pendingWrites,this.nodes,_,U,!1,{step:f+2}),V=Object.values(P).reduce((Ke,{name:cr,id:Lr})=>(Ke[cr]??=[],Ke[cr].push({id:Lr}),Ke),{}),Oe=h.reduce((Ke,cr)=>{let[Lr,Me]=cr;Ke[Me]??=[];let Ao=Ke[Me].length,$i=V[Me]?.[Ao]?.id;return Ke[Me].push({values:Lr,asNode:Me,taskId:$i}),Ke},{});return i(so(U,u.metadata),Object.values(Oe).flat())}return so(U,u.metadata)}if(b===Bn){if(a.length>1)throw new De("Cannot apply multiple updates when updating as input");let O=await Gn(Tg(this.inputChannels,h));if(O.length===0)throw new De(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Sr(l,_,[{name:Bn,writes:O,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let w=u?.metadata?.step!=null?u.metadata.step+1:-1,U=await r.put(d,Ln(l,_,w),{source:"input",step:w,parents:u?.metadata?.parents??{}},uu(p,l.channel_versions));return await r.putWrites(U,O,Mi(Bn,l.id)),so(U,u?u.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&u?.pendingWrites!==void 0&&u.pendingWrites.length>0){let O=oo(l,u.pendingWrites,this.nodes,_,u.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(u.metadata?.step??-1)+1}),w=(u.pendingWrites??[]).filter(P=>P[0]===ir).map(P=>P.slice(1));w.length>0&&Sr(u.checkpoint,_,[{name:Bn,writes:w,triggers:[]}],void 0,this.triggerToNodes);for(let[P,V,Oe]of u.pendingWrites)[Ot,ke,No].includes(V)||O[P]===void 0||O[P].writes.push([V,Oe]);let U=Object.values(O).filter(P=>P.writes.length>0);U.length>0&&Sr(l,_,U,void 0,this.triggerToNodes)}let y=Object.values(l.versions_seen).map(O=>Object.values(O)).flat().find(O=>!!O),x=[];if(a.length===1){let{values:O,asNode:w,taskId:U}=a[0];if(w===void 0&&Object.keys(this.nodes).length===1)[w]=Object.keys(this.nodes);else if(w===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(w=this.inputChannels);else if(w===void 0){let P=Object.entries(l.versions_seen).map(([V,Oe])=>Object.values(Oe).map(Ke=>[Ke,V])).flat().filter(([V,Oe])=>Oe!==ke).sort(([V],[Oe])=>ug(V,Oe));P&&(P.length===1?w=P[0][1]:P[P.length-1][0]!==P[P.length-2][0]&&(w=P[P.length-1][1]))}if(w===void 0)throw new De('Ambiguous update, specify "asNode"');x.push({values:O,asNode:w,taskId:U})}else for(let{asNode:O,values:w,taskId:U}of a){if(O==null)throw new De('"asNode" is required when applying multiple updates');x.push({values:w,asNode:O,taskId:U})}let I=[];for(let{asNode:O,values:w,taskId:U}of x){if(this.nodes[O]===void 0)throw new De(`Node "${O.toString()}" does not exist`);let P=this.nodes[O].getWriters();if(!P.length)throw new De(`No writers found for node "${O.toString()}"`);I.push({name:O,input:w,proc:P.length>1?br.from(P,{omitSequenceTags:!0}):P[0],writes:[],triggers:[ke],id:U??Mi(ke,l.id),writers:[]})}for(let O of I)await O.proc.invoke(O.input,Ne({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[bn]:w=>O.writes.push(...w),[Vn]:(w,U=!1)=>ld(l,_,O,w,U)}}));for(let O of I){let w=O.writes.filter(U=>U[0]!==nr);u!==void 0&&w.length>0&&await r.putWrites(d,w,O.id)}Sr(l,_,I,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let A=uu(p,l.channel_versions),j=await r.put(d,Ln(l,_,f+1),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},A);for(let O of I){let w=O.writes.filter(U=>U[0]===nr);w.length>0&&await r.putWrites(j,w,O.id)}return so(j,u?u.metadata:void 0)},s=e;for(let{updates:o}of t)s=await i(s,o);return s}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:s,interruptBefore:o,...a}=e,c=!0,u=t!==void 0?t:this.debug,l=i;l===void 0?l=this.streamChannelsAsIs:jS(l,this.channels);let p=n;p===void 0?p=this.inputChannels:jS(p,this.channels);let f=o??this.interruptBefore??[],d=s??this.interruptAfter??[],m;r!==void 0?(m=Array.isArray(r)?r:[r],c=typeof r=="string"):(e.configurable?.[Ea]!==void 0?m=["values"]:m=this.streamMode,c=!0);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.[ft]!==void 0)h=e.configurable[ft];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");h=this.checkpointer}let b=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let y=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),x=e.durability??y??e?.configurable?.[_S]??"async";return[u,m,p,l,a,f,d,h,b,c,_,x]}async stream(e,t){let r=new AbortController,n={recursionLimit:this.config?.recursionLimit,...t,signal:lu(t?.signal,r.signal).signal},i=await super.stream(e,n);return new CS(t?.encoding==="text/event-stream"?PM(i):i,r)}streamEvents(e,t,r){let n=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:yM(this.config?.callbacks,t?.callbacks),signal:lu(t?.signal,n.signal).signal};return new CS(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=ad(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 s=await this._validateInput(e),{runId:o,...a}=i,[c,u,,l,p,f,d,m,h,b,_,y]=this._defaults(a);typeof p.context<"u"?p.context=await this._validateContext(p.context):p.configurable=await this._validateContext(p.configurable);let x=new Ng({modes:new Set(u)});if(this.checkpointer===!0){p.configurable??={};let P=p.configurable[Jr]??"";p.configurable[Jr]=P.split(et).map(V=>V.split(Ir)[0]).join(et)}if(u.includes("messages")){let P=new MM(Oe=>x.push(Oe)),{callbacks:V}=p;if(V===void 0)p.callbacks=[P];else if(Array.isArray(V))p.callbacks=V.concat(P);else{let Oe=V.copy();Oe.addHandler(P,!0),p.callbacks=Oe}}p.writer??=P=>{if(!u.includes("custom"))return;let V=eM()?.configurable?.[Jr]?.split(et).slice(0,-1);x.push([V??[],"custom",P])},p.interrupt??=this.userInterrupt??UM;let I=await(await Et(p))?.handleChainStart(this.toJSON(),_M(e,"input"),o,void 0,void 0,void 0,p?.runName??this.getName()),A=td(this.channels),j,O,U=(async()=>{try{j=await NM.initialize({input:s,config:p,checkpointer:m,nodes:this.nodes,channelSpecs:A,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:h,cache:_,stream:x,interruptAfter:d,interruptBefore:f,manager:I,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});let P=new jM({loop:j,nodeFinished:p.configurable?.[X1]});t?.subgraphs&&(j.config.configurable={...j.config.configurable,[nu]:j.stream}),await this._runLoop({loop:j,runner:P,debug:c,config:p}),y==="sync"&&await Promise.all(j?.checkpointerPromises??[])}catch(P){O=P}finally{try{j&&(await j.store?.stop(),await j.cache?.stop()),await Promise.all(j?.checkpointerPromises??[])}catch(P){O=O??P}O?x.error(O):x.close()}})();try{for await(let P of x){if(P===void 0)throw new Error("Data structure error.");let[V,Oe,Ke]=P;if(u.includes(Oe)){if(r==="text/event-stream"){n?yield[V,Oe,Ke]:yield[null,Oe,Ke];continue}n&&!b?yield[V,Oe,Ke]:b?n?yield[V,Ke]:yield Ke:yield[Oe,Ke]}}}catch(P){throw await I?.handleChainError(O),P}finally{await U}await I?.handleChainEnd(j?.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=[],s=await this.stream(e,n),o=[],a;for await(let c of s)r==="values"?od(c)?o.push(c[ke]):a=c:i.push(c);if(r==="values"){if(o.length>0){let c=o.flat(1);if(a==null)return{[ke]:c};if(typeof a=="object")return{...a,[ke]:c}}return a}return i}async _runLoop(e){let{loop:t,runner:r,debug:n,config:i}=e,s;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:o}of await t._matchCachedWrites())t._outputWrites(o.id,o.writes,!0);n&&TM(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&Pg(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,a)=>{n&&OM(o,a,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status==="out_of_steps")throw new O_([`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(s=o,!await t.finishAndHandleError(s))throw o}finally{s===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};var Hn=class BM extends Lt{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let r=new BM(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 De("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Ve;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Ve;return this.value[0]}isAvailable(){return this.value.length!==0}};var zS=class{path;ends;constructor(e){ue.isRunnable(e.path)?this.path=e.path:this.path=dt(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return _t.registerWriter(new sr({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(i){throw i.name===Vd.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
223
223
  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 s;if(this.ends?s=i.map(o=>$t(o)?o:this.ends[o]):s=i,s.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(s.filter($t).some(o=>o.node===xe))throw new De("Cannot send a packet to the END node");return await r(s,t)??e}},LS=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,s]of r){for(let a of[et,Ir])if(n.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n===xe)throw new Error(`Node \`${n}\` is reserved.`);let o=dt(i);this.nodes[n]={runnable:o,metadata:s?.metadata,subgraphs:ud(o)?[o]:s?.subgraphs,ends:s?.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===xe)throw new Error("END cannot be a start node");if(t===Ae)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};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!ue.isRunnable(n.path)){let s=Array.isArray(n.pathMap)?n.pathMap.join(","):Object.keys(n.pathMap??{}).join(",");n.path=dt(n.path).withConfig({runName:`Branch<${n.source}${s!==""?`,${s}`:""}>`.slice(0,63)})}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 zS(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(Ae,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,xe)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);let i=new US({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Ae]:new Hn,[xe]:new Hn},inputChannels:Ae,outputChannels:xe,streamChannels:[],streamMode:"values",name:n});for(let[s,o]of Object.entries(this.nodes))i.attachNode(s,o);for(let[s,o]of this.edges)i.attachEdge(s,o);for(let[s,o]of Object.entries(this.branches))for(let[a,c]of Object.entries(o))i.attachBranch(s,a,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!==Ae&&!(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 s of Object.values(i))if(s.ends!=null)for(let o of Object.values(s.ends))r.add(o);else{r.add(xe);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 C_([`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(`
224
- `),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!==xe&&!(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}},US=class extends Mg{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Hn,this.nodes[e]=new Kn({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new _t([{channel:e,value:Dr}],[Be])),this.streamChannels.push(e)}attachEdge(e,t){if(t===xe){if(e===Ae)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new _t([{channel:xe,value:Dr}],[Be]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e===Ae&&!this.nodes[Ae]&&(this.nodes[Ae]=FM.subscribeTo(Ae,{tags:[Be]})),this.nodes[e].pipe(r.run(i=>new _t(i.map(s=>$t(s)?s:{channel:s===xe?xe:`branch:${e}:${t}:${s}`,value:Dr}),[Be])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let i of n)if(i!==xe){let s=`branch:${e}:${t}:${i}`;this.channels[s]=new Hn,this.nodes[i].triggers.push(s),this.nodes[i].channels.push(s)}}async getGraphAsync(e){let t=e?.xray,r=new _a,n={[Ae]:r.addNode({schema:Z.any()},Ae)},i={},s={};t&&(s=Object.fromEntries((await Gn(this.getSubgraphsAsync())).filter(c=>VM(c[1]))));function o(c,u,l,p=!1){if(u===xe&&i[xe]===void 0&&(i[xe]=r.addNode({schema:Z.any()},xe)),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,p)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=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 d=typeof t=="number"?t-1:t,m=s[c]!==void 0?await s[c].getGraphAsync({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!En(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[xe]:xe};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)o(or(c),or(l),void 0,!0);return r}getGraph(e){let t=e?.xray,r=new _a,n={[Ae]:r.addNode({schema:Z.any()},Ae)},i={},s={};t&&(s=Object.fromEntries(Aa(this.getSubgraphs()).filter(c=>VM(c[1]))));function o(c,u,l,p=!1){return u===xe&&i[xe]===void 0&&(i[xe]=r.addNode({schema:Z.any()},xe)),r.addEdge(n[c],i[u],l!==u?l:void 0,p)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=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 d=typeof t=="number"?t-1:t,m=s[c]!==void 0?s[c].getGraph({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!En(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[xe]:xe};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}return r}};function VM(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function or(e){return e==="subgraph"?`"${e}"`:e}function ao(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function ZM(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function co(e){if(ZM(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function uo(e){if(e!=null&&ao(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 FS=Symbol.for("langgraph.channel.missing"),jg=class GM extends Lt{lc_graph_name="UntrackedValue";guard;_value=FS;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new GM({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new De("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===FS)throw new Ve;return this._value}checkpoint(){}isAvailable(){return this._value!==FS}};var lo=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),BS=class KM extends Lt{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new KM(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 De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!lo(this.names,this.seen))throw new Ve}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&lo(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&lo(this.names,this.seen)}},VS=class qM extends Lt{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 qM(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 De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!lo(this.names,this.seen))throw new Ve}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&lo(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&lo(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&lo(this.names,this.seen)}};var ZS=Symbol.for("langgraph.state.reduced_value"),ps=class{[ZS]=!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&&ZS in e&&e[ZS]===!0}};var HM=Symbol.for("langgraph.state.untracked_value"),Ca=class{[HM]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&HM in e}};var GS=Symbol.for("langgraph.state.state_schema"),wi=class{[GS]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(ps.isInstance(r)){let n=uo(r.valueSchema);e[t]=new os(r.reducer,n)}else if(Ca.isInstance(r)){let n=r.schema?uo(r.schema):void 0;e[t]=new jg({guard:r.guard,initialValueFactory:n})}else if(ao(r))e[t]=new Un(uo(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(ps.isInstance(n)?(i=co(n.valueSchema),i&&n.jsonSchemaExtra&&(i={...i,...n.jsonSchemaExtra})):Ca.isInstance(n)?i=n.schema?co(n.schema):void 0:ao(n)&&(i=co(n)),i){e[r]=i;let s=!1;ps.isInstance(n)?s=uo(n.valueSchema)!==void 0:Ca.isInstance(n)?s=n.schema?uo(n.schema)!==void 0:!1:s=uo(n)!==void 0,s||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;ps.isInstance(r)?n=co(r.inputSchema):Ca.isInstance(r)?n=r.schema?co(r.schema):void 0:ao(r)&&(n=co(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 s;if(ps.isInstance(i)?s=i.inputSchema:Ca.isInstance(i)?s=i.schema:ao(i)&&(s=i),s){let o=await s["~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&&GS in e&&e[GS]===!0}};var WM="__remove_all__";function ds(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],i=r.map(Qt),s=n.map(Qt);for(let l of i)(l.id===null||l.id===void 0)&&(l.id=Ar(),l.lc_kwargs.id=l.id);let o;for(let l=0;l<s.length;l+=1){let p=s[l];(p.id===null||p.id===void 0)&&(p.id=Ar(),p.lc_kwargs.id=p.id),Tn.isInstance(p)&&p.id===WM&&(o=l)}if(o!=null)return s.slice(o+1);let a=[...i],c=new Map(a.map((l,p)=>[l.id,p])),u=new Set;for(let l of s){let p=c.get(l.id);if(p!==void 0)Tn.isInstance(l)?u.add(l.id):(u.delete(l.id),a[p]=l);else{if(Tn.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,a.length),a.push(l)}}return a.filter(l=>!u.has(l.id))}var n5=Z.custom().default(()=>[]),i5=Z.custom(),s5=new ps(n5,{inputSchema:i5,reducer:ds,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var o5="lg:",a5=class{_map=new WeakMap;_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=ea(e);for(let[n,i]of Object.entries(r)){let s=this.get(i);s?.reducer?t[n]=new os(s.reducer.fn,s.default):t[n]=new Un(s?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,s])=>s===!0).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}:${o}`).join("|"),n=this._extensionCache.get(r)??new WeakMap;if(n.has(e))return n.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let s=Object.entries(ea(e)).map(([o,a])=>{let c=this.get(a),u=t.withReducerSchema?c?.reducer?.schema??a:a;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=On(u)??On(a),p=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`${o5}${p}`)}return[o,u]});i=Ym(e,Object.fromEntries(s)),it(i)&&(i._def.unknownKeys="strip")}return t.asPartial&&(i=Cc(i)),n.set(e,i),this._extensionCache.set(r,n),i}},md=new a5;function JM(e,t){if(t.reducer&&!t.default){let r=Qm(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return md.extend(r,()=>t),r}else return md.extend(e,()=>t),e}function Pa(e){return e==null?!1:!!(wi.isInstance(e)||yr(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"||hS(t)))}function XM(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&Pa(t.state),n="stateSchema"in t&&Pa(t.stateSchema),i="input"in t&&Pa(t.input);return!(!r&&!n&&!i||"input"in t&&t.input!=null&&!Pa(t.input)||"output"in t&&t.output!=null&&!Pa(t.output))}var fs="__root__",Dg=Symbol.for("langgraph.state.partial"),zg=class extends LS{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=md;_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 ol;let i=this._getChannelsFromSchema(n);this._schemaDefinition=i,wi.isInstance(n)?this._schemaRuntimeDefinition=n:yr(n)&&(this._schemaRuntimeDefinition=n),r.input?wi.isInstance(r.input)?this._inputRuntimeDefinition=r.input:yr(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Dg:this._inputRuntimeDefinition=Dg,r.output?wi.isInstance(r.output)?this._outputRuntimeDefinition=r.output:yr(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let s=r.input?this._getChannelsFromSchema(r.input):i,o=r.output?this._getChannelsFromSchema(r.output):i;this._inputDefinition=s,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&yr(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}_normalizeToStateGraphInit(e,t){if(XM(e)){if(yr(t)||fg.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(Pa(e)){if(yr(t)||fg.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(u5(e))return{state:c5(e.channels)};throw new ol}_getChannelsFromSchema(e){if(wi.isInstance(e))return e.getChannels();if(yr(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 ol("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,s]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[et,Ir])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===xe||n===Ae)throw new Error(`Node \`${n}\` is reserved.`);let o=this._schemaDefinition;s?.input!==void 0&&(o=this._getChannelsFromSchema(s.input)),this._addSchema(o);let a;ue.isRunnable(i)?a=i:typeof i=="function"?a=new sr({func:i,name:n,trace:!1}):a=dt(i);let c=s?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:a,retryPolicy:s?.retryPolicy,cachePolicy:c,metadata:s?.metadata,input:o??this._schemaDefinition,subgraphs:ud(a)?[a]:s?.subgraphs,ends:s?.ends,defer:s?.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===xe)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===xe)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,s]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,s),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:i,name:s,description:o}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(i)?i:[]]);let a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=a.length===1&&a[0]===fs?fs:a,u=Object.keys(this.channels),l=u.length===1&&u[0]===fs?fs:u,p=this._interrupt,f=new QM({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Ae]:new Hn},inputChannels:Ae,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:r,name:s,description:o,userInterrupt:p});f.attachNode(Ae);for(let[d,m]of Object.entries(this.nodes))f.attachNode(d,m);f.attachBranch(Ae,vS,YM(),{withReader:!1});for(let[d]of Object.entries(this.nodes))f.attachBranch(d,vS,YM(),{withReader:!1});for(let[d,m]of this.edges)f.attachEdge(d,m);for(let[d,m]of this.waitingEdges)f.attachEdge(d,m);for(let[d,m]of Object.entries(this.branches))for(let[h,b]of Object.entries(m))f.attachBranch(d,h,b);return f.validate()}};function c5(e){let t={};for(let[r,n]of Object.entries(e))r===fs?t[r]=mg(n):t[r]=mg(n);return t}var QM=class extends US{description;_metaRegistry=md;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e===Ae?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):r=Object.keys(this.builder.channels);function n(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(c=>Pt(c))){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([fs,u]);return c}else if(a!=null)return[[fs,a]];return null}let i=e;function s(a){if(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples().filter(([c])=>r.includes(c));if(Array.isArray(a)&&a.length>0&&a.some(Pt)){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>r.includes(l)))}else{let l=s(u);l&&c.push(...l??[])}return c}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([c])=>r.includes(c));{let c=Array.isArray(a)?"array":typeof a;throw new De(`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 sr({func:r.length&&r[0]===fs?n:s,trace:!1,recurse:!1})}];if(e===Ae)this.nodes[e]=new Kn({tags:[Be],triggers:[Ae],channels:[Ae],writers:[new _t(o,[Be])]});else{let a=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(p=>[p,p])),u=Object.keys(c).length===1&&fs in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new gS:new Hn(!1),this.nodes[e]=new Kn({triggers:[l],channels:u?Object.keys(c):c,writers:[new _t(o,[Be])],mapper:u?void 0:p=>Object.fromEntries(Object.entries(p).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!==xe){if(typeof e=="string")this.nodes[e].writers.push(new _t([{channel:`branch:to:${t}`,value:null}],[Be]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new VS(new Set(e)):new BS(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new _t([{channel:r,value:n}],[Be]))}}}attachBranch(e,t,r,n={withReader:!0}){let i=async(s,o)=>{let a=s.filter(u=>u!==xe);if(!a.length)return;let c=a.map(u=>$t(u)?u:{channel:u===xe?u:`branch:to:${u}`,value:e});await _t.doWrite({...o,tags:(o.tags??[]).concat([Be])},c)};this.nodes[e].writers.push(r.run(i,n.withReader?s=>iM.doRead(s,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(wi.isInstance(t)){if(Pt(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===Dg&&wi.isInstance(r)){if(Pt(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=s=>{if(s!=null)return this._metaRegistry.getExtendedChannelSchemas(s,{withReducerSchema:!0})};if(yr(t))return i(t);if(t===Dg)return yr(r)?Cc(i(r)):void 0})();if(Pt(e)){let i=e;return e.update&&n!=null&&(i.update=Oc(n,e.update)),i}return n!=null?Oc(n,e):e}isInterrupted(e){return od(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return yr(t)&&Oc(t,e),e}};function u5(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function l5(e){if($t(e))return[e];let t=[];Pt(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Pt));let r=[];for(let n of t){if(n.graph===jr.PARENT)throw new Zd(n);$t(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function YM(){return new zS({path:new sr({func:l5,tags:[Be],trace:!1,recurse:!1,name:"<control_branch>"})})}var ej=function(t,r){let{name:n,checkpointer:i,store:s,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t;if(rM(r)||nM(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let a="updates",c=xM(n,r);function u(d){return typeof d=="object"&&d!==null&&"__lg_type"in d&&d.__lg_type==="__pregel_final"}let l=new sr({name:"pluckReturnValue",func:d=>u(d)?d.value:d}),p=new sr({name:"pluckSaveValue",func:d=>u(d)?d.save:d}),f=new Kn({bound:c,triggers:[Ae],channels:[Ae],writers:[new _t([{channel:xe,value:Dr,mapper:l},{channel:ka,value:Dr,mapper:p}],[Be])]});return new Mg({name:n,checkpointer:i,nodes:{[n]:f},channels:{[Ae]:new Hn,[xe]:new Un,[ka]:new Un},inputChannels:Ae,outputChannels:xe,streamChannels:xe,streamMode:a,store:s,cache:o})};ej.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};var p5=Fn.Root({messages:Fn({reducer:ds,default:()=>[]})}),tj={reducer:{fn:ds},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},d5=ce.object({messages:JM(ce.custom(),tj)});var wn=ce;async function KS(e,t,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
224
+ `),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!==xe&&!(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}},US=class extends Mg{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Hn,this.nodes[e]=new Kn({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new _t([{channel:e,value:Dr}],[Be])),this.streamChannels.push(e)}attachEdge(e,t){if(t===xe){if(e===Ae)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new _t([{channel:xe,value:Dr}],[Be]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e===Ae&&!this.nodes[Ae]&&(this.nodes[Ae]=FM.subscribeTo(Ae,{tags:[Be]})),this.nodes[e].pipe(r.run(i=>new _t(i.map(s=>$t(s)?s:{channel:s===xe?xe:`branch:${e}:${t}:${s}`,value:Dr}),[Be])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let i of n)if(i!==xe){let s=`branch:${e}:${t}:${i}`;this.channels[s]=new Hn,this.nodes[i].triggers.push(s),this.nodes[i].channels.push(s)}}async getGraphAsync(e){let t=e?.xray,r=new _a,n={[Ae]:r.addNode({schema:Z.any()},Ae)},i={},s={};t&&(s=Object.fromEntries((await Gn(this.getSubgraphsAsync())).filter(c=>VM(c[1]))));function o(c,u,l,p=!1){if(u===xe&&i[xe]===void 0&&(i[xe]=r.addNode({schema:Z.any()},xe)),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,p)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=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 d=typeof t=="number"?t-1:t,m=s[c]!==void 0?await s[c].getGraphAsync({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!En(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[xe]:xe};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)o(or(c),or(l),void 0,!0);return r}getGraph(e){let t=e?.xray,r=new _a,n={[Ae]:r.addNode({schema:Z.any()},Ae)},i={},s={};t&&(s=Object.fromEntries(Aa(this.getSubgraphs()).filter(c=>VM(c[1]))));function o(c,u,l,p=!1){return u===xe&&i[xe]===void 0&&(i[xe]=r.addNode({schema:Z.any()},xe)),r.addEdge(n[c],i[u],l!==u?l:void 0,p)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=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 d=typeof t=="number"?t-1:t,m=s[c]!==void 0?s[c].getGraph({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!En(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[xe]:xe};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}return r}};function VM(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function or(e){return e==="subgraph"?`"${e}"`:e}function ao(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function ZM(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function co(e){if(ZM(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function uo(e){if(e!=null&&ao(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 FS=Symbol.for("langgraph.channel.missing"),jg=class GM extends Lt{lc_graph_name="UntrackedValue";guard;_value=FS;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new GM({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new De("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===FS)throw new Ve;return this._value}checkpoint(){}isAvailable(){return this._value!==FS}};var lo=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),BS=class KM extends Lt{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new KM(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 De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!lo(this.names,this.seen))throw new Ve}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&lo(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&lo(this.names,this.seen)}},VS=class qM extends Lt{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 qM(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 De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!lo(this.names,this.seen))throw new Ve}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&lo(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&lo(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&lo(this.names,this.seen)}};var ZS=Symbol.for("langgraph.state.reduced_value"),ps=class{[ZS]=!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&&ZS in e&&e[ZS]===!0}};var HM=Symbol.for("langgraph.state.untracked_value"),Ca=class{[HM]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&HM in e}};var GS=Symbol.for("langgraph.state.state_schema"),wi=class{[GS]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(ps.isInstance(r)){let n=uo(r.valueSchema);e[t]=new os(r.reducer,n)}else if(Ca.isInstance(r)){let n=r.schema?uo(r.schema):void 0;e[t]=new jg({guard:r.guard,initialValueFactory:n})}else if(ao(r))e[t]=new Un(uo(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(ps.isInstance(n)?(i=co(n.valueSchema),i&&n.jsonSchemaExtra&&(i={...i,...n.jsonSchemaExtra})):Ca.isInstance(n)?i=n.schema?co(n.schema):void 0:ao(n)&&(i=co(n)),i){e[r]=i;let s=!1;ps.isInstance(n)?s=uo(n.valueSchema)!==void 0:Ca.isInstance(n)?s=n.schema?uo(n.schema)!==void 0:!1:s=uo(n)!==void 0,s||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;ps.isInstance(r)?n=co(r.inputSchema):Ca.isInstance(r)?n=r.schema?co(r.schema):void 0:ao(r)&&(n=co(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 s;if(ps.isInstance(i)?s=i.inputSchema:Ca.isInstance(i)?s=i.schema:ao(i)&&(s=i),s){let o=await s["~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&&GS in e&&e[GS]===!0}};var WM="__remove_all__";function ds(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],i=r.map(Qt),s=n.map(Qt);for(let l of i)(l.id===null||l.id===void 0)&&(l.id=Ar(),l.lc_kwargs.id=l.id);let o;for(let l=0;l<s.length;l+=1){let p=s[l];(p.id===null||p.id===void 0)&&(p.id=Ar(),p.lc_kwargs.id=p.id),Tn.isInstance(p)&&p.id===WM&&(o=l)}if(o!=null)return s.slice(o+1);let a=[...i],c=new Map(a.map((l,p)=>[l.id,p])),u=new Set;for(let l of s){let p=c.get(l.id);if(p!==void 0)Tn.isInstance(l)?u.add(l.id):(u.delete(l.id),a[p]=l);else{if(Tn.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,a.length),a.push(l)}}return a.filter(l=>!u.has(l.id))}var n5=Z.custom().default(()=>[]),i5=Z.custom(),s5=new ps(n5,{inputSchema:i5,reducer:ds,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var o5="lg:",a5=class{_map=new WeakMap;_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=ea(e);for(let[n,i]of Object.entries(r)){let s=this.get(i);s?.reducer?t[n]=new os(s.reducer.fn,s.default):t[n]=new Un(s?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,s])=>s===!0).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}:${o}`).join("|"),n=this._extensionCache.get(r)??new WeakMap;if(n.has(e))return n.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let s=Object.entries(ea(e)).map(([o,a])=>{let c=this.get(a),u=t.withReducerSchema?c?.reducer?.schema??a:a;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=On(u)??On(a),p=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`${o5}${p}`)}return[o,u]});i=Ym(e,Object.fromEntries(s)),it(i)&&(i._def.unknownKeys="strip")}return t.asPartial&&(i=Cc(i)),n.set(e,i),this._extensionCache.set(r,n),i}},md=new a5;function JM(e,t){if(t.reducer&&!t.default){let r=Qm(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return md.extend(r,()=>t),r}else return md.extend(e,()=>t),e}function Pa(e){return e==null?!1:!!(wi.isInstance(e)||yr(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"||hS(t)))}function XM(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&Pa(t.state),n="stateSchema"in t&&Pa(t.stateSchema),i="input"in t&&Pa(t.input);return!(!r&&!n&&!i||"input"in t&&t.input!=null&&!Pa(t.input)||"output"in t&&t.output!=null&&!Pa(t.output))}var fs="__root__",Dg=Symbol.for("langgraph.state.partial"),zg=class extends LS{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=md;_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 ol;let i=this._getChannelsFromSchema(n);this._schemaDefinition=i,wi.isInstance(n)?this._schemaRuntimeDefinition=n:yr(n)&&(this._schemaRuntimeDefinition=n),r.input?wi.isInstance(r.input)?this._inputRuntimeDefinition=r.input:yr(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Dg:this._inputRuntimeDefinition=Dg,r.output?wi.isInstance(r.output)?this._outputRuntimeDefinition=r.output:yr(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let s=r.input?this._getChannelsFromSchema(r.input):i,o=r.output?this._getChannelsFromSchema(r.output):i;this._inputDefinition=s,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&yr(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}_normalizeToStateGraphInit(e,t){if(XM(e)){if(yr(t)||fg.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(Pa(e)){if(yr(t)||fg.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(u5(e))return{state:c5(e.channels)};throw new ol}_getChannelsFromSchema(e){if(wi.isInstance(e))return e.getChannels();if(yr(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 ol("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,s]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[et,Ir])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===xe||n===Ae)throw new Error(`Node \`${n}\` is reserved.`);let o=this._schemaDefinition;s?.input!==void 0&&(o=this._getChannelsFromSchema(s.input)),this._addSchema(o);let a;ue.isRunnable(i)?a=i:typeof i=="function"?a=new sr({func:i,name:n,trace:!1}):a=dt(i);let c=s?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:a,retryPolicy:s?.retryPolicy,cachePolicy:c,metadata:s?.metadata,input:o??this._schemaDefinition,subgraphs:ud(a)?[a]:s?.subgraphs,ends:s?.ends,defer:s?.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===xe)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===xe)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,s]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,s),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:i,name:s,description:o}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(i)?i:[]]);let a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=a.length===1&&a[0]===fs?fs:a,u=Object.keys(this.channels),l=u.length===1&&u[0]===fs?fs:u,p=this._interrupt,f=new QM({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Ae]:new Hn},inputChannels:Ae,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:r,name:s,description:o,userInterrupt:p});f.attachNode(Ae);for(let[d,m]of Object.entries(this.nodes))f.attachNode(d,m);f.attachBranch(Ae,vS,YM(),{withReader:!1});for(let[d]of Object.entries(this.nodes))f.attachBranch(d,vS,YM(),{withReader:!1});for(let[d,m]of this.edges)f.attachEdge(d,m);for(let[d,m]of this.waitingEdges)f.attachEdge(d,m);for(let[d,m]of Object.entries(this.branches))for(let[h,b]of Object.entries(m))f.attachBranch(d,h,b);return f.validate()}};function c5(e){let t={};for(let[r,n]of Object.entries(e))r===fs?t[r]=mg(n):t[r]=mg(n);return t}var QM=class extends US{description;_metaRegistry=md;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e===Ae?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):r=Object.keys(this.builder.channels);function n(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(c=>Pt(c))){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([fs,u]);return c}else if(a!=null)return[[fs,a]];return null}let i=e;function s(a){if(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples().filter(([c])=>r.includes(c));if(Array.isArray(a)&&a.length>0&&a.some(Pt)){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>r.includes(l)))}else{let l=s(u);l&&c.push(...l??[])}return c}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([c])=>r.includes(c));{let c=Array.isArray(a)?"array":typeof a;throw new De(`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 sr({func:r.length&&r[0]===fs?n:s,trace:!1,recurse:!1})}];if(e===Ae)this.nodes[e]=new Kn({tags:[Be],triggers:[Ae],channels:[Ae],writers:[new _t(o,[Be])]});else{let a=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(p=>[p,p])),u=Object.keys(c).length===1&&fs in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new gS:new Hn(!1),this.nodes[e]=new Kn({triggers:[l],channels:u?Object.keys(c):c,writers:[new _t(o,[Be])],mapper:u?void 0:p=>Object.fromEntries(Object.entries(p).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!==xe){if(typeof e=="string")this.nodes[e].writers.push(new _t([{channel:`branch:to:${t}`,value:null}],[Be]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new VS(new Set(e)):new BS(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new _t([{channel:r,value:n}],[Be]))}}}attachBranch(e,t,r,n={withReader:!0}){let i=async(s,o)=>{let a=s.filter(u=>u!==xe);if(!a.length)return;let c=a.map(u=>$t(u)?u:{channel:u===xe?u:`branch:to:${u}`,value:e});await _t.doWrite({...o,tags:(o.tags??[]).concat([Be])},c)};this.nodes[e].writers.push(r.run(i,n.withReader?s=>iM.doRead(s,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(wi.isInstance(t)){if(Pt(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===Dg&&wi.isInstance(r)){if(Pt(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=s=>{if(s!=null)return this._metaRegistry.getExtendedChannelSchemas(s,{withReducerSchema:!0})};if(yr(t))return i(t);if(t===Dg)return yr(r)?Cc(i(r)):void 0})();if(Pt(e)){let i=e;return e.update&&n!=null&&(i.update=Oc(n,e.update)),i}return n!=null?Oc(n,e):e}isInterrupted(e){return od(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return yr(t)&&Oc(t,e),e}};function u5(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function l5(e){if($t(e))return[e];let t=[];Pt(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Pt));let r=[];for(let n of t){if(n.graph===jr.PARENT)throw new Zd(n);$t(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function YM(){return new zS({path:new sr({func:l5,tags:[Be],trace:!1,recurse:!1,name:"<control_branch>"})})}var ej=function(t,r){let{name:n,checkpointer:i,store:s,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t;if(rM(r)||nM(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let a="updates",c=xM(n,r);function u(d){return typeof d=="object"&&d!==null&&"__lg_type"in d&&d.__lg_type==="__pregel_final"}let l=new sr({name:"pluckReturnValue",func:d=>u(d)?d.value:d}),p=new sr({name:"pluckSaveValue",func:d=>u(d)?d.save:d}),f=new Kn({bound:c,triggers:[Ae],channels:[Ae],writers:[new _t([{channel:xe,value:Dr,mapper:l},{channel:ka,value:Dr,mapper:p}],[Be])]});return new Mg({name:n,checkpointer:i,nodes:{[n]:f},channels:{[Ae]:new Hn,[xe]:new Un,[ka]:new Un},inputChannels:Ae,outputChannels:xe,streamChannels:xe,streamMode:a,store:s,cache:o})};ej.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};var p5=Fn.Root({messages:Fn({reducer:ds,default:()=>[]})}),tj={reducer:{fn:ds},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},d5=ce.object({messages:JM(ce.custom(),tj)});async function KS(e,t,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
225
225
 
226
226
  If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
227
227
 
228
228
  Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
229
229
  |`,`
230
230
  \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
231
- `].join(" "));let n=await Et(r),i=n?.getParentRunId();n!==void 0&&i!==void 0&&await n.handleCustomEvent?.(e,t,i)}function hd(e,t){return e.lc_error_code=t,e.message=`${e.message}
231
+ `].join(" "));let n=await Et(r),i=n?.getParentRunId();n!==void 0&&i!==void 0&&await n.handleCustomEvent?.(e,t,i)}var wn=ce;function hd(e,t){return e.lc_error_code=t,e.message=`${e.message}
232
232
 
233
233
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
234
234
  `,e}function se(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r}function k(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var qS=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return qS=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function gd(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var _d=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};var W=class extends Error{},Rt=class e extends W{constructor(t,r,n,i){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(t,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&i?`${t} ${i}`:t?`${t} status code (no body)`:i||"(no status code or body)"}static generate(t,r,n,i){if(!t||!i)return new po({message:n,cause:_d(r)});let s=r?.error;return t===400?new pu(t,s,n,i):t===401?new du(t,s,n,i):t===403?new fu(t,s,n,i):t===404?new mu(t,s,n,i):t===409?new hu(t,s,n,i):t===422?new gu(t,s,n,i):t===429?new _u(t,s,n,i):t>=500?new yu(t,s,n,i):new e(t,s,n,i)}},yt=class extends Rt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}},po=class extends Rt{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}},xi=class extends po{constructor({message:t}={}){super({message:t??"Request timed out."})}},pu=class extends Rt{},du=class extends Rt{},fu=class extends Rt{},mu=class extends Rt{},hu=class extends Rt{},gu=class extends Rt{},_u=class extends Rt{},yu=class extends Rt{},vu=class extends W{constructor(){super("Could not parse response content as the length limit was reached")}},bu=class extends W{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ii=class extends Error{constructor(t){super(t)}};var m5=/^[a-z][a-z0-9+.-]*:/i,rj=e=>m5.test(e),ar=e=>(ar=Array.isArray,ar(e)),HS=ar;function WS(e){return typeof e!="object"?{}:e??{}}function nj(e){if(!e)return!0;for(let t in e)return!1;return!0}function ij(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function yd(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var sj=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new W(`${e} must be an integer`);if(t<0)throw new W(`${e} must be a positive integer`);return t};var oj=e=>{try{return JSON.parse(e)}catch{return}};var Si=e=>new Promise(t=>setTimeout(t,e));var fo="6.16.0";var lj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function h5(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var g5=()=>{let e=h5();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":cj(Deno.build.os),"X-Stainless-Arch":aj(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":cj(globalThis.process.platform??"unknown"),"X-Stainless-Arch":aj(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=_5();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _5(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,s=n[2]||0,o=n[3]||0;return{browser:t,version:`${i}.${s}.${o}`}}}return null}var aj=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",cj=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),uj,pj=()=>uj??(uj=g5());function dj(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function JS(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Lg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return JS({start(){},async pull(r){let{done:n,value:i}=await t.next();n?r.close():r.enqueue(i)},async cancel(){await t.return?.()}})}function XS(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function fj(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var mj=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Ug="RFC3986",YS=e=>String(e),Fg={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:YS},QS="RFC1738";var Bg=(e,t)=>(Bg=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Bg(e,t)),Ei=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var eE=1024,hj=(e,t,r,n,i)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let o="";for(let a=0;a<s.length;a+=eE){let c=s.length>=eE?s.slice(a,a+eE):s,u=[];for(let l=0;l<c.length;++l){let p=c.charCodeAt(l);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||i===QS&&(p===40||p===41)){u[u.length]=c.charAt(l);continue}if(p<128){u[u.length]=Ei[p];continue}if(p<2048){u[u.length]=Ei[192|p>>6]+Ei[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=Ei[224|p>>12]+Ei[128|p>>6&63]+Ei[128|p&63];continue}l+=1,p=65536+((p&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=Ei[240|p>>18]+Ei[128|p>>12&63]+Ei[128|p>>6&63]+Ei[128|p&63]}o+=u.join("")}return o};function gj(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function tE(e,t){if(ar(e)){let r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var yj={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},vj=function(e,t){Array.prototype.push.apply(e,ar(t)?t:[t])},_j,Mt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:hj,encodeValuesOnly:!1,format:Ug,formatter:YS,indices:!1,serializeDate(e){return(_j??(_j=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function b5(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var rE={};function bj(e,t,r,n,i,s,o,a,c,u,l,p,f,d,m,h,b,_){let y=e,x=_,I=0,A=!1;for(;(x=x.get(rE))!==void 0&&!A;){let P=x.get(e);if(I+=1,typeof P<"u"){if(P===I)throw new RangeError("Cyclic object value");A=!0}typeof x.get(rE)>"u"&&(I=0)}if(typeof u=="function"?y=u(t,y):y instanceof Date?y=f?.(y):r==="comma"&&ar(y)&&(y=tE(y,function(P){return P instanceof Date?f?.(P):P})),y===null){if(s)return c&&!h?c(t,Mt.encoder,b,"key",d):t;y=""}if(b5(y)||gj(y)){if(c){let P=h?t:c(t,Mt.encoder,b,"key",d);return[m?.(P)+"="+m?.(c(y,Mt.encoder,b,"value",d))]}return[m?.(t)+"="+m?.(String(y))]}let j=[];if(typeof y>"u")return j;let O;if(r==="comma"&&ar(y))h&&c&&(y=tE(y,c)),O=[{value:y.length>0?y.join(",")||null:void 0}];else if(ar(u))O=u;else{let P=Object.keys(y);O=l?P.sort(l):P}let w=a?String(t).replace(/\./g,"%2E"):String(t),U=n&&ar(y)&&y.length===1?w+"[]":w;if(i&&ar(y)&&y.length===0)return U+"[]";for(let P=0;P<O.length;++P){let V=O[P],Oe=typeof V=="object"&&typeof V.value<"u"?V.value:y[V];if(o&&Oe===null)continue;let Ke=p&&a?V.replace(/\./g,"%2E"):V,cr=ar(y)?typeof r=="function"?r(U,Ke):U:U+(p?"."+Ke:"["+Ke+"]");_.set(e,I);let Lr=new WeakMap;Lr.set(rE,_),vj(j,bj(Oe,cr,r,n,i,s,o,a,r==="comma"&&h&&ar(y)?null:c,u,l,p,f,d,m,h,b,Lr))}return j}function w5(e=Mt){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");let t=e.charset||Mt.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Ug;if(typeof e.format<"u"){if(!Bg(Fg,e.format))throw new TypeError("Unknown format option provided.");r=e.format}let n=Fg[r],i=Mt.filter;(typeof e.filter=="function"||ar(e.filter))&&(i=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in yj?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=Mt.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:Mt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:Mt.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:Mt.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Mt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?Mt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Mt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:Mt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:Mt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Mt.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Mt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Mt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Mt.strictNullHandling}}function nE(e,t={}){let r=e,n=w5(t),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ar(n.filter)&&(s=n.filter,i=s);let o=[];if(typeof r!="object"||r===null)return"";let a=yj[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let f=0;f<i.length;++f){let d=i[f];n.skipNulls&&r[d]===null||vj(o,bj(r[d],d,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let l=o.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),l.length>0?p+l:""}function Ij(e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}var wj;function wu(e){let t;return(wj??(t=new globalThis.TextEncoder,wj=t.encode.bind(t)))(e)}var xj;function iE(e){let t;return(xj??(t=new globalThis.TextDecoder,xj=t.decode.bind(t)))(e)}var Xr,Yr,Na=class{constructor(){Xr.set(this,void 0),Yr.set(this,void 0),se(this,Xr,new Uint8Array,"f"),se(this,Yr,null,"f")}decode(t){if(t==null)return[];let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?wu(t):t;se(this,Xr,Ij([k(this,Xr,"f"),r]),"f");let n=[],i;for(;(i=I5(k(this,Xr,"f"),k(this,Yr,"f")))!=null;){if(i.carriage&&k(this,Yr,"f")==null){se(this,Yr,i.index,"f");continue}if(k(this,Yr,"f")!=null&&(i.index!==k(this,Yr,"f")+1||i.carriage)){n.push(iE(k(this,Xr,"f").subarray(0,k(this,Yr,"f")-1))),se(this,Xr,k(this,Xr,"f").subarray(k(this,Yr,"f")),"f"),se(this,Yr,null,"f");continue}let s=k(this,Yr,"f")!==null?i.preceding-1:i.preceding,o=iE(k(this,Xr,"f").subarray(0,s));n.push(o),se(this,Xr,k(this,Xr,"f").subarray(i.index),"f"),se(this,Yr,null,"f")}return n}flush(){return k(this,Xr,"f").length?this.decode(`
@@ -267,4 +267,4 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
267
267
  Title: {title}
268
268
  Description: {description}`,qq=`Name: {name}
269
269
  Alias: {alias}
270
- Description: {description}`,Hq=ce.object({schemaVersion:ce.literal(Vq),modified:ce.number().int().nonnegative(),embeddings:ce.object({modelProvider:ce.literal(Zq),model:ce.literal(Gq),dimensions:ce.literal(Fd),templates:ce.object({layer:ce.string().default(Kq),field:ce.string().default(qq)})}),layers:ce.array(ce.object({id:ce.string().min(1),name:ce.string().min(1),title:ce.string().catch(""),description:ce.string().catch(""),vector:ce.array(ce.number()).length(Fd,{message:`Layer vector must be exactly ${Fd} dimensions`}),fields:ce.array(ce.object({name:ce.string().min(1),alias:ce.string().catch(""),description:ce.string().catch(""),vector:ce.array(ce.number()).length(Fd,{message:`Field vector must be exactly ${Fd} dimensions`})}))})).default([])}),Wq=e=>{let t=Hq.safeParse(e);if(!t.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return t.data},Jq=(e,t)=>{let r=new Map,n=new Map;if(t.allLayers.forEach(i=>{i instanceof mq&&n.set(i.id,i)}),e.length!==n.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let i of e){let s=n.get(i.id);if(!s)throw new Error(`Layer with ID ${i.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(i.fields.length!==s.fields.length)throw new Error(`Field count mismatch for layer ID ${i.id} during registry restoration. Regenerate embeddings.`);let o={name:i.name,title:i.title,description:i.description},a=new Map;for(let c of i.fields){let u=s.fieldsIndex.get(c.name);if(!u)throw new Error(`Field with name ${c.name} not found in the original layer ${i.id} during registry restoration. Regenerate embeddings.`);a.set(c.name,{name:c.name,alias:c.alias,description:c.description,type:u.type||"unknown",valueType:u.valueType||"unknown"})}r.set(i.id,{layerItem:o,fieldRegistry:a})}return r},Xq=async e=>{try{return(await hq(e,{responseType:"json"})).data}catch(t){throw new Error(`Failed to fetch data from ${e}: ${String(t)}`)}},Yq=async e=>{let t=e.map;if(!t?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:r}=await t.portalItem.fetchResources(),n=r.find(s=>s.resource.path==="embeddings-v01.json");if(!n?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let i=await Xq(n.resource.url);return Wq(i)},vz=class e{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.threadId="",this.agentRegistry=new ZE,this.streamEpoch=0}static async init(t){let r=new e;try{if(t.view?.map){await bz.whenOnce(()=>t.view.ready);let n=await Yq(t.view),i=Jq(n.layers,t.view.map);r.layersAndFieldsRegistry=i,r.embeddingsWorker=await yq(n)}return t.agents?.forEach(n=>{r.agentRegistry.register(n)}),r.orchestratorReady=!0,r}catch(n){throw console.error("Orchestrator initialization failed:",n),n}}async*ask(t){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!t.trim())return;this.threadId=String(Date.now()),this.graph||(this.graph=Dq().compile({checkpointer:new lg}));let r=this.embeddingsWorker?Uq({worker:this.embeddingsWorker}):void 0,n=this.embeddingsWorker?Bq({worker:this.embeddingsWorker}):void 0,i=new Map,s={version:"v2",streamMode:"custom",configurable:{thread_id:this.threadId,hitlResponse:null,services:{layerSearch:r,fieldSearch:n,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:i}},subgraphs:!0},o=this.graph?.streamEvents({userInput:t,messages:this.chatHistory},s),a=++this.streamEpoch;for(yield*this.pipeStream(o,a);;){let u=(await this.graph.getState(s,{subgraphs:!0})).tasks.find(l=>l.interrupts.length>0)?.interrupts[0]?.value;if(!u)break;this.currentInterrupt=u,this.interruptHandler=new GE(this.graph,s),yield{runId:this.threadId,timestamp:Date.now(),type:"interrupt",interrupt:u};try{let l=await this.interruptHandler.waitForUser(),p=++this.streamEpoch;yield*this.pipeStream(l,p)}catch(l){if(l){yield{runId:this.threadId,timestamp:Date.now(),type:"error",error:{message:l?.message}};return}yield{runId:this.threadId,timestamp:Date.now(),type:"cancelled"};return}}let c=(await this.graph.getState(s,{subgraphs:!0})).values;this.chatHistory=c.messages.length?c.messages:this.chatHistory,yield{runId:this.threadId,timestamp:Date.now(),type:"completed",result:{content:Oq(c.messages)}}}newConversation(){this.chatHistory=[]}resumeInterrupt(t){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,t)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}async*pipeStream(t,r){for await(let n of t){if(r!==this.streamEpoch){console.log("Stale stream detected, aborting.");break}n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:this.threadId,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:this.threadId,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}},Qq=wn.object({name:wn.string(),description:wn.string(),valueType:wn.string(),alias:wn.string()}),VDe=wn.object({fields:wn.array(Qq)});var ZDe=wn.object({title:wn.string(),description:wn.string(),name:wn.string().nullable()});var GDe=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must be the same length");let r=0,n=0,i=0;for(let a=0;a<e.length;++a){let c=e[a],u=t[a];r+=c*u,n+=c*c,i+=u*u}let s=Math.sqrt(n*i);if(s===0)return 0;let o=r/s;return Math.max(-1,Math.min(1,o))};return{a:Vd,b:Ri,c:ot,d:Wt,e:at,f:$e,g:si,h:ce,i:Jp,j:Fn,k:Ae,l:xe,m:$t,n:jr,o:Pt,p:sr,q:ds,r:zg,s:wn,t:Os,u:UDe,v:FDe,w:Nq,x:BDe,y:zq,z:vz,A:GDe}},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request")
270
+ Description: {description}`,Hq=ce.object({schemaVersion:ce.literal(Vq),modified:ce.number().int().nonnegative(),embeddings:ce.object({modelProvider:ce.literal(Zq),model:ce.literal(Gq),dimensions:ce.literal(Fd),templates:ce.object({layer:ce.string().default(Kq),field:ce.string().default(qq)})}),layers:ce.array(ce.object({id:ce.string().min(1),name:ce.string().min(1),title:ce.string().catch(""),description:ce.string().catch(""),vector:ce.array(ce.number()).length(Fd,{message:`Layer vector must be exactly ${Fd} dimensions`}),fields:ce.array(ce.object({name:ce.string().min(1),alias:ce.string().catch(""),description:ce.string().catch(""),vector:ce.array(ce.number()).length(Fd,{message:`Field vector must be exactly ${Fd} dimensions`})}))})).default([])}),Wq=e=>{let t=Hq.safeParse(e);if(!t.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return t.data},Jq=(e,t)=>{let r=new Map,n=new Map;if(t.allLayers.forEach(i=>{i instanceof mq&&n.set(i.id,i)}),e.length!==n.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let i of e){let s=n.get(i.id);if(!s)throw new Error(`Layer with ID ${i.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(i.fields.length!==s.fields.length)throw new Error(`Field count mismatch for layer ID ${i.id} during registry restoration. Regenerate embeddings.`);let o={name:i.name,title:i.title,description:i.description},a=new Map;for(let c of i.fields){let u=s.fieldsIndex.get(c.name);if(!u)throw new Error(`Field with name ${c.name} not found in the original layer ${i.id} during registry restoration. Regenerate embeddings.`);a.set(c.name,{name:c.name,alias:c.alias,description:c.description,type:u.type||"unknown",valueType:u.valueType||"unknown",domain:s.getFieldDomain(c.name)??void 0})}r.set(i.id,{layerItem:o,fieldRegistry:a})}return r},Xq=async e=>{try{return(await hq(e,{responseType:"json"})).data}catch(t){throw new Error(`Failed to fetch data from ${e}: ${String(t)}`)}},Yq=async e=>{let t=e.map;if(!t?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:r}=await t.portalItem.fetchResources(),n=r.find(s=>s.resource.path==="embeddings-v01.json");if(!n?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let i=await Xq(n.resource.url);return Wq(i)},vz=class e{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.threadId="",this.agentRegistry=new ZE,this.streamEpoch=0}static async init(t){let r=new e;try{if(t.view?.map){await bz.whenOnce(()=>t.view.ready);let n=await Yq(t.view),i=Jq(n.layers,t.view.map);r.layersAndFieldsRegistry=i,r.embeddingsWorker=await yq(n)}return t.agents?.forEach(n=>{r.agentRegistry.register(n)}),r.orchestratorReady=!0,r}catch(n){throw console.error("Orchestrator initialization failed:",n),n}}async*ask(t){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!t.trim())return;this.threadId=String(Date.now()),this.graph||(this.graph=Dq().compile({checkpointer:new lg}));let r=this.embeddingsWorker?Uq({worker:this.embeddingsWorker}):void 0,n=this.embeddingsWorker?Bq({worker:this.embeddingsWorker}):void 0,i=new Map,s={version:"v2",streamMode:"custom",configurable:{thread_id:this.threadId,hitlResponse:null,services:{layerSearch:r,fieldSearch:n,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:i}},subgraphs:!0},o=this.graph?.streamEvents({userInput:t,messages:this.chatHistory},s),a=++this.streamEpoch;for(yield*this.pipeStream(o,a);;){let u=(await this.graph.getState(s,{subgraphs:!0})).tasks.find(l=>l.interrupts.length>0)?.interrupts[0]?.value;if(!u)break;this.currentInterrupt=u,this.interruptHandler=new GE(this.graph,s),yield{runId:this.threadId,timestamp:Date.now(),type:"interrupt",interrupt:u};try{let l=await this.interruptHandler.waitForUser(),p=++this.streamEpoch;yield*this.pipeStream(l,p)}catch(l){if(l){yield{runId:this.threadId,timestamp:Date.now(),type:"error",error:{message:l?.message}};return}yield{runId:this.threadId,timestamp:Date.now(),type:"cancelled"};return}}let c=(await this.graph.getState(s,{subgraphs:!0})).values;this.chatHistory=c.messages.length?c.messages:this.chatHistory,yield{runId:this.threadId,timestamp:Date.now(),type:"completed",result:{content:Oq(c.messages)}}}newConversation(){this.chatHistory=[]}resumeInterrupt(t){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,t)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}async*pipeStream(t,r){for await(let n of t){if(r!==this.streamEpoch){console.log("Stale stream detected, aborting.");break}n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:this.threadId,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:this.threadId,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}},Qq=wn.object({name:wn.string(),description:wn.string(),valueType:wn.string(),alias:wn.string()}),VDe=wn.object({fields:wn.array(Qq)});var ZDe=wn.object({title:wn.string(),description:wn.string(),name:wn.string().nullable()});return{a:Vd,b:Ri,c:ot,d:Wt,e:at,f:$e,g:si,h:ce,i:Jp,j:Fn,k:Ae,l:xe,m:$t,n:jr,o:Pt,p:sr,q:ds,r:zg,s:wn,t:Os,u:UDe,v:FDe,w:Nq,x:BDe,y:vz}},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request")
@@ -39,6 +39,8 @@ Use the most recent relevant user question from the chat history. The question w
39
39
  - Use fields with the **highest \`relevanceScore\`**.
40
40
  - DO NOT use subqueries or \`SELECT\` keyword.
41
41
  - Combine conditions with \`AND\`, \`OR\`, or \`NOT\` as appropriate.
42
+ - **Coded-value domain fields** \u2192 Always use the numeric/string **code** in WHERE clauses, never the domain name. Domain values are listed under each field as \`code=name\` pairs
43
+ - **Range domain fields** \u2192 Use the listed min/max as valid bounds for comparisons.
42
44
  - If no meaningful layer filter can be generated, do not call a tool.
43
45
 
44
46
  ### Mixed Questions
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./E77IJ3SU.js";import b from"./EH66ASBE.js";import{a as r,b as e}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as a,z as s}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{b:i}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-data-exploration-agent"),e(this)}};s("arcgis-assistant-data-exploration-agent",t);return t},b,c)
2
+ import c from"./F2UO6SO4.js";import b from"./PTDPFR7R.js";import{a as r,b as e}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as a,z as s}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{b:i}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-data-exploration-agent"),e(this)}};s("arcgis-assistant-data-exploration-agent",t);return t},b,c)
@@ -59,6 +59,8 @@ Make no tool call when:
59
59
  - Use fields with the **highest \`relevanceScore\`**.
60
60
  - DO NOT use subqueries or \`SELECT\` keyword.
61
61
  - Combine conditions with \`AND\`, \`OR\`, or \`NOT\` as appropriate.
62
+ - **Coded-value domain fields** \u2192 Always use the numeric/string **code** in WHERE clauses, never the domain name. Domain values are listed under each field as \`code=name\` pairs
63
+ - **Range domain fields** \u2192 Use the listed min/max as valid bounds for comparisons.
62
64
  - If no meaningful layer filter can be generated, do not call a tool.
63
65
 
64
66
  ## Top N / Ranked queries
package/dist/cdn/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{p as e,y as s}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";var t=e(s,{"arcgis-assistant":[()=>import("./I5KOHNUY.js"),"_messages:,copyEnabled,description,entryMessage,feedbackEnabled,heading,keepSuggestedPrompts,logEnabled,messages:,orchestrator:,referenceElement,suggestedPrompts:;clearChatHistory,submitMessage;register"],"arcgis-assistant-agent":[()=>import("./AGZUEMOX.js"),"agent:,context:;;getContext"],"arcgis-assistant-data-exploration-agent":[()=>import("./2XALI4ZK.js"),"referenceElement;;getContext"],"arcgis-assistant-help-agent":[()=>import("./LKI5DI3H.js"),"referenceElement;;getContext"],"arcgis-assistant-layer-filter-agent":[()=>import("./XWE57GB7.js"),"referenceElement;;getContext"],"arcgis-assistant-layer-query-agent":[()=>import("./DARXCM4F.js"),"referenceElement;;getContext"],"arcgis-assistant-layer-styling-agent":[()=>import("./2YSKWJQE.js"),"referenceElement;;getContext"],"arcgis-assistant-navigation-agent":[()=>import("./7X4WODN4.js"),"referenceElement;;getContext"],"arcgis-assistant-chat":[()=>import("./NVDHSI7U.js"),"copyEnabled,feedbackEnabled,loading,loadingMessage,logEnabled,messages:,user"],"arcgis-assistant-chat-card":[()=>import("./XDZPERQF.js"),"_messages:,content,copyEnabled,error,feedbackEnabled,loading,loadingMessage,log:,logEnabled,message:,messageRole,user"],"arcgis-assistant-chat-card-content":[()=>import("./HWZW3JSY.js"),"content,loading,loadingMessage,type"],"arcgis-assistant-chat-entry":[()=>import("./ZGRFMSA2.js"),"_messages:,awaitingResponse,entryPlaceholder,inputValue,keyboardShortcutsDisabled,messages:,status"],"arcgis-assistant-interrupt":[()=>import("./MYKSIL6I.js"),"_messages:,message,options:,type"],"arcgis-assistant-shell":[()=>import("./PQHYDFCL.js"),"_messages:,awaitingResponse,description,entryMessage,entryMessageClosed,heading,inputValue,loading,messages:,status,suggestedPrompts:"]});t({resourcesUrl:import.meta.url});var a=new CSSStyleSheet;a.replaceSync("@layer{:not([hydrated]):is(arcgis-assistant,arcgis-assistant-agent,arcgis-assistant-data-exploration-agent,arcgis-assistant-help-agent,arcgis-assistant-layer-filter-agent,arcgis-assistant-layer-query-agent,arcgis-assistant-layer-styling-agent,arcgis-assistant-navigation-agent,arcgis-assistant-chat,arcgis-assistant-chat-card,arcgis-assistant-chat-card-content,arcgis-assistant-chat-entry,arcgis-assistant-interrupt,arcgis-assistant-shell){visibility:hidden}}");document.adoptedStyleSheets=[...document.adoptedStyleSheets,a];window.$arcgis||Object.defineProperty(window,"$arcgis",{configurable:!1,enumerable:!0,writable:!1,value:{}}),((a,r,p,j,i=(a.importMap??={}).imports??={})=>{"utils".split(",").map(e=>i[p+e+j]=i[p+e]=import.meta.resolve("./"+e+j));a.t=(c,...x)=>Promise.all(x.map(x=>x.then?x:(!a?.forceESM&&a?.import||(x=>import(x+".js").then(m=>m.default??m)))("@arcgis/core/"+x))).then(c);r.p=a.t(([m])=>{r.t=m.trackAccess;r.o=m.createObservable;r.c=m.createTrackingTarget;r.r=m.runTracked},"applications/Components/reactiveUtils")})($arcgis,s,"@arcgis/ai-components/",".js")
2
+ import{p as e,y as s}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";var t=e(s,{"arcgis-assistant":[()=>import("./LZ7ZI65E.js"),"_messages:,copyEnabled,description,entryMessage,feedbackEnabled,heading,keepSuggestedPrompts,logEnabled,messages:,orchestrator:,referenceElement,suggestedPrompts:;clearChatHistory,submitMessage;register"],"arcgis-assistant-agent":[()=>import("./AGZUEMOX.js"),"agent:,context:;;getContext"],"arcgis-assistant-data-exploration-agent":[()=>import("./XKAASU5X.js"),"referenceElement;;getContext"],"arcgis-assistant-help-agent":[()=>import("./4GZDQE56.js"),"referenceElement;;getContext"],"arcgis-assistant-layer-filter-agent":[()=>import("./ENDNSNQH.js"),"referenceElement;;getContext"],"arcgis-assistant-layer-query-agent":[()=>import("./C3VBX534.js"),"referenceElement;;getContext"],"arcgis-assistant-layer-styling-agent":[()=>import("./L7XZIZCR.js"),"referenceElement;;getContext"],"arcgis-assistant-navigation-agent":[()=>import("./7UC775RA.js"),"referenceElement;;getContext"],"arcgis-assistant-chat":[()=>import("./NVDHSI7U.js"),"copyEnabled,feedbackEnabled,loading,loadingMessage,logEnabled,messages:,user"],"arcgis-assistant-chat-card":[()=>import("./XDZPERQF.js"),"_messages:,content,copyEnabled,error,feedbackEnabled,loading,loadingMessage,log:,logEnabled,message:,messageRole,user"],"arcgis-assistant-chat-card-content":[()=>import("./HWZW3JSY.js"),"content,loading,loadingMessage,type"],"arcgis-assistant-chat-entry":[()=>import("./ZGRFMSA2.js"),"_messages:,awaitingResponse,entryPlaceholder,inputValue,keyboardShortcutsDisabled,messages:,status"],"arcgis-assistant-interrupt":[()=>import("./MYKSIL6I.js"),"_messages:,message,options:,type"],"arcgis-assistant-shell":[()=>import("./PQHYDFCL.js"),"_messages:,awaitingResponse,description,entryMessage,entryMessageClosed,heading,inputValue,loading,messages:,status,suggestedPrompts:"]});t({resourcesUrl:import.meta.url});var a=new CSSStyleSheet;a.replaceSync("@layer{:not([hydrated]):is(arcgis-assistant,arcgis-assistant-agent,arcgis-assistant-data-exploration-agent,arcgis-assistant-help-agent,arcgis-assistant-layer-filter-agent,arcgis-assistant-layer-query-agent,arcgis-assistant-layer-styling-agent,arcgis-assistant-navigation-agent,arcgis-assistant-chat,arcgis-assistant-chat-card,arcgis-assistant-chat-card-content,arcgis-assistant-chat-entry,arcgis-assistant-interrupt,arcgis-assistant-shell){visibility:hidden}}");document.adoptedStyleSheets=[...document.adoptedStyleSheets,a];window.$arcgis||Object.defineProperty(window,"$arcgis",{configurable:!1,enumerable:!0,writable:!1,value:{}}),((a,r)=>{a.t=(c,...x)=>Promise.all(x.map(x=>x.then?x:(!a?.forceESM&&a?.import||(x=>import(x+".js").then(m=>m.default??m)))("@arcgis/core/"+x))).then(c);r.p=a.t(([m])=>{r.t=m.trackAccess;r.o=m.createObservable;r.c=m.createTrackingTarget;r.r=m.runTracked},"applications/Components/reactiveUtils")})($arcgis,s)
@@ -15,13 +15,14 @@ import type { ArcgisMap as ArcgisMap } from "@arcgis/map-components/components/a
15
15
  * agent for the assistant to function. You can register agents declaratively using any of the
16
16
  * available agent components, or you can register custom agents.
17
17
  *
18
- * ## Register ArcGIS agents
18
+ * ## Register agents
19
19
  *
20
- * To register ArcGIS agents declaratively, include one or more of the following agent components as children
20
+ * To register agents declaratively, include one or more agent components as children
21
21
  * of the `arcgis-assistant` component. This can be done in HTML or programmatically using JavaScript.
22
22
  *
23
23
  * ```html
24
- * <arcgis-assistant>
24
+ * <arcgis-map id="my-map"></arcgis-map>
25
+ * <arcgis-assistant reference-element="#my-map">
25
26
  * <arcgis-assistant-navigation-agent></arcgis-assistant-navigation-agent>
26
27
  * <arcgis-assistant-data-exploration-agent></arcgis-assistant-data-exploration-agent>
27
28
  * <arcgis-assistant-help-agent></arcgis-assistant-help-agent>
@@ -36,6 +37,10 @@ import type { ArcgisMap as ArcgisMap } from "@arcgis/map-components/components/a
36
37
  * assistant.appendChild(dataExplorationAgent);
37
38
  * ```
38
39
  *
40
+ * Note that the `reference-element` property on the `arcgis-assistant` component must point to a valid `arcgis-map` element
41
+ * for the included ArcGIS agents to function properly, as they rely on the map context to perform their tasks. This is not
42
+ * a requirement for [custom agents](https://developers.arcgis.com/javascript/latest/agentic-apps/ai-custom-agents/).
43
+ *
39
44
  * ## Context
40
45
  *
41
46
  * Use the [referenceElement](https://developers.arcgis.com/javascript/latest/references/ai-components/components/arcgis-assistant/#referenceElement) property to provide a web map as context to the assistant and its agents.
@@ -44,6 +49,16 @@ import type { ArcgisMap as ArcgisMap } from "@arcgis/map-components/components/a
44
49
  *
45
50
  * To learn more about this component, try out the [demo](https://developers.arcgis.com/javascript/latest/references/ai-components/components/arcgis-assistant/#demos)
46
51
  *
52
+ * ## Important considerations and best practices
53
+ *
54
+ * Due to the non-deterministic nature of generative AI, there may be inaccuracies or unexpected behavior when using the
55
+ * out-of-the-box agents. Therefore, it is important to set clear expectations
56
+ * for end users and provide guidance on how to interact with the assistant to help mitigate these issues. Some ways to do this include:
57
+ *
58
+ * - Provide [suggestedPrompts](https://developers.arcgis.com/javascript/latest/references/ai-components/components/arcgis-assistant/#suggestedPrompts). This helps users understand the bounds of the assistant
59
+ * and gives them an idea of how to phrase questions to get the best results.
60
+ * - Use the [entryMessage](https://developers.arcgis.com/javascript/latest/references/ai-components/components/arcgis-assistant/#entryMessage) property to provide an entry message with instructions and guidance.
61
+ *
47
62
  * @slot - This is the default slot
48
63
  * @slot [header-actions-end] - Slot for adding actions to the end of the header.
49
64
  * @slot [entry-message] - Slot for adding a welcome or entry message on load.
@@ -51,6 +66,8 @@ import type { ArcgisMap as ArcgisMap } from "@arcgis/map-components/components/a
51
66
  * @slot [footer-content] - Slot for adding content to the footer.
52
67
  * @since 5.0
53
68
  * @beta
69
+ * @see [Intro to building agentic mapping applications](https://developers.arcgis.com/javascript/latest/agentic-apps/ai-introduction/)
70
+ * @see [AI Assistant component sample](https://developers.arcgis.com/javascript/latest/sample-code/ai-assistant/)
54
71
  * @see [arcgis-assistant-data-exploration-agent](https://developers.arcgis.com/javascript/latest/references/ai-components/components/arcgis-assistant-data-exploration-agent/)
55
72
  * @see [arcgis-assistant-navigation-agent](https://developers.arcgis.com/javascript/latest/references/ai-components/components/arcgis-assistant-navigation-agent/)
56
73
  * @see [arcgis-assistant-help-agent](https://developers.arcgis.com/javascript/latest/references/ai-components/components/arcgis-assistant-help-agent/)
@@ -59,7 +76,7 @@ export abstract class ArcgisAssistant extends LitElement {
59
76
  /** @internal */
60
77
  protected _messages: { assistantLabel: string; } & T9nMeta<{ assistantLabel: string; }>;
61
78
  /**
62
- * When `true`, enables the copy action that when clicked copies the content of the message to the clipboard. This can be helpful for users to easily copy and share
79
+ * When `true`, enables the copy action that, when clicked, copies the content of the message to the clipboard. This can be helpful for users to easily copy and share
63
80
  * information provided by the assistant, such as a summary of findings, a set of instructions, or any other relevant details. Enabling this property can enhance the user experience by providing a convenient way for users to capture and utilize the information generated by the assistant.
64
81
  *
65
82
  * @default false
@@ -90,7 +107,7 @@ export abstract class ArcgisAssistant extends LitElement {
90
107
  */
91
108
  accessor description: string | undefined;
92
109
  /**
93
- * The message to display when the assistant is first loaded. This is intended to be a welcome or entry message that
110
+ * The instructions to display when the assistant is first loaded. This is intended to be a welcome or entry message that
94
111
  * provides guidance to users on how to interact with the assistant. Once the user submits their first message,
95
112
  * the entry message will be closed and replaced with the chat interface. You can use this property to provide
96
113
  * instructions, suggest prompts, or simply welcome users to the assistant.
@@ -134,7 +151,7 @@ export abstract class ArcgisAssistant extends LitElement {
134
151
  *
135
152
  * For applications where the primary interface is the assistant, this heading could also be used as the
136
153
  * application title. In cases where the assistant could be collapsed or is a secondary interface to a standard
137
- * GUI application, the heading should be more specific to the assistant's function to avoid confusion with the overall
154
+ * GUI, the heading should be more specific to the assistant's function to avoid confusion with the overall
138
155
  * application title.
139
156
  *
140
157
  * @example
@@ -144,7 +161,7 @@ export abstract class ArcgisAssistant extends LitElement {
144
161
  * @example
145
162
  * ```js
146
163
  * const assistant = document.querySelector("arcgis-assistant");
147
- * assistant.heading = "Parcel Viewer";
164
+ * assistant.heading = "Zoning Assistant";
148
165
  * ```
149
166
  */
150
167
  accessor heading: string | undefined;
@@ -196,7 +213,7 @@ export abstract class ArcgisAssistant extends LitElement {
196
213
  /**
197
214
  * The reference element to the map that provides context for the assistant and its agents. Currently,
198
215
  * this is only scoped to `arcgis-map` elements. This is required when ArcGIS agents are registered to the assistant.
199
- * For example, this allows the navigation agent to know which view on which to perform navigation.
216
+ * For example, this allows the navigation agent to execute a map navigation tool for a specific map.
200
217
  *
201
218
  * @example
202
219
  * ```html