@arcgis/ai-components 5.0.0-next.172 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/cdn/{L5SDXDWS.js → 2NGJKVKI.js} +2 -0
  2. package/dist/cdn/{XJBDOKVO.js → 3NUCOIH7.js} +1 -1
  3. package/dist/cdn/{EEDB5R5I.js → 47ISWZWF.js} +1 -1
  4. package/dist/cdn/{S2AISX2B.js → 4BCBYUA5.js} +1 -1
  5. package/dist/cdn/{X32CEQPR.js → 6EWGJPEC.js} +1 -1
  6. package/dist/cdn/{7U2D75VS.js → BZME25Z4.js} +1 -1
  7. package/dist/cdn/{X6KG7ER5.js → CHLH5JPV.js} +1 -1
  8. package/dist/cdn/{2LLHYNFN.js → DDSISLRG.js} +1 -1
  9. package/dist/cdn/{FEJ3AX3C.js → ECWTYXXJ.js} +1 -1
  10. package/dist/cdn/{RSCAEBPM.js → EFAKOLKM.js} +54 -54
  11. package/dist/cdn/{24DH2UEG.js → EFEB7MEM.js} +1 -1
  12. package/dist/cdn/{GHF3DNLD.js → IJUMNRZE.js} +1 -1
  13. package/dist/cdn/{WWTWOB2N.js → IPZPHBUD.js} +1 -1
  14. package/dist/cdn/{SWW34SX4.js → L4SPLYLI.js} +1 -1
  15. package/dist/cdn/{SCEUBKWE.js → LM63GUX3.js} +1 -1
  16. package/dist/cdn/{4GEEK3VW.js → MEF5KWID.js} +1 -1
  17. package/dist/cdn/{7GTFRRWF.js → MGKFU4HC.js} +1 -1
  18. package/dist/cdn/OI4KO2XF.js +2 -0
  19. package/dist/cdn/{ZGBJH7GR.js → Q7HZOMWK.js} +1 -1
  20. package/dist/cdn/{AIF7B65D.js → VL4VHVEB.js} +2 -0
  21. package/dist/cdn/{7KB4R4Z2.js → XCT2OBFX.js} +1 -1
  22. package/dist/cdn/index.js +1 -1
  23. package/dist/chunks/runtime.js +1 -1
  24. package/dist/components/arcgis-assistant/customElement.d.ts +25 -8
  25. package/dist/components/arcgis-assistant/customElement.js +29 -25
  26. package/dist/components/arcgis-assistant/index.js +2 -1
  27. package/dist/components/arcgis-assistant-agent/customElement.d.ts +12 -2
  28. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.d.ts +5 -0
  29. package/dist/components/arcgis-assistant-help-agent/customElement.d.ts +7 -3
  30. package/dist/components/arcgis-assistant-navigation-agent/customElement.d.ts +10 -5
  31. package/dist/docs/api.json +1 -1
  32. package/dist/docs/docs.json +1 -1
  33. package/dist/docs/vscode.html-custom-data.json +1 -1
  34. package/dist/docs/web-types.json +1 -1
  35. package/dist/utils/index.d.ts +11 -7
  36. package/package.json +7 -7
  37. package/dist/cdn/TU25CAM4.js +0 -2
