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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/agent-utils/BaseAgent.d.ts +90 -0
  2. package/dist/agent-utils/BaseAgent.js +87 -0
  3. package/dist/agent-utils/FunctionAgent.d.ts +64 -0
  4. package/dist/agent-utils/FunctionAgent.js +98 -0
  5. package/dist/agent-utils/LLMAgent.d.ts +65 -0
  6. package/dist/agent-utils/LLMAgent.js +139 -0
  7. package/dist/agent-utils/WorkflowAgent.d.ts +44 -0
  8. package/dist/agent-utils/WorkflowAgent.js +70 -0
  9. package/dist/agent-utils/middlewares/humanInTheLoop.d.ts +152 -0
  10. package/dist/agent-utils/middlewares/humanInTheLoop.js +94 -0
  11. package/dist/agent-utils/middlewares/middleware.d.ts +25 -0
  12. package/dist/agent-utils/middlewares/middleware.js +44 -0
  13. package/dist/agent-utils/middlewares/trace.d.ts +25 -0
  14. package/dist/agent-utils/middlewares/trace.js +50 -0
  15. package/dist/agent-utils/middlewares/types.d.ts +123 -0
  16. package/dist/agent-utils/middlewares/types.js +2 -0
  17. package/dist/agent-utils/tools/FunctionTool.d.ts +127 -0
  18. package/dist/agent-utils/tools/FunctionTool.js +80 -0
  19. package/dist/agent-utils/types.d.ts +152 -0
  20. package/dist/agent-utils/workflows/BaseWorkflow.d.ts +87 -0
  21. package/dist/agent-utils/workflows/ConditionalWorkflow.d.ts +72 -0
  22. package/dist/agent-utils/workflows/ConditionalWorkflow.js +61 -0
  23. package/dist/agent-utils/workflows/LoopWorkflow.d.ts +58 -0
  24. package/dist/agent-utils/workflows/LoopWorkflow.js +56 -0
  25. package/dist/agent-utils/workflows/ParallelWorkflow.d.ts +68 -0
  26. package/dist/agent-utils/workflows/ParallelWorkflow.js +129 -0
  27. package/dist/agent-utils/workflows/RouterWorkflow.d.ts +63 -0
  28. package/dist/agent-utils/workflows/RouterWorkflow.js +75 -0
  29. package/dist/agent-utils/workflows/SequentialWorkflow.d.ts +56 -0
  30. package/dist/agent-utils/workflows/SequentialWorkflow.js +69 -0
  31. package/dist/agent-utils/workflows/SwitchWorkflow.d.ts +74 -0
  32. package/dist/agent-utils/workflows/SwitchWorkflow.js +84 -0
  33. package/dist/assets/embeddings.worker-k9_Ou679.js +1 -0
  34. package/dist/cdn/{RACFQ7G7.js → 7J26XD64.js} +1 -1
  35. package/dist/cdn/{RYEH3CUI.js → B3TOOMRL.js} +48 -49
  36. package/dist/cdn/DQE7BZ7J.js +42 -0
  37. package/dist/cdn/FTK7YZJ2.js +36 -0
  38. package/dist/cdn/IHFTPX4T.js +22 -0
  39. package/dist/cdn/J5NF6FQP.js +14 -0
  40. package/dist/cdn/{EJWQC2SL.js → KLIA4JYQ.js} +1 -1
  41. package/dist/cdn/N5ORE2OA.js +16 -0
  42. package/dist/cdn/UBPQG2VW.js +3 -0
  43. package/dist/cdn/WI7N36W3.js +166 -0
  44. package/dist/cdn/YOFAGUJN.js +2 -0
  45. package/dist/cdn/index.js +1 -1
  46. package/dist/chunks/BaseWorkflow.js +107 -0
  47. package/dist/chunks/adapter.js +2964 -0
  48. package/dist/chunks/arcgisKnowledgeGraph.js +174 -0
  49. package/dist/chunks/arcgis_knowledge_current_lc_context.js +8 -0
  50. package/dist/chunks/arcgis_knowledge_current_map_context.js +8 -0
  51. package/dist/chunks/arcgis_knowledge_lucene_generation_prompt.js +101 -0
  52. package/dist/chunks/arcgis_knowledge_summarize_result_prompt.js +48 -0
  53. package/dist/chunks/arcgis_knowledge_tool_prompt.js +34 -0
  54. package/dist/chunks/dataExplorationGraph.js +289 -0
  55. package/dist/chunks/data_explore_filter_prompt.js +125 -0
  56. package/dist/chunks/data_explore_query_prompt.js +131 -0
  57. package/dist/chunks/embeddings.worker.js +25 -0
  58. package/dist/chunks/field_descriptions_prompt.js +112 -0
  59. package/dist/chunks/generateLayerDescriptions.js +413 -0
  60. package/dist/chunks/graph.js +86 -0
  61. package/dist/chunks/helpGraph.js +123 -0
  62. package/dist/chunks/help_prompt.js +57 -0
  63. package/dist/chunks/intent_prompt.js +124 -0
  64. package/dist/chunks/layerStylingGraph.js +189 -0
  65. package/dist/chunks/layer_descriptions_prompt.js +59 -0
  66. package/dist/chunks/layer_styling_prompt.js +72 -0
  67. package/dist/chunks/navigationGraph.js +266 -0
  68. package/dist/chunks/navigation_intent_prompt.js +46 -0
  69. package/dist/chunks/navigation_tool_prompt.js +39 -0
  70. package/dist/chunks/orchestrator.js +528 -0
  71. package/dist/chunks/state.js +71 -0
  72. package/dist/chunks/summarize_query_response_prompt.js +77 -0
  73. package/dist/chunks/toolCallResponse.js +29 -0
  74. package/dist/chunks/utils.js +46 -40
  75. package/dist/chunks/utils2.js +41 -10
  76. package/dist/chunks/utils3.js +16 -0
  77. package/dist/components/arcgis-assistant/customElement.js +31 -23
  78. package/dist/components/arcgis-assistant/types.d.ts +1 -1
  79. package/dist/components/arcgis-assistant-agent/customElement.d.ts +1 -1
  80. package/dist/components/arcgis-assistant-agent/customElement.js +1 -1
  81. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +24 -8
  82. package/dist/components/arcgis-assistant-help-agent/customElement.js +27 -8
  83. package/dist/components/arcgis-assistant-knowledge-agent/customElement.d.ts +16 -2
  84. package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +36 -19
  85. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +27 -8
  86. package/dist/components/arcgis-assistant-message-block/customElement.d.ts +1 -1
  87. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +25 -7
  88. package/dist/docs/api.json +1 -1
  89. package/dist/docs/docs.json +1 -1
  90. package/dist/docs/web-types.json +1 -1
  91. package/dist/utils/index.d.ts +203 -9
  92. package/dist/utils/index.js +108 -10
  93. package/package.json +22 -7
  94. package/dist/cdn/F746AXM6.js +0 -2
  95. package/dist/cdn/HKVQQV3Z.js +0 -2
  96. package/dist/cdn/NWLDMNBB.js +0 -283
  97. package/dist/cdn/PGHTDGBE.js +0 -2
  98. package/dist/cdn/R5PFKR6I.js +0 -2
  99. package/dist/cdn/RTYJZ47N.js +0 -2
  100. package/dist/cdn/SHR5YB5Q.js +0 -2
  101. /package/dist/cdn/{YVTKUITE.js → 53Z3R4OY.js} +0 -0
  102. /package/dist/cdn/{CFT5BBC6.js → 77GAVZIK.js} +0 -0
  103. /package/dist/cdn/{Z7GVYVWK.js → BXKPX3C7.js} +0 -0
  104. /package/dist/cdn/{W5CHGOOR.js → G7XK3XOR.js} +0 -0
  105. /package/dist/cdn/{LSGRWCAO.js → GH7EROHP.js} +0 -0
  106. /package/dist/cdn/{DMLSCJAM.js → HJGF7W5O.js} +0 -0
  107. /package/dist/cdn/{5X5GJH2L.js → KWORBODI.js} +0 -0
  108. /package/dist/cdn/{K6LVZHWM.js → MFEAOGTZ.js} +0 -0
  109. /package/dist/cdn/{47QQSSPB.js → MLQKBQSG.js} +0 -0
  110. /package/dist/cdn/{JDL3HFFX.js → MQ7QXIOW.js} +0 -0
  111. /package/dist/cdn/{MZJGADGH.js → NMWLJECU.js} +0 -0
  112. /package/dist/cdn/{ESTSYVJP.js → ORRZDP5H.js} +0 -0
  113. /package/dist/cdn/{JKAITV5Q.js → PTKZXFXB.js} +0 -0
  114. /package/dist/cdn/{5PT7ZFXF.js → RNMI3HNM.js} +0 -0
  115. /package/dist/cdn/{7EXACS27.js → SCT3365V.js} +0 -0
  116. /package/dist/cdn/{24MYCR6F.js → URYKQKFE.js} +0 -0
  117. /package/dist/cdn/{SFREIREB.js → WTEDVMFR.js} +0 -0
