@arcgis/ai-components 5.2.0-next.71 → 5.2.0-next.73

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.
Files changed (167) hide show
  1. package/LICENSE.md +4 -2
  2. package/dist/agent-utils/LLMAgent.d.ts +5 -2
  3. package/dist/agent-utils/LLMAgent.js +1 -1
  4. package/dist/agent-utils/types.d.ts +1 -1
  5. package/dist/agentic-workflow/AgenticWorkflowRuntime.d.ts +24 -0
  6. package/dist/agentic-workflow/Edge.d.ts +16 -0
  7. package/dist/agentic-workflow/WebAgent.d.ts +39 -0
  8. package/dist/agentic-workflow/jsonTypes.d.ts +193 -0
  9. package/dist/agentic-workflow/nodes/AgentNode.d.ts +28 -0
  10. package/dist/agentic-workflow/nodes/BaseNode.d.ts +35 -0
  11. package/dist/agentic-workflow/nodes/EndMessageNode.d.ts +25 -0
  12. package/dist/agentic-workflow/nodes/StartNode.d.ts +21 -0
  13. package/dist/agentic-workflow/nodes/support/Prompt.d.ts +20 -0
  14. package/dist/agentic-workflow/nodes/tools/ArcgisTool.d.ts +21 -0
  15. package/dist/agentic-workflow/types.d.ts +29 -0
  16. package/dist/cdn/2EJROB32.js +2 -0
  17. package/dist/cdn/34O57OGV.js +2 -0
  18. package/dist/cdn/3LXXSMA5.js +2 -0
  19. package/dist/cdn/3MJQA533.js +2 -0
  20. package/dist/cdn/3U476GCP.js +5 -0
  21. package/dist/cdn/3XXZUQMQ.js +2 -0
  22. package/dist/cdn/4YDXYW4J.js +2 -0
  23. package/dist/cdn/4ZUUS4DH.js +2 -0
  24. package/dist/cdn/527C4GD2.js +36 -0
  25. package/dist/cdn/5RZGG4F2.js +2 -0
  26. package/dist/cdn/5SF6DEMO.js +2 -0
  27. package/dist/cdn/5Y6TQAJN.js +2 -0
  28. package/dist/cdn/65IWA2PM.js +2 -0
  29. package/dist/cdn/{MW5S2XCB.js → 67YCNNCN.js} +2 -2
  30. package/dist/cdn/6FKLWNGA.js +2 -0
  31. package/dist/cdn/6QJFOL6M.js +2 -0
  32. package/dist/cdn/6RDKDLSX.js +2 -0
  33. package/dist/cdn/6SGNSDLY.js +2 -0
  34. package/dist/cdn/7747YL7V.js +2 -0
  35. package/dist/cdn/7TO56JHS.js +2 -0
  36. package/dist/cdn/ABXLPDEK.js +2 -0
  37. package/dist/cdn/BBJDW6GC.js +2 -0
  38. package/dist/cdn/{PUFTYLJ2.js → C4FKFOU4.js} +4 -4
  39. package/dist/cdn/CCC6LBMY.js +2 -0
  40. package/dist/cdn/CGVVL52C.js +2 -0
  41. package/dist/cdn/DBHLKLKM.js +2 -0
  42. package/dist/cdn/DKLK4EUE.js +2 -0
  43. package/dist/cdn/E25RINU2.js +2 -0
  44. package/dist/cdn/E62P76TP.js +2 -0
  45. package/dist/cdn/E7JLG2A2.js +2 -0
  46. package/dist/cdn/{TFT6HK3O.js → E7KEOJZG.js} +1 -1
  47. package/dist/cdn/FDOMMK2M.js +2 -0
  48. package/dist/cdn/FSMHR7GK.js +2 -0
  49. package/dist/cdn/GG3AESSV.js +2 -0
  50. package/dist/cdn/H6JSNAT4.js +2 -0
  51. package/dist/cdn/HNMFFLSY.js +2 -0
  52. package/dist/cdn/HO2YDJI2.js +6 -0
  53. package/dist/cdn/{KQHLOYKL.js → I4L45WQS.js} +1 -1
  54. package/dist/cdn/ITBQGOMF.js +11 -0
  55. package/dist/cdn/JH6EAWB2.js +2 -0
  56. package/dist/cdn/JON2JHS2.js +2 -0
  57. package/dist/cdn/JWPB3XZM.js +2 -0
  58. package/dist/cdn/JXB4TNSG.js +2 -0
  59. package/dist/cdn/JYVBCHR6.js +6 -0
  60. package/dist/cdn/KRN6AFNB.js +18 -0
  61. package/dist/cdn/KZACIY2W.js +2 -0
  62. package/dist/cdn/MKJS7QYQ.js +2 -0
  63. package/dist/cdn/N735LT4S.js +2 -0
  64. package/dist/cdn/NP7DG7LQ.js +2 -0
  65. package/dist/cdn/NTZAOJH5.js +2 -0
  66. package/dist/cdn/{CXW5URTF.js → OHMNQ3RU.js} +5 -5
  67. package/dist/cdn/ONQ6JSBJ.js +2 -0
  68. package/dist/cdn/PAUIFUMO.js +2 -0
  69. package/dist/cdn/QNNGPA3Q.js +2 -0
  70. package/dist/cdn/RATZTLNX.js +2 -0
  71. package/dist/cdn/RU5DVLYG.js +156 -0
  72. package/dist/cdn/{YHQJ66WJ.js → S3XUYAUX.js} +1 -1
  73. package/dist/cdn/S6ZAQRC6.js +2 -0
  74. package/dist/cdn/SABZC4D4.js +2 -0
  75. package/dist/cdn/TYL5G7KR.js +2 -0
  76. package/dist/cdn/{XETNZW4D.js → UAZLKUFN.js} +1 -1
  77. package/dist/cdn/UZL6UVE4.js +2 -0
  78. package/dist/cdn/VBZ5XGAM.js +2 -0
  79. package/dist/cdn/VXBUMZYR.js +2 -0
  80. package/dist/cdn/W5FLNFSN.js +2 -0
  81. package/dist/cdn/W5J4Q3RO.js +14 -0
  82. package/dist/cdn/WQKNV6KK.js +2 -0
  83. package/dist/cdn/{ICYUPLZM.js → WZFC5HUX.js} +1 -1
  84. package/dist/cdn/XGBEHER5.js +2 -0
  85. package/dist/cdn/XPTCV6YV.js +2 -0
  86. package/dist/cdn/Y5UFOH54.js +2 -0
  87. package/dist/cdn/YGCTAIBS.js +2 -0
  88. package/dist/cdn/{SXHH575T.js → ZJEWP2ND.js} +20 -24
  89. package/dist/cdn/agent-utils/index.js +1 -1
  90. package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
  91. package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
  92. package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
  93. package/dist/cdn/index.js +1 -1
  94. package/dist/chunks/adapter.js +939 -1950
  95. package/dist/chunks/adapter10.js +21 -0
  96. package/dist/chunks/adapter11.js +30 -0
  97. package/dist/chunks/adapter12.js +22 -0
  98. package/dist/chunks/adapter13.js +22 -0
  99. package/dist/chunks/adapter14.js +109 -0
  100. package/dist/chunks/adapter15.js +40 -0
  101. package/dist/chunks/adapter16.js +154 -0
  102. package/dist/chunks/adapter17.js +141 -0
  103. package/dist/chunks/adapter18.js +127 -0
  104. package/dist/chunks/adapter2.js +52 -0
  105. package/dist/chunks/adapter3.js +30 -0
  106. package/dist/chunks/adapter4.js +50 -0
  107. package/dist/chunks/adapter5.js +27 -0
  108. package/dist/chunks/adapter6.js +24 -0
  109. package/dist/chunks/adapter7.js +26 -0
  110. package/dist/chunks/adapter8.js +21 -0
  111. package/dist/chunks/adapter9.js +42 -0
  112. package/dist/chunks/arcgisKnowledgeGraph.js +5 -5
  113. package/dist/chunks/baseAgentState.js +56 -0
  114. package/dist/chunks/dataExplorationGraph.js +34 -31
  115. package/dist/chunks/fetchAgentContext.js +13 -0
  116. package/dist/chunks/fetchService.js +10 -0
  117. package/dist/chunks/formatFeatureAttributes.js +132 -0
  118. package/dist/chunks/generateLayerDescriptions.js +189 -235
  119. package/dist/chunks/helpGraph.js +11 -9
  120. package/dist/chunks/layerStylingGraph.js +22 -21
  121. package/dist/chunks/mergeWhereClauses.js +15 -0
  122. package/dist/chunks/navigationGraph.js +81 -70
  123. package/dist/chunks/orchestrator.js +1 -1
  124. package/dist/chunks/state.js +20 -26
  125. package/dist/chunks/types.js +59 -0
  126. package/dist/chunks/utils2.js +3 -3
  127. package/dist/components/arcgis-assistant-agent/customElement.d.ts +13 -1
  128. package/dist/components/arcgis-assistant-agent/customElement.js +636 -10
  129. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +15 -5
  130. package/dist/components/arcgis-assistant-help-agent/customElement.js +21 -5
  131. package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +39 -22
  132. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +22 -5
  133. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +13 -5
  134. package/dist/docs/api.json +1 -1
  135. package/dist/docs/docs.json +1 -1
  136. package/dist/docs/vscode.html-custom-data.json +1 -1
  137. package/dist/docs/web-types.json +1 -1
  138. package/dist/loader.js +1 -1
  139. package/dist/types/lumina.d.ts +1 -1
  140. package/dist/types/preact.d.ts +1 -1
  141. package/dist/types/react.d.ts +1 -1
  142. package/dist/types/stencil.d.ts +1 -1
  143. package/dist/utils/index.js +26 -25
  144. package/package.json +4 -4
  145. package/dist/cdn/3DJDRAGV.js +0 -2
  146. package/dist/cdn/4CEMUECT.js +0 -2
  147. package/dist/cdn/4PCAK3ET.js +0 -2
  148. package/dist/cdn/57OMVTIU.js +0 -2
  149. package/dist/cdn/6U7TEAAJ.js +0 -2
  150. package/dist/cdn/BE7ZN5FZ.js +0 -2
  151. package/dist/cdn/BNSJO6X2.js +0 -2
  152. package/dist/cdn/CMDRED5H.js +0 -2
  153. package/dist/cdn/DTIVDIDY.js +0 -2
  154. package/dist/cdn/E5ZKBC24.js +0 -36
  155. package/dist/cdn/GP6NDTUE.js +0 -18
  156. package/dist/cdn/HBLRVXEB.js +0 -2
  157. package/dist/cdn/HQXPPYMD.js +0 -2
  158. package/dist/cdn/IEHPNCTL.js +0 -2
  159. package/dist/cdn/LHLO6PTD.js +0 -2
  160. package/dist/cdn/OWXCOUIQ.js +0 -2
  161. package/dist/cdn/PVE7Q43N.js +0 -2
  162. package/dist/cdn/ST5FQYT7.js +0 -180
  163. package/dist/cdn/WUNCZOGU.js +0 -2
  164. package/dist/cdn/WVPU4QOO.js +0 -2
  165. package/dist/cdn/WXWO5D3W.js +0 -2
  166. package/dist/cdn/XCRR2EEG.js +0 -6
  167. package/dist/cdn/ZS6SXJP2.js +0 -2