@@ -1,27 +1,27 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
2
- import a from"./SCEUBKWE.js";export default $arcgis.t(([pt,ge,Be,yt,{addressToLocations:wt},O,ce,Qe,U,re,pe,ye,We,Ue,we,Ke,{createRenderer:bt},{getSchemesByTag:vt,getSchemes:St},{getBackgroundColorTheme:Re},{createAgeRenderer:Tt,createContinuousRenderer:xt},{getSchemesByTag:be},{createContinuousRenderer:Et},{createRenderer:It},{getSchemesByTag:$t},{createRenderer:Ft},{getSchemesByTag:Lt},{createRenderer:_t},{getSchemesByTag:kt},{createRenderer:Nt},{getSchemesByTag:At},{createAgeRenderer:qt,createContinuousRenderer:Rt},{createRenderer:Mt},{getSchemesByTag:Ct},He,Me,Ce,{executeQueryStreaming:zt},jt,{a:Fe,b:Le,c:P,d:ne,e:se,f:j,g:B,h:R,i:y,j:p,k:_,l:E,m:_e,n:J,o:Z,p:ke,q:k,r:N,s:n,t:h,u:I,v:Y,w:Ne,x:V}])=>{var qe=e=>Array.isArray(e)&&e.every(P),ht=e=>typeof e=="object"&&e!=null&&"messages"in e&&qe(e.messages),mt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,M=class extends ke{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 P(a)&&a.getType()==="tool"||Z(a)?a:new ne({status:"success",name:t.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||Le(a))throw a;return new ne({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(mt(e))t=[await this.runTool(e.lg_tool_call,r)];else{let i;if(qe(e))i=e;else if(ht(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(B(d)){l=d;break}}if(l==null||!B(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(Z))return Array.isArray(e)?t:{messages:t};let a=[],o=null;for(let i of t)Z(i)?i.graph===J.PARENT&&Array.isArray(i.goto)&&i.goto.every(s=>_e(s))?o?o.goto.push(...i.goto):o=new J({graph:J.PARENT,goto:i.goto}):a.push(i):a.push(Array.isArray(e)?[i]:{messages:[i]});return o&&a.push(o),a}};var Ss=p.Root({llmInputMessages:p({reducer:(e,r)=>k([],r),default:()=>[]})});var Je=p.Root({messages:p({reducer:k,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(`
2
+ import a from"./LM63GUX3.js";export default $arcgis.t(([wt,ge,Be,bt,{addressToLocations:vt},D,ue,Qe,U,oe,ye,we,We,Ue,Ke,St,{createRenderer:Tt},{getSchemesByTag:xt,getSchemes:Et},{getBackgroundColorTheme:Re},{createAgeRenderer:It,createContinuousRenderer:Ft},{getSchemesByTag:be},{createContinuousRenderer:$t},{createRenderer:Lt},{getSchemesByTag:_t},{createRenderer:kt},{getSchemesByTag:Nt},{createRenderer:At},{getSchemesByTag:qt},{createRenderer:Rt},{getSchemesByTag:Mt},{createAgeRenderer:Ct,createContinuousRenderer:zt},{createRenderer:jt},{getSchemesByTag:Vt},He,Me,Ce,{executeQueryStreaming:Ot},Dt,{a:$e,b:Le,c:P,d:le,e:ce,f:V,g:B,h:C,i:w,j:g,k:N,l:E,m:_e,n:J,o:Z,p:ke,q:A,r:q,s:n,t:h,u:F,v:Y,w:Ne,x:O}])=>{var qe=e=>Array.isArray(e)&&e.every(P),ft=e=>typeof e=="object"&&e!=null&&"messages"in e&&qe(e.messages),pt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,z=class extends ke{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 P(a)&&a.getType()==="tool"||Z(a)?a:new le({status:"success",name:t.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||Le(a))throw a;return new le({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(pt(e))t=[await this.runTool(e.lg_tool_call,r)];else{let i;if(qe(e))i=e;else if(ft(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(B(d)){l=d;break}}if(l==null||!B(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(Z))return Array.isArray(e)?t:{messages:t};let a=[],o=null;for(let i of t)Z(i)?i.graph===J.PARENT&&Array.isArray(i.goto)&&i.goto.every(s=>_e(s))?o?o.goto.push(...i.goto):o=new J({graph:J.PARENT,goto:i.goto}):a.push(i):a.push(Array.isArray(e)?[i]:{messages:[i]});return o&&a.push(o),a}};var Es=g.Root({llmInputMessages:g({reducer:(e,r)=>A([],r),default:()=>[]})});var Je=g.Root({messages:g({reducer:A,default:()=>[]}),outputMessage:g({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
4
 
5
5
  `);return o[o.length-1]?.trim()===t?e:`${e}
6
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 Vt(e,r){let t=O.getDefault().helperServices.geocode.find(T=>T.name==="ArcGIS World Geocoding Service");if(!t)throw new Error("ArcGIS World Geocoding Service not found in helperServices.");let a=t.url,o=`${ce.assetsPath?.endsWith("/")?ce.assetsPath:`${ce.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await wt(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,f=new Be({xmin:s,ymin:l,xmax:c,ymax:d,spatialReference:u}),m=(s+c)/2,g=(l+d)/2,S=new ge({x:m,y:g,spatialReference:u}),b=new yt({url:o,width:24,height:24}),v=new pt({geometry:S,symbol:b});return r.graphics.removeAll(),r.graphics.add(v),await r.goTo(f),`Successfully zoomed to: ${e}. Location coordinates: x=${m}, y=${g}, wkid=${u.wkid}`}var Ot=["mapView"];function $(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("NavigationAgent context missing");let t=Ot.filter(a=>!(a in r));if(t.length)throw new Error(`NavigationAgent context missing: ${t.join(", ")}`);return r}async function Dt({address:e},r){let{mapView:t}=$(r);return await Vt(e,t)}var Gt=n.object({address:n.string().describe("The full address or place name to locate.")}),Pt=y(Dt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Gt});async function Bt(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 Qt({bookmarkName:e},r){let{mapView:t}=$(r);return await Promise.resolve(Bt(e,t))}var Wt=R.object({bookmarkName:R.string().describe("The name of the bookmark to navigate to.")}),Ut=y(Qt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Wt});async function Kt(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 Ht({layerId:e,where:r},t){let{mapView:a}=$(t);return await Kt(e,r,a)}var Jt=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")}),Zt=y(Ht,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Jt});async function Yt(e){let r=new Be({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}=$(r);return await Yt(t)}var er=R.object({}),tr=y(Xt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:er});async function rr(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 ar(e,r){let{mapView:t}=$(r);return await rr(t)}var or=n.object({}),ir=y(ar,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:or});async function nr(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}`;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 sr({layerId:e},r){let{mapView:t}=$(r);return await nr(e,t)}var lr=R.object({layerId:R.string().describe("The id of the layer to navigate to")}),cr=y(sr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:lr});async function dr(e,r){return await r.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function ur({scale:e},r){let{mapView:t}=$(r);return await dr(e,t)}var hr=n.object({scale:n.number().describe("The map scale of the view to go to.")}),mr=y(ur,{name:"goToScale",description:"Go to the specified view scale.",schema:hr});async function fr(e,r,t){let a={target:new ge({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 gr({center:e,zoom:r,scale:t},a){let{mapView:o}=$(a);return await fr(e,o,{zoom:r,scale:t})}var pr=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.")}),yr=y(gr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:pr});async function wr(e,r){return await r.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function br({zoom:e},r){let{mapView:t}=$(r);return await wr(e,t)}var vr=n.object({zoom:n.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Sr=y(br,{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:vr}),ve=[Pt,Ut,Zt,tr,ir,cr,mr,yr,Sr],ze=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./QZJ4SRT5.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./BN4IYD74.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./M32BWJ4D.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./L5SDXDWS.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./AIF7B65D.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./I2OEGQRT.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./XOLWLHTD.js").then(e=>e.default),"../agents/layerFilter/prompts/layer_filter_prompt.md":()=>import("./Y4325EIX.js").then(e=>e.default),"../agents/layerQuery/prompts/data_query_prompt.md":()=>import("./3YA7AYJB.js").then(e=>e.default),"../agents/layerQuery/prompts/summarize_query_response_prompt.md":()=>import("./JVPRUGML.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./TBTPT64L.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./QYS2QVQH.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./IMPD5HA4.js").then(e=>e.default)});async function F(e){let r=Object.entries(ze).find(([t])=>t.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
7
+ ${t}`},default:()=>""}),intent:g({reducer:(e,r)=>r}),vectorSearchLayerResults:g({reducer:(e,r)=>r,default:()=>[]}),vectorSearchFieldResults:g({reducer:(e,r)=>r})});async function Gt(e,r){let t=D.getDefault().helperServices.geocode.find(S=>S.name==="ArcGIS World Geocoding Service");if(!t)throw new Error("ArcGIS World Geocoding Service not found in helperServices.");let a=t.url,o=`${ue.assetsPath?.endsWith("/")?ue.assetsPath:`${ue.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await vt(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,f=new Be({xmin:s,ymin:l,xmax:c,ymax:d,spatialReference:u}),m=(s+c)/2,p=(l+d)/2,T=new ge({x:m,y:p,spatialReference:u}),y=new bt({url:o,width:24,height:24}),v=new wt({geometry:T,symbol:y});return r.graphics.removeAll(),r.graphics.add(v),await r.goTo(f),`Successfully zoomed to: ${e}. Location coordinates: x=${m}, y=${p}, wkid=${u.wkid}`}var Pt=["mapView"];function $(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("NavigationAgent context missing");let t=Pt.filter(a=>!(a in r));if(t.length)throw new Error(`NavigationAgent context missing: ${t.join(", ")}`);return r}async function Bt({address:e},r){let{mapView:t}=$(r);return await Gt(e,t)}var Qt=n.object({address:n.string().describe("The full address or place name to locate.")}),Wt=w(Bt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Qt});async function Ut(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 Kt({bookmarkName:e},r){let{mapView:t}=$(r);return await Promise.resolve(Ut(e,t))}var Ht=C.object({bookmarkName:C.string().describe("The name of the bookmark to navigate to.")}),Jt=w(Kt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Ht});async function Zt(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 Yt({layerId:e,where:r},t){let{mapView:a}=$(t);return await Zt(e,r,a)}var Xt=C.object({layerId:C.string().describe("The layerId of the layer to zoom to."),where:C.string().describe("The sql-92 where clause used to query features to zoom to")}),er=w(Yt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Xt});async function tr(e){let r=new Be({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 rr(e,r){let{mapView:t}=$(r);return await tr(t)}var ar=C.object({}),or=w(rr,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ar});async function ir(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 nr(e,r){let{mapView:t}=$(r);return await ir(t)}var sr=n.object({}),lr=w(nr,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:sr});async function cr(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}`;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 dr({layerId:e},r){let{mapView:t}=$(r);return await cr(e,t)}var ur=C.object({layerId:C.string().describe("The id of the layer to navigate to")}),hr=w(dr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:ur});async function mr(e,r){return await r.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function fr({scale:e},r){let{mapView:t}=$(r);return await mr(e,t)}var pr=n.object({scale:n.number().describe("The map scale of the view to go to.")}),gr=w(fr,{name:"goToScale",description:"Go to the specified view scale.",schema:pr});async function yr(e,r,t){let a={target:new ge({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 wr({center:e,zoom:r,scale:t},a){let{mapView:o}=$(a);return await yr(e,o,{zoom:r,scale:t})}var br=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.")}),vr=w(wr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:br});async function Sr(e,r){return await r.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function Tr({zoom:e},r){let{mapView:t}=$(r);return await Sr(e,t)}var xr=n.object({zoom:n.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Er=w(Tr,{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:xr}),ve=[Wt,Jt,er,or,lr,hr,gr,vr,Er],ze=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./QZJ4SRT5.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./BN4IYD74.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./M32BWJ4D.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./2NGJKVKI.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./VL4VHVEB.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./I2OEGQRT.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./XOLWLHTD.js").then(e=>e.default),"../agents/layerFilter/prompts/layer_filter_prompt.md":()=>import("./Y4325EIX.js").then(e=>e.default),"../agents/layerQuery/prompts/data_query_prompt.md":()=>import("./3YA7AYJB.js").then(e=>e.default),"../agents/layerQuery/prompts/summarize_query_response_prompt.md":()=>import("./JVPRUGML.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./TBTPT64L.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./QYS2QVQH.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./IMPD5HA4.js").then(e=>e.default)});async function L(e){let r=Object.entries(ze).find(([t])=>t.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
8
8
  Available prompts:
9
9
  ${Object.keys(ze).join(`
10
- `)}`);return await r[1]()}var Tr=(e,r=3)=>e.filter(t=>t instanceof se).slice(-r),x=(e,r=3)=>{let t=e.map((o,i)=>o instanceof se?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)},A=(e,r=" ")=>Tr(e).map(t=>t.content).join(r).trim();async function xr(e,r){let t=await F("navigation_tool_prompt"),{mapView:a}=$(r),o=a.map,i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((S,b)=>`${b+1}. layerId=${S.id} | title=${S.title??""} | name=${S.name??""} | score=${S.score.toFixed(2)}`).join(`
10
+ `)}`);return await r[1]()}var Ir=(e,r=3)=>e.filter(t=>t instanceof ce).slice(-r),x=(e,r=3)=>{let t=e.map((o,i)=>o instanceof ce?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)},R=(e,r=" ")=>Ir(e).map(t=>t.content).join(r).trim();async function Fr(e,r){let t=await L("navigation_tool_prompt"),{mapView:a}=$(r),o=a.map,i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((T,y)=>`${y+1}. layerId=${T.id} | title=${T.title??""} | name=${T.name??""} | score=${T.score.toFixed(2)}`).join(`
11
11
  `):"",s=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",l=e.intent==="goToBookmark"&&o.bookmarks?.length?`Available bookmarks:
12
12
  ${JSON.stringify(o.bookmarks,null,2)}`:"",c=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
13
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},f=await V({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:u,tools:ve}),m=[...e.messages,f],g=(f.tool_calls?.length??0)>0?[...m]:[...m,f];return{...e,messages:g}}async function Er(e,r){let t=await new M(ve).invoke({messages:x(e.messages)},r),a=t.messages.map(s=>s.text).join(`
14
+ ${s}`:"",u={intent:e.intent,bookmarksSection:l,layersSection:c,fieldsSection:d,currentZoom:a.zoom},f=await O({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:u,tools:ve}),m=[...e.messages,f],p=(f.tool_calls?.length??0)>0?[...m]:[...m,f];return{...e,messages:p}}async function $r(e,r){let t=await new z(ve).invoke({messages:x(e.messages)},r),a=t.messages.map(s=>s.text).join(`
15
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 Ir(e,r){let t=await F("navigation_intent_prompt"),{mapView:a}=$(r),o=ve.map(f=>({name:f.name,description:f.description,schema:f.schema})),i=a.map,s=i.bookmarks?.length?`Available bookmarks:
17
- ${JSON.stringify(i.bookmarks,null,2)}`:"",l={tools:o.map(({name:f,description:m,schema:g})=>`${f}: ${m}, ${JSON.stringify(g)}`).join(`
18
- `),bookmarks:s},c=n.object({intent:n.string()}),d=await Ne({promptText:t,messages:x(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},$r=.7,Fr=async(e,r)=>{try{let t=A(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:$r,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:
16
+ `);return{...e,messages:o,outputMessage:i}}async function Lr(e,r){let t=await L("navigation_intent_prompt"),{mapView:a}=$(r),o=ve.map(f=>({name:f.name,description:f.description,schema:f.schema})),i=a.map,s=i.bookmarks?.length?`Available bookmarks:
17
+ ${JSON.stringify(i.bookmarks,null,2)}`:"",l={tools:o.map(({name:f,description:m,schema:p})=>`${f}: ${m}, ${JSON.stringify(p)}`).join(`
18
+ `),bookmarks:s},c=n.object({intent:n.string()}),d=await Ne({promptText:t,messages:x(e.messages),inputVariables:l,schema:c}),u=typeof d.intent=="string"?d.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var b=(e,r)=>{let t=e?.configurable?.services?.[r];if(t==null)throw new Error(`${r} missing in config.configurable.services`);return t},_r=.7,kr=async(e,r)=>{try{let t=R(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=(await a.searchLayers({text:t,minScore:_r,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
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}},je=.7,Lr=10,_r=async(e,r)=>{try{let t=A(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:je,topResults:Lr,embeddingCache:i})).map(({layerId:d,results:u})=>{let f=o.get(d)?.fieldRegistry;return{layerId:d,layerName:o.get(d)?.layerItem.name,results:u.map(m=>{let g=f?.get(m.name);return{name:m.name,score:m.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:
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}},je=.7,Nr=10,Ar=async(e,r)=>{try{let t=R(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(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:je,topResults:Nr,embeddingCache:i})).map(({layerId:d,results:u})=>{let f=o.get(d)?.fieldRegistry;return{layerId:d,layerName:o.get(d)?.layerItem.name,results:u.map(m=>{let p=f?.get(m.name);return{name:m.name,score:m.score,type:p?.type,alias:p?.alias,description:p?.description,statistics:p?.statistics}})}}),c;return l.length>0?c=`Vector search completed. Matching layers and fields:
21
21
  ${l.map(d=>`${d.layerName??d.layerId}:
22
22
  ${d.results.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
23
23
  `)}`).join(`
24
- `)}`:c=`No vector search field results found for score over ${je}.`,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}},D=(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},kr=(e,r)=>D(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,r),Nr=()=>new N(Je).addNode("requireNavigationServices",kr).addNode("intentLLM",Ir).addNode("vectorSearchLayers",Fr).addNode("vectorSearchFields",_r).addNode("agent",xr).addNode("tools",Er).addEdge(_,"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),Ar=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
24
+ `)}`:c=`No vector search field results found for score over ${je}.`,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}},G=(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},qr=(e,r)=>G(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,r),Rr=()=>new q(Je).addNode("requireNavigationServices",qr).addNode("intentLLM",Lr).addNode("vectorSearchLayers",kr).addNode("vectorSearchFields",Ar).addNode("agent",Fr).addNode("tools",$r).addEdge(N,"requireNavigationServices").addEdge("requireNavigationServices","intentLLM").addConditionalEdges("intentLLM",e=>e.intent==="goToLayer"||e.intent==="goToFeatures"?"vectorSearchLayers":"agent",{vectorSearchLayers:"vectorSearchLayers",agent:"agent"}).addConditionalEdges("vectorSearchLayers",e=>e.intent==="goToFeatures"?"vectorSearchFields":"agent",{vectorSearchFields:"vectorSearchFields",agent:"agent"}).addEdge("vectorSearchFields","agent").addEdge("agent","tools").addEdge("tools",E),Mr=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
25
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
26
 
27
27
  Supported actions:
@@ -40,11 +40,11 @@ ${d.results.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
40
40
  _Example: “Center the map on San Francisco at scale 50000”_
41
41
  _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
42
42
  _Example: “Go to the Downtown bookmark”_
43
- _Example: “Where is Mount Rainier?”_`,xl={id:"navigation",name:"Navigation Agent",description:Ar,createGraph:Nr,workspace:Je},Ze=p.Root({messages:p({reducer:k,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(`
43
+ _Example: “Where is Mount Rainier?”_`,Fl={id:"navigation",name:"Navigation Agent",description:Mr,createGraph:Rr,workspace:Je},Ze=g.Root({messages:g({reducer:A,default:()=>[]}),outputMessage:g({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
44
 
45
45
  `);return o[o.length-1]?.trim()===t?e:`${e}
46
46
 
47
- ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p(),queryResponse:p()}),qr=async(e,r)=>(await h({text:"Exiting Data Exploration agent"},r),e),K=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)))},Rr=["mapView"];function C(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("DataExplorationAgent context missing");let t=Rr.filter(a=>!(a in r));if(t.length)throw new Error(`DataExplorationAgent context missing: ${t.join(", ")}`);return r}var Mr=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."},Cr=async(e,r)=>{let{mapView:t}=C(r);return Mr(t)},zr=y(Cr,{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({})}),jr=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."},Vr=async(e,r)=>{let{mapView:t}=C(r);return await jr(t)},Or=y(Vr,{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 te(e){return"point"in e&&e.point!==void 0}function Q(e){return"layerId"in e&&e.layerId!==void 0}var ae=async(e,r)=>{if(te(e)){let{point:t}=e;return{geometry:new ge({x:t.x,y:t.y,spatialReference:t.spatialReference?{wkid:t.spatialReference.wkid}:r.spatialReference})}}if(Q(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=re.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"}},Dr=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)}}},Gr=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 ae(o,r);if("error"in u)return u.error;l=u.geometry}if(s.featureEffect=null,s.featureEffect=new Qe({filter:new U({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 Dr(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"],q=n.enum(Pr),Br=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 Gr(e,s,a,o,r,t)},Qr=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:q.optional().describe("The units for the distance buffer.")}),Wr=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:q.optional().describe("The units for the distance buffer.")}),Ur=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([Qr,Wr]).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.")}),Kr=y(Br,{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:Ur}),ue=(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},Hr=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},Jr=async(e,r,t,a)=>{let o=a.map?.allLayers.find(d=>d.id===e),i=Hr(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null,c=ue(r,l,o)||l;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${c}`,details:{fieldName:r,value:c,where:t.where}}};async function Zr({layerId:e,fieldName:r,query:t},a){let{mapView:o}=C(a),i=await Jr(e,r,t,o);return JSON.stringify(i,null,2)}var Yr=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(Zr,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Yr}),Se=(e,r,t)=>t?e.hasAllFeaturesInView&&e.availableFields===r:e.hasAllFeatures&&e.availableFields===r,ea=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryFilter:s}=e,l=o.map?.allLayers.find(T=>T.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),u=d?.alias;if(!d)throw new Error(`Field '${t}' not found.`);let f,m;if(s){let T=await ae(s,o);if("error"in T)throw new Error(T.error);if(!T.geometry)throw Q(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");Q(s)?f={geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}:te(s)&&(f={point:s.point,distance:s.distance,units:s.units,applied:!0}),m=new U({geometry:T.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let g=Se(c,[t],!1),S=null,b=null,v=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{let T={layer:l,useFeaturesInView:g,view:g?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m},outStatisticTypes:{include:[a]}};S=await pe(T),["string","small-integer","integer"].includes(d.type)&&(b=(await ye({layer:l,useFeaturesInView:g,view:g?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m}})).uniqueValueInfos.sort((G,z)=>z.count-G.count).slice(0,v))}catch(T){console.error("Statistics error:",T)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof S?.[a]=="number"?S[a]:"N/A"}`,details:{fieldName:t,fieldAlias:u,statisticType:a,statistic:S?.[a]??null,summaryStatistics:S,uniqueValues:b,where:r.where,spatialFilterInfo:f}}};async function ta({targetLayer:e,fieldName:r,statisticType:t,geometryFilter:a},o){let i=w(o,"layersAndFieldsRegistry"),{mapView:s}=C(o),l=await ea({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryFilter:a});return JSON.stringify(l,null,2)}var ra=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:q.optional().describe("The units for the distance buffer.")}),aa=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:q.optional().describe("The units for the distance buffer.")}),oa=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([ra,aa]).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.")}),ia=y(ta,{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.
47
+ ${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponse:g()}),Cr=async(e,r)=>(await h({text:"Exiting Data Exploration agent"},r),e),K=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)))},zr=["mapView"];function j(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("DataExplorationAgent context missing");let t=zr.filter(a=>!(a in r));if(t.length)throw new Error(`DataExplorationAgent context missing: ${t.join(", ")}`);return r}var jr=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."},Vr=async(e,r)=>{let{mapView:t}=j(r);return jr(t)},Or=w(Vr,{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({})}),Dr=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."},Gr=async(e,r)=>{let{mapView:t}=j(r);return await Dr(t)},Pr=w(Gr,{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 te(e){return"point"in e&&e.point!==void 0}function Q(e){return"layerId"in e&&e.layerId!==void 0}var ie=async(e,r)=>{if(te(e)){let{point:t}=e;return{geometry:new ge({x:t.x,y:t.y,spatialReference:t.spatialReference?{wkid:t.spatialReference.wkid}:r.spatialReference})}}if(Q(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=oe.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"}},Br=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)}}},Qr=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 ie(o,r);if("error"in u)return u.error;l=u.geometry}if(s.featureEffect=null,s.featureEffect=new Qe({filter:new U({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 Br(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}`},Wr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],M=n.enum(Wr),Ur=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}=j(i);return await Qr(e,s,a,o,r,t)},Kr=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:M.optional().describe("The units for the distance buffer.")}),Hr=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:M.optional().describe("The units for the distance buffer.")}),Jr=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([Kr,Hr]).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.")}),Zr=w(Ur,{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:Jr}),re=(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},Yr=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},Xr=async(e,r,t,a)=>{let o=a.map?.allLayers.find(d=>d.id===e),i=Yr(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null,c=re(r,l,o)||l;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${c}`,details:{fieldName:r,value:c,where:t.where}}};async function ea({layerId:e,fieldName:r,query:t},a){let{mapView:o}=j(a),i=await Xr(e,r,t,o);return JSON.stringify(i,null,2)}var ta=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.")})}),ra=w(ea,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:ta}),Se=(e,r,t)=>t?e.hasAllFeaturesInView&&e.availableFields===r:e.hasAllFeatures&&e.availableFields===r;function ae(e,r){let t=e??"";return r!=null&&r&&(t=t?`(${t}) AND (${r})`:r),t||null}var aa=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),u=d?.alias;if(!d)throw new Error(`Field '${t}' not found.`);let f,m;if(s){let S=await ie(s,o);if("error"in S)throw new Error(S.error);if(!S.geometry)throw Q(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");Q(s)?f={geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}:te(s)&&(f={point:s.point,distance:s.distance,units:s.units,applied:!0}),m=new U({geometry:S.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let p=Se(c,[t],!1),T=null,y=null,v=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{let S={layer:l,useFeaturesInView:p,view:p?o:void 0,field:t,sqlWhere:ae(l.definitionExpression,r.where),...m&&{filter:m},outStatisticTypes:{include:[a]}};T=await ye(S),["string","small-integer","integer"].includes(d.type)&&(y=(await we({layer:l,useFeaturesInView:p,view:p?o:void 0,field:t,sqlWhere:ae(l.definitionExpression,r.where),...m&&{filter:m}})).uniqueValueInfos.sort((I,k)=>k.count-I.count).slice(0,v))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof T?.[a]=="number"?T[a]:"N/A"}`,details:{fieldName:t,fieldAlias:u,statisticType:a,statistic:T?.[a]??null,summaryStatistics:T,uniqueValues:y,where:r.where,spatialFilterInfo:f}}};async function oa({targetLayer:e,fieldName:r,statisticType:t,geometryFilter:a},o){let i=b(o,"layersAndFieldsRegistry"),{mapView:s}=j(o),l=await aa({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryFilter:a});return JSON.stringify(l,null,2)}var ia=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:M.optional().describe("The units for the distance buffer.")}),na=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:M.optional().describe("The units for the distance buffer.")}),sa=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([ia,na]).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.")}),la=w(oa,{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
48
 
49
49
  USE THIS TOOL FOR:
50
50
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -56,7 +56,7 @@ DO NOT USE FOR:
56
56
  - "Show / list / find features" \u2014 use queryFeatures instead
57
57
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
58
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:oa}),na=async(e,r,t,a,o)=>{let i=t.map?.allLayers.find(m=>m.id===e.layerId),s=await t.whenLayerView(i),l=i.title??e.layerId,c;if(a){let m=await ae(a,t);if("error"in m)return{tool:"getTopFeatures",layerName:l,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:l,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};c=m.geometry}else o&&(c=t.extent.clone());let d=r.groupByFields&&r.groupByFields.length>0,u=i.objectIdField,f=e.outFields.length>2?e.outFields:["*"];!f.includes("*")&&!f.includes(u)&&f.push(u);try{let m;if(d){let b=new We({where:e.where||"1=1",outFields:f,orderByFields:e.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new Ue({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})});m=await i.queryTopFeatures(b)}else{let b=new we({where:e.where||"1=1",outFields:f,orderByFields:r.orderByFields,num:r.topCount,geometry:c,spatialRelationship:c?"intersects":void 0,distance:a?.distance,units:a?.units,outSpatialReference:t.spatialReference}),v=Se(s,e.outFields,o??!1);try{m=v?await s.queryFeatures(b):await i.queryFeatures(b)}catch(T){console.warn("Client-side query failed, falling back to server:",T),m=await i.queryFeatures(b)}}let g=m.features.map(b=>b.attributes),S=m.features.map(b=>b.attributes[u]);return{tool:"getTopFeatures",layerName:l,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,attributes:g,objectIds:S,objectIdField:u,where:e.where,orderByFields:r.orderByFields,...d&&{groupByFields:r.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:l,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},sa=async({targetLayer:e,topFilter:r,geometryFilter:t,useCurrentExtent:a},o)=>{let{mapView:i}=C(o),s=await na(e,r,i,t,a);return JSON.stringify(s,null,2)},la=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:q.optional().describe("The units for the distance buffer.")}),ca=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:q.optional().describe("The units for the distance buffer.")}),da=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([la,ca]).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."))}),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).")}),ua=y(sa,{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:da}),de=25,ha=async(e,r,t,a)=>{let o=r.map?.allLayers.find(b=>b.id===e.layerId),i=await r.whenLayerView(o),s=o.title??e.layerId,l;if(t){let b=await ae(t,r);if("error"in b){let v={error:b.error};return Q(t)?(v.geometryLayerId=t.layerId,v.geometryWhere=t.where):te(t)&&(v.point=t.point),{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:v}}if(!b.geometry){let v={};return Q(t)?(v.error=`No features found matching: ${t.where}`,v.geometryLayerId=t.layerId,v.geometryWhere=t.where):te(t)&&(v.error="Failed to create point geometry",v.point=t.point),{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:v}}l=b.geometry}else a&&(l=r.extent.clone());let c=Se(i,e.outFields,a??!1),d=new we({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,f;try{u=c?await i.queryFeatureCount(d):await o.queryFeatureCount(d),u>0&&u<=de&&(f=c?await i.queryFeatures(d):await o.queryFeatures(d),f&&f.features.forEach(b=>{let v=b.attributes;o.fields.forEach(T=>{let G=v[T.name],z=ue(T.name,G,o);z&&(v[T.name]=z)})}))}catch(b){console.warn("Client-side query failed, falling back to server:",b),u=await o.queryFeatureCount(d),u>0&&u<=de&&(f=await o.queryFeatures(d),f&&f.features.forEach(v=>{o.fields.forEach(T=>{let G=v.attributes[T.name],z=ue(T.name,G,o);z&&(v.attributes[T.name]=z)})}))}let m=o.objectIdField,g=f?.features.map(b=>b.attributes[m]),S=f?.features.map(b=>b.attributes);return{tool:"queryFeatures",layerName:s,summary:`${u} features found`,details:{totalCount:u,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...g&&{objectIds:g,objectIdField:m},...S&&{attributes:S},...u>de&&{note:`${u} features found.`}}}};async function ma({targetLayer:e,geometryFilter:r,useCurrentExtent:t},a){let{mapView:o}=C(a),i=await ha(e,o,r,t);return JSON.stringify(i,null,2)}var fa=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:q.optional().describe("The units for the distance buffer.")}),ga=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:q.optional().describe("The units for the distance buffer.")}),pa=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([fa,ga]).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).")}),ya=y(ma,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
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:sa}),ca=async(e,r,t,a,o)=>{let i=t.map?.allLayers.find(m=>m.id===e.layerId),s=await t.whenLayerView(i),l=i.title??e.layerId,c;if(a){let m=await ie(a,t);if("error"in m)return{tool:"getTopFeatures",layerName:l,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:l,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};c=m.geometry}else o&&(c=t.extent.clone());let d=r.groupByFields&&r.groupByFields.length>0,u=i.objectIdField,f=e.outFields.length>2?e.outFields:["*"];!f.includes("*")&&!f.includes(u)&&f.push(u);try{let m;if(d){let y=new We({where:e.where||"1=1",outFields:f,orderByFields:e.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new Ue({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})});m=await i.queryTopFeatures(y)}else{let y=i.createQuery();y.where=ae(i.definitionExpression,e.where||"1=1"),y.outFields=f,y.orderByFields=r.orderByFields,y.num=r.topCount,c&&(y.geometry=c,y.spatialRelationship="intersects"),a?.distance&&(y.distance=a.distance),a?.units&&(y.units=a.units),y.outSpatialReference=t.spatialReference;let v=Se(s,e.outFields,o??!1);try{m=v?await s.queryFeatures(y):await i.queryFeatures(y)}catch(S){console.warn("Client-side query failed, falling back to server:",S),m=await i.queryFeatures(y)}}let p=m.features.map(y=>y.attributes[u]),T=m.features.map(y=>{let v=y.attributes,S={};return i.fields.forEach(I=>{if(I.name===i.objectIdField){S[I.name]=v[I.name];return}let k=v[I.name],ut=re(I.name,k,i),ht=I.alias||I.name;S[ht]=ut??k}),S});return{tool:"getTopFeatures",layerName:l,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,attributes:T,objectIds:p,objectIdField:u,where:e.where,orderByFields:r.orderByFields,...d&&{groupByFields:r.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:l,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},da=async({targetLayer:e,topFilter:r,geometryFilter:t,useCurrentExtent:a},o)=>{let{mapView:i}=j(o),s=await ca(e,r,i,t,a);return JSON.stringify(s,null,2)},ua=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:M.optional().describe("The units for the distance buffer.")}),ha=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:M.optional().describe("The units for the distance buffer.")}),ma=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([ua,ha]).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."))}),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).")}),fa=w(da,{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:ma}),he=25,pa=async(e,r,t,a)=>{let o=r.map?.allLayers.find(y=>y.id===e.layerId),i=await r.whenLayerView(o),s=o.title??e.layerId,l;if(t){let y=await ie(t,r);if("error"in y){let v={error:y.error};return Q(t)?(v.geometryLayerId=t.layerId,v.geometryWhere=t.where):te(t)&&(v.point=t.point),{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:v}}if(!y.geometry){let v={};return Q(t)?(v.error=`No features found matching: ${t.where}`,v.geometryLayerId=t.layerId,v.geometryWhere=t.where):te(t)&&(v.error="Failed to create point geometry",v.point=t.point),{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:v}}l=y.geometry}else a&&(l=r.extent.clone());let c=Se(i,e.outFields,a??!1),d=o.createQuery();d.where=ae(o.definitionExpression,e.where||"1=1"),d.outFields=e.outFields.length?e.outFields:["*"],d.orderByFields=e.orderByFields,l&&(d.geometry=l,d.spatialRelationship="intersects"),t?.distance&&(d.distance=t.distance),t?.units&&(d.units=t.units),d.outSpatialReference=r.spatialReference;let u,f;try{u=c?await i.queryFeatureCount(d):await o.queryFeatureCount(d),u>0&&u<=he&&(f=c?await i.queryFeatures(d):await o.queryFeatures(d),f&&f.features.forEach(y=>{let v=y.attributes;o.fields.forEach(S=>{let I=v[S.name],k=re(S.name,I,o);k&&(v[S.name]=k)})}))}catch(y){console.warn("Client-side query failed, falling back to server:",y),u=await o.queryFeatureCount(d),u>0&&u<=he&&(f=await o.queryFeatures(d),f&&f.features.forEach(v=>{o.fields.forEach(S=>{let I=v.attributes[S.name],k=re(S.name,I,o);k&&(v.attributes[S.name]=k)})}))}let m=o.objectIdField,p=f?.features.map(y=>y.attributes[m]),T=f?.features.map(y=>y.attributes);return{tool:"queryFeatures",layerName:s,summary:`${u} features found`,details:{totalCount:u,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...p&&{objectIds:p,objectIdField:m},...T&&{attributes:T},...u>he&&{note:`${u} features found.`}}}};async function ga({targetLayer:e,geometryFilter:r,useCurrentExtent:t},a){let{mapView:o}=j(a),i=await pa(e,o,r,t);return JSON.stringify(i,null,2)}var ya=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:M.optional().describe("The units for the distance buffer.")}),wa=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:M.optional().describe("The units for the distance buffer.")}),ba=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([ya,wa]).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).")}),va=w(ga,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
60
60
 
