@arcgis/ai-components 5.1.0-next.14 → 5.1.0-next.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./BDLIIICB.js";import b from"./5XHJVBOQ.js";import{a as s,b as a}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as e,z as r}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{d:i}])=>{var t=class extends e{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-query-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-layer-query-agent"),a(this)}};r("arcgis-assistant-layer-query-agent",t);return t},b,c)
2
+ import c from"./BWML3XTP.js";import b from"./Z43QFN6Z.js";import{a as s,b as a}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as e,z as r}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{d:i}])=>{var t=class extends e{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-query-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-layer-query-agent"),a(this)}};r("arcgis-assistant-layer-query-agent",t);return t},b,c)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import b from"./BDLIIICB.js";import a from"./5XHJVBOQ.js";import{a as r,b as i}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as s,z as e}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{f:a}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-help-agent"),i(this)}};e("arcgis-assistant-help-agent",t);return t},a,b)
2
+ import b from"./BWML3XTP.js";import a from"./Z43QFN6Z.js";import{a as r,b as i}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as s,z as e}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{f:a}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-help-agent"),i(this)}};e("arcgis-assistant-help-agent",t);return t},a,b)
@@ -15,11 +15,19 @@ Also consider any **relevant context from the chat history**, such as user quest
15
15
 
16
16
  3. The response can be per layer, or summarize based on the question.
17
17
 
18
- 4. When the user asks "where" a feature is located: Simply confirm whether the feature was found and in which layer. DO NOT attempt to provide coordinates, addresses, or geographic descriptions.
18
+ 4. DO NOT ramble.
19
19
 
