@arcgis/ai-components 5.1.0-next.98 → 5.1.0-next.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,24 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import a from"./D7WNBUVK.js";import{Bb as V,Fb as M,L as D,M as se,Q as le,R as O,Za as F,_a as f,a as q,b as E,g as Te,j as Z,k as J,kb as v,q as Ee,qb as ke,u as Ie}from"./YW52XJMM.js";export default $arcgis.t(([pt,mt,{addressToLocations:gt},z,ue,ft,Ve,yt,Ge,Pe,{formatDateOnly:wt,convertDateFormatToIntlOptions:Y,formatTimeOnly:bt,formatDate:Ce},Be,Qe,vt,St,{createRenderer:xt},{getSchemesByTag:Tt,getSchemes:Et},{getBackgroundColorTheme:qe},{createAgeRenderer:It,createContinuousRenderer:kt},{getSchemesByTag:we},{createContinuousRenderer:$t},{createRenderer:_t},{getSchemesByTag:Ft},{createRenderer:Nt},{getSchemesByTag:Ct},{createRenderer:qt},{getSchemesByTag:Mt},{createRenderer:At},{getSchemesByTag:Rt},{createAgeRenderer:Lt,createContinuousRenderer:zt},{createRenderer:jt},{getSchemesByTag:Dt},,{fetchKnowledgeGraph:Ot,executeQueryStreaming:Vt,executeSearchStreaming:Gt},be,Me,Ae,Pt,,Bt,{a:l,b:G,c:$e,d:g,e:I,g:_e,h:ce,i:j}])=>{var Ne=e=>Array.isArray(e)&&e.every(D),ct=e=>typeof e=="object"&&e!=null&&"messages"in e&&Ne(e.messages),dt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,A=class extends ke{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:a,handleToolErrors:o}=t??{};super({name:r,tags:a,func:(n,s)=>this.run(n,s)}),this.tools=e,this.handleToolErrors=o??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(a=>a.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let a=await r.invoke({...e,type:"tool_call"},t);return D(a)&&a.getType()==="tool"||J(a)?a:new se({status:"success",name:r.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||Ie(a))throw a;return new se({status:"error",content:`Error: ${a.message}
3
- Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(dt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Ne(e))n=e;else if(ct(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(d=>d.getType()==="tool").map(d=>d.tool_call_id)),i;for(let d=n.length-1;d>=0;d-=1){let c=n[d];if(O(c)){i=c;break}}if(i==null||!O(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(d=>d.id==null||!s.has(d.id)).map(d=>this.runTool(d,t))??[])}if(!r.some(J))return Array.isArray(e)?r:{messages:r};let a=[],o=null;for(let n of r)J(n)?n.graph===Z.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>Te(s))?o?o.goto.push(...n.goto):o=new Z({graph:Z.PARENT,goto:n.goto}):a.push(n):a.push(Array.isArray(e)?[n]:{messages:[n]});return o&&a.push(o),a}};var Yi=v.Root({llmInputMessages:v({reducer:(e,t)=>V([],t),default:()=>[]})});var P=(e,t)=>t??e,Ke=v.Root({...$e(),intent:v({reducer:P}),vectorSearchLayerResults:v({reducer:P,default:()=>[]}),vectorSearchFieldResults:v({reducer:P}),navigationInternalState:v({reducer:P,default:()=>({toolCallMessage:void 0})})});async function Qt(e,t){let r=z.getDefault().helperServices,a=r.geocode.find(u=>u.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!a)throw new Error("No geocoding service found in helperServices.");let o=a.url,n=`${ue.assetsPath?.endsWith("/")?ue.assetsPath:`${ue.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await gt(o,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent||!s.location)throw new Error(`Could not find location for: ${e}`);let i=new mt({url:n,width:24,height:24}),d=new pt({geometry:s.location,symbol:i});t.graphics.removeAll(),t.graphics.add(d),await t.goTo(s.extent);let c={lastResolvedLocation:{value:{address:s.address??"",location:s.location?s.location.toJSON():null,extent:s.extent?s.extent.toJSON():null}}};return{text:`Successfully zoomed to ${e}.`,sharedStatePatch:c}}var Kt=["mapView"];function k(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=Kt.filter(a=>!(a in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Ut({address:e},t){let{mapView:r}=k(t);return await Qt(e,r)}var Wt=l.object({address:l.string().describe("The full address or place name to locate.")}),Ht=f(Ut,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Wt});async function Zt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let a=r.find(n=>n.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 t.goTo(o),{text:`Navigated to bookmark: ${e}`}}async function Jt({bookmarkName:e},t){let{mapView:r}=k(t);return await Promise.resolve(Zt(e,r))}var Yt=F.object({bookmarkName:F.string().describe("The name of the bookmark to navigate to.")}),Xt=f(Jt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Yt});async function er(e,t,r){let a=r.map?.allLayers.find(n=>n.id===e);if(!a)return{text:`Error: Layer with id ${e} not found`};let o=a.createQuery();o.where=t??"1=1";try{let{extent:n,count:s}=await a.queryExtent(o);if(s===0)return{text:`No features found in ${a.title} matching: ${t}`};if(n)await r.goTo(n);else return{text:`Error: Unable to determine extent for ${a.title}`};return{text:`Successfully zoomed to ${s} feature(s) in ${a.title}`}}catch(n){return console.error("Error in goToFeatures:",n),{text:`Error: ${n instanceof Error?n.message:"Unknown error"}`}}}async function tr({layerId:e,where:t},r){let{mapView:a}=k(r);return await er(e,t,a)}var rr=F.object({layerId:F.string().describe("The layerId of the layer to zoom to."),where:F.string().describe("The sql-92 where clause used to query features to zoom to")}),ar=f(tr,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:rr});async function or(e){let t=new ft({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"Successfully zoomed to world extent"}}async function nr(e,t){let{mapView:r}=k(t);return await or(r)}var ir=F.object({}),sr=f(nr,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ir});async function lr(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function cr(e,t){let{mapView:r}=k(t);return await lr(r)}var dr=l.object({}),ur=f(cr,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:dr});async function hr(e,t){await t.when();let r=t.map?.allLayers.find(o=>o.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),{text:`Could not find layer for: ${e}`};let a;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?a=t.map.diagramNodesExtent:a=r.fullExtent,a?(await t.goTo(a),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function pr({layerId:e},t){let{mapView:r}=k(t);return await hr(e,r)}var mr=F.object({layerId:F.string().describe("The id of the layer to navigate to")}),gr=f(pr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:mr});async function fr(e,t){return await t.goTo({scale:e}),{text:`Successfully zoomed to: ${e}`}}async function yr({scale:e},t){let{mapView:r}=k(t);return await fr(e,r)}var wr=l.object({scale:l.number().describe("The map scale of the view to go to.")}),br=f(yr,{name:"goToScale",description:"Go to the specified view scale.",schema:wr});async function vr(e,t,r){let a={target:new Ve({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(a.zoom=r.zoom),r?.scale!==void 0&&(a.scale=r.scale),await t.goTo(a),{text:`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function Sr({center:e,zoom:t,scale:r},a){let{mapView:o}=k(a);return await vr(e,o,{zoom:t,scale:r})}var xr=l.object({center:l.object({longitude:l.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:l.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:l.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:l.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),Tr=f(Sr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:xr});async function Er(e,t){return await t.goTo({zoom:e}),{text:`Successfully zoomed to: ${e}`}}async function Ir({zoom:e},t){let{mapView:r}=k(t);return await Er(e,r)}var kr=l.object({zoom:l.number().min(1).max(20).describe("The zoom level of the view to go to.")}),$r=f(Ir,{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:kr}),ve=[Ht,Xt,ar,sr,ur,gr,br,Tr,$r],Re=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LSGRWCAO.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./5JS65BCP.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./YVTKUITE.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./AKOWC7YT.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./MZJGADGH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./5PT7ZFXF.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./7EXACS27.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./ESTSYVJP.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./CFT5BBC6.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./SFREIREB.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./DMLSCJAM.js").then(e=>e.default)});async function N(e){let t=Object.entries(Re).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
2
+ import a from"./D7WNBUVK.js";import{Bb as G,Fb as q,L as D,M as se,Q as le,R as V,Za as N,_a as f,a as M,b as E,g as Te,j as J,k as Y,kb as v,q as Ee,qb as ke,u as Ie}from"./YW52XJMM.js";export default $arcgis.t(([St,xt,{addressToLocations:Tt},z,ue,Et,Ve,It,Ge,Pe,{formatDateOnly:kt,convertDateFormatToIntlOptions:X,formatTimeOnly:$t,formatDate:Ce},Be,Qe,_t,Nt,{createRenderer:Ft},{getSchemesByTag:Ct,getSchemes:Mt},{getBackgroundColorTheme:Me},{createAgeRenderer:qt,createContinuousRenderer:At},{getSchemesByTag:we},{createContinuousRenderer:Rt},{createRenderer:Lt},{getSchemesByTag:zt},{createRenderer:jt},{getSchemesByTag:Ot},{createRenderer:Dt},{getSchemesByTag:Vt},{createRenderer:Gt},{getSchemesByTag:Pt},{createAgeRenderer:Bt,createContinuousRenderer:Qt},{createRenderer:Kt},{getSchemesByTag:Ut},,{fetchKnowledgeGraph:Wt,executeQueryStreaming:Ht,executeSearchStreaming:Zt},be,qe,Ae,Jt,,Yt,{a:l,b:P,c:$e,d:g,e:I,g:_e,h:ce,i:j}])=>{var Fe=e=>Array.isArray(e)&&e.every(D),yt=e=>typeof e=="object"&&e!=null&&"messages"in e&&Fe(e.messages),wt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,A=class extends ke{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:a,handleToolErrors:o}=t??{};super({name:r,tags:a,func:(n,s)=>this.run(n,s)}),this.tools=e,this.handleToolErrors=o??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(a=>a.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let a=await r.invoke({...e,type:"tool_call"},t);return D(a)&&a.getType()==="tool"||Y(a)?a:new se({status:"success",name:r.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||Ie(a))throw a;return new se({status:"error",content:`Error: ${a.message}
3
+ Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(wt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Fe(e))n=e;else if(yt(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(d=>d.getType()==="tool").map(d=>d.tool_call_id)),i;for(let d=n.length-1;d>=0;d-=1){let c=n[d];if(V(c)){i=c;break}}if(i==null||!V(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(d=>d.id==null||!s.has(d.id)).map(d=>this.runTool(d,t))??[])}if(!r.some(Y))return Array.isArray(e)?r:{messages:r};let a=[],o=null;for(let n of r)Y(n)?n.graph===J.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>Te(s))?o?o.goto.push(...n.goto):o=new J({graph:J.PARENT,goto:n.goto}):a.push(n):a.push(Array.isArray(e)?[n]:{messages:[n]});return o&&a.push(o),a}};var is=v.Root({llmInputMessages:v({reducer:(e,t)=>G([],t),default:()=>[]})});var B=(e,t)=>t??e,Ke=v.Root({...$e(),intent:v({reducer:B}),vectorSearchLayerResults:v({reducer:B,default:()=>[]}),vectorSearchFieldResults:v({reducer:B}),navigationInternalState:v({reducer:B,default:()=>({toolCallMessage:void 0})})});async function Xt(e,t){let r=z.getDefault().helperServices,a=r.geocode.find(u=>u.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!a)throw new Error("No geocoding service found in helperServices.");let o=a.url,n=`${ue.assetsPath?.endsWith("/")?ue.assetsPath:`${ue.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await Tt(o,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent||!s.location)throw new Error(`Could not find location for: ${e}`);let i=new xt({url:n,width:24,height:24}),d=new St({geometry:s.location,symbol:i});t.graphics.removeAll(),t.graphics.add(d),await t.goTo(s.extent);let c={lastResolvedLocation:{value:{address:s.address??"",location:s.location?s.location.toJSON():null,extent:s.extent?s.extent.toJSON():null}}};return{text:`Successfully zoomed to ${e}.`,sharedStatePatch:c}}var er=["mapView"];function k(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=er.filter(a=>!(a in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function tr({address:e},t){let{mapView:r}=k(t);return await Xt(e,r)}var rr=l.object({address:l.string().describe("The full address or place name to locate.")}),ar=f(tr,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:rr});async function or(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let a=r.find(n=>n.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 t.goTo(o),{text:`Navigated to bookmark: ${e}`}}async function nr({bookmarkName:e},t){let{mapView:r}=k(t);return await Promise.resolve(or(e,r))}var ir=N.object({bookmarkName:N.string().describe("The name of the bookmark to navigate to.")}),sr=f(nr,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:ir});async function lr(e,t,r){let a=r.map?.allLayers.find(n=>n.id===e);if(!a)return{text:`Error: Layer with id ${e} not found`};let o=a.createQuery();o.where=t??"1=1";try{let{extent:n,count:s}=await a.queryExtent(o);if(s===0)return{text:`No features found in ${a.title} matching: ${t}`};if(n)await r.goTo(n);else return{text:`Error: Unable to determine extent for ${a.title}`};return{text:`Successfully zoomed to ${s} feature(s) in ${a.title}`}}catch(n){return console.error("Error in goToFeatures:",n),{text:`Error: ${n instanceof Error?n.message:"Unknown error"}`}}}async function cr({layerId:e,where:t},r){let{mapView:a}=k(r);return await lr(e,t,a)}var dr=N.object({layerId:N.string().describe("The layerId of the layer to zoom to."),where:N.string().describe("The sql-92 where clause used to query features to zoom to")}),ur=f(cr,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:dr});async function hr(e){let t=new Et({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"Successfully zoomed to world extent"}}async function mr(e,t){let{mapView:r}=k(t);return await hr(r)}var pr=N.object({}),gr=f(mr,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:pr});async function fr(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function yr(e,t){let{mapView:r}=k(t);return await fr(r)}var wr=l.object({}),br=f(yr,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:wr});async function vr(e,t){await t.when();let r=t.map?.allLayers.find(o=>o.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),{text:`Could not find layer for: ${e}`};let a;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?a=t.map.diagramNodesExtent:a=r.fullExtent,a?(await t.goTo(a),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function Sr({layerId:e},t){let{mapView:r}=k(t);return await vr(e,r)}var xr=N.object({layerId:N.string().describe("The id of the layer to navigate to")}),Tr=f(Sr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:xr});async function Er(e,t){return await t.goTo({scale:e}),{text:`Successfully zoomed to: ${e}`}}async function Ir({scale:e},t){let{mapView:r}=k(t);return await Er(e,r)}var kr=l.object({scale:l.number().describe("The map scale of the view to go to.")}),$r=f(Ir,{name:"goToScale",description:"Go to the specified view scale.",schema:kr});async function _r(e,t,r){let a={target:new Ve({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(a.zoom=r.zoom),r?.scale!==void 0&&(a.scale=r.scale),await t.goTo(a),{text:`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function Nr({center:e,zoom:t,scale:r},a){let{mapView:o}=k(a);return await _r(e,o,{zoom:t,scale:r})}var Fr=l.object({center:l.object({longitude:l.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:l.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:l.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:l.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),Cr=f(Nr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:Fr});async function Mr(e,t){return await t.goTo({zoom:e}),{text:`Successfully zoomed to: ${e}`}}async function qr({zoom:e},t){let{mapView:r}=k(t);return await Mr(e,r)}var Ar=l.object({zoom:l.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Rr=f(qr,{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:Ar}),ve=[ar,sr,ur,gr,br,Tr,$r,Cr,Rr],Re=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LSGRWCAO.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./YVTKUITE.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./K6LVZHWM.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./4QVKWA2Z.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./MZJGADGH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./5PT7ZFXF.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./7EXACS27.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./ESTSYVJP.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./CFT5BBC6.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./SFREIREB.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./DMLSCJAM.js").then(e=>e.default)});async function F(e){let t=Object.entries(Re).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
4
4
  Available prompts:
5
5
  ${Object.keys(Re).join(`
6
- `)}`);return await t[1]()}async function _r(e,t){let r=await N("navigation_tool_prompt"),{mapView:a}=k(t),o=a.map.bookmarks?.map(m=>m.name).filter(Boolean)??[],n=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((m,w)=>`${w+1}. layerId=${m.id} | title=${m.title??""} | name=${m.name??""} | score=${m.score.toFixed(2)}`).join(`
6
+ `)}`);return await t[1]()}async function Lr(e,t){let r=await F("navigation_tool_prompt"),{mapView:a}=k(t),o=a.map.bookmarks?.map(p=>p.name).filter(Boolean)??[],n=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((p,y)=>`${y+1}. layerId=${p.id} | title=${p.title??""} | name=${p.name??""} | score=${p.score.toFixed(2)}`).join(`
7
7
  `):"",s=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",i=e.intent==="goToBookmark"&&o.length?`Available bookmarks:
8
- ${o.map(m=>`- ${m}`).join(`
8
+ ${o.map(p=>`- ${p}`).join(`
9
9
  `)}`:"",d=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
10
10
  ${n}`:"",c=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
11
- ${s}`:"",u={intent:e.intent,bookmarksSection:i,layersSection:d,fieldsSection:c,currentZoom:a.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},h=await j({promptText:r,modelTier:"fast",inputVariables:u,tools:ve}),p=(h.tool_calls?.length??0)>0,b=typeof h.text=="string"?h.text.trim():"",y=b.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:p?h:void 0},outputMessage:p?e.outputMessage:b,status:p?e.status:y?"success":"failed"}}var K=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r},Fr=e=>{let t=typeof e=="string"?e:String(e);try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r}catch{console.warn("Failed to parse tool response as JSON:",t)}return{text:t}};async function Nr(e,t){let r=new A(ve);try{let a=e.navigationInternalState.toolCallMessage;if(!a)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let{messages:o}=await r.invoke({messages:[a]},t),n="",s;for(let i of o){let d=Fr(i.content);d.text&&(n+=`${d.text}
12
- `),d.sharedStatePatch&&(s={...s,...d.sharedStatePatch})}return await g({text:`Finished executing navigation tool: ${n}`},t),{...e,outputMessage:n,sharedStatePatch:s,status:"success",summary:n?K(n):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await g({text:`Navigation tool execution failed: ${o}`},t),{...e,outputMessage:`Navigation tool execution failed: ${o}`,status:"failed",summary:`Navigation tool execution failed: ${o}`,navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}}async function Cr(e,t){let r=await N("navigation_intent_prompt"),{mapView:a}=k(t),o=ve.map(h=>({name:h.name,description:h.description,schema:h.schema})),n=a.map.bookmarks?.map(h=>h.name).filter(Boolean)??[],s=n.length?`Available bookmarks:
11
+ ${s}`:"",u={intent:e.intent,bookmarksSection:i,layersSection:d,fieldsSection:c,currentZoom:a.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},h=await j({promptText:r,modelTier:"fast",inputVariables:u,tools:ve}),m=(h.tool_calls?.length??0)>0,w=typeof h.text=="string"?h.text.trim():"",b=w.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:m?h:void 0},outputMessage:m?e.outputMessage:w,status:m?e.status:b?"success":"failed"}}var U=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r},zr=e=>{let t=typeof e=="string"?e:String(e);try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r}catch{console.warn("Failed to parse tool response as JSON:",t)}return{text:t}};async function jr(e,t){let r=new A(ve);try{let a=e.navigationInternalState.toolCallMessage;if(!a)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let{messages:o}=await r.invoke({messages:[a]},t),n="",s;for(let i of o){let d=zr(i.content);d.text&&(n+=`${d.text}
12
+ `),d.sharedStatePatch&&(s={...s,...d.sharedStatePatch})}return await g({text:`Finished executing navigation tool: ${n}`},t),{...e,outputMessage:n,sharedStatePatch:s,status:"success",summary:n?U(n):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await g({text:`Navigation tool execution failed: ${o}`},t),{...e,outputMessage:`Navigation tool execution failed: ${o}`,status:"failed",summary:`Navigation tool execution failed: ${o}`,navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}}async function Or(e,t){let r=await F("navigation_intent_prompt"),{mapView:a}=k(t),o=ve.map(h=>({name:h.name,description:h.description,schema:h.schema})),n=a.map.bookmarks?.map(h=>h.name).filter(Boolean)??[],s=n.length?`Available bookmarks:
13
13
  ${n.map(h=>`- ${h}`).join(`
14
- `)}`:"",i={tools:o.map(({name:h,description:p,schema:b})=>`${h}: ${p}, ${JSON.stringify(b)}`).join(`
15
- `),bookmarks:s,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},d=l.object({intent:l.string()}),c=await ce({promptText:r,inputVariables:i,schema:d,modelTier:"fast"}),u=typeof c.intent=="string"?c.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var x=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},qr=.7,Mr=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=(await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:qr,embeddingCache:o})).map(({id:i,score:d})=>{let c=a.get(i)?.layerItem;return{id:i,title:c?.title,name:c?.name??void 0,score:d}}),s;return n.length>0?s=`Vector search completed. Matching layers:
14
+ `)}`:"",i={tools:o.map(({name:h,description:m,schema:w})=>`${h}: ${m}, ${JSON.stringify(w)}`).join(`
15
+ `),bookmarks:s,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},d=l.object({intent:l.string()}),c=await ce({promptText:r,inputVariables:i,schema:d,modelTier:"fast"}),u=typeof c.intent=="string"?c.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var x=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},Dr=.7,Vr=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=(await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Dr,embeddingCache:o})).map(({id:i,score:d})=>{let c=a.get(i)?.layerItem;return{id:i,title:c?.title,name:c?.name??void 0,score:d}}),s;return n.length>0?s=`Vector search completed. Matching layers:
16
16
  ${n.map(i=>`- layerId=${i.id} | title=${i.title??""} | name=${i.name??""} | score=${i.score.toFixed(2)}`).join(`
17
- `)}`:s="Vector search completed. No matching layers found.",await g({text:s},t),{...e,vectorSearchLayerResults:n}}catch(r){throw await g({text:`Error during vector search layers: ${r instanceof Error?r.message:String(r)}`},t),r}},Le=.7,Ar=10,Rr=async(e,t)=>{try{await g({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=e.vectorSearchLayerResults?.map(d=>d.id)??[];if(n.length===0)return await g({text:"No candidate layers for field search"},t),e;let s=(await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:n,minScore:Le,topResults:Ar,embeddingCache:o})).map(({layerId:d,results:c})=>{let u=a.get(d)?.fieldRegistry;return{layerId:d,layerName:a.get(d)?.layerItem.name,results:c.map(h=>{let p=u?.get(h.name);return{name:h.name,score:h.score,type:p?.type,alias:p?.alias,description:p?.description,statistics:p?.statistics}})}}),i;return s.length>0?i=`Vector search completed. Matching layers and fields:
17
+ `)}`:s="Vector search completed. No matching layers found.",await g({text:s},t),{...e,vectorSearchLayerResults:n}}catch(r){throw await g({text:`Error during vector search layers: ${r instanceof Error?r.message:String(r)}`},t),r}},Le=.7,Gr=10,Pr=async(e,t)=>{try{await g({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=e.vectorSearchLayerResults?.map(d=>d.id)??[];if(n.length===0)return await g({text:"No candidate layers for field search"},t),e;let s=(await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:n,minScore:Le,topResults:Gr,embeddingCache:o})).map(({layerId:d,results:c})=>{let u=a.get(d)?.fieldRegistry;return{layerId:d,layerName:a.get(d)?.layerItem.name,results:c.map(h=>{let m=u?.get(h.name);return{name:h.name,score:h.score,type:m?.type,alias:m?.alias,description:m?.description,statistics:m?.statistics}})}}),i;return s.length>0?i=`Vector search completed. Matching layers and fields:
18
18
  ${s.map(d=>`${d.layerName??d.layerId}:
19
19
  ${d.results.map(c=>` - ${c.name} (${c.score.toFixed(2)})`).join(`
20
20
  `)}`).join(`
21
- `)}`:i=`No vector search field results found for score over ${Le}.`,await g({text:i},t),{...e,vectorSearchFieldResults:s}}catch(r){throw await g({text:`Error during vector search fields: ${r instanceof Error?r.message:String(r)}`},t),r}},ae=(e,t)=>(r,a)=>{let o=a?.configurable?.services;for(let n of e)if(!o?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r},Lr=(e,t)=>ae(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),zr=()=>new M(Ke).addNode("requireNavigationServices",Lr).addNode("intentLLM",Cr).addNode("vectorSearchLayers",Mr).addNode("vectorSearchFields",Rr).addNode("agent",_r).addNode("tools",Nr).addEdge(q,"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),jr=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
21
+ `)}`:i=`No vector search field results found for score over ${Le}.`,await g({text:i},t),{...e,vectorSearchFieldResults:s}}catch(r){throw await g({text:`Error during vector search fields: ${r instanceof Error?r.message:String(r)}`},t),r}},ae=(e,t)=>(r,a)=>{let o=a?.configurable?.services;for(let n of e)if(!o?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r},Br=(e,t)=>ae(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),Qr=()=>new q(Ke).addNode("requireNavigationServices",Br).addNode("intentLLM",Or).addNode("vectorSearchLayers",Vr).addNode("vectorSearchFields",Pr).addNode("agent",Lr).addNode("tools",jr).addEdge(M,"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),Kr=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
22
22
  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.
23
23
 
24
24
  Supported actions:
@@ -37,7 +37,7 @@ ${d.results.map(c=>` - ${c.name} (${c.score.toFixed(2)})`).join(`
37
37
  _Example: “Center the map on San Francisco at scale 50000”_
38
38
  _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
39
39
  _Example: “Go to the Downtown bookmark”_
40
- _Example: “Where is Mount Rainier?”_`,al={id:"navigation",name:"Navigation Agent",description:jr,createGraph:zr,workspace:Ke},Ue=v.Root({...G(),vectorSearchLayerIds:v(),vectorSearchFieldResults:v(),layerFieldInfo:v(),queryResponse:v(),dataExplorationMessages:v({reducer:V,default:()=>[]})}),Dr=async(e,t)=>(await g({text:"Exiting Data Exploration agent"},t),e),Se=async(e,t)=>{let r=e.tool_calls??[];if(r.length===0){await g({text:`LLM did not request any tool calls: ${String(e?.content)}`},t);return}await Promise.all(r.map(async a=>await g({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},t)))},Or=["mapView"];function R(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=Or.filter(a=>!(a in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var Vr=e=>{let t=e.map?.allLayers.filter(a=>a.type==="feature"),r=0;return t?.forEach(a=>{let o=a;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},Gr=async(e,t)=>{let{mapView:r}=R(t);return Vr(r)},Pr=f(Gr,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:l.object({})}),Br=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let a=r;a.featureEffect&&(a.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},Qr=async(e,t)=>{let{mapView:r}=R(t);return await Br(r)},Kr=f(Qr,{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:l.object({})});function te(e){return"point"in e&&e.point!==void 0}function B(e){return"layerId"in e&&e.layerId!==void 0}var oe=async(e,t)=>{if(te(e)){let{point:r}=e;return{geometry:new Ve({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(B(e)){let r=t.map?.allLayers.find(o=>o.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=r.title??r.id;try{let o=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!o.features.length)return{error:`No features found in geometry layer "${a}" with the specified where clause: ${e.where}`};let n;if(o.features.length===1){let s=o.features[0].geometry;if(!s)return{error:"The geometry of the first feature is undefined or null."};n=s}else{let s=o.features.map(d=>d.geometry),i=Pe.executeMany(s);if(!i)return{error:"Failed to create a combined geometry."};n=i}return n.spatialReference||(n.spatialReference=t.spatialReference),{geometry:n}}catch(o){return{error:`Failed to query geometry: ${String(o)}`}}}return{error:"Invalid geometry configuration provided"}},Ur=async(e,t,r,a,o,n)=>{let s=e.map?.allLayers.find(d=>d.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let i=s.createQuery();i.where=r??"1=1",a&&(i.geometry=a,i.spatialRelationship="intersects",o&&(i.distance=o),n&&(i.units=n));try{let{extent:d,count:c}=await s.queryExtent(i);return!d||c===0?{success:!1,error:`No features found for filter (where: ${i.where}${a?", spatial filter used":""})`}:(await e.goTo(d),{success:!0})}catch(d){return{success:!1,error:d instanceof Error?d.message:String(d)}}},Wr=async(e,t,r,a,o,n)=>{let s=t.map?.allLayers.find(h=>h.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let i;if(o){let h=await oe(o,t);if("error"in h)return h.error;i=h.geometry}if(s.featureEffect=null,s.featureEffect=new yt({filter:new Ge({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:a}),s.visible=!0,n)return`Applied feature effects to "${s.title??e.layerId}" within current map extent.`;let d=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,c=await Ur(t,e.layerId,d,i,o?.distance,o?.units),u=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 "${u}" but no features matched. ${c.error}`},Hr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],L=l.enum(Hr),Zr=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:a="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:s}=R(n);return await Wr(e,s,a,o,t,r)},Jr=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),Yr=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),Xr=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer on which to set a feature effect."),where:l.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:l.array(l.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:l.union([Jr,Yr]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:l.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:l.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:l.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.")}),ea=f(Zr,{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:Xr}),me=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},ta=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,ra=e=>{if(typeof e=="string"&&e)return e;let t=me(e);return t?t.toISOString().slice(0,10):null},We=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),a=(Math.abs(e)%60).toString().padStart(2,"0"),o=`${t}${r}:${a}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:o}},aa=(e,t,r)=>{let a=t?.toLowerCase();if(a==="date-only"){let n=ra(e);return n?wt(n,Y("short-date")):e}if(a==="time-only"){if(typeof e=="string"&&e)return bt(e,Y("long-time"));let n=me(e);return n?Ce(n,{...Y("long-time"),timeZone:"UTC"}):e}let o=me(e);return o?Ce(o,{...Y("short-date-short-time"),timeZone:ta(r)}):e},He=(e,t,r)=>{if(e&&typeof e!="function"){let a="getField"in r&&r.getField?.(e),o=a&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(a.name):null;if(o?.type==="coded-value"){let n=o.codedValues.find(s=>s.code===t);return n?n.name:null}}return null},oa=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,na=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},ia=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},sa=(e,t,r)=>{let a=na(e);if(!a)return e;let o={};t.dateStyle?o.dateStyle=t.dateStyle:(t.year&&(o.year=t.year),t.month&&(o.month=t.month)),t.timeStyle&&(o.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?o.hour12=!0:t.timeStyle&&t.hour12==="never"&&(o.hour12=!1),o.timeZone=oa(r);try{return new Intl.DateTimeFormat(void 0,o).format(a)}catch{return e}},Ze=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,Je=(e,t,r,a,o)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?ia(r,n):n?.type==="date-time"?sa(r,n,o):aa(r,a,o)},la=(e,t,r,a)=>{let o=e.fieldsIndex?.get(t),n=He(t,r,e)??r;return Je(e,t,n,o?.type,a)},ca=(e,t)=>Ze(e,t),Ye=(e,t,r)=>{let a=e.objectIdField,o=t.features.map(s=>s.attributes[a]),n=t.features.map(s=>{let i=s.attributes,d={};return e.fields.forEach(c=>{if(!Object.hasOwn(i,c.name))return;let u=i[c.name];if(c.name===a){d[c.name]=u;return}let h=He(c.name,u,e)??u,p=Ze(e,c.name);d[p]=Je(e,c.name,h,c.type,r)}),d});return{objectIds:o,attributes:n}},da=(e,t,r)=>{let a=e.createQuery();return a.outFields=[t],a.where=r||"1=1",a.num=1,a},ua=async(e,t,r,a)=>{let o=a.map?.allLayers.find(u=>u.id===e),n=da(o,t,r.where),s=(await o.queryFeatures(n)).features[0],i=s?s.attributes[t]:null,d=la(o,t,i,a.timeZone),c=ca(o,t);return{tool:"getAttribute",layerName:o.title??e,summary:`${c} = ${d}`,details:{fieldName:t,fieldAlias:c!==t?c:void 0,value:d,where:r.where}}};async function ha({layerId:e,fieldName:t,query:r},a){let{mapView:o}=R(a),n=await ua(e,t,r,o);return JSON.stringify(n,null,2)}var pa=l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:l.string().describe("The name of the field/attribute from which to get a field value."),query:l.object({where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),ma=f(ha,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:pa}),xe=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function re(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var ga=async e=>{let{targetLayer:t,fieldName:r,statisticType:a,mapView:o,layersAndFieldsRegistry:n,geometryFilter:s}=e,i=o.map?.allLayers.find(S=>S.id===t.layerId);if(!i)throw new Error(`Layer '${t.layerId}' not found.`);let d=await o.whenLayerView(i),c=n.get(t.layerId)?.fieldRegistry.get(r),u=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let h,p;if(s){let S=await oe(s,o);if("error"in S)throw new Error(S.error);if(!S.geometry)throw B(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");if(B(s)){let T=o.map?.allLayers.find(_=>_.id===s.layerId);h={geometryLayerName:T?.title??T?.id,geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}}else te(s)&&(h={point:s.point,distance:s.distance,units:s.units,applied:!0});p=new Ge({geometry:S.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let b=xe(d,[r],!1),y=null,m=null,w=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let S={layer:i,useFeaturesInView:b,view:b?o:void 0,field:r,sqlWhere:re(i.definitionExpression,t.where),...p&&{filter:p},outStatisticTypes:{include:[a]}};y=await Be(S);let T=["string","small-integer","integer"],_=c.domain?.type==="coded-value"?c.domain:null;(T.includes(c.type)||_)&&(m=(await Qe({layer:i,useFeaturesInView:b,view:b?o:void 0,field:r,sqlWhere:re(i.definitionExpression,t.where),...p&&{filter:p}})).uniqueValueInfos.sort((C,W)=>W.count-C.count).slice(0,w)),m&&c.domain?.type==="coded-value"&&(m=m.map(C=>({...C,value:_?_.getName(C.value)??C.value:C.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:i.title??t.layerId,summary:`${a} = ${typeof y?.[a]=="number"?y[a]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:a,statistic:y?.[a]??null,summaryStatistics:y,uniqueValues:m,where:t.where,spatialFilterInfo:h}}};async function fa({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:a},o){let n=x(o,"layersAndFieldsRegistry"),{mapView:s}=R(o),i=await ga({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:a});return JSON.stringify(i,null,2)}var ya=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),wa=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),ba=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:l.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."),fieldName:l.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:l.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),va=f(fa,{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.
40
+ _Example: “Where is Mount Rainier?”_`,ul={id:"navigation",name:"Navigation Agent",description:Kr,createGraph:Qr,workspace:Ke},Ue=v.Root({...P(),vectorSearchLayerIds:v(),vectorSearchFieldResults:v(),layerFieldInfo:v(),queryResponse:v(),dataExplorationMessages:v({reducer:G,default:()=>[]})}),Ur=async(e,t)=>(await g({text:"Exiting Data Exploration agent"},t),e),Se=async(e,t)=>{let r=e.tool_calls??[];if(r.length===0){await g({text:`LLM did not request any tool calls: ${String(e?.content)}`},t);return}await Promise.all(r.map(async a=>await g({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},t)))},Wr=["mapView"];function R(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=Wr.filter(a=>!(a in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var Hr=e=>{let t=e.map?.allLayers.filter(a=>a.type==="feature"),r=0;return t?.forEach(a=>{let o=a;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},Zr=async(e,t)=>{let{mapView:r}=R(t);return Hr(r)},Jr=f(Zr,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:l.object({})}),Yr=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let a=r;a.featureEffect&&(a.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},Xr=async(e,t)=>{let{mapView:r}=R(t);return await Yr(r)},ea=f(Xr,{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:l.object({})});function te(e){return"point"in e&&e.point!==void 0}function Q(e){return"layerId"in e&&e.layerId!==void 0}var oe=async(e,t)=>{if(te(e)){let{point:r}=e;return{geometry:new Ve({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(Q(e)){let r=t.map?.allLayers.find(o=>o.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=r.title??r.id;try{let o=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!o.features.length)return{error:`No features found in geometry layer "${a}" with the specified where clause: ${e.where}`};let n;if(o.features.length===1){let s=o.features[0].geometry;if(!s)return{error:"The geometry of the first feature is undefined or null."};n=s}else{let s=o.features.map(d=>d.geometry),i=Pe.executeMany(s);if(!i)return{error:"Failed to create a combined geometry."};n=i}return n.spatialReference||(n.spatialReference=t.spatialReference),{geometry:n}}catch(o){return{error:`Failed to query geometry: ${String(o)}`}}}return{error:"Invalid geometry configuration provided"}},ta=async(e,t,r,a,o,n)=>{let s=e.map?.allLayers.find(d=>d.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let i=s.createQuery();i.where=r??"1=1",a&&(i.geometry=a,i.spatialRelationship="intersects",o&&(i.distance=o),n&&(i.units=n));try{let{extent:d,count:c}=await s.queryExtent(i);return!d||c===0?{success:!1,error:`No features found for filter (where: ${i.where}${a?", spatial filter used":""})`}:(await e.goTo(d),{success:!0})}catch(d){return{success:!1,error:d instanceof Error?d.message:String(d)}}},ra=async(e,t,r,a,o,n)=>{let s=t.map?.allLayers.find(h=>h.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let i;if(o){let h=await oe(o,t);if("error"in h)return h.error;i=h.geometry}if(s.featureEffect=null,s.featureEffect=new It({filter:new Ge({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:a}),s.visible=!0,n)return`Applied feature effects to "${s.title??e.layerId}" within current map extent.`;let d=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,c=await ta(t,e.layerId,d,i,o?.distance,o?.units),u=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 "${u}" but no features matched. ${c.error}`},aa=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],L=l.enum(aa),oa=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:a="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:s}=R(n);return await ra(e,s,a,o,t,r)},na=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),ia=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),sa=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer on which to set a feature effect."),where:l.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:l.array(l.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:l.union([na,ia]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:l.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:l.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:l.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.")}),la=f(oa,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:sa}),pe=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},ca=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,da=e=>{if(typeof e=="string"&&e)return e;let t=pe(e);return t?t.toISOString().slice(0,10):null},We=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),a=(Math.abs(e)%60).toString().padStart(2,"0"),o=`${t}${r}:${a}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:o}},ua=(e,t,r)=>{let a=t?.toLowerCase();if(a==="date-only"){let n=da(e);return n?kt(n,X("short-date")):e}if(a==="time-only"){if(typeof e=="string"&&e)return $t(e,X("long-time"));let n=pe(e);return n?Ce(n,{...X("long-time"),timeZone:"UTC"}):e}let o=pe(e);return o?Ce(o,{...X("short-date-short-time"),timeZone:ca(r)}):e},He=(e,t,r)=>{if(e&&typeof e!="function"){let a="getField"in r&&r.getField?.(e),o=a&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(a.name):null;if(o?.type==="coded-value"){let n=o.codedValues.find(s=>s.code===t);return n?n.name:null}}return null},ha=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,ma=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},pa=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},ga=(e,t,r)=>{let a=ma(e);if(!a)return e;let o={};t.dateStyle?o.dateStyle=t.dateStyle:(t.year&&(o.year=t.year),t.month&&(o.month=t.month)),t.timeStyle&&(o.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?o.hour12=!0:t.timeStyle&&t.hour12==="never"&&(o.hour12=!1),o.timeZone=ha(r);try{return new Intl.DateTimeFormat(void 0,o).format(a)}catch{return e}},Ze=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,Je=(e,t,r,a,o)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?pa(r,n):n?.type==="date-time"?ga(r,n,o):ua(r,a,o)},fa=(e,t,r,a)=>{let o=e.fieldsIndex?.get(t),n=He(t,r,e)??r;return Je(e,t,n,o?.type,a)},ya=(e,t)=>Ze(e,t),Ye=(e,t,r)=>{let a=e.objectIdField,o=t.features.map(s=>s.attributes[a]),n=t.features.map(s=>{let i=s.attributes,d={};return e.fields.forEach(c=>{if(!Object.hasOwn(i,c.name))return;let u=i[c.name];if(c.name===a){d[c.name]=u;return}let h=He(c.name,u,e)??u,m=Ze(e,c.name);d[m]=Je(e,c.name,h,c.type,r)}),d});return{objectIds:o,attributes:n}},wa=(e,t,r)=>{let a=e.createQuery();return a.outFields=[t],a.where=r||"1=1",a.num=1,a},ba=async(e,t,r,a)=>{let o=a.map?.allLayers.find(u=>u.id===e),n=wa(o,t,r.where),s=(await o.queryFeatures(n)).features[0],i=s?s.attributes[t]:null,d=fa(o,t,i,a.timeZone),c=ya(o,t);return{tool:"getAttribute",layerName:o.title??e,summary:`${c} = ${d}`,details:{fieldName:t,fieldAlias:c!==t?c:void 0,value:d,where:r.where}}};async function va({layerId:e,fieldName:t,query:r},a){let{mapView:o}=R(a),n=await ba(e,t,r,o);return JSON.stringify(n,null,2)}var Sa=l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:l.string().describe("The name of the field/attribute from which to get a field value."),query:l.object({where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),xa=f(va,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Sa}),xe=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function re(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var Ta=async e=>{let{targetLayer:t,fieldName:r,statisticType:a,mapView:o,layersAndFieldsRegistry:n,geometryFilter:s}=e,i=o.map?.allLayers.find(S=>S.id===t.layerId);if(!i)throw new Error(`Layer '${t.layerId}' not found.`);let d=await o.whenLayerView(i),c=n.get(t.layerId)?.fieldRegistry.get(r),u=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let h,m;if(s){let S=await oe(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");if(Q(s)){let T=o.map?.allLayers.find(_=>_.id===s.layerId);h={geometryLayerName:T?.title??T?.id,geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}}else te(s)&&(h={point:s.point,distance:s.distance,units:s.units,applied:!0});m=new Ge({geometry:S.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let w=xe(d,[r],!1),b=null,p=null,y=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let S={layer:i,useFeaturesInView:w,view:w?o:void 0,field:r,sqlWhere:re(i.definitionExpression,t.where),...m&&{filter:m},outStatisticTypes:{include:[a]}};b=await Be(S);let T=["string","small-integer","integer"],_=c.domain?.type==="coded-value"?c.domain:null;(T.includes(c.type)||_)&&(p=(await Qe({layer:i,useFeaturesInView:w,view:w?o:void 0,field:r,sqlWhere:re(i.definitionExpression,t.where),...m&&{filter:m}})).uniqueValueInfos.sort((C,H)=>H.count-C.count).slice(0,y)),p&&c.domain?.type==="coded-value"&&(p=p.map(C=>({...C,value:_?_.getName(C.value)??C.value:C.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:i.title??t.layerId,summary:`${a} = ${typeof b?.[a]=="number"?b[a]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:a,statistic:b?.[a]??null,summaryStatistics:b,uniqueValues:p,where:t.where,spatialFilterInfo:h}}};async function Ea({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:a},o){let n=x(o,"layersAndFieldsRegistry"),{mapView:s}=R(o),i=await Ta({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:a});return JSON.stringify(i,null,2)}var Ia=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),ka=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),$a=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:l.union([Ia,ka]).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:l.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:l.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),_a=f(Ea,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
41
41
 
42
42
  USE THIS TOOL FOR:
43
43
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -49,7 +49,7 @@ DO NOT USE FOR:
49
49
  - "Show / list / find features" \u2014 use queryFeatures instead
50
50
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
51
51
 
52
- 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:ba}),Sa=async(e,t,r,a,o)=>{let n=r.map?.allLayers.find(p=>p.id===e.layerId),s=await r.whenLayerView(n),i=n.title??e.layerId,d;if(a){let p=await oe(a,r);if("error"in p)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:p.error}};if(!p.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};d=p.geometry}else o&&(d=r.extent.clone());let c=t.groupByFields&&t.groupByFields.length>0,u=n.objectIdField,h=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,u])];try{let p;if(c){let m=new vt({where:e.where||"1=1",outFields:h,orderByFields:e.orderByFields,geometry:d,spatialRelationship:d?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new St({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});p=await n.queryTopFeatures(m)}else{let m=n.createQuery();m.where=re(n.definitionExpression,e.where||"1=1"),m.outFields=h.length?h:["*"],m.orderByFields=t.orderByFields,m.num=t.topCount,d&&(m.geometry=d,m.spatialRelationship="intersects"),a?.distance&&(m.distance=a.distance),a?.units&&(m.units=a.units),m.outSpatialReference=r.spatialReference;let w=xe(s,e.outFields,o??!1);try{p=w?await s.queryFeatures(m):await n.queryFeatures(m)}catch(S){console.warn("Client-side query failed, falling back to server:",S),p=await n.queryFeatures(m)}}let b=p.features.map(m=>m.attributes[u]),{attributes:y}=Ye(n,p,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:y,objectIds:b,objectIdField:u,where:e.where,orderByFields:t.orderByFields,...c&&{groupByFields:t.groupByFields}}}}catch(p){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:p instanceof Error?p.message:String(p)}}}},xa=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:a},o)=>{let{mapView:n}=R(o),s=await Sa(e,t,n,r,a);return JSON.stringify(s,null,2)},Ta=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),Ea=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),Ia=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.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:l.union([Ta,Ea]).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:l.object({topCount:l.number().describe("Number of top features to return per group."),orderByFields:l.array(l.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:l.array(l.string().describe("Field(s) to group results by. Returns top N per group."))}),useCurrentExtent:l.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).")}),ka=f(xa,{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:Ia}),he=25,$a=async(e,t,r,a)=>{let o=t.map?.allLayers.find(m=>m.id===e.layerId),n=await t.whenLayerView(o),s=o.title??e.layerId,i;if(r){let m=await oe(r,t);if("error"in m){let w={error:m.error};if(B(r)){let S=t.map?.allLayers.find(T=>T.id===r.layerId);w.geometryLayerName=S?.title??S?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else te(r)&&(w.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:w}}if(!m.geometry){let w={};if(B(r)){let S=t.map?.allLayers.find(T=>T.id===r.layerId);w.error=`No features found matching: ${r.where}`,w.geometryLayerName=S?.title??S?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else te(r)&&(w.error="Failed to create point geometry",w.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:w}}i=m.geometry}else a&&(i=t.extent.clone());let d=xe(n,e.outFields,a??!1),c=o.objectIdField,u=o.createQuery();u.where=re(o.definitionExpression,e.where||"1=1"),u.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,c])],u.orderByFields=e.orderByFields,i&&(u.geometry=i,u.spatialRelationship="intersects"),r?.distance&&(u.distance=r.distance),r?.units&&(u.units=r.units),u.outSpatialReference=t.spatialReference;let h,p;try{h=d?await n.queryFeatureCount(u):await o.queryFeatureCount(u),h>0&&h<=he&&(p=d?await n.queryFeatures(u):await o.queryFeatures(u))}catch(m){console.warn("Client-side query failed, falling back to server:",m),h=await o.queryFeatureCount(u),h>0&&h<=he&&(p=await o.queryFeatures(u))}let{objectIds:b,attributes:y}=p?Ye(o,p,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:s,summary:`${h} features found`,details:{totalCount:h,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...b&&{objectIds:b,objectIdField:c},...y&&{attributes:y},...h>he&&{note:`${h} features found.`}}}};async function _a({targetLayer:e,geometryFilter:t,useCurrentExtent:r},a){let{mapView:o}=R(a),n=await $a(e,o,t,r);return JSON.stringify(n,null,2)}var Fa=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),Na=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),Ca=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.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:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.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:l.union([Fa,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."),useCurrentExtent:l.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),qa=f(_a,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
52
+ 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:$a}),Na=async(e,t,r,a,o)=>{let n=r.map?.allLayers.find(m=>m.id===e.layerId),s=await r.whenLayerView(n),i=n.title??e.layerId,d;if(a){let m=await oe(a,r);if("error"in m)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};d=m.geometry}else o&&(d=r.extent.clone());let c=t.groupByFields&&t.groupByFields.length>0,u=n.objectIdField,h=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,u])];try{let m;if(c){let p=new _t({where:e.where||"1=1",outFields:h,orderByFields:e.orderByFields,geometry:d,spatialRelationship:d?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new Nt({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});m=await n.queryTopFeatures(p)}else{let p=n.createQuery();p.where=re(n.definitionExpression,e.where||"1=1"),p.outFields=h.length?h:["*"],p.orderByFields=t.orderByFields,p.num=t.topCount,d&&(p.geometry=d,p.spatialRelationship="intersects"),a?.distance&&(p.distance=a.distance),a?.units&&(p.units=a.units),p.outSpatialReference=r.spatialReference;let y=xe(s,e.outFields,o??!1);try{m=y?await s.queryFeatures(p):await n.queryFeatures(p)}catch(S){console.warn("Client-side query failed, falling back to server:",S),m=await n.queryFeatures(p)}}let w=m.features.map(p=>p.attributes[u]),{attributes:b}=Ye(n,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:b,objectIds:w,objectIdField:u,where:e.where,orderByFields:t.orderByFields,...c&&{groupByFields:t.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},Fa=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:a},o)=>{let{mapView:n}=R(o),s=await Na(e,t,n,r,a);return JSON.stringify(s,null,2)},Ca=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),Ma=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),qa=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.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:l.union([Ca,Ma]).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:l.object({topCount:l.number().describe("Number of top features to return per group."),orderByFields:l.array(l.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:l.array(l.string().describe("Field(s) to group results by. Returns top N per group."))}),useCurrentExtent:l.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).")}),Aa=f(Fa,{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:qa}),he=25,Ra=async(e,t,r,a)=>{let o=t.map?.allLayers.find(p=>p.id===e.layerId),n=await t.whenLayerView(o),s=o.title??e.layerId,i;if(r){let p=await oe(r,t);if("error"in p){let y={error:p.error};if(Q(r)){let S=t.map?.allLayers.find(T=>T.id===r.layerId);y.geometryLayerName=S?.title??S?.id,y.geometryLayerId=r.layerId,y.geometryWhere=r.where}else te(r)&&(y.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:y}}if(!p.geometry){let y={};if(Q(r)){let S=t.map?.allLayers.find(T=>T.id===r.layerId);y.error=`No features found matching: ${r.where}`,y.geometryLayerName=S?.title??S?.id,y.geometryLayerId=r.layerId,y.geometryWhere=r.where}else te(r)&&(y.error="Failed to create point geometry",y.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:y}}i=p.geometry}else a&&(i=t.extent.clone());let d=xe(n,e.outFields,a??!1),c=o.objectIdField,u=o.createQuery();u.where=re(o.definitionExpression,e.where||"1=1"),u.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,c])],u.orderByFields=e.orderByFields,i&&(u.geometry=i,u.spatialRelationship="intersects"),r?.distance&&(u.distance=r.distance),r?.units&&(u.units=r.units),u.outSpatialReference=t.spatialReference;let h,m;try{h=d?await n.queryFeatureCount(u):await o.queryFeatureCount(u),h>0&&h<=he&&(m=d?await n.queryFeatures(u):await o.queryFeatures(u))}catch(p){console.warn("Client-side query failed, falling back to server:",p),h=await o.queryFeatureCount(u),h>0&&h<=he&&(m=await o.queryFeatures(u))}let{objectIds:w,attributes:b}=m?Ye(o,m,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:s,summary:`${h} features found`,details:{totalCount:h,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...w&&{objectIds:w,objectIdField:c},...b&&{attributes:b},...h>he&&{note:`${h} features found.`}}}};async function La({targetLayer:e,geometryFilter:t,useCurrentExtent:r},a){let{mapView:o}=R(a),n=await Ra(e,o,t,r);return JSON.stringify(n,null,2)}var za=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:L.optional().describe("The units for the distance buffer.")}),ja=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:L.optional().describe("The units for the distance buffer.")}),Oa=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.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:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.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:l.union([za,ja]).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:l.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),Da=f(La,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
53
53
 
54
54
  USE THIS TOOL FOR:
55
55
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -58,15 +58,15 @@ USE THIS TOOL FOR:
58
58
  - Spatial queries \u2014 finding features near/within/intersecting other features
59
59
  - Any question where the user wants to SEE or COUNT matching features
60
60
 
61
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Ca}),Xe=[ma,va,ka,qa],et=[ea,Kr,Pr],Ma=async(e,t)=>{await g({text:"Requesting LLM for layer filter results"},t);let r=await N("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=We(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await j({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:et}),i=[...e.dataExplorationMessages,s];if(!((s.tool_calls?.length??0)>0))return await g({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:i};let d=[...i,s],c=s.content.toString();return await Se(s,t),{...e,dataExplorationMessages:d,outputMessage:c}},Aa=async(e,t)=>{await g({text:"Requesting LLM for layer query results"},t);let r=await N("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=We(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await j({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:Xe}),i=s.content.toString();return await Se(s,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,s],outputMessage:i,status:"success",summary:i?K(i):"Query executed."}},Ra=async(e,t)=>{try{await g({text:"Requesting LLM for summary on query results"},t);let r=await N("summarize_query_response_prompt"),a={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await _e({promptText:r,modelTier:"fast",messages:e.dataExplorationMessages,inputVariables:a}),n=typeof o=="string"?o:o.content,s=new le(n);await g({text:`Received response from LLM: ${n}`},t);let i=n;return{...e,outputMessage:i,status:"success",summary:i?K(i):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,s]}}catch(r){throw await g({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${r instanceof Error?r.message:String(r)}`)}};async function La(e,t){let r=await new A(et).invoke({messages:e.dataExplorationMessages},t);return await g({text:`Finished executing layer filter tool: ${r.messages.map(a=>a.content).join(", ")}`},t),{...e}}var za=new A(Xe);async function ja(e,t){let{messages:r}=await za.invoke({messages:e.dataExplorationMessages},t),a=[],o=[];for(let n of r){let s=n.content,i;typeof s!="string"&&(i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:s}});try{typeof s=="string"?i=JSON.parse(s):i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:s}}}catch{i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:s}}}a.push(i),i.details&&typeof i.details=="object"&&"error"in i.details?o.push(`- ${i.tool}: Error - ${String(i.details.error)}`):o.push(`- ${i.layerName}: ${i.summary}`)}return await g({text:`Finished executing layer query tool: ${o.join(", ")}`},t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,...r],queryResponse:a,status:"success",outputMessage:o.join(`
62
- `),summary:o.length>0?K(o.join(`
63
- `)):"Query executed."}}var Da=10,Oa=["string","small-integer","integer"],Va=async(e,t,{includeSummaryStatistics:r=!0,includeUniqueValues:a=!0}={})=>{let o=null,n=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){r&&(o=await Be({layer:e,field:t.name}));let s=t.domain?.type==="coded-value"?t.domain:null;a&&(Oa.includes(t.type)||s)&&(n=(await Qe({layer:e,field:t.name})).uniqueValueInfos.sort((i,d)=>d.count-i.count).slice(0,Da),s&&(n=n.map(i=>({...i,value:s.getName(i.value)??i.value}))))}}catch(s){console.error(`Error fetching statistics for field ${t.name}:`,s)}return{summaryStatistics:o,uniqueValues:n}};function Ga(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function Pa(e,t,r,a=!0){let o=[],n=[],s=[];for(let i of e){let d=function(y){let m=t.get(y)?.layerItem;return m?[m.name&&`Name: ${m.name}`,m.title&&`Title: ${m.title}`,m.description&&`Description: ${m.description}`].filter(Boolean).join(" | "):y},{layerId:c,results:u}=i,h=r.map?.allLayers.find(y=>y.id===c),p=t.get(c)?.fieldRegistry;if(!p)continue;let b=o.find(y=>y.layerId===c);b||(b={layerId:c,layerSummary:d(c),fieldInfos:[]},o.push(b));for(let y of u){let m=p.get(y.name);if(!m)continue;let w=m.statistics,S=a&&!w?.summaryStatistics,T=Ga(m.type,m.domain?.type)&&!w?.uniqueValues,_=S||T;if(s.push({layerId:c,fieldName:m.name,didFetchStatistics:_}),_){let C=Va(h,m,{includeSummaryStatistics:S,includeUniqueValues:T}).then(W=>{let H={summaryStatistics:w?.summaryStatistics??null,uniqueValues:w?.uniqueValues??null};S&&(H.summaryStatistics=W.summaryStatistics),T&&(H.uniqueValues=W.uniqueValues),p.set(m.name,{...m,statistics:H}),m.statistics=H});n.push(C)}b.fieldInfos.push(m)}}return await Promise.all(n),{layerFieldInfo:o,didFetchStatistics:n.length>0,fieldStatisticsFetchStatus:s}}var ze=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function Ba(e,t){return ze.test(e)||ze.test(t)}var Qa=async(e,t)=>{try{await g({text:"Preparing field information for vector search results"},t);let r=x(t,"layersAndFieldsRegistry"),{mapView:a}=R(t),{assignedTask:o,userRequest:n}=e.agentExecutionContext,s=Ba(o,n),{layerFieldInfo:i,didFetchStatistics:d,fieldStatisticsFetchStatus:c}=await Pa(e.vectorSearchFieldResults,r,a,s);d?await g({text:"Statistics fetched"},t):await g({text:"Statistics skipped"},t);for(let u of c)await g({text:` - ${u.fieldName} - stats ${u.didFetchStatistics?"fetched":"skipped"}`},t);return await g({text:"Field information prepared"},t),{...e,layerFieldInfo:i}}catch(r){throw await g({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${r instanceof Error?r.message:String(r)}`)}},je=.7,Ka=10,Ua=async(e,t)=>{try{await g({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:je,topResults:Ka,embeddingCache:o}),s=n.map(({layerId:d,results:c})=>{let u=c.map(h=>` - ${h.name} (${h.score.toFixed(2)})`).join(`
61
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Oa}),Xe=[xa,_a,Aa,Da],et=[la,ea,Jr],Va=async(e,t)=>{await g({text:"Requesting LLM for layer filter results"},t);let r=await F("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=We(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await j({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:et}),i=[...e.dataExplorationMessages,s];if(!((s.tool_calls?.length??0)>0))return await g({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:i};let d=[...i,s],c=s.content.toString();return await Se(s,t),{...e,dataExplorationMessages:d,outputMessage:c}},Ga=async(e,t)=>{await g({text:"Requesting LLM for layer query results"},t);let r=await F("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=We(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await j({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:Xe}),i=s.content.toString();return await Se(s,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,s],outputMessage:i,status:"success",summary:i?U(i):"Query executed."}},Pa=async(e,t)=>{try{await g({text:"Requesting LLM for summary on query results"},t);let r=await F("summarize_query_response_prompt"),a={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await _e({promptText:r,modelTier:"fast",messages:e.dataExplorationMessages,inputVariables:a}),n=typeof o=="string"?o:o.content,s=new le(n);await g({text:`Received response from LLM: ${n}`},t);let i=n;return{...e,outputMessage:i,status:"success",summary:i?U(i):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,s]}}catch(r){throw await g({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${r instanceof Error?r.message:String(r)}`)}};async function Ba(e,t){let r=await new A(et).invoke({messages:e.dataExplorationMessages},t);return await g({text:`Finished executing layer filter tool: ${r.messages.map(a=>a.content).join(", ")}`},t),{...e}}var Qa=new A(Xe);async function Ka(e,t){let{messages:r}=await Qa.invoke({messages:e.dataExplorationMessages},t),a=[],o=[];for(let n of r){let s=n.content,i;typeof s!="string"&&(i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:s}});try{typeof s=="string"?i=JSON.parse(s):i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:s}}}catch{i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:s}}}a.push(i),i.details&&typeof i.details=="object"&&"error"in i.details?o.push(`- ${i.tool}: Error - ${String(i.details.error)}`):o.push(`- ${i.layerName}: ${i.summary}`)}return await g({text:`Finished executing layer query tool: ${o.join(", ")}`},t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,...r],queryResponse:a,status:"success",outputMessage:o.join(`
62
+ `),summary:o.length>0?U(o.join(`
63
+ `)):"Query executed."}}var Ua=10,Wa=["string","small-integer","integer"],Ha=async(e,t,{includeSummaryStatistics:r=!0,includeUniqueValues:a=!0}={})=>{let o=null,n=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){r&&(o=await Be({layer:e,field:t.name}));let s=t.domain?.type==="coded-value"?t.domain:null;a&&(Wa.includes(t.type)||s)&&(n=(await Qe({layer:e,field:t.name})).uniqueValueInfos.sort((i,d)=>d.count-i.count).slice(0,Ua),s&&(n=n.map(i=>({...i,value:s.getName(i.value)??i.value}))))}}catch(s){console.error(`Error fetching statistics for field ${t.name}:`,s)}return{summaryStatistics:o,uniqueValues:n}};function Za(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function Ja(e,t,r,a=!0){let o=[],n=[],s=[];for(let i of e){let d=function(b){let p=t.get(b)?.layerItem;return p?[p.name&&`Name: ${p.name}`,p.title&&`Title: ${p.title}`,p.description&&`Description: ${p.description}`].filter(Boolean).join(" | "):b},{layerId:c,results:u}=i,h=r.map?.allLayers.find(b=>b.id===c),m=t.get(c)?.fieldRegistry;if(!m)continue;let w=o.find(b=>b.layerId===c);w||(w={layerId:c,layerSummary:d(c),fieldInfos:[]},o.push(w));for(let b of u){let p=m.get(b.name);if(!p)continue;let y=p.statistics,S=a&&!y?.summaryStatistics,T=Za(p.type,p.domain?.type)&&!y?.uniqueValues,_=S||T;if(s.push({layerId:c,fieldName:p.name,didFetchStatistics:_}),_){let C=Ha(h,p,{includeSummaryStatistics:S,includeUniqueValues:T}).then(H=>{let Z={summaryStatistics:y?.summaryStatistics??null,uniqueValues:y?.uniqueValues??null};S&&(Z.summaryStatistics=H.summaryStatistics),T&&(Z.uniqueValues=H.uniqueValues),m.set(p.name,{...p,statistics:Z}),p.statistics=Z});n.push(C)}w.fieldInfos.push(p)}}return await Promise.all(n),{layerFieldInfo:o,didFetchStatistics:n.length>0,fieldStatisticsFetchStatus:s}}var ze=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function Ya(e,t){return ze.test(e)||ze.test(t)}var Xa=async(e,t)=>{try{await g({text:"Preparing field information for vector search results"},t);let r=x(t,"layersAndFieldsRegistry"),{mapView:a}=R(t),{assignedTask:o,userRequest:n}=e.agentExecutionContext,s=Ya(o,n),{layerFieldInfo:i,didFetchStatistics:d,fieldStatisticsFetchStatus:c}=await Ja(e.vectorSearchFieldResults,r,a,s);d?await g({text:"Statistics fetched"},t):await g({text:"Statistics skipped"},t);for(let u of c)await g({text:` - ${u.fieldName} - stats ${u.didFetchStatistics?"fetched":"skipped"}`},t);return await g({text:"Field information prepared"},t),{...e,layerFieldInfo:i}}catch(r){throw await g({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${r instanceof Error?r.message:String(r)}`)}},je=.7,eo=10,to=async(e,t)=>{try{await g({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:je,topResults:eo,embeddingCache:o}),s=n.map(({layerId:d,results:c})=>{let u=c.map(h=>` - ${h.name} (${h.score.toFixed(2)})`).join(`
64
64
  `);return`${a.get(d)?.layerItem.name??d}:
65
65
  ${u}`}).join(`
66
66
  `),i;return n.length>0?i=`Vector search completed. Matching layers and fields with scores:
67
- ${s}`:i=`No vector search results found for score over ${je}.`,await g({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Wa=.7,Ha=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Wa,embeddingCache:o}),s=n.map(c=>c.id),i=n.map(({id:c,score:u})=>`${a.get(c)?.layerItem.name??c} (${u.toFixed(2)})`).join(`
67
+ ${s}`:i=`No vector search results found for score over ${je}.`,await g({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},ro=.7,ao=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:ro,embeddingCache:o}),s=n.map(c=>c.id),i=n.map(({id:c,score:u})=>`${a.get(c)?.layerItem.name??c} (${u.toFixed(2)})`).join(`
68
68
  `),d;return s.length>0?d=`Vector search completed. Matching layers with scores:
69
- ${i}`:d="Vector search completed. No matching layers found.",await g({text:d},t),{...e,vectorSearchLayerIds:s}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Za=(e,t)=>ae(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),Ja=()=>new M(Ue).addNode("requireDataExplorationServices",Za).addNode("vectorSearchLayers",Ha).addNode("vectorSearchFields",Ua).addNode("fieldStatistics",Qa).addNode("queryAgent",Aa).addNode("queryTools",ja).addNode("summarizeQueryResponseLLM",Ra).addNode("filterAgent",Ma).addNode("filterTools",La).addNode("earlyExit",Dr).addEdge(q,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),Ya=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).
69
+ ${i}`:d="Vector search completed. No matching layers found.",await g({text:d},t),{...e,vectorSearchLayerIds:s}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},oo=(e,t)=>ae(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),no=()=>new q(Ue).addNode("requireDataExplorationServices",oo).addNode("vectorSearchLayers",ao).addNode("vectorSearchFields",to).addNode("fieldStatistics",Xa).addNode("queryAgent",Ga).addNode("queryTools",Ka).addNode("summarizeQueryResponseLLM",Pa).addNode("filterAgent",Va).addNode("filterTools",Ba).addNode("earlyExit",Ur).addEdge(M,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),io=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).
70
70
  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.
71
71
  _Example: “Only show stations where Brand is Shell”_
72
72
  _Example: “Make Shell stations stand out on the map”_
@@ -74,13 +74,13 @@ ${i}`:d="Vector search completed. No matching layers found.",await g({text:d},t)
74
74
  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.
75
75
  _Example: “How many features are there?”_
76
76
  _Example: “What’s the average population?”_
77
- _Example: “Which values are in the status field?”_`,ol={id:"dataExploration",name:"Data Exploration Agent",description:Ya,createGraph:Ja,workspace:Ue},De=.7,Xa=10,eo=async(e,t)=>{try{await g({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:De,topResults:Xa,embeddingCache:o}),s=n.map(({layerId:d,results:c})=>{let u=c.map(h=>` - ${h.name} (${h.score.toFixed(2)})`).join(`
77
+ _Example: “Which values are in the status field?”_`,hl={id:"dataExploration",name:"Data Exploration Agent",description:io,createGraph:no,workspace:Ue},Oe=.7,so=10,lo=async(e,t)=>{try{await g({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Oe,topResults:so,embeddingCache:o}),s=n.map(({layerId:d,results:c})=>{let u=c.map(h=>` - ${h.name} (${h.score.toFixed(2)})`).join(`
78
78
  `);return`${a.get(d)?.layerItem.name??d}:
79
79
  ${u}`}).join(`
80
80
  `),i;return n.length>0?i=`Vector search completed. Matching layers and fields with scores:
81
- ${s}`:i=`No vector search results found for score over ${De}.`,await g({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},to=.7,ro=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:to}),n=o.map(d=>d.id),s=o.map(({id:d,score:c})=>`${a.get(d)?.layerItem.name??d} (${c.toFixed(2)})`).join(`
81
+ ${s}`:i=`No vector search results found for score over ${Oe}.`,await g({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},co=.7,uo=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:co}),n=o.map(d=>d.id),s=o.map(({id:d,score:c})=>`${a.get(d)?.layerItem.name??d} (${c.toFixed(2)})`).join(`
82
82
  `),i;return n.length>0?i=`Vector search completed. Matching layers with scores:
83
- ${s}`:i="Vector search completed. No matching layers found.",await g({text:i},t),{...e,vectorSearchLayerIds:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}};async function ao(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n?s=Tt({basemapTheme:await qe(a),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:s=Et({basemapTheme:await qe(a),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:a,attributes:t.map(i=>({field:i,label:r.fields.find(d=>d.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function oo(e){return await xt(e)}async function no({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:n?"chart-size":"chart",fields:a,layer:i,view:s,colorSchemeTags:o};try{let c=await ao(d),u=await oo(c);return i.renderer=u.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying chart renderer: ${c instanceof Error?c.message:String(c)}`}}var io=["mapView"];function $(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=io.filter(a=>!(a in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function so({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await no({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var lo=l.object({layerId:l.string().describe("The id of the layer to apply the chart renderer to"),fields:l.array(l.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),co=f(so,{name:"chart",description:`Label: Charts
83
+ ${s}`:i="Vector search completed. No matching layers found.",await g({text:i},t),{...e,vectorSearchLayerIds:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}};async function ho(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n?s=Ct({basemapTheme:await Me(a),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:s=Mt({basemapTheme:await Me(a),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:a,attributes:t.map(i=>({field:i,label:r.fields.find(d=>d.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function mo(e){return await Ft(e)}async function po({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:n?"chart-size":"chart",fields:a,layer:i,view:s,colorSchemeTags:o};try{let c=await ho(d),u=await mo(c);return i.renderer=u.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying chart renderer: ${c instanceof Error?c.message:String(c)}`}}var go=["mapView"];function $(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=go.filter(a=>!(a in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function fo({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await po({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var yo=l.object({layerId:l.string().describe("The id of the layer to apply the chart renderer to"),fields:l.array(l.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),wo=f(fo,{name:"chart",description:`Label: Charts
84
84
  Description: Show the values of two or more categories as a proportion of the total using a pie chart.
85
85
  Keywords: pie, chart, all categories, breakdown, proportion
86
86
  Example: Show the total number of homes built in each decade using a pie chart for each feature.
@@ -90,19 +90,19 @@ ${s}`:i="Vector search completed. No matching layers found.",await g({text:i},t)
90
90
  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.
91
91
  Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
92
92
  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.
93
- Fields: This style requires 2-8 number fields.`,schema:lo});function uo(e){let{fields:t,layer:r,view:a,theme:o,colorSchemeTags:n}=e,s=t[0],i;return n&&(i=we({geometryType:r.geometryType,includedTags:n,theme:o||"high-to-low"})[0]),{layer:r,view:a,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function ho(e){return await It(e)}async function po({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=uo(d),u=await ho(c);return i.renderer=u.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function mo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await po({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var go=l.object({layerId:l.string().describe("The id of the layer to apply the color-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),fo=f(mo,{name:"color-age",description:`Label: Age (color)
93
+ Fields: This style requires 2-8 number fields.`,schema:yo});function bo(e){let{fields:t,layer:r,view:a,theme:o,colorSchemeTags:n}=e,s=t[0],i;return n&&(i=we({geometryType:r.geometryType,includedTags:n,theme:o||"high-to-low"})[0]),{layer:r,view:a,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function vo(e){return await qt(e)}async function So({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=bo(d),u=await vo(c);return i.renderer=u.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function xo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await So({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var To=l.object({layerId:l.string().describe("The id of the layer to apply the color-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Eo=f(xo,{name:"color-age",description:`Label: Age (color)
94
94
  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.
95
95
  Keywords: since, age, how old, how long
96
96
  Example: Show the age of each feature based on its reported date.
97
- Fields: This style requires at least one field with a date type.`,schema:go});function yo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,{theme:n}=e,s=t[1],i=t[0],d;return o&&(d=we({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:i,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:d}}async function wo(e){return await kt(e)}async function bo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=yo(d),u=await wo(c);return i.renderer=u.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color renderer: ${c instanceof Error?c.message:String(c)}`}}async function vo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await bo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var So=l.object({layerId:l.string().describe("The id of the layer to apply the color renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),xo=f(vo,{name:"color",description:`Label: Counts and Amounts (color)
97
+ Fields: This style requires at least one field with a date type.`,schema:To});function Io(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,{theme:n}=e,s=t[1],i=t[0],d;return o&&(d=we({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:i,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:d}}async function ko(e){return await At(e)}async function $o({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=Io(d),u=await ko(c);return i.renderer=u.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color renderer: ${c instanceof Error?c.message:String(c)}`}}async function _o({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await $o({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var No=l.object({layerId:l.string().describe("The id of the layer to apply the color renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Fo=f(_o,{name:"color",description:`Label: Counts and Amounts (color)
98
98
  Description: Vary color along a continuous color ramp to represent numeric or ranked data.
99
99
  Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
100
100
  Example: Color each feature based on the population density.
101
- 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:So});function To(e){let{fields:t,layer:r,view:a,colorSchemeTags:o,theme:n}=e,s,i,d=t[0];return o&&(i=we({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:d,normalizationField:s,theme:n,colorOptions:{colorScheme:i}}}async function Eo(e){return await $t(e)}async function Io({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color-size-univariate",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=To(d),u=await Eo(c);return i.renderer=u.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color-size-univariate renderer: ${c instanceof Error?c.message:String(c)}`}}async function ko({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Io({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var $o=l.object({layerId:l.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:l.array(l.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),_o=f(ko,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
101
+ 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:No});function Co(e){let{fields:t,layer:r,view:a,colorSchemeTags:o,theme:n}=e,s,i,d=t[0];return o&&(i=we({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:d,normalizationField:s,theme:n,colorOptions:{colorScheme:i}}}async function Mo(e){return await Rt(e)}async function qo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color-size-univariate",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=Co(d),u=await Mo(c);return i.renderer=u.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color-size-univariate renderer: ${c instanceof Error?c.message:String(c)}`}}async function Ao({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await qo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Ro=l.object({layerId:l.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:l.array(l.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Lo=f(Ao,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
102
102
  Description: Vary symbol size and color based on the values of two numeric attributes.
103
103
  Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
104
104
  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.
105
- 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:$o});function Fo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n;return o&&(n=Ft({includedTags:o,numColors:Math.min(t.length,8)})[0]),{layer:r,view:a,legendOptions:{unit:"units"},attributes:t.map(s=>({field:s,label:r.fields.find(i=>i.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function No(e){return await _t(e)}async function Co({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=Fo(i),c=await No(d);return s.renderer=c.renderer,s.visible=!0,`Dot Density renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying dot density renderer: ${d instanceof Error?d.message:String(d)}`}}async function qo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=$(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await Co({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Mo=l.object({layerId:l.string().describe("The id of the layer to apply the dot density renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Ao=f(qo,{name:"dot-density",description:`Dot Density
105
+ 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:Ro});function zo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n;return o&&(n=zt({includedTags:o,numColors:Math.min(t.length,8)})[0]),{layer:r,view:a,legendOptions:{unit:"units"},attributes:t.map(s=>({field:s,label:r.fields.find(i=>i.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function jo(e){return await Lt(e)}async function Oo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=zo(i),c=await jo(d);return s.renderer=c.renderer,s.visible=!0,`Dot Density renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying dot density renderer: ${d instanceof Error?d.message:String(d)}`}}async function Do({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=$(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await Oo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Vo=l.object({layerId:l.string().describe("The id of the layer to apply the dot density renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Go=f(Do,{name:"dot-density",description:`Dot Density
106
106
  Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
107
107
  **Use cases:**
108
108
  - Population distribution visualization
@@ -113,11 +113,11 @@ ${s}`:i="Vector search completed. No matching layers found.",await g({text:i},t)
113
113
  - Visualize distribution of different crops across regions
114
114
  - Display demographic patterns within census tracts
115
115
  **Fields:** Requires 2-8 number fields.
116
- **Keywords:** density, how much, how many, total, number, amount`,schema:Mo});function Ro(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s=t[0];return o&&(n=Ct({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:r,view:a,field:s,heatmapScheme:n}}async function Lo(e){return await Nt(e)}async function zo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=Ro(i),c=await Lo(d);return s.renderer=c.renderer,s.visible=!0,`Heatmap renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying heatmap renderer: ${d instanceof Error?d.message:String(d)}`}}async function jo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=$(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await zo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Do=l.object({layerId:l.string().describe("The id of the layer to apply the heatmap renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Oo=f(jo,{name:"heatmap",description:`Label: Heat Map
116
+ **Keywords:** density, how much, how many, total, number, amount`,schema:Vo});function Po(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s=t[0];return o&&(n=Ot({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:r,view:a,field:s,heatmapScheme:n}}async function Bo(e){return await jt(e)}async function Qo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=Po(i),c=await Bo(d);return s.renderer=c.renderer,s.visible=!0,`Heatmap renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying heatmap renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ko({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=$(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await Qo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Uo=l.object({layerId:l.string().describe("The id of the layer to apply the heatmap renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Wo=f(Ko,{name:"heatmap",description:`Label: Heat Map
117
117
  Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
118
118
  Keywords: density, heatmap, hot spots, pattern, cluster
119
119
  Example: Create a heatmap
120
- Fields: This typically requires zero or one field of type number.`,schema:Do});function Vo(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n&&(s=Mt({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:a,fields:t.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function Go(e){return await qt(e)}async function Po({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:n?"predominance-size":"predominance",fields:a,layer:i,view:s,colorSchemeTags:o};try{let c=Vo(d),u=await Go(c);return i.renderer=u.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying predominance renderer: ${c instanceof Error?c.message:String(c)}`}}async function Bo({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Po({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var Qo=l.object({layerId:l.string().describe("The id of the layer to apply the predominance renderer to"),fields:l.array(l.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),Ko=f(Bo,{name:"predominance",description:`Label: Predominant category
120
+ Fields: This typically requires zero or one field of type number.`,schema:Uo});function Ho(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n&&(s=Vt({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:a,fields:t.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function Zo(e){return await Dt(e)}async function Jo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:n?"predominance-size":"predominance",fields:a,layer:i,view:s,colorSchemeTags:o};try{let c=Ho(d),u=await Zo(c);return i.renderer=u.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying predominance renderer: ${c instanceof Error?c.message:String(c)}`}}async function Yo({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Jo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var Xo=l.object({layerId:l.string().describe("The id of the layer to apply the predominance renderer to"),fields:l.array(l.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),en=f(Yo,{name:"predominance",description:`Label: Predominant category
121
121
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
122
122
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
123
123
  Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
@@ -127,15 +127,15 @@ Fields: This typically requires zero or one field of type number.`,schema:Do});f
127
127
  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.
128
128
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
129
129
  Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
130
- Fields: This style relies on 2-10 number fields.`,schema:Qo});function Uo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s={field:t[0]},i={field:t[1]};return o&&(n=Rt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field1:s,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function Wo(e){return await At(e)}async function Ho({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=Uo(i),c=await Wo(d);return s.renderer=c.renderer,s.visible=!0,`Relationship renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying relationship renderer: ${d instanceof Error?d.message:String(d)}`}}async function Zo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=$(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await Ho({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Jo=l.object({layerId:l.string().describe("The id of the layer to apply the relationship renderer to"),fields:l.array(l.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Yo=f(Zo,{name:"relationship",description:`Label: Relationship
130
+ Fields: This style relies on 2-10 number fields.`,schema:Xo});function tn(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s={field:t[0]},i={field:t[1]};return o&&(n=Pt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field1:s,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function rn(e){return await Gt(e)}async function an({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=tn(i),c=await rn(d);return s.renderer=c.renderer,s.visible=!0,`Relationship renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying relationship renderer: ${d instanceof Error?d.message:String(d)}`}}async function on({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=$(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await an({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var nn=l.object({layerId:l.string().describe("The id of the layer to apply the relationship renderer to"),fields:l.array(l.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),sn=f(on,{name:"relationship",description:`Label: Relationship
131
131
  Description: Overlays two color ramps to represent the relationship between two numeric attributes.
132
132
  Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
133
133
  Example: Show the relationship between tree height and carbon storage
134
- Fields: This style requires two number fields.`,schema:Jo});function Xo(e){let{fields:t,layer:r,view:a,theme:o}=e,n=t[0];return{layer:r,view:a,startTime:n,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function en(e){return await Lt(e)}async function tn({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"size-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=Xo(d),u=await en(c);return i.renderer=u.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying size-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function rn({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await tn({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var an=l.object({layerId:l.string().describe("The id of the layer to apply the size-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),on=f(rn,{name:"size-age",description:`Label: Age (size)
134
+ Fields: This style requires two number fields.`,schema:nn});function ln(e){let{fields:t,layer:r,view:a,theme:o}=e,n=t[0];return{layer:r,view:a,startTime:n,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function cn(e){return await Bt(e)}async function dn({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"size-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=ln(d),u=await cn(c);return i.renderer=u.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying size-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function un({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await dn({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var hn=l.object({layerId:l.string().describe("The id of the layer to apply the size-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),mn=f(un,{name:"size-age",description:`Label: Age (size)
135
135
  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.
136
136
  Keywords: since, age, how old, how long
137
137
  Example: Change the size of features so older features are larger than new features.
138
- Fields: This style requires at least one field with a date type.`,schema:an});function nn(e){let{fields:t,layer:r,view:a}=e,{theme:o}=e,n=t[1],s=t[0];return{layer:r,view:a,field:s,normalizationField:n,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function sn(e){return await zt(e)}async function ln({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"size",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=nn(d),u=await sn(c);return i.renderer=u.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying size renderer: ${c instanceof Error?c.message:String(c)}`}}async function cn({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await ln({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var dn=l.object({layerId:l.string().describe("The id of the layer to apply the size renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),un=f(cn,{name:"size",description:`Label: Counts and Amounts (size)
138
+ Fields: This style requires at least one field with a date type.`,schema:hn});function pn(e){let{fields:t,layer:r,view:a}=e,{theme:o}=e,n=t[1],s=t[0];return{layer:r,view:a,field:s,normalizationField:n,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function gn(e){return await Qt(e)}async function fn({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"size",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=pn(d),u=await gn(c);return i.renderer=u.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying size renderer: ${c instanceof Error?c.message:String(c)}`}}async function yn({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await fn({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var wn=l.object({layerId:l.string().describe("The id of the layer to apply the size renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),bn=f(yn,{name:"size",description:`Label: Counts and Amounts (size)
139
139
  Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
140
140
  Keywords: graduated size, proportional size, how much, total, number, amount, size
141
141
  Example: Vary the size of each point based on the total population.
@@ -145,27 +145,27 @@ Fields: This typically requires zero or one field of type number.`,schema:Do});f
145
145
  Description: Vary symbol sizes along a continuous ramp to represent dates.
146
146
  Keywords: graduated size, proportional size, classed size, how much, total, number, when
147
147
  Example: Vary the size of each feature based on the date a ticket was completed.
148
- Fields: This style requires a single field with a date type.`,schema:dn});function hn(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n=t[0],s=t[1],i=t[2],d;return o&&(d=Dt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field:n,field2:s,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:d}}async function pn(e){return await jt(e)}async function mn({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"type",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=hn(d),u=await pn(c);return i.renderer=u.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying type renderer: ${c instanceof Error?c.message:String(c)}`}}async function gn({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await mn({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var fn=l.object({layerId:l.string().describe("The id of the layer to apply the type renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),yn=f(gn,{name:"type",description:`Label: Types (unique symbols)
148
+ Fields: This style requires a single field with a date type.`,schema:wn});function vn(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n=t[0],s=t[1],i=t[2],d;return o&&(d=Ut({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field:n,field2:s,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:d}}async function Sn(e){return await Kt(e)}async function xn({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"type",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=vn(d),u=await Sn(c);return i.renderer=u.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying type renderer: ${c instanceof Error?c.message:String(c)}`}}async function Tn({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=$(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await xn({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var En=l.object({layerId:l.string().describe("The id of the layer to apply the type renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),In=f(Tn,{name:"type",description:`Label: Types (unique symbols)
149
149
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
150
150
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
151
151
  Example: Color each feature based on the region it belongs to
152
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:fn}),tt=[co,fo,xo,_o,Ao,Oo,Ko,Yo,on,un,yn],rt=(e,t=3)=>{let r=e.map((o,n)=>o.type==="human"?n:-1).filter(o=>o!==-1);if(r.length===0)return[];let a=r.length>t?r[r.length-t]:r[0];return e.slice(a)},wn=async(e,t)=>{await g({text:"Requesting LLM for layer query results"},t);let r=await N("navigation_intent_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await j({promptText:r,modelTier:"advanced",messages:rt(e.agentExecutionContext.messages),inputVariables:a,tools:tt});return await Se(o,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,o]}}};async function bn(e,t){let r=await new A(tt).invoke({messages:rt(e.agentExecutionContext.messages)},t),a=r.messages.map(n=>n.text).join(`
152
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:En}),tt=[wo,Eo,Fo,Lo,Go,Wo,en,sn,mn,bn,In],rt=(e,t=3)=>{let r=e.map((o,n)=>o.type==="human"?n:-1).filter(o=>o!==-1);if(r.length===0)return[];let a=r.length>t?r[r.length-t]:r[0];return e.slice(a)},kn=async(e,t)=>{await g({text:"Requesting LLM for layer query results"},t);let r=await F("navigation_intent_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await j({promptText:r,modelTier:"advanced",messages:rt(e.agentExecutionContext.messages),inputVariables:a,tools:tt});return await Se(o,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,o]}}};async function $n(e,t){let r=await new A(tt).invoke({messages:rt(e.agentExecutionContext.messages)},t),a=r.messages.map(n=>n.text).join(`
153
153
  `);await g({text:`Finished executing layer filter tool: ${a}`},t);let o=r.messages.map(n=>n.text).join(`
154
- `);return{...e,outputMessage:o}}var at=v.Root({...G(),vectorSearchLayerIds:v(),vectorSearchFieldResults:v(),layerFieldInfo:v(),selectedLayerId:v()}),vn=async(e,t)=>(await g({text:"Exiting Layer Styling agent"},t),e),Sn=async(e,t)=>{try{await g({text:"Populating layer and field info"},t);let r=[];for(let a of e.vectorSearchFieldResults){let o=function(u){let h=i.get(u)?.layerItem;return h?[h.name&&`Name: ${h.name}`,h.title&&`Title: ${h.title}`,h.description&&`Description: ${h.description}`].filter(Boolean).join(" | "):u},{layerId:n,results:s}=a,i=x(t,"layersAndFieldsRegistry"),d=i.get(n)?.fieldRegistry;if(!d)continue;let c=r.find(u=>u.layerId===n);c||(c={layerId:n,layerSummary:o(n),fieldInfos:[]},r.push(c));for(let u of s){let h=d.get(u.name);h&&c.fieldInfos.push(h)}}return await g({text:"Populated layerFieldInfo"},t),{...e,layerFieldInfo:r}}catch(r){throw await g({text:"Error populating layerFieldInfo"},t),new Error(`Error populating layerFieldInfo: ${r instanceof Error?r.message:String(r)}`)}},xn=(e,t)=>{let r=e.vectorSearchLayerIds??[];if(r.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=t.configurable;if(!a||a.agentId!==Oe.id||a.id!=="reviewLayerSelection"){let n={agentId:Oe.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...r]};throw new Ee(n)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},Tn=(e,t)=>ae(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,t),En=()=>new M(at).addNode("requireLayerStylingServices",Tn).addNode("vectorSearchLayers",ro).addNode("layerSelectionHITL",xn).addNode("vectorSearchFields",eo).addNode("populateLayerFieldInfo",Sn).addNode("agent",wn).addNode("tools",bn).addNode("earlyExit",vn).addEdge(q,"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),In=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.
154
+ `);return{...e,outputMessage:o}}var at=v.Root({...P(),vectorSearchLayerIds:v(),vectorSearchFieldResults:v(),layerFieldInfo:v(),selectedLayerId:v()}),_n=async(e,t)=>(await g({text:"Exiting Layer Styling agent"},t),e),Nn=async(e,t)=>{try{await g({text:"Populating layer and field info"},t);let r=[];for(let a of e.vectorSearchFieldResults){let o=function(u){let h=i.get(u)?.layerItem;return h?[h.name&&`Name: ${h.name}`,h.title&&`Title: ${h.title}`,h.description&&`Description: ${h.description}`].filter(Boolean).join(" | "):u},{layerId:n,results:s}=a,i=x(t,"layersAndFieldsRegistry"),d=i.get(n)?.fieldRegistry;if(!d)continue;let c=r.find(u=>u.layerId===n);c||(c={layerId:n,layerSummary:o(n),fieldInfos:[]},r.push(c));for(let u of s){let h=d.get(u.name);h&&c.fieldInfos.push(h)}}return await g({text:"Populated layerFieldInfo"},t),{...e,layerFieldInfo:r}}catch(r){throw await g({text:"Error populating layerFieldInfo"},t),new Error(`Error populating layerFieldInfo: ${r instanceof Error?r.message:String(r)}`)}},Fn=(e,t)=>{let r=e.vectorSearchLayerIds??[];if(r.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=t.configurable;if(!a||a.agentId!==De.id||a.id!=="reviewLayerSelection"){let n={agentId:De.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...r]};throw new Ee(n)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},Cn=(e,t)=>ae(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,t),Mn=()=>new q(at).addNode("requireLayerStylingServices",Cn).addNode("vectorSearchLayers",uo).addNode("layerSelectionHITL",Fn).addNode("vectorSearchFields",lo).addNode("populateLayerFieldInfo",Nn).addNode("agent",kn).addNode("tools",$n).addNode("earlyExit",_n).addEdge(M,"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),qn=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.
155
155
  _Example: “Color points by sales amount”_
156
156
  _Example: “Show population density with a color gradient”_
157
157
  _Example: “Create a relationship map between height and depth”_
158
- _Example: “Vary circle sizes according to population”_`,Oe={id:"layerStyling",name:"Layer Styling Agent",description:In,createGraph:En,workspace:at},ot=v.Root({...G(),helpInternalState:v({reducer:P,default:()=>({toolCallMessage:void 0})})}),kn=(e,t)=>{let r=Array.from(e.values()).find(({layerItem:n})=>n.title?.toLowerCase().includes(t.toLowerCase()));if(!r){let n=Array.from(e.values()).map(s=>s.layerItem.title).join(", ");return`Could not find a layer matching "${t}". Available layers: ${n}`}let a=Array.from(r.fieldRegistry.values()),o=a.map(n=>`- **${n.alias||n.name}** (\`${n.name}\`, ${n.type})${n.description?`: ${n.description}`:""}`).join(`
158
+ _Example: “Vary circle sizes according to population”_`,De={id:"layerStyling",name:"Layer Styling Agent",description:qn,createGraph:Mn,workspace:at},ot=v.Root({...P(),helpInternalState:v({reducer:B,default:()=>({toolCallMessage:void 0})})}),An=(e,t)=>{let r=Array.from(e.values()).find(({layerItem:n})=>n.title?.toLowerCase().includes(t.toLowerCase()));if(!r){let n=Array.from(e.values()).map(s=>s.layerItem.title).join(", ");return`Could not find a layer matching "${t}". Available layers: ${n}`}let a=Array.from(r.fieldRegistry.values()),o=a.map(n=>`- **${n.alias||n.name}** (\`${n.name}\`, ${n.type})${n.description?`: ${n.description}`:""}`).join(`
159
159
  `);return`**${r.layerItem.title}** has ${a.length} field(s):
160
160
 
161
- ${o}`},$n=async({layerTitle:e},t)=>{let r=x(t,"layersAndFieldsRegistry");return kn(r,e)},_n=f($n,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:l.object({layerTitle:l.string().describe("The title or partial title of the layer to list fields for.")})}),nt=[_n],Fn=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:a},o)=>{let n=Array.from(a.values()).map(i=>i.name).slice(0,10).join(", "),s=a.size>10?` (and ${a.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
161
+ ${o}`},Rn=async({layerTitle:e},t)=>{let r=x(t,"layersAndFieldsRegistry");return An(r,e)},Ln=f(Rn,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:l.object({layerTitle:l.string().describe("The title or partial title of the layer to list fields for.")})}),nt=[Ln],zn=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:a},o)=>{let n=Array.from(a.values()).map(i=>i.name).slice(0,10).join(", "),s=a.size>10?` (and ${a.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
162
162
  Fields: ${n}${s}`}).join(`
163
163
 
164
164
  `);return`This map contains ${e.size} layer(s):
165
165
 
166
- ${t}`},Nn=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: ${r.agent.description}`).join(`
167
- `):"No agents currently available."};async function Cn(e,t){let r=await N("help_prompt"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"agentRegistry");try{let n=await j({promptText:r,modelTier:"fast",tools:nt,inputVariables:{layerSummary:Fn(a),agents:Nn(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}}),s=(n.tool_calls?.length??0)>0,i=typeof n.text=="string"?n.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:s?n:void 0},outputMessage:s?e.outputMessage:i,summary:s?"Prepared help tool call from assigned task.":"Provided map-related help based on the assigned task.",status:s?e.status:"success"}}catch(n){let s=n instanceof Error?n.message:String(n);return{...e,outputMessage:`Error invoking help agent: ${s}`,summary:"Help agent execution failed.",status:"failed"}}}var qn=(e,t)=>ae(["agentRegistry"],"Help Agent")(e,t);async function Mn(e,t){let r=new A(nt);try{let a=e.helpInternalState.toolCallMessage;if(!a)throw new Error("helpToolCalling: missing helpInternalState.toolCallMessage");let o=(await r.invoke({messages:[a]},t)).messages.map(n=>n.text).join(`
168
- `);return await g({text:`Finished executing help tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?K(o):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await g({text:`Help tool execution failed: ${o}`},t),{...e,outputMessage:`Help tool execution failed: ${o}`,status:"failed",summary:`Help tool execution failed: ${o}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var An=()=>new M(ot).addNode("requireHelpServices",qn).addNode("agent",Cn).addNode("tools",Mn).addEdge(q,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":E).addEdge("tools",E),Rn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
166
+ ${t}`},jn=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: ${r.agent.description}`).join(`
167
+ `):"No agents currently available."};async function On(e,t){let r=await F("help_prompt"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"agentRegistry");try{let n=await j({promptText:r,modelTier:"fast",tools:nt,inputVariables:{layerSummary:zn(a),agents:jn(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}}),s=(n.tool_calls?.length??0)>0,i=typeof n.text=="string"?n.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:s?n:void 0},outputMessage:s?e.outputMessage:i,summary:s?"Prepared help tool call from assigned task.":"Provided map-related help based on the assigned task.",status:s?e.status:"success"}}catch(n){let s=n instanceof Error?n.message:String(n);return{...e,outputMessage:`Error invoking help agent: ${s}`,summary:"Help agent execution failed.",status:"failed"}}}var Dn=(e,t)=>ae(["agentRegistry"],"Help Agent")(e,t);async function Vn(e,t){let r=new A(nt);try{let a=e.helpInternalState.toolCallMessage;if(!a)throw new Error("helpToolCalling: missing helpInternalState.toolCallMessage");let o=(await r.invoke({messages:[a]},t)).messages.map(n=>n.text).join(`
168
+ `);return await g({text:`Finished executing help tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?U(o):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await g({text:`Help tool execution failed: ${o}`},t),{...e,outputMessage:`Help tool execution failed: ${o}`,status:"failed",summary:`Help tool execution failed: ${o}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var Gn=()=>new q(ot).addNode("requireHelpServices",Dn).addNode("agent",On).addNode("tools",Vn).addEdge(M,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":E).addEdge("tools",E),Pn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
169
169
 
170
170
  _Example: “Tell me about this map”_
171
171
  _Example: “List all layers in this map”_
@@ -178,59 +178,57 @@ ${t}`},Nn=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: $
178
178
 
179
179
  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.
180
180
  _Example: "Create a chart"_
181
- _Example: "Create a table"_`,nl={id:"help",name:"Help Agent",description:Rn,createGraph:An,workspace:ot},il=v.Root({...G(),intent:v({reducer:(e,t)=>t}),arcgisKnowledgeMessages:v({reducer:V,default:()=>[]})}),X={conversationId:""},Ln=["linkChartView"],pe=["knowledgeGraph","linkChartView"];function ne(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=Ln.filter(a=>!(a in t));if(r.length)throw new Error(`Link Chart context missing: ${r.join(", ")}`);return t}async function U(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=pe.find(a=>a in t);if(!r||pe.every(a=>a in t))throw new Error(`Knowledge Graph context should be exactly one of ${pe.join(", ")}`);if(r==="knowledgeGraph")return t;{let a=t.linkChartView.map.knowledgeGraph.url;if(!a)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Ot(a)}}}var ge=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=fe.fromDataModel(t)}},fe=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let a of t.entityTypes)r.entityTypes.push(Q.fromEntityType(a));for(let a of t.relationshipTypes)r.relationshipTypes.push(ye.fromRelationshipType(a));return r.identifierInfo={mappingInfo:{identifierMapsTo:zn(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}},Q=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(t){let r=new e;r.name=t.name,r.alias=t.alias?t.alias:void 0,r.role=jn(t.role);for(let a of t.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:Dn(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};r.properties.push(o)}return r}},ye=class extends Q{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=Q.fromEntityType(t);r.observedEndPoints=[];for(let a of t.endPoints)r.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return r}},zn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},jn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function Dn(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 On(e,t,r,a){let{graphQuery:o,explanation:n}=await ie(e,t,r,a);return`Generated Graph Query:
181
+ _Example: "Create a table"_`,ml={id:"help",name:"Help Agent",description:Pn,createGraph:Gn,workspace:ot},pl=v.Root({...P(),intent:v({reducer:(e,t)=>t}),arcgisKnowledgeMessages:v({reducer:G,default:()=>[]}),arcgisKnowledgeToolResult:v({reducer:(e,t)=>t,default:()=>null})}),ee={conversationId:""},Bn=["linkChartView"],me=["knowledgeGraph","linkChartView"];function ne(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=Bn.filter(a=>!(a in t));if(r.length)throw new Error(`Link Chart context missing: ${r.join(", ")}`);return t}async function W(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=me.find(a=>a in t);if(!r||me.every(a=>a in t))throw new Error(`Knowledge Graph context should be exactly one of ${me.join(", ")}`);if(r==="knowledgeGraph")return t;{let a=t.linkChartView.map.knowledgeGraph.url;if(!a)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Wt(a)}}}var ge=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=fe.fromDataModel(t)}},fe=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let a of t.entityTypes)r.entityTypes.push(K.fromEntityType(a));for(let a of t.relationshipTypes)r.relationshipTypes.push(ye.fromRelationshipType(a));return r.identifierInfo={mappingInfo:{identifierMapsTo:Qn(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}static getDataModelTypesSummary(t){let r=t.entityTypes.map(o=>o.name).join(", "),a=t.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
182
+ Relationship Types: ${a}.`}},K=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(t){let r=new e;r.name=t.name,r.alias=t.alias?t.alias:void 0,r.role=Kn(t.role);for(let a of t.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:Un(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};r.properties.push(o)}return r}},ye=class extends K{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=K.fromEntityType(t);r.observedEndPoints=[];for(let a of t.endPoints)r.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return r}},Qn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},Kn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function Un(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 Wn(e,t,r,a){let{graphQuery:o,explanation:n}=await ie(e,t,r,a);return`Generated Graph Query:
182
183
  ${o}
183
184
 
184
- Explanation: ${n}`}async function ie(e,t,r,a){let o={message:e,context:new ge(t)};X.conversationId&&(o.conversationId=X.conversationId),await g({text:"Attempting to generate a cypher query from your prompt..."},a);let n=await Me(`${r}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Ae.findCredential(z.getDefault().url)?.token??""}});if(n.httpStatus!==200)throw new Error(`Graph query service returned an error: ${n.httpStatus}`,{cause:n.data});X.conversationId||(X.conversationId=n.data.conversationId);let s=!1,i=Date.now(),d=n.data.sequenceNumber,c="",u="",h=1;for(;!s;){await new Promise(b=>setTimeout(b,1e3)),await g({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,h)}`},a),h=h%3+1;let p=await Me(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:n.data.conversationId,inquiryId:n.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:Ae.findCredential(z.getDefault().url)?.token??""}});if(p.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${p.httpStatus}`,{cause:p.data});if(p.data.context)c=p.data.context.graphQuery,u=p.data.message||"";else if(!p.data.hasMore)s=!0;else if(Date.now()-i>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=p.data.sequenceNumber}return{graphQuery:c,explanation:u}}function it(e){return typeof e!="object"||e===null?String(e):"details"in e&&typeof e.details=="object"&&e.details!==null&&"errorMessage"in e.details&&typeof e.details.errorMessage=="string"?e.details.errorMessage:"message"in e&&typeof e.message=="string"?e.message:String(e)}var st=async({kg:e,queryParams:t,targetStructure:r,targetStructureReducer:a,requestOptions:o,queryRowLimit:n,queryTimeoutMs:s})=>{let i=null,d=r,c=new AbortController,u=o?.signal,h=()=>{c.abort(u?.reason)};u&&(u.aborted?c.abort(u.reason):u.addEventListener("abort",h,{once:!0}));try{let p=await Vt(e,t,o);i=p.resultHeader;let b=p.resultRowsStream.getReader(),y=0,m=Date.now(),w=!1;for(;;){let{done:S,value:T}=await b.read();if(S)break;if(!w&&s&&Date.now()-m>s)return c.abort(),{type:"timeout"};for(let _ of T){if(y++,n&&y>n)return c.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:d};d=a(d,_)}}}catch(p){return c.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:it(p),error:p}}finally{u?.removeEventListener("abort",h)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:d}},Vn=(e,t)=>{let{id:r,typeName:a,properties:o}=t,n=[...e.dataModel.entityTypes,...e.dataModel.relationshipTypes].find(d=>d.name===a);if(!n)return r;let s=4,i=r;for(let d of n.properties.filter(c=>c.fieldType==="esriFieldTypeString")){let c=d.name;if(c?.toLowerCase()==="name"){i=o[c];break}else c?.toLowerCase().includes("name")&&s>2?(i=o[c],s=2):d.fieldType==="esriFieldTypeString"&&s>3&&(i=o[c],s=3)}return i||r},Gn=async({kg:e,searchQuery:t,typeCategoryFilter:r,namedTypesFilter:a,searchResultLimit:o,requestOptions:n})=>{let s=[],i=[r];r==="both"&&!e.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let d=o??1/0;try{for(let c of i){if(d-s.length<=0)break;let u=(await Gt(e,new Pt({searchQuery:t,typeCategoryFilter:c,namedTypesFilter:a??void 0,num:o}),n)).resultRowsStream.getReader(),h=!1;for(;!h;){let{done:p,value:b}=await u.read();if(p){h=!0;break}for(let y of b)for(let m of y)s.push(m)}}}catch(c){return console.log('Error when running graph search with query: "',t,'" - error: ',c),n?.signal?.aborted?{type:"aborted"}:{type:"error",errorMessage:it(c),error:c}}return{type:"success",results:s}};function ee(e,t){if(!(!e||typeof e!="object")){if(Bn(e))for(let r of e.path)ee(r,t);else if(Pn(e))t.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let r of e)ee(r,t);else if(Qn(e))for(let r of Object.values(e.properties??{}))ee(r,t)}}function Pn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Bn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Qn(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function Kn(e,t){let r=[];for(let a of[...t.dataModel.entityTypes,...t.dataModel.relationshipTypes]){let o=e.getMemberIdsByType(a.name);for(let n of o)r.push({id:n,typeName:a.name})}return r}async function Un(e,t,r,a,o){let{graphQuery:n,explanation:s}=await ie(e,t.dataModel,r,o);await g({text:`Attempting to execute query: ${n.substring(0,500)}${n.length>500?"...":""}`},o);let i=await st({kg:t,queryParams:new be({openCypherQuery:n}),targetStructure:new Map,targetStructureReducer:(d,c)=>{for(let u of c)ee(u,d);return d},requestOptions:{signal:o?.signal,timeout:o?.timeout}});if(i.type==="success"){let d=i.processedResult,c=Array.from(d.values());return await g({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:
185
+ Explanation: ${n}`}async function ie(e,t,r,a){let o={message:e,context:new ge(t)};ee.conversationId&&(o.conversationId=ee.conversationId),await g({text:"Attempting to generate a cypher query from your prompt..."},a);let n=await qe(`${r}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Ae.findCredential(z.getDefault().url)?.token??""}});if(n.httpStatus!==200)throw new Error(`Graph query service returned an error: ${n.httpStatus}`,{cause:n.data});ee.conversationId||(ee.conversationId=n.data.conversationId);let s=!1,i=Date.now(),d=n.data.sequenceNumber,c="",u="",h=1;for(;!s;){await new Promise(w=>setTimeout(w,1e3)),await g({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,h)}`},a),h=h%3+1;let m=await qe(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:n.data.conversationId,inquiryId:n.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:Ae.findCredential(z.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)c=m.data.context.graphQuery,u=m.data.message||"";else if(!m.data.hasMore)s=!0;else if(Date.now()-i>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=m.data.sequenceNumber}return{graphQuery:c,explanation:u}}function it(e,t=100){let r={};for(let a of Object.entries(e.properties??{})){let[o,n]=a;typeof n=="string"&&n.length>t?r[o]=`${n.slice(0,t)}... (truncated, original length: ${n.length})`:r[o]=n}return e.properties=r,e}function st(e){return typeof e!="object"||e===null?String(e):"details"in e&&typeof e.details=="object"&&e.details!==null&&"errorMessage"in e.details&&typeof e.details.errorMessage=="string"?e.details.errorMessage:"message"in e&&typeof e.message=="string"?e.message:String(e)}var lt=async({kg:e,queryParams:t,targetStructure:r,targetStructureReducer:a,requestOptions:o,queryRowLimit:n,queryTimeoutMs:s})=>{let i=null,d=r,c=new AbortController,u=o?.signal,h=()=>{c.abort(u?.reason)};u&&(u.aborted?c.abort(u.reason):u.addEventListener("abort",h,{once:!0}));try{let m=await Ht(e,t,o);i=m.resultHeader;let w=m.resultRowsStream.getReader(),b=0,p=Date.now(),y=!1;for(;;){let{done:S,value:T}=await w.read();if(S)break;if(!y&&s&&Date.now()-p>s)return c.abort(),{type:"timeout"};for(let _ of T){if(b++,n&&b>n)return c.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:d};d=a(d,_)}}}catch(m){return c.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:st(m),error:m}}finally{u?.removeEventListener("abort",h)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:d}},Hn=async({kg:e,searchQuery:t,typeCategoryFilter:r,namedTypesFilter:a,searchResultLimit:o,requestOptions:n})=>{let s=[],i=[r];r==="both"&&!e.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let d=o??1/0;try{for(let c of i){let u=d-s.length;if(u<=0)break;let h=(await Zt(e,new Jt({searchQuery:t,typeCategoryFilter:c,namedTypesFilter:a??void 0,num:u}),n)).resultRowsStream.getReader(),m=!1;for(;!m;){let{done:w,value:b}=await h.read();if(w){m=!0;break}for(let p of b)for(let y of p)s.push(y)}}}catch(c){return console.log('Error when running graph search with query: "',t,'" - error: ',c),n?.signal?.aborted?{type:"aborted"}:{type:"error",errorMessage:st(c),error:c}}return{type:"success",results:s}};function Zn(e,t){O(e,r=>{t.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function O(e,t){if(!(!e||typeof e!="object")){if(Yn(e))for(let r of e.path)O(r,t);else if(Jn(e))t(e);else if(Array.isArray(e))for(let r of e)O(r,t);else if(Xn(e))for(let r of Object.values(e.properties??{}))O(r,t)}}function Jn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Yn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Xn(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function ei(e,t){let r=[];for(let a of[...t.dataModel.entityTypes,...t.dataModel.relationshipTypes]){let o=e.getMemberIdsByType(a.name);for(let n of o)r.push({id:n,typeName:a.name})}return r}async function ti(e,t,r,a,o){let{graphQuery:n,explanation:s}=await ie(e,t.dataModel,r,o);await g({text:`Attempting to execute query: ${n.substring(0,500)}${n.length>500?"...":""}`},o);let i=await lt({kg:t,queryParams:new be({openCypherQuery:n}),targetStructure:new Map,targetStructureReducer:(d,c)=>{for(let u of c)Zn(u,d);return d},requestOptions:{signal:o?.signal,timeout:o?.timeout}});if(i.type==="success"){let d=i.processedResult,c=Array.from(d.values());return await g({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:
185
186
  ${n}
186
187
 
187
- Explanation: ${s}`}else throw new Error(`Failed to execute query. Reason: ${i.type==="aborted"?"Query was aborted.":i.type==="timeout"?"Query timed out.":`Error message: ${i.errorMessage}`}`)}async function Wn({prompt:e},t){let{knowledgeGraph:r}=await U(t),{linkChartView:a}=ne(t),o=z.getDefault().helperServices,n=await N("arcgis_knowledge_current_lc_context"),s=Kn(a.map,r),i=`${e}
188
+ Explanation: ${s}`}else throw new Error(`Failed to execute query. Reason: ${i.type==="aborted"?"Query was aborted.":i.type==="timeout"?"Query timed out.":`Error message: ${i.errorMessage}`}`)}var ct="addRecords",ri=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),ai=async({prompt:e},t)=>{let{knowledgeGraph:r}=await W(t),{linkChartView:a}=ne(t),o=z.getDefault().helperServices,n=await F("arcgis_knowledge_current_lc_context"),s=ei(a.map,r),i=`${e}
188
189
 
189
- ${n}${JSON.stringify(s)}`;return await Un(i,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Hn=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),sl=f(Wn,{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:Hn});async function Zn(e,t){return await t.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function Jn({layout:e},t){let{linkChartView:r}=ne(t);return await Zn(e,r)}var Yn=l.object({layout:l.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")}),ll=f(Jn,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:Yn});function Xn(e,t){return t.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function ei({setting:e},t){let{linkChartView:r}=ne(t);return Xn(e,r)}var ti=l.object({setting:l.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),cl=f(ei,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:ti});async function ri(e,t,r,a,o){let{graphQuery:n,explanation:s}=await ie(e,t.dataModel,r,o);await g({text:`Attempting to create link chart from derived query: ${n}`},o);let i=await Bt.fromCypherQuery(t,new be({openCypherQuery:n}));return await g({text:"Link chart created successfully, loading..."},o),a.map=i,await i.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart:
190
+ ${n}${JSON.stringify(s)}`,d=await ti(i,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t);return{toolName:ct,status:"success",summary:d}},gl=f(ai,{name:ct,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:ri});async function oi(e,t){return await t.map.applyLayout(e),`Successfully applied layout: ${e}.`}var dt="applyLayout",ni=l.object({layout:l.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")}),ii=async({layout:e},t)=>{let{linkChartView:r}=ne(t),a=await oi(e,r);return{toolName:dt,status:"success",summary:a}},fl=f(ii,{name:dt,description:"Apply a diagram layout to the link chart",schema:ni});function si(e,t){return t.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}var ut="changeNonspatialVisibility",li=l.object({setting:l.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),ci=async({setting:e},t)=>{let{linkChartView:r}=ne(t),a=si(e,r);return{toolName:ut,status:"success",summary:a}},yl=f(ci,{name:ut,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:li});async function di(e,t,r,a,o){let{graphQuery:n,explanation:s}=await ie(e,t.dataModel,r,o);await g({text:`Attempting to create link chart from derived query: ${n}`},o);let i=await Yt.fromCypherQuery(t,new be({openCypherQuery:n}));return await g({text:"Link chart created successfully, loading..."},o),a.map=i,await i.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart:
190
191
  ${n}
191
192
 
192
- Explanation: ${s}`}async function ai({prompt:e},t){let{knowledgeGraph:r}=await U(t),{linkChartView:a}=ne(t),o=z.getDefault().helperServices;return await ri(e,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var oi=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),dl=f(ai,{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:oi});async function ni({prompt:e},t){let{knowledgeGraph:r}=await U(t),a=z.getDefault().helperServices,{graphQuery:o}=await ie(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t);await g({text:"Attempting to execute the generated cypher query..."},t);let n=await st({kg:r,queryParams:new be({openCypherQuery:o}),targetStructure:new Array,targetStructureReducer:(u,h)=>(u.push(h),u),requestOptions:{signal:t?.signal,timeout:t?.timeout}});if(n.type!=="success")throw new Error(n.type==="aborted"?"Query was aborted.":n.type==="timeout"?"Query timed out.":`Query failed with error: ${n.errorMessage}`);let{processedResult:s,resultHeader:i}=n,d=i.headerKeys,c=`| ${d.join(" | ")} |
193
- `;c+=`| ${d.map(()=>"---").join(" | ")} |
194
- `;for(let u of s){let h=u.map(p=>typeof p=="object"?JSON.stringify(p):String(p));c+=`| ${h.join(" | ")} |
195
- `}return`To answer the inquiry, the following cypher query was executed against the knowledge graph:
193
+ Explanation: ${s}`}var ht="createLinkChart",ui=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),hi=async({prompt:e},t)=>{let{knowledgeGraph:r}=await W(t),{linkChartView:a}=ne(t),o=z.getDefault().helperServices,n=await di(e,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t);return{toolName:ht,status:"success",summary:n}},wl=f(hi,{name:ht,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:ui}),mt="queryGraphData",mi=l.object({prompt:l.string().describe(`The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. IMPORTANT:
194
+
195
+ REQUEST LIMIT: If the user does not specifically request for no limits or an explicit limit to be placed on the query, or the number of rows will not be limited by e.g. the number of entity or relationship types in the graph, ensure that the generated query has a reasonable row limit (e.g. 10 rows).
196
+
197
+ DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),pi=async({prompt:e},t)=>{let{knowledgeGraph:r}=await W(t),a=z.getDefault().helperServices,{graphQuery:o}=await ie(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t);await g({text:"Attempting to execute the generated cypher query..."},t);let n=await lt({kg:r,queryParams:new be({openCypherQuery:o}),targetStructure:new Array,targetStructureReducer:(h,m)=>(h.push(m),h),requestOptions:{signal:t?.signal,timeout:t?.timeout}});if(n.type!=="success")throw new Error(n.type==="aborted"?"Query was aborted.":n.type==="timeout"?"Query timed out.":`Query failed with error: ${n.errorMessage}`);let{processedResult:s,resultHeader:i}=n,d=i.headerKeys;for(let h of s)for(let m of h)O(m,w=>it(w));let c=50,u=s.slice(0,c).map(h=>JSON.stringify(h));return{toolName:mt,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
196
198
 
197
199
  \`\`\`cypher
198
200
  ${o}
199
201
  \`\`\`
200
202
 
201
203
  Query Results:
204
+ ${u.length} result(s) found.
202
205
 
203
- ${c}
204
- `}var ii=l.object({prompt:l.string().describe(`The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. IMPORTANT:
206
+ Column Headers: ${d.join(", ")}
205
207
 
206
- REQUEST LIMIT: If the user does not specifically request for no limits or an explicit limit to be placed on the query, or the number of rows will not be limited by e.g. the number of entity or relationship types in the graph, ensure that the generated query has a reasonable row limit (e.g. 10 rows).
208
+ ${u.length>c?`Showing top ${c} results:
207
209
 
208
- DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),ul=f(ni,{name:"queryGraphData",description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:ii});async function si({prompt:e},t){let{knowledgeGraph:r}=await U(t),a=z.getDefault().helperServices;return await On(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t)}var li=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),hl=f(si,{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:li}),ci=e=>{let t=e.dataModel,r=new Map;for(let i of t.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[d,c]of i.searchProperties.entries()){let u=r.get(d)??new Set;c.propertyNames.forEach(h=>u.add(h)),r.set(d,u)}let a=t.entityTypes.filter(i=>r.has(i.name)),o=t.relationshipTypes.filter(i=>r.has(i.name)),n=`Entity Types:
210
+ `:`Results:
211
+
212
+ `}${u.join(`
213
+ `)}
214
+ `,details:{generatedQuery:o,resultHeader:i,queryResults:s}}},bl=f(pi,{name:mt,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:mi}),pt="generateCypher",gi=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),fi=async({prompt:e},t)=>{let{knowledgeGraph:r}=await W(t),a=z.getDefault().helperServices,o=await Wn(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t);return{toolName:pt,status:"success",summary:o}},vl=f(fi,{name:pt,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:gi}),yi=e=>{let t=e.dataModel,r=new Map;for(let i of t.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[d,c]of i.searchProperties.entries()){let u=r.get(d)??new Set;c.propertyNames.forEach(h=>u.add(h)),r.set(d,u)}let a=t.entityTypes.filter(i=>r.has(i.name)),o=t.relationshipTypes.filter(i=>r.has(i.name)),n=`Entity Types:
209
215
  ${a.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
210
216
  `)}`,s=`Relationship Types:
211
217
  ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
212
218
  `)}`;return`${n}
213
219
 
214
- ${s}`};async function di(e,t){let r=await N("arcgis_knowledge_lucene_generation_prompt"),a={inquiry:e,dataModelForSearch:ci(t)},o=l.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),n=l.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),s=l.array(l.enum(t.dataModel.entityTypes.map(d=>d.name).concat(t.dataModel.relationshipTypes.map(d=>d.name)))).min(1),i=l.object({query:l.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:s.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:o,resultLimit:n});return await ce({promptText:r,inputVariables:a,schema:i})}async function ui({prompt:e},t){let{knowledgeGraph:r}=await U(t);await g({text:"Generating search query for the user inquiry"},t);let a=await di(e,r);await g({text:"Executing graph search with generated search query"},t);let o=await Gn({kg:r,searchQuery:a.query,typeCategoryFilter:a.typeCategoryFilter,namedTypesFilter:a.typeFilters,searchResultLimit:a.resultLimit,requestOptions:{signal:t?.signal,timeout:t?.timeout}});if(o.type!=="success")throw new Error(`Graph search failed with error: ${o.type==="error"?o.errorMessage:"aborted"}`);let n=10,s=` Name | Type | ID
215
- --- | --- | ---
216
- `;for(let i of o.results.slice(0,Math.min(n,o.results.length))){let d=Vn(r,i);s+=` ${d} | ${i.typeName} | ${i.id}
217
- `}return o.results.length>n&&o.results.length<100?s+=`...and ${o.results.length-n} more result(s)
218
- `:o.results.length>=100?s+=`...and at least ${o.results.length-n} more result(s).
219
- `:o.results.length===0&&(s="No results found for the given inquiry and search parameters."),`To answer the user's inquiry, the following lucene query was generated:
220
-
221
- \`\`\`
222
- ${a.query}
223
- \`\`\`
224
-
225
- Type category filter applied: ${a.typeCategoryFilter}
226
-
227
- Type filters applied: ${a.typeFilters?a.typeFilters.join(", "):"none"}
220
+ ${s}`};async function wi(e,t){let r=await F("arcgis_knowledge_lucene_generation_prompt"),a={inquiry:e,dataModelForSearch:yi(t)},o=l.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),n=l.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),s=l.array(l.enum(t.dataModel.entityTypes.map(d=>d.name).concat(t.dataModel.relationshipTypes.map(d=>d.name)))).min(1),i=l.object({query:l.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:s.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:o,resultLimit:n});return await ce({promptText:r,inputVariables:a,schema:i})}var gt="searchGraphData",bi=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),vi=async({prompt:e},t)=>{let{knowledgeGraph:r}=await W(t);await g({text:"Generating search query for the user inquiry"},t);let a=await wi(e,r);await g({text:"Executing graph search with generated search query"},t);let o=await Hn({kg:r,searchQuery:a.query,typeCategoryFilter:a.typeCategoryFilter,namedTypesFilter:a.typeFilters,searchResultLimit:a.resultLimit,requestOptions:{signal:t?.signal,timeout:t?.timeout}});if(o.type!=="success")throw new Error(`Graph search failed with error: ${o.type==="error"?o.errorMessage:"aborted"}`);for(let i of o.results)O(i,d=>it(d));let n=10,s=o.results.slice(0,n);return{toolName:gt,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
221
+ Query: ${a.query}
222
+ Type Category Filter: ${a.typeCategoryFilter}
223
+ Named Type Filters: ${a.typeFilters?a.typeFilters.join(", "):"None"}
224
+ Result Limit: ${a.resultLimit??"No limit"}
228
225
 
229
- Search Results limited to: ${a.resultLimit??"no limit specified"}
226
+ Search Results: ${o.results.length} result(s) found.
227
+
228
+ ${o.results.length>n?`Showing top ${n} results:
230
229
 
231
- Search Results:
232
- ${s}
233
- `}var hi=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),pl=f(ui,{name:"searchGraphData",description:"Allows users to search the knowledge graph for text matching their inquiry, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.",schema:hi});var ml=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).
230
+ `:""}${s.map(i=>JSON.stringify(i)).join(`
231
+ `)}`,details:{generatedQuery:a,searchResults:{...o}}}},Sl=f(vi,{name:gt,description:"Allows users to search the knowledge graph for text matching their inquiry, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.",schema:bi});var xl=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).
234
232
  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.
235
233
  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,
236
234
  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
@@ -268,4 +266,4 @@ _example: "Discover and add all the relationships originating at 'Entity E' to t
268
266
  _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
269
267
  _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
270
268
  _example: "Find John Smith and all people he has made phone calls to in the last year"_
271
- _example: "What is the average age of all people who work for Esri?"_`;return{a:al,b:ol,c:Oe,d:nl}},"Graphic","symbols/PictureMarkerSymbol","rest/locator","portal/Portal","config","geometry/Extent","geometry/Point","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","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","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphQueryStreaming","request","identity/IdentityManager","rest/knowledgeGraph/GraphSearchStreaming","rest/knowledgeGraph/KnowledgeGraph","WebLinkChart",a)
269
+ _example: "What is the average age of all people who work for Esri?"_`;return{a:ul,b:hl,c:De,d:ml}},"Graphic","symbols/PictureMarkerSymbol","rest/locator","portal/Portal","config","geometry/Extent","geometry/Point","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","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","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphQueryStreaming","request","identity/IdentityManager","rest/knowledgeGraph/GraphSearchStreaming","rest/knowledgeGraph/KnowledgeGraph","WebLinkChart",a)