@@ -0,0 +1,36 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import f from"./3ZPPYCNL.js";import e from"./RU5DVLYG.js";import d from"./HNMFFLSY.js";import{a as Z}from"./RATZTLNX.js";import{a as h}from"./FDOMMK2M.js";import c from"./3MJQA533.js";import{a as F}from"./E25RINU2.js";import{a as C}from"./SABZC4D4.js";import b from"./GG3AESSV.js";import{a as L}from"./KZACIY2W.js";import{a as _}from"./XGBEHER5.js";import{a as I}from"./JWPB3XZM.js";import a from"./ZJEWP2ND.js";import{a as x}from"./ONQ6JSBJ.js";import{a as g}from"./HJG7QM2R.js";import{Wa as E,a as w,b as k}from"./E7KEOJZG.js";import{a as y}from"./VXFQANGJ.js";export default $arcgis.t(([,,,,,,{o:$,p:N},R,b,M,{a:A,b:v,c:S,d:q,e:V},j])=>{var T=[b,F,C,R,L,_,I,M,Z];async function B(e,t){let a=await S("navigation_tool_prompt"),{mapView:s}=x(t,["mapView"]),c=s.map.bookmarks?.map(p=>p.name).filter(Boolean)??[],i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((p,G)=>`${G+1}. layerId=${p.id} | title=${p.title??""} | name=${p.name??""} | score=${p.score.toFixed(2)}`).join(`
3
+ `):"",l=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",n=e.intent==="goToBookmark"&&c.length?`Available bookmarks:
4
+ ${c.map(p=>`- ${p}`).join(`
5
+ `)}`:"",o=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
6
+ ${i}`:"",m=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
7
+ ${l}`:"",u={intent:e.intent,bookmarksSection:n,layersSection:o,fieldsSection:m,currentZoom:s.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},r=await N({promptText:a,modelTier:"fast",config:t,inputVariables:u,tools:T});await j(r,t);let d=(r.tool_calls?.length??0)>0,f=typeof r.text=="string"?r.text.trim():"",z=f.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:d?r:void 0},outputMessage:d?e.outputMessage:f,status:d?e.status:z?"success":"failed"}}var D=e=>{let t=typeof e=="string"?e:String(e);try{let a=JSON.parse(t);if(a&&typeof a=="object"&&typeof a.text=="string")return a}catch{console.warn("Failed to parse tool response as JSON:",t)}return{text:t}};async function J(e,t){let a=new A(T,{handleToolErrors:!1});try{let s=e.navigationInternalState.toolCallMessage;if(!s)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let{messages:c}=await a.invoke({messages:[s]},t),i="",l;for(let n of c){let o=D(n.content);o.text&&(i+=`${o.text}
8
+ `),o.sharedStatePatch&&(l={...l,...o.sharedStatePatch})}return await g({text:`Finished executing navigation tool: ${i}`},t),{...e,outputMessage:i,sharedStatePatch:l,status:"success",summary:i?q(i):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(s){let c=s instanceof Error?s.message:String(s);return await g({text:`Navigation tool execution failed: ${c}`},t),{...e,outputMessage:`Navigation tool execution failed: ${c}`,status:"failed",summary:`Navigation tool execution failed: ${c}`,navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}}async function P(e,t){let a=await S("navigation_intent_prompt"),{mapView:s}=x(t,["mapView"]),c=T.map(r=>({name:r.name,description:r.description,schema:r.schema})),i=s.map.bookmarks?.map(r=>r.name).filter(Boolean)??[],l=i.length?`Available bookmarks:
9
+ ${i.map(r=>`- ${r}`).join(`
10
+ `)}`:"No bookmarks are available in this map.",n={tools:c.map(({name:r,description:d,schema:f})=>`${r}: ${d}, ${JSON.stringify(f)}`).join(`
11
+ `),bookmarks:l,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=y.object({intent:y.string()}),m=await $({promptText:a,config:t,inputVariables:n,schema:o,modelTier:"fast"}),u=typeof m.intent=="string"?m.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var H=.7,W=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let a=h(t,"layerSearch"),s=h(t,"layersAndFieldsRegistry"),c=h(t,"embeddingCache"),i=(await a.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:H,embeddingCache:c})).map(({id:n,score:o})=>{let m=s.get(n)?.layerItem;return{id:n,title:m?.title,name:m?.name??void 0,score:o}}),l;return i.length>0?l=`Vector search completed. Matching layers:
12
+ ${i.map(n=>`- layerId=${n.id} | title=${n.title??""} | name=${n.name??""} | score=${n.score.toFixed(2)}`).join(`
13
+ `)}`:l="Vector search completed. No matching layers found.",await g({text:l},t),{...e,vectorSearchLayerResults:i}}catch(a){throw await g({text:`Error during vector search layers: ${a instanceof Error?a.message:String(a)}`},t),a}},O=.7,K=10,Q=async(e,t)=>{try{await g({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let a=h(t,"fieldSearch"),s=h(t,"layersAndFieldsRegistry"),c=h(t,"embeddingCache"),i=e.vectorSearchLayerResults?.map(o=>o.id)??[];if(i.length===0)return await g({text:"No candidate layers for field search"},t),e;let l=(await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:i,minScore:O,topResults:K,embeddingCache:c})).map(({layerId:o,results:m})=>{let u=s.get(o)?.fieldRegistry;return{layerId:o,layerName:s.get(o)?.layerItem.name,results:m.map(r=>{let d=u?.get(r.name);return{name:r.name,score:r.score,type:d?.type,alias:d?.alias,description:d?.description,statistics:d?.statistics,domain:d?.domain}})}}),n;return l.length>0?n=`Vector search completed. Matching layers and fields:
14
+ ${l.map(o=>`${o.layerName??o.layerId}:
15
+ ${o.results.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
16
+ `)}`).join(`
17
+ `)}`:n=`No vector search field results found for score over ${O}.`,await g({text:n},t),{...e,vectorSearchFieldResults:l}}catch(a){throw await g({text:`Error during vector search fields: ${a instanceof Error?a.message:String(a)}`},t),a}},U=(e,t)=>V(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),X=()=>new E(v).addNode("requireNavigationServices",U).addNode("intentLLM",P).addNode("vectorSearchLayers",W).addNode("vectorSearchFields",Q).addNode("agent",B).addNode("tools",J).addEdge(w,"requireNavigationServices").addEdge("requireNavigationServices","intentLLM").addConditionalEdges("intentLLM",e=>e.intent==="goToLayer"||e.intent==="goToFeatures"?"vectorSearchLayers":"agent",{vectorSearchLayers:"vectorSearchLayers",agent:"agent"}).addConditionalEdges("vectorSearchLayers",e=>e.intent==="goToFeatures"?"vectorSearchFields":"agent",{vectorSearchFields:"vectorSearchFields",agent:"agent"}).addEdge("vectorSearchFields","agent").addEdge("agent","tools").addEdge("tools",k),Y=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
18
+ This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
19
+
20
+ Supported actions:
21
+ - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
22
+ - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
23
+ - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
24
+ - **Layers**: Zoom to the full extent of a specific layer (e.g., "Go to the water mains layer"). For the purposes of link charts, if the user requests to go to the extent of a link chart or the entities/nodes within it, that should be treated as a request to use the goToLayer tool on the link chart layer
25
+ - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
26
+ - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
27
+ - **Extents**: Reset to the initial web map extent or zoom to the full world extent (e.g., "Reset the map", "Zoom to the full world extent").
28
+ - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
29
+
30
+ _Example: “Zoom to Texas”_
31
+ _Example: “Go to the water mains layer”_
32
+ _Example: “Zoom to to the extent of my link chart”_
33
+ _Example: “Center the map on San Francisco at scale 50000”_
34
+ _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
35
+ _Example: “Go to the Downtown bookmark”_
36
+ _Example: “Where is Mount Rainier?”_`,Fe={id:"navigation",name:"Navigation Agent",description:Y,createGraph:X,workspace:v};return Fe},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer",a,b,c,d,e,f)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{$ as J,$a as Ga,A as z,Aa as ia,B as A,Ba as ja,C as B,Ca as ka,D as C,E as D,Ea as la,F as E,Fa as ma,G as F,Ga as na,H as G,Ha as oa,I as H,Ia as pa,Ja as qa,Ka as ra,La as sa,Ma as ta,Na as ua,Oa as va,Pa as wa,Qa as xa,Ra as ya,S as I,Sa as za,Ta as Aa,Wa as Ba,Xa as Ca,Ya as Da,Za as Ea,_a as Fa,a,aa as K,ab as Ha,b,ba as L,bb as Ia,c,ca as M,cb as Ja,d,da as N,db as Ka,e,ea as O,eb as La,f,fa as P,ga as Q,h as g,ha as R,i as h,ia as S,j as i,ja as T,k as j,ka as U,l as k,la as V,m as l,ma as W,n as m,na as X,o as n,oa as Y,p as o,pa as Z,q as p,qa as _,r as q,ra as $,s as r,sa as aa,t as s,ta as ba,u as t,ua as ca,v as u,va as da,w as v,wa as ea,x as w,xa as fa,y as x,ya as ga,z as y,za as ha}from"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{S as Annotation,O as AsyncBatchedStore,Q as BaseChannel,L as BaseCheckpointSaver,k as BaseLangGraphError,N as BaseStore,R as BinaryOperatorAggregate,d as COMMAND_SYMBOL,I as ChatModelStreamImpl,i as Command,e as CommandInstance,Ca as CompiledStateGraph,qa as DeltaChannel,ua as DeltaValue,b as END,B as EmptyChannelError,A as EmptyInputError,$ as EventLog,la as Graph,l as GraphBubbleUp,o as GraphDrained,q as GraphInterrupt,m as GraphRecursionError,ha as GraphRunStream,n as GraphValueError,c as INTERRUPT,P as InMemoryStore,C as InvalidUpdateError,M as MemorySaver,Da as MessageGraph,Ia as MessagesAnnotation,Aa as MessagesDeltaValue,za as MessagesValue,Ja as MessagesZodMeta,Ka as MessagesZodState,D as MultipleSubgraphsError,s as NodeError,r as NodeInterrupt,y as NodeTimeoutError,g as Overwrite,u as ParentCommand,wa as REMOVE_ALL_MESSAGES,sa as ReducedValue,F as RemoteException,X as RunControl,a as START,Y as STREAM_EVENTS_V3_MODES,f as Send,Ba as StateGraph,G as StateGraphInputError,va as StateSchema,$ as StreamChannel,ia as SubgraphRunStream,E as UnreachableNodeError,ta as UntrackedValue,ra as UntrackedValueChannel,xa as addMessages,_ as convertToProtocolEvent,K as copyCheckpoint,ja as createGraphRunStream,ba as createLifecycleTransformer,ca as createMessagesTransformer,ea as createSubgraphDiscoveryTransformer,fa as createValuesTransformer,J as emptyCheckpoint,Ga as entrypoint,aa as filterLifecycleEntries,da as filterSubgraphHandles,V as getConfig,W as getCurrentTaskInput,oa as getJsonSchemaFromSchema,Ha as getPreviousState,pa as getSchemaDefaultGetter,T as getStore,H as getSubgraphsSeenSet,U as getWriter,ka as interrupt,Z as isCheckpointEnvelope,j as isCommand,w as isGraphBubbleUp,p as isGraphDrained,x as isGraphInterrupt,h as isInterrupted,ga as isNativeTransformer,t as isNodeError,z as isNodeTimeoutError,v as isParentCommand,na as isSerializableSchema,ma as isStandardSchema,ya as messagesDeltaReducer,xa as messagesStateReducer,Ea as pushMessage,Fa as task,La as writer};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{c as i,e as c}from"./UZL6UVE4.js";export default $arcgis.t(([m,{subclass:p}])=>{function a(t){return t?Object.keys(t.shape??{}):[]}function d(t){let e={};for(let n of t)for(let s of a(n))e[s]=void 0;return e}function g(t,e){return Object.fromEntries(e.filter(n=>Object.hasOwn(t,n)).map(n=>[n,t[n]]))}function l(t,e){return`${t.id}_${e}`}function h(t,e){let n=e.inputSchema;return n?{...g(t,a(n)),agentExecutionContext:t.agentExecutionContext,outputMessage:t.outputMessage,status:void 0,summary:""}:{...t,status:void 0,summary:""}}function x(t,e){return t.outputSchema?g(e,a(t.outputSchema)):{}}function y(t){let e={outputMessage:t.outputMessage,status:t.status,summary:t.summary};return t.agentExecutionContext&&(e.agentExecutionContext=t.agentExecutionContext),e}function v(t,e){return async(n,s)=>{let o=await t.run(h(n,t),s),r=x(t,o);return e||o.status==="failed"?{...r,...y(o)}:{...r,outputMessage:o.outputMessage}}}var w=Object.getOwnPropertyDescriptor,E=(t,e,n,s)=>{for(var o=s>1?void 0:s?w(e,n):e,r=t.length-1,u;r>=0;r--)(u=t[r])&&(o=u(o)||o);return o},f=class extends m{generate(){let t=this.getAgents();this.validateAgents(t);for(let r of t)r.generate();let e=d(t.flatMap(r=>r.getSchemas())),n=i(e),s=this.buildNodes(t),o=this.buildEdges(t);return{workspace:n,createGraph:()=>c(s,o,n,{entryNode:this.getEntryNode(t)})}}buildNodes(t){let e={};for(let[n,s]of t.entries())e[l(s,n)]=v(s,this.isTerminalAgent(t,n));return e}validateAgents(t){if(!t.length)throw new Error("Workflow requires at least one agent.")}};f=E([p("BaseWorkflow")],f);return{a:a,b:d,c:l,d:f}},"core/Accessor","core/accessorSupport/decorators")
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./XGBEHER5.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as goToLayerTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import q from"./KRN6AFNB.js";import p from"./3ZPPYCNL.js";import n from"./RU5DVLYG.js";import m from"./HNMFFLSY.js";import"./RATZTLNX.js";import l from"./W5FLNFSN.js";import k from"./W5J4Q3RO.js";import j from"./MKJS7QYQ.js";import h from"./ITBQGOMF.js";import g from"./CCC6LBMY.js";import"./34O57OGV.js";import{a as o,c as a}from"./V6HOUZPZ.js";import"./3U476GCP.js";import"./FDOMMK2M.js";import f from"./3MJQA533.js";import"./E25RINU2.js";import"./SABZC4D4.js";import e from"./GG3AESSV.js";import"./KZACIY2W.js";import"./XGBEHER5.js";import"./JWPB3XZM.js";import"./3UEKINYC.js";import"./RLEHNAIA.js";import d from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import"./7TO56JHS.js";import"./4YDXYW4J.js";import c from"./YGCTAIBS.js";import b from"./QNNGPA3Q.js";import"./ONQ6JSBJ.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(([,,,,,,,,,,,,,,,,,,,,,s])=>{var t=class extends i{constructor(){super(...arguments),this.agent=s}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=o(this,"arcgis-assistant-data-exploration-agent"),this.#i=a(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-data-exploration-agent",t);return t},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","views/LinkChartView","rest/knowledgeGraphService",b,c,d,e,f,g,h,j,k,l,m,n,p,q)
@@ -1,9 +1,9 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import b from"./ST5FQYT7.js";import a from"./SXHH575T.js";import{a as c,b as k}from"./HJG7QM2R.js";import{Va as x,a as w,b as d,j as f}from"./TFT6HK3O.js";import{ca as u}from"./LUY6V4TP.js";export default $arcgis.t(([,,,,,,{p:_,r:b},{K:y,L:K,M:q,N:S,O:M,P:T,Q:E,R:C,S:G,T:N,U:R,a:v,m:m,n:h,p:A}])=>{var z=[T,E,N,C,M,R,G];async function $(e,a){let o=await m("arcgis_knowledge_tool_prompt"),s=K(a),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:s},r=await b({promptText:o,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:z,config:a}),i=(r.tool_calls?.length??0)>0,t=typeof r.text=="string"?r.text.trim():"",l=t.length>0,p=r.content.toString();return!i&&(s==="map"||s==="knowledgeGraph")?{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:s==="map"?"No tools were found for the current view and prompt. Maps do not support changing nonspatial visibility, layout changes, or generation from queries.":"No tools were found for the current prompt and knowledge graph service. A knowledge graph service only supports search and query.",status:"success"}:{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:i?p:t,status:i?e.status:l?"success":"failed",summary:p?h(p):"ArcGIS Knowledge Agent tool executed."}}var L={generateCypher:"generated-cypher-query",queryGraphData:"graph-query-result",searchGraphData:"graph-search-result",addRecords:"added-records",applyLayout:"applied-layout",changeNonspatialVisibility:"changed-nonspatial-visibility",createLinkChart:"created-link-chart"};function I(e){return!!e&&e.status==="success"&&!!L[e.toolName]}function D(e){return{type:L[e.toolName],data:e.details}}async function F(e,a){let o=new v(z,{handleToolErrors:!1});try{let s=await o.invoke({messages:e.arcgisKnowledgeMessages},a),n=[];for(let t of s.messages){let l;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{l=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}.
2
+ import b from"./RU5DVLYG.js";import a from"./ZJEWP2ND.js";import{a as c,b as k}from"./HJG7QM2R.js";import{Wa as x,a as w,b as d,j as f}from"./E7KEOJZG.js";import{ca as u}from"./LUY6V4TP.js";export default $arcgis.t(([,,,,,,{n:_,p:b},{A:M,B:T,C:E,D:C,E:G,F:N,G:R,a:v,c:m,d:h,e:A,w:y,x:K,y:q,z:S}])=>{var z=[T,E,N,C,M,R,G];async function $(e,a){let o=await m("arcgis_knowledge_tool_prompt"),s=K(a),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:s},r=await b({promptText:o,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:z,config:a}),i=(r.tool_calls?.length??0)>0,t=typeof r.text=="string"?r.text.trim():"",l=t.length>0,p=r.content.toString();return!i&&(s==="map"||s==="knowledgeGraph")?{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:s==="map"?"No tools were found for the current view and prompt. Maps do not support changing nonspatial visibility, layout changes, or generation from queries.":"No tools were found for the current prompt and knowledge graph service. A knowledge graph service only supports search and query.",status:"success"}:{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:i?p:t,status:i?e.status:l?"success":"failed",summary:p?h(p):"ArcGIS Knowledge Agent tool executed."}}var L={generateCypher:"generated-cypher-query",queryGraphData:"graph-query-result",searchGraphData:"graph-search-result",addRecords:"added-records",applyLayout:"applied-layout",changeNonspatialVisibility:"changed-nonspatial-visibility",createLinkChart:"created-link-chart"};function I(e){return!!e&&e.status==="success"&&!!L[e.toolName]}function D(e){return{type:L[e.toolName],data:e.details}}async function F(e,a){let o=new v(z,{handleToolErrors:!1});try{let s=await o.invoke({messages:e.arcgisKnowledgeMessages},a),n=[];for(let t of s.messages){let l;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{l=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}.
3
3
 
4
4
  Original Content: ${t.content}`)}if(!l||typeof l!="object"||!("toolName"in l))throw new Error(`Parsed tool message content does not have expected structure. Parsed content: ${JSON.stringify(l)}`);n.push(l)}await c({text:`Finished executing ArcGIS Knowledge Agent tools: ${s.messages.filter(t=>t.name).map(t=>t.name).join(", ")}`},a);let r=n.filter(t=>typeof t!="string").map(t=>`- Called Tool: ${t.toolName}, Status: ${t.status}`),i=n[0];return i&&I(i)&&await k(D(i),a),{...e,outputMessage:r.join(`
5
5
  `),summary:r.length?h(r.join(`
6
- `)):"ArcGIS Knowledge Agent did not execute any tools or return any results.",arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,...s.messages],arcgisKnowledgeToolResult:n}}catch(s){let n=s instanceof Error?s.message:String(s);return await c({text:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`},a),{...e,outputMessage:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`,status:"failed",summary:h(`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages]}}}var V=(e,a)=>A([],"ArcgisKnowledge Agent")(e,a);async function j(e,a){let o=(e.arcgisKnowledgeToolResult??[]).map(l=>({...l,details:void 0})),{knowledgeGraph:s}=await q(a),n=S.getDataModelTypesSummary(s.dataModel),r={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,toolResult:o,dataModelSummary:n},i=await _({promptText:await m("arcgis_knowledge_summarize_result_prompt"),modelTier:"default",inputVariables:r,config:a}),t=typeof i=="string"?i:i.content;return{...e,outputMessage:t,status:"success",summary:h(t),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new u(t)]}}async function O(e){let a=e.arcgisKnowledgeToolResult?.[0],o=a?.status==="success"?a.summary:"ArcGIS Knowledge Agent tool execution failed.";return{...e,outputMessage:o,status:"success",summary:h(o),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new u(o)]}}function g(e){return async(a,o)=>o?.signal?.aborted?(await c({text:"Knowledge Agent execution cancelled"},o),new f({goto:d,update:{outputMessage:"Knowledge Agent execution cancelled",summary:"Knowledge Agent execution cancelled",status:"failed"}})):await e(a,o)}var J=()=>new x(y).addNode("requireArcgisKnowledgeServices",V).addNode("agent",g($)).addNode("tools",g(F)).addNode("summarizationLLM",g(j)).addNode("finalizeToolSummary",g(O)).addEdge(w,"requireArcgisKnowledgeServices").addEdge("requireArcgisKnowledgeServices","agent").addConditionalEdges("agent",e=>(e.arcgisKnowledgeMessages[e.arcgisKnowledgeMessages.length-1]?.tool_calls?.length??0)>0?"tools":d).addConditionalEdges("tools",e=>{if(e.status==="failed")return d;let a=e.arcgisKnowledgeToolResult?.[0];return a?.status==="success"&&["applyLayout","changeNonspatialVisibility"].includes(a.toolName)?"finalizeToolSummary":"summarizationLLM"}).addEdge("summarizationLLM",d).addEdge("finalizeToolSummary",d),P=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
6
+ `)):"ArcGIS Knowledge Agent did not execute any tools or return any results.",arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,...s.messages],arcgisKnowledgeToolResult:n}}catch(s){let n=s instanceof Error?s.message:String(s);return await c({text:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`},a),{...e,outputMessage:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`,status:"failed",summary:h(`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages]}}}var V=(e,a)=>A([],"ArcgisKnowledge Agent")(e,a);async function O(e,a){let o=(e.arcgisKnowledgeToolResult??[]).map(l=>({...l,details:void 0})),{knowledgeGraph:s}=await q(a),n=S.getDataModelTypesSummary(s.dataModel),r={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,toolResult:o,dataModelSummary:n},i=await _({promptText:await m("arcgis_knowledge_summarize_result_prompt"),modelTier:"default",inputVariables:r,config:a}),t=typeof i=="string"?i:i.content;return{...e,outputMessage:t,status:"success",summary:h(t),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new u(t)]}}async function j(e){let a=e.arcgisKnowledgeToolResult?.[0],o=a?.status==="success"?a.summary:"ArcGIS Knowledge Agent tool execution failed.";return{...e,outputMessage:o,status:"success",summary:h(o),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new u(o)]}}function g(e){return async(a,o)=>o?.signal?.aborted?(await c({text:"Knowledge Agent execution cancelled"},o),new f({goto:d,update:{outputMessage:"Knowledge Agent execution cancelled",summary:"Knowledge Agent execution cancelled",status:"failed"}})):await e(a,o)}var J=()=>new x(y).addNode("requireArcgisKnowledgeServices",V).addNode("agent",g($)).addNode("tools",g(F)).addNode("summarizationLLM",g(O)).addNode("finalizeToolSummary",g(j)).addEdge(w,"requireArcgisKnowledgeServices").addEdge("requireArcgisKnowledgeServices","agent").addConditionalEdges("agent",e=>(e.arcgisKnowledgeMessages[e.arcgisKnowledgeMessages.length-1]?.tool_calls?.length??0)>0?"tools":d).addConditionalEdges("tools",e=>{if(e.status==="failed")return d;let a=e.arcgisKnowledgeToolResult?.[0];return a?.status==="success"&&["applyLayout","changeNonspatialVisibility"].includes(a.toolName)?"finalizeToolSummary":"summarizationLLM"}).addEdge("summarizationLLM",d).addEdge("finalizeToolSummary",d),P=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
7
7
  This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
8
8
  For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
9
9
  expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./3U476GCP.js";import"./FDOMMK2M.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as listLayerFieldsTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{c}from"./UZL6UVE4.js";export default $arcgis.t(([l,{property:i,subclass:y},{watch:d}])=>{var w=Object.defineProperty,g=Object.getOwnPropertyDescriptor,t=(s,a,p,o)=>{for(var r=o>1?void 0:o?g(a,p):a,h=s.length-1,n;h>=0;h--)(n=s[h])&&(r=(o?n(a,p,r):n(r))||r);return o&&r&&w(a,p,r),r},m=()=>{throw new Error("createGraph method not implemented.")},e=class extends l{constructor(){super(...arguments),this.description="",this.middlewares=[],this.createGraph=m,this.workspace=c()}initialize(){this.addHandles([d(()=>[this.name,this.description],()=>this.generate(),{initial:!0,sync:!0}),d(()=>this.createGraph,()=>this._compiledGraph=void 0)])}get id(){return this.name.replace(/\s+/gu,"-").toLowerCase()}get registration(){return{id:this.id,name:this.name,description:this.description,createGraph:this.createGraph,workspace:this.workspace}}async run(s={},a){return this.createGraph===m&&this.generate(),this._compiledGraph=this._compiledGraph??this.createGraph().compile(),await this._compiledGraph.invoke(s,a)}};t([i({readOnly:!0})],e.prototype,"id",1);t([i()],e.prototype,"name",2);t([i()],e.prototype,"description",2);t([i()],e.prototype,"middlewares",2);t([i({readOnly:!0})],e.prototype,"createGraph",2);t([i({readOnly:!0})],e.prototype,"workspace",2);t([i({readOnly:!0})],e.prototype,"registration",1);e=t([y("BaseAgent")],e);return e},"core/Accessor","core/accessorSupport/decorators","core/reactiveUtils")
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./SABZC4D4.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as goToFeaturesTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./E25RINU2.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as goToBookmarkTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import a from"./GG3AESSV.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([a])=>{return a},a)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a as f}from"./ONQ6JSBJ.js";import{Bc as o}from"./LUY6V4TP.js";import{a as l}from"./VXFQANGJ.js";var i=a=>{let r=a.map?.allLayers.filter(t=>t.type==="feature"),e=0;return r?.forEach(t=>{let s=t;s.featureEffect&&(s.featureEffect=null,e++)}),e>0?`Cleared filters from ${e} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},n=async(a,r)=>{let{mapView:e}=f(r,["mapView"]);return i(e)},h=o(n,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:l.object({})});export{h as a};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import n from"./67YCNNCN.js";import m from"./RU5DVLYG.js";import l from"./HNMFFLSY.js";import"./RATZTLNX.js";import k from"./W5FLNFSN.js";import j from"./W5J4Q3RO.js";import i from"./MKJS7QYQ.js";import h from"./ITBQGOMF.js";import g from"./CCC6LBMY.js";import"./34O57OGV.js";import{c as s,d as p}from"./V6HOUZPZ.js";import"./3U476GCP.js";import"./FDOMMK2M.js";import f from"./3MJQA533.js";import"./E25RINU2.js";import"./SABZC4D4.js";import d from"./GG3AESSV.js";import"./KZACIY2W.js";import"./XGBEHER5.js";import"./JWPB3XZM.js";import"./3UEKINYC.js";import"./RLEHNAIA.js";import c from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import"./7TO56JHS.js";import"./4YDXYW4J.js";import b from"./YGCTAIBS.js";import a from"./QNNGPA3Q.js";import"./ONQ6JSBJ.js";import{v as e,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:m},,,,,,,,,,,,,n])=>{var r=class extends e{constructor(){super(...arguments),this.agent=n}static{this.properties={referenceElement:1,serviceUrl:3,context:0}}#i;#r;#t;#e;get serviceUrl(){return this.#r}set serviceUrl(t){this.#r=t}async getContext(){let t=this.context?{...this.context,knowledgeGraph:void 0,view:void 0}:{};if(this.#i)return{...t,view:this.#i};if(this.#t)try{let i=await this.#t;return{...t,knowledgeGraph:i}}catch(i){console.error("Failed to load knowledge graph via service URL:",i)}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=m(this.serviceUrl):this.#t=void 0}load(){this.#i=p(this)??void 0,this.#e=s(this)}disconnectedCallback(){this.#e?.unregister(this.agent.id),super.disconnectedCallback()}};o("arcgis-assistant-knowledge-agent",r);return r},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",a,b,c,d,f,g,h,i,j,k,l,m,n)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import q from"./C4FKFOU4.js";import n from"./3ZPPYCNL.js";import m from"./RU5DVLYG.js";import l from"./HNMFFLSY.js";import"./RATZTLNX.js";import k from"./W5FLNFSN.js";import j from"./W5J4Q3RO.js";import h from"./MKJS7QYQ.js";import g from"./ITBQGOMF.js";import f from"./CCC6LBMY.js";import"./34O57OGV.js";import{a as o,c as p}from"./V6HOUZPZ.js";import"./3U476GCP.js";import"./FDOMMK2M.js";import e from"./3MJQA533.js";import"./E25RINU2.js";import"./SABZC4D4.js";import d from"./GG3AESSV.js";import"./KZACIY2W.js";import"./XGBEHER5.js";import"./JWPB3XZM.js";import"./3UEKINYC.js";import"./RLEHNAIA.js";import c from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import"./7TO56JHS.js";import"./4YDXYW4J.js";import b from"./YGCTAIBS.js";import a from"./QNNGPA3Q.js";import"./ONQ6JSBJ.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(([,,,,,,,,,,,,,,,,,,,,,,,,m])=>{var t=class extends i{constructor(){super(...arguments),this.agent=m}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=o(this,"arcgis-assistant-help-agent"),this.#i=p(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,e,f,g,h,j,k,l,m,n,q)
@@ -1,12 +1,12 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import d from"./3ZPPYCNL.js";import b from"./ST5FQYT7.js";import a from"./SXHH575T.js";import{a as p}from"./HJG7QM2R.js";import{Va as c,a as u,b as i}from"./TFT6HK3O.js";export default $arcgis.t(([,,,,,,{r:g},{I:d,J:E,a:h,m:f,n:y,o:m,p:x},S])=>{var _=[E],v=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:s},o)=>{let a=Array.from(s.values()).map(n=>n.name).slice(0,10).join(", "),l=s.size>10?` (and ${s.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
2
+ import d from"./3ZPPYCNL.js";import b from"./RU5DVLYG.js";import{a as h}from"./3U476GCP.js";import{a as m}from"./FDOMMK2M.js";import a from"./ZJEWP2ND.js";import{a as p}from"./HJG7QM2R.js";import{Wa as c,a as u,b as n}from"./E7KEOJZG.js";export default $arcgis.t(([,,,,,,{p:g},{a:f,c:y,d:x,e:E,v:d},S])=>{var _=[h],v=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:s},o)=>{let a=Array.from(s.values()).map(i=>i.name).slice(0,10).join(", "),l=s.size>10?` (and ${s.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
3
3
  Fields: ${a}${l}`}).join(`
4
4
 
5
5
  `);return`This map contains ${e.size} layer(s):
6
6
 
7
7
  ${t}`},w=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: ${r.agent.description}`).join(`
8
- `):"No agents currently available."};async function $(e,t){let r=await f("help_prompt"),s=m(t,"layersAndFieldsRegistry"),o=m(t,"agentRegistry");try{let a=await g({promptText:r,modelTier:"default",config:t,tools:_,inputVariables:{layerSummary:v(s),agents:w(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}});await S(a,t);let l=(a.tool_calls?.length??0)>0,n=typeof a.text=="string"?a.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:l?a:void 0},outputMessage:l?e.outputMessage:n,summary:l?"Prepared help tool call from assigned task.":"Provided map-related help based on the assigned task.",status:l?e.status:"success"}}catch(a){let l=a instanceof Error?a.message:String(a);return{...e,outputMessage:`Error invoking help agent: ${l}`,summary:"Help agent execution failed.",status:"failed"}}}var b=(e,t)=>x(["agentRegistry"],"Help Agent")(e,t);async function k(e,t){let r=new h(_,{handleToolErrors:!1});try{let s=e.helpInternalState.toolCallMessage;if(!s)throw new Error("helpToolCalling: missing helpInternalState.toolCallMessage");let o=(await r.invoke({messages:[s]},t)).messages.map(a=>a.text).join(`
9
- `);return await p({text:`Finished executing help tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?y(o):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(s){let o=s instanceof Error?s.message:String(s);return await p({text:`Help tool execution failed: ${o}`},t),{...e,outputMessage:`Help tool execution failed: ${o}`,status:"failed",summary:`Help tool execution failed: ${o}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var C=()=>new c(d).addNode("requireHelpServices",b).addNode("agent",$).addNode("tools",k).addEdge(u,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":i).addEdge("tools",i),H=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
8
+ `):"No agents currently available."};async function $(e,t){let r=await y("help_prompt"),s=m(t,"layersAndFieldsRegistry"),o=m(t,"agentRegistry");try{let a=await g({promptText:r,modelTier:"default",config:t,tools:_,inputVariables:{layerSummary:v(s),agents:w(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}});await S(a,t);let l=(a.tool_calls?.length??0)>0,i=typeof a.text=="string"?a.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:l?a:void 0},outputMessage:l?e.outputMessage:i,summary:l?"Prepared help tool call from assigned task.":"Provided map-related help based on the assigned task.",status:l?e.status:"success"}}catch(a){let l=a instanceof Error?a.message:String(a);return{...e,outputMessage:`Error invoking help agent: ${l}`,summary:"Help agent execution failed.",status:"failed"}}}var b=(e,t)=>E(["agentRegistry"],"Help Agent")(e,t);async function k(e,t){let r=new f(_,{handleToolErrors:!1});try{let s=e.helpInternalState.toolCallMessage;if(!s)throw new Error("helpToolCalling: missing helpInternalState.toolCallMessage");let o=(await r.invoke({messages:[s]},t)).messages.map(a=>a.text).join(`
9
+ `);return await p({text:`Finished executing help tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?x(o):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(s){let o=s instanceof Error?s.message:String(s);return await p({text:`Help tool execution failed: ${o}`},t),{...e,outputMessage:`Help tool execution failed: ${o}`,status:"failed",summary:`Help tool execution failed: ${o}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var C=()=>new c(d).addNode("requireHelpServices",b).addNode("agent",$).addNode("tools",k).addEdge(u,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":n).addEdge("tools",n),H=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
10
10
 
11
11
  _Example: “Tell me about this map”_
12
12
  _Example: “List all layers in this map”_
@@ -19,4 +19,4 @@ ${t}`},w=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: ${
19
19
 
20
20
  IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond that the requested action is not supported.
21
21
  _Example: "Create a chart"_
22
- _Example: "Create a table"_`,V={id:"help",name:"Help Agent",description:H,createGraph:C,workspace:d};return V},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer",a,b,d)
22
+ _Example: "Create a table"_`,J={id:"help",name:"Help Agent",description:H,createGraph:C,workspace:d};return J},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer",a,b,d)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ export default $arcgis.t(([{formatDateOnly:h,convertDateFormatToIntlOptions:m,formatTimeOnly:N,formatDate:c}])=>{var T=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),y=e=>{if(!e)return!1;let t=e.toLowerCase();return T.has(t)},f=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},S=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,w=e=>{if(typeof e=="string"&&e)return e;let t=f(e);return t?t.toISOString().slice(0,10):null},j=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",n=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),r=(Math.abs(e)%60).toString().padStart(2,"0"),i=`${t}${n}:${r}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:i}},I=(e,t,n)=>{let r=t?.toLowerCase();if(r&&!y(r))return e;if(r==="date-only"){let o=w(e);return o?h(o,m("short-date")):e}if(r==="time-only"){if(typeof e=="string"&&e)return N(e,m("long-time"));let o=f(e);return o?c(o,{...m("long-time"),timeZone:"UTC"}):e}let i=f(e);return i?c(i,{...m("short-date-short-time"),timeZone:S(n)}):e},g=(e,t,n)=>{if(e&&typeof e!="function"){let r="getField"in n&&n.getField?.(e),i=r&&"getFieldDomain"in n&&n.getFieldDomain?n.getFieldDomain(r.name):null;if(i?.type==="coded-value"){let o=i.codedValues.find(s=>s.code===t);return o?o.name:null}}return null},O=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,v=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},x=(e,t)=>{if(typeof e!="number")return e;let n={};t.minimumFractionDigits!==void 0&&(n.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(n.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?n.useGrouping=!0:t.useGrouping==="never"&&(n.useGrouping=!1);try{return new Intl.NumberFormat(void 0,n).format(e)}catch{return e}},C=(e,t,n)=>{let r=v(e);if(!r)return e;let i={};t.dateStyle?i.dateStyle=t.dateStyle:(t.year&&(i.year=t.year),t.month&&(i.month=t.month)),t.timeStyle&&(i.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?i.hour12=!0:t.timeStyle&&t.hour12==="never"&&(i.hour12=!1),i.timeZone=O(n);try{return new Intl.DateTimeFormat(void 0,i).format(r)}catch{return e}},p=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,F=(e,t,n,r,i)=>{if(n==null)return n;let o=e.getFieldConfiguration?.(t)?.fieldFormat;return o?.type==="number"?x(n,o):o?.type==="date-time"?!r||y(r)?C(n,o,i):n:I(n,r,i)},G=(e,t,n,r)=>{let i=e.fieldsIndex?.get(t),o=g(t,n,e)??n;return F(e,t,o,i?.type,r)},$=(e,t)=>p(e,t),k=(e,t,n)=>{let r=e.objectIdField,i=t.features.map(s=>s.attributes[r]),o=t.features.map(s=>{let d=s.attributes,u={};return e.fields.forEach(a=>{if(!Object.hasOwn(d,a.name))return;let l=d[a.name];if(a.name===r){u[a.name]=l;return}let D=g(a.name,l,e)??l,b=p(e,a.name);u[b]=F(e,a.name,D,a.type,n)}),u});return{objectIds:i,attributes:o}};return{a:j,b:G,c:$,d:k}},"intl")
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import c from"./3LXXSMA5.js";import"./M3MRIGDZ.js";import b from"./6QJFOL6M.js";import"./UZL6UVE4.js";import a from"./ZJEWP2ND.js";import"./HO2YDJI2.js";import"./R74ZHFA6.js";import"./HJG7QM2R.js";import"./S3XUYAUX.js";import"./WZFC5HUX.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,,a])=>{return a},a,b,c)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import b from"./5SF6DEMO.js";import a from"./6QJFOL6M.js";import{e as m}from"./UZL6UVE4.js";import"./HO2YDJI2.js";import"./E7KEOJZG.js";import"./LUY6V4TP.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([{property:n,subclass:l},{watch:w},c])=>{var d=Object.defineProperty,f=Object.getOwnPropertyDescriptor,p=(e,r,s,o)=>{for(var t=o>1?void 0:o?f(r,s):r,i=e.length-1,a;i>=0;i--)(a=e[i])&&(t=(o?a(r,s,t):a(t))||t);return o&&t&&d(r,s,t),t},h=class extends c{constructor(e){super(e)}initialize(){this.addHandles(w(()=>[this.name,this.description,this.inputSchema,this.outputSchema,this.workflow],()=>this.generate(),{initial:!0,sync:!0}))}getSchemas(){return[this.inputSchema,...this.workflow.getAgents().flatMap(e=>e.getSchemas()),this.outputSchema].filter(Boolean)}generate(){let{workspace:e,createGraph:r}=this.workflow.generate();if(this._set("workspace",e),!this.middlewares?.length)this._set("createGraph",r);else{let s=this.id,o={[s]:async(i,a)=>await r().compile().invoke(i,a)},t=[{from:s,decide:()=>{}}];this._set("createGraph",()=>m(o,t,e,{agent:this,entryNode:s,middlewares:this.middlewares}))}}};p([n()],h.prototype,"workflow",2);p([n()],h.prototype,"inputSchema",2);p([n()],h.prototype,"outputSchema",2);h=p([l("WorkflowAgent")],h);return h},"core/accessorSupport/decorators","core/reactiveUtils",a,b)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./7TO56JHS.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as clearFiltersTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a as m}from"./ONQ6JSBJ.js";import{Bc as i}from"./LUY6V4TP.js";import{Dd as e}from"./MWYBF3F3.js";async function s(o,a){let t=a.map.bookmarks;if(!t||t.length===0)throw new Error("No bookmarks found in the map.");let r=t.find(k=>k.name===o);if(!r)throw new Error(`Bookmark with name "${o}" not found.`);let n=r.viewpoint;if(!n)throw new Error(`Bookmark with name "${o}" does not have a valid viewpoint.`);return await a.goTo(n),{text:`Navigated to bookmark: ${o}`}}async function h({bookmarkName:o},a){let{mapView:t}=m(a,["mapView"]);return await Promise.resolve(s(o,t))}var w=e.object({bookmarkName:e.string().describe("The name of the bookmark to navigate to.")}),b=i(h,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:w});export{b as a};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./KZACIY2W.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as goToHomeExtentTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import b from"./YGCTAIBS.js";import a from"./QNNGPA3Q.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,a])=>{return a},a,b)
@@ -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
+ var s=(n,r)=>{let i=n?.configurable?.services?.[r];if(i==null)throw new Error(`${r} missing in config.configurable.services`);return i};export{s as a};
@@ -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,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./ONQ6JSBJ.js";import{Bc as n}from"./LUY6V4TP.js";import{Dd as e}from"./MWYBF3F3.js";export default $arcgis.t(([m])=>{async function r(t){let o=new m({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(o),{text:"Successfully zoomed to world extent"}}async function s(t,o){let{mapView:i}=a(o,["mapView"]);return await r(i)}var c=e.object({}),u=n(s,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:c});return u},"geometry/Extent")
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import b from"./W5J4Q3RO.js";import"./34O57OGV.js";import"./FDOMMK2M.js";import a from"./QNNGPA3Q.js";import"./ONQ6JSBJ.js";import"./LUY6V4TP.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,a])=>{return a},a,b)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a as c}from"./ONQ6JSBJ.js";import{Bc as n}from"./LUY6V4TP.js";import{a as e}from"./VXFQANGJ.js";export default $arcgis.t(([m])=>{async function r(t,a,o){let i={target:new m({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return o?.zoom!==void 0&&(i.zoom=o.zoom),o?.scale!==void 0&&(i.scale=o.scale),await a.goTo(i),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,o?.zoom!==void 0?`zoom ${o.zoom}`:"",o?.scale!==void 0?`scale 1:${o.scale}`:""].filter(Boolean).join(", ")}`}}async function s({center:t,zoom:a,scale:o},i){let{mapView:l}=c(i,["mapView"]);return await r(t,l,{zoom:a,scale:o})}var d=e.object({center:e.object({longitude:e.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:e.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:e.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:e.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),g=n(s,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:d});return g},"geometry/Point")
@@ -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"./SXHH575T.js";import{b as E}from"./R74ZHFA6.js";import{a as g}from"./HJG7QM2R.js";import{Va as A,a as v,b as I,ba as S,y as R}from"./TFT6HK3O.js";import{ca as b,oa as C}from"./LUY6V4TP.js";export default $arcgis.t(([N,U,H,T,_,{a:k,d:D,e:f,g:$,h:M,o: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)}
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)