20
- 5. DO NOT ramble.
20
+ 5. If a \`geometryFilter\` is used, do NOT assume the feature referenced in that geometry (e.g., "ApplicationNumber = 'XYZ'") must appear in the results. It may only be used as a spatial anchor.
21
21
 
22
- 6. Use bullet points for lists and use new lines (\\n) and appropriate formatting in your response
22
+ Only describe what _was_ found \u2014 not what was _used to search_.
23
+
24
+ 6. If no feature \`attributes\` are returned but \`totalCount\` is present, assume the spatial filter was applied correctly. There is no need to say the subset was not returned \u2014 just summarize based on the count and available context.
25
+
26
+ 7. Do not give suggestions like exporting the results as the tools are not capable to do that.
27
+
28
+ 8. Use bullet points for lists and use new lines (\\n) and appropriate formatting in your response.
29
+
30
+ 9. Do NOT say things like "I can't change the map", "I can't highlight features", or suggest WHERE clauses for the user to run manually. A separate system handles map visualization automatically after this step. Your job is ONLY to summarize the data returned by the query.
23
31
 
24
32
  In all cases:
25
33
 
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./BDLIIICB.js";import b from"./5XHJVBOQ.js";import{a as i,b as e}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as s,z as a}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{a:r}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=r}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=i(this,"arcgis-assistant-navigation-agent"),e(this)}};a("arcgis-assistant-navigation-agent",t);return t},b,c)
2
+ import c from"./BWML3XTP.js";import b from"./Z43QFN6Z.js";import{a as i,b as e}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as s,z as a}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{a:r}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=r}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=i(this,"arcgis-assistant-navigation-agent"),e(this)}};a("arcgis-assistant-navigation-agent",t);return t},b,c)
@@ -29,6 +29,18 @@ Validator: Before producing output, verify every field used exists in the listed
29
29
 
30
30
  Use the most recent relevant user question from the chat history. The question will **not** be restated again here. Start with a fresh WHERE clause for each question - do not inherit filters from previous questions unless user explicitly asks to combine them.
31
31
 
32
+ ### Rules for generating where clause SQL expressions:
33
+
34
+ - Use only the field\u2019s **\`name\`** in the output expression.
35
+ - Use metadata (\`alias\`, \`description\`, \`statistics\`) only to help understand the user's meaning \u2014 not in the syntax.
36
+ - Use field \`type\` to choose appropriate operators:
37
+ - **String** \u2192 \`LIKE '%value%'\`, \`=\`, \`IN (...)\` (prefer \`LIKE\` over \`=\`)
38
+ - **Number/Date** \u2192 \`=\`, \`<\`, \`>\`, \`BETWEEN\`, etc.
39
+ - Use fields with the **highest \`relevanceScore\`**.
40
+ - DO NOT use subqueries or \`SELECT\` keyword.
41
+ - Combine conditions with \`AND\`, \`OR\`, or \`NOT\` as appropriate.
42
+ - If no meaningful layer filter can be generated, do not call a tool.
43
+
32
44
  ### Mixed Questions
33
45
 
34
46
  If a question has both aggregate and display components (e.g., "How many wells have depth > 100? Show them"):
@@ -0,0 +1,273 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import a from"./Z43QFN6Z.js";export default $arcgis.t(([gt,me,Pe,pt,{addressToLocations:yt},V,se,Ge,Q,ee,fe,ge,Be,Qe,pe,We,{createRenderer:wt},{getSchemesByTag:bt,getSchemes:vt},{getBackgroundColorTheme:Ae},{createAgeRenderer:St,createContinuousRenderer:Tt},{getSchemesByTag:ye},{createContinuousRenderer:Et},{createRenderer:xt},{getSchemesByTag:It},{createRenderer:$t},{getSchemesByTag:Ft},{createRenderer:Lt},{getSchemesByTag:_t},{createRenderer:kt},{getSchemesByTag:Nt},{createAgeRenderer:At,createContinuousRenderer:qt},{createRenderer:Rt},{getSchemesByTag:Mt},Ue,qe,Re,{executeQueryStreaming:Ct},zt,{a:Ie,b:$e,c:D,d:oe,e:ie,f:z,g:P,h:R,i:y,j:p,k:L,l:E,m:Fe,n:K,o:H,p:Le,q:_,r:k,s:n,t:h,u:x,v:J,w:_e,x:j}])=>{var Ne=e=>Array.isArray(e)&&e.every(D),ut=e=>typeof e=="object"&&e!=null&&"messages"in e&&Ne(e.messages),ht=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,M=class extends Le{tools;handleToolErrors=!0;trace=!1;constructor(e,r){let{name:t,tags:a,handleToolErrors:o}=r??{};super({name:t,tags:a,func:(i,s)=>this.run(i,s)}),this.tools=e,this.handleToolErrors=o??this.handleToolErrors}async runTool(e,r){let t=this.tools.find(a=>a.name===e.name);try{if(t===void 0)throw new Error(`Tool "${e.name}" not found.`);let a=await t.invoke({...e,type:"tool_call"},r);return D(a)&&a.getType()==="tool"||H(a)?a:new oe({status:"success",name:t.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||$e(a))throw a;return new oe({status:"error",content:`Error: ${a.message}
3
+ Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,r){let t;if(ht(e))t=[await this.runTool(e.lg_tool_call,r)];else{let i;if(Ne(e))i=e;else if(ut(e))i=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(i.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),l;for(let c=i.length-1;c>=0;c-=1){let d=i[c];if(P(d)){l=d;break}}if(l==null||!P(l))throw new Error("ToolNode only accepts AIMessages as input.");t=await Promise.all(l.tool_calls?.filter(c=>c.id==null||!s.has(c.id)).map(c=>this.runTool(c,r))??[])}if(!t.some(H))return Array.isArray(e)?t:{messages:t};let a=[],o=null;for(let i of t)H(i)?i.graph===K.PARENT&&Array.isArray(i.goto)&&i.goto.every(s=>Fe(s))?o?o.goto.push(...i.goto):o=new K({graph:K.PARENT,goto:i.goto}):a.push(i):a.push(Array.isArray(e)?[i]:{messages:[i]});return o&&a.push(o),a}};var vs=p.Root({llmInputMessages:p({reducer:(e,r)=>_([],r),default:()=>[]})});var Ke=p.Root({messages:p({reducer:_,default:()=>[]}),outputMessage:p({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
4
+
5
+ `);return o[o.length-1]?.trim()===t?e:`${e}
6
+
7
+ ${t}`},default:()=>""}),intent:p({reducer:(e,r)=>r}),vectorSearchLayerResults:p({reducer:(e,r)=>r,default:()=>[]}),vectorSearchFieldResults:p({reducer:(e,r)=>r})});async function jt(e,r){let t=V.getDefault().helperServices.geocode.find(q=>q.name==="ArcGIS World Geocoding Service");if(!t)throw new Error("ArcGIS World Geocoding Service not found in helperServices.");let a=t.url,o=`${se.assetsPath?.endsWith("/")?se.assetsPath:`${se.assetsPath}/`}esri/images/search/search-symbol-32.png`;console.log(`[goToAddress] Geocoding: ${e} using ${a}`);let i=(await yt(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!i?.extent)throw new Error(`Could not find location for: ${e}`);let{xmin:s,ymin:l,xmax:c,ymax:d,spatialReference:u}=i.extent,m=new Pe({xmin:s,ymin:l,xmax:c,ymax:d,spatialReference:u}),f=(s+c)/2,g=(l+d)/2,b=new me({x:f,y:g,spatialReference:u}),v=new pt({url:o,width:24,height:24}),S=new gt({geometry:b,symbol:v});return r.graphics.removeAll(),r.graphics.add(S),await r.goTo(m),`Successfully zoomed to: ${e}. Location coordinates: x=${f}, y=${g}, wkid=${u.wkid}`}var Vt=["mapView"];function I(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("NavigationAgent context missing");let t=Vt.filter(a=>!(a in r));if(t.length)throw new Error(`NavigationAgent context missing: ${t.join(", ")}`);return r}async function Ot({address:e},r){let{mapView:t}=I(r);return await jt(e,t)}var Dt=n.object({address:n.string().describe("The full address or place name to locate.")}),Pt=y(Ot,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Dt});async function Gt(e,r){let t=r.map.bookmarks;if(!t||t.length===0)throw new Error("No bookmarks found in the map.");let a=t.find(i=>i.name===e);if(!a)throw new Error(`Bookmark with name "${e}" not found.`);let o=a.viewpoint;if(!o)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await r.goTo(o),`Navigated to bookmark: ${e}`}async function Bt({bookmarkName:e},r){let{mapView:t}=I(r);return await Promise.resolve(Gt(e,t))}var Qt=R.object({bookmarkName:R.string().describe("The name of the bookmark to navigate to.")}),Wt=y(Bt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Qt});async function Ut(e,r,t){let a=t.map?.allLayers.find(i=>i.id===e);if(!a)return`Error: Layer with id ${e} not found`;let o=a.createQuery();o.where=r??"1=1";try{let{extent:i,count:s}=await a.queryExtent(o);if(s===0)return`No features found in ${a.title} matching: ${r}`;if(i)await t.goTo(i);else return`Error: Unable to determine extent for ${a.title}`;return`Successfully zoomed to ${s} feature(s) in ${a.title}`}catch(i){return console.error("Error in goToFeatures:",i),`Error: ${i instanceof Error?i.message:"Unknown error"}`}}async function Kt({layerId:e,where:r},t){let{mapView:a}=I(t);return await Ut(e,r,a)}var Ht=R.object({layerId:R.string().describe("The layerId of the layer to zoom to."),where:R.string().describe("The sql-92 where clause used to query features to zoom to")}),Jt=y(Kt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Ht});async function Zt(e){let r=new Pe({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(r),"Successfully zoomed to world extent"}async function Xt(e,r){let{mapView:t}=I(r);return await Zt(t)}var Yt=R.object({}),er=y(Xt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Yt});async function tr(e){let r=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(r)await e.goTo(r);else throw new Error("Initial extent is undefined");return"Successfully zoomed to home extent"}async function rr(e,r){let{mapView:t}=I(r);return await tr(t)}var ar=n.object({}),or=y(rr,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:ar});async function ir(e,r){await r.when();let t=r.map?.allLayers.find(o=>o.id===e);if(!t)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),`Could not find layer for: ${e}`;console.log(`[goToLayer] Zooming to layer: ${t.title}`);let a;return(t.type==="link-chart"||t.type==="knowledge-graph-sublayer")&&r.map?.activeLinkChartLayer?a=r.map.diagramNodesExtent:a=t.fullExtent,a?(await r.goTo(a),t.visible=!0,`Successfully zoomed to: ${t.title??""}`):"Layer has no defined extent. Cannot zoom to layer."}async function nr({layerId:e},r){let{mapView:t}=I(r);return await ir(e,t)}var sr=R.object({layerId:R.string().describe("The id of the layer to navigate to")}),lr=y(nr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:sr});async function cr(e,r){return await r.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function dr({scale:e},r){let{mapView:t}=I(r);return await cr(e,t)}var ur=n.object({scale:n.number().describe("The map scale of the view to go to.")}),hr=y(dr,{name:"goToScale",description:"Go to the specified view scale.",schema:ur});async function mr(e,r,t){let a={target:new me({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return t?.zoom!==void 0&&(a.zoom=t.zoom),t?.scale!==void 0&&(a.scale=t.scale),await r.goTo(a),`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,t?.zoom!==void 0?`zoom ${t.zoom}`:"",t?.scale!==void 0?`scale 1:${t.scale}`:""].filter(Boolean).join(", ")}`}async function fr({center:e,zoom:r,scale:t},a){let{mapView:o}=I(a);return await mr(e,o,{zoom:r,scale:t})}var gr=n.object({center:n.object({longitude:n.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:n.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:n.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:n.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),pr=y(fr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:gr});async function yr(e,r){return await r.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function wr({zoom:e},r){let{mapView:t}=I(r);return await yr(e,t)}var br=n.object({zoom:n.number().min(1).max(20).describe("The zoom level of the view to go to.")}),vr=y(wr,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:br}),we=[Pt,Wt,Jt,er,or,lr,hr,pr,vr],Me=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LSGRWCAO.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./KKHKKCYH.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./KQ6LEQHH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./XFRPNWXC.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./ARLFZJO5.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./7CPZ6SAH.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./62K6RJZZ.js").then(e=>e.default),"../agents/layerFilter/prompts/layer_filter_prompt.md":()=>import("./X7WF7TCS.js").then(e=>e.default),"../agents/layerQuery/prompts/data_query_prompt.md":()=>import("./6T2EIYO4.js").then(e=>e.default),"../agents/layerQuery/prompts/summarize_query_response_prompt.md":()=>import("./HN2HMAMX.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./CFT5BBC6.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./W2A22QZU.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./LTBEINKG.js").then(e=>e.default)});async function $(e){let r=Object.entries(Me).find(([t])=>t.endsWith(`/${e}.md`));if(console.log(`entry for prompt "${e}":`,r),!r)throw new Error(`Prompt not found: ${e}
8
+ Available prompts:
9
+ ${Object.keys(Me).join(`
10
+ `)}`);return await r[1]()}var Sr=(e,r=3)=>e.filter(t=>t instanceof ie).slice(-r),T=(e,r=3)=>{let t=e.map((o,i)=>o instanceof ie?i:-1).filter(o=>o!==-1);if(t.length===0)return[];let a=t.length>r?t[t.length-r]:t[0];return e.slice(a)},N=(e,r=" ")=>Sr(e).map(t=>t.content).join(r).trim();async function Tr(e,r){let t=await $("navigation_tool_prompt"),{mapView:a}=I(r),o=a.map,i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((b,v)=>`${v+1}. layerId=${b.id} | title=${b.title??""} | name=${b.name??""} | score=${b.score.toFixed(2)}`).join(`
11
+ `):"",s=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",l=e.intent==="goToBookmark"&&o.bookmarks?.length?`Available bookmarks:
12
+ ${JSON.stringify(o.bookmarks,null,2)}`:"",c=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
13
+ ${i}`:"",d=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
14
+ ${s}`:"",u={intent:e.intent,bookmarksSection:l,layersSection:c,fieldsSection:d,currentZoom:a.zoom},m=await j({promptText:t,modelTier:"advanced",messages:T(e.messages),inputVariables:u,tools:we}),f=[...e.messages,m],g=(m.tool_calls?.length??0)>0?[...f]:[...f,m];return{...e,messages:g}}async function Er(e,r){let t=await new M(we).invoke({messages:T(e.messages)},r),a=t.messages.map(s=>s.text).join(`
15
+ `);await h({text:`Finished executing navigation tool: ${a}`},r);let o=[...e.messages,...t.messages],i=t.messages.map(s=>s.text).join(`
16
+ `);return{...e,messages:o,outputMessage:i}}async function xr(e,r){let t=await $("navigation_intent_prompt"),{mapView:a}=I(r),o=we.map(m=>({name:m.name,description:m.description,schema:m.schema})),i=a.map,s=i.bookmarks?.length?`Available bookmarks:
17
+ ${JSON.stringify(i.bookmarks,null,2)}`:"",l={tools:o.map(({name:m,description:f,schema:g})=>`${m}: ${f}, ${JSON.stringify(g)}`).join(`
18
+ `),bookmarks:s},c=n.object({intent:n.string()}),d=await _e({promptText:t,messages:T(e.messages),inputVariables:l,schema:c}),u=typeof d.intent=="string"?d.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var w=(e,r)=>{let t=e?.configurable?.services?.[r];if(t==null)throw new Error(`${r} missing in config.configurable.services`);return t},Ir=.7,$r=async(e,r)=>{try{let t=N(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=w(r,"layerSearch"),o=w(r,"layersAndFieldsRegistry"),i=w(r,"embeddingCache"),s=(await a.searchLayers({text:t,minScore:Ir,embeddingCache:i})).map(({id:c,score:d})=>{let u=o.get(c)?.layerItem;return{id:c,title:u?.title,name:u?.name??void 0,score:d}}),l;return s.length>0?l=`Vector search completed. Matching layers:
19
+ ${s.map(c=>`- layerId=${c.id} | title=${c.title??""} | name=${c.name??""} | score=${c.score.toFixed(2)}`).join(`
20
+ `)}`:l="Vector search completed. No matching layers found.",await h({text:l},r),{...e,vectorSearchLayerResults:s}}catch(t){throw await h({text:`Error during vector search layers: ${t instanceof Error?t.message:String(t)}`},r),t}},Ce=.7,Fr=10,Lr=async(e,r)=>{try{let t=N(e.messages);await h({text:"Similarity search to find fields"},r);let a=w(r,"fieldSearch"),o=w(r,"layersAndFieldsRegistry"),i=w(r,"embeddingCache"),s=e.vectorSearchLayerResults?.map(d=>d.id)??[];if(s.length===0)return await h({text:"No candidate layers for field search"},r),e;let l=(await a.searchFields({text:t,layerIds:s,minScore:Ce,topResults:Fr,embeddingCache:i})).map(({layerId:d,results:u})=>{let m=o.get(d)?.fieldRegistry;return{layerId:d,layerName:o.get(d)?.layerItem.name,results:u.map(f=>{let g=m?.get(f.name);return{name:f.name,score:f.score,type:g?.type,alias:g?.alias,description:g?.description,statistics:g?.statistics}})}}),c;return l.length>0?c=`Vector search completed. Matching layers and fields:
21
+ ${l.map(d=>`${d.layerName??d.layerId}:
22
+ ${d.results.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
23
+ `)}`).join(`
24
+ `)}`:c=`No vector search field results found for score over ${Ce}.`,await h({text:c},r),{...e,vectorSearchFieldResults:l}}catch(t){throw await h({text:`Error during vector search fields: ${t instanceof Error?t.message:String(t)}`},r),t}},O=(e,r)=>(t,a)=>{let o=a?.configurable?.services;for(let i of e)if(!o?.[i])throw new Error(`${r} requires services.${i} to be available.`);return t},_r=(e,r)=>O(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,r),kr=()=>new k(Ke).addNode("requireNavigationServices",_r).addNode("intentLLM",xr).addNode("vectorSearchLayers",$r).addNode("vectorSearchFields",Lr).addNode("agent",Tr).addNode("tools",Er).addEdge(L,"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",E),Nr=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
25
+ 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.
26
+
27
+ Supported actions:
28
+ - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
29
+ - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
30
+ - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
31
+ - **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
32
+ - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
33
+ - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
34
+ - **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").
35
+ - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
36
+
37
+ _Example: “Zoom to Texas”_
38
+ _Example: “Go to the water mains layer”_
39
+ _Example: “Zoom to to the extent of my link chart”_
40
+ _Example: “Center the map on San Francisco at scale 50000”_
41
+ _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
42
+ _Example: “Go to the Downtown bookmark”_
43
+ _Example: “Where is Mount Rainier?”_`,Tl={id:"navigation",name:"Navigation Agent",description:Nr,createGraph:kr,workspace:Ke},He=p.Root({messages:p({reducer:_,default:()=>[]}),outputMessage:p({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
44
+
45
+ `);return o[o.length-1]?.trim()===t?e:`${e}
46
+
47
+ ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p(),queryResponse:p()}),Ar=async(e,r)=>(await h({text:"Exiting Data Exploration agent"},r),e),W=async(e,r)=>{let t=e.tool_calls??[];if(t.length===0){await h({text:`LLM did not request any tool calls: ${String(e?.content)}`},r);return}await Promise.all(t.map(async a=>await h({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},r))),console.log("LLM response:",JSON.stringify(e.tool_calls,null,2))},qr=["mapView"];function C(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("DataExplorationAgent context missing");let t=qr.filter(a=>!(a in r));if(t.length)throw new Error(`DataExplorationAgent context missing: ${t.join(", ")}`);return r}var Rr=e=>{let r=e.map?.allLayers.filter(a=>a.type==="feature"),t=0;return r?.forEach(a=>{let o=a;o.featureEffect&&(o.featureEffect=null,t++)}),t>0?`Cleared filters from ${t} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},Mr=async(e,r)=>{let{mapView:t}=C(r);return Rr(t)},Cr=y(Mr,{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:n.object({})}),zr=async e=>{e.map?.allLayers.filter(t=>t.type==="feature")?.forEach(t=>{let a=t;a.featureEffect&&(a.featureEffect=null)});let r=e.map.initialViewProperties?.viewpoint?.targetGeometry;return r?(await e.goTo(r),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},jr=async(e,r)=>{let{mapView:t}=C(r);return await zr(t)},Vr=y(jr,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:n.object({})});function Y(e){return"point"in e&&e.point!==void 0}function G(e){return"layerId"in e&&e.layerId!==void 0}var te=async(e,r)=>{if(Y(e)){let{point:t}=e;return{geometry:new me({x:t.x,y:t.y,spatialReference:t.spatialReference?{wkid:t.spatialReference.wkid}:r.spatialReference})}}if(G(e)){let t=r.map?.allLayers.find(a=>a.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};try{let a=await t.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:r.spatialReference});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=ee.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return o.spatialReference||(o.spatialReference=r.spatialReference),{geometry:o}}catch(a){return{error:`Failed to query geometry: ${String(a)}`}}}return{error:"Invalid geometry configuration provided"}},Or=async(e,r,t,a,o,i)=>{let s=e.map?.allLayers.find(c=>c.id===r);if(!s)return{success:!1,error:`Layer '${r}' not found.`};let l=s.createQuery();l.where=t??"1=1",a&&(l.geometry=a,l.spatialRelationship="intersects",o&&(l.distance=o),i&&(l.units=i));try{let{extent:c,count:d}=await s.queryExtent(l);return!c||d===0?{success:!1,error:`No features found for filter (where: ${l.where}${a?", spatial filter used":""})`}:(await e.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},Dr=async(e,r,t,a,o,i)=>{let s=r.map?.allLayers.find(u=>u.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let l;if(o){let u=await te(o,r);if("error"in u)return u.error;l=u.geometry}if(s.featureEffect=null,s.featureEffect=new Ge({filter:new Q({where:e.where,geometry:l,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:t,excludedEffect:a}),s.visible=!0,i)return`Applied feature effects to "${s.title??e.layerId}" within current map extent.`;let c=await Or(r,e.layerId,e.where,l,o?.distance,o?.units),d=s.title??e.layerId;return c.success?`Applied feature effects to target layer "${s.title??e.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${c.error}`},Pr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],A=n.enum(Pr),Gr=async({targetLayer:e,geometryFilter:r,useCurrentExtent:t,includedEffect:a="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},i)=>{let{mapView:s}=C(i);return await Dr(e,s,a,o,r,t)},Br=n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:n.number().optional().describe("The buffer distance around the geometry."),units:A.optional().describe("The units for the distance buffer.")}),Qr=n.object({point:n.object({x:n.number().describe("X coordinate (longitude) from navigation result"),y:n.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:n.object({wkid:n.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:n.number().optional().describe("Optional buffer distance around the point."),units:A.optional().describe("The units for the distance buffer.")}),Wr=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a feature effect."),where:n.string().describe("The SQL-92 where clause representing the features to emphasize.")}),geometryFilter:n.union([Br,Qr]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:n.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:n.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:n.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),Ur=y(Gr,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Wr}),ce=(e,r,t)=>{if(e&&typeof e!="function"){let a="getField"in t&&t.getField?.(e),o=a&&"getFieldDomain"in t&&t.getFieldDomain?t.getFieldDomain(a.name):null;if(o?.type==="coded-value"){let i=o.codedValues.find(s=>s.code===r);return i?i.name:null}}return null},Kr=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},Hr=async(e,r,t,a)=>{let o=a.map?.allLayers.find(d=>d.id===e),i=Kr(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null,c=ce(r,l,o)||l;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${c}`,details:{fieldName:r,value:c,where:t.where}}};async function Jr({layerId:e,fieldName:r,query:t},a){let{mapView:o}=C(a),i=await Hr(e,r,t,o);return JSON.stringify(i,null,2)}var Zr=n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:n.string().describe("The name of the field/attribute from which to get a field value."),query:n.object({where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Xr=y(Jr,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Zr}),be=(e,r,t)=>t?e.hasAllFeaturesInView&&e.availableFields===r:e.hasAllFeatures&&e.availableFields===r,Yr=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryFilter:s}=e,l=o.map?.allLayers.find(S=>S.id===r.layerId);if(!l)throw new Error(`Layer '${r.layerId}' not found.`);let c=await o.whenLayerView(l),d=i.get(r.layerId)?.fieldRegistry.get(t);if(!d)throw new Error(`Field '${t}' not found.`);let u,m;if(s){let S=await te(s,o);if("error"in S)throw new Error(S.error);if(!S.geometry)throw G(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");G(s)?u={geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}:Y(s)&&(u={point:s.point,distance:s.distance,units:s.units,applied:!0}),m=new Q({geometry:S.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let f=be(c,[t],!1),g=null,b=null,v=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{let S={layer:l,useFeaturesInView:f,view:f?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m},outStatisticTypes:{include:[a]}};g=await fe(S),["string","small-integer","integer"].includes(d.type)&&(b=(await ge({layer:l,useFeaturesInView:f,view:f?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m}})).uniqueValueInfos.sort((q,ct)=>ct.count-q.count).slice(0,v))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof g?.[a]=="number"?g[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:g?.[a]??null,summaryStatistics:g,uniqueValues:b,where:r.where,spatialFilterInfo:u}}};async function ea({targetLayer:e,fieldName:r,statisticType:t,geometryFilter:a},o){let i=w(o,"layersAndFieldsRegistry"),{mapView:s}=C(o),l=await Yr({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryFilter:a});return JSON.stringify(l,null,2)}var ta=n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:n.number().optional().describe("The buffer distance around the geometry."),units:A.optional().describe("The units for the distance buffer.")}),ra=n.object({point:n.object({x:n.number().describe("X coordinate (longitude) from navigation result"),y:n.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:n.object({wkid:n.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:n.number().optional().describe("Optional buffer distance around the point."),units:A.optional().describe("The units for the distance buffer.")}),aa=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:n.union([ta,ra]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:n.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:n.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),oa=y(ea,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
48
+
49
+ USE THIS TOOL FOR:
50
+ - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
51
+ - "Most common/frequent value of [field]?" \u2014 frequency analysis
52
+ - Questions requiring a mathematical aggregation across many features
53
+
54
+ DO NOT USE FOR:
55
+ - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
56
+ - "Show / list / find features" \u2014 use queryFeatures instead
57
+ - Simple counts of features matching a condition \u2014 use queryFeatures instead
58
+
59
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:aa}),ia=async(e,r,t,a)=>{let o=t.map?.allLayers.find(u=>u.id===e.layerId),i=await t.whenLayerView(o),s=o.title??e.layerId,l;if(a){let u=await te(a,t);if("error"in u)return{tool:"getTopFeatures",layerName:s,summary:"Geometry lookup failed",details:{error:u.error}};if(!u.geometry)return{tool:"getTopFeatures",layerName:s,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};l=u.geometry}let c=e.outFields.length>2?e.outFields:["*"],d=r.groupByFields&&r.groupByFields.length>0;try{let u;if(d){let f=new Be({where:e.where||"1=1",outFields:c,orderByFields:e.orderByFields,geometry:l,spatialRelationship:l?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new Qe({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})});u=await o.queryTopFeatures(f)}else{let f=new pe({where:e.where||"1=1",outFields:c,orderByFields:r.orderByFields,num:r.topCount,geometry:l,spatialRelationship:l?"intersects":void 0,distance:a?.distance,units:a?.units,outSpatialReference:t.spatialReference}),g=be(i,e.outFields,!1);try{u=g?await i.queryFeatures(f):await o.queryFeatures(f)}catch(b){console.warn("Client-side query failed, falling back to server:",b),u=await o.queryFeatures(f)}}let m=u.features.map(f=>f.attributes);return{tool:"getTopFeatures",layerName:s,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,attributes:m,where:e.where,orderByFields:r.orderByFields,...d&&{groupByFields:r.groupByFields}}}}catch(u){return{tool:"getTopFeatures",layerName:s,summary:"Query failed",details:{error:u instanceof Error?u.message:String(u)}}}},na=async({targetLayer:e,topFilter:r,geometryFilter:t},a)=>{let{mapView:o}=C(a),i=await ia(e,r,o,t);return JSON.stringify(i,null,2)},sa=n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:n.number().optional().describe("The buffer distance around the geometry."),units:A.optional().describe("The units for the distance buffer.")}),la=n.object({point:n.object({x:n.number().describe("X coordinate (longitude) from navigation result"),y:n.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:n.object({wkid:n.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:n.number().optional().describe("Optional buffer distance around the point."),units:A.optional().describe("The units for the distance buffer.")}),ca=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:n.union([sa,la]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:n.object({topCount:n.number().describe("Number of top features to return per group."),orderByFields:n.array(n.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:n.array(n.string().describe("Field(s) to group results by. Returns top N per group."))})}),da=y(na,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:ca}),le=25,ua=async(e,r,t,a)=>{let o=r.map?.allLayers.find(g=>g.id===e.layerId),i=await r.whenLayerView(o),s=o.title??e.layerId,l;if(t){let g=await te(t,r);if("error"in g){let b={error:g.error};return G(t)?(b.geometryLayerId=t.layerId,b.geometryWhere=t.where):Y(t)&&(b.point=t.point),{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:b}}if(!g.geometry){let b={};return G(t)?(b.error=`No features found matching: ${t.where}`,b.geometryLayerId=t.layerId,b.geometryWhere=t.where):Y(t)&&(b.error="Failed to create point geometry",b.point=t.point),{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:b}}l=g.geometry}else a&&(l=r.extent.clone());let c=be(i,e.outFields,a??!1),d=new pe({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,...l&&{geometry:l,spatialRelationship:"intersects"},...t?.distance&&{distance:t.distance},...t?.units&&{units:t.units},outSpatialReference:r.spatialReference}),u,m;try{u=c?await i.queryFeatureCount(d):await o.queryFeatureCount(d),u>0&&u<=le&&(m=c?await i.queryFeatures(d):await o.queryFeatures(d),m&&m.features.forEach(g=>{let b=g.attributes;o.fields.forEach(v=>{let S=b[v.name],q=ce(v.name,S,o);q&&(b[v.name]=q)})}))}catch(g){console.warn("Client-side query failed, falling back to server:",g),u=await o.queryFeatureCount(d),u>0&&u<=le&&(m=await o.queryFeatures(d),m&&m.features.forEach(b=>{o.fields.forEach(v=>{let S=b.attributes[v.name],q=ce(v.name,S,o);q&&(b.attributes[v.name]=q)})}))}let f=m?.features.map(g=>g.attributes);return{tool:"queryFeatures",layerName:s,summary:`${u} features found`,details:{totalCount:u,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...f&&{attributes:f},...u>le&&{note:`${u} features found.`}}}};async function ha({targetLayer:e,geometryFilter:r,useCurrentExtent:t},a){let{mapView:o}=C(a),i=await ua(e,o,r,t);return JSON.stringify(i,null,2)}var ma=n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:n.number().optional().describe("The buffer distance around the geometry."),units:A.optional().describe("The units for the distance buffer.")}),fa=n.object({point:n.object({x:n.number().describe("X coordinate (longitude) from navigation result"),y:n.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:n.object({wkid:n.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:n.number().optional().describe("Optional buffer distance around the point."),units:A.optional().describe("The units for the distance buffer.")}),ga=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:n.union([ma,fa]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:n.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),pa=y(ha,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
60
+
61
+ USE THIS TOOL FOR:
62
+ - "Show / display / list features where..." \u2014 finding and listing features
63
+ - "How many X are Y?" \u2014 counting features that match a condition
64
+ - "Which features..." / "Find features..." \u2014 identifying specific features
65
+ - Spatial queries \u2014 finding features near/within/intersecting other features
66
+ - Any question where the user wants to SEE or COUNT matching features
67
+
68
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:ga}),Je=[Xr,oa,da,pa],Ze=[Ur,Vr,Cr],re=()=>{let e=new Date().getTimezoneOffset(),r=e<=0?"+":"-",t=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),a=(Math.abs(e)%60).toString().padStart(2,"0"),o=`${r}${t}:${a}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:o}},ya=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await $("data_explore_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=re(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,queryResponse:e.queryResponse},s=await j({promptText:t,modelTier:"advanced",messages:T(e.messages),inputVariables:i,tools:Ze}),l=[...e.messages,s];if(!((s.tool_calls?.length??0)>0))return await h({text:"LLM determined no filter changes needed"},r),{...e,messages:l};let c=[...l,s],d=s.content.toString();return await W(s,r),{...e,messages:c,outputMessage:d}},wa=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await $("data_explore_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=re(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await j({promptText:t,modelTier:"advanced",messages:T(e.messages),inputVariables:i,tools:Je}),l=[...e.messages,s],c=s.content.toString();return await W(s,r),{...e,messages:l,outputMessage:c}},ba=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await $("summarize_query_response_prompt"),a={queryResponse:e.queryResponse},o=await J({promptText:t,messages:T(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content,s=new z(i);return await h({text:`Received response from LLM: ${i}`},r),{...e,outputMessage:i,messages:[...e.messages,s]}}catch(t){throw await h({text:"Error during filter LLM request"},r),new Error(`Error during filter LLM request: ${t instanceof Error?t.message:String(t)}`)}};async function va(e,r){let t=await new M(Ze).invoke({messages:T(e.messages)},r),a=[...e.messages,...t.messages],o=t.messages.map(s=>new z({content:s.content,additional_kwargs:s.additional_kwargs}));await h({text:`Finished executing layer filter tool: ${t.messages.map(s=>s.content).join(", ")}`},r);let i=[...a,...o];return{...e,messages:i}}var Sa=new M(Je);async function Ta(e,r){let{messages:t}=await Sa.invoke({messages:T(e.messages)},r),a=[],o=[];for(let s of t){let l=s.content,c;if(typeof l!="string"){c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:l}};continue}try{c=JSON.parse(l)}catch{c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:l}}}a.push(c),c.details&&typeof c.details=="object"&&"error"in c.details?o.push(`- ${c.tool}: Error - ${String(c.details.error)}`):o.push(`- ${c.layerName}: ${c.summary}`)}let i=[...e.messages,...t];return await h({text:`Finished executing layer query tool: ${o.join(", ")}`},r),{...e,messages:i,queryResponse:a}}var Ea=10,xa=async(e,r)=>{let t=null,a=null;try{r.type!=="geometry"&&r.type!=="oid"&&r.type!=="global-id"&&(t=await fe({layer:e,field:r.name}),r.type==="string"&&(a=(await ge({layer:e,field:r.name})).uniqueValueInfos.sort((o,i)=>i.count-o.count).slice(0,Ea)))}catch(o){console.error(`Error fetching statistics for field ${r.name}:`,o)}return{summaryStatistics:t,uniqueValues:a}};async function ve(e,r,t){let a=[],o=[];for(let i of e){let s=function(f){let g=r.get(f)?.layerItem;return g?[g.name&&`Name: ${g.name}`,g.title&&`Title: ${g.title}`,g.description&&`Description: ${g.description}`].filter(Boolean).join(" | "):f},{layerId:l,results:c}=i,d=t.map?.allLayers.find(f=>f.id===l),u=r.get(l)?.fieldRegistry;if(!u)continue;let m=a.find(f=>f.layerId===l);m||(m={layerId:l,layerSummary:s(l),fieldInfos:[]},a.push(m));for(let f of c){let g=u.get(f.name);if(g){if(!g.statistics){let b=xa(d,g).then(v=>{u.set(g.name,{...g,statistics:v}),g.statistics=v});o.push(b)}m.fieldInfos.push(g)}}}return await Promise.all(o),a}var Ia=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=w(r,"layersAndFieldsRegistry"),{mapView:a}=C(r),o=await ve(e.vectorSearchFieldResults,t,a);return console.log("Field statistics retrieved:",o),await h({text:"Statistics retrieved"},r),{...e,layerFieldInfo:o}}catch(t){throw await h({text:"Error during fetching statistics"},r),new Error(`Error during fetching statistics: ${t instanceof Error?t.message:String(t)}`)}},ze=.7,$a=10,Fa=async(e,r)=>{try{let t=N(e.messages);await h({text:"Similarity search to find fields"},r);let a=w(r,"fieldSearch"),o=w(r,"layersAndFieldsRegistry"),i=w(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:ze,topResults:$a,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
69
+ `);return`${o.get(d)?.layerItem.name??d}:
70
+ ${m}`}).join(`
71
+ `),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
72
+ ${l}`:c=`No vector search results found for score over ${ze}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},La=.7,_a=async(e,r)=>{try{let t=N(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=w(r,"layerSearch"),o=w(r,"layersAndFieldsRegistry"),i=w(r,"embeddingCache"),s=await a.searchLayers({text:t,minScore:La,embeddingCache:i}),l=s.map(u=>u.id),c=s.map(({id:u,score:m})=>`${o.get(u)?.layerItem.name??u} (${m.toFixed(2)})`).join(`
73
+ `),d;return l.length>0?d=`Vector search completed. Matching layers with scores:
74
+ ${c}`:d="Vector search completed. No matching layers found.",await h({text:d},r),{...e,vectorSearchLayerIds:l}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},ka=(e,r)=>O(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,r),Na=()=>new k(He).addNode("requireDataExplorationServices",ka).addNode("vectorSearchLayers",_a).addNode("vectorSearchFields",Fa).addNode("fieldStatistics",Ia).addNode("queryAgent",wa).addNode("queryTools",Ta).addNode("summarizeQueryResponseLLM",ba).addNode("filterAgent",ya).addNode("filterTools",va).addNode("earlyExit",Ar).addEdge(L,"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.messages[e.messages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.messages[e.messages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),Aa=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).
75
+ 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.
76
+ _Example: “Only show stations where Brand is Shell”_
77
+ _Example: “Make Shell stations stand out on the map”_
78
+ _Example: “Gray out all stations that aren’t Shell”_
79
+ 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.
80
+ _Example: “How many features are there?”_
81
+ _Example: “What’s the average population?”_
82
+ _Example: “Which values are in the status field?”_`,El={id:"dataExploration",name:"Data Exploration Agent",description:Aa,createGraph:Na,workspace:He},je=.7,qa=10,Ra=async(e,r)=>{try{let t=N(e.messages);await h({text:"Similarity search to find fields"},r);let a=w(r,"fieldSearch"),o=w(r,"layersAndFieldsRegistry"),i=w(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:je,topResults:qa,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
83
+ `);return`${o.get(d)?.layerItem.name??d}:
84
+ ${m}`}).join(`
85
+ `),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
86
+ ${l}`:c=`No vector search results found for score over ${je}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},Ma=.7,Ca=async(e,r)=>{try{let t=N(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=w(r,"layerSearch"),o=w(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:Ma}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
87
+ `),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
88
+ ${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},Xe=["mapView"];function Se(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerFilterAgent context missing");let t=Xe.filter(a=>!(a in r));if(t.length)throw new Error(`LayerFilterAgent context missing: ${t.join(", ")}`);return r}var za=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=w(r,"layersAndFieldsRegistry"),{mapView:a}=Se(r),o=await ve(e.vectorSearchFieldResults,t,a);return console.log("Field statistics retrieved:",o),await h({text:"Statistics retrieved"},r),{...e,layerFieldInfo:o}}catch(t){throw await h({text:"Error during fetching statistics"},r),new Error(`Error during fetching statistics: ${t instanceof Error?t.message:String(t)}`)}},Ye=async(e,r,t)=>{let a=e.map?.allLayers.find(s=>s.id===r),o=a.createQuery();o.where=t??"1=1";let{features:i}=await a.queryFeatures(o);e.goTo(i)},et=async(e,r)=>{let t=r.map?.allLayers.find(i=>i.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=await t.queryFeatures({where:e.where,returnGeometry:!0});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=ee.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},ja=async(e,r,t,a,o)=>{let i=r.map?.allLayers.find(l=>l.id===e.layerId);if(!i)return`Could not find target layer with ID: ${e.layerId}`;console.log("Layer type:",i.type),console.log("Layer geometryType:",i.geometryType),console.log("Layer renderer:",i.renderer?.type);let s;if(o){let l=await et(o,r);if("error"in l)return l.error;s=l.geometry}return i.featureEffect=new Ge({filter:new Q({where:e.where,geometry:s,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:t,excludedEffect:a}),i.visible=!0,i.refresh(),Ye(r,o?o.layerId:e.layerId,o?o.where:e.where),`Applied feature effects to target layer "${i.title??e.layerId}"${o?` using geometry from layer "${o.layerId}"`:""}.`},Va=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],tt=n.enum(Va),Oa=async({targetLayer:e,geometryLayer:r,includedEffect:t="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},o)=>{let{mapView:i}=Se(o);return await ja(e,i,t,a,r)},Da=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a feature effect."),where:n.string().describe("The SQL-92 where clause representing the features to emphasize.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:tt.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),includedEffect:n.string().optional().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:n.string().optional().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),Pa=y(Oa,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Da}),Ga=async(e,r,t)=>{let a=r.map?.allLayers.find(s=>s.id===e.layerId);if(!a)return`Could not find target layer with ID: ${e.layerId}`;let o;if(t){let s=await et(t,r);if("error"in s)return s.error;o=s.geometry}let i=await r.whenLayerView(a);return i.filter=new Q({where:e.where,geometry:o,spatialRelationship:"intersects",distance:t?.distance,units:t?.units}),a.visible=!0,Ye(r,t?t.layerId:e.layerId,t?t.where:e.where),`Applied feature filter to layer "${a.title??e.layerId}"${t?` using geometry from layer "${t.layerId}"`:""}.`},Ba=async({targetLayer:e,geometryLayer:r},t)=>{let{mapView:a}=Se(t);return await Ga(e,a,r)},Qa=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a filter."),where:n.string().describe("The SQL-92 where clause representing the features to display.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:tt.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Wa=y(Ba,{name:"setFeatureFilter",description:"Sets a client-side filter using a where clause, geometry filter, or both on a target layer. This filters features at the client level in the view.",schema:Qa}),rt=[Pa,Wa],Ua=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await $("layer_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=re(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await j({promptText:t,modelTier:"advanced",messages:T(e.messages),inputVariables:i,tools:rt}),l=s.content.toString();return await W(s,r),{...e,messages:[...e.messages,s],outputMessage:l}};async function Ka(e,r){let t=await new M(rt).invoke({messages:T(e.messages)},r),a=t.messages.map(s=>s.text).join(`
89
+ `);await h({text:`Finished executing layer filter tool: ${a}`},r);let o=[...e.messages,...t.messages],i=t.messages.map(s=>s.text).join(`
90
+ `);return{...e,outputMessage:i,messages:o}}var at=p.Root({messages:p({reducer:_,default:()=>[]}),outputMessage:p({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
91
+
92
+ `);return o[o.length-1]?.trim()===t?e:`${e}
93
+
94
+ ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p()}),Ha=async(e,r)=>(await h({text:"Exiting Layer Filter agent"},r),e),Ja=(e,r)=>O(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Filter Agent")(e,r),Za=()=>new k(at).addNode("requireLayerFilterServices",Ja).addNode("vectorSearchLayers",Ca).addNode("vectorSearchFields",Ra).addNode("fieldStatistics",za).addNode("agent",Ua).addNode("tools",Ka).addNode("earlyExit",Ha).addEdge(L,"requireLayerFilterServices").addEdge("requireLayerFilterServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","agent").addConditionalEdges("agent",e=>(e.messages[e.messages.length-1]?.tool_calls?.length??0)>0?"tools":"earlyExit").addEdge("tools","earlyExit").addEdge("earlyExit",E),Xa=String.raw`- **layer filter** — User wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
95
+ The Layer Filter Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
96
+ _Example: “Only show stations where Brand is Shell”_
97
+ _Example: “Make Shell stations stand out on the map”_
98
+ _Example: “Gray out all stations that aren’t Shell”_`,xl={id:"layerFilter",name:"Layer Filter Agent",description:Xa,createGraph:Za,workspace:at},ot=p.Root({messages:p({reducer:_,default:()=>[]}),outputMessage:p({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
99
+
100
+ `);return o[o.length-1]?.trim()===t?e:`${e}
101
+
102
+ ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p(),queryResponses:p()}),Ya=async(e,r)=>(await h({text:"Exiting Layer Query agent"},r),e);function U(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerQueryAgent context missing");let t=Xe.filter(a=>!(a in r));if(t.length)throw new Error(`LayerQueryAgent context missing: ${t.join(", ")}`);return r}var eo=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=w(r,"layersAndFieldsRegistry"),{mapView:a}=U(r),o=await ve(e.vectorSearchFieldResults,t,a);return console.log("Field statistics retrieved:",o),await h({text:"Statistics retrieved"},r),{...e,layerFieldInfo:o}}catch(t){throw await h({text:"Error during fetching statistics"},r),new Error(`Error during fetching statistics: ${t instanceof Error?t.message:String(t)}`)}},Ve=.7,to=10,ro=async(e,r)=>{try{let t=N(e.messages);await h({text:"Similarity search to find fields"},r);let a=w(r,"fieldSearch"),o=w(r,"layersAndFieldsRegistry"),i=w(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:Ve,topResults:to,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
103
+ `);return`${o.get(d)?.layerItem.name??d}:
104
+ ${m}`}).join(`
105
+ `),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
106
+ ${l}`:c=`No vector search results found for score over ${Ve}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},ao=.7,oo=async(e,r)=>{try{let t=N(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=w(r,"layerSearch"),o=w(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:ao}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
107
+ `),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
108
+ ${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},io=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},no=async(e,r,t,a)=>{let o=a.map?.allLayers.find(c=>c.id===e),i=io(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${l}`,details:{fieldName:r,value:l,where:t.where}}};async function so({layerId:e,fieldName:r,query:t},a){let{mapView:o}=U(a),i=await no(e,r,t,o);return JSON.stringify(i,null,2)}var lo=n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:n.string().describe("The name of the field/attribute from which to get a field value."),query:n.object({where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),co=y(so,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:lo}),Te=async(e,r)=>{let t=r.map?.allLayers.find(i=>i.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=await t.queryFeatures({where:e.where,returnGeometry:!0});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=ee.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},uo=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryLayer:s}=e,l=o.map?.allLayers.find(g=>g.id===r.layerId);if(!l)throw new Error(`Layer '${r.layerId}' not found.`);let c=i.get(r.layerId)?.fieldRegistry.get(t);if(!c)throw new Error(`Field '${t}' not found.`);let d;if(s){let g=await Te(s,o);if("error"in g)throw new Error(g.error);if(d=g.geometry,s.distance&&s.units){let b=We.execute(d,s.distance,{unit:s.units==="us-nautical-miles"?"nautical-miles":s.units});b&&(d=b)}}else d=o.extent.clone();let u=new Q({geometry:d,spatialRelationship:"intersects"}),m=null,f=null;try{m=await fe({layer:l,field:t,sqlWhere:r.where,filter:u,outStatisticTypes:{include:[a]}}),c.type==="string"&&(f=(await ge({layer:l,field:t,sqlWhere:r.where,filter:u})).uniqueValueInfos)}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof m?.[a]=="number"?m[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:m?.[a]??null,summaryStatistics:m,uniqueValues:f,where:r.where}}},ho=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],mo=n.enum(ho);async function fo({targetLayer:e,fieldName:r,statisticType:t,geometryLayer:a},o){let i=w(o,"layersAndFieldsRegistry"),{mapView:s}=U(o),l=await uo({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryLayer:a});return console.log(l),JSON.stringify(l,null,2)}var go=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryLayer:n.union([n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().optional().describe("The distance by which to query from the input geometry."),units:mo.optional().describe("The units used to query by geometry and distance.")}),n.object({}).strict()]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),fieldName:n.string().describe("The name of the field for which to get statistics."),statisticType:n.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),po=y(fo,{name:"getStatistics",description:"Returns one or more summary statistics for the given field. Statistic types include: count, maximum, minimum, average, median, standard deviation, variance, mode, sum, nullcount (number of features without a value for a given field), unique values. Statistics can be returned for number, date, and string fields. Only call this tool when the question requires filtering (e.g. a WHERE clause or spatial constraint) that cannot be satisfied by precomputed stats.",schema:go}),yo=async(e,r,t,a)=>{let o=t.map?.allLayers.find(d=>d.id===e.layerId),i=a?await Te(a,t):{geometry:void 0},s="geometry"in i?i.geometry:void 0,l=new Be({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,geometry:s,spatialRelationship:s?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new Qe({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})}),c=await o.queryTopFeatures(l);return{tool:"getTopFeatures",layerName:o.title??e.layerId,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,features:c.features,where:e.where}}},wo=async({targetLayer:e,topFilter:r,geometryLayer:t},a)=>{let{mapView:o}=U(a),i=await yo(e,r,o,t);return JSON.stringify(i,null,2)},bo=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.string().describe("The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output."))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to query from the input geometry."),units:A.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),topFilter:n.object({topCount:n.number().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),groupByFields:n.array(n.string().describe("The field(s) for which to group by the top features."))})}),vo=y(wo,{name:"getTopFeatures",description:"Returns the top n features from a layer",schema:bo}),So=async(e,r,t)=>{let a=r.map?.allLayers.find(c=>c.id===e.layerId),o=t?await Te(t,r):{geometry:void 0},i="geometry"in o?o.geometry:void 0,s=new pe({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,geometry:i,spatialRelationship:i?"intersects":void 0,distance:t?.distance,units:t?.units}),l=await a.queryFeatures(s);return{tool:"queryFeatures",layerName:a.title??e.layerId,summary:`${l.features.length} features found`,details:{totalCount:l.features.length,features:l.features.slice(0,10),where:e.where}}};async function To({targetLayer:e,geometryLayer:r},t){let{mapView:a}=U(t),o=await So(e,a,r);return JSON.stringify(o,null,2)}var Eo=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.string().describe("The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output."))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to query from the input geometry."),units:A.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),xo=y(To,{name:"queryFeatures",description:"Queries for one or more features from a given layer.",schema:Eo}),it=[xo,po,co,vo],Io=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await $("data_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=re(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await j({promptText:t,modelTier:"advanced",messages:T(e.messages),inputVariables:i,tools:it});if(!(s.tool_calls&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0))return{...e,messages:[...e.messages,s]};let l=s.content.toString()||"LLM requested tool calls.";return await W(s,r),{...e,outputMessage:l,messages:[...e.messages,s]}},$o=new M(it);async function Fo(e,r){let{messages:t}=await $o.invoke({messages:T(e.messages)},r),a=[],o=[];for(let l of t){let c=l.content;if(typeof c!="string"){console.warn("Skipping non-string tool output:",c);continue}let d;try{d=JSON.parse(c)}catch{console.warn("Skipping invalid JSON from tool:",c);continue}a.push(d),o.push(`- ${d.layerName}: ${d.summary}`)}if(o.length===0)return{...e,queryResponses:a};let i=new z({content:`Query results:
109
+ ${o.join(`
110
+ `)}`}),s=`Query results:
111
+ ${o.join(`
112
+ `)}`;return{...e,outputMessage:s,messages:[...e.messages,...t,i],queryResponses:a}}var Lo=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await $("summarize_query_response_prompt"),a={queryResponse:e.queryResponses},o=await J({promptText:t,messages:T(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content;return e.messages=[...e.messages,new z(i)],e.outputMessage=i,await h({text:`Received response from LLM: ${i}`},r),e}catch(t){throw await h({text:"Error during filter LLM request"},r),new Error(`Error during filter LLM request: ${t instanceof Error?t.message:String(t)}`)}},_o=(e,r)=>O(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Query Agent")(e,r),ko=()=>new k(ot).addNode("requireLayerQueryServices",_o).addNode("vectorSearchLayers",oo).addNode("vectorSearchFields",ro).addNode("fieldStatistics",eo).addNode("agent",Io).addNode("tools",Fo).addNode("summarizeQueryResponseLLM",Lo).addNode("earlyExit",Ya).addEdge(L,"requireLayerQueryServices").addEdge("requireLayerQueryServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","agent").addEdge("agent","tools").addConditionalEdges("tools",e=>e.queryResponses.length?"summarizeQueryResponseLLM":"earlyExit").addEdge("summarizeQueryResponseLLM",E).addEdge("earlyExit",E),No=String.raw`- **layerQuery** — 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. CRITICAL: Always call the Layer Filter Agent after this agent.
113
+ 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?”).
114
+ _Example: “How many features are there?”_
115
+ _Example: “What’s the average population?”_
116
+ _Example: “Which values are in the status field?”_`,Il={id:"layerQuery",name:"Layer Query Agent",description:No,createGraph:ko,workspace:ot},Oe=.7,Ao=10,qo=async(e,r)=>{try{let t=N(e.messages);await h({text:"Similarity search to find fields"},r);let a=w(r,"fieldSearch"),o=w(r,"layersAndFieldsRegistry"),i=w(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:Oe,topResults:Ao,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
117
+ `);return`${o.get(d)?.layerItem.name??d}:
118
+ ${m}`}).join(`
119
+ `),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
120
+ ${l}`:c=`No vector search results found for score over ${Oe}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},Ro=.7,Mo=async(e,r)=>{try{let t=N(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=w(r,"layerSearch"),o=w(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:Ro}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
121
+ `),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
122
+ ${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}};async function Co(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i?s=bt({basemapTheme:await Ae(a),geometryType:t.geometryType,includedTags:i,numColors:Math.min(r.length,8)})[0]:s=vt({basemapTheme:await Ae(a),geometryType:t.geometryType,numColors:Math.min(r.length,8)}).primaryScheme,{layer:t,view:a,attributes:r.map(l=>({field:l,label:t.fields.find(c=>c.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function zo(e){return await wt(e)}async function jo({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,includeSize:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:i?"chart-size":"chart",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=await Co(c),u=await zo(d);return l.renderer=u.renderer,l.visible=!0,`Chart renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying chart renderer: ${d instanceof Error?d.message:String(d)}`}}var Vo=["mapView"];function F(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerStylingAgent context missing");let t=Vo.filter(a=>!(a in r));if(t.length)throw new Error(`LayerStylingAgent context missing: ${t.join(", ")}`);return r}async function Oo({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await jo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,includeSize:a})}var Do=n.object({layerId:n.string().describe("The id of the layer to apply the chart renderer to"),fields:n.array(n.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),includeSize:n.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Po=y(Oo,{name:"chart",description:`Label: Charts
123
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart.
124
+ Keywords: pie, chart, all categories, breakdown, proportion
125
+ Example: Show the total number of homes built in each decade using a pie chart for each feature.
126
+ Fields: This style requires 2-8 number fields.
127
+
128
+ Label: Charts and Size
129
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
130
+ Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
131
+ Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
132
+ Fields: This style requires 2-8 number fields.`,schema:Do});function Go(e){let{fields:r,layer:t,view:a,theme:o,colorSchemeTags:i}=e,s=r[0],l;return i&&(l=ye({geometryType:t.geometryType,includedTags:i,theme:o||"high-to-low"})[0]),{layer:t,view:a,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:l}}async function Bo(e){return await St(e)}async function Qo({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"color-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Go(c),u=await Bo(d);return l.renderer=u.renderer,l.visible=!0,`Color-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Wo({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Qo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Uo=n.object({layerId:n.string().describe("The id of the layer to apply the color-age renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Ko=y(Wo,{name:"color-age",description:`Label: Age (color)
133
+ Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
134
+ Keywords: since, age, how old, how long
135
+ Example: Show the age of each feature based on its reported date.
136
+ Fields: This style requires at least one field with a date type.`,schema:Uo});function Ho(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,{theme:i}=e,s=r[1],l=r[0],c;return o&&(c=ye({geometryType:t.geometryType,includedTags:o,theme:i||"high-to-low"})[0]),{layer:t,view:a,field:l,normalizationField:s,theme:i,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function Jo(e){return await Tt(e)}async function Zo({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"color",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Ho(c),u=await Jo(d);return l.renderer=u.renderer,l.visible=!0,`Color renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color renderer: ${d instanceof Error?d.message:String(d)}`}}async function Xo({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Zo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Yo=n.object({layerId:n.string().describe("The id of the layer to apply the color renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the color renderer"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),ei=y(Xo,{name:"color",description:`Label: Counts and Amounts (color)
137
+ Description: Vary color along a continuous color ramp to represent numeric or ranked data.
138
+ Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
139
+ Example: Color each feature based on the population density.
140
+ Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:Yo});function ti(e){let{fields:r,layer:t,view:a,colorSchemeTags:o,theme:i}=e,s,l,c=r[0];return o&&(l=ye({geometryType:t.geometryType,includedTags:o,theme:i||"high-to-low"})[0]),{layer:t,view:a,field:c,normalizationField:s,theme:i,colorOptions:{colorScheme:l}}}async function ri(e){return await Et(e)}async function ai({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"color-size-univariate",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=ti(c),u=await ri(d);return l.renderer=u.renderer,l.visible=!0,`Color-size-univariate renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-size-univariate renderer: ${d instanceof Error?d.message:String(d)}`}}async function oi({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await ai({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var ii=n.object({layerId:n.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:n.array(n.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),ni=y(oi,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
141
+ Description: Vary symbol size and color based on the values of two numeric attributes.
142
+ Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
143
+ Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
144
+ Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:ii});function si(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i;return o&&(i=It({includedTags:o,numColors:Math.min(r.length,8)})[0]),{layer:t,view:a,legendOptions:{unit:"units"},attributes:r.map(s=>({field:s,label:t.fields.find(l=>l.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:i}}async function li(e){return await xt(e)}async function ci({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o}){let i=r,s=e?.allLayers.find(c=>c.id===t);if(!s)return`Could not find layer for id: ${t}`;let l={styleName:"dot-density",fields:a,layer:s,view:i,colorSchemeTags:o};try{let c=si(l),d=await li(c);return s.renderer=d.renderer,s.visible=!0,`Dot Density renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function di({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=F(a);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await ci({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var ui=n.object({layerId:n.string().describe("The id of the layer to apply the dot density renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use")}),hi=y(di,{name:"dot-density",description:`Dot Density
145
+ Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
146
+ **Use cases:**
147
+ - Population distribution visualization
148
+ - Comparing multiple categories within areas
149
+ - Showing spatial distribution patterns
150
+ **Examples:**
151
+ - Show the density of the population based on various race/ethnic groups
152
+ - Visualize distribution of different crops across regions
153
+ - Display demographic patterns within census tracts
154
+ **Fields:** Requires 2-8 number fields.
155
+ **Keywords:** density, how much, how many, total, number, amount`,schema:ui});function mi(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s=r[0];return o&&(i=Ft({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:t,view:a,field:s,heatmapScheme:i}}async function fi(e){return await $t(e)}async function gi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o}){let i=r,s=e?.allLayers.find(c=>c.id===t);if(!s)return`Could not find layer for id: ${t}`;let l={styleName:"heatmap",fields:a,layer:s,view:i,colorSchemeTags:o};try{let c=mi(l),d=await fi(c);return s.renderer=d.renderer,s.visible=!0,`Heatmap renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function pi({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=F(a);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await gi({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var yi=n.object({layerId:n.string().describe("The id of the layer to apply the heatmap renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use")}),wi=y(pi,{name:"heatmap",description:`Label: Heat Map
156
+ Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
157
+ Keywords: density, heatmap, hot spots, pattern, cluster
158
+ Example: Create a heatmap
159
+ Fields: This typically requires zero or one field of type number.`,schema:yi});function bi(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i&&(s=_t({geometryType:t.geometryType,includedTags:i,numColors:Math.min(r.length,10)})[0]),{layer:t,view:a,fields:r.map(l=>({name:l})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function vi(e){return await Lt(e)}async function Si({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,includeSize:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:i?"predominance-size":"predominance",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=bi(c),u=await vi(d);return l.renderer=u.renderer,l.visible=!0,`Predominance renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying predominance renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ti({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Si({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,includeSize:a})}var Ei=n.object({layerId:n.string().describe("The id of the layer to apply the predominance renderer to"),fields:n.array(n.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),includeSize:n.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),xi=y(Ti,{name:"predominance",description:`Label: Predominant category
160
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
161
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
162
+ Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
163
+ Fields: This style relies on 2-10 number fields.
164
+
165
+ Label: Predominant category and Size
166
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
167
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
168
+ Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
169
+ Fields: This style relies on 2-10 number fields.`,schema:Ei});function Ii(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s={field:r[0]},l={field:r[1]};return o&&(i=Nt({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field1:s,field2:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:i}}async function $i(e){return await kt(e)}async function Fi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o}){let i=r,s=e?.allLayers.find(c=>c.id===t);if(!s)return`Could not find layer for id: ${t}`;let l={styleName:"relationship",fields:a,layer:s,view:i,colorSchemeTags:o};try{let c=Ii(l),d=await $i(c);return s.renderer=d.renderer,s.visible=!0,`Relationship renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function Li({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=F(a);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await Fi({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var _i=n.object({layerId:n.string().describe("The id of the layer to apply the relationship renderer to"),fields:n.array(n.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use")}),ki=y(Li,{name:"relationship",description:`Label: Relationship
170
+ Description: Overlays two color ramps to represent the relationship between two numeric attributes.
171
+ Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
172
+ Example: Show the relationship between tree height and carbon storage
173
+ Fields: This style requires two number fields.`,schema:_i});function Ni(e){let{fields:r,layer:t,view:a,theme:o}=e,i=r[0];return{layer:t,view:a,startTime:i,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Ai(e){return await At(e)}async function qi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"size-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Ni(c),u=await Ai(d);return l.renderer=u.renderer,l.visible=!0,`Size-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ri({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await qi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Mi=n.object({layerId:n.string().describe("The id of the layer to apply the size-age renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Ci=y(Ri,{name:"size-age",description:`Label: Age (size)
174
+ Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
175
+ Keywords: since, age, how old, how long
176
+ Example: Change the size of features so older features are larger than new features.
177
+ Fields: This style requires at least one field with a date type.`,schema:Mi});function zi(e){let{fields:r,layer:t,view:a}=e,{theme:o}=e,i=r[1],s=r[0];return{layer:t,view:a,field:s,normalizationField:i,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function ji(e){return await qt(e)}async function Vi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"size",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=zi(c),u=await ji(d);return l.renderer=u.renderer,l.visible=!0,`Size renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size renderer: ${d instanceof Error?d.message:String(d)}`}}async function Oi({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Vi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Di=n.object({layerId:n.string().describe("The id of the layer to apply the size renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Pi=y(Oi,{name:"size",description:`Label: Counts and Amounts (size)
178
+ Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
179
+ Keywords: graduated size, proportional size, how much, total, number, amount, size
180
+ Example: Vary the size of each point based on the total population.
181
+ Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.
182
+
183
+ Label: Continuous Timeline (size)
184
+ Description: Vary symbol sizes along a continuous ramp to represent dates.
185
+ Keywords: graduated size, proportional size, classed size, how much, total, number, when
186
+ Example: Vary the size of each feature based on the date a ticket was completed.
187
+ Fields: This style requires a single field with a date type.`,schema:Di});function Gi(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e;console.log("processTypeRendererParams",e);let i=r[0],s=r[1],l=r[2],c;return o&&(c=Mt({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field:i,field2:s,field3:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function Bi(e){return await Rt(e)}async function Qi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"type",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Gi(c),u=await Bi(d);return l.renderer=u.renderer,l.visible=!0,`Type renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying type renderer: ${d instanceof Error?d.message:String(d)}`}}async function Wi({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=F(o);return await x({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Qi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Ui=n.object({layerId:n.string().describe("The id of the layer to apply the type renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),Ki=y(Wi,{name:"type",description:`Label: Types (unique symbols)
188
+ Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
189
+ Keywords: categorical, category, type, unique, discrete, point of interest, region, group
190
+ Example: Color each feature based on the region it belongs to
191
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:Ui}),nt=[Po,Ko,ei,ni,hi,wi,xi,ki,Ci,Pi,Ki],Hi=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await $("navigation_intent_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await j({promptText:t,modelTier:"advanced",messages:T(e.messages),inputVariables:a,tools:nt});return await W(o,r),{...e,messages:[...e.messages,o]}};async function Ji(e,r){let t=await new M(nt).invoke({messages:T(e.messages)},r),a=t.messages.map(i=>i.text).join(`
192
+ `);await h({text:`Finished executing layer filter tool: ${a}`},r);let o=t.messages.map(i=>i.text).join(`
193
+ `);return{...e,outputMessage:o}}var st=p.Root({messages:p({reducer:_,default:()=>[]}),outputMessage:p({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
194
+
195
+ `);return o[o.length-1]?.trim()===t?e:`${e}
196
+
197
+ ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p(),selectedLayerId:p()}),Zi=async(e,r)=>(await h({text:"Exiting Layer Styling agent"},r),e),Xi=async(e,r)=>{try{await h({text:"Populating layer and field info"},r);let t=[];for(let a of e.vectorSearchFieldResults){let o=function(u){let m=l.get(u)?.layerItem;return m?[m.name&&`Name: ${m.name}`,m.title&&`Title: ${m.title}`,m.description&&`Description: ${m.description}`].filter(Boolean).join(" | "):u},{layerId:i,results:s}=a,l=w(r,"layersAndFieldsRegistry"),c=l.get(i)?.fieldRegistry;if(!c)continue;let d=t.find(u=>u.layerId===i);d||(d={layerId:i,layerSummary:o(i),fieldInfos:[]},t.push(d));for(let u of s){let m=c.get(u.name);m&&d.fieldInfos.push(m)}}return console.log("Populated layerFieldInfo:",t),await h({text:"Populated layerFieldInfo"},r),{...e,layerFieldInfo:t}}catch(t){throw await h({text:"Error populating layerFieldInfo"},r),new Error(`Error populating layerFieldInfo: ${t instanceof Error?t.message:String(t)}`)}},Yi=(e,r)=>{let t=e.vectorSearchLayerIds??[];if(t.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=r.configurable;if(console.log("hitlResponse:",a),!a||a.agentId!==De.id||a.id!=="reviewLayerSelection"){let i={agentId:De.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...t]};throw new Ie(i)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},en=(e,r)=>O(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,r),tn=()=>new k(st).addNode("requireLayerStylingServices",en).addNode("vectorSearchLayers",Mo).addNode("layerSelectionHITL",Yi).addNode("vectorSearchFields",qo).addNode("populateLayerFieldInfo",Xi).addNode("agent",Hi).addNode("tools",Ji).addNode("earlyExit",Zi).addEdge(L,"requireLayerStylingServices").addEdge("requireLayerStylingServices","vectorSearchLayers").addConditionalEdges("layerSelectionHITL",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"populateLayerFieldInfo":"earlyExit").addEdge("populateLayerFieldInfo","agent").addEdge("agent","tools").addEdge("tools",E).addEdge("earlyExit",E),rn=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.
198
+ _Example: “Color points by sales amount”_
199
+ _Example: “Show population density with a color gradient”_
200
+ _Example: “Create a relationship map between height and depth”_
201
+ _Example: “Vary circle sizes according to population”_`,De={id:"layerStyling",name:"Layer Styling Agent",description:rn,createGraph:tn,workspace:st},lt=p.Root({messages:p({reducer:_,default:()=>[]}),outputMessage:p({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
202
+
203
+ `);return o[o.length-1]?.trim()===t?e:`${e}
204
+
205
+ ${t}`},default:()=>""})}),an=e=>{if(!e||e.size===0)return"No layers available in this map.";let r=Array.from(e.values()).map(({layerItem:t,fieldRegistry:a},o)=>{let i=Array.from(a.values()).map(l=>l.name).slice(0,10).join(", "),s=a.size>10?` (and ${a.size-10} more)`:"";return`${o+1}. "${t.title}". Description: ${t.description}
206
+ Fields: ${i}${s}`}).join(`
207
+
208
+ `);return`This map contains ${e.size} layer(s):
209
+
210
+ ${r}`},on=e=>{let r=e?.list()??[];return r.length?r.map(t=>`- ${t.agent.name}: ${t.agent.description}`).join(`
211
+ `):"No agents currently available."};async function nn(e,r){let t=await $("help_prompt"),a=w(r,"layersAndFieldsRegistry"),o=w(r,"agentRegistry"),i={layerSummary:an(a),agents:on(o)},s=await J({promptText:t,messages:T(e.messages),inputVariables:i}),l=new z(s),c=[...e.messages,l],d=`${e.outputMessage}
212
+
213
+ ${s}`.trim();return{...e,messages:c,outputMessage:d}}var sn=(e,r)=>O(["agentRegistry"],"Help Agent")(e,r),ln=()=>new k(lt).addNode("requireHelpServices",sn).addNode("agent",nn).addEdge(L,"requireHelpServices").addEdge("requireHelpServices","agent").addEdge("agent",E),cn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
214
+
215
+ _Example: “Tell me about this map”_
216
+ _Example: “List all layers in this map”_
217
+ _Example: “List fields in protected areas layer”_
218
+ _Example: “What agents are available to me?”_
219
+ _Example: “What can you do?”_
220
+ _Example: “What can I ask”_
221
+
222
+ Even if the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent.
223
+
224
+ 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.
225
+ _Example: "Create a chart"_
226
+ _Example: "Create a table"_`,$l={id:"help",name:"Help Agent",description:cn,createGraph:ln,workspace:lt},Fl=p.Root({messages:p({reducer:_,default:()=>[]}),outputMessage:p({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
227
+
228
+ `);return o[o.length-1]?.trim()===t?e:`${e}
229
+
230
+ ${t}`},default:()=>""}),intent:p({reducer:(e,r)=>r})}),Z={conversationId:""},dn=["linkChartView"],un=["knowledgeGraph"];function ae(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("ArcgisKnowledgeAgent context missing");let t=dn.filter(a=>!(a in r));if(t.length)throw new Error(`Link Chart context missing: ${t.join(", ")}`);return r}function Ee(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("ArcgisKnowledgeAgent context missing");let t=un.filter(a=>!(a in r));if(t.length)throw new Error(`Knowledge Graph context missing: ${t.join(", ")}`);return r}var de=class{constructor(r){this.dataModel=r,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ue.fromDataModel(r)}},ue=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(r){let t=new e;for(let a of r.entityTypes)t.entityTypes.push(B.fromEntityType(a));for(let a of r.relationshipTypes)t.relationshipTypes.push(he.fromRelationshipType(a));return t.identifierInfo={mappingInfo:{identifierMapsTo:hn(r.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:r.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},t.spatialReference=JSON.parse(JSON.stringify(r.spatialReference)),t}},B=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(r){let t=new e;t.name=r.name,t.alias=r.alias?r.alias:void 0,t.role=mn(r.role);for(let a of r.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:fn(a.role),geometryDef:a.fieldType==="esriFieldTypeGeometry"?{geometryType:a.geometryType??"esriGeometryAny",hasM:a.hasM?a.hasM:void 0,hasZ:a.hasZ?a.hasZ:void 0}:void 0};t.properties.push(o)}return t}},he=class extends B{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(r){let t=B.fromEntityType(r);t.observedEndPoints=[];for(let a of r.endPoints)t.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return t}},hn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},mn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function fn(e){switch(e){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}async function gn(e,r,t,a){let{graphQuery:o,explanation:i}=await xe(e,r,t,a);return`Generated Graph Query:
231
+ ${o}
232
+
233
+ Explanation: ${i}`}async function xe(e,r,t,a){let o={message:e,context:new de(r)};Z.conversationId&&(o.conversationId=Z.conversationId),await h({text:"Attempting to generate a cypher query from your prompt..."},a);let i=await qe(`${t}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Re.findCredential(V.getDefault().url)?.token??""}});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});Z.conversationId||(Z.conversationId=i.data.conversationId);let s=!1,l=Date.now(),c=i.data.sequenceNumber,d="",u="",m=1;for(;!s;){await new Promise(g=>setTimeout(g,1e3)),await h({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,m)}`},a),m=m%3+1;let f=await qe(`${t}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Re.findCredential(V.getDefault().url)?.token??""}});if(f.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${f.httpStatus}`,{cause:f.data});if(f.data.context)d=f.data.context.graphQuery,u=f.data.message||"";else if(!f.data.hasMore)s=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=f.data.sequenceNumber}return{graphQuery:d,explanation:u}}function X(e,r){if(!(!e||typeof e!="object")){if(yn(e))for(let t of e.path)X(t,r);else if(pn(e))r.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let t of e)X(t,r);else if(wn(e))for(let t of Object.values(e.properties??{}))X(t,r)}}function pn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function yn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function wn(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function bn(e,r){let t=[];for(let a of[...r.dataModel.entityTypes,...r.dataModel.relationshipTypes]){let o=e.getMemberIdsByType(a.name);for(let i of o)t.push({id:i,typeName:a.name})}return t}var vn=async e=>{let r=new Map,t=e.resultRowsStream.getReader();for(;;){let{done:a,value:o}=await t.read();if(a)break;for(let i of o)for(let s of i)X(s,r)}return Array.from(r.values())};async function Sn(e,r,t,a,o){let{graphQuery:i,explanation:s}=await xe(e,r.dataModel,t,o);await h({text:`Attempting to execute query: ${i.substring(0,500)}${i.length>500?"...":""}`},o);let l=await Ct(r,new Ue({openCypherQuery:i}),{signal:o?.signal,timeout:o?.timeout}),c=await vn(l);return await h({text:`Query Results parsed into ${c.length} unique relationships and entities. Atempting to add to link chart...`},o),await a.map.addRecords(c),a.goTo(a.map.diagramNodesExtent),`Link Chart updated successfully. Cypher Query used:
234
+ ${i}
235
+
236
+ Explanation: ${s}`}async function Tn({prompt:e},r){let{knowledgeGraph:t}=Ee(r),{linkChartView:a}=ae(r),o=V.getDefault().helperServices,i=await $("arcgis_knowledge_current_lc_context"),s=bn(a.map,t),l=`${e}
237
+
238
+ ${i}${JSON.stringify(s)}`;return await Sn(l,t,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,r)}var En=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Ll=y(Tn,{name:"addRecords",description:"Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt.",schema:En});async function xn(e,r){return await r.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function In({layout:e},r){let{linkChartView:t}=ae(r);return await xn(e,t)}var $n=n.object({layout:n.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),_l=y(In,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:$n});function Fn(e,r){return r.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function Ln({setting:e},r){let{linkChartView:t}=ae(r);return Fn(e,t)}var _n=n.object({setting:n.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),kl=y(Ln,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:_n});async function kn(e,r,t,a,o){let{graphQuery:i,explanation:s}=await xe(e,r.dataModel,t,o);await h({text:`Attempting to create link chart from derived query: ${i}`},o);let l=await zt.fromCypherQuery(r,new Ue({openCypherQuery:i}));return await h({text:"Link chart created successfully, loading..."},o),a.map=l,await l.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart:
239
+ ${i}
240
+
241
+ Explanation: ${s}`}async function Nn({prompt:e},r){let{knowledgeGraph:t}=Ee(r),{linkChartView:a}=ae(r),o=V.getDefault().helperServices;return await kn(e,t,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,r)}var An=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),Nl=y(Nn,{name:"createLinkChart",description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt.",schema:An});async function qn({prompt:e},r){let{knowledgeGraph:t}=Ee(r),a=V.getDefault().helperServices;return await gn(e,t.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,r)}var Rn=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Al=y(qn,{name:"generateCypher",description:"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.",schema:Rn});var ql=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).
242
+ 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.
243
+ 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,
244
+ 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
245
+ 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.
246
+ This agent is designed to handle requests that manipulate the specific link chart.
247
+ 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,
248
+ and can alternatively use those queries to create a new link chart visualization from the results if requested.
249
+
250
+ Supported actions:
251
+ - **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.
252
+ - **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.
253
+ - **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.
254
+ - **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
255
+ - **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.
256
+
257
+ _example: "Change the layout to hierarchical-bottom-to-top"_
258
+ _example: "Apply radial-root-centric layout"_
259
+ _example: "Show nonspatial data"_
260
+ _example: "Hide nonspatial data"_
261
+ _example: "Turn off nonspatial visibility"_
262
+ _example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
263
+ _example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
264
+ _example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
265
+ _example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
266
+ _example: "Find all people who work for Microsoft and put them on a new link chart"_
267
+ _example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
268
+ _example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
269
+ _example: "Find all the products supplied by Supplier X and add them to my visualization"_
270
+ _example: "Expand the link chart from 'Entity D' to show its direct connections"_
271
+ _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
272
+ _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
273
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_`;return{a:Tl,b:El,c:xl,d:Il,e:De,f:$l}},"Graphic","geometry/Point","geometry/Extent","symbols/PictureMarkerSymbol","rest/locator","portal/Portal","config","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","rest/support/Query","geometry/operators/bufferOperator","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","rest/knowledgeGraph/GraphQueryStreaming","request","identity/IdentityManager","rest/knowledgeGraphService","WebLinkChart",a)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./BDLIIICB.js";import b from"./5XHJVBOQ.js";import{a as r,b as e}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as a,z as s}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{b:i}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-data-exploration-agent"),e(this)}};s("arcgis-assistant-data-exploration-agent",t);return t},b,c)
2
+ import c from"./BWML3XTP.js";import b from"./Z43QFN6Z.js";import{a as r,b as e}from"./WFEBJPQ4.js";import"./OJUEJ4RT.js";import"./WBSNYWJJ.js";import{v as a,z as s}from"./VG7GKLZR.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{b:i}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-data-exploration-agent"),e(this)}};s("arcgis-assistant-data-exploration-agent",t);return t},b,c)