@@ -0,0 +1,42 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import c from"./WI7N36W3.js";import a from"./B3TOOMRL.js";import{Fb as k,Q as x,a as y,b as l}from"./HFNOF6ZK.js";import{c as b,d as A}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as w,y as f}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,,,,{fetchKnowledgeGraph:J},{f:c,k:v,m:_},{K:u,L:K,M:S,N:M,O:G,P:T,Q:C,R:N,S:R,T:z,U:F,a:q,m:g,n:d,p:E}])=>{var L=[T,C,z,N,G,F,R];async function I(e,a){let i=await g("arcgis_knowledge_tool_prompt"),s=K(a),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:s},r=await _({promptText:i,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:L}),t=(r.tool_calls?.length??0)>0,o=typeof r.text=="string"?r.text.trim():"",h=o.length>0,p=r.content.toString();return!t&&(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:t?p:o,status:t?e.status:h?"success":"failed",summary:p?d(p):"ArcGIS Knowledge Agent tool executed."}}async function U(e,a){let i=new q(L);try{let s=await i.invoke({messages:e.arcgisKnowledgeMessages},a),n=[];for(let t of s.messages){let o;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{o=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}`)}if(!o||typeof o!="object"||!("toolName"in o))throw new Error(`Parsed tool message content does not have expected structure. Parsed content: ${JSON.stringify(o)}`);n.push(o)}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}`);return{...e,outputMessage:r.join(`
3
+ `),summary:r.length?d(r.join(`
4
+ `)):"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: ${n}`},a),{...e,outputMessage:`ArcGIS Knowledge Agent tool execution failed: ${n}`,status:"failed",summary:`ArcGIS Knowledge Agent tool execution failed: ${n}`,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages]}}}var D=(e,a)=>E([],"ArcgisKnowledge Agent")(e,a);async function j(e,a){let i=(e.arcgisKnowledgeToolResult??[]).map(h=>({...h,details:void 0})),{knowledgeGraph:s}=await S(a),n=M.getDataModelTypesSummary(s.dataModel),r={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,toolResult:i,dataModelSummary:n},t=await v({promptText:await g("arcgis_knowledge_summarize_result_prompt"),modelTier:"default",inputVariables:r}),o=typeof t=="string"?t:t.content;return{...e,outputMessage:o,status:"success",summary:d(o),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new x(o)]}}var O=()=>new k(u).addNode("requireArcgisKnowledgeServices",D).addNode("agent",I).addNode("tools",U).addNode("summarizationLLM",j).addEdge(y,"requireArcgisKnowledgeServices").addEdge("requireArcgisKnowledgeServices","agent").addConditionalEdges("agent",e=>(e.arcgisKnowledgeMessages[e.arcgisKnowledgeMessages.length-1]?.tool_calls?.length??0)>0?"tools":l).addConditionalEdges("tools",e=>e.status==="failed"?l:"summarizationLLM").addEdge("summarizationLLM",l),V=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).
5
+ 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.
6
+ 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,
7
+ 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
8
+ that exist out from specified entities and adding those to the link chart, changing whether or not nonspatial data is visible, or changing the layout of the link chart.
9
+ This agent is designed to handle requests that manipulate the specific link chart.
10
+ For knowledge graph data more generally, the agent can generate Open Cypher queries based on user prompts that represent inquiries into the data of the knowledge service and its graph database,
11
+ and can alternatively use those queries to create a new link chart visualization from the results if requested.
12
+
13
+ Supported actions:
14
+ - **Change or Apply Layout**: Changes the current layout visualization strategy of the link chart (e.g., "Change the layout to basic-grid", "Apply hierarchical layout"). Valid layout types include organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline. A best effort should be made to transform the user's request into one of these layout types.
15
+ - **Change Nonspatial Data Visibility**: Changes whether or not nonspatial data is visible on the link chart (e.g., "Show nonspatial data", "Hide nonspatial data"). Valid settings are "hidden" and "visible". A best effort should be made to transform the user's request into one of these settings.
16
+ - **Generate a cypher query**: Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance. The user should explicitly request that a cypher query be returned - if they do not, the purpose of the query is for one of the other tools or skills.
17
+ - **Create a New Link Chart from a user prompt**: Identifies that the users prompt is an inquiry into the data of the knowledge service and its graph database and creates a new link chart from the results. The user should have requested that a link chart be created or made(or similar term) from their prompt
18
+ - **Add Records (entities or relationships)**: Identifies that the users prompt is an inquiry into the data of the knowledge graph service and its graph database, and that the user wants to take the result of the inquiry and add those entities and/or relationships to the link chart. The generated query should be syntactically correct and optimized for performance.
19
+ - **Search Graph Data**: Generates and runs a lucene syntax query based on the user's prompt, returning matching entity and relationship records from the knowledge graph.
20
+ - **Query Graph Data**: Generates and executes a cypher query based on the user's prompt, and displays the results in the chat pane, allowing the user to explore the data in their knowledge graph.
21
+
22
+ _example: "Change the layout to hierarchical-bottom-to-top"_
23
+ _example: "Apply radial-root-centric layout"_
24
+ _example: "Show nonspatial data"_
25
+ _example: "Hide nonspatial data"_
26
+ _example: "Turn off nonspatial visibility"_
27
+ _example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
28
+ _example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
29
+ _example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
30
+ _example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
31
+ _example: "Find all people who work for Microsoft and put them on a new link chart"_
32
+ _example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
33
+ _example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
34
+ _example: "Find all the products supplied by Supplier X and add them to my visualization"_
35
+ _example: "Expand the link chart from 'Entity D' to show its direct connections"_
36
+ _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
37
+ _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
38
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
39
+ _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
40
+ _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
41
+ _example: "Find John Smith and all people he has made phone calls to in the last year"_
42
+ _example: "What is the average age of all people who work for Esri?"_`,$={id:"arcgisKnowledge",name:"ArcgisKnowledge Agent",description:V,createGraph:O,workspace:u};var m=class extends w{constructor(){super(...arguments),this.agent=$}static{this.properties={referenceElement:1,serviceUrl:3,context:0}}#t;#a;#e;get serviceUrl(){return this.#a}set serviceUrl(a){this.#a=a}async getContext(){let a=this.context?{...this.context,knowledgeGraph:void 0,view:void 0}:{};if(this.#t)return{...a,view:this.#t};if(this.#e)try{let i=await this.#e;return{...a,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(a){a.has("serviceUrl")&&this.serviceUrl?this.#e=J(this.serviceUrl):this.#e=void 0}load(){this.#t=A(this)??void 0,b(this)}};f("arcgis-assistant-knowledge-agent",m);return m},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","rest/knowledgeGraphService",a,c)
@@ -0,0 +1,36 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import b from"./WI7N36W3.js";import a from"./B3TOOMRL.js";import{Fb as C,a as N,b as T}from"./HFNOF6ZK.js";import{a as L,c as R}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as E,y as $}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{a:f,f:d,l:b,m:F},{a:_,b:v,c:x,d:I,e:A,f:M,g:Z,h:q,i:j,j:V,k:O,l:z,m:S,n:G,o:h,p:B}])=>{var w=[I,A,M,Z,q,j,V,O,z];async function H(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=x(t),l=r.map.bookmarks?.map(p=>p.name).filter(Boolean)??[],i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((p,W)=>`${W+1}. layerId=${p.id} | title=${p.title??""} | name=${p.name??""} | score=${p.score.toFixed(2)}`).join(`
3
+ `):"",c=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",n=e.intent==="goToBookmark"&&l.length?`Available bookmarks:
4
+ ${l.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
+ ${c}`:"",u={intent:e.intent,bookmarksSection:n,layersSection:o,fieldsSection:m,currentZoom:r.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await F({promptText:a,modelTier:"fast",inputVariables:u,tools:w}),g=(s.tool_calls?.length??0)>0,y=typeof s.text=="string"?s.text.trim():"",P=y.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:g?s:void 0},outputMessage:g?e.outputMessage:y,status:g?e.status:P?"success":"failed"}}var K=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 Q(e,t){let a=new _(w);try{let r=e.navigationInternalState.toolCallMessage;if(!r)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let{messages:l}=await a.invoke({messages:[r]},t),i="",c;for(let n of l){let o=K(n.content);o.text&&(i+=`${o.text}
8
+ `),o.sharedStatePatch&&(c={...c,...o.sharedStatePatch})}return await d({text:`Finished executing navigation tool: ${i}`},t),{...e,outputMessage:i,sharedStatePatch:c,status:"success",summary:i?G(i):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(r){let l=r instanceof Error?r.message:String(r);return await d({text:`Navigation tool execution failed: ${l}`},t),{...e,outputMessage:`Navigation tool execution failed: ${l}`,status:"failed",summary:`Navigation tool execution failed: ${l}`,navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}}async function U(e,t){let a=await S("navigation_intent_prompt"),{mapView:r}=x(t),l=w.map(s=>({name:s.name,description:s.description,schema:s.schema})),i=r.map.bookmarks?.map(s=>s.name).filter(Boolean)??[],c=i.length?`Available bookmarks:
9
+ ${i.map(s=>`- ${s}`).join(`
10
+ `)}`:"",n={tools:l.map(({name:s,description:g,schema:y})=>`${s}: ${g}, ${JSON.stringify(y)}`).join(`
11
+ `),bookmarks:c,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=f.object({intent:f.string()}),m=await b({promptText:a,inputVariables:n,schema:o,modelTier:"fast"}),u=typeof m.intent=="string"?m.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var X=.7,Y=async(e,t)=>{try{await d({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let a=h(t,"layerSearch"),r=h(t,"layersAndFieldsRegistry"),l=h(t,"embeddingCache"),i=(await a.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:X,embeddingCache:l})).map(({id:n,score:o})=>{let m=r.get(n)?.layerItem;return{id:n,title:m?.title,name:m?.name??void 0,score:o}}),c;return i.length>0?c=`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
+ `)}`:c="Vector search completed. No matching layers found.",await d({text:c},t),{...e,vectorSearchLayerResults:i}}catch(a){throw await d({text:`Error during vector search layers: ${a instanceof Error?a.message:String(a)}`},t),a}},D=.7,ee=10,te=async(e,t)=>{try{await d({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let a=h(t,"fieldSearch"),r=h(t,"layersAndFieldsRegistry"),l=h(t,"embeddingCache"),i=e.vectorSearchLayerResults?.map(o=>o.id)??[];if(i.length===0)return await d({text:"No candidate layers for field search"},t),e;let c=(await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:i,minScore:D,topResults:ee,embeddingCache:l})).map(({layerId:o,results:m})=>{let u=r.get(o)?.fieldRegistry;return{layerId:o,layerName:r.get(o)?.layerItem.name,results:m.map(s=>{let g=u?.get(s.name);return{name:s.name,score:s.score,type:g?.type,alias:g?.alias,description:g?.description,statistics:g?.statistics}})}}),n;return c.length>0?n=`Vector search completed. Matching layers and fields:
14
+ ${c.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 ${D}.`,await d({text:n},t),{...e,vectorSearchFieldResults:c}}catch(a){throw await d({text:`Error during vector search fields: ${a instanceof Error?a.message:String(a)}`},t),a}},ae=(e,t)=>B(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),oe=()=>new C(v).addNode("requireNavigationServices",ae).addNode("intentLLM",U).addNode("vectorSearchLayers",Y).addNode("vectorSearchFields",te).addNode("agent",H).addNode("tools",Q).addEdge(N,"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",T),se=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?”_`,J={id:"navigation",name:"Navigation Agent",description:se,createGraph:oe,workspace:v};var k=class extends E{constructor(){super(...arguments),this.agent=J}static{this.properties={referenceElement:1}}#e;getContext(){if(!this.#e)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#e}}load(){this.#e=L(this,"arcgis-assistant-navigation-agent"),R(this)}};$("arcgis-assistant-navigation-agent",k);return k},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b)
@@ -0,0 +1,22 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import b from"./WI7N36W3.js";import a from"./B3TOOMRL.js";import{Fb as f,a as h,b as l}from"./HFNOF6ZK.js";import{a as y,c as E}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as u,y as d}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{f:p,m:x},{I:c,J:H,a:S,m:_,n:w,o:m,p:v}])=>{var C=[H],b=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:o,fieldRegistry:a},s)=>{let r=Array.from(a.values()).map(n=>n.name).slice(0,10).join(", "),i=a.size>10?` (and ${a.size-10} more)`:"";return`${s+1}. "${o.title}". Description: ${o.description}
3
+ Fields: ${r}${i}`}).join(`
4
+
5
+ `);return`This map contains ${e.size} layer(s):
6
+
7
+ ${t}`},k=e=>{let t=e?.list()??[];return t.length?t.map(o=>`- ${o.agent.name}: ${o.agent.description}`).join(`
8
+ `):"No agents currently available."};async function I(e,t){let o=await _("help_prompt"),a=m(t,"layersAndFieldsRegistry"),s=m(t,"agentRegistry");try{let r=await x({promptText:o,modelTier:"fast",tools:C,inputVariables:{layerSummary:b(a),agents:k(s),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}}),i=(r.tool_calls?.length??0)>0,n=typeof r.text=="string"?r.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:i?r:void 0},outputMessage:i?e.outputMessage:n,summary:i?"Prepared help tool call from assigned task.":"Provided map-related help based on the assigned task.",status:i?e.status:"success"}}catch(r){let i=r instanceof Error?r.message:String(r);return{...e,outputMessage:`Error invoking help agent: ${i}`,summary:"Help agent execution failed.",status:"failed"}}}var M=(e,t)=>v(["agentRegistry"],"Help Agent")(e,t);async function T(e,t){let o=new S(C);try{let a=e.helpInternalState.toolCallMessage;if(!a)throw new Error("helpToolCalling: missing helpInternalState.toolCallMessage");let s=(await o.invoke({messages:[a]},t)).messages.map(r=>r.text).join(`
9
+ `);return await p({text:`Finished executing help tool: ${s}`},t),{...e,outputMessage:s,status:"success",summary:s?w(s):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(a){let s=a instanceof Error?a.message:String(a);return await p({text:`Help tool execution failed: ${s}`},t),{...e,outputMessage:`Help tool execution failed: ${s}`,status:"failed",summary:`Help tool execution failed: ${s}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var q=()=>new f(c).addNode("requireHelpServices",M).addNode("agent",I).addNode("tools",T).addEdge(h,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":l).addEdge("tools",l),A=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
10
+
11
+ _Example: “Tell me about this map”_
12
+ _Example: “List all layers in this map”_
13
+ _Example: “List fields in protected areas layer”_
14
+ _Example: “What agents are available to me?”_
15
+ _Example: “What can you do?”_
16
+ _Example: “What can I ask”_
17
+
18
+ Even if the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent.
19
+
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 accordingly.
21
+ _Example: "Create a chart"_
22
+ _Example: "Create a table"_`,$={id:"help",name:"Help Agent",description:A,createGraph:q,workspace:c};var g=class extends u{constructor(){super(...arguments),this.agent=$}static{this.properties={referenceElement:1}}#e;getContext(){if(!this.#e)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#e}}load(){this.#e=y(this,"arcgis-assistant-help-agent"),E(this)}};d("arcgis-assistant-help-agent",g);return g},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","views/LinkChartView","rest/knowledgeGraphService",a,b)
@@ -0,0 +1,14 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import c from"./YOFAGUJN.js";import b from"./WI7N36W3.js";import a from"./B3TOOMRL.js";import{Fb as I,a as w,b as h,q as E}from"./HFNOF6ZK.js";import{a as v,c as F}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as x,y as S}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{f:n,m:L},{A:z,B:u,a:$,m:C,o:y,p:N,q:A,r:R,s:T,t:b,u:_,v:V,w:q,x:j,y:k,z:M},D])=>{var B=.7,P=10,J=async(t,r)=>{try{await n({text:"Similarity search to find fields"},r);let e=y(r,"fieldSearch"),i=y(r,"layersAndFieldsRegistry"),o=y(r,"embeddingCache"),a=await e.searchFields({text:t.agentExecutionContext.assignedTask,layerIds:t.vectorSearchLayerIds,minScore:B,topResults:P,embeddingCache:o}),m=a.map(({layerId:c,results:d})=>{let g=d.map(s=>` - ${s.name} (${s.score.toFixed(2)})`).join(`
3
+ `);return`${i.get(c)?.layerItem.name??c}:
4
+ ${g}`}).join(`
5
+ `),l;return a.length>0?l=`Vector search completed. Matching layers and fields with scores:
6
+ ${m}`:l=`No vector search results found for score over ${B}.`,await n({text:l},r),{...t,vectorSearchFieldResults:a}}catch(e){throw await n({text:`Error during vector search: ${e instanceof Error?e.message:String(e)}`},r),new Error(`Vector search failed: ${e instanceof Error?e.message:String(e)}`)}},K=.7,U=async(t,r)=>{try{await n({text:`Similarity search to find layers: ${t.agentExecutionContext.assignedTask}`},r);let e=y(r,"layerSearch"),i=y(r,"layersAndFieldsRegistry"),o=await e.searchLayers({text:t.agentExecutionContext.assignedTask,minScore:K}),a=o.map(c=>c.id),m=o.map(({id:c,score:d})=>`${i.get(c)?.layerItem.name??c} (${d.toFixed(2)})`).join(`
7
+ `),l;return a.length>0?l=`Vector search completed. Matching layers with scores:
8
+ ${m}`:l="Vector search completed. No matching layers found.",await n({text:l},r),{...t,vectorSearchLayerIds:a}}catch(e){throw await n({text:`Error during vector search: ${e instanceof Error?e.message:String(e)}`},r),new Error(`Vector search failed: ${e instanceof Error?e.message:String(e)}`)}},G=[A,R,T,b,_,V,q,j,k,M,z],H=(t,r=3)=>{let e=t.map((o,a)=>o.type==="human"?a:-1).filter(o=>o!==-1);if(e.length===0)return[];let i=e.length>r?e[e.length-r]:e[0];return t.slice(i)},O=async(t,r)=>{await n({text:"Requesting LLM for layer query results"},r);let e=await C("navigation_intent_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let i={layerFieldInfo:t.layerFieldInfo},o=await L({promptText:e,modelTier:"advanced",messages:H(t.agentExecutionContext.messages),inputVariables:i,tools:G});return await D(o,r),{...t,agentExecutionContext:{...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages,o]}}};async function Q(t,r){let e=await new $(G).invoke({messages:H(t.agentExecutionContext.messages)},r),i=e.messages.map(a=>a.text).join(`
9
+ `);await n({text:`Finished executing layer filter tool: ${i}`},r);let o=e.messages.map(a=>a.text).join(`
10
+ `);return{...t,outputMessage:o}}var W=async(t,r)=>(await n({text:"Exiting Layer Styling agent"},r),t),X=async(t,r)=>{try{await n({text:"Populating layer and field info"},r);let e=[];for(let i of t.vectorSearchFieldResults){let o=function(g){let s=l.get(g)?.layerItem;return s?[s.name&&`Name: ${s.name}`,s.title&&`Title: ${s.title}`,s.description&&`Description: ${s.description}`].filter(Boolean).join(" | "):g},{layerId:a,results:m}=i,l=y(r,"layersAndFieldsRegistry"),c=l.get(a)?.fieldRegistry;if(!c)continue;let d=e.find(g=>g.layerId===a);d||(d={layerId:a,layerSummary:o(a),fieldInfos:[]},e.push(d));for(let g of m){let s=c.get(g.name);s&&d.fieldInfos.push(s)}}return await n({text:"Populated layerFieldInfo"},r),{...t,layerFieldInfo:e}}catch(e){throw await n({text:"Error populating layerFieldInfo"},r),new Error(`Error populating layerFieldInfo: ${e instanceof Error?e.message:String(e)}`)}},Y=(t,r)=>{let e=t.vectorSearchLayerIds??[];if(e.length<=1)return{...t,selectedLayerId:t.vectorSearchLayerIds[0]};let{hitlResponse:i}=r.configurable;if(i?.agentId!==p.id||i.id!=="reviewLayerSelection"){let a={agentId:p.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...e]};throw new E(a)}let o=null;return Array.isArray(i.payload)&&i.payload.length>0&&(o=i.payload[0]),{...t,selectedLayerId:o??t.vectorSearchLayerIds[0]}},Z=(t,r)=>N(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(t,r),ee=()=>new I(u).addNode("requireLayerStylingServices",Z).addNode("vectorSearchLayers",U).addNode("layerSelectionHITL",Y).addNode("vectorSearchFields",J).addNode("populateLayerFieldInfo",X).addNode("agent",O).addNode("tools",Q).addNode("earlyExit",W).addEdge(w,"requireLayerStylingServices").addEdge("requireLayerStylingServices","vectorSearchLayers").addConditionalEdges("layerSelectionHITL",t=>t.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",t=>t.vectorSearchFieldResults.length?"populateLayerFieldInfo":"earlyExit").addEdge("populateLayerFieldInfo","agent").addEdge("agent","tools").addEdge("tools",h).addEdge("earlyExit",h),te=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
11
+ _Example: “Color points by sales amount”_
12
+ _Example: “Show population density with a color gradient”_
13
+ _Example: “Create a relationship map between height and depth”_
14
+ _Example: “Vary circle sizes according to population”_`,p={id:"layerStyling",name:"Layer Styling Agent",description:te,createGraph:ee,workspace:u};var f=class extends x{constructor(){super(...arguments),this.agent=p}static{this.properties={referenceElement:1}}#e;getContext(){if(!this.#e)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#e}}load(){this.#e=v(this,"arcgis-assistant-layer-styling-agent"),F(this)}};S("arcgis-assistant-layer-styling-agent",f);return f},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","views/LinkChartView","rest/knowledgeGraphService",a,b,c)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{a as s,b as i}from"./47QQSSPB.js";import{b as r}from"./YGW7TUNX.js";function c(e,n){let t=s(e.el,e.referenceElement);if(t)return t;let o=r(e.el,"arcgis-assistant"),a=s(e.el,o?.referenceElement);if(a)return a;throw new Error(`${n}: Reference element not found`)}function g(e,n){let t=c(e,n).view;if(!t)throw new Error(`${n}: Reference element does not have a view`);return t}function m(e){return typeof e=="function"}function w(e){let n=r(e.el,"arcgis-assistant");if(n===void 0)throw new Error("arcgis-assistant-agent must be used within an arcgis-assistant element");n.register({agent:e.agent,getContext:async()=>await e.getContext?.()??e.context??{}})}function f(e){let n=i(e.el,e.referenceElement);if(n)return n;let t=r(e.el,"arcgis-assistant");return s(e.el,t?.referenceElement)||null}function E(e){let n=f(e);return n?n.view:null}export{g as a,m as b,w as c,E as d};
2
+ import{a as s,b as i}from"./MLQKBQSG.js";import{b as r}from"./YGW7TUNX.js";function c(e,n){let t=s(e.el,e.referenceElement);if(t)return t;let o=r(e.el,"arcgis-assistant"),a=s(e.el,o?.referenceElement);if(a)return a;throw new Error(`${n}: Reference element not found`)}function g(e,n){let t=c(e,n).view;if(!t)throw new Error(`${n}: Reference element does not have a view`);return t}function m(e){return typeof e=="function"}function w(e){let n=r(e.el,"arcgis-assistant");if(n===void 0)throw new Error("arcgis-assistant-agent must be used within an arcgis-assistant element");n.register({agent:e.agent,getContext:async()=>await e.getContext?.()??e.context??{}})}function f(e){let n=i(e.el,e.referenceElement);if(n)return n;let t=r(e.el,"arcgis-assistant");return s(e.el,t?.referenceElement)||null}function E(e){let n=f(e);return n?n.view:null}export{g as a,m as b,w as c,E as d};
@@ -0,0 +1,16 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import d from"./YOFAGUJN.js";import c from"./WI7N36W3.js";import a from"./B3TOOMRL.js";import{Fb as N,Q as k,a as V,b as E}from"./HFNOF6ZK.js";import{a as D,c as O}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as b,y as A}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,K,X,,,{f:o,k:z,m:T},{C:R,D:G,E:F,F:P,G:L,H:U,a:j,m:w,n:M,o:p,p:Q},I])=>{var Y=async(e,t)=>(await o({text:"Exiting Data Exploration agent"},t),e),Z=async(e,t)=>{await o({text:"Requesting LLM for layer filter results"},t);let a=await w("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:d,userTimezoneOffset:n}=F(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:n,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await T({promptText:a,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:i,tools:L}),r=[...e.dataExplorationMessages,s];if(!((s.tool_calls?.length??0)>0))return await o({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:r};let u=[...r,s],c=s.content.toString();return await I(s,t),{...e,dataExplorationMessages:u,outputMessage:c}},ee=async(e,t)=>{await o({text:"Requesting LLM for layer query results"},t);let a=await w("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:d,userTimezoneOffset:n}=F(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:n,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await T({promptText:a,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:i,tools:P}),r=s.content.toString();return await I(s,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,s],outputMessage:r,status:"success",summary:r?M(r):"Query executed."}},te=async(e,t)=>{try{await o({text:"Requesting LLM for summary on query results"},t);let a=await w("summarize_query_response_prompt"),d={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},n=await z({promptText:a,modelTier:"fast",messages:e.dataExplorationMessages,inputVariables:d}),i=typeof n=="string"?n:n.content,s=new k(i);await o({text:`Received response from LLM: ${i}`},t);let r=i;return{...e,outputMessage:r,status:"success",summary:r?M(r):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,s]}}catch(a){throw await o({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${a instanceof Error?a.message:String(a)}`)}};async function ae(e,t){let a=await new j(L).invoke({messages:e.dataExplorationMessages},t);return await o({text:`Finished executing layer filter tool: ${a.messages.map(d=>d.content).join(", ")}`},t),{...e}}var se=10,re=["string","small-integer","integer"],ie=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:d=!0}={})=>{let n=null,i=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(n=await K({layer:e,field:t.name}));let s=t.domain?.type==="coded-value"?t.domain:null;d&&(re.includes(t.type)||s)&&(i=(await X({layer:e,field:t.name})).uniqueValueInfos.sort((r,u)=>u.count-r.count).slice(0,se),s&&(i=i.map(r=>({...r,value:s.getName(r.value)??r.value}))))}}catch(s){console.error(`Error fetching statistics for field ${t.name}:`,s)}return{summaryStatistics:n,uniqueValues:i}};function oe(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function ne(e,t,a,d=!0){let n=[],i=[],s=[];for(let r of e){let u=function(g){let l=t.get(g)?.layerItem;return l?[l.name&&`Name: ${l.name}`,l.title&&`Title: ${l.title}`,l.description&&`Description: ${l.description}`].filter(Boolean).join(" | "):g},{layerId:c,results:m}=r,f=a.map?.allLayers.find(g=>g.id===c),S=t.get(c)?.fieldRegistry;if(!S)continue;let h=n.find(g=>g.layerId===c);h||(h={layerId:c,layerSummary:u(c),fieldInfos:[]},n.push(h));for(let g of m){let l=S.get(g.name);if(!l)continue;let y=l.statistics,v=d&&!y?.summaryStatistics,q=oe(l.type,l.domain?.type)&&!y?.uniqueValues,$=v||q;if(s.push({layerId:c,fieldName:l.name,didFetchStatistics:$}),$){let J=ie(f,l,{includeSummaryStatistics:v,includeUniqueValues:q}).then(C=>{let x={summaryStatistics:y?.summaryStatistics??null,uniqueValues:y?.uniqueValues??null};v&&(x.summaryStatistics=C.summaryStatistics),q&&(x.uniqueValues=C.uniqueValues),S.set(l.name,{...l,statistics:x}),l.statistics=x});i.push(J)}h.fieldInfos.push(l)}}return await Promise.all(i),{layerFieldInfo:n,didFetchStatistics:i.length>0,fieldStatisticsFetchStatus:s}}var W=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function le(e,t){return W.test(e)||W.test(t)}var de=async(e,t)=>{try{await o({text:"Preparing field information for vector search results"},t);let a=p(t,"layersAndFieldsRegistry"),{mapView:d}=G(t),{assignedTask:n,userRequest:i}=e.agentExecutionContext,s=le(n,i),{layerFieldInfo:r,didFetchStatistics:u,fieldStatisticsFetchStatus:c}=await ne(e.vectorSearchFieldResults,a,d,s);u?await o({text:"Statistics fetched"},t):await o({text:"Statistics skipped"},t);for(let m of c)await o({text:` - ${m.fieldName} - stats ${m.didFetchStatistics?"fetched":"skipped"}`},t);return await o({text:"Field information prepared"},t),{...e,layerFieldInfo:r}}catch(a){throw await o({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${a instanceof Error?a.message:String(a)}`)}},B=.7,ce=10,ue=async(e,t)=>{try{await o({text:"Similarity search to find fields"},t);let a=p(t,"fieldSearch"),d=p(t,"layersAndFieldsRegistry"),n=p(t,"embeddingCache"),i=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:B,topResults:ce,embeddingCache:n}),s=i.map(({layerId:u,results:c})=>{let m=c.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
3
+ `);return`${d.get(u)?.layerItem.name??u}:
4
+ ${m}`}).join(`
5
+ `),r;return i.length>0?r=`Vector search completed. Matching layers and fields with scores:
6
+ ${s}`:r=`No vector search results found for score over ${B}.`,await o({text:r},t),{...e,vectorSearchFieldResults:i}}catch(a){throw await o({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},me=.7,ge=async(e,t)=>{try{await o({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let a=p(t,"layerSearch"),d=p(t,"layersAndFieldsRegistry"),n=p(t,"embeddingCache"),i=await a.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:me,embeddingCache:n}),s=i.map(c=>c.id),r=i.map(({id:c,score:m})=>`${d.get(c)?.layerItem.name??c} (${m.toFixed(2)})`).join(`
7
+ `),u;return s.length>0?u=`Vector search completed. Matching layers with scores:
8
+ ${r}`:u="Vector search completed. No matching layers found.",await o({text:u},t),{...e,vectorSearchLayerIds:s}}catch(a){throw await o({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},pe=(e,t)=>Q(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),fe=()=>new N(R).addNode("requireDataExplorationServices",pe).addNode("vectorSearchLayers",ge).addNode("vectorSearchFields",ue).addNode("fieldStatistics",de).addNode("queryAgent",ee).addNode("queryTools",U).addNode("summarizeQueryResponseLLM",te).addNode("filterAgent",Z).addNode("filterTools",ae).addNode("earlyExit",Y).addEdge(V,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),he=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
9
+ The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
10
+ _Example: “Only show stations where Brand is Shell”_
11
+ _Example: “Make Shell stations stand out on the map”_
12
+ _Example: “Gray out all stations that aren’t Shell”_
13
+ This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
14
+ _Example: “How many features are there?”_
15
+ _Example: “What’s the average population?”_
16
+ _Example: “Which values are in the status field?”_`,H={id:"dataExploration",name:"Data Exploration Agent",description:he,createGraph:fe,workspace:R};var _=class extends b{constructor(){super(...arguments),this.agent=H}static{this.properties={referenceElement:1}}#e;getContext(){if(!this.#e)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#e}}load(){this.#e=D(this,"arcgis-assistant-data-exploration-agent"),O(this)}};A("arcgis-assistant-data-exploration-agent",_);return _},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,c,d)
@@ -0,0 +1,3 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import{a as S,b as I}from"./EUNEQNYC.js";import{a as M}from"./XLFCW5OF.js";import"./M56MGI7M.js";import a from"./B3TOOMRL.js";import{Fb as j,Q as q,W as F,a as P,b as D,eb as O,u as W}from"./HFNOF6ZK.js";import{a as U}from"./MLQKBQSG.js";import"./YGW7TUNX.js";import{g as C,h as g,l as R,n as h,t as b,u as v,v as L,w as f,y as A}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([Ie,{whenOnce:_e,watch:ke,when:$e},Ce,Y,ee,J,te,se,,,Re,{property:y,subclass:Le},{b:H,e:N,f:m,h:z,i:V,j:T}])=>{var re=async t=>{let e=await ie(),s=await H("default"),i=ee.getDefault(),r=(await Y.getCredential(`${i.url}/sharing`)).token,a={type:"generateEmbeddings",webmapEmbeddings:t,auth:{apiUrl:s,token:r}};return e.postMessage(a),await new Promise((n,c)=>{let o=l=>{l.data==="completed"&&(e.removeEventListener("message",o),n())},d=l=>{e.removeEventListener("message",o),c(l instanceof Error?l:new Error("Embeddings worker error"))};e.addEventListener("message",o),e.addEventListener("error",d,{once:!0})}),e},ie=async()=>{{let t=(await import("./URYKQKFE.js")).default;return new t}},ae=t=>{t.currentIntent="none"},ne=async(t,e)=>{if(t.agentExecutionContext.userRequest){let i=new F(t.agentExecutionContext.userRequest.trim());t.agentExecutionContext.messages=[...t.agentExecutionContext.messages,i],ae(t)}let s=e?.configurable?.services.agentRegistry.list().map(i=>i.agent.id)??[];return await m({text:`Available agents: ${[...s].join(", ")}`},e),await m({text:"Analyzing user input"},e),t},oe=async(t,e)=>(await m({text:"Exiting..."},e),t),B=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ce=(t,e)=>{if(!B(t)){t!==void 0&&console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);return}let s={};for(let[i,r]of Object.entries(t)){if(!B(r)||!("value"in r)){console.warn(`Agent "${e}" returned invalid sharedStatePatch entry for key "${i}". Ignoring that entry.`);continue}s[i]={value:r.value}}return s},de=t=>{let{previousSharedState:e,patch:s,agentId:i}=t;if(!s)return e;let r=Date.now(),a={...e};for(let[n,c]of Object.entries(s))c?.value!==void 0&&(a[n]={value:c.value,meta:{updatedByAgentId:i,updatedAt:r}});return a},G=t=>typeof t!="string"?void 0:t.trim()||void 0,le=t=>{switch(t){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."}},ge=(t,e)=>{let s=G(e?.outputMessage),i=G(e?.summary),r=e?.status,a=r==="success"||r==="failed"?r:"unknown";a==="unknown"&&console.warn(`Agent "${t}" returned missing/invalid status. Defaulting to "unknown".`);let n=ce(e?.sharedStatePatch,t);return{outputMessage:s,summary:i??s??le(a),status:a,sharedStatePatch:n}},Q=4e3,he=async(t,e)=>{let s=e?.configurable,{agentRegistry:i}=s.services,r=i?.get(t.currentIntent);if(!r)return console.warn(`No agent found for intent: ${t.currentIntent}`),t;await m({text:`Executing registered agent: ${r.agent.name}`},e);let a={...e??{},configurable:{...s??{},agentId:r.agent.id,context:r.getContext?await r.getContext():void 0}},n;try{let d=await r.agent.createGraph().compile().invoke({agentExecutionContext:{...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages],priorSteps:structuredClone(t.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(t.agentExecutionContext.sharedState??{})}},a);n=ge(r.agent.name,d),await m({text:`Finished executing registered agent: ${r.agent.name}`},e)}catch(d){if(W(d))throw d;let l=d instanceof Error?d.message:String(d);console.error(`Agent "${r.agent.name}" failed:`,d),await m({text:`Registered agent failed: ${r.agent.name}. ${l}`},e),n={status:"failed",outputMessage:`Agent execution failed: ${l}`,summary:`Agent execution failed: ${l}`}}let c=n.outputMessage,o=[...t.agentExecutionContext.messages];if(c){let d=c.length>Q?`${c.slice(0,Q-14)}
3
+ [truncated]`:c;o.push(new q(d))}return{...t,stepCount:t.stepCount+1,lastExecutedAgent:r.agent.id,requiresFollowUp:n.status==="failed"?!0:t.requiresFollowUp,finalOutputMessage:c??"",agentExecutionContext:{...t.agentExecutionContext,messages:o,priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:r.agent.id,assignedTask:t.agentExecutionContext.assignedTask,summary:n?.summary||"No summary provided.",status:n?.status||"unknown"}],sharedState:de({previousSharedState:t.agentExecutionContext.sharedState,patch:n.sharedStatePatch,agentId:r.agent.id})}}},ue=3,pe=()=>new j(N).addNode("ingestInput",ne).addNode("intentLLM",V).addNode("executeRegisteredAgent",he).addNode("exit",oe).addEdge(P,"ingestInput").addEdge("ingestInput","intentLLM").addConditionalEdges("intentLLM",t=>t.currentIntent==="none"||t.currentIntent===t.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",t=>t.stepCount>=ue||!t.requiresFollowUp?"exit":"intentLLM").addEdge("exit",D),_=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:s}=e;if(this.agentRegistry.has(s.id))throw new Error(`Duplicate agent id: ${s.id}`);this.agentRegistry.set(s.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},k=class{constructor(e,s){this.graph=e,this.config={...s}}async waitForUser(){return await new Promise((e,s)=>{this.resolveWait=e,this.rejectWait=s})}handle(e,s){try{let i={agentId:e.agentId,id:e.id,payload:s},r=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:i},subgraphs:!0,version:"v2"});this.resolveWait?.(r)}catch(i){this.rejectWait?.(i)}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)}},me=async t=>{try{return await(await z()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}},K=async(t,e)=>{let s=e.get(t);if(s)return s;let i=await me([t]);return e.set(t,i[0]),i[0]};async function ye(t,e,s,i){let r=`req-${Date.now()}`,a={type:"layerSearch",precomputedEmbedding:i?await K(t,i):void 0,requestId:r,minScore:s};return await new Promise(n=>{let c=o=>{o.data.requestId===r&&n(o.data.results)};e.addEventListener("message",c,{once:!0}),e.postMessage(a)})}function we(t){let{worker:e}=t;return{async searchLayers({text:s,minScore:i,embeddingCache:r}){return await ye(s,e,i,r)}}}var fe=async({combinedQuery:t,layerIds:e,embeddingsWorker:s,minScore:i,topResults:r,embeddingCache:a})=>{let n=`req-${Date.now()}`,c=a?await K(t,a):void 0,o={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:c,requestId:n,minScore:i,topResults:r};return await new Promise(d=>{let l=w=>{if(w.data.requestId!==n)return;let x=w.data.results.map(({layerId:Z,results:X})=>({layerId:Z,results:X}));d(x)};s.addEventListener("message",l,{once:!0}),s.postMessage(o)})};function be(t){let{worker:e}=t;return{async searchFields({text:s,layerIds:i,minScore:r,topResults:a,embeddingCache:n}){return await fe({combinedQuery:s,layerIds:i,embeddingsWorker:e,minScore:r,topResults:a,embeddingCache:n})}}}var ve=t=>{let e=T.safeParse(t);if(!e.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return e.data},Ee=(t,e)=>{let s=new Map,i=new Map;if(e.allLayers.forEach(r=>{r instanceof te&&i.set(r.id,r)}),t.length!==i.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let r of t){let a=i.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 n={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})}s.set(r.id,{layerItem:n,fieldRegistry:c})}return s},xe=async t=>{try{return(await se(t,{responseType:"json"})).data}catch(e){throw new Error(`Failed to fetch data from ${t}: ${String(e)}`)}},Se=async t=>{let e=t.map;if(!e?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:s}=await e.portalItem.fetchResources(),i=s.find(a=>a.resource.path==="embeddings-v01.json");if(!i?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let r=await xe(i.resource.url);return ve(r)},E=class t{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.threadId="",this.agentRegistry=new _,this.streamEpoch=0}static async init(e){let s=new t;try{if(e.view?.map){await J.whenOnce(()=>e.view.ready);let i=await Se(e.view),r=Ee(i.layers,e.view.map);s.layersAndFieldsRegistry=r,s.embeddingsWorker=await re(i)}return e.agents?.forEach(i=>{s.agentRegistry.register(i)}),s.orchestratorReady=!0,s}catch(i){throw console.error("Orchestrator initialization failed:",i),i}}async*ask(e){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!e.trim())return;this.threadId=String(Date.now()),this.graph||(this.graph=pe().compile({checkpointer:new O}));let s=this.embeddingsWorker?we({worker:this.embeddingsWorker}):void 0,i=this.embeddingsWorker?be({worker:this.embeddingsWorker}):void 0,r=new Map,a={version:"v2",streamMode:"custom",configurable:{thread_id:this.threadId,hitlResponse:null,services:{layerSearch:s,fieldSearch:i,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:r}},subgraphs:!0},n=this.graph?.streamEvents({agentExecutionContext:{userRequest:e,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},a),c=++this.streamEpoch;for(yield*this.pipeStream(n,c);;){let d=(await this.graph.getState(a,{subgraphs:!0})).tasks.find(l=>l.interrupts.length>0)?.interrupts[0]?.value;if(!d)break;this.currentInterrupt=d,this.interruptHandler=new k(this.graph,a),yield{runId:this.threadId,timestamp:Date.now(),type:"interrupt",interrupt:d};try{let l=await this.interruptHandler.waitForUser(),w=++this.streamEpoch;yield*this.pipeStream(l,w)}catch(l){if(l){yield{runId:this.threadId,timestamp:Date.now(),type:"error",error:{message:l?.message}};return}yield{runId:this.threadId,timestamp:Date.now(),type:"cancelled"};return}}let o=(await this.graph.getState(a,{subgraphs:!0})).values;this.chatHistory=o.agentExecutionContext.messages.length?o.agentExecutionContext.messages:this.chatHistory,this.priorSteps=o.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=o.agentExecutionContext.sharedState??{},yield{runId:this.threadId,timestamp:Date.now(),type:"completed",result:{content:o.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}resumeInterrupt(e){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,e)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}async*pipeStream(e,s){for await(let i of e){if(s!==this.streamEpoch){console.log("Stale stream detected, aborting.");break}i.event==="on_custom_event"&&i.name==="trace_message"?yield{runId:this.threadId,timestamp:Date.now(),type:"trace",data:i.data}:i.name==="graph_ux_suggestion"&&(yield{runId:this.threadId,timestamp:Date.now(),type:"ux-suggestion",suggestion:i.data})}}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};var Ae=C`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%)}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}`,Me=Object.defineProperty,Pe=Object.getOwnPropertyDescriptor,p=(t,e,s,i)=>{for(var r=i>1?void 0:i?Pe(e,s):e,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Me(e,s,r),r},u=class extends Re{constructor(t){super(t),this.view=null,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await _e(()=>!this.view.updating),this._set("orchestrator",await E.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([ke(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(t,e){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let s=[],i;try{let r=this.orchestrator.ask(t);for await(let a of r){let n=a.runId;if(e?.aborted){yield{type:"cancelled",runId:n};break}switch(a.type){case"trace":{this._set("processingStep",a.data.text),s.push(a.data.text);break}case"completed":{let c=a.result,o=!!c.content.length,d=!!i?.length;if(!o&&!d){yield{type:"completed",error:"Could not process the request.",log:s,runId:n};return}let l=c.content;this._set("processingStep",""),yield{type:"completed",response:l,blocks:i,log:s,runId:n};return}case"ux-suggestion":{let c=a.suggestion;i=i?[...i,c]:[c];break}case"interrupt":{let{kind:c,message:o,metadata:d}=a.interrupt,l=Array.isArray(d)?d.filter(x=>typeof x=="string"):[],w=(()=>{switch(c){case"booleanChoice":return{type:"boolean-choice",message:o,options:l};case"singleSelection":return{type:"single-select",message:o,options:l};case"multipleSelection":return{type:"multi-select",message:o,options:l};case"textInput":return{type:"text-input",message:o};default:return{type:c,message:o,options:l}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:w,runId:n};break}case"cancelled":{yield{type:"cancelled",runId:n};return}case"error":{yield{type:"completed",error:a.error.message,log:s,runId:n};return}default:{console.warn("Unknown event type:",a);break}}}}catch(r){console.warn("Error during message processing:",r),yield{type:"completed",error:"An error occurred during message processing.",log:s,runId:"error"};return}finally{this._set("processing",!1)}}};p([y({readOnly:!0})],u.prototype,"orchestrator",2);p([y()],u.prototype,"agents",2);p([y()],u.prototype,"portal",2);p([y()],u.prototype,"view",2);p([y({readOnly:!0})],u.prototype,"loading",2);p([y({readOnly:!0})],u.prototype,"processing",2);p([y({readOnly:!0})],u.prototype,"processingStep",2);u=p([Le("OrchestratorController")],u);var De="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",We="Embeddings not found for this web map.",qe="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",$=class extends L{constructor(){super(...arguments),this._messages=M({blocking:!0}),this.#e=b(),this.#n=b(),this.#t=b(),this.#s=null,this.#o=new Map,this.#r=Ce.getDefault(),this.#i=e=>{e.stopPropagation(),this.cancelInterrupt()},this.#a=e=>{e.stopPropagation();let s=e.detail;this.submitInterrupt(s)},this.#c=e=>{e.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let s=e.detail;this._inputValue="",this.arcgisSubmit.emit(s),this.submitMessage(s)},this.#d=e=>{if(e.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this.#s?.abort()},this.#l=e=>{e.stopPropagation();let s=e.detail;this.arcgisFeedback.emit(s)},this.#g=e=>{e.stopPropagation();let s=e.detail;this._inputValue=s.prompt,this.arcgisPromptSelect.emit(s)},this.#h=e=>{this.arcgisSlottableRequest.emit(e.detail)},this._orchestratorController=null,this._interrupt=null,this._error=null,this._inputValue="",this.messages=new Ie([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.arcgisCancel=h(),this.arcgisError=h(),this.arcgisFeedback=h(),this.arcgisInterrupt=h(),this.arcgisInterruptCancel=h(),this.arcgisInterruptSubmit=h(),this.arcgisPromptSelect=h(),this.arcgisReady=h(),this.arcgisSubmit=h(),this.arcgisSlottableRequest=h({bubbles:!1,composed:!1})}static{this.properties={_orchestratorController:16,_interrupt:16,_error:16,_inputValue:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5}}static{this.styles=Ae}#e;#n;#t;#s;#o;#r;#i;#a;#c;#d;#l;#g;#h;async#u(){try{let e=U(this.el,this.referenceElement);await e?.componentOnReady();let s=[...this.#o.values()];return s.length?(this._orchestratorController=new u({agents:s,portal:this.#r,view:e?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(e){return this._error=e?.message??"Error initializing orchestrator.",R(this)(e),!1}}get _user(){return this.#r?.user?.fullName||this.#r?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(e){this.#o.set(e.agent.id,e)}async submitMessage(e){let s=e.trim();if(!s||(this.messages.push({id:Date.now().toString(),role:"user",content:s}),!this._orchestratorController))return;let i=this._orchestratorController.ask(s,this.#s?.signal);for await(let r of i){let a=r.runId;switch(r.type){case"completed":this.messages.push({role:"assistant",content:r.response,blocks:r.blocks,log:r.log,error:r.error,id:a});break;case"interrupt":this._interrupt={...r.payload,id:a},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":this.messages.push({role:"assistant",error:"Request cancelled.",id:a});break}}}submitInterrupt(e){this.arcgisInterruptSubmit.emit(e),this.orchestrator?.resumeInterrupt(e),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#e.value?.addEventListener("arcgisPromptSelect",this.#g),this.#e.value?.addEventListener("arcgisSubmit",this.#c),this.#e.value?.addEventListener("arcgisCancel",this.#d),this.#e.value?.addEventListener("arcgisFeedback",this.#l);let e=$e(()=>!!this._interrupt&&!!this.#t.value,()=>{let s=this.#t.value;s.removeEventListener("arcgisSubmit",this.#a),s.removeEventListener("arcgisCancel",this.#i),s.addEventListener("arcgisSubmit",this.#a,{once:!0}),s.addEventListener("arcgisCancel",this.#i,{once:!0})});return queueMicrotask(()=>{this.#u().then(s=>{s?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{e.remove(),this.#e.value?.removeEventListener("arcgisPromptSelect",this.#g),this.#t.value?.removeEventListener("arcgisSubmit",this.#a),this.#t.value?.removeEventListener("arcgisCancel",this.#i),this.#e.value?.removeEventListener("arcgisSubmit",this.#c),this.#e.value?.removeEventListener("arcgisCancel",this.#d),this.#e.value?.removeEventListener("arcgisFeedback",this.#l),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this.#s?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue=""}_renderEntryMessage(){return this._interrupt?g`<slot name=interrupt><arcgis-assistant-interrupt .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${v(this.#t)}></arcgis-assistant-interrupt></slot>`:this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:g`<calcite-notice open kind=info closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:g`<slot name=entry-message></slot>`}_renderErrorNotice(){return this._error?g`<calcite-notice closable slot=entry-message open kind=danger icon width=full>${this._error===De?g`<div slot=message>${We}</div><calcite-link slot=link .href=${qe} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:g`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}_renderSuggestedPrompts(){return this.suggestedPrompts?.length?g`<div class="suggested-prompts-container"><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}render(){return g`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${v(this.#e)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(e=>e.role==="assistant"?g`<arcgis-assistant-message .message=${e} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#h}><slot name=${S(e.id)??f} slot=${S(e.id)??f}>${e?.error?g`<calcite-notice class="error-notice" open icon kind=warning width=full><div slot=message>${e.error}</div></calcite-notice>`:g`<arcgis-assistant-message-text .content=${e?.content}></arcgis-assistant-message-text>`}</slot>${e.blocks?.map((s,i)=>g`<slot name=${I(e.id,i)??f} slot=${I(e.id,i)??f}><arcgis-assistant-message-block .block=${s}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:g`<arcgis-assistant-user-message .message=${e} .user=${this._user}></arcgis-assistant-user-message>`)}</slot><slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep}></arcgis-assistant-message-loading></slot></arcgis-assistant-chat></div>${this._renderSuggestedPrompts()}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} ${v(this.#n)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse?"circle-stop":"send"} @click=${()=>{this.#n.value?.submitMessage()}} round>${this.awaitingResponse?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};A("arcgis-assistant",$);return $},"core/Collection","core/reactiveUtils","portal/Portal","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","layers/FeatureLayer","core/Accessor","core/accessorSupport/decorators",a)