61
61
  USE THIS TOOL FOR:
62
62
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -65,13 +65,13 @@ USE THIS TOOL FOR:
65
65
  - Spatial queries \u2014 finding features near/within/intersecting other features
66
66
  - Any question where the user wants to SEE or COUNT matching features
67
67
 
68
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:pa}),Ye=[Xr,ia,ua,ya],Xe=[Kr,Or,zr],oe=()=>{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}},wa=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await F("data_explore_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=oe(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,queryResponse:e.queryResponse},s=await V({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:Xe}),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 K(s,r),{...e,messages:c,outputMessage:d}},ba=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("data_explore_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=oe(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await V({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:Ye}),l=[...e.messages,s],c=s.content.toString();return await K(s,r),{...e,messages:l,outputMessage:c}},va=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await F("summarize_query_response_prompt"),a={queryResponse:e.queryResponse},o=await Y({promptText:t,messages:x(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content,s=new j(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 Sa(e,r){let t=await new M(Xe).invoke({messages:x(e.messages)},r),a=[...e.messages,...t.messages],o=t.messages.map(s=>new j({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 Ta=new M(Ye);async function xa(e,r){let{messages:t}=await Ta.invoke({messages:x(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,Ia=async(e,r)=>{let t=null,a=null;try{r.type!=="geometry"&&r.type!=="oid"&&r.type!=="global-id"&&(t=await pe({layer:e,field:r.name}),r.type==="string"&&(a=(await ye({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 Te(e,r,t){let a=[],o=[];for(let i of e){let s=function(m){let g=r.get(m)?.layerItem;return g?[g.name&&`Name: ${g.name}`,g.title&&`Title: ${g.title}`,g.description&&`Description: ${g.description}`].filter(Boolean).join(" | "):m},{layerId:l,results:c}=i,d=t.map?.allLayers.find(m=>m.id===l),u=r.get(l)?.fieldRegistry;if(!u)continue;let f=a.find(m=>m.layerId===l);f||(f={layerId:l,layerSummary:s(l),fieldInfos:[]},a.push(f));for(let m of c){let g=u.get(m.name);if(g){if(!g.statistics){let S=Ia(d,g).then(b=>{u.set(g.name,{...g,statistics:b}),g.statistics=b});o.push(S)}f.fieldInfos.push(g)}}}return await Promise.all(o),a}var $a=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 Te(e.vectorSearchFieldResults,t,a);return 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,Fa=10,La=async(e,r)=>{try{let t=A(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:Fa,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
68
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:ba}),Ye=[ra,la,fa,va],Xe=[Zr,Pr,Or],ne=()=>{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}},Sa=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await L("data_explore_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=ne(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,queryResponse:e.queryResponse},s=await O({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:Xe}),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 K(s,r),{...e,messages:c,outputMessage:d}},Ta=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await L("data_explore_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=ne(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await O({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:Ye}),l=[...e.messages,s],c=s.content.toString();return await K(s,r),{...e,messages:l,outputMessage:c}},xa=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await L("summarize_query_response_prompt"),a={queryResponse:e.queryResponse},o=await Y({promptText:t,messages:x(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content,s=new V(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 Ea(e,r){let t=await new z(Xe).invoke({messages:x(e.messages)},r),a=[...e.messages,...t.messages],o=t.messages.map(s=>new V({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 Ia=new z(Ye);async function Fa(e,r){let{messages:t}=await Ia.invoke({messages:x(e.messages)},r),a=[],o=[];for(let s of t){let l=s.content,c;typeof l!="string"&&(c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:l}});try{typeof l=="string"?c=JSON.parse(l):c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw: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 $a=10,La=async(e,r)=>{let t=null,a=null;try{r.type!=="geometry"&&r.type!=="oid"&&r.type!=="global-id"&&(t=await ye({layer:e,field:r.name}),r.type==="string"&&(a=(await we({layer:e,field:r.name})).uniqueValueInfos.sort((o,i)=>i.count-o.count).slice(0,$a)))}catch(o){console.error(`Error fetching statistics for field ${r.name}:`,o)}return{summaryStatistics:t,uniqueValues:a}};async function Te(e,r,t){let a=[],o=[];for(let i of e){let s=function(m){let p=r.get(m)?.layerItem;return p?[p.name&&`Name: ${p.name}`,p.title&&`Title: ${p.title}`,p.description&&`Description: ${p.description}`].filter(Boolean).join(" | "):m},{layerId:l,results:c}=i,d=t.map?.allLayers.find(m=>m.id===l),u=r.get(l)?.fieldRegistry;if(!u)continue;let f=a.find(m=>m.layerId===l);f||(f={layerId:l,layerSummary:s(l),fieldInfos:[]},a.push(f));for(let m of c){let p=u.get(m.name);if(p){if(!p.statistics){let T=La(d,p).then(y=>{u.set(p.name,{...p,statistics:y}),p.statistics=y});o.push(T)}f.fieldInfos.push(p)}}}return await Promise.all(o),a}var _a=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=b(r,"layersAndFieldsRegistry"),{mapView:a}=j(r),o=await Te(e.vectorSearchFieldResults,t,a);return 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,ka=10,Na=async(e,r)=>{try{let t=R(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:Ve,topResults:ka,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
69
69
  `);return`${o.get(d)?.layerItem.name??d}:
70
70
  ${f}`}).join(`
71
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 ${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)}`)}},_a=.7,ka=async(e,r)=>{try{let t=A(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:_a,embeddingCache:i}),l=s.map(u=>u.id),c=s.map(({id:u,score:f})=>`${o.get(u)?.layerItem.name??u} (${f.toFixed(2)})`).join(`
72
+ ${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)}`)}},Aa=.7,qa=async(e,r)=>{try{let t=R(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchLayers({text:t,minScore:Aa,embeddingCache:i}),l=s.map(u=>u.id),c=s.map(({id:u,score:f})=>`${o.get(u)?.layerItem.name??u} (${f.toFixed(2)})`).join(`
73
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)}`)}},Na=(e,r)=>D(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,r),Aa=()=>new N(Ze).addNode("requireDataExplorationServices",Na).addNode("vectorSearchLayers",ka).addNode("vectorSearchFields",La).addNode("fieldStatistics",$a).addNode("queryAgent",ba).addNode("queryTools",xa).addNode("summarizeQueryResponseLLM",va).addNode("filterAgent",wa).addNode("filterTools",Sa).addNode("earlyExit",qr).addEdge(_,"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),qa=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).
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)}`)}},Ra=(e,r)=>G(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,r),Ma=()=>new q(Ze).addNode("requireDataExplorationServices",Ra).addNode("vectorSearchLayers",qa).addNode("vectorSearchFields",Na).addNode("fieldStatistics",_a).addNode("queryAgent",Ta).addNode("queryTools",Fa).addNode("summarizeQueryResponseLLM",xa).addNode("filterAgent",Sa).addNode("filterTools",Ea).addNode("earlyExit",Cr).addEdge(N,"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),Ca=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
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
76
  _Example: “Only show stations where Brand is Shell”_
77
77
  _Example: “Make Shell stations stand out on the map”_
@@ -79,47 +79,47 @@ ${c}`:d="Vector search completed. No matching layers found.",await h({text:d},r)
79
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
80
  _Example: “How many features are there?”_
81
81
  _Example: “What’s the average population?”_
82
- _Example: “Which values are in the status field?”_`,El={id:"dataExploration",name:"Data Exploration Agent",description:qa,createGraph:Aa,workspace:Ze},Oe=.7,Ra=10,Ma=async(e,r)=>{try{let t=A(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:Ra,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
82
+ _Example: “Which values are in the status field?”_`,$l={id:"dataExploration",name:"Data Exploration Agent",description:Ca,createGraph:Ma,workspace:Ze},Oe=.7,za=10,ja=async(e,r)=>{try{let t=R(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:Oe,topResults:za,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
83
83
  `);return`${o.get(d)?.layerItem.name??d}:
84
84
  ${f}`}).join(`
85
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 ${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)}`)}},Ca=.7,za=async(e,r)=>{try{let t=A(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:Ca}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
86
+ ${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)}`)}},Va=.7,Oa=async(e,r)=>{try{let t=R(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:Va}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
87
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)}`)}},et=["mapView"];function xe(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerFilterAgent context missing");let t=et.filter(a=>!(a in r));if(t.length)throw new Error(`LayerFilterAgent context missing: ${t.join(", ")}`);return r}var ja=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=w(r,"layersAndFieldsRegistry"),{mapView:a}=xe(r),o=await Te(e.vectorSearchFieldResults,t,a);return 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)}`)}},tt=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)},rt=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=re.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},Va=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 rt(o,r);if("error"in l)return l.error;s=l.geometry}return i.featureEffect=new Qe({filter:new U({where:e.where,geometry:s,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:t,excludedEffect:a}),i.visible=!0,i.refresh(),tt(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}"`:""}.`},Oa=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],at=n.enum(Oa),Da=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}=xe(o);return await Va(e,i,t,a,r)},Ga=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:at.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(Da,{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:Ga}),Ba=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 rt(t,r);if("error"in s)return s.error;o=s.geometry}let i=await r.whenLayerView(a);return i.filter=new U({where:e.where,geometry:o,spatialRelationship:"intersects",distance:t?.distance,units:t?.units}),a.visible=!0,tt(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}"`:""}.`},Qa=async({targetLayer:e,geometryLayer:r},t)=>{let{mapView:a}=xe(t);return await Ba(e,a,r)},Wa=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:at.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Ua=y(Qa,{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:Wa}),ot=[Pa,Ua],Ka=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await F("layer_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=oe(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await V({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:ot}),l=s.content.toString();return await K(s,r),{...e,messages:[...e.messages,s],outputMessage:l}};async function Ha(e,r){let t=await new M(ot).invoke({messages:x(e.messages)},r),a=t.messages.map(s=>s.text).join(`
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)}`)}},et=["mapView"];function xe(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerFilterAgent context missing");let t=et.filter(a=>!(a in r));if(t.length)throw new Error(`LayerFilterAgent context missing: ${t.join(", ")}`);return r}var Da=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=b(r,"layersAndFieldsRegistry"),{mapView:a}=xe(r),o=await Te(e.vectorSearchFieldResults,t,a);return 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)}`)}},tt=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)},rt=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=oe.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},Ga=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}`;let s;if(o){let l=await rt(o,r);if("error"in l)return l.error;s=l.geometry}return i.featureEffect=new Qe({filter:new U({where:e.where,geometry:s,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:t,excludedEffect:a}),i.visible=!0,i.refresh(),tt(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}"`:""}.`},Pa=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],at=n.enum(Pa),Ba=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}=xe(o);return await Ga(e,i,t,a,r)},Qa=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:at.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.")}),Wa=w(Ba,{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:Qa}),Ua=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 rt(t,r);if("error"in s)return s.error;o=s.geometry}let i=await r.whenLayerView(a);return i.filter=new U({where:e.where,geometry:o,spatialRelationship:"intersects",distance:t?.distance,units:t?.units}),a.visible=!0,tt(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}"`:""}.`},Ka=async({targetLayer:e,geometryLayer:r},t)=>{let{mapView:a}=xe(t);return await Ua(e,a,r)},Ha=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:at.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Ja=w(Ka,{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:Ha}),ot=[Wa,Ja],Za=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await L("layer_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=ne(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await O({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:ot}),l=s.content.toString();return await K(s,r),{...e,messages:[...e.messages,s],outputMessage:l}};async function Ya(e,r){let t=await new z(ot).invoke({messages:x(e.messages)},r),a=t.messages.map(s=>s.text).join(`
89
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 it=p.Root({messages:p({reducer:k,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(`
90
+ `);return{...e,outputMessage:i,messages:o}}var it=g.Root({messages:g({reducer:A,default:()=>[]}),outputMessage:g({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
91
 
92
92
  `);return o[o.length-1]?.trim()===t?e:`${e}
93
93
 
94
- ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p()}),Ja=async(e,r)=>(await h({text:"Exiting Layer Filter agent"},r),e),Za=(e,r)=>D(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Filter Agent")(e,r),Ya=()=>new N(it).addNode("requireLayerFilterServices",Za).addNode("vectorSearchLayers",za).addNode("vectorSearchFields",Ma).addNode("fieldStatistics",ja).addNode("agent",Ka).addNode("tools",Ha).addNode("earlyExit",Ja).addEdge(_,"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).
94
+ ${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g()}),Xa=async(e,r)=>(await h({text:"Exiting Layer Filter agent"},r),e),eo=(e,r)=>G(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Filter Agent")(e,r),to=()=>new q(it).addNode("requireLayerFilterServices",eo).addNode("vectorSearchLayers",Oa).addNode("vectorSearchFields",ja).addNode("fieldStatistics",Da).addNode("agent",Za).addNode("tools",Ya).addNode("earlyExit",Xa).addEdge(N,"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),ro=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
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
96
  _Example: “Only show stations where Brand is Shell”_
97
97
  _Example: “Make Shell stations stand out on the map”_
98
- _Example: “Gray out all stations that aren’t Shell”_`,Il={id:"layerFilter",name:"Layer Filter Agent",description:Xa,createGraph:Ya,workspace:it},nt=p.Root({messages:p({reducer:k,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(`
98
+ _Example: “Gray out all stations that aren’t Shell”_`,Ll={id:"layerFilter",name:"Layer Filter Agent",description:ro,createGraph:to,workspace:it},nt=g.Root({messages:g({reducer:A,default:()=>[]}),outputMessage:g({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
99
 
100
100
  `);return o[o.length-1]?.trim()===t?e:`${e}
101
101
 
102
- ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p(),queryResponses:p()}),eo=async(e,r)=>(await h({text:"Exiting Layer Query agent"},r),e);function H(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerQueryAgent context missing");let t=et.filter(a=>!(a in r));if(t.length)throw new Error(`LayerQueryAgent context missing: ${t.join(", ")}`);return r}var to=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=w(r,"layersAndFieldsRegistry"),{mapView:a}=H(r),o=await Te(e.vectorSearchFieldResults,t,a);return 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)}`)}},De=.7,ro=10,ao=async(e,r)=>{try{let t=A(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:De,topResults:ro,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
102
+ ${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponses:g()}),ao=async(e,r)=>(await h({text:"Exiting Layer Query agent"},r),e);function H(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerQueryAgent context missing");let t=et.filter(a=>!(a in r));if(t.length)throw new Error(`LayerQueryAgent context missing: ${t.join(", ")}`);return r}var oo=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=b(r,"layersAndFieldsRegistry"),{mapView:a}=H(r),o=await Te(e.vectorSearchFieldResults,t,a);return 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)}`)}},De=.7,io=10,no=async(e,r)=>{try{let t=R(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:De,topResults:io,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
103
103
  `);return`${o.get(d)?.layerItem.name??d}:
104
104
  ${f}`}).join(`
105
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 ${De}.`,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)}`)}},oo=.7,io=async(e,r)=>{try{let t=A(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:oo}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
106
+ ${l}`:c=`No vector search results found for score over ${De}.`,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)}`)}},so=.7,lo=async(e,r)=>{try{let t=R(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:so}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
107
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)}`)}},no=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},so=async(e,r,t,a)=>{let o=a.map?.allLayers.find(c=>c.id===e),i=no(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 lo({layerId:e,fieldName:r,query:t},a){let{mapView:o}=H(a),i=await so(e,r,t,o);return JSON.stringify(i,null,2)}var co=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.")})}),uo=y(lo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:co}),Ee=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=re.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},ho=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 Ee(s,o);if("error"in g)throw new Error(g.error);if(d=g.geometry,s.distance&&s.units){let S=Ke.execute(d,s.distance,{unit:s.units==="us-nautical-miles"?"nautical-miles":s.units});S&&(d=S)}}else d=o.extent.clone();let u=new U({geometry:d,spatialRelationship:"intersects"}),f=null,m=null;try{f=await pe({layer:l,field:t,sqlWhere:r.where,filter:u,outStatisticTypes:{include:[a]}}),c.type==="string"&&(m=(await ye({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 f?.[a]=="number"?f[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:f?.[a]??null,summaryStatistics:f,uniqueValues:m,where:r.where}}},mo=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],fo=n.enum(mo);async function go({targetLayer:e,fieldName:r,statisticType:t,geometryLayer:a},o){let i=w(o,"layersAndFieldsRegistry"),{mapView:s}=H(o),l=await ho({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryLayer:a});return JSON.stringify(l,null,2)}var po=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:fo.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.")}),yo=y(go,{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:po}),wo=async(e,r,t,a)=>{let o=t.map?.allLayers.find(d=>d.id===e.layerId),i=a?await Ee(a,t):{geometry:void 0},s="geometry"in i?i.geometry:void 0,l=new We({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 Ue({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}}},bo=async({targetLayer:e,topFilter:r,geometryLayer:t},a)=>{let{mapView:o}=H(a),i=await wo(e,r,o,t);return JSON.stringify(i,null,2)},vo=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:q.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."))})}),So=y(bo,{name:"getTopFeatures",description:"Returns the top n features from a layer",schema:vo}),To=async(e,r,t)=>{let a=r.map?.allLayers.find(c=>c.id===e.layerId),o=t?await Ee(t,r):{geometry:void 0},i="geometry"in o?o.geometry:void 0,s=new we({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 xo({targetLayer:e,geometryLayer:r},t){let{mapView:a}=H(t),o=await To(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:q.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Io=y(xo,{name:"queryFeatures",description:"Queries for one or more features from a given layer.",schema:Eo}),st=[Io,yo,uo,So],$o=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("data_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=oe(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await V({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:st});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 K(s,r),{...e,outputMessage:l,messages:[...e.messages,s]}},Fo=new M(st);async function Lo(e,r){let{messages:t}=await Fo.invoke({messages:x(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 j({content:`Query results:
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)}`)}},co=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},uo=async(e,r,t,a)=>{let o=a.map?.allLayers.find(c=>c.id===e),i=co(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 ho({layerId:e,fieldName:r,query:t},a){let{mapView:o}=H(a),i=await uo(e,r,t,o);return JSON.stringify(i,null,2)}var mo=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.")})}),fo=w(ho,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:mo}),Ee=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=oe.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},po=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryLayer:s}=e,l=o.map?.allLayers.find(p=>p.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 p=await Ee(s,o);if("error"in p)throw new Error(p.error);if(d=p.geometry,s.distance&&s.units){let T=Ke.execute(d,s.distance,{unit:s.units==="us-nautical-miles"?"nautical-miles":s.units});T&&(d=T)}}else d=o.extent.clone();let u=new U({geometry:d,spatialRelationship:"intersects"}),f=null,m=null;try{f=await ye({layer:l,field:t,sqlWhere:r.where,filter:u,outStatisticTypes:{include:[a]}}),c.type==="string"&&(m=(await we({layer:l,field:t,sqlWhere:r.where,filter:u})).uniqueValueInfos)}catch(p){console.error("Statistics error:",p)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof f?.[a]=="number"?f[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:f?.[a]??null,summaryStatistics:f,uniqueValues:m,where:r.where}}},go=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],yo=n.enum(go);async function wo({targetLayer:e,fieldName:r,statisticType:t,geometryLayer:a},o){let i=b(o,"layersAndFieldsRegistry"),{mapView:s}=H(o),l=await po({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryLayer:a});return JSON.stringify(l,null,2)}var 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.")}),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:yo.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.")}),vo=w(wo,{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:bo}),So=async(e,r,t,a)=>{let o=t.map?.allLayers.find(d=>d.id===e.layerId),i=a?await Ee(a,t):{geometry:void 0},s="geometry"in i?i.geometry:void 0,l=new We({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 Ue({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}}},To=async({targetLayer:e,topFilter:r,geometryLayer:t},a)=>{let{mapView:o}=H(a),i=await So(e,r,o,t);return JSON.stringify(i,null,2)},xo=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:M.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."))})}),Eo=w(To,{name:"getTopFeatures",description:"Returns the top n features from a layer",schema:xo}),Io=async(e,r,t)=>{let a=r.map?.allLayers.find(c=>c.id===e.layerId),o=t?await Ee(t,r):{geometry:void 0},i="geometry"in o?o.geometry:void 0,s=new St({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 Fo({targetLayer:e,geometryLayer:r},t){let{mapView:a}=H(t),o=await Io(e,a,r);return JSON.stringify(o,null,2)}var $o=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:M.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Lo=w(Fo,{name:"queryFeatures",description:"Queries for one or more features from a given layer.",schema:$o}),st=[Lo,vo,fo,Eo],_o=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await L("data_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=ne(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await O({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:i,tools:st});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 K(s,r),{...e,outputMessage:l,messages:[...e.messages,s]}},ko=new z(st);async function No(e,r){let{messages:t}=await ko.invoke({messages:x(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 V({content:`Query results:
109
109
  ${o.join(`
110
110
  `)}`}),s=`Query results:
111
111
  ${o.join(`
112
- `)}`;return{...e,outputMessage:s,messages:[...e.messages,...t,i],queryResponses:a}}var _o=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await F("summarize_query_response_prompt"),a={queryResponse:e.queryResponses},o=await Y({promptText:t,messages:x(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content;return e.messages=[...e.messages,new j(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)}`)}},ko=(e,r)=>D(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Query Agent")(e,r),No=()=>new N(nt).addNode("requireLayerQueryServices",ko).addNode("vectorSearchLayers",io).addNode("vectorSearchFields",ao).addNode("fieldStatistics",to).addNode("agent",$o).addNode("tools",Lo).addNode("summarizeQueryResponseLLM",_o).addNode("earlyExit",eo).addEdge(_,"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),Ao=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.
112
+ `)}`;return{...e,outputMessage:s,messages:[...e.messages,...t,i],queryResponses:a}}var Ao=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await L("summarize_query_response_prompt"),a={queryResponse:e.queryResponses},o=await Y({promptText:t,messages:x(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content;return e.messages=[...e.messages,new V(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)}`)}},qo=(e,r)=>G(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Query Agent")(e,r),Ro=()=>new q(nt).addNode("requireLayerQueryServices",qo).addNode("vectorSearchLayers",lo).addNode("vectorSearchFields",no).addNode("fieldStatistics",oo).addNode("agent",_o).addNode("tools",No).addNode("summarizeQueryResponseLLM",Ao).addNode("earlyExit",ao).addEdge(N,"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),Mo=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
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
114
  _Example: “How many features are there?”_
115
115
  _Example: “What’s the average population?”_
116
- _Example: “Which values are in the status field?”_`,$l={id:"layerQuery",name:"Layer Query Agent",description:Ao,createGraph:No,workspace:nt},Ge=.7,qo=10,Ro=async(e,r)=>{try{let t=A(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:Ge,topResults:qo,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
116
+ _Example: “Which values are in the status field?”_`,_l={id:"layerQuery",name:"Layer Query Agent",description:Mo,createGraph:Ro,workspace:nt},Ge=.7,Co=10,zo=async(e,r)=>{try{let t=R(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:Ge,topResults:Co,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let f=u.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
117
117
  `);return`${o.get(d)?.layerItem.name??d}:
118
118
  ${f}`}).join(`
119
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 ${Ge}.`,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)}`)}},Mo=.7,Co=async(e,r)=>{try{let t=A(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:Mo}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
120
+ ${l}`:c=`No vector search results found for score over ${Ge}.`,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)}`)}},jo=.7,Vo=async(e,r)=>{try{let t=R(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:jo}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
121
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 zo(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i?s=vt({basemapTheme:await Re(a),geometryType:t.geometryType,includedTags:i,numColors:Math.min(r.length,8)})[0]:s=St({basemapTheme:await Re(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 jo(e){return await bt(e)}async function Vo({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 zo(c),u=await jo(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 Oo=["mapView"];function L(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerStylingAgent context missing");let t=Oo.filter(a=>!(a in r));if(t.length)throw new Error(`LayerStylingAgent context missing: ${t.join(", ")}`);return r}async function Do({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Vo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,includeSize:a})}var Go=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(Do,{name:"chart",description:`Label: Charts
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 Oo(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i?s=xt({basemapTheme:await Re(a),geometryType:t.geometryType,includedTags:i,numColors:Math.min(r.length,8)})[0]:s=Et({basemapTheme:await Re(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 Do(e){return await Tt(e)}async function Go({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 Oo(c),u=await Do(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 Po=["mapView"];function _(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerStylingAgent context missing");let t=Po.filter(a=>!(a in r));if(t.length)throw new Error(`LayerStylingAgent context missing: ${t.join(", ")}`);return r}async function Bo({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Go({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,includeSize:a})}var Qo=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)")}),Wo=w(Bo,{name:"chart",description:`Label: Charts
123
123
  Description: Show the values of two or more categories as a proportion of the total using a pie chart.
124
124
  Keywords: pie, chart, all categories, breakdown, proportion
125
125
  Example: Show the total number of homes built in each decade using a pie chart for each feature.
@@ -129,19 +129,19 @@ ${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r)
129
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
130
  Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
131
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:Go});function Bo(e){let{fields:r,layer:t,view:a,theme:o,colorSchemeTags:i}=e,s=r[0],l;return i&&(l=be({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 Qo(e){return await Tt(e)}async function Wo({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=Bo(c),u=await Qo(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 Uo({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Wo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Ko=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")}),Ho=y(Uo,{name:"color-age",description:`Label: Age (color)
132
+ Fields: This style requires 2-8 number fields.`,schema:Qo});function Uo(e){let{fields:r,layer:t,view:a,theme:o,colorSchemeTags:i}=e,s=r[0],l;return i&&(l=be({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 Ko(e){return await It(e)}async function Ho({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=Uo(c),u=await Ko(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 Jo({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Ho({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Zo=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")}),Yo=w(Jo,{name:"color-age",description:`Label: Age (color)
133
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
134
  Keywords: since, age, how old, how long
135
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:Ko});function Jo(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,{theme:i}=e,s=r[1],l=r[0],c;return o&&(c=be({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 Zo(e){return await xt(e)}async function Yo({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=Jo(c),u=await Zo(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}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Yo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var ei=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")}),ti=y(Xo,{name:"color",description:`Label: Counts and Amounts (color)
136
+ Fields: This style requires at least one field with a date type.`,schema:Zo});function Xo(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,{theme:i}=e,s=r[1],l=r[0],c;return o&&(c=be({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 ei(e){return await Ft(e)}async function ti({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=Xo(c),u=await ei(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 ri({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await ti({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var ai=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")}),oi=w(ri,{name:"color",description:`Label: Counts and Amounts (color)
137
137
  Description: Vary color along a continuous color ramp to represent numeric or ranked data.
138
138
  Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
139
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:ei});function ri(e){let{fields:r,layer:t,view:a,colorSchemeTags:o,theme:i}=e,s,l,c=r[0];return o&&(l=be({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 ai(e){return await Et(e)}async function oi({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=ri(c),u=await ai(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 ii({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await oi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var ni=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")}),si=y(ii,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
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:ai});function ii(e){let{fields:r,layer:t,view:a,colorSchemeTags:o,theme:i}=e,s,l,c=r[0];return o&&(l=be({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 ni(e){return await $t(e)}async function si({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=ii(c),u=await ni(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 li({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await si({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var ci=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")}),di=w(li,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
141
141
  Description: Vary symbol size and color based on the values of two numeric attributes.
142
142
  Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
143
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:ni});function li(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i;return o&&(i=$t({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 ci(e){return await It(e)}async function di({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=li(l),d=await ci(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 ui({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=L(a);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await di({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var hi=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")}),mi=y(ui,{name:"dot-density",description:`Dot Density
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:ci});function ui(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i;return o&&(i=_t({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 hi(e){return await Lt(e)}async function mi({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=ui(l),d=await hi(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 fi({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=_(a);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await mi({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var pi=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")}),gi=w(fi,{name:"dot-density",description:`Dot Density
145
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
146
  **Use cases:**
147
147
  - Population distribution visualization
@@ -152,11 +152,11 @@ ${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r)
152
152
  - Visualize distribution of different crops across regions
153
153
  - Display demographic patterns within census tracts
154
154
  **Fields:** Requires 2-8 number fields.
155
- **Keywords:** density, how much, how many, total, number, amount`,schema:hi});function fi(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s=r[0];return o&&(i=Lt({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:t,view:a,field:s,heatmapScheme:i}}async function gi(e){return await Ft(e)}async function pi({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=fi(l),d=await gi(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 yi({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=L(a);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await pi({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var wi=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")}),bi=y(yi,{name:"heatmap",description:`Label: Heat Map
155
+ **Keywords:** density, how much, how many, total, number, amount`,schema:pi});function yi(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s=r[0];return o&&(i=Nt({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:t,view:a,field:s,heatmapScheme:i}}async function wi(e){return await kt(e)}async function bi({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=yi(l),d=await wi(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 vi({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=_(a);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await bi({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var Si=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")}),Ti=w(vi,{name:"heatmap",description:`Label: Heat Map
156
156
  Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
157
157
  Keywords: density, heatmap, hot spots, pattern, cluster
158
158
  Example: Create a heatmap
159
- Fields: This typically requires zero or one field of type number.`,schema:wi});function vi(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i&&(s=kt({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 Si(e){return await _t(e)}async function Ti({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=vi(c),u=await Si(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 xi({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Ti({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)")}),Ii=y(xi,{name:"predominance",description:`Label: Predominant category
159
+ Fields: This typically requires zero or one field of type number.`,schema:Si});function xi(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i&&(s=qt({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 Ei(e){return await At(e)}async function Ii({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=xi(c),u=await Ei(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 Fi({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Ii({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,includeSize:a})}var $i=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)")}),Li=w(Fi,{name:"predominance",description:`Label: Predominant category
160
160
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
161
161
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
162
162
  Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
@@ -166,15 +166,15 @@ Fields: This typically requires zero or one field of type number.`,schema:wi});f
166
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
167
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
168
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 $i(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s={field:r[0]},l={field:r[1]};return o&&(i=At({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field1:s,field2:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:i}}async function Fi(e){return await Nt(e)}async function Li({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=$i(l),d=await Fi(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 _i({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=L(a);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await Li({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var ki=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")}),Ni=y(_i,{name:"relationship",description:`Label: Relationship
169
+ Fields: This style relies on 2-10 number fields.`,schema:$i});function _i(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s={field:r[0]},l={field:r[1]};return o&&(i=Mt({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field1:s,field2:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:i}}async function ki(e){return await Rt(e)}async function Ni({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=_i(l),d=await ki(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 Ai({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=_(a);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await Ni({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var qi=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")}),Ri=w(Ai,{name:"relationship",description:`Label: Relationship
170
170
  Description: Overlays two color ramps to represent the relationship between two numeric attributes.
171
171
  Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
172
172
  Example: Show the relationship between tree height and carbon storage
173
- Fields: This style requires two number fields.`,schema:ki});function Ai(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 qi(e){return await qt(e)}async function Ri({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=Ai(c),u=await qi(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 Mi({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Ri({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Ci=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")}),zi=y(Mi,{name:"size-age",description:`Label: Age (size)
173
+ Fields: This style requires two number fields.`,schema:qi});function Mi(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 Ci(e){return await Ct(e)}async function zi({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=Mi(c),u=await Ci(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 ji({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await zi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Vi=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")}),Oi=w(ji,{name:"size-age",description:`Label: Age (size)
174
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
175
  Keywords: since, age, how old, how long
176
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:Ci});function ji(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 Vi(e){return await Rt(e)}async function Oi({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=ji(c),u=await Vi(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 Di({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Oi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Gi=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(Di,{name:"size",description:`Label: Counts and Amounts (size)
177
+ Fields: This style requires at least one field with a date type.`,schema:Vi});function Di(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 Gi(e){return await zt(e)}async function Pi({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=Di(c),u=await Gi(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 Bi({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Pi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Qi=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")}),Wi=w(Bi,{name:"size",description:`Label: Counts and Amounts (size)
178
178
  Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
179
179
  Keywords: graduated size, proportional size, how much, total, number, amount, size
180
180
  Example: Vary the size of each point based on the total population.
@@ -184,33 +184,33 @@ Fields: This typically requires zero or one field of type number.`,schema:wi});f
184
184
  Description: Vary symbol sizes along a continuous ramp to represent dates.
185
185
  Keywords: graduated size, proportional size, classed size, how much, total, number, when
186
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:Gi});function Bi(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i=r[0],s=r[1],l=r[2],c;return o&&(c=Ct({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field:i,field2:s,field3:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function Qi(e){return await Mt(e)}async function Wi({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=Bi(c),u=await Qi(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 Ui({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=L(o);return await I({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Wi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Ki=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")}),Hi=y(Ui,{name:"type",description:`Label: Types (unique symbols)
187
+ Fields: This style requires a single field with a date type.`,schema:Qi});function Ui(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i=r[0],s=r[1],l=r[2],c;return o&&(c=Vt({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field:i,field2:s,field3:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function Ki(e){return await jt(e)}async function Hi({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=Ui(c),u=await Ki(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 Ji({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=_(o);return await F({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Hi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Zi=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")}),Yi=w(Ji,{name:"type",description:`Label: Types (unique symbols)
188
188
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
189
189
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
190
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:Ki}),lt=[Po,Ho,ti,si,mi,bi,Ii,Ni,zi,Pi,Hi],Ji=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("navigation_intent_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await V({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:a,tools:lt});return await K(o,r),{...e,messages:[...e.messages,o]}};async function Zi(e,r){let t=await new M(lt).invoke({messages:x(e.messages)},r),a=t.messages.map(i=>i.text).join(`
191
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:Zi}),lt=[Wo,Yo,oi,di,gi,Ti,Li,Ri,Oi,Wi,Yi],Xi=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await L("navigation_intent_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await O({promptText:t,modelTier:"advanced",messages:x(e.messages),inputVariables:a,tools:lt});return await K(o,r),{...e,messages:[...e.messages,o]}};async function en(e,r){let t=await new z(lt).invoke({messages:x(e.messages)},r),a=t.messages.map(i=>i.text).join(`
192
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 ct=p.Root({messages:p({reducer:k,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(`
193
+ `);return{...e,outputMessage:o}}var ct=g.Root({messages:g({reducer:A,default:()=>[]}),outputMessage:g({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
194
 
195
195
  `);return o[o.length-1]?.trim()===t?e:`${e}
196
196
 
197
- ${t}`},default:()=>""}),vectorSearchLayerIds:p(),vectorSearchFieldResults:p(),layerFieldInfo:p(),selectedLayerId:p()}),Yi=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 f=l.get(u)?.layerItem;return f?[f.name&&`Name: ${f.name}`,f.title&&`Title: ${f.title}`,f.description&&`Description: ${f.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 f=c.get(u.name);f&&d.fieldInfos.push(f)}}return 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)}`)}},en=(e,r)=>{let t=e.vectorSearchLayerIds??[];if(t.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=r.configurable;if(!a||a.agentId!==Pe.id||a.id!=="reviewLayerSelection"){let i={agentId:Pe.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...t]};throw new Fe(i)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},tn=(e,r)=>D(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,r),rn=()=>new N(ct).addNode("requireLayerStylingServices",tn).addNode("vectorSearchLayers",Co).addNode("layerSelectionHITL",en).addNode("vectorSearchFields",Ro).addNode("populateLayerFieldInfo",Xi).addNode("agent",Ji).addNode("tools",Zi).addNode("earlyExit",Yi).addEdge(_,"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),an=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.
197
+ ${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),selectedLayerId:g()}),tn=async(e,r)=>(await h({text:"Exiting Layer Styling agent"},r),e),rn=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 f=l.get(u)?.layerItem;return f?[f.name&&`Name: ${f.name}`,f.title&&`Title: ${f.title}`,f.description&&`Description: ${f.description}`].filter(Boolean).join(" | "):u},{layerId:i,results:s}=a,l=b(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 f=c.get(u.name);f&&d.fieldInfos.push(f)}}return 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)}`)}},an=(e,r)=>{let t=e.vectorSearchLayerIds??[];if(t.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=r.configurable;if(!a||a.agentId!==Pe.id||a.id!=="reviewLayerSelection"){let i={agentId:Pe.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...t]};throw new $e(i)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},on=(e,r)=>G(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,r),nn=()=>new q(ct).addNode("requireLayerStylingServices",on).addNode("vectorSearchLayers",Vo).addNode("layerSelectionHITL",an).addNode("vectorSearchFields",zo).addNode("populateLayerFieldInfo",rn).addNode("agent",Xi).addNode("tools",en).addNode("earlyExit",tn).addEdge(N,"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),sn=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
198
  _Example: “Color points by sales amount”_
199
199
  _Example: “Show population density with a color gradient”_
200
200
  _Example: “Create a relationship map between height and depth”_
201
- _Example: “Vary circle sizes according to population”_`,Pe={id:"layerStyling",name:"Layer Styling Agent",description:an,createGraph:rn,workspace:ct},dt=p.Root({messages:p({reducer:k,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(`
201
+ _Example: “Vary circle sizes according to population”_`,Pe={id:"layerStyling",name:"Layer Styling Agent",description:sn,createGraph:nn,workspace:ct},dt=g.Root({messages:g({reducer:A,default:()=>[]}),outputMessage:g({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
202
 
203
203
  `);return o[o.length-1]?.trim()===t?e:`${e}
204
204
 
205
- ${t}`},default:()=>""})}),on=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}
205
+ ${t}`},default:()=>""})}),ln=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
206
  Fields: ${i}${s}`}).join(`
207
207
 
208
208
  `);return`This map contains ${e.size} layer(s):
209
209
 
210
- ${r}`},nn=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 sn(e,r){let t=await F("help_prompt"),a=w(r,"layersAndFieldsRegistry"),o=w(r,"agentRegistry"),i={layerSummary:on(a),agents:nn(o)},s=await Y({promptText:t,messages:x(e.messages),inputVariables:i}),l=new j(s),c=[...e.messages,l],d=`${e.outputMessage}
210
+ ${r}`},cn=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 dn(e,r){let t=await L("help_prompt"),a=b(r,"layersAndFieldsRegistry"),o=b(r,"agentRegistry"),i={layerSummary:ln(a),agents:cn(o)},s=await Y({promptText:t,messages:x(e.messages),inputVariables:i}),l=new V(s),c=[...e.messages,l],d=`${e.outputMessage}
212
212
 
213
- ${s}`.trim();return{...e,messages:c,outputMessage:d}}var ln=(e,r)=>D(["agentRegistry"],"Help Agent")(e,r),cn=()=>new N(dt).addNode("requireHelpServices",ln).addNode("agent",sn).addEdge(_,"requireHelpServices").addEdge("requireHelpServices","agent").addEdge("agent",E),dn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
213
+ ${s}`.trim();return{...e,messages:c,outputMessage:d}}var un=(e,r)=>G(["agentRegistry"],"Help Agent")(e,r),hn=()=>new q(dt).addNode("requireHelpServices",un).addNode("agent",dn).addEdge(N,"requireHelpServices").addEdge("requireHelpServices","agent").addEdge("agent",E),mn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
214
214
 
215
215
  _Example: “Tell me about this map”_
216
216
  _Example: “List all layers in this map”_
@@ -223,22 +223,22 @@ ${s}`.trim();return{...e,messages:c,outputMessage:d}}var ln=(e,r)=>D(["agentRegi
223
223
 
224
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
225
  _Example: "Create a chart"_
226
- _Example: "Create a table"_`,Fl={id:"help",name:"Help Agent",description:dn,createGraph:cn,workspace:dt},Ll=p.Root({messages:p({reducer:k,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(`
226
+ _Example: "Create a table"_`,kl={id:"help",name:"Help Agent",description:mn,createGraph:hn,workspace:dt},Nl=g.Root({messages:g({reducer:A,default:()=>[]}),outputMessage:g({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
227
 
228
228
  `);return o[o.length-1]?.trim()===t?e:`${e}
229
229
 
230
- ${t}`},default:()=>""}),intent:p({reducer:(e,r)=>r})}),X={conversationId:""},un=["linkChartView"],hn=["knowledgeGraph"];function ie(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(`Link Chart context missing: ${t.join(", ")}`);return r}function Ie(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("ArcgisKnowledgeAgent context missing");let t=hn.filter(a=>!(a in r));if(t.length)throw new Error(`Knowledge Graph context missing: ${t.join(", ")}`);return r}var he=class{constructor(r){this.dataModel=r,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=me.fromDataModel(r)}},me=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(W.fromEntityType(a));for(let a of r.relationshipTypes)t.relationshipTypes.push(fe.fromRelationshipType(a));return t.identifierInfo={mappingInfo:{identifierMapsTo:mn(r.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:r.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},t.spatialReference=JSON.parse(JSON.stringify(r.spatialReference)),t}},W=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=fn(r.role);for(let a of r.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:gn(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}},fe=class extends W{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(r){let t=W.fromEntityType(r);t.observedEndPoints=[];for(let a of r.endPoints)t.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return t}},mn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},fn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function gn(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 pn(e,r,t,a){let{graphQuery:o,explanation:i}=await $e(e,r,t,a);return`Generated Graph Query:
230
+ ${t}`},default:()=>""}),intent:g({reducer:(e,r)=>r})}),X={conversationId:""},fn=["linkChartView"],pn=["knowledgeGraph"];function se(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("ArcgisKnowledgeAgent context missing");let t=fn.filter(a=>!(a in r));if(t.length)throw new Error(`Link Chart context missing: ${t.join(", ")}`);return r}function Ie(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("ArcgisKnowledgeAgent context missing");let t=pn.filter(a=>!(a in r));if(t.length)throw new Error(`Knowledge Graph context missing: ${t.join(", ")}`);return r}var me=class{constructor(r){this.dataModel=r,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=fe.fromDataModel(r)}},fe=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(W.fromEntityType(a));for(let a of r.relationshipTypes)t.relationshipTypes.push(pe.fromRelationshipType(a));return t.identifierInfo={mappingInfo:{identifierMapsTo:gn(r.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:r.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},t.spatialReference=JSON.parse(JSON.stringify(r.spatialReference)),t}},W=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=yn(r.role);for(let a of r.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:wn(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}},pe=class extends W{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(r){let t=W.fromEntityType(r);t.observedEndPoints=[];for(let a of r.endPoints)t.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return t}},gn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},yn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function wn(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 bn(e,r,t,a){let{graphQuery:o,explanation:i}=await Fe(e,r,t,a);return`Generated Graph Query:
231
231
  ${o}
232
232
 
233
- Explanation: ${i}`}async function $e(e,r,t,a){let o={message:e,context:new he(r)};X.conversationId&&(o.conversationId=X.conversationId),await h({text:"Attempting to generate a cypher query from your prompt..."},a);let i=await Me(`${t}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Ce.findCredential(O.getDefault().url)?.token??""}});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});X.conversationId||(X.conversationId=i.data.conversationId);let s=!1,l=Date.now(),c=i.data.sequenceNumber,d="",u="",f=1;for(;!s;){await new Promise(g=>setTimeout(g,1e3)),await h({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,f)}`},a),f=f%3+1;let m=await Me(`${t}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Ce.findCredential(O.getDefault().url)?.token??""}});if(m.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${m.httpStatus}`,{cause:m.data});if(m.data.context)d=m.data.context.graphQuery,u=m.data.message||"";else if(!m.data.hasMore)s=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=m.data.sequenceNumber}return{graphQuery:d,explanation:u}}function ee(e,r){if(!(!e||typeof e!="object")){if(wn(e))for(let t of e.path)ee(t,r);else if(yn(e))r.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let t of e)ee(t,r);else if(bn(e))for(let t of Object.values(e.properties??{}))ee(t,r)}}function yn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function wn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function bn(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function vn(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 Sn=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)ee(s,r)}return Array.from(r.values())};async function Tn(e,r,t,a,o){let{graphQuery:i,explanation:s}=await $e(e,r.dataModel,t,o);await h({text:`Attempting to execute query: ${i.substring(0,500)}${i.length>500?"...":""}`},o);let l=await zt(r,new He({openCypherQuery:i}),{signal:o?.signal,timeout:o?.timeout}),c=await Sn(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:
233
+ Explanation: ${i}`}async function Fe(e,r,t,a){let o={message:e,context:new me(r)};X.conversationId&&(o.conversationId=X.conversationId),await h({text:"Attempting to generate a cypher query from your prompt..."},a);let i=await Me(`${t}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Ce.findCredential(D.getDefault().url)?.token??""}});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});X.conversationId||(X.conversationId=i.data.conversationId);let s=!1,l=Date.now(),c=i.data.sequenceNumber,d="",u="",f=1;for(;!s;){await new Promise(p=>setTimeout(p,1e3)),await h({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,f)}`},a),f=f%3+1;let m=await Me(`${t}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Ce.findCredential(D.getDefault().url)?.token??""}});if(m.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${m.httpStatus}`,{cause:m.data});if(m.data.context)d=m.data.context.graphQuery,u=m.data.message||"";else if(!m.data.hasMore)s=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=m.data.sequenceNumber}return{graphQuery:d,explanation:u}}function ee(e,r){if(!(!e||typeof e!="object")){if(Sn(e))for(let t of e.path)ee(t,r);else if(vn(e))r.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let t of e)ee(t,r);else if(Tn(e))for(let t of Object.values(e.properties??{}))ee(t,r)}}function vn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Sn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Tn(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function xn(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 En=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)ee(s,r)}return Array.from(r.values())};async function In(e,r,t,a,o){let{graphQuery:i,explanation:s}=await Fe(e,r.dataModel,t,o);await h({text:`Attempting to execute query: ${i.substring(0,500)}${i.length>500?"...":""}`},o);let l=await Ot(r,new He({openCypherQuery:i}),{signal:o?.signal,timeout:o?.timeout}),c=await En(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
234
  ${i}
235
235
 
236
- Explanation: ${s}`}async function xn({prompt:e},r){let{knowledgeGraph:t}=Ie(r),{linkChartView:a}=ie(r),o=O.getDefault().helperServices,i=await F("arcgis_knowledge_current_lc_context"),s=vn(a.map,t),l=`${e}
236
+ Explanation: ${s}`}async function Fn({prompt:e},r){let{knowledgeGraph:t}=Ie(r),{linkChartView:a}=se(r),o=D.getDefault().helperServices,i=await L("arcgis_knowledge_current_lc_context"),s=xn(a.map,t),l=`${e}
237
237
 
238
- ${i}${JSON.stringify(s)}`;return await Tn(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.")}),_l=y(xn,{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 In(e,r){return await r.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function $n({layout:e},r){let{linkChartView:t}=ie(r);return await In(e,t)}var Fn=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")}),kl=y($n,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:Fn});function Ln(e,r){return r.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function _n({setting:e},r){let{linkChartView:t}=ie(r);return Ln(e,t)}var kn=n.object({setting:n.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Nl=y(_n,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:kn});async function Nn(e,r,t,a,o){let{graphQuery:i,explanation:s}=await $e(e,r.dataModel,t,o);await h({text:`Attempting to create link chart from derived query: ${i}`},o);let l=await jt.fromCypherQuery(r,new He({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:
238
+ ${i}${JSON.stringify(s)}`;return await In(l,t,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,r)}var $n=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Al=w(Fn,{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:$n});async function Ln(e,r){return await r.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function _n({layout:e},r){let{linkChartView:t}=se(r);return await Ln(e,t)}var kn=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")}),ql=w(_n,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:kn});function Nn(e,r){return r.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function An({setting:e},r){let{linkChartView:t}=se(r);return Nn(e,t)}var qn=n.object({setting:n.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Rl=w(An,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:qn});async function Rn(e,r,t,a,o){let{graphQuery:i,explanation:s}=await Fe(e,r.dataModel,t,o);await h({text:`Attempting to create link chart from derived query: ${i}`},o);let l=await Dt.fromCypherQuery(r,new He({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
239
  ${i}
240
240
 
241
- Explanation: ${s}`}async function An({prompt:e},r){let{knowledgeGraph:t}=Ie(r),{linkChartView:a}=ie(r),o=O.getDefault().helperServices;return await Nn(e,t,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,r)}var qn=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),Al=y(An,{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:qn});async function Rn({prompt:e},r){let{knowledgeGraph:t}=Ie(r),a=O.getDefault().helperServices;return await pn(e,t.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,r)}var Mn=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),ql=y(Rn,{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:Mn});var Rl=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).
241
+ Explanation: ${s}`}async function Mn({prompt:e},r){let{knowledgeGraph:t}=Ie(r),{linkChartView:a}=se(r),o=D.getDefault().helperServices;return await Rn(e,t,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,r)}var Cn=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),Ml=w(Mn,{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:Cn});async function zn({prompt:e},r){let{knowledgeGraph:t}=Ie(r),a=D.getDefault().helperServices;return await bn(e,t.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,r)}var jn=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Cl=w(zn,{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:jn});var zl=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
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
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
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
@@ -270,4 +270,4 @@ _example: "Find all the products supplied by Supplier X and add them to my visua
270
270
  _example: "Expand the link chart from 'Entity D' to show its direct connections"_
271
271
  _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
272
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:xl,b:El,c:Il,d:$l,e:Pe,f:Fl}},"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)
273
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_`;return{a:Fl,b:$l,c:Ll,d:_l,e:Pe,f:kl}},"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","geometry/operators/bufferOperator","rest/support/Query","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)