@arcgis/ai-components 5.2.0-next.71 → 5.2.0-next.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +4 -2
- package/dist/agent-utils/types.d.ts +1 -1
- package/dist/agentic-workflow/AgenticWorkflowRuntime.d.ts +24 -0
- package/dist/agentic-workflow/Edge.d.ts +16 -0
- package/dist/agentic-workflow/WebAgent.d.ts +39 -0
- package/dist/agentic-workflow/jsonTypes.d.ts +186 -0
- package/dist/agentic-workflow/nodes/AgentNode.d.ts +26 -0
- package/dist/agentic-workflow/nodes/BaseNode.d.ts +35 -0
- package/dist/agentic-workflow/nodes/EndMessageNode.d.ts +25 -0
- package/dist/agentic-workflow/nodes/StartNode.d.ts +21 -0
- package/dist/agentic-workflow/nodes/support/Prompt.d.ts +20 -0
- package/dist/agentic-workflow/types.d.ts +29 -0
- package/dist/cdn/{PUFTYLJ2.js → 33BF35AO.js} +1 -1
- package/dist/cdn/55M2HE4U.js +2 -0
- package/dist/cdn/5RZGG4F2.js +2 -0
- package/dist/cdn/5SF6DEMO.js +2 -0
- package/dist/cdn/{MW5S2XCB.js → 5SFZS2RD.js} +1 -1
- package/dist/cdn/6QJFOL6M.js +2 -0
- package/dist/cdn/BAB3MK4Y.js +2 -0
- package/dist/cdn/BMBV6Y2A.js +2 -0
- package/dist/cdn/D3RKQSWS.js +2 -0
- package/dist/cdn/DBHLKLKM.js +2 -0
- package/dist/cdn/{CXW5URTF.js → DWYODVWW.js} +1 -1
- package/dist/cdn/{TFT6HK3O.js → E7KEOJZG.js} +1 -1
- package/dist/cdn/FSMHR7GK.js +2 -0
- package/dist/cdn/HO2YDJI2.js +6 -0
- package/dist/cdn/{KQHLOYKL.js → I4L45WQS.js} +1 -1
- package/dist/cdn/IGQFAL3H.js +2 -0
- package/dist/cdn/JYVBCHR6.js +6 -0
- package/dist/cdn/{XETNZW4D.js → NJJYZP3R.js} +1 -1
- package/dist/cdn/NSXX2KYS.js +2 -0
- package/dist/cdn/OFRFP4BX.js +2 -0
- package/dist/cdn/OUFGJV3R.js +2 -0
- package/dist/cdn/PAUIFUMO.js +2 -0
- package/dist/cdn/RWM5T4XB.js +180 -0
- package/dist/cdn/{YHQJ66WJ.js → S3XUYAUX.js} +1 -1
- package/dist/cdn/S6ZAQRC6.js +2 -0
- package/dist/cdn/SRFLL6ET.js +2 -0
- package/dist/cdn/UZL6UVE4.js +2 -0
- package/dist/cdn/{GP6NDTUE.js → WDOM6Z5O.js} +2 -2
- package/dist/cdn/WQKNV6KK.js +2 -0
- package/dist/cdn/{ICYUPLZM.js → WZFC5HUX.js} +1 -1
- package/dist/cdn/XPTCV6YV.js +2 -0
- package/dist/cdn/Y5UFOH54.js +2 -0
- package/dist/cdn/{E5ZKBC24.js → Z4XUJQ2I.js} +2 -2
- package/dist/cdn/{SXHH575T.js → ZJEWP2ND.js} +20 -24
- package/dist/cdn/agent-utils/index.js +1 -1
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
- package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
- package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/adapter.js +668 -679
- package/dist/chunks/baseAgentState.js +56 -0
- package/dist/chunks/dataExplorationGraph.js +13 -13
- package/dist/chunks/generateLayerDescriptions.js +189 -235
- package/dist/chunks/navigationGraph.js +28 -28
- package/dist/chunks/orchestrator.js +1 -1
- package/dist/chunks/state.js +20 -26
- package/dist/chunks/utils2.js +3 -3
- package/dist/components/arcgis-assistant-agent/customElement.d.ts +13 -1
- package/dist/components/arcgis-assistant-agent/customElement.js +513 -12
- package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -1
- package/dist/components/arcgis-assistant-help-agent/customElement.js +1 -1
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -1
- package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -1
- package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/vscode.html-custom-data.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/loader.js +1 -1
- package/dist/types/lumina.d.ts +1 -1
- package/dist/types/preact.d.ts +1 -1
- package/dist/types/react.d.ts +1 -1
- package/dist/types/stencil.d.ts +1 -1
- package/dist/utils/index.js +26 -25
- package/package.json +4 -4
- package/dist/cdn/3DJDRAGV.js +0 -2
- package/dist/cdn/4CEMUECT.js +0 -2
- package/dist/cdn/4PCAK3ET.js +0 -2
- package/dist/cdn/57OMVTIU.js +0 -2
- package/dist/cdn/6U7TEAAJ.js +0 -2
- package/dist/cdn/BE7ZN5FZ.js +0 -2
- package/dist/cdn/BNSJO6X2.js +0 -2
- package/dist/cdn/CMDRED5H.js +0 -2
- package/dist/cdn/DTIVDIDY.js +0 -2
- package/dist/cdn/HBLRVXEB.js +0 -2
- package/dist/cdn/HQXPPYMD.js +0 -2
- package/dist/cdn/IEHPNCTL.js +0 -2
- package/dist/cdn/LHLO6PTD.js +0 -2
- package/dist/cdn/OWXCOUIQ.js +0 -2
- package/dist/cdn/PVE7Q43N.js +0 -2
- package/dist/cdn/ST5FQYT7.js +0 -180
- package/dist/cdn/WUNCZOGU.js +0 -2
- package/dist/cdn/WVPU4QOO.js +0 -2
- package/dist/cdn/WXWO5D3W.js +0 -2
- package/dist/cdn/XCRR2EEG.js +0 -6
- package/dist/cdn/ZS6SXJP2.js +0 -2
|
@@ -205,4 +205,4 @@ data: ${JSON.stringify({message:String(n)})}
|
|
|
205
205
|
|
|
206
206
|
`))}finally{r.close()}}})}var Om=class{static subscribeTo(e,t){let{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&r!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof e=="string"?r?s={[r]:e}:s=[e]:s=Object.fromEntries(e.map(i=>[i,i])),new lt({channels:s,triggers:Array.isArray(e)?e:[e],tags:n})}static writeTo(e,t){let r=[];for(let n of e)r.push({channel:n,value:Be,skipNone:!1});for(let[n,s]of Object.entries(t??{}))H.isRunnable(s)||typeof s=="function"?r.push({channel:n,value:Be,skipNone:!0,mapper:we(s)}):r.push({channel:n,value:s,skipNone:!1});return new te(r)}},uy=class extends H{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)}},oa=class extends uy{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;streamTransformers;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,"__pregel_tasks"in this.channels&&"lc_graph_name"in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!=="Topic")throw new Error(`Channel '${_t}' is reserved and cannot be used in the graph.`);this.channels[_t]=new pc({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}withConfig(e){let{streamTransformers:t,...r}=e,n=Le(this.config,r),s=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:n,streamTransformers:s})}validate(){Im({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let r of t.triggers)this.triggerToNodes[r]??=[],this.triggerToNodes[r].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[r,n]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(r))continue;let s=n.subgraphs?.length?n.subgraphs:[n.bound];for(let i of s){let a=Yi(i);if(a!==void 0){if(r===e){yield[r,a];return}if(e===void 0&&(yield[r,a]),t){let o=e;e!==void 0&&(o=e.slice(r.length+1));for(let[c,l]of a.getSubgraphs(o,t))yield[`${r}|${c}`,l]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:n=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let s=await hn(this.channels,t.checkpoint,{saver:typeof this.checkpointer=="object"?this.checkpointer:void 0,config:t.config??e});if(t.pendingWrites?.length){let h=t.pendingWrites.filter(([p,m])=>p===Me).map(([p,m,d])=>[String(m),d]);h.length>0&&Re(t.checkpoint,s,[{name:dt,writes:h,triggers:[]}],void 0,this.triggerToNodes)}let i=Object.values(fr(t.checkpoint,t.pendingWrites,this.nodes,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),a=await ct(this.getSubgraphsAsync()),o=t.config.configurable?.checkpoint_ns??"",c={};for(let h of i){let p=a.find(([d])=>d===h.name);if(!p)continue;let m=`${String(h.name)}:${h.id}`;if(o&&(m=`${o}|${m}`),r===void 0){let d={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:m}};c[h.id]=d}else{let d={configurable:{[We]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:m}},y=p[1];c[h.id]=await y.getState(d,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){let h=Object.fromEntries(i.map(m=>[m.id,m]));for(let[m,d,y]of t.pendingWrites)["__error__","__interrupt__",Mr].includes(d)||m in h&&h[m].writes.push([String(d),y]);let p=i.filter(m=>m.writes.length>0);p.length>0&&Re(t.checkpoint,s,p,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});let u=i.filter(h=>h.writes.length===0).map(h=>h.name);return{values:ut(s,this.streamChannelsAsIs),next:u,tasks:sc(i,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:hr(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let r=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!r)throw new Nr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_read===void 0&&e.configurable?.__pregel_checkpointer===void 0){let a=ji(n);for await(let[o,c]of this.getSubgraphsAsync(a,!0))if(o===a)return await c.getState(Fr(e,{[We]:r}),{subgraphs:t?.subgraphs})}let s=Le(this.config,e),i=await r.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:i,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let r=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!r)throw new Nr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_checkpointer===void 0){let i=ji(n);for await(let[a,o]of this.getSubgraphsAsync(i,!0))if(a===i){yield*o.getStateHistory(Fr(e,{[We]:r}),t);return}}let s=Le(this.config,e,{configurable:{checkpoint_ns:n}});for await(let i of r.list(s,t))yield this._prepareStateSnapshot({config:i.config,saved:i})}async bulkUpdateState(e,t){let r=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!r)throw new Nr("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(a=>a.updates.length===0))throw new Error("No updates provided");let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.__pregel_checkpointer===void 0){let a=ji(n);for await(let[,o]of this.getSubgraphsAsync(a,!0))return await o.bulkUpdateState(Fr(e,{[We]:r}),t);throw new Error(`Subgraph "${a}" not found`)}let s=async(a,o)=>{let c=this.config?Le(this.config,a):a,l=await r.getTuple(c),u=l!==void 0?it(l.checkpoint):Dr(),h={...l?.checkpoint.channel_versions},p=l?.metadata?.step??-1,m=Fr(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),d=c.metadata??{};l?.config.configurable&&(m=Fr(c,l.config.configurable),d={...l.metadata,...d});let{values:y,asNode:v}=o[0];if(y==null&&v===void 0){if(o.length>1)throw new $("Cannot create empty checkpoint with multiple updates");return hr(await r.put(m,at(u,void 0,p),{source:"update",step:p+1,parents:l?.metadata?.parents??{}},{}),l?l.metadata:void 0)}let b=await hn(this.channels,u,{saver:r,config:l?.config??m});if(y===null&&v==="__end__"){if(o.length>1)throw new $("Cannot apply multiple updates when clearing state");if(l){let x=fr(u,l.pendingWrites||[],this.nodes,b,l.config,!0,{step:(l.metadata?.step??-1)+1,checkpointer:r,store:this.store}),_=(l.pendingWrites||[]).filter(P=>P[0]===Me).map(P=>P.slice(1));_.length>0&&Re(u,b,[{name:dt,writes:_,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[P,M,F]of l.pendingWrites||[])["__error__","__interrupt__",Mr].includes(M)||P in x&&x[P].writes.push([M,F]);Re(u,b,Object.values(x),r.getNextVersion.bind(r),this.triggerToNodes)}return hr(await r.put(m,at(u,b,p),{...d,source:"update",step:p+1,parents:l?.metadata?.parents??{}},yn(h,u.channel_versions)),l?l.metadata:void 0)}if(v==="__copy__"){if(o.length>1)throw new $("Cannot copy checkpoint with multiple updates");if(l==null)throw new $("Cannot copy a non-existent checkpoint");let x=M=>!Array.isArray(M)||M.length===0?!1:M.every(F=>Array.isArray(F)&&F.length===2),_=at(u,void 0,p),P=await r.put(l.parentConfig??Fr(l.config,{checkpoint_id:void 0}),_,{source:"fork",step:p+1,parents:l.metadata?.parents??{}},{});if(x(y)){let M=fr(_,l.pendingWrites,this.nodes,b,P,!1,{step:p+2}),F=Object.values(M).reduce((G,{name:z,id:_e})=>(G[z]??=[],G[z].push({id:_e}),G),{}),j=y.reduce((G,z)=>{let[_e,V]=z;G[V]??=[];let N=G[V].length,R=F[V]?.[N]?.id;return G[V].push({values:_e,asNode:V,taskId:R}),G},{});return s(hr(P,l.metadata),Object.values(j).flat())}return hr(P,l.metadata)}if(v==="__input__"){if(o.length>1)throw new $("Cannot apply multiple updates when updating as input");let x=await ct(Xi(this.inputChannels,y));if(x.length===0)throw new $(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Re(u,b,[{name:dt,writes:x,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=l?.metadata?.step!=null?l.metadata.step+1:-1,P=await r.put(m,at(u,b,_),{source:"input",step:_,parents:l?.metadata?.parents??{}},yn(h,u.channel_versions));return await r.putWrites(P,x,yt(dt,u.id)),hr(P,l?l.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&l?.pendingWrites!==void 0&&l.pendingWrites.length>0){let x=fr(u,l.pendingWrites,this.nodes,b,l.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(l.metadata?.step??-1)+1}),_=(l.pendingWrites??[]).filter(M=>M[0]===Me).map(M=>M.slice(1));_.length>0&&Re(l.checkpoint,b,[{name:dt,writes:_,triggers:[]}],void 0,this.triggerToNodes);for(let[M,F,j]of l.pendingWrites)["__error__","__interrupt__",Mr].includes(F)||x[M]===void 0||x[M].writes.push([F,j]);let P=Object.values(x).filter(M=>M.writes.length>0);P.length>0&&Re(u,b,P,void 0,this.triggerToNodes)}let S=Object.values(u.versions_seen).map(x=>Object.values(x)).flat().find(x=>!!x),k=[];if(o.length===1){let{values:x,asNode:_,taskId:P}=o[0];if(_===void 0&&Object.keys(this.nodes).length===1)[_]=Object.keys(this.nodes);else if(_===void 0&&S===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(_=this.inputChannels);else if(_===void 0){let M=Object.entries(u.versions_seen).map(([F,j])=>Object.values(j).map(G=>[G,F])).flat().filter(([F,j])=>j!==Y).sort(([F],[j])=>Ai(F,j));M&&(M.length===1?_=M[0][1]:M[M.length-1][0]!==M[M.length-2][0]&&(_=M[M.length-1][1]))}if(_===void 0)throw new $('Ambiguous update, specify "asNode"');k.push({values:x,asNode:_,taskId:P})}else for(let{asNode:x,values:_,taskId:P}of o){if(x==null)throw new $('"asNode" is required when applying multiple updates');k.push({values:_,asNode:x,taskId:P})}let C=[];for(let{asNode:x,values:_,taskId:P}of k){if(this.nodes[x]===void 0)throw new $(`Node "${x.toString()}" does not exist`);let M=this.nodes[x].getWriters();if(!M.length)throw new $(`No writers found for node "${x.toString()}"`);C.push({name:x,input:_,proc:M.length>1?et.from(M,{omitSequenceTags:!0}):M[0],writes:[],triggers:[Y],id:P??yt("__interrupt__",u.id),writers:[]})}for(let x of C)await x.proc.invoke(x.input,he({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[Se]:_=>x.writes.push(..._),[Ie]:(_,P=!1)=>bn(u,b,x,_,P)}}));for(let x of C){let _=x.writes.filter(P=>P[0]!==Ne);l!==void 0&&_.length>0&&await r.putWrites(m,_,x.id)}Re(u,b,C,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let T=yn(h,u.channel_versions),O=await r.put(m,at(u,b,p+1),{source:"update",step:p+1,parents:l?.metadata?.parents??{}},T);for(let x of C){let _=x.writes.filter(P=>P[0]===Ne);_.length>0&&await r.putWrites(O,_,x.id)}return hr(O,l?l.metadata:void 0)},i=e;for(let{updates:a}of t)i=await s(i,a);return i}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){let{debug:t,streamMode:r,inputKeys:n,outputKeys:s,interruptAfter:i,interruptBefore:a,...o}=e,c=!0,l=t!==void 0?t:this.debug,u=s;u===void 0?u=this.streamChannelsAsIs:hc(u,this.channels);let h=n;h===void 0?h=this.inputChannels:hc(h,this.channels);let p=a??this.interruptBefore??[],m=i??this.interruptAfter??[],d;r!==void 0?(d=Array.isArray(r)?r:[r],c=typeof r=="string"):(e.configurable?.__pregel_task_id!==void 0?d=["values"]:d=this.streamMode,c=!0);let y;if(this.checkpointer===!1)y=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)y=e.configurable[We];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");y=this.checkpointer}let v=e.store??this.store,b=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 S=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),k=e.durability??S??e?.configurable?.__pregel_durability??"async";return[l,d,h,u,o,p,m,y,v,c,b,k]}async stream(e,t){let r=new AbortController,n=Fi()?.configurable;n?.__pregel_read!==void 0&&t?.configurable?.__pregel_read===void 0&&(t={...t,configurable:{...n,...t?.configurable}});let s={recursionLimit:this.config?.recursionLimit,...t,signal:pr(t?.signal,r.signal).signal},i=await super.stream(e,s);return new sa(t?.encoding==="text/event-stream"?mm(i):i,r)}async#e(e,t){let{version:r,encoding:n,transformers:s,...i}=t,a={recursionLimit:this.config?.recursionLimit,...i,configurable:{...this.config?.configurable,...i?.configurable},version:r,streamMode:Fo,subgraphs:!0,encoding:void 0},o=this.stream(e,a),c=qo({[Symbol.asyncIterator]:async function*(){let l=await o;for await(let u of l)yield u}},[...this.streamTransformers??[],...s??[]]);if(n==="text/event-stream"){let l=new AbortController;return l.signal.addEventListener("abort",()=>c.abort(l.signal.reason),{once:!0}),new sa(ly(c),l)}return c}streamEvents(e,t,r){if(t.version==="v3")return this.#e(e,t);let n=new AbortController,s={recursionLimit:this.config?.recursionLimit,...t,signal:pr(t?.signal,n.signal).signal};return new sa(super.streamEvents(e,s,r),n)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let r="version"in(t??{})?void 0:t?.encoding??void 0,n=t?.subgraphs,s=t?.version==="v3",i=pn(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');let a=await this._validateInput(e),{runId:o,...c}=i,[l,u,,h,p,m,d,y,v,b,S,k]=this._defaults(c);p.metadata={ls_integration:"langgraph",...p.metadata},typeof p.context<"u"?p.context=await this._validateContext(p.context):p.configurable=await this._validateContext(p.configurable);let C=new ac({modes:new Set(u)});if(this.checkpointer===!0){p.configurable??={};let j=p.configurable.checkpoint_ns??"";p.configurable[Ue]=j.split("|").map(G=>G.split(":")[0]).join("|")}if(u.includes("messages")){let j=s?new Em(z=>C.push(z)):new Sm(z=>C.push(z)),{callbacks:G}=p;if(G===void 0)p.callbacks=[j];else if(Array.isArray(G))p.callbacks=G.concat(j);else{let z=G.copy();z.addHandler(j,!0),p.callbacks=z}}if(u.includes("tools")){let j=new fm(z=>C.push(z)),{callbacks:G}=p;if(G===void 0)p.callbacks=[j];else if(Array.isArray(G))p.callbacks=G.concat(j);else{let z=G.copy();z.addHandler(j,!0),p.callbacks=z}}p.writer??=j=>{if(!u.includes("custom"))return;let G=Fi()?.configurable?.[Ue]?.split("|").slice(0,-1);C.push([G??[],"custom",j])},p.interrupt??=this.userInterrupt??Zo,p.serverInfo==null&&(p.serverInfo=hy(p)),p.control??=new Lo;let T={tracerInheritableMetadata:my(p)},O=await(await De._configureSync(p?.callbacks,void 0,p?.tags,void 0,p?.metadata,void 0,T))?.handleChainStart(this.toJSON(),Xf(e,"input"),o,void 0,void 0,void 0,p?.runName??this.getName()),x=un(this.channels),_,P,F=(async()=>{try{_=await bm.initialize({input:a,config:p,checkpointer:y,nodes:this.nodes,channelSpecs:x,outputKeys:h,streamKeys:this.streamChannelsAsIs,store:v,cache:S,stream:C,interruptAfter:d,interruptBefore:m,manager:O,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:k});let j=new xm({loop:_,nodeFinished:p.configurable?.[xu]});t?.subgraphs&&(_.config.configurable={..._.config.configurable,[Dn]:_.stream}),await this._runLoop({loop:_,runner:j,debug:l,config:p}),k==="sync"&&await Promise.all(_?.checkpointerPromises??[])}catch(j){P=j}finally{try{_&&(await _.store?.stop(),await _.cache?.stop()),await Promise.all(_?.checkpointerPromises??[])}catch(j){P=P??j}P?(await new Promise(j=>{queueMicrotask(j)}),C.error(P)):C.close()}})();try{for await(let j of C){if(j===void 0)throw new Error("Data structure error.");let[G,z,_e]=j,V="version"in(t??{});if(u.includes(z)||z==="checkpoints"&&fn(_e)&&(s||V&&n&&u.includes("values"))){if(r==="text/event-stream"){n?yield[G,z,_e]:yield[null,z,_e];continue}n&&!b?yield[G,z,_e]:b?n?yield[G,_e]:yield _e:yield[z,_e]}}}catch(j){throw await O?.handleChainError(P),j}finally{await F}await O?.handleChainEnd(_?.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},s=[],i=await this.stream(e,n),a=[],o;for await(let c of i)r==="values"?Or(c)?a.push(c[Y]):o=c:s.push(c);if(r==="values"){if(a.length>0){let c=a.flat(1);if(o==null)return{[Y]:c};if(typeof o=="object")return{...o,[Y]:c}}return o}return s}async _runLoop(e){let{loop:t,runner:r,debug:n,config:s}=e,i;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:a}of await t._matchCachedWrites())t._outputWrites(a.id,a.writes,!0);n&&lm(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&ys(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(a,o)=>{n&&um(a,o,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal})}if(t.status==="draining")throw t.control==null?new Error("Draining status requires run control"):new Vs(t.control.drainReason??"shutdown");if(t.status==="out_of_steps")throw new ba([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(a){if(i=a,!await t.finishAndHandleError(i))throw a}finally{i===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};function hy(e){let t=e.metadata??{},r=e.configurable??{},n=r.assistant_id??t.assistant_id,s=r.graph_id??t.graph_id,i=r.langgraph_auth_user,a;if(i!=null&&typeof i=="object"&&"identity"in i&&(a=i),n!=null||s!=null||a!=null)return{assistantId:n!=null?String(n):"",graphId:s!=null?String(s):"",user:a}}var py=new Set(["key","token","secret","password","auth"]);function fy(e,t){let r=e.toLowerCase(),n=!1;for(let s of py)if(r.includes(s)){n=!0;break}return e.startsWith("__")||!(typeof t=="string"||typeof t=="number"||typeof t=="boolean")||n}function my(e){let t=e.configurable;if(!t)return;let r={};for(let[n,s]of Object.entries(t))fy(n,s)||(r[n]=s);return Object.keys(r).length>0?r:void 0}var ht=class Nm extends ie{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let r=new Nm(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 $("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new W;return this.value[0]}checkpoint(){if(this.value.length===0)throw new W;return this.value[0]}isAvailable(){return this.value.length!==0}};var fc=class{path;ends;constructor(e){H.isRunnable(e.path)?this.path=e.path:this.path=we(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return te.registerWriter(new fe({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(s){throw s.name===Hs.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
207
207
|
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(e,t,r,n){let s=await this.path.invoke(n?n(t):e,t);Array.isArray(s)||(s=[s]);let i;if(this.ends?i=s.map(a=>ce(a)?a:this.ends[a]):i=s,i.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(i.filter(ce).some(a=>a.node==="__end__"))throw new $("Cannot send a packet to the END node");return await r(i,t)??e}},mc=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,s,i]of r){for(let o of["|",":"])if(n.includes(o))throw new Error(`"${o}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n==="__end__")throw new Error(`Node \`${n}\` is reserved.`);let a=we(s);this.nodes[n]={runnable:a,metadata:i?.metadata,subgraphs:ms(a)?[a]:i?.subgraphs,ends:i?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e==="__end__")throw new Error("END cannot be a start node");if(t==="__start__")throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([r])=>r===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){let n=typeof e=="object"?e:{source:e,path:t,pathMap:r};this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),H.isRunnable(n.path)||(n.path=we(n.path));let s=n.path.getName()==="RunnableLambda"?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[n.source]??={},this.branches[n.source][s]=new fc(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(Z,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,Q)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n,transformers:s}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);let i=new dc({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Z]:new ht,[Q]:new ht},inputChannels:Z,outputChannels:Q,streamChannels:[],streamMode:"values",name:n,streamTransformers:s});for(let[a,o]of Object.entries(this.nodes))i.attachNode(a,o);for(let[a,o]of this.edges)i.attachEdge(a,o);for(let[a,o]of Object.entries(this.branches))for(let[c,l]of Object.entries(o))i.attachBranch(a,c,l);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([n,s])=>n));for(let[n]of Object.entries(this.branches))t.add(n);for(let n of t)if(n!=="__start__"&&!(n in this.nodes))throw new Error(`Found edge starting at unknown node \`${n}\``);let r=new Set([...this.allEdges].map(([n,s])=>s));for(let[n,s]of Object.entries(this.branches))for(let i of Object.values(s))if(i.ends!=null)for(let a of Object.values(i.ends))r.add(a);else{r.add(Q);for(let a of Object.keys(this.nodes))a!==n&&r.add(a)}for(let n of Object.values(this.nodes))for(let s of n.ends??[])r.add(s);if(Object.values(this.nodes).some(n=>n.isErrorHandler))for(let n of Object.keys(this.nodes))r.add(n);for(let n of Object.keys(this.nodes))if(!this.nodes[n].isErrorHandler&&!r.has(n))throw new wa([`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(`
|
|
208
|
-
`),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!=="__end__"&&!(n in this.nodes))throw new Error(`Found edge ending at unknown node \`${n}\``);if(e){for(let n of e)if(!(n in this.nodes))throw new Error(`Interrupt node \`${n}\` is not present`)}this.compiled=!0}},dc=class extends oa{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new ht,this.nodes[e]=new lt({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new te([{channel:e,value:Be}],[se])),this.streamChannels.push(e)}attachEdge(e,t){if(t==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new te([{channel:Q,value:Be}],[se]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[Z]=Om.subscribeTo(Z,{tags:[se]})),this.nodes[e].pipe(r.run(s=>new te(s.map(i=>ce(i)?i:{channel:i==="__end__"?Q:`branch:${e}:${t}:${i}`,value:Be}),[se])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let s of n)if(s!=="__end__"){let i=`branch:${e}:${t}:${s}`;this.channels[i]=new ht,this.nodes[s].triggers.push(i),this.nodes[s].channels.push(i)}}async getGraphAsync(e){let t=e?.xray,r=new da,n={[Z]:r.addNode({schema:Qt.any()},Z)},s={},i={};t&&(i=Object.fromEntries((await ct(this.getSubgraphsAsync())).filter(l=>Mm(l[1]))));let a=[];function o(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[Q]=r.addNode({schema:Qt.any()},Q)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return a.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=ue(l),p=u.runnable,m=u.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?m.__interrupt="before,after":this.interruptBefore?.includes(l)?m.__interrupt="before":this.interruptAfter?.includes(l)&&(m.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,y=i[l]!==void 0?await i[l].getGraphAsync({...e,xray:d}):p.getGraph(e);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let S=function(C){return C?C.lc_runnable:!1},k=function(C,T){if(C!==void 0&&!pa(C))return C;if(S(T))try{let O=T.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return T.getName()}else return T.name??"UnknownSchema"},[v,b]=r.extend(y,h);if(v===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);b!==void 0&&(n[h]={name:k(b.id,b.data),...b}),s[h]={name:k(v.id,v.data),...v}}else{let v=r.addNode(p,h,m);n[h]=v,s[h]=v}}else{let d=r.addNode(p,h,m);n[h]=d,s[h]=d}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)o(ue(l),ue(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[ue(p),ue(p)])),[Q]:Q};for(let p of Object.values(u)){let m;p.ends!==void 0?m=p.ends:m=h;for(let[d,y]of Object.entries(m))o(ue(l),ue(y),d,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)o(ue(l),ue(h),void 0,!0);return Pm(this.builder.nodes,a,o),r}getGraph(e){let t=e?.xray,r=new da,n={[Z]:r.addNode({schema:Qt.any()},Z)},s={},i={};t&&(i=Object.fromEntries(ur(this.getSubgraphs()).filter(l=>Mm(l[1]))));let a=[];function o(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[Q]=r.addNode({schema:Qt.any()},Q)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return a.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=ue(l),p=u.runnable,m=u.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?m.__interrupt="before,after":this.interruptBefore?.includes(l)?m.__interrupt="before":this.interruptAfter?.includes(l)&&(m.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,y=i[l]!==void 0?i[l].getGraph({...e,xray:d}):p.getGraph(e);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let S=function(C){return C?C.lc_runnable:!1},k=function(C,T){if(C!==void 0&&!pa(C))return C;if(S(T))try{let O=T.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return T.getName()}else return T.name??"UnknownSchema"},[v,b]=r.extend(y,h);if(v===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);b!==void 0&&(n[h]={name:k(b.id,b.data),...b}),s[h]={name:k(v.id,v.data),...v}}else{let v=r.addNode(p,h,m);n[h]=v,s[h]=v}}else{let d=r.addNode(p,h,m);n[h]=d,s[h]=d}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)o(ue(l),ue(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[ue(p),ue(p)])),[Q]:Q};for(let p of Object.values(u)){let m;p.ends!==void 0?m=p.ends:m=h;for(let[d,y]of Object.entries(m))o(ue(l),ue(y),d,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)o(ue(l),ue(h),void 0,!0);return Pm(this.builder.nodes,a,o),r}};function Mm(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function ue(e){return e==="subgraph"?`"${e}"`:e}function Pm(e,t,r){let n=new Set(t.map(i=>i.src)),s=[...new Set(t.filter(i=>!i.conditional&&i.dest!=="__end__").map(i=>i.dest))].sort();for(let i of s){if(n.has(i))continue;let a=Object.keys(e).find(o=>ue(o)===i);a!==void 0&&e[a]?.isErrorHandler||r(i,Q)}}function Bt(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function gc(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function dy(e){return Bt(e)&&gc(e)}function mr(e){if(gc(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function Vt(e){if(e!=null&&Bt(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 gy=e=>e!=null&&e.lc_graph_name==="DeltaChannel",ca=class Rm extends ie{lc_graph_name="DeltaChannel";value;reducer;snapshotFrequency;initialValueFactory;constructor(t,r){super();let n=r?.snapshotFrequency??1e3;if(!Number.isInteger(n)||n<=0)throw new Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=t,this.snapshotFrequency=n,this.initialValueFactory=r?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let r=new Rm(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?r.value=this.initialValueFactory():Ta(t)?r.value=t.value:r.value=t,r}replayWrites(t){let r=t.map(a=>a[2]);if(r.length===0)return;let n=this.value,s=0;for(let a=0;a<r.length;a+=1){let[o,c]=tt(r[a]);o&&(n=c??this.initialValueFactory(),s=a+1)}let i=r.slice(s);this.value=i.length>0?this.reducer(n,i):n}update(t){if(t.length===0)return!1;let r,n=!1;for(let i of t)if(Ar(i)){if(n)throw new $("Can receive only one Overwrite value per step.");n=!0,[,r]=tt(i)}if(n)return this.value=r??this.initialValueFactory(),!0;let s=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(s,t),!0}get(){if(this.value===void 0)throw new W;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:!gy(t)||this.snapshotFrequency!==t.snapshotFrequency?!1:this.reducer===t.reducer}};var _c=Symbol.for("langgraph.channel.missing"),la=class Dm extends ie{lc_graph_name="UntrackedValue";guard;_value=_c;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new Dm({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new $("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===_c)throw new W;return this._value}checkpoint(){}isAvailable(){return this._value!==_c}};var dr=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),yc=class Lm extends ie{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new Lm(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 $(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!dr(this.names,this.seen))throw new W}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&dr(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&dr(this.names,this.seen)}},bc=class Fm extends ie{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 Fm(this.names);if(typeof t<"u"){let[n,s]=t;r.seen=new Set(n),r.finished=s}return r}update(t){let r=!1;for(let n of t)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),r=!0;else if(!this.names.has(n))throw new $(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!dr(this.names,this.seen))throw new W}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&dr(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&dr(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&dr(this.names,this.seen)}};var vc=Symbol.for("langgraph.state.reduced_value"),Ut=class{[vc]=!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&&vc in e&&e[vc]===!0}};var jm=Symbol.for("langgraph.state.untracked_value"),$r=class{[jm]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&jm in e}};var wc=Symbol.for("langgraph.state.delta_value"),Ht=class{[wc]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&wc in e&&e[wc]===!0}};var Sc=Symbol.for("langgraph.state.state_schema"),pt=class{[Sc]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(Ht.isInstance(r)){let n=Vt(r.valueSchema);e[t]=new ca(r.reducer,{snapshotFrequency:r.snapshotFrequency,initialValueFactory:n})}else if(Ut.isInstance(r)){let n=Vt(r.valueSchema);e[t]=new Ft(r.reducer,n)}else if($r.isInstance(r)){let n=r.schema?Vt(r.schema):void 0;e[t]=new la({guard:r.guard,initialValueFactory:n})}else if(Bt(r))e[t]=new ot(Vt(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let s;if(Ht.isInstance(n)||Ut.isInstance(n)?(s=mr(n.valueSchema),n.jsonSchemaExtra&&(s={...s??{},...n.jsonSchemaExtra})):$r.isInstance(n)?s=n.schema?mr(n.schema):void 0:Bt(n)&&(s=mr(n)),s){e[r]=s;let i=!1;Ht.isInstance(n)||Ut.isInstance(n)?i=Vt(n.valueSchema)!==void 0:$r.isInstance(n)?i=n.schema?Vt(n.schema)!==void 0:!1:i=Vt(n)!==void 0,i||t.push(r)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,r]of Object.entries(this.fields)){let n;Ht.isInstance(r)||Ut.isInstance(r)?(n=mr(r.inputSchema),r.jsonSchemaExtra&&(n={...n??{},...r.jsonSchemaExtra})):$r.isInstance(r)?n=r.schema?mr(r.schema):void 0:Bt(r)&&(n=mr(r)),n&&(e[t]=n)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e)){let s=this.fields[r];if(s===void 0){t[r]=n;continue}let i;if(Ht.isInstance(s)||Ut.isInstance(s)){let[a,o]=tt(n);if(a){i=s.valueSchema;let c=await i["~standard"].validate(o);if(c.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(c.issues)}`);t[r]={[mt]:c.value};continue}i=s.inputSchema}else $r.isInstance(s)?i=s.schema:Bt(s)&&(i=s);if(i){let a=await i["~standard"].validate(n);if(a.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(a.issues)}`);t[r]=a.value}else t[r]=n}return t}static isInstance(e){return typeof e=="object"&&e!==null&&Sc in e&&e[Sc]===!0}};var _y="__remove_all__";function gr(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],s=r.map(de),i=n.map(de);for(let u of s)(u.id===null||u.id===void 0)&&(u.id=kn(),u.lc_kwargs.id=u.id);let a;for(let u=0;u<i.length;u+=1){let h=i[u];(h.id===null||h.id===void 0)&&(h.id=kn(),h.lc_kwargs.id=h.id),Ze.isInstance(h)&&h.id==="__remove_all__"&&(a=u)}if(a!=null)return i.slice(a+1);let o=[...s],c=new Map(o.map((u,h)=>[u.id,h])),l=new Set;for(let u of i){let h=c.get(u.id);if(h!==void 0)Ze.isInstance(u)?l.add(u.id):(l.delete(u.id),o[h]=u);else{if(Ze.isInstance(u))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,o.length),o.push(u)}}return o.filter(u=>!l.has(u.id))}function kc(e,t){let r=[];for(let o of t)Array.isArray(o)?r.push(...o):r.push(o);let n=e.length>0&&re.isInstance(e[0])?e:e.map(de),s=r.map(de),i=new Map;for(let o=0;o<n.length;o+=1){let c=n[o].id;c!=null&&i.set(c,o)}let a=[...n];for(let o of s){let c=o.id;Ze.isInstance(o)&&c==="__remove_all__"?(a.length=0,i.clear()):c==null?a.push(o):Ze.isInstance(o)?i.has(c)&&(a[i.get(c)]=null,i.delete(c)):i.has(c)?a[i.get(c)]=o:(i.set(c,a.length),a.push(o))}return a.filter(o=>o!==null)}var $m=Qt.custom().default(()=>[]),Bm=Qt.custom(),yy=new Ut($m,{inputSchema:Bm,reducer:gr,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}}),by=new Ht($m,{inputSchema:Bm,reducer:kc,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var vy=class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let r=this.get(e);this._map.set(e,t(r))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},r=Er(e);for(let[n,s]of Object.entries(r)){let i=this.get(s);i?.reducer?t[n]=new Ft(i.reducer.fn,i.default):t[n]=new ot(i?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,i])=>i===!0).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}:${a}`).join("|"),n=this._extensionCache.get(r)??new Map;if(n.has(e))return n.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let i=Object.entries(Er(e)).map(([a,o])=>{let c=this.get(o),l=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let u=Cr(l)??Cr(o),h=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`lg:${h}`)}return[a,l]});s=Ns(e,Object.fromEntries(i)),Is(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=Yt(s)),n.set(e,s),this._extensionCache.set(r,n),s}},bs=new vy;function Vm(e,t){if(t.reducer&&!t.default){let r=Ms(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return bs.extend(r,()=>t),r}else return bs.extend(e,()=>t),e}function Br(e){return e==null?!1:!!(pt.isInstance(e)||be(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||Po(t)))}function Um(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&Br(t.state),n="stateSchema"in t&&Br(t.stateSchema),s="input"in t&&Br(t.input);return!(!r&&!n&&!s||"input"in t&&t.input!=null&&!Br(t.input)||"output"in t&&t.output!=null&&!Br(t.output))}var Gt="__root__",vn="__default_error_handler__",ua=Symbol.for("langgraph.state.partial"),Cc=class extends mc{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=bs;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new jn;let s=this._getChannelsFromSchema(n);this._schemaDefinition=s,pt.isInstance(n)?this._schemaRuntimeDefinition=n:be(n)&&(this._schemaRuntimeDefinition=n),r.input?pt.isInstance(r.input)?this._inputRuntimeDefinition=r.input:be(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=ua:this._inputRuntimeDefinition=ua,r.output?pt.isInstance(r.output)?this._outputRuntimeDefinition=r.output:be(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let i=r.input?this._getChannelsFromSchema(r.input):s,a=r.output?this._getChannelsFromSchema(r.output):s;this._inputDefinition=i,this._outputDefinition=a,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&be(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}setNodeDefaults(e){return e.retryPolicy!==void 0&&(this._nodeDefaults.retryPolicy=e.retryPolicy),e.cachePolicy!==void 0&&(this._nodeDefaults.cachePolicy=typeof e.cachePolicy=="boolean"?e.cachePolicy?{}:void 0:e.cachePolicy),e.timeout!==void 0&&(this._nodeDefaults.timeout=er(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new fe({func:(t,r)=>{let n=r?.configurable?.[Ln];return e(t,n,r)},name:vn,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(Um(e)){if(be(t)||Di.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(Br(e)){if(be(t)||Di.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(Sy(e))return{state:wy(e.channels)};throw new jn}_getChannelsFromSchema(e){if(pt.isInstance(e))return e.getChannels();if(be(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 jn("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,r]of Object.entries(e)){let n;if(typeof r=="function"?n=r():n=r,this.channels[t]!==void 0){if(!this.channels[t].equals(n)&&n.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=n}}}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([n,s])=>[n,s]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,s,i]of r){if(n in this.channels)throw new Error(`${n} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let p of["|",":"])if(n.includes(p))throw new Error(`"${p}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n==="__end__"||n==="__start__")throw new Error(`Node \`${n}\` is reserved.`);let a=this._schemaDefinition;i?.input!==void 0&&(a=this._getChannelsFromSchema(i.input)),this._addSchema(a);let o;H.isRunnable(s)?o=s:typeof s=="function"?o=new fe({func:s,name:n,trace:!1}):o=we(s);let c=i?.cachePolicy,l;c!==void 0&&(l=typeof c=="boolean"?c?{}:!1:c);let u;if(i?.errorHandler!==void 0){if(u=`__error_handler__${n}`,u in this.nodes)throw new Error(`Cannot add error handler to node \`${n}\`: the reserved name \`${u}\` is already in use. StateGraph registers \`__error_handler__<nodeName>\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`);let p=i.errorHandler,m={runnable:new fe({func:(d,y)=>{let v=y?.configurable?.[Ln];return p(d,v,y)},name:u,trace:!1}),metadata:void 0,input:a??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[u]=m}let h={runnable:o,retryPolicy:i?.retryPolicy,cachePolicy:l,timeout:er(i?.timeout),metadata:i?.metadata,input:a??this._schemaDefinition,subgraphs:ms(o)?[o]:i?.subgraphs,ends:i?.ends,defer:i?.defer,errorHandlerNode:u};this.nodes[n]=h}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(let r of e){if(r==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(n=>n===r))throw new Error(`Need to add a node named "${r}" first`)}if(t==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(let[n,s,i]of t){if(n in this.nodes)throw new Error(`Node names must be unique: node with the name "${n}" already exists.`);let a=n;this.addNode(n,s,i),r!=null&&this.addEdge(r,a),r=a}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:a,transformers:o}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(vn in this.nodes)throw new Error(`Cannot apply a default error handler: the reserved node name \`${vn}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[vn]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:a,transformers:o,defaultErrorHandlerNode:c!==void 0?vn:void 0})}finally{c!==void 0&&delete this.nodes[vn]}}_compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:a,transformers:o,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(s)?s:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===Gt?Gt:l,h=Object.keys(this.channels),p=h.length===1&&h[0]===Gt?Gt:h,m=this._interrupt,d=new Gm({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Z]:new ht},inputChannels:Z,outputChannels:u,streamChannels:p,streamMode:"updates",store:t,cache:r,name:i,description:a,userInterrupt:m,streamTransformers:o});d.attachNode(Z);let y=this._nodeDefaults,v=y.retryPolicy!==void 0||y.cachePolicy!==void 0||y.timeout!==void 0||c!==void 0;for(let[b,S]of Object.entries(this.nodes)){let k=S.isErrorHandler===!0,C=v?{...S,retryPolicy:S.retryPolicy??y.retryPolicy,cachePolicy:k||S.cachePolicy===!1?void 0:S.cachePolicy??y.cachePolicy,timeout:S.timeout??y.timeout,errorHandlerNode:!k&&c!==void 0&&S.errorHandlerNode===void 0?c:S.errorHandlerNode}:S;d.attachNode(b,C)}d.attachBranch(Z,ya,Hm(),{withReader:!1});for(let[b]of Object.entries(this.nodes))d.attachBranch(b,ya,Hm(),{withReader:!1});for(let[b,S]of this.edges)d.attachEdge(b,S);for(let[b,S]of this.waitingEdges)d.attachEdge(b,S);for(let[b,S]of Object.entries(this.branches))for(let[k,C]of Object.entries(S))d.attachBranch(b,k,C);return d.validate()}};function wy(e){let t={};for(let[r,n]of Object.entries(e))r===Gt?t[r]=Li(n):t[r]=Li(n);return t}var Gm=class extends dc{description;_metaRegistry=bs;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e==="__start__"?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([c])=>c):r=Object.keys(this.builder.channels);function n(c){if(pe(c))return c.graph===je.PARENT?null:c._updateAsTuples();if(Array.isArray(c)&&c.length>0&&c.some(l=>pe(l))){let l=[];for(let u of c)if(pe(u)){if(u.graph===je.PARENT)continue;l.push(...u._updateAsTuples())}else l.push([Gt,u]);return l}else if(c!=null)return[[Gt,c]];return null}let s=e,i=async c=>{if(c==null||c.length===0)return c;let l=this.builder._schemaRuntimeDefinition;if(pt.isInstance(l)){let u=new Set(l.getChannelKeys());return Promise.all(c.map(async([h,p])=>{if(!u.has(h))return[h,p];let m=await l.validateInput({[h]:p});return[h,Object.prototype.hasOwnProperty.call(m,h)?m[h]:p]}))}if(be(l)){let u=new Set(Object.keys(Er(l)));if(c.filter(([m])=>u.has(m)).length===0)return c;let h=Yt(this._metaRegistry.getExtendedChannelSchemas(l,{withReducerSchema:!0})),p=Yt(l);return c.map(([m,d])=>{if(!u.has(m))return[m,d];let[y,v]=tt(d);if(y){let S=Jt(p,{[m]:v});return[m,Object.prototype.hasOwnProperty.call(S,m)?{[mt]:S[m]}:d]}let b=Jt(h,{[m]:d});return[m,Object.prototype.hasOwnProperty.call(b,m)?b[m]:d]})}return c};async function a(c){if(c){if(pe(c))return c.graph===je.PARENT?null:i(c._updateAsTuples().filter(([l])=>r.includes(l)));if(Array.isArray(c)&&c.length>0&&c.some(pe)){let l=[];for(let u of c)if(pe(u)){if(u.graph===je.PARENT)continue;l.push(...u._updateAsTuples().filter(([h])=>r.includes(h)))}else{let h=await a(u);h&&l.push(...h??[])}return i(l)}else{if(typeof c=="object"&&!Array.isArray(c))return i(Object.entries(c).filter(([l])=>r.includes(l)));{let l=Array.isArray(c)?"array":typeof c;throw new $(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let o=[{value:Be,mapper:new fe({func:r.length&&r[0]===Gt?n:a,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new lt({tags:[se],triggers:[Z],channels:[Z],writers:[new te(o,[se])]});else{let c=t?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(c)).map(d=>[d,d])),u=Object.keys(l).length===1&&Gt in l,h=`branch:to:${e}`;this.channels[h]=t?.defer?new Do:new ht(!1);let p=t?.cachePolicy,m=p===!1?void 0:p;this.nodes[e]=new lt({triggers:[h],channels:u?Object.keys(l):l,writers:[new te(o,[se])],mapper:u?void 0:d=>Object.fromEntries(Object.entries(d).filter(([y])=>y in l)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:m,timeout:t?.timeout,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new te([{channel:`branch:to:${t}`,value:null}],[se]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new bc(new Set(e)):new yc(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new te([{channel:r,value:n}],[se]))}}}attachBranch(e,t,r,n={withReader:!0}){let s=async(i,a)=>{let o=i.filter(l=>l!==Q);if(!o.length)return;let c=o.map(l=>ce(l)?l:{channel:l==="__end__"?l:`branch:to:${l}`,value:e});await te.doWrite({...a,tags:(a.tags??[]).concat([se])},c)};this.nodes[e].writers.push(r.run(s,n.withReader?i=>zf.doRead(i,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(pt.isInstance(t)){if(pe(e)){let s=e;return e.update&&(s.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await t.validateInput(e)}if(t===ua&&pt.isInstance(r)){if(pe(e)){let s=e;return e.update&&(s.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await r.validateInput(e)}let n=(()=>{let s=i=>{if(i!=null)return this._metaRegistry.getExtendedChannelSchemas(i,{withReducerSchema:!0})};if(be(t))return s(t);if(t===ua)return be(r)?Yt(s(r)):void 0})();if(pe(e)){let s=e;if(e.update&&n!=null){let i=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,a=Jt(n,i);s.update=Object.fromEntries(Object.keys(i).map(o=>[o,a[o]]))}return s}return n!=null?Jt(n,e):e}isInterrupted(e){return Or(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return be(t)&&Jt(t,e),e}};function Sy(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function ky(e){if(ce(e))return[e];let t=[];pe(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(pe));let r=[];for(let n of t){if(n.graph===je.PARENT)throw new Ws(n);ce(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function Hm(){return new fc({path:new fe({func:ky,tags:[se],trace:!1,recurse:!1,name:"<control_branch>"})})}var Cy=class extends Cc{constructor(){super({channels:{__root__:{reducer:gr,default:()=>[]}}})}};function Ey(e,t){let{stateKey:r,...n}=t??{},s=pn(n),i=r??"messages";r===null&&(i=void 0);let a=de(e);if(!a.id)throw new Error("Message ID is required.");let o=(Array.isArray(s.callbacks)?s.callbacks:typeof s.callbacks<"u"?s.callbacks.handlers:[]).find(c=>"name"in c&&c.name==="StreamMessagesHandler");if(o){let c=s.metadata??{},l=(c.langgraph_checkpoint_ns??"").split("|");o._emit([l,c],a,void 0,!1)}return i&&s.configurable?.__pregel_send?.([[i,a]]),a}function Ty(e,t){let r=typeof e=="string"?{name:e,retry:void 0,cachePolicy:void 0,timeout:void 0}:e,{name:n,retry:s}=r,i=er(r.timeout);if(Qo(t)||ec(t))throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");let a=r.cachePolicy??("cache"in r?r.cache:void 0),o;return typeof a=="boolean"?o=a?{}:void 0:o=a,(...c)=>rm({func:t,name:n,retry:s,cache:o,timeout:i},...c)}var Wm=function(t,r){let{name:n,checkpointer:s,store:i,cache:a}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t,o=er(typeof t=="string"?void 0:t.timeout);if(Qo(r)||ec(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let c="updates",l=tm(n,r);function u(d){return typeof d=="object"&&d!==null&&"__lg_type"in d&&d.__lg_type==="__pregel_final"}let h=new fe({name:"pluckReturnValue",func:d=>u(d)?d.value:d}),p=new fe({name:"pluckSaveValue",func:d=>u(d)?d.save:d}),m=new lt({bound:l,triggers:[Z],channels:[Z],timeout:o,writers:[new te([{channel:Q,value:Be,mapper:h},{channel:ir,value:Be,mapper:p}],[se])]});return new oa({name:n,checkpointer:s,nodes:{[n]:m},channels:{[Z]:new ht,[Q]:new ot,[ir]:new ot},inputChannels:Z,outputChannels:Q,streamChannels:Q,streamMode:c,store:i,cache:a})};Wm.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};function xy(){return oe.getRunnableConfig().configurable?.[rr]}var Iy=us.Root({messages:us({reducer:gr,default:()=>[]})}),Km={reducer:{fn:gr},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},Ay=Xt.object({messages:Vm(Xt.custom(),Km)});function Oy(e){let t=oe.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");return r.writer?.(e)}export{Z as a,Q as b,Y as c,_a as d,Ou as e,Tr as f,ce as g,Xm as h,Or as i,je as j,pe as k,Ke as l,Bs as m,ba as n,Nr as o,Vs as p,Us as q,Nt as r,Hs as s,Gs as t,Qm as u,Ws as v,va as w,ar as x,Mt as y,Ks as z,ed as A,zs as B,W as C,$ as D,td as E,wa as F,rd as G,jn as H,nd as I,Uu as J,Xs as K,Zs as L,Ua as M,Ah as N,Oh as O,md as P,dd as Q,Ga as R,or as S,si as T,cr as U,xd as V,ao as W,nn as X,gg as Y,Cg as Z,Dr as _,it as $,Ii as aa,Sf as ba,ln as ca,Ni as da,Ef as ea,ie as fa,Ft as ga,us as ha,i_ as ia,a_ as ja,Fi as ka,o_ as la,Lo as ma,Fo as na,fn as oa,jo as pa,Je as qa,Bi as ra,Uo as sa,hs as ta,ps as ua,Ho as va,Go as wa,Vi as xa,zo as ya,Ff as za,qo as Aa,Zo as Ba,fe as Ca,mc as Da,Bt as Ea,dy as Fa,mr as Ga,Vt as Ha,ca as Ia,la as Ja,Ut as Ka,$r as La,Ht as Ma,pt as Na,_y as Oa,gr as Pa,kc as Qa,yy as Ra,by as Sa,bs as Ta,Vm as Ua,Cc as Va,Gm as Wa,Cy as Xa,Ey as Ya,Ty as Za,Wm as _a,xy as $a,Iy as ab,Km as bb,Ay as cb,Oy as db};
|
|
208
|
+
`),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!=="__end__"&&!(n in this.nodes))throw new Error(`Found edge ending at unknown node \`${n}\``);if(e){for(let n of e)if(!(n in this.nodes))throw new Error(`Interrupt node \`${n}\` is not present`)}this.compiled=!0}},dc=class extends oa{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new ht,this.nodes[e]=new lt({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new te([{channel:e,value:Be}],[se])),this.streamChannels.push(e)}attachEdge(e,t){if(t==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new te([{channel:Q,value:Be}],[se]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[Z]=Om.subscribeTo(Z,{tags:[se]})),this.nodes[e].pipe(r.run(s=>new te(s.map(i=>ce(i)?i:{channel:i==="__end__"?Q:`branch:${e}:${t}:${i}`,value:Be}),[se])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let s of n)if(s!=="__end__"){let i=`branch:${e}:${t}:${s}`;this.channels[i]=new ht,this.nodes[s].triggers.push(i),this.nodes[s].channels.push(i)}}async getGraphAsync(e){let t=e?.xray,r=new da,n={[Z]:r.addNode({schema:Qt.any()},Z)},s={},i={};t&&(i=Object.fromEntries((await ct(this.getSubgraphsAsync())).filter(l=>Mm(l[1]))));let a=[];function o(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[Q]=r.addNode({schema:Qt.any()},Q)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return a.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=ue(l),p=u.runnable,m=u.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?m.__interrupt="before,after":this.interruptBefore?.includes(l)?m.__interrupt="before":this.interruptAfter?.includes(l)&&(m.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,y=i[l]!==void 0?await i[l].getGraphAsync({...e,xray:d}):p.getGraph(e);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let S=function(C){return C?C.lc_runnable:!1},k=function(C,T){if(C!==void 0&&!pa(C))return C;if(S(T))try{let O=T.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return T.getName()}else return T.name??"UnknownSchema"},[v,b]=r.extend(y,h);if(v===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);b!==void 0&&(n[h]={name:k(b.id,b.data),...b}),s[h]={name:k(v.id,v.data),...v}}else{let v=r.addNode(p,h,m);n[h]=v,s[h]=v}}else{let d=r.addNode(p,h,m);n[h]=d,s[h]=d}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)o(ue(l),ue(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[ue(p),ue(p)])),[Q]:Q};for(let p of Object.values(u)){let m;p.ends!==void 0?m=p.ends:m=h;for(let[d,y]of Object.entries(m))o(ue(l),ue(y),d,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)o(ue(l),ue(h),void 0,!0);return Pm(this.builder.nodes,a,o),r}getGraph(e){let t=e?.xray,r=new da,n={[Z]:r.addNode({schema:Qt.any()},Z)},s={},i={};t&&(i=Object.fromEntries(ur(this.getSubgraphs()).filter(l=>Mm(l[1]))));let a=[];function o(l,u,h,p=!1){if(u==="__end__"&&s.__end__===void 0&&(s[Q]=r.addNode({schema:Qt.any()},Q)),n[l]!==void 0){if(s[u]===void 0)throw new Error(`End node ${u} not found!`);return a.push({src:l,dest:u,conditional:p}),r.addEdge(n[l],s[u],h!==u?h:void 0,p)}}for(let[l,u]of Object.entries(this.builder.nodes)){let h=ue(l),p=u.runnable,m=u.metadata??{};if(this.interruptBefore?.includes(l)&&this.interruptAfter?.includes(l)?m.__interrupt="before,after":this.interruptBefore?.includes(l)?m.__interrupt="before":this.interruptAfter?.includes(l)&&(m.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,y=i[l]!==void 0?i[l].getGraph({...e,xray:d}):p.getGraph(e);if(y.trimFirstNode(),y.trimLastNode(),Object.keys(y.nodes).length>1){let S=function(C){return C?C.lc_runnable:!1},k=function(C,T){if(C!==void 0&&!pa(C))return C;if(S(T))try{let O=T.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return T.getName()}else return T.name??"UnknownSchema"},[v,b]=r.extend(y,h);if(v===void 0)throw new Error(`Could not extend subgraph "${l}" due to missing entrypoint.`);b!==void 0&&(n[h]={name:k(b.id,b.data),...b}),s[h]={name:k(v.id,v.data),...v}}else{let v=r.addNode(p,h,m);n[h]=v,s[h]=v}}else{let d=r.addNode(p,h,m);n[h]=d,s[h]=d}}let c=[...this.builder.allEdges].sort(([l],[u])=>l<u?-1:u>l?1:0);for(let[l,u]of c)o(ue(l),ue(u));for(let[l,u]of Object.entries(this.builder.branches)){let h={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==l).map(p=>[ue(p),ue(p)])),[Q]:Q};for(let p of Object.values(u)){let m;p.ends!==void 0?m=p.ends:m=h;for(let[d,y]of Object.entries(m))o(ue(l),ue(y),d,!0)}}for(let[l,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let h of u.ends)o(ue(l),ue(h),void 0,!0);return Pm(this.builder.nodes,a,o),r}};function Mm(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function ue(e){return e==="subgraph"?`"${e}"`:e}function Pm(e,t,r){let n=new Set(t.map(i=>i.src)),s=[...new Set(t.filter(i=>!i.conditional&&i.dest!=="__end__").map(i=>i.dest))].sort();for(let i of s){if(n.has(i))continue;let a=Object.keys(e).find(o=>ue(o)===i);a!==void 0&&e[a]?.isErrorHandler||r(i,Q)}}function Bt(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function gc(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function dy(e){return Bt(e)&&gc(e)}function mr(e){if(gc(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function Vt(e){if(e!=null&&Bt(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 gy=e=>e!=null&&e.lc_graph_name==="DeltaChannel",ca=class Rm extends ie{lc_graph_name="DeltaChannel";value;reducer;snapshotFrequency;initialValueFactory;constructor(t,r){super();let n=r?.snapshotFrequency??1e3;if(!Number.isInteger(n)||n<=0)throw new Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=t,this.snapshotFrequency=n,this.initialValueFactory=r?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let r=new Rm(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?r.value=this.initialValueFactory():Ta(t)?r.value=t.value:r.value=t,r}replayWrites(t){let r=t.map(a=>a[2]);if(r.length===0)return;let n=this.value,s=0;for(let a=0;a<r.length;a+=1){let[o,c]=tt(r[a]);o&&(n=c??this.initialValueFactory(),s=a+1)}let i=r.slice(s);this.value=i.length>0?this.reducer(n,i):n}update(t){if(t.length===0)return!1;let r,n=!1;for(let i of t)if(Ar(i)){if(n)throw new $("Can receive only one Overwrite value per step.");n=!0,[,r]=tt(i)}if(n)return this.value=r??this.initialValueFactory(),!0;let s=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(s,t),!0}get(){if(this.value===void 0)throw new W;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:!gy(t)||this.snapshotFrequency!==t.snapshotFrequency?!1:this.reducer===t.reducer}};var _c=Symbol.for("langgraph.channel.missing"),la=class Dm extends ie{lc_graph_name="UntrackedValue";guard;_value=_c;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new Dm({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new $("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===_c)throw new W;return this._value}checkpoint(){}isAvailable(){return this._value!==_c}};var dr=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),yc=class Lm extends ie{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new Lm(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 $(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!dr(this.names,this.seen))throw new W}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&dr(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&dr(this.names,this.seen)}},bc=class Fm extends ie{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 Fm(this.names);if(typeof t<"u"){let[n,s]=t;r.seen=new Set(n),r.finished=s}return r}update(t){let r=!1;for(let n of t)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),r=!0;else if(!this.names.has(n))throw new $(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!dr(this.names,this.seen))throw new W}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&dr(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&dr(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&dr(this.names,this.seen)}};var vc=Symbol.for("langgraph.state.reduced_value"),Ut=class{[vc]=!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&&vc in e&&e[vc]===!0}};var jm=Symbol.for("langgraph.state.untracked_value"),$r=class{[jm]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&jm in e}};var wc=Symbol.for("langgraph.state.delta_value"),Ht=class{[wc]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&wc in e&&e[wc]===!0}};var Sc=Symbol.for("langgraph.state.state_schema"),pt=class{[Sc]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(Ht.isInstance(r)){let n=Vt(r.valueSchema);e[t]=new ca(r.reducer,{snapshotFrequency:r.snapshotFrequency,initialValueFactory:n})}else if(Ut.isInstance(r)){let n=Vt(r.valueSchema);e[t]=new Ft(r.reducer,n)}else if($r.isInstance(r)){let n=r.schema?Vt(r.schema):void 0;e[t]=new la({guard:r.guard,initialValueFactory:n})}else if(Bt(r))e[t]=new ot(Vt(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let s;if(Ht.isInstance(n)||Ut.isInstance(n)?(s=mr(n.valueSchema),n.jsonSchemaExtra&&(s={...s??{},...n.jsonSchemaExtra})):$r.isInstance(n)?s=n.schema?mr(n.schema):void 0:Bt(n)&&(s=mr(n)),s){e[r]=s;let i=!1;Ht.isInstance(n)||Ut.isInstance(n)?i=Vt(n.valueSchema)!==void 0:$r.isInstance(n)?i=n.schema?Vt(n.schema)!==void 0:!1:i=Vt(n)!==void 0,i||t.push(r)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,r]of Object.entries(this.fields)){let n;Ht.isInstance(r)||Ut.isInstance(r)?(n=mr(r.inputSchema),r.jsonSchemaExtra&&(n={...n??{},...r.jsonSchemaExtra})):$r.isInstance(r)?n=r.schema?mr(r.schema):void 0:Bt(r)&&(n=mr(r)),n&&(e[t]=n)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e)){let s=this.fields[r];if(s===void 0){t[r]=n;continue}let i;if(Ht.isInstance(s)||Ut.isInstance(s)){let[a,o]=tt(n);if(a){i=s.valueSchema;let c=await i["~standard"].validate(o);if(c.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(c.issues)}`);t[r]={[mt]:c.value};continue}i=s.inputSchema}else $r.isInstance(s)?i=s.schema:Bt(s)&&(i=s);if(i){let a=await i["~standard"].validate(n);if(a.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(a.issues)}`);t[r]=a.value}else t[r]=n}return t}static isInstance(e){return typeof e=="object"&&e!==null&&Sc in e&&e[Sc]===!0}};var _y="__remove_all__";function gr(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],s=r.map(de),i=n.map(de);for(let u of s)(u.id===null||u.id===void 0)&&(u.id=kn(),u.lc_kwargs.id=u.id);let a;for(let u=0;u<i.length;u+=1){let h=i[u];(h.id===null||h.id===void 0)&&(h.id=kn(),h.lc_kwargs.id=h.id),Ze.isInstance(h)&&h.id==="__remove_all__"&&(a=u)}if(a!=null)return i.slice(a+1);let o=[...s],c=new Map(o.map((u,h)=>[u.id,h])),l=new Set;for(let u of i){let h=c.get(u.id);if(h!==void 0)Ze.isInstance(u)?l.add(u.id):(l.delete(u.id),o[h]=u);else{if(Ze.isInstance(u))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${u.id}')`);c.set(u.id,o.length),o.push(u)}}return o.filter(u=>!l.has(u.id))}function kc(e,t){let r=[];for(let o of t)Array.isArray(o)?r.push(...o):r.push(o);let n=e.length>0&&re.isInstance(e[0])?e:e.map(de),s=r.map(de),i=new Map;for(let o=0;o<n.length;o+=1){let c=n[o].id;c!=null&&i.set(c,o)}let a=[...n];for(let o of s){let c=o.id;Ze.isInstance(o)&&c==="__remove_all__"?(a.length=0,i.clear()):c==null?a.push(o):Ze.isInstance(o)?i.has(c)&&(a[i.get(c)]=null,i.delete(c)):i.has(c)?a[i.get(c)]=o:(i.set(c,a.length),a.push(o))}return a.filter(o=>o!==null)}var $m=Qt.custom().default(()=>[]),Bm=Qt.custom(),yy=new Ut($m,{inputSchema:Bm,reducer:gr,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}}),by=new Ht($m,{inputSchema:Bm,reducer:kc,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var vy=class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let r=this.get(e);this._map.set(e,t(r))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},r=Er(e);for(let[n,s]of Object.entries(r)){let i=this.get(s);i?.reducer?t[n]=new Ft(i.reducer.fn,i.default):t[n]=new ot(i?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,i])=>i===!0).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}:${a}`).join("|"),n=this._extensionCache.get(r)??new Map;if(n.has(e))return n.get(e);let s=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let i=Object.entries(Er(e)).map(([a,o])=>{let c=this.get(o),l=t.withReducerSchema?c?.reducer?.schema??o:o;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let u=Cr(l)??Cr(o),h=JSON.stringify({...c.jsonSchemaExtra,description:u});l=l.describe(`lg:${h}`)}return[a,l]});s=Ns(e,Object.fromEntries(i)),Is(s)&&(s._def.unknownKeys="strip")}return t.asPartial&&(s=Yt(s)),n.set(e,s),this._extensionCache.set(r,n),s}},bs=new vy;function Vm(e,t){if(t.reducer&&!t.default){let r=Ms(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return bs.extend(r,()=>t),r}else return bs.extend(e,()=>t),e}function Br(e){return e==null?!1:!!(pt.isInstance(e)||be(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||Po(t)))}function Um(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&Br(t.state),n="stateSchema"in t&&Br(t.stateSchema),s="input"in t&&Br(t.input);return!(!r&&!n&&!s||"input"in t&&t.input!=null&&!Br(t.input)||"output"in t&&t.output!=null&&!Br(t.output))}var Gt="__root__",vn="__default_error_handler__",ua=Symbol.for("langgraph.state.partial"),Cc=class extends mc{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=bs;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new jn;let s=this._getChannelsFromSchema(n);this._schemaDefinition=s,pt.isInstance(n)?this._schemaRuntimeDefinition=n:be(n)&&(this._schemaRuntimeDefinition=n),r.input?pt.isInstance(r.input)?this._inputRuntimeDefinition=r.input:be(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=ua:this._inputRuntimeDefinition=ua,r.output?pt.isInstance(r.output)?this._outputRuntimeDefinition=r.output:be(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let i=r.input?this._getChannelsFromSchema(r.input):s,a=r.output?this._getChannelsFromSchema(r.output):s;this._inputDefinition=i,this._outputDefinition=a,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&be(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}setNodeDefaults(e){return e.retryPolicy!==void 0&&(this._nodeDefaults.retryPolicy=e.retryPolicy),e.cachePolicy!==void 0&&(this._nodeDefaults.cachePolicy=typeof e.cachePolicy=="boolean"?e.cachePolicy?{}:void 0:e.cachePolicy),e.timeout!==void 0&&(this._nodeDefaults.timeout=er(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new fe({func:(t,r)=>{let n=r?.configurable?.[Ln];return e(t,n,r)},name:vn,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(Um(e)){if(be(t)||Di.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(Br(e)){if(be(t)||Di.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(Sy(e))return{state:wy(e.channels)};throw new jn}_getChannelsFromSchema(e){if(pt.isInstance(e))return e.getChannels();if(be(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 jn("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,r]of Object.entries(e)){let n;if(typeof r=="function"?n=r():n=r,this.channels[t]!==void 0){if(!this.channels[t].equals(n)&&n.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=n}}}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([n,s])=>[n,s]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,s,i]of r){if(n in this.channels)throw new Error(`${n} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let p of["|",":"])if(n.includes(p))throw new Error(`"${p}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n==="__end__"||n==="__start__")throw new Error(`Node \`${n}\` is reserved.`);let a=this._schemaDefinition;i?.input!==void 0&&(a=this._getChannelsFromSchema(i.input)),this._addSchema(a);let o;H.isRunnable(s)?o=s:typeof s=="function"?o=new fe({func:s,name:n,trace:!1}):o=we(s);let c=i?.cachePolicy,l;c!==void 0&&(l=typeof c=="boolean"?c?{}:!1:c);let u;if(i?.errorHandler!==void 0){if(u=`__error_handler__${n}`,u in this.nodes)throw new Error(`Cannot add error handler to node \`${n}\`: the reserved name \`${u}\` is already in use. StateGraph registers \`__error_handler__<nodeName>\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`);let p=i.errorHandler,m={runnable:new fe({func:(d,y)=>{let v=y?.configurable?.[Ln];return p(d,v,y)},name:u,trace:!1}),metadata:void 0,input:a??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[u]=m}let h={runnable:o,retryPolicy:i?.retryPolicy,cachePolicy:l,timeout:er(i?.timeout),metadata:i?.metadata,input:a??this._schemaDefinition,subgraphs:ms(o)?[o]:i?.subgraphs,ends:i?.ends,defer:i?.defer,errorHandlerNode:u};this.nodes[n]=h}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(let r of e){if(r==="__end__")throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(n=>n===r))throw new Error(`Need to add a node named "${r}" first`)}if(t==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(let[n,s,i]of t){if(n in this.nodes)throw new Error(`Node names must be unique: node with the name "${n}" already exists.`);let a=n;this.addNode(n,s,i),r!=null&&this.addEdge(r,a),r=a}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:a,transformers:o}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(vn in this.nodes)throw new Error(`Cannot apply a default error handler: the reserved node name \`${vn}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[vn]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:a,transformers:o,defaultErrorHandlerNode:c!==void 0?vn:void 0})}finally{c!==void 0&&delete this.nodes[vn]}}_compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:s,name:i,description:a,transformers:o,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(s)?s:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===Gt?Gt:l,h=Object.keys(this.channels),p=h.length===1&&h[0]===Gt?Gt:h,m=this._interrupt,d=new Gm({builder:this,checkpointer:e,interruptAfter:s,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Z]:new ht},inputChannels:Z,outputChannels:u,streamChannels:p,streamMode:"updates",store:t,cache:r,name:i,description:a,userInterrupt:m,streamTransformers:o});d.attachNode(Z);let y=this._nodeDefaults,v=y.retryPolicy!==void 0||y.cachePolicy!==void 0||y.timeout!==void 0||c!==void 0;for(let[b,S]of Object.entries(this.nodes)){let k=S.isErrorHandler===!0,C=v?{...S,retryPolicy:S.retryPolicy??y.retryPolicy,cachePolicy:k||S.cachePolicy===!1?void 0:S.cachePolicy??y.cachePolicy,timeout:S.timeout??y.timeout,errorHandlerNode:!k&&c!==void 0&&S.errorHandlerNode===void 0?c:S.errorHandlerNode}:S;d.attachNode(b,C)}d.attachBranch(Z,ya,Hm(),{withReader:!1});for(let[b]of Object.entries(this.nodes))d.attachBranch(b,ya,Hm(),{withReader:!1});for(let[b,S]of this.edges)d.attachEdge(b,S);for(let[b,S]of this.waitingEdges)d.attachEdge(b,S);for(let[b,S]of Object.entries(this.branches))for(let[k,C]of Object.entries(S))d.attachBranch(b,k,C);return d.validate()}};function wy(e){let t={};for(let[r,n]of Object.entries(e))r===Gt?t[r]=Li(n):t[r]=Li(n);return t}var Gm=class extends dc{description;_metaRegistry=bs;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e==="__start__"?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([c])=>c):r=Object.keys(this.builder.channels);function n(c){if(pe(c))return c.graph===je.PARENT?null:c._updateAsTuples();if(Array.isArray(c)&&c.length>0&&c.some(l=>pe(l))){let l=[];for(let u of c)if(pe(u)){if(u.graph===je.PARENT)continue;l.push(...u._updateAsTuples())}else l.push([Gt,u]);return l}else if(c!=null)return[[Gt,c]];return null}let s=e,i=async c=>{if(c==null||c.length===0)return c;let l=this.builder._schemaRuntimeDefinition;if(pt.isInstance(l)){let u=new Set(l.getChannelKeys());return Promise.all(c.map(async([h,p])=>{if(!u.has(h))return[h,p];let m=await l.validateInput({[h]:p});return[h,Object.prototype.hasOwnProperty.call(m,h)?m[h]:p]}))}if(be(l)){let u=new Set(Object.keys(Er(l)));if(c.filter(([m])=>u.has(m)).length===0)return c;let h=Yt(this._metaRegistry.getExtendedChannelSchemas(l,{withReducerSchema:!0})),p=Yt(l);return c.map(([m,d])=>{if(!u.has(m))return[m,d];let[y,v]=tt(d);if(y){let S=Jt(p,{[m]:v});return[m,Object.prototype.hasOwnProperty.call(S,m)?{[mt]:S[m]}:d]}let b=Jt(h,{[m]:d});return[m,Object.prototype.hasOwnProperty.call(b,m)?b[m]:d]})}return c};async function a(c){if(c){if(pe(c))return c.graph===je.PARENT?null:i(c._updateAsTuples().filter(([l])=>r.includes(l)));if(Array.isArray(c)&&c.length>0&&c.some(pe)){let l=[];for(let u of c)if(pe(u)){if(u.graph===je.PARENT)continue;l.push(...u._updateAsTuples().filter(([h])=>r.includes(h)))}else{let h=await a(u);h&&l.push(...h??[])}return i(l)}else{if(typeof c=="object"&&!Array.isArray(c))return i(Object.entries(c).filter(([l])=>r.includes(l)));{let l=Array.isArray(c)?"array":typeof c;throw new $(`Expected node "${s.toString()}" to return an object or an array containing at least one Command object, received ${l}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let o=[{value:Be,mapper:new fe({func:r.length&&r[0]===Gt?n:a,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new lt({tags:[se],triggers:[Z],channels:[Z],writers:[new te(o,[se])]});else{let c=t?.input??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(c)).map(d=>[d,d])),u=Object.keys(l).length===1&&Gt in l,h=`branch:to:${e}`;this.channels[h]=t?.defer?new Do:new ht(!1);let p=t?.cachePolicy,m=p===!1?void 0:p;this.nodes[e]=new lt({triggers:[h],channels:u?Object.keys(l):l,writers:[new te(o,[se])],mapper:u?void 0:d=>Object.fromEntries(Object.entries(d).filter(([y])=>y in l)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:m,timeout:t?.timeout,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new te([{channel:`branch:to:${t}`,value:null}],[se]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new bc(new Set(e)):new yc(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new te([{channel:r,value:n}],[se]))}}}attachBranch(e,t,r,n={withReader:!0}){let s=async(i,a)=>{let o=i.filter(l=>l!==Q);if(!o.length)return;let c=o.map(l=>ce(l)?l:{channel:l==="__end__"?l:`branch:to:${l}`,value:e});await te.doWrite({...a,tags:(a.tags??[]).concat([se])},c)};this.nodes[e].writers.push(r.run(s,n.withReader?i=>zf.doRead(i,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(pt.isInstance(t)){if(pe(e)){let s=e;return e.update&&(s.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await t.validateInput(e)}if(t===ua&&pt.isInstance(r)){if(pe(e)){let s=e;return e.update&&(s.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),s}return await r.validateInput(e)}let n=(()=>{let s=i=>{if(i!=null)return this._metaRegistry.getExtendedChannelSchemas(i,{withReducerSchema:!0})};if(be(t))return s(t);if(t===ua)return be(r)?Yt(s(r)):void 0})();if(pe(e)){let s=e;if(e.update&&n!=null){let i=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,a=Jt(n,i);s.update=Object.fromEntries(Object.keys(i).map(o=>[o,a[o]]))}return s}return n!=null?Jt(n,e):e}isInterrupted(e){return Or(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return be(t)&&Jt(t,e),e}};function Sy(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function ky(e){if(ce(e))return[e];let t=[];pe(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(pe));let r=[];for(let n of t){if(n.graph===je.PARENT)throw new Ws(n);ce(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function Hm(){return new fc({path:new fe({func:ky,tags:[se],trace:!1,recurse:!1,name:"<control_branch>"})})}var Cy=class extends Cc{constructor(){super({channels:{__root__:{reducer:gr,default:()=>[]}}})}};function Ey(e,t){let{stateKey:r,...n}=t??{},s=pn(n),i=r??"messages";r===null&&(i=void 0);let a=de(e);if(!a.id)throw new Error("Message ID is required.");let o=(Array.isArray(s.callbacks)?s.callbacks:typeof s.callbacks<"u"?s.callbacks.handlers:[]).find(c=>"name"in c&&c.name==="StreamMessagesHandler");if(o){let c=s.metadata??{},l=(c.langgraph_checkpoint_ns??"").split("|");o._emit([l,c],a,void 0,!1)}return i&&s.configurable?.__pregel_send?.([[i,a]]),a}function Ty(e,t){let r=typeof e=="string"?{name:e,retry:void 0,cachePolicy:void 0,timeout:void 0}:e,{name:n,retry:s}=r,i=er(r.timeout);if(Qo(t)||ec(t))throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");let a=r.cachePolicy??("cache"in r?r.cache:void 0),o;return typeof a=="boolean"?o=a?{}:void 0:o=a,(...c)=>rm({func:t,name:n,retry:s,cache:o,timeout:i},...c)}var Wm=function(t,r){let{name:n,checkpointer:s,store:i,cache:a}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t,o=er(typeof t=="string"?void 0:t.timeout);if(Qo(r)||ec(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let c="updates",l=tm(n,r);function u(d){return typeof d=="object"&&d!==null&&"__lg_type"in d&&d.__lg_type==="__pregel_final"}let h=new fe({name:"pluckReturnValue",func:d=>u(d)?d.value:d}),p=new fe({name:"pluckSaveValue",func:d=>u(d)?d.save:d}),m=new lt({bound:l,triggers:[Z],channels:[Z],timeout:o,writers:[new te([{channel:Q,value:Be,mapper:h},{channel:ir,value:Be,mapper:p}],[se])]});return new oa({name:n,checkpointer:s,nodes:{[n]:m},channels:{[Z]:new ht,[Q]:new ot,[ir]:new ot},inputChannels:Z,outputChannels:Q,streamChannels:Q,streamMode:c,store:i,cache:a})};Wm.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};function xy(){return oe.getRunnableConfig().configurable?.[rr]}var Iy=us.Root({messages:us({reducer:gr,default:()=>[]})}),Km={reducer:{fn:gr},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},Ay=Xt.object({messages:Vm(Xt.custom(),Km)});function Oy(e){let t=oe.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");return r.writer?.(e)}export{Z as a,Q as b,Y as c,_a as d,Ou as e,Tr as f,ce as g,Xm as h,Or as i,je as j,pe as k,Ke as l,Bs as m,ba as n,Nr as o,Vs as p,Us as q,Nt as r,Hs as s,Gs as t,Qm as u,Ws as v,va as w,ar as x,Mt as y,Ks as z,ed as A,zs as B,W as C,$ as D,td as E,wa as F,rd as G,jn as H,nd as I,Uu as J,Xs as K,Zs as L,Ua as M,Ah as N,Oh as O,md as P,dd as Q,Ga as R,or as S,si as T,cr as U,xd as V,nt as W,ao as X,nn as Y,gg as Z,Cg as _,Dr as $,it as aa,Ii as ba,Sf as ca,ln as da,Ni as ea,Ef as fa,ie as ga,Ft as ha,us as ia,i_ as ja,a_ as ka,Fi as la,o_ as ma,Lo as na,Fo as oa,fn as pa,jo as qa,Je as ra,Bi as sa,Uo as ta,hs as ua,ps as va,Ho as wa,Go as xa,Vi as ya,zo as za,Ff as Aa,qo as Ba,Zo as Ca,fe as Da,mc as Ea,Bt as Fa,dy as Ga,mr as Ha,Vt as Ia,ca as Ja,la as Ka,Ut as La,$r as Ma,Ht as Na,pt as Oa,_y as Pa,gr as Qa,kc as Ra,yy as Sa,by as Ta,bs as Ua,Vm as Va,Cc as Wa,Gm as Xa,Cy as Ya,Ey as Za,Ty as _a,Wm as $a,xy as ab,Iy as bb,Km as cb,Ay as db,Oy as eb};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import a from"./5SF6DEMO.js";import{e as l}from"./UZL6UVE4.js";import"./HO2YDJI2.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([{property:g,subclass:u},{d:w}])=>{var f=Object.defineProperty,m=Object.getOwnPropertyDescriptor,c=(o,r,n,s)=>{for(var e=s>1?void 0:s?m(r,n):r,a=o.length-1,t;a>=0;a--)(t=o[a])&&(e=(s?t(r,n,e):t(e))||e);return s&&e&&f(r,n,e),e},p=class extends w{constructor(o){super(o)}getAgents(){return this.workflow.getAgents()}generate(){let o=this.workflow.generate(),r=o.workspace,n=o.createGraph().compile(),{decideContinue:s}=this,e={[i]:async(t,d)=>await n.invoke(t,d)},a=[{from:i,decide:async(t,d)=>await Promise.resolve(s(t,d))?i:void 0}];return{workspace:r,createGraph:()=>l(e,a,r,{entryNode:i})}}buildEdges(){throw new Error("LoopWorkflow overrides generate(); buildEdges should not be called.")}getEntryNode(){return i}isTerminalAgent(){return!0}};c([g()],p.prototype,"workflow",2);c([g()],p.prototype,"decideContinue",2);p=c([u("LoopWorkflow")],p);var i="__loop_body";return p},"core/accessorSupport/decorators",a)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{ia as r}from"./E7KEOJZG.js";var u=(t,e)=>e,o=(t,e)=>({...t,...e}),i=(t="",e)=>{let s=typeof e=="string"?e.trim():"";if(!s)return t;let a=t.trim();if(!a)return s;if(a===s)return t;let n=a.split(`
|
|
3
|
+
|
|
4
|
+
`);return n[n.length-1]?.trim()===s?t:`${t}
|
|
5
|
+
|
|
6
|
+
${s}`},c=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),d=()=>({agentExecutionContext:r({reducer:o,default:c}),outputMessage:r({reducer:i,default:()=>""}),summary:r({reducer:u,default:()=>""}),status:r({reducer:u})}),f=()=>({...d(),sharedStatePatch:r({reducer:u})});export{u as a,o as b,i as c,c as d,d as e,f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import a from"./
|
|
2
|
+
import a from"./ZJEWP2ND.js";import{b as E}from"./R74ZHFA6.js";import{a as g}from"./HJG7QM2R.js";import{Wa as A,a as v,b as I,ca as S,y as R}from"./E7KEOJZG.js";import{ca as b,oa as C}from"./LUY6V4TP.js";export default $arcgis.t(([N,U,H,T,_,{a:k,b:D,c:f,e:$,f:M,m:W}])=>{var G=async e=>{let t=await z(),n=await k("default"),s=U.getDefault(),r=(await N.getCredential(`${s.url}/sharing`)).token,a={type:"generateEmbeddings",webmapEmbeddings:e,auth:{apiUrl:n,token:r}};return t.postMessage(a),await new Promise((i,c)=>{let o=u=>{u.data==="completed"&&(t.removeEventListener("message",o),i())},d=u=>{t.removeEventListener("message",o),c(u instanceof Error?u:new Error("Embeddings worker error"))};t.addEventListener("message",o),t.addEventListener("error",d,{once:!0})}),t},z=async()=>{{let e=(await import("./OKVLGJAG.js")).default;return new e}},Q=e=>{e.currentIntent="none"},B=async(e,t)=>{let n=f(t);if(e.agentExecutionContext.userRequest){let r=new C(e.agentExecutionContext.userRequest.trim());e.agentExecutionContext.messages=[...e.agentExecutionContext.messages,r],Q(e)}let s=n?.services.agentRegistry.list().map(r=>r.agent.id)??[];return await g({text:`Available agents: ${[...s].join(", ")}`},t),await g({text:"Analyzing user input"},t),e},J=async(e,t)=>(await g({text:"Exiting..."},t),e),q=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),K=(e,t)=>{if(!q(e)){e!==void 0&&console.warn(`Agent "${t}" returned invalid sharedStatePatch. Ignoring it.`);return}let n={};for(let[s,r]of Object.entries(e)){if(!q(r)||!("value"in r)){console.warn(`Agent "${t}" returned invalid sharedStatePatch entry for key "${s}". Ignoring that entry.`);continue}n[s]={value:r.value}}return n},V=e=>{let{previousSharedState:t,patch:n,agentId:s}=e;if(!n)return t;let r=Date.now(),a={...t};for(let[i,c]of Object.entries(n))c?.value!==void 0&&(a[i]={value:c.value,meta:{updatedByAgentId:s,updatedAt:r}});return a},F=e=>typeof e!="string"?void 0:e.trim()||void 0,X=e=>{switch(e){case"failed":return"Agent failed without a summary.";case"unknown":return"Agent returned with unknown status.";case"success":return"Agent completed without a summary.";default:return"Agent completed without a summary."}},Y=(e,t)=>{let n=F(t?.outputMessage),s=F(t?.summary),r=t?.status,a=r==="success"||r==="failed"?r:"unknown";a==="unknown"&&console.warn(`Agent "${e}" returned missing/invalid status. Defaulting to "unknown".`);let i=K(t?.sharedStatePatch,e);return{outputMessage:n,summary:s??n??X(a),status:a,sharedStatePatch:i}},L=4e3,Z=async(e,t)=>{let n=f(t);if(t?.signal?.aborted)return await g({text:"Run cancelled; skipping agent execution"},t),{...e,currentIntent:"none",requiresFollowUp:!1};let{agentRegistry:s}=n?.services??{},r=s?.get(e.currentIntent);if(!r)return console.warn(`No agent found for intent: ${e.currentIntent}`),e;await g({text:`Executing registered agent: ${r.agent.name}`},t);let a={...t??{},configurable:{...n??{},agentId:r.agent.id,context:r.getContext?await r.getContext():void 0}},i;try{let d=await r.agent.createGraph().compile().invoke({agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages],priorSteps:structuredClone(e.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(e.agentExecutionContext.sharedState??{})}},a);i=Y(r.agent.name,d),await g({text:`Finished executing registered agent: ${r.agent.name}`},t)}catch(d){if(R(d)||t?.signal?.aborted||d instanceof Error&&d.name==="AbortError")throw d;let u=d instanceof Error?d.message:String(d);console.error(`Agent "${r.agent.name}" failed:`,d),await g({text:`Registered agent failed: ${r.agent.name}. ${u}`},t),i={status:"failed",outputMessage:`Agent execution failed: ${u}`,summary:`Agent execution failed: ${u}`}}let c=i.outputMessage,o=[...e.agentExecutionContext.messages];if(c){let d=c.length>L?`${c.slice(0,L-14)}
|
|
3
3
|
[truncated]`:c;o.push(new b(d))}return{...e,stepCount:e.stepCount+1,lastExecutedAgent:r.agent.id,requiresFollowUp:i.status==="failed"?!0:e.requiresFollowUp,finalOutputMessage:c??"",agentExecutionContext:{...e.agentExecutionContext,messages:o,priorSteps:[...e.agentExecutionContext.priorSteps??[],{agentId:r.agent.id,assignedTask:e.agentExecutionContext.assignedTask,summary:i?.summary||"No summary provided.",status:i?.status||"unknown"}],sharedState:V({previousSharedState:e.agentExecutionContext.sharedState,patch:i.sharedStatePatch,agentId:r.agent.id})}}},ee=async(e,t)=>{if(e.routing.mode!=="direct")throw new Error("Direct agent assignment requires direct routing.");return await g({text:`Doing a direct route to agent: ${e.routing.agentId}`},t),{...e,currentIntent:e.routing.agentId,requiresFollowUp:!1,agentExecutionContext:{...e.agentExecutionContext,assignedTask:e.agentExecutionContext.userRequest}}},te=3,re=e=>e.routing.mode==="direct"?"assignDirectAgent":"intentLLM",ne=e=>e.routing.mode==="direct"||e.stepCount>=te||!e.requiresFollowUp?"exit":"intentLLM",se=()=>new A(D).addNode("ingestInput",B).addNode("assignDirectAgent",ee).addNode("intentLLM",M).addNode("executeRegisteredAgent",Z).addNode("exit",J).addEdge(v,"ingestInput").addConditionalEdges("ingestInput",re).addEdge("assignDirectAgent","executeRegisteredAgent").addConditionalEdges("intentLLM",e=>e.currentIntent==="none"||e.currentIntent===e.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",ne).addEdge("exit",I),w=class{constructor(){this.agentRegistry=new Map}register(t){let{agent:n}=t;if(this.agentRegistry.has(n.id))throw new Error(`Duplicate agent id: ${n.id}`);this.agentRegistry.set(n.id,t)}get(t){return this.agentRegistry.get(t)}list(){return[...this.agentRegistry.values()]}},x=class{constructor(t,n){this.graph=t,this.config={...n}}async waitForUser(){return await new Promise((t,n)=>{this.resolveWait=t,this.rejectWait=n})}handle(t,n){try{let s={agentId:t.agentId,id:t.id,payload:n},r=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:s},subgraphs:!0,version:"v2"});this.resolveWait?.(r)}catch(s){this.rejectWait?.(s)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("Request cancelled by user.")),this.resolveWait=void 0,this.rejectWait=void 0)}},ae=async e=>{try{return await(await $()).embedDocuments(e)}catch(t){throw console.error("Failed to generate embeddings:",t),t}},O=async(e,t)=>{let n=t.get(e);if(n)return n;let s=await ae([e]);return t.set(e,s[0]),s[0]};async function ie(e,t,n,s){let r=`req-${Date.now()}`,a={type:"layerSearch",precomputedEmbedding:s?await O(e,s):void 0,requestId:r,minScore:n};return await new Promise(i=>{let c=o=>{o.data.requestId===r&&i(o.data.results)};t.addEventListener("message",c,{once:!0}),t.postMessage(a)})}function oe(e){let{worker:t}=e;return{async searchLayers({text:n,minScore:s,embeddingCache:r}){return await ie(n,t,s,r)}}}var de=async({combinedQuery:e,layerIds:t,embeddingsWorker:n,minScore:s,topResults:r,embeddingCache:a})=>{let i=`req-${Date.now()}`,c=a?await O(e,a):void 0,o={type:"fieldSearch",layerIdForFieldsSearch:t,precomputedEmbedding:c,requestId:i,minScore:s,topResults:r};return await new Promise(d=>{let u=p=>{if(p.data.requestId!==i)return;let y=p.data.results.map(({layerId:l,results:m})=>({layerId:l,results:m}));d(y)};n.addEventListener("message",u,{once:!0}),n.postMessage(o)})};function ce(e){let{worker:t}=e;return{async searchFields({text:n,layerIds:s,minScore:r,topResults:a,embeddingCache:i}){return await de({combinedQuery:n,layerIds:s,embeddingsWorker:t,minScore:r,topResults:a,embeddingCache:i})}}}var ue=e=>{let t=W.safeParse(e);if(!t.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return t.data},ge=(e,t)=>{let n=new Map,s=new Map;if(t.allLayers.forEach(r=>{r instanceof T&&s.set(r.id,r)}),e.length!==s.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let r of e){let a=s.get(r.id);if(!a)throw new Error(`Layer with ID ${r.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(r.fields.length!==a.fields.length)throw new Error(`Field count mismatch for layer ID ${r.id} during registry restoration. Regenerate embeddings.`);let i={name:r.name,title:r.title,description:r.description},c=new Map;for(let o of r.fields){let d=a.fieldsIndex.get(o.name);if(!d)throw new Error(`Field with name ${o.name} not found in the original layer ${r.id} during registry restoration. Regenerate embeddings.`);c.set(o.name,{name:o.name,alias:a.getFieldAlias(o.name)??o.alias,description:o.description,type:d.type||"unknown",valueType:d.valueType||"unknown",domain:a.getFieldDomain(o.name)??void 0})}n.set(r.id,{layerItem:i,fieldRegistry:c})}return n},le=async e=>{try{return(await _(e,{responseType:"json"})).data}catch(t){throw new Error(`Failed to fetch data from ${e}: ${String(t)}`)}},he=async e=>{let t=e.map;if(!t?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:n}=await t.portalItem.fetchResources(),s=n.find(a=>a.resource.path==="embeddings-v01.json");if(!s?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let r=await le(s.resource.url);return ue(r)},j=class e{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.agentRegistry=new w,this.activeRunId="",this.cancelledRunIds=new Set,this.streamEpoch=0}static async init(t){let n=new e;try{if(t.view?.map){await H.whenOnce(()=>t.view.ready);let s=await he(t.view),r=ge(s.layers,t.view.map);n.layersAndFieldsRegistry=r,n.embeddingsWorker=await G(s)}return t.agents?.forEach(s=>{n.agentRegistry.register(s)}),n.orchestratorReady=!0,n}catch(s){throw console.error("Orchestrator initialization failed:",s),s}}async*ask(t,n={}){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");let s=this.createRequestAgentRegistry(n);if(!s.list().length)throw new Error("Orchestrator has no agents selected for this request.");if(++this.streamEpoch,!t.trim())return;let r=E();this.activeRunId=r,this.activeAbortController=new AbortController,this.graph||(this.graph=se().compile({checkpointer:new S}));let a=this.embeddingsWorker?oe({worker:this.embeddingsWorker}):void 0,i=this.embeddingsWorker?ce({worker:this.embeddingsWorker}):void 0,c=new Map,o=n.routing==="direct"?{mode:"direct",agentId:n.agentId}:{mode:"auto"},d={thread_id:r,hitlResponse:null,services:{layerSearch:a,fieldSearch:i,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:s,embeddingCache:c}},u={version:"v2",streamMode:"custom",signal:this.activeAbortController.signal,configurable:d,subgraphs:!0},p=this.graph?.streamEvents({routing:o,agentExecutionContext:{userRequest:t,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},u),y=++this.streamEpoch;if(yield*this.pipeStream(p,y,r),this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}for(;;){if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let m=(await this.graph.getState(u,{subgraphs:!0})).tasks.find(h=>h.interrupts.length>0)?.interrupts[0]?.value;if(!m)break;this.currentInterrupt=m,this.interruptHandler=new x(this.graph,u),yield{runId:r,timestamp:Date.now(),type:"interrupt",interrupt:m};try{let h=await this.interruptHandler.waitForUser(),P=++this.streamEpoch;yield*this.pipeStream(h,P,r)}catch(h){if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}if(h){yield{runId:r,timestamp:Date.now(),type:"error",error:{message:h?.message}};return}}}if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let l=(await this.graph.getState(u,{subgraphs:!0})).values;if(this.isRunCancelled(r)){yield{runId:r,timestamp:Date.now(),type:"cancelled",reason:"user"};return}this.chatHistory=l.agentExecutionContext.messages.length?l.agentExecutionContext.messages:this.chatHistory,this.priorSteps=l.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=l.agentExecutionContext.sharedState??{},yield{runId:r,timestamp:Date.now(),type:"completed",result:{content:l.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}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()}cancel(){this.activeRunId&&(this.cancelledRunIds.add(this.activeRunId),this.activeAbortController?.abort(),++this.streamEpoch,this.interruptHandler?.cancel())}async*pipeStream(t,n,s){for await(let r of t){if(this.isRunCancelled(s)||n!==this.streamEpoch)break;r.event==="on_custom_event"&&r.name==="trace_message"?yield{runId:s,timestamp:Date.now(),type:"trace",data:r.data}:r.name==="graph_ux_suggestion"&&(yield{runId:s,timestamp:Date.now(),type:"ux-suggestion",suggestion:r.data})}}isRunCancelled(t){return this.cancelledRunIds.has(t)}createRequestAgentRegistry(t){let n=t.routing==="direct"?[t.agentId]:t.agentIds,s=n?n.map(a=>{let i=this.agentRegistry.get(a);if(!i)throw new Error(`Agent is not registered: ${a}`);return i}):this.agentRegistry.list(),r=new w;return s.forEach(a=>r.register(a)),r}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};return{a:ae,b:j}},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request",a)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import c from"./5SFZS2RD.js";import b from"./RWM5T4XB.js";import{c as s,d as n}from"./V6HOUZPZ.js";import"./3UEKINYC.js";import"./RLEHNAIA.js";import a from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import{v as r,z as o}from"./6TA5KFAQ.js";import"./R74ZHFA6.js";import"./HJG7QM2R.js";import"./WZFC5HUX.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,,,,,,,,,{fetchKnowledgeGraph:p},,,a])=>{var i=class extends r{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1,serviceUrl:3,context:0}}#e;#i;#t;#r;get serviceUrl(){return this.#i}set serviceUrl(t){this.#i=t}async getContext(){let t=this.context?{...this.context,knowledgeGraph:void 0,view:void 0}:{};if(this.#e)return{...t,view:this.#e};if(this.#t)try{let e=await this.#t;return{...t,knowledgeGraph:e}}catch(e){console.error("Failed to load knowledge graph via service URL:",e)}if(!this.context?.knowledgeGraph&&!this.context?.view)throw new Error("arcgis-assistant-knowledge-agent requires either a knowledgeGraph or view in context, and neither were provided");return this.context}willUpdate(t){t.has("serviceUrl")&&this.serviceUrl?this.#t=p(this.serviceUrl):this.#t=void 0}load(){this.#e=n(this)??void 0,this.#r=s(this)}disconnectedCallback(){this.#r?.unregister(this.agent.id),super.disconnectedCallback()}};o("arcgis-assistant-knowledge-agent",i);return i},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",a,b,c)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import a from"./5SF6DEMO.js";import{c as C,e as N}from"./UZL6UVE4.js";import"./HO2YDJI2.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([{property:B,subclass:D},{a:h,b:S,c:p,d:A}])=>{var G=Object.defineProperty,z=Object.getOwnPropertyDescriptor,P=(t,e,s,n)=>{for(var r=n>1?void 0:n?z(e,s):e,o=t.length-1,a;o>=0;o--)(a=t[o])&&(r=(n?a(e,s,r):a(r))||r);return n&&r&&G(e,s,r),r},x=class extends A{constructor(t){super(t)}getAgents(){return this.agents}generate(){let t=this.getAgents();this.validateAgents(t);for(let o of t)o.generate();let e=S(t.flatMap(o=>o.getSchemas()));for(let[o]of t.entries())e[_(o)]=void 0;let s=C(e),n=this.buildNodes(t),r=this.buildEdges(t);return{workspace:s,createGraph:()=>N(n,r,s,{entryNode:this.getEntryNode(t)})}}getEntryNode(t){return y}isTerminalAgent(t,e){return!1}buildNodes(t){let e={};for(let[s,n]of t.entries()){let r=_(s),o=p(n,s);e[o]=async(a,u)=>{let l=await n.run(F(a,n),u),i={},m=i;return m[r]=l,i}}return e[y]=()=>({}),e[k]=s=>R(s,t),e}buildEdges(t){return[...t.map((e,s)=>({from:y,to:p(e,s)})),...t.map((e,s)=>({from:p(e,s),to:k}))]}};P([B()],x.prototype,"agents",2);x=P([D("ParallelWorkflow")],x);var y="__parallel_fanOut",k="__parallel_join";function _(t){return`__parallel_update_${t}`}function W(t,e){return Object.fromEntries(e.filter(s=>Object.hasOwn(t,s)).map(s=>[s,t[s]]))}function F(t,e){let s=e.inputSchema;return s?{...W(t,h(s)),agentExecutionContext:t.agentExecutionContext,outputMessage:t.outputMessage,status:void 0,summary:""}:{...t,status:void 0,summary:""}}function I(t,e){return t.outputSchema?W(e,h(t.outputSchema)):{}}function K(t,e){let s=t.agentExecutionContext?.messages??[],n=e.agentExecutionContext?.messages??[];return n.length>s.length?n.slice(s.length):void 0}function R(t,e){let s=[],n=[],r=[],o={},a={},u=new Set;for(let[m,J]of e.entries()){let E=_(m),d=t[E];if(a[E]=void 0,!d||typeof d!="object")continue;let c=d,b=c.outputMessage,O=K(t,c),v=c.summary,$=I(J,c),w=b.trim();typeof b=="string"&&w&&s.push(w);let j=v.trim();typeof v=="string"&&j&&n.push(j),Array.isArray(O)&&r.push(...O),c.status&&u.add(c.status);for(let[f,g]of Object.entries($))if(!(g===void 0||f.startsWith("__parallel_update_"))&&!M(t[f],g)){if(!Object.hasOwn(o,f)){o[f]=g;continue}if(!M(o[f],g))throw new Error(`ParallelWorkflow detected conflicting updates for state key "${f}".`)}}let l={...a,...o},i=l;return r.length>0&&(i.agentExecutionContext={...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages,...r]}),s.length&&(i.outputMessage=s.join(`
|
|
3
|
+
|
|
4
|
+
`)),n.length&&(i.summary=n.join(`
|
|
5
|
+
|
|
6
|
+
`)),u.size&&(i.status=u.has("failed")?"failed":u.has("success")?"success":void 0),l}function M(t,e){return t===e?!0:t&&e?JSON.stringify(t)===JSON.stringify(e):!1}return x},"core/accessorSupport/decorators",a)
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import{a as E}from"./B6CJG5UH.js";import b from"./
|
|
2
|
+
import{a as E}from"./B6CJG5UH.js";import b from"./I4L45WQS.js";import{a as I}from"./434TAA3J.js";import{a as D}from"./2GH3K5JP.js";import"./OKMZQXBQ.js";import{a as R}from"./3UEKINYC.js";import"./RLEHNAIA.js";import a from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import{g as $,h as c,k as C,l as P,n as d,t as _,u as y,v as T,x as k,z as A}from"./6TA5KFAQ.js";import"./R74ZHFA6.js";import"./HJG7QM2R.js";import"./WZFC5HUX.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([N,{whenOnce:U,watch:B,when:V},j,,q,,,H,{property:m,subclass:F},,{b:L}])=>{var G=$`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%);--calcite-panel-content-bottom-space: 0}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%;background:var(--calcite-panel-background-color, var(--calcite-color-background))}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}.interrupt-waiting-message{font-style:italic;color:var(--calcite-color-text-2)}`;function S(o){return o.trim()?E.lexer(o).filter(t=>t.type!=="space").map(t=>E.parser([t])):[]}var f=class{constructor(){this._stableParts=[],this._stableText="",this._rawText=""}push(t){return this._rawText+=t,this._advanceStableBoundary(),this.getParts()}finalize(){let t=this._rawText.slice(this._stableText.length);return t.trim()&&(this._stableParts.push(...S(t)),this._stableText=this._rawText),this._stableParts}getParts(){let t=this._trimIncompleteTail(this._rawText.slice(this._stableText.length)),s=t.trim()?S(t):[];return[...this._stableParts,...s]}reset(){this._stableParts=[],this._stableText="",this._rawText=""}_advanceStableBoundary(){let t=this._rawText.slice(this._stableText.length),s=this._lastSafeBoundary(t);if(s<=0)return;let i=t.slice(0,s);this._stableParts.push(...S(i)),this._stableText+=i}_lastSafeBoundary(t){let s=t.split(`
|
|
3
3
|
`),i=!1,e=0,n=0;for(let r of s)/^\s*(```|~~~)/u.test(r)&&(i=!i),n+=r.length+1,r.trim()===""&&!i&&(e=n);return e<t.length?e:0}_trimIncompleteTail(t){let s=t.lastIndexOf("<");if(s!==-1&&!t.includes(">",s))return t.slice(0,s);let i=this._earliestUnclosedTag(t);if(i!==-1)return t.slice(0,i);let e=t.lastIndexOf("[");if(e!==-1){let n=t.slice(e);if(!/\[[^\]]*\]\([^)]*\)/u.test(n))return t.slice(0,e)}return t}_earliestUnclosedTag(t){let s=new Set(["br","img","hr","input","meta","link","area","base","col","embed","source","track","wbr"]),i=/<(\/?)([a-zA-Z][\w-]*)\b[^>]*?(\/?)>/gu,e=[];for(let n=i.exec(t);n;n=i.exec(t)){let[,r,a,l]=n,h=a.toLowerCase();if(!(s.has(h)||l==="/"))if(r==="/"){for(let g=e.length-1;g>=0;g--)if(e[g].name===h){e.splice(g);break}}else e.push({name:h,index:n.index})}return e.length?e[0].index:-1}};function W(o){let t=new f;return t.push(o),t.finalize()}var Y=async o=>await new Promise(t=>setTimeout(t,o));async function*Z(o,{chunkSize:t=15,delay:s=50}={}){let i=new f;for(let e=0;e<o.length;e+=t)yield i.push(o.slice(e,e+t)),await Y(s);yield i.finalize()}var J=Object.defineProperty,K=Object.getOwnPropertyDescriptor,u=(o,t,s,i)=>{for(var e=i>1?void 0:i?K(t,s):t,n=o.length-1,r;n>=0;n--)(r=o[n])&&(e=(i?r(t,s,e):r(e))||e);return i&&e&&J(t,s,e),e},O=o=>!o||typeof o!="object"?!1:o.name==="AbortError";async function*z(o,t,s,i,e=!1){if(e){if(i?.aborted){yield{type:"cancelled",log:s,runId:t};return}yield{type:"block-data",blockType:"text",data:{parts:W(o)},runId:t};return}for await(let n of Z(o)){if(i?.aborted){yield{type:"cancelled",log:s,runId:t};return}yield{type:"block-data",blockType:"text",data:{parts:n},runId:t}}}var p=class extends H{constructor(o){super(o),this.view=null,this.streamingDisabled=!1,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 U(()=>!this.view.updating),this._set("orchestrator",await L.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([B(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(o,t){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let s=[],i,e="pending";try{let n=this.orchestrator.ask(o);for await(let r of n)switch(e=r.runId,r.type){case"trace":{this._set("processingStep",r.data.text),s.push(r.data.text);break}case"completed":{this._set("processing",!1),this._set("processingStep","");let a=r.result,l=!!a.content.length,h=!!i?.length;if(!l&&!h){yield{type:"completed",error:"No response received.",log:s,runId:e};return}let g=a.content;if(yield{type:"block-start",blockType:"text",runId:e},yield*z(g,e,s,t,this.streamingDisabled),yield{type:"block-end",blockType:"text",runId:e},h)for(let v of i){if(t?.aborted){yield{type:"cancelled",log:s,runId:e};return}let{type:b,data:w}=v;if(yield{type:"block-start",blockType:b,runId:e},b==="text"){let M=typeof w?.content=="string"?w.content:"";yield*z(M,e,s,t,this.streamingDisabled)}else yield{type:"block-data",blockType:b,data:w,runId:e};yield{type:"block-end",blockType:b,runId:e}}yield{type:"completed",response:g,blocks:i,log:s,runId:e};return}case"ux-suggestion":{let a=r.suggestion;i=i?[...i,a]:[a];break}case"interrupt":{let{kind:a,message:l,metadata:h}=r.interrupt,g=Array.isArray(h)?h.filter(b=>typeof b=="string"):[],v=(()=>{switch(a){case"booleanChoice":return{type:"boolean-choice",message:l,options:g};case"singleSelection":return{type:"single-select",message:l,options:g};case"multipleSelection":return{type:"multi-select",message:l,options:g};case"textInput":return{type:"text-input",message:l};default:return{type:a,message:l,options:g}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:v,runId:e};break}case"cancelled":{yield{type:"cancelled",log:s,runId:e};return}case"error":{if(t?.aborted||O(r.error)){yield{type:"cancelled",log:s,runId:e};return}yield{type:"completed",error:r.error.message,log:s,runId:e};return}default:{console.warn("Unknown event type:",r);break}}}catch(n){if(t?.aborted||O(n)){yield{type:"cancelled",log:s,runId:e};return}console.warn("Error during message processing:",n),yield{type:"completed",error:"An error occurred during message processing.",log:s,runId:"error"};return}finally{this._set("processing",!1)}}cancel(){this.orchestrator?.cancel()}};u([m({readOnly:!0})],p.prototype,"orchestrator",2);u([m()],p.prototype,"agents",2);u([m()],p.prototype,"portal",2);u([m()],p.prototype,"view",2);u([m()],p.prototype,"streamingDisabled",2);u([m({readOnly:!0})],p.prototype,"loading",2);u([m({readOnly:!0})],p.prototype,"processing",2);u([m({readOnly:!0})],p.prototype,"processingStep",2);p=u([F("OrchestratorController")],p);var Q="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",X="Embeddings not found for this web map.",tt="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",x=class extends T{constructor(){super(...arguments),this._messages=D({blocking:!0}),this.#t=_(),this.#l=_(),this.#s=_(),this.#e=null,this.#r=new Map,this.#i=j.getDefault(),this.#a=t=>{t.stopPropagation(),this.cancelInterrupt()},this.#n=t=>{t.stopPropagation();let s=t.detail;this.submitInterrupt(s)},this.#c=t=>{t.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let s=t.detail;this._inputValue="",this.arcgisSubmit.emit(s),this.submitMessage(s)},this.#h=t=>{if(this._canceling=!0,t.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this._orchestratorController?.cancel(),this.#e?.abort(),this.#e=null},this.#g=t=>{t.stopPropagation();let s=t.detail;this.arcgisFeedback.emit(s)},this.#d=t=>{t.stopPropagation();let s=t.detail;this._inputValue=s.prompt,this.arcgisPromptSelect.emit(s)},this.#p=t=>{this.arcgisSlottableRequest.emit(t.detail)},this._orchestratorController=null,this._interrupt=null,this._interruptDetails=[],this._error=null,this._inputValue="",this._isAnswering=!1,this._canceling=!1,this.messages=new N([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.streamingDisabled=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.assistantAvatarEnabled=!1,this.arcgisCancel=d(),this.arcgisError=d(),this.arcgisFeedback=d(),this.arcgisInterrupt=d(),this.arcgisInterruptCancel=d(),this.arcgisInterruptSubmit=d(),this.arcgisPromptSelect=d(),this.arcgisReady=d(),this.arcgisSubmit=d(),this.arcgisSlottableRequest=d({bubbles:!1,composed:!1}),this.arcgisResponse=d()}static{this.properties={_orchestratorController:16,_interrupt:16,_interruptDetails:16,_error:16,_inputValue:16,_isAnswering:16,_signedInUserId:16,_canceling:16,_isSignedIn:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,streamingDisabled:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5,assistantAvatarEnabled:5}}static{this.styles=G}#t;#l;#s;#e;#r;#i;#a;#n;#c;#h;#g;#d;#p;async#o(){try{let t=R(this.el,this.referenceElement);await t?.componentOnReady();let s=[...this.#r.values()];return s.length?(this._orchestratorController?.destroy(),this._orchestratorController=new p({agents:s,portal:this.#i,streamingDisabled:this.streamingDisabled,view:t?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(t){return this._error=t?.message??"Error initializing orchestrator.",P(this)(t),!1}}get _isSignedIn(){return!!this.#i?.user||!!this._signedInUserId}get _user(){return this.#i?.user?.fullName||this.#i?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(t){this.#r.set(t.agent.id,t),this._orchestratorController&&this.#o()}unregister(t){this.#r.delete(t),this._orchestratorController&&this.#o()}async submitMessage(t){let s=t.trim();if(!s||(this.messages.push({id:Date.now().toString(),role:"user",content:s}),!this._orchestratorController))return;this.#e=new AbortController,this._orchestratorController.streamingDisabled=this.streamingDisabled;let i=this._orchestratorController.ask(s,this.#e?.signal);for await(let e of i){let n=e.runId,r=this.messages.at(-1);switch(e.type){case"block-start":{this._isAnswering=!0;let a={type:e.blockType,isPending:!0};if(r?.role==="assistant"&&r.id===n){let l=[...r.blocks??[],a];this.messages.splice(-1,1,{...r,blocks:l})}else this.messages.push({role:"assistant",blocks:[a],id:n,isStreaming:!0,interrupts:this._interruptDetails}),this._interruptDetails=[];break}case"block-data":{if(r?.role!=="assistant"||r?.id!==n)break;let a=[...r.blocks??[]],l=a[a.length-1],{blockType:h,data:g}=e;if(l?.type!==h||!l.isPending)break;h==="text"?a[a.length-1]={...l,data:{...l.data,parts:g?.parts}}:a[a.length-1]={...l,data:{...l.data,...g??{}}},this.messages.splice(-1,1,{...r,blocks:a});break}case"block-end":{if(r?.role!=="assistant"||r?.id!==n)break;let a=[...r.blocks??[]],l=a[a.length-1];if(l?.type!==e.blockType||!l.isPending)break;let h=l;a[a.length-1]={...h,data:{...h.data},isPending:!1},this.messages.splice(-1,1,{...r,blocks:a});break}case"completed":e.error?(this.messages.push({role:"assistant",log:e.log,error:e.error,id:n,interrupts:this._interruptDetails}),this._interruptDetails=[]):r?.role==="assistant"&&r.id===n&&this.messages.splice(-1,1,{...r,content:e.response,blocks:r.blocks?.map(a=>({...a,data:{...a.data},isPending:!1}))??[],isStreaming:!1,log:e.log}),this._isAnswering=!1,this.#e=null,this._canceling=!1;break;case"interrupt":this._interrupt={...e.payload,id:n},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":r?.role==="assistant"&&r.id===n?this.messages.splice(-1,1,{...r,blocks:r.blocks?.filter(a=>a.type==="text"||!a.isPending)??[],isStreaming:!1,log:e.log,error:"(Stopped by user)"}):(this.messages.push({role:"assistant",log:e.log,error:"(Stopped by user)",id:n,interrupts:this._interruptDetails}),this._interruptDetails=[]),this._isAnswering=!1,this.#e=null,this._canceling=!1;break}}}submitInterrupt(t){this.arcgisInterruptSubmit.emit(t),this._interrupt&&(this._interruptDetails=[...this._interruptDetails,{interrupt:this._interrupt,response:t}]),this.orchestrator?.resumeInterrupt(t),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#t.value?.addEventListener("arcgisPromptSelect",this.#d),this.#t.value?.addEventListener("arcgisSubmit",this.#c),this.#t.value?.addEventListener("arcgisCancel",this.#h),this.#t.value?.addEventListener("arcgisFeedback",this.#g);let t=V(()=>!!this._interrupt&&!!this.#s.value,()=>{let i=this.#s.value;i.removeEventListener("arcgisSubmit",this.#n),i.removeEventListener("arcgisCancel",this.#a),i.addEventListener("arcgisSubmit",this.#n,{once:!0}),i.addEventListener("arcgisCancel",this.#a,{once:!0})}),s=this.messages.on("after-add",i=>{let e=i.item;e.role==="assistant"&&(e.error||e.content)&&this.arcgisResponse.emit(e)});return queueMicrotask(()=>{this.#o().then(i=>{i?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{t.remove(),s.remove(),this.#t.value?.removeEventListener("arcgisPromptSelect",this.#d),this.#s.value?.removeEventListener("arcgisSubmit",this.#n),this.#s.value?.removeEventListener("arcgisCancel",this.#a),this.#t.value?.removeEventListener("arcgisSubmit",this.#c),this.#t.value?.removeEventListener("arcgisCancel",this.#h),this.#t.value?.removeEventListener("arcgisFeedback",this.#g),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this._orchestratorController?.cancel(),this.#e?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue="",this._signedInUserId=void 0}_renderEntryMessage(){return this._isSignedIn?this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:c`<calcite-notice open kind=brand closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:c`<slot name=entry-message></slot>`:this._renderSignInNotice()}_renderSignInNotice(){let t=this.#i;return c`<calcite-notice slot=entry-message open kind=brand icon width=full><div slot=message>You need to sign in to use the assistant chat.</div>${t?c`<calcite-link slot=link @click=${async()=>{try{let s=await q.getCredential(`${t.url}/sharing`);this._signedInUserId=s.userId,this._error=null,this.requestUpdate(),await this.#o()?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))}catch(s){this._error=s?.message??"Error signing in.",this.arcgisError.emit(new Error(this._error)),C("error",this,"Error signing in:",{detail:{error:s}})}}} target=_blank title="Sign in to ArcGIS Online">Sign in</calcite-link>`:c`<div slot=link>No portal information available</div>`}</calcite-notice>`}_renderErrorNotice(){return this._error?c`<calcite-notice slot=entry-message open kind=brand icon width=full>${this._error===Q?c`<div slot=message>${X}</div><calcite-link slot=link .href=${tt} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:c`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}render(){return c`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${y(this.#t)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages} .interrupt=${this._interrupt}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(t=>t.role==="assistant"?c`<arcgis-assistant-message .message=${t} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#p} .assistantAvatarEnabled=${this.assistantAvatarEnabled}>${t.blocks?.map((s,i)=>c`<slot name=${I(t.id,i)??k} slot=${I(t.id,i)??k}><arcgis-assistant-message-block .block=${s}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:c`<arcgis-assistant-user-message .message=${t} .user=${this._user}></arcgis-assistant-user-message>`)}</slot>${this._interrupt?c`<div slot=message-loading><div class="interrupt-waiting-message">waiting for user input...</div></div>`:c`<slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep} .assistantAvatarEnabled=${this.assistantAvatarEnabled} .interrupts=${this._interruptDetails}></arcgis-assistant-message-loading></slot>`}</arcgis-assistant-chat></div>${this._interrupt?c`<slot name=interrupt><arcgis-assistant-interrupt slot=content-bottom .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${y(this.#s)}></arcgis-assistant-interrupt></slot>`:this.suggestedPrompts?.length?c`<div class="suggested-prompts-container" slot=content-bottom><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse||this._isAnswering} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} .disabled=${this._canceling||!this._isSignedIn||!!this._interrupt} ${y(this.#l)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse||this._isAnswering?"circle-stop":"send"} @click=${()=>{this.#l.value?.submitMessage()}} round>${this.awaitingResponse||this._isAnswering?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};A("arcgis-assistant",x);return x},"core/Collection","core/reactiveUtils","portal/Portal","request","identity/IdentityManager","config","layers/FeatureLayer","core/Accessor","core/accessorSupport/decorators",a,b)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import d from"./33BF35AO.js";import c from"./3ZPPYCNL.js";import b from"./RWM5T4XB.js";import{a as s,c as e}from"./V6HOUZPZ.js";import"./3UEKINYC.js";import"./RLEHNAIA.js";import a from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import{v as i,z as r}from"./6TA5KFAQ.js";import"./R74ZHFA6.js";import"./HJG7QM2R.js";import"./WZFC5HUX.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,,,,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-help-agent"),this.#i=e(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-help-agent",t);return t},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c,d)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import d from"./DWYODVWW.js";import c from"./3ZPPYCNL.js";import b from"./RWM5T4XB.js";import{a as s,c as e}from"./V6HOUZPZ.js";import"./3UEKINYC.js";import"./RLEHNAIA.js";import a from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import{v as i,z as r}from"./6TA5KFAQ.js";import"./R74ZHFA6.js";import"./HJG7QM2R.js";import"./WZFC5HUX.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,,,,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-layer-styling-agent"),this.#i=e(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-layer-styling-agent",t);return t},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c,d)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import k from"./WDOM6Z5O.js";import j from"./33BF35AO.js";import i from"./5SFZS2RD.js";import f from"./DWYODVWW.js";import e from"./Z4XUJQ2I.js";import d from"./3ZPPYCNL.js";import c from"./RWM5T4XB.js";import b from"./I4L45WQS.js";import a from"./ZJEWP2ND.js";import{e as g,f as h}from"./HO2YDJI2.js";import"./R74ZHFA6.js";import{a as u,b as y}from"./HJG7QM2R.js";import"./WZFC5HUX.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([C,I,{d:w,g:v,h:A,i:b,j:S,k:d,l:p,m:M,n:E,o:P,p:T,q:x,r:D},{a:f,b:V},,,O,L,k,W,R])=>{var U=async e=>{let a=e.allLayers.toArray(),s=[],o=new Map;for(let t of a)if(t instanceof C){let i=(async()=>{let n=await x(t),r=await D(t,n);o.set(t.id,{layerItem:r,fieldRegistry:n})})();s.push(i)}return await Promise.all(s),o},q=async e=>{await I.whenOnce(()=>e.ready);let a=await U(e.map),{layers:s}=await z(a),o={schemaVersion:v,modified:Date.now(),embeddings:{modelProvider:b,model:S,dimensions:A,templates:{layer:d,field:p}},layers:s},t=M.safeParse(o);if(!t.success)throw console.error("Schema Mismatch:",t.error.format()),new Error("Webmap embedding generation failed validation.");return t.data},z=async e=>{let a=[],s=[];for(let[i,{fieldRegistry:n,layerItem:r}]of e.entries()){let l=H(d,{name:r.name,title:r.title,description:r.description});a.push(l);let m={id:i,name:r.name??"",title:r.title,description:r.description,vector:[],fields:[]};for(let[,c]of n.entries()){let N=H(p,{name:c.name,alias:c.alias,description:c.description});a.push(N),m.fields.push({name:c.name,alias:c.alias,description:c.description,vector:[]})}s.push(m)}let o=await f(a),t=0;return{layers:s.map(i=>(i.vector=o[t++],i.fields.forEach(n=>{n.vector=o[t++]}),i))}},H=(e,a)=>e.replace(/\{(\w+)\}/gu,(s,o)=>a[o]??""),F=(e,a)=>{if(e.length!==a.length)throw new Error("Vectors must be the same length");let s=0,o=0,t=0;for(let r=0;r<e.length;++r){let l=e[r],m=a[r];s+=l*m,o+=l*l,t+=m*m}let i=Math.sqrt(o*t);if(i===0)return 0;let n=s/i;return Math.max(-1,Math.min(1,n))},ee=E,ae=P,te=T,se=u,re=f,oe=F,ie=O,ne=L,me=R,ce=W,le=k,de=q,pe=()=>g(),fe=()=>h(),ge=async(e,a)=>await y(e,a),he=async({modelTier:e="default",temperature:a=0,config:s}={})=>await w({modelTier:e,temperature:a,config:s});return{ArcgisKnowledgeAgent:le,DataExplorationAgent:me,HelpAgent:ce,LayerStylingAgent:ne,NavigationAgent:ie,Orchestrator:V,cosineSimilarity:oe,createAgentRuntimeState:pe,createAgentRuntimeStateWithSharedState:fe,createChatModel:he,createWebmapEmbeddings:de,getEmbeddings:re,invokeStructuredPrompt:ae,invokeTextPrompt:ee,invokeToolPrompt:te,sendTraceMessage:se,sendUXSuggestion:ge}},"layers/FeatureLayer","core/reactiveUtils",a,b,c,d,e,f,i,j,k)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import a from"./5SF6DEMO.js";import"./UZL6UVE4.js";import"./HO2YDJI2.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([{property:g,subclass:y},{c:p,d:w}])=>{var b=Object.defineProperty,k=Object.getOwnPropertyDescriptor,v=e=>{throw TypeError(e)},h=(e,t,r,s)=>{for(var n=s>1?void 0:s?k(t,r):t,o=e.length-1,a;o>=0;o--)(a=e[o])&&(n=(s?a(t,r,n):a(n))||n);return s&&n&&b(t,r,n),n},A=(e,t,r)=>t.has(e)||v("Cannot "+r),M=(e,t,r)=>t.has(e)?v("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),m=(e,t,r)=>(A(e,t,"access private method"),r),c,u,i=class extends w{constructor(e){super(e),M(this,c)}getAgents(){let e=Object.values(this.agentsMap);return this.defaultAgent?e.concat(this.defaultAgent):e}buildNodes(e){let t=super.buildNodes(e);return t[d]=()=>({}),t}buildEdges(e){m(this,c,u).call(this);let t=this.resolver,r=new Map;for(let[o,[a]]of Object.entries(this.agentsMap).entries())r.set(a,p(e[o],o));let{defaultAgent:s}=this,n=s?p(s,e.length-1):void 0;return[{from:d,decide:async(o,a)=>{let l=await Promise.resolve(t(o,a));if(!l)return;let f=r.get(l);if(f)return f;if(s)return n;throw new Error(`SwitchWorkflow resolver returned unknown case: ${l}. Expected one of: ${Object.keys(this.agentsMap).join(", ")||"(none)"}.`)}}]}getEntryNode(){return d}isTerminalAgent(){return!0}validateAgents(e){m(this,c,u).call(this),super.validateAgents(e)}};c=new WeakSet;u=function(){if(!Object.keys(this.agentsMap).length)throw new Error("SwitchWorkflow requires a non-empty agentsMap.")};h([g()],i.prototype,"agentsMap",2);h([g()],i.prototype,"resolver",2);h([g()],i.prototype,"defaultAgent",2);i=h([y("SwitchWorkflow")],i);var d="__switch_decide";return i},"core/accessorSupport/decorators",a)
|