@arcgis/ai-components 5.1.0-next.73 → 5.1.0-next.74

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,27 +1,26 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import a from"./L7YTPHKQ.js";export default $arcgis.t(([lt,ge,Pe,ct,{addressToLocations:dt},O,de,ut,Ge,Be,{formatDateOnly:mt,convertDateFormatToIntlOptions:H,formatTimeOnly:ht,formatDate:Re},Qe,Ue,pt,ft,{createRenderer:gt},{getSchemesByTag:yt,getSchemes:wt},{getBackgroundColorTheme:qe},{createAgeRenderer:bt,createContinuousRenderer:xt},{getSchemesByTag:ye},{createContinuousRenderer:vt},{createRenderer:Et},{getSchemesByTag:St},{createRenderer:Tt},{getSchemesByTag:kt},{createRenderer:It},{getSchemesByTag:Ct},{createRenderer:_t},{getSchemesByTag:$t},{createAgeRenderer:Nt,createContinuousRenderer:Ft},{createRenderer:At},{getSchemesByTag:Rt},We,Le,Me,{executeQueryStreaming:qt},Lt,{a:A,b:T,c:Te,d:W,e:K,f:ke,g:Ie,h:V,i:le,j:Z,k:P,l:N,m:w,n:g,o:Ce,p:_e,q:R,r:i,s:p,t:I,u:$e,v:Ne,w:j}])=>{var Ae=e=>Array.isArray(e)&&e.every(V),ot=e=>typeof e=="object"&&e!=null&&"messages"in e&&Ae(e.messages),nt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,q=class extends Ce{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 V(a)&&a.getType()==="tool"||K(a)?a:new le({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 le({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(nt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Ae(e))n=e;else if(ot(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),l;for(let c=n.length-1;c>=0;c-=1){let d=n[c];if(P(d)){l=d;break}}if(l==null||!P(l))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(l.tool_calls?.filter(c=>c.id==null||!s.has(c.id)).map(c=>this.runTool(c,t))??[])}if(!r.some(K))return Array.isArray(e)?r:{messages:r};let a=[],o=null;for(let n of r)K(n)?n.graph===W.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>Te(s))?o?o.goto.push(...n.goto):o=new W({graph:W.PARENT,goto:n.goto}):a.push(n):a.push(Array.isArray(e)?[n]:{messages:[n]});return o&&a.push(o),a}};var _i=g.Root({llmInputMessages:g({reducer:(e,t)=>_e([],t),default:()=>[]})});var Q=(e,t)=>({...e,...t}),U=(e="",t)=>{let r=typeof t=="string"?t.trim():"";if(!r)return e;let a=e.trim();if(!a)return r;if(a===r)return e;let o=a.split(`
2
+ import a from"./2E6GEUNH.js";import{Bb as $e,Fb as R,L as V,M as le,Q as H,R as P,Za as N,_a as w,a as A,b as E,g as Ee,j as W,k as K,kb as g,q as Ie,qb as Ce,u as ke}from"./WI3JQXAS.js";export default $arcgis.t(([ct,ge,Pe,dt,{addressToLocations:ut},D,de,mt,Ge,Be,{formatDateOnly:ht,convertDateFormatToIntlOptions:Z,formatTimeOnly:pt,formatDate:Re},Qe,Ue,ft,gt,{createRenderer:yt},{getSchemesByTag:wt,getSchemes:bt},{getBackgroundColorTheme:Me},{createAgeRenderer:vt,createContinuousRenderer:xt},{getSchemesByTag:ye},{createContinuousRenderer:St},{createRenderer:Tt},{getSchemesByTag:Et},{createRenderer:It},{getSchemesByTag:kt},{createRenderer:Ct},{getSchemesByTag:$t},{createRenderer:_t},{getSchemesByTag:Nt},{createAgeRenderer:Ft,createContinuousRenderer:At},{createRenderer:Rt},{getSchemesByTag:Mt},We,qe,Le,{executeQueryStreaming:qt},Lt,{a:i,b:p,c:k,e:_e,f:Ne,g:O}])=>{var Ae=e=>Array.isArray(e)&&e.every(V),nt=e=>typeof e=="object"&&e!=null&&"messages"in e&&Ae(e.messages),it=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,M=class extends Ce{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 V(a)&&a.getType()==="tool"||K(a)?a:new le({status:"success",name:r.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||ke(a))throw a;return new le({status:"error",content:`Error: ${a.message}
3
+ Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(it(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Ae(e))n=e;else if(nt(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),l;for(let c=n.length-1;c>=0;c-=1){let d=n[c];if(P(d)){l=d;break}}if(l==null||!P(l))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(l.tool_calls?.filter(c=>c.id==null||!s.has(c.id)).map(c=>this.runTool(c,t))??[])}if(!r.some(K))return Array.isArray(e)?r:{messages:r};let a=[],o=null;for(let n of r)K(n)?n.graph===W.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>Ee(s))?o?o.goto.push(...n.goto):o=new W({graph:W.PARENT,goto:n.goto}):a.push(n):a.push(Array.isArray(e)?[n]:{messages:[n]});return o&&a.push(o),a}};var _i=g.Root({llmInputMessages:g({reducer:(e,t)=>$e([],t),default:()=>[]})});var Q=(e,t)=>({...e,...t}),U=(e="",t)=>{let r=typeof t=="string"?t.trim():"";if(!r)return e;let a=e.trim();if(!a)return r;if(a===r)return e;let o=a.split(`
4
4
 
5
5
  `);return o[o.length-1]?.trim()===r?e:`${e}
6
6
 
7
- ${r}`},D=(e,t)=>t??e,Ke=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),summary:g({reducer:D,default:()=>""}),status:g({reducer:D,default:()=>"success"}),intent:g({reducer:(e,t)=>t}),vectorSearchLayerResults:g({reducer:(e,t)=>t,default:()=>[]}),vectorSearchFieldResults:g({reducer:(e,t)=>t})});async function Mt(e,t){let r=O.getDefault().helperServices,a=r.geocode.find(S=>S.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!a)throw new Error("No geocoding service found in helperServices.");let o=a.url,n=`${de.assetsPath?.endsWith("/")?de.assetsPath:`${de.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await dt(o,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent)throw new Error(`Could not find location for: ${e}`);let{xmin:l,ymin:c,xmax:d,ymax:m,spatialReference:u}=s.extent,h=new Pe({xmin:l,ymin:c,xmax:d,ymax:m,spatialReference:u}),y=(l+d)/2,E=(c+m)/2,f=new ge({x:y,y:E,spatialReference:u}),x=new ct({url:n,width:24,height:24}),b=new lt({geometry:f,symbol:x});return t.graphics.removeAll(),t.graphics.add(b),await t.goTo(h),`Successfully zoomed to: ${e}. Location coordinates: x=${y}, y=${E}, wkid=${u.wkid}`}var zt=["mapView"];function C(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=zt.filter(a=>!(a in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function jt({address:e},t){let{mapView:r}=C(t);return await Mt(e,r)}var Ot=i.object({address:i.string().describe("The full address or place name to locate.")}),Dt=w(jt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Ot});async function Vt(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),`Navigated to bookmark: ${e}`}async function Pt({bookmarkName:e},t){let{mapView:r}=C(t);return await Promise.resolve(Vt(e,r))}var Gt=N.object({bookmarkName:N.string().describe("The name of the bookmark to navigate to.")}),Bt=w(Pt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Gt});async function Qt(e,t,r){let a=r.map?.allLayers.find(n=>n.id===e);if(!a)return`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`No features found in ${a.title} matching: ${t}`;if(n)await r.goTo(n);else return`Error: Unable to determine extent for ${a.title}`;return`Successfully zoomed to ${s} feature(s) in ${a.title}`}catch(n){return console.error("Error in goToFeatures:",n),`Error: ${n instanceof Error?n.message:"Unknown error"}`}}async function Ut({layerId:e,where:t},r){let{mapView:a}=C(r);return await Qt(e,t,a)}var Wt=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")}),Kt=w(Ut,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Wt});async function Zt(e){let t=new Pe({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),"Successfully zoomed to world extent"}async function Ht(e,t){let{mapView:r}=C(t);return await Zt(r)}var Jt=N.object({}),Yt=w(Ht,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Jt});async function Xt(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return"Successfully zoomed to home extent"}async function er(e,t){let{mapView:r}=C(t);return await Xt(r)}var tr=i.object({}),rr=w(er,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:tr});async function ar(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}`),`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,`Successfully zoomed to: ${r.title??""}`):"Layer has no defined extent. Cannot zoom to layer."}async function or({layerId:e},t){let{mapView:r}=C(t);return await ar(e,r)}var nr=N.object({layerId:N.string().describe("The id of the layer to navigate to")}),ir=w(or,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:nr});async function sr(e,t){return await t.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function lr({scale:e},t){let{mapView:r}=C(t);return await sr(e,r)}var cr=i.object({scale:i.number().describe("The map scale of the view to go to.")}),dr=w(lr,{name:"goToScale",description:"Go to the specified view scale.",schema:cr});async function ur(e,t,r){let a={target:new ge({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),`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 mr({center:e,zoom:t,scale:r},a){let{mapView:o}=C(a);return await ur(e,o,{zoom:t,scale:r})}var hr=i.object({center:i.object({longitude:i.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:i.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:i.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:i.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),pr=w(mr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:hr});async function fr(e,t){return await t.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function gr({zoom:e},t){let{mapView:r}=C(t);return await fr(e,r)}var yr=i.object({zoom:i.number().min(1).max(20).describe("The zoom level of the view to go to.")}),wr=w(gr,{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:yr}),we=[Dt,Bt,Kt,Yt,rr,ir,dr,pr,wr],ze=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LSGRWCAO.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./KKHKKCYH.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./KQ6LEQHH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./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("./KWBMH7LU.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("./ZDEYVBH7.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./ABCHVJTB.js").then(e=>e.default)});async function L(e){let t=Object.entries(ze).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
7
+ ${r}`},C=(e,t)=>t??e,Ke=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),summary:g({reducer:C,default:()=>""}),status:g({reducer:C}),intent:g({reducer:C}),vectorSearchLayerResults:g({reducer:C,default:()=>[]}),vectorSearchFieldResults:g({reducer:C}),navigationInternalState:g({reducer:C,default:()=>({toolCallMessage:void 0})})});async function zt(e,t){let r=D.getDefault().helperServices,a=r.geocode.find(S=>S.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!a)throw new Error("No geocoding service found in helperServices.");let o=a.url,n=`${de.assetsPath?.endsWith("/")?de.assetsPath:`${de.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await ut(o,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent)throw new Error(`Could not find location for: ${e}`);let{xmin:l,ymin:c,xmax:d,ymax:m,spatialReference:u}=s.extent,h=new Pe({xmin:l,ymin:c,xmax:d,ymax:m,spatialReference:u}),y=(l+d)/2,T=(c+m)/2,f=new ge({x:y,y:T,spatialReference:u}),v=new dt({url:n,width:24,height:24}),b=new ct({geometry:f,symbol:v});return t.graphics.removeAll(),t.graphics.add(b),await t.goTo(h),`Successfully zoomed to: ${e}. Location coordinates: x=${y}, y=${T}, wkid=${u.wkid}`}var jt=["mapView"];function $(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=jt.filter(a=>!(a in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Ot({address:e},t){let{mapView:r}=$(t);return await zt(e,r)}var Dt=i.object({address:i.string().describe("The full address or place name to locate.")}),Vt=w(Ot,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Dt});async function Pt(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),`Navigated to bookmark: ${e}`}async function Gt({bookmarkName:e},t){let{mapView:r}=$(t);return await Promise.resolve(Pt(e,r))}var Bt=N.object({bookmarkName:N.string().describe("The name of the bookmark to navigate to.")}),Qt=w(Gt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Bt});async function Ut(e,t,r){let a=r.map?.allLayers.find(n=>n.id===e);if(!a)return`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`No features found in ${a.title} matching: ${t}`;if(n)await r.goTo(n);else return`Error: Unable to determine extent for ${a.title}`;return`Successfully zoomed to ${s} feature(s) in ${a.title}`}catch(n){return console.error("Error in goToFeatures:",n),`Error: ${n instanceof Error?n.message:"Unknown error"}`}}async function Wt({layerId:e,where:t},r){let{mapView:a}=$(r);return await Ut(e,t,a)}var Kt=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")}),Ht=w(Wt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Kt});async function Zt(e){let t=new Pe({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),"Successfully zoomed to world extent"}async function Jt(e,t){let{mapView:r}=$(t);return await Zt(r)}var Yt=N.object({}),Xt=w(Jt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Yt});async function er(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return"Successfully zoomed to home extent"}async function tr(e,t){let{mapView:r}=$(t);return await er(r)}var rr=i.object({}),ar=w(tr,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:rr});async function or(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}`),`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,`Successfully zoomed to: ${r.title??""}`):"Layer has no defined extent. Cannot zoom to layer."}async function nr({layerId:e},t){let{mapView:r}=$(t);return await or(e,r)}var ir=N.object({layerId:N.string().describe("The id of the layer to navigate to")}),sr=w(nr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:ir});async function lr(e,t){return await t.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function cr({scale:e},t){let{mapView:r}=$(t);return await lr(e,r)}var dr=i.object({scale:i.number().describe("The map scale of the view to go to.")}),ur=w(cr,{name:"goToScale",description:"Go to the specified view scale.",schema:dr});async function mr(e,t,r){let a={target:new ge({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),`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 hr({center:e,zoom:t,scale:r},a){let{mapView:o}=$(a);return await mr(e,o,{zoom:t,scale:r})}var pr=i.object({center:i.object({longitude:i.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:i.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:i.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:i.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),fr=w(hr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:pr});async function gr(e,t){return await t.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function yr({zoom:e},t){let{mapView:r}=$(t);return await gr(e,r)}var wr=i.object({zoom:i.number().min(1).max(20).describe("The zoom level of the view to go to.")}),br=w(yr,{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:wr}),we=[Vt,Qt,Ht,Xt,ar,sr,ur,fr,br],ze=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LSGRWCAO.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./KKHKKCYH.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./KQ6LEQHH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./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("./KWBMH7LU.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 q(e){let t=Object.entries(ze).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
8
8
  Available prompts:
9
9
  ${Object.keys(ze).join(`
10
- `)}`);return await t[1]()}var $=(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)};async function br(e,t){let r=await L("navigation_tool_prompt"),{mapView:a}=C(t),o=a.map,n=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((E,f)=>`${f+1}. layerId=${E.id} | title=${E.title??""} | name=${E.name??""} | score=${E.score.toFixed(2)}`).join(`
10
+ `)}`);return await t[1]()}async function vr(e,t){let r=await q("navigation_tool_prompt"),{mapView:a}=$(t),o=a.map,n=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((f,v)=>`${v+1}. layerId=${f.id} | title=${f.title??""} | name=${f.name??""} | score=${f.score.toFixed(2)}`).join(`
11
11
  `):"",s=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",l=e.intent==="goToBookmark"&&o.bookmarks?.length?`Available bookmarks:
12
12
  ${JSON.stringify(o.bookmarks,null,2)}`:"",c=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
13
13
  ${n}`:"",d=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
14
- ${s}`:"",m={intent:e.intent,bookmarksSection:l,layersSection:c,fieldsSection:d,currentZoom:a.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},u=await j({promptText:r,modelTier:"advanced",messages:$(e.agentExecutionContext.messages),inputVariables:m,tools:we}),h=[...e.agentExecutionContext.messages,u],y=(u.tool_calls?.length??0)>0?[...h]:[...h,u];return{...e,agentExecutionContext:{...e.agentExecutionContext,messages:y}}}async function xr(e,t){let r=await new q(we).invoke({messages:$(e.agentExecutionContext.messages)},t),a=r.messages.map(s=>s.text).join(`
15
- `);await p({text:`Finished executing navigation tool: ${a}`},t);let o=[...e.agentExecutionContext.messages,...r.messages],n=r.messages.map(s=>s.text).join(`
16
- `);return{...e,agentExecutionContext:{...e.agentExecutionContext,messages:o},outputMessage:n}}async function vr(e,t){let r=await L("navigation_intent_prompt"),{mapView:a}=C(t),o=we.map(u=>({name:u.name,description:u.description,schema:u.schema})),n=a.map,s=n.bookmarks?.length?`Available bookmarks:
14
+ ${s}`:"",m={intent:e.intent,bookmarksSection:l,layersSection:c,fieldsSection:d,currentZoom:a.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},u=await O({promptText:r,modelTier:"advanced",inputVariables:m,tools:we}),h=(u.tool_calls?.length??0)>0,y=typeof u.text=="string"?u.text.trim():"",T=y.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:h?u:void 0},outputMessage:h?e.outputMessage:y,status:h?e.status:T?"partial":"failed"}}var He=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r};async function xr(e,t){let r=new M(we);try{let a=e.navigationInternalState.toolCallMessage;if(!a)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let o=(await r.invoke({messages:[a]},t)).messages.map(n=>n.text).join(`
15
+ `);return await p({text:`Finished executing navigation tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?He(o):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await p({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 Sr(e,t){let r=await q("navigation_intent_prompt"),{mapView:a}=$(t),o=we.map(u=>({name:u.name,description:u.description,schema:u.schema})),n=a.map,s=n.bookmarks?.length?`Available bookmarks:
17
16
  ${JSON.stringify(n.bookmarks,null,2)}`:"",l={tools:o.map(({name:u,description:h,schema:y})=>`${u}: ${h}, ${JSON.stringify(y)}`).join(`
18
- `),bookmarks:s,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},c=i.object({intent:i.string()}),d=await Ne({promptText:r,messages:$(e.agentExecutionContext.messages),inputVariables:l,schema:c}),m=typeof d.intent=="string"?d.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:m||""}}var v=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},Er=.7,Sr=async(e,t)=>{try{await p({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=v(t,"layerSearch"),a=v(t,"layersAndFieldsRegistry"),o=v(t,"embeddingCache"),n=(await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Er,embeddingCache:o})).map(({id:l,score:c})=>{let d=a.get(l)?.layerItem;return{id:l,title:d?.title,name:d?.name??void 0,score:c}}),s;return n.length>0?s=`Vector search completed. Matching layers:
17
+ `),bookmarks:s,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},c=i.object({intent:i.string()}),d=await Ne({promptText:r,inputVariables:l,schema:c}),m=typeof d.intent=="string"?d.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:m||""}}var x=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},Tr=.7,Er=async(e,t)=>{try{await p({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:Tr,embeddingCache:o})).map(({id:l,score:c})=>{let d=a.get(l)?.layerItem;return{id:l,title:d?.title,name:d?.name??void 0,score:c}}),s;return n.length>0?s=`Vector search completed. Matching layers:
19
18
  ${n.map(l=>`- layerId=${l.id} | title=${l.title??""} | name=${l.name??""} | score=${l.score.toFixed(2)}`).join(`
20
- `)}`:s="Vector search completed. No matching layers found.",await p({text:s},t),{...e,vectorSearchLayerResults:n}}catch(r){throw await p({text:`Error during vector search layers: ${r instanceof Error?r.message:String(r)}`},t),r}},je=.7,Tr=10,kr=async(e,t)=>{try{await p({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let r=v(t,"fieldSearch"),a=v(t,"layersAndFieldsRegistry"),o=v(t,"embeddingCache"),n=e.vectorSearchLayerResults?.map(c=>c.id)??[];if(n.length===0)return await p({text:"No candidate layers for field search"},t),e;let s=(await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:n,minScore:je,topResults:Tr,embeddingCache:o})).map(({layerId:c,results:d})=>{let m=a.get(c)?.fieldRegistry;return{layerId:c,layerName:a.get(c)?.layerItem.name,results:d.map(u=>{let h=m?.get(u.name);return{name:u.name,score:u.score,type:h?.type,alias:h?.alias,description:h?.description,statistics:h?.statistics}})}}),l;return s.length>0?l=`Vector search completed. Matching layers and fields:
19
+ `)}`:s="Vector search completed. No matching layers found.",await p({text:s},t),{...e,vectorSearchLayerResults:n}}catch(r){throw await p({text:`Error during vector search layers: ${r instanceof Error?r.message:String(r)}`},t),r}},je=.7,Ir=10,kr=async(e,t)=>{try{await p({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(c=>c.id)??[];if(n.length===0)return await p({text:"No candidate layers for field search"},t),e;let s=(await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:n,minScore:je,topResults:Ir,embeddingCache:o})).map(({layerId:c,results:d})=>{let m=a.get(c)?.fieldRegistry;return{layerId:c,layerName:a.get(c)?.layerItem.name,results:d.map(u=>{let h=m?.get(u.name);return{name:u.name,score:u.score,type:h?.type,alias:h?.alias,description:h?.description,statistics:h?.statistics}})}}),l;return s.length>0?l=`Vector search completed. Matching layers and fields:
21
20
  ${s.map(c=>`${c.layerName??c.layerId}:
22
21
  ${c.results.map(d=>` - ${d.name} (${d.score.toFixed(2)})`).join(`
23
22
  `)}`).join(`
24
- `)}`:l=`No vector search field results found for score over ${je}.`,await p({text:l},t),{...e,vectorSearchFieldResults:s}}catch(r){throw await p({text:`Error during vector search fields: ${r instanceof Error?r.message:String(r)}`},t),r}},oe=(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},Ir=(e,t)=>oe(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),Cr=()=>new R(Ke).addNode("requireNavigationServices",Ir).addNode("intentLLM",vr).addNode("vectorSearchLayers",Sr).addNode("vectorSearchFields",kr).addNode("agent",br).addNode("tools",xr).addEdge(A,"requireNavigationServices").addEdge("requireNavigationServices","intentLLM").addConditionalEdges("intentLLM",e=>e.intent==="goToLayer"||e.intent==="goToFeatures"?"vectorSearchLayers":"agent",{vectorSearchLayers:"vectorSearchLayers",agent:"agent"}).addConditionalEdges("vectorSearchLayers",e=>e.intent==="goToFeatures"?"vectorSearchFields":"agent",{vectorSearchFields:"vectorSearchFields",agent:"agent"}).addEdge("vectorSearchFields","agent").addEdge("agent","tools").addEdge("tools",T),_r=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
23
+ `)}`:l=`No vector search field results found for score over ${je}.`,await p({text:l},t),{...e,vectorSearchFieldResults:s}}catch(r){throw await p({text:`Error during vector search fields: ${r instanceof Error?r.message:String(r)}`},t),r}},oe=(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},Cr=(e,t)=>oe(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),$r=()=>new R(Ke).addNode("requireNavigationServices",Cr).addNode("intentLLM",Sr).addNode("vectorSearchLayers",Er).addNode("vectorSearchFields",kr).addNode("agent",vr).addNode("tools",xr).addEdge(A,"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),_r=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
25
24
  This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
26
25
 
27
26
  Supported actions:
@@ -40,7 +39,7 @@ ${c.results.map(d=>` - ${d.name} (${d.score.toFixed(2)})`).join(`
40
39
  _Example: “Center the map on San Francisco at scale 50000”_
41
40
  _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
42
41
  _Example: “Go to the Downtown bookmark”_
43
- _Example: “Where is Mount Rainier?”_`,Ns={id:"navigation",name:"Navigation Agent",description:_r,createGraph:Cr,workspace:Ke},Ze=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),summary:g({reducer:D,default:()=>""}),status:g({reducer:D,default:()=>"success"}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponse:g()}),$r=async(e,t)=>(await p({text:"Exiting Data Exploration agent"},t),e),be=async(e,t)=>{let r=e.tool_calls??[];if(r.length===0){await p({text:`LLM did not request any tool calls: ${String(e?.content)}`},t);return}await Promise.all(r.map(async a=>await p({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},t)))},Nr=["mapView"];function M(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=Nr.filter(a=>!(a in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var Fr=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."},Ar=async(e,t)=>{let{mapView:r}=M(t);return Fr(r)},Rr=w(Ar,{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:i.object({})}),qr=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."},Lr=async(e,t)=>{let{mapView:r}=M(t);return await qr(r)},Mr=w(Lr,{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:i.object({})});function X(e){return"point"in e&&e.point!==void 0}function G(e){return"layerId"in e&&e.layerId!==void 0}var ne=async(e,t)=>{if(X(e)){let{point:r}=e;return{geometry:new ge({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(G(e)){let r=t.map?.allLayers.find(a=>a.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};try{let a=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let n=a.features[0].geometry;if(!n)return{error:"The geometry of the first feature is undefined or null."};o=n}else{let n=a.features.map(l=>l.geometry),s=Be.executeMany(n);if(!s)return{error:"Failed to create a combined geometry."};o=s}return o.spatialReference||(o.spatialReference=t.spatialReference),{geometry:o}}catch(a){return{error:`Failed to query geometry: ${String(a)}`}}}return{error:"Invalid geometry configuration provided"}},zr=async(e,t,r,a,o,n)=>{let s=e.map?.allLayers.find(c=>c.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let l=s.createQuery();l.where=r??"1=1",a&&(l.geometry=a,l.spatialRelationship="intersects",o&&(l.distance=o),n&&(l.units=n));try{let{extent:c,count:d}=await s.queryExtent(l);return!c||d===0?{success:!1,error:`No features found for filter (where: ${l.where}${a?", spatial filter used":""})`}:(await e.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},jr=async(e,t,r,a,o,n)=>{let s=t.map?.allLayers.find(u=>u.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let l;if(o){let u=await ne(o,t);if("error"in u)return u.error;l=u.geometry}if(s.featureEffect=null,s.featureEffect=new ut({filter:new Ge({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:l,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 c=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,d=await zr(t,e.layerId,c,l,o?.distance,o?.units),m=s.title??e.layerId;return d.success?`Applied feature effects to target layer "${s.title??e.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${m}" but no features matched. ${d.error}`},Or=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],z=i.enum(Or),Dr=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}=M(n);return await jr(e,s,a,o,t,r)},Vr=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),Pr=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),Gr=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer on which to set a feature effect."),where:i.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:i.array(i.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:i.union([Vr,Pr]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:i.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:i.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:i.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.")}),Br=w(Dr,{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:Gr}),ee=(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},Qr=new Set(["date","date-only","time-only","timestamp-offset"]),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},Ur=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Wr=e=>{if(typeof e=="string"&&e)return e;let t=me(e);return t?t.toISOString().slice(0,10):null},He=()=>{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}},te=e=>e?Qr.has(e.toLowerCase()):!1,re=(e,t,r)=>{let a=t?.toLowerCase();if(a==="date-only"){let n=Wr(e);return n?mt(n,H("short-date")):e}if(a==="time-only"){if(typeof e=="string"&&e)return ht(e,H("long-time"));let n=me(e);return n?Re(n,{...H("long-time"),timeZone:"UTC"}):e}let o=me(e);return o?Re(o,{...H("short-date-short-time"),timeZone:Ur(r)}):e},Kr=(e,t,r)=>{let a=e.createQuery();return a.outFields=[t],a.where=r||"1=1",a.num=1,a},Zr=async(e,t,r,a)=>{let o=a.map?.allLayers.find(u=>u.id===e),n=Kr(o,t,r.where),s=(await o.queryFeatures(n)).features[0],l=s?s.attributes[t]:null,c=o.fields.find(u=>u.name===t),d=ee(t,l,o)||l,m=c&&te(c.type)?re(d,c.type,a.timeZone):d;return{tool:"getAttribute",layerName:o.title??e,summary:`${t} = ${m}`,details:{fieldName:t,value:m,where:r.where}}};async function Hr({layerId:e,fieldName:t,query:r},a){let{mapView:o}=M(a),n=await Zr(e,t,r,o);return JSON.stringify(n,null,2)}var Jr=i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:i.string().describe("The name of the field/attribute from which to get a field value."),query:i.object({where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Yr=w(Hr,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Jr}),xe=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function ae(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var Xr=async e=>{let{targetLayer:t,fieldName:r,statisticType:a,mapView:o,layersAndFieldsRegistry:n,geometryFilter:s}=e,l=o.map?.allLayers.find(b=>b.id===t.layerId);if(!l)throw new Error(`Layer '${t.layerId}' not found.`);let c=await o.whenLayerView(l),d=n.get(t.layerId)?.fieldRegistry.get(r),m=d?.alias;if(!d)throw new Error(`Field '${r}' not found.`);let u,h;if(s){let b=await ne(s,o);if("error"in b)throw new Error(b.error);if(!b.geometry)throw G(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");G(s)?u={geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}:X(s)&&(u={point:s.point,distance:s.distance,units:s.units,applied:!0}),h=new Ge({geometry:b.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let y=xe(c,[r],!1),E=null,f=null,x=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{let b={layer:l,useFeaturesInView:y,view:y?o:void 0,field:r,sqlWhere:ae(l.definitionExpression,t.where),...h&&{filter:h},outStatisticTypes:{include:[a]}};E=await Qe(b);let S=["string","small-integer","integer"],k=d.domain?.type==="coded-value"?d.domain:null;(S.includes(d.type)||k)&&(f=(await Ue({layer:l,useFeaturesInView:y,view:y?o:void 0,field:r,sqlWhere:ae(l.definitionExpression,t.where),...h&&{filter:h}})).uniqueValueInfos.sort((F,se)=>se.count-F.count).slice(0,x)),f&&d.domain?.type==="coded-value"&&(f=f.map(F=>({...F,value:k?k.getName(F.value)??F.value:F.value})))}catch(b){console.error("Statistics error:",b)}return{tool:"getStatistics",layerName:l.title??t.layerId,summary:`${a} = ${typeof E?.[a]=="number"?E[a]:"N/A"}`,details:{fieldName:r,fieldAlias:m,statisticType:a,statistic:E?.[a]??null,summaryStatistics:E,uniqueValues:f,where:t.where,spatialFilterInfo:u}}};async function ea({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:a},o){let n=v(o,"layersAndFieldsRegistry"),{mapView:s}=M(o),l=await Xr({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:a});return JSON.stringify(l,null,2)}var ta=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),ra=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),aa=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:i.union([ta,ra]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:i.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:i.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),oa=w(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.
42
+ _Example: “Where is Mount Rainier?”_`,Fs={id:"navigation",name:"Navigation Agent",description:_r,createGraph:$r,workspace:Ke},Ze=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),summary:g({reducer:C,default:()=>""}),status:g({reducer:C,default:()=>"success"}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponse:g()}),Nr=async(e,t)=>(await p({text:"Exiting Data Exploration agent"},t),e),be=async(e,t)=>{let r=e.tool_calls??[];if(r.length===0){await p({text:`LLM did not request any tool calls: ${String(e?.content)}`},t);return}await Promise.all(r.map(async a=>await p({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},t)))},j=(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)},Fr=["mapView"];function L(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=Fr.filter(a=>!(a in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var Ar=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."},Rr=async(e,t)=>{let{mapView:r}=L(t);return Ar(r)},Mr=w(Rr,{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:i.object({})}),qr=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."},Lr=async(e,t)=>{let{mapView:r}=L(t);return await qr(r)},zr=w(Lr,{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:i.object({})});function X(e){return"point"in e&&e.point!==void 0}function G(e){return"layerId"in e&&e.layerId!==void 0}var ne=async(e,t)=>{if(X(e)){let{point:r}=e;return{geometry:new ge({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(G(e)){let r=t.map?.allLayers.find(a=>a.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};try{let a=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let n=a.features[0].geometry;if(!n)return{error:"The geometry of the first feature is undefined or null."};o=n}else{let n=a.features.map(l=>l.geometry),s=Be.executeMany(n);if(!s)return{error:"Failed to create a combined geometry."};o=s}return o.spatialReference||(o.spatialReference=t.spatialReference),{geometry:o}}catch(a){return{error:`Failed to query geometry: ${String(a)}`}}}return{error:"Invalid geometry configuration provided"}},jr=async(e,t,r,a,o,n)=>{let s=e.map?.allLayers.find(c=>c.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let l=s.createQuery();l.where=r??"1=1",a&&(l.geometry=a,l.spatialRelationship="intersects",o&&(l.distance=o),n&&(l.units=n));try{let{extent:c,count:d}=await s.queryExtent(l);return!c||d===0?{success:!1,error:`No features found for filter (where: ${l.where}${a?", spatial filter used":""})`}:(await e.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},Or=async(e,t,r,a,o,n)=>{let s=t.map?.allLayers.find(u=>u.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let l;if(o){let u=await ne(o,t);if("error"in u)return u.error;l=u.geometry}if(s.featureEffect=null,s.featureEffect=new mt({filter:new Ge({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:l,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 c=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,d=await jr(t,e.layerId,c,l,o?.distance,o?.units),m=s.title??e.layerId;return d.success?`Applied feature effects to target layer "${s.title??e.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${m}" but no features matched. ${d.error}`},Dr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],z=i.enum(Dr),Vr=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}=L(n);return await Or(e,s,a,o,t,r)},Pr=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),Gr=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),Br=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer on which to set a feature effect."),where:i.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:i.array(i.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:i.union([Pr,Gr]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:i.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:i.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:i.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.")}),Qr=w(Vr,{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:Br}),ee=(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},Ur=new Set(["date","date-only","time-only","timestamp-offset"]),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},Wr=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Kr=e=>{if(typeof e=="string"&&e)return e;let t=me(e);return t?t.toISOString().slice(0,10):null},Je=()=>{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}},te=e=>e?Ur.has(e.toLowerCase()):!1,re=(e,t,r)=>{let a=t?.toLowerCase();if(a==="date-only"){let n=Kr(e);return n?ht(n,Z("short-date")):e}if(a==="time-only"){if(typeof e=="string"&&e)return pt(e,Z("long-time"));let n=me(e);return n?Re(n,{...Z("long-time"),timeZone:"UTC"}):e}let o=me(e);return o?Re(o,{...Z("short-date-short-time"),timeZone:Wr(r)}):e},Hr=(e,t,r)=>{let a=e.createQuery();return a.outFields=[t],a.where=r||"1=1",a.num=1,a},Zr=async(e,t,r,a)=>{let o=a.map?.allLayers.find(u=>u.id===e),n=Hr(o,t,r.where),s=(await o.queryFeatures(n)).features[0],l=s?s.attributes[t]:null,c=o.fields.find(u=>u.name===t),d=ee(t,l,o)||l,m=c&&te(c.type)?re(d,c.type,a.timeZone):d;return{tool:"getAttribute",layerName:o.title??e,summary:`${t} = ${m}`,details:{fieldName:t,value:m,where:r.where}}};async function Jr({layerId:e,fieldName:t,query:r},a){let{mapView:o}=L(a),n=await Zr(e,t,r,o);return JSON.stringify(n,null,2)}var Yr=i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:i.string().describe("The name of the field/attribute from which to get a field value."),query:i.object({where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Xr=w(Jr,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Yr}),ve=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function ae(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var ea=async e=>{let{targetLayer:t,fieldName:r,statisticType:a,mapView:o,layersAndFieldsRegistry:n,geometryFilter:s}=e,l=o.map?.allLayers.find(b=>b.id===t.layerId);if(!l)throw new Error(`Layer '${t.layerId}' not found.`);let c=await o.whenLayerView(l),d=n.get(t.layerId)?.fieldRegistry.get(r),m=d?.alias;if(!d)throw new Error(`Field '${r}' not found.`);let u,h;if(s){let b=await ne(s,o);if("error"in b)throw new Error(b.error);if(!b.geometry)throw G(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");G(s)?u={geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}:X(s)&&(u={point:s.point,distance:s.distance,units:s.units,applied:!0}),h=new Ge({geometry:b.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let y=ve(c,[r],!1),T=null,f=null,v=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{let b={layer:l,useFeaturesInView:y,view:y?o:void 0,field:r,sqlWhere:ae(l.definitionExpression,t.where),...h&&{filter:h},outStatisticTypes:{include:[a]}};T=await Qe(b);let S=["string","small-integer","integer"],I=d.domain?.type==="coded-value"?d.domain:null;(S.includes(d.type)||I)&&(f=(await Ue({layer:l,useFeaturesInView:y,view:y?o:void 0,field:r,sqlWhere:ae(l.definitionExpression,t.where),...h&&{filter:h}})).uniqueValueInfos.sort((F,se)=>se.count-F.count).slice(0,v)),f&&d.domain?.type==="coded-value"&&(f=f.map(F=>({...F,value:I?I.getName(F.value)??F.value:F.value})))}catch(b){console.error("Statistics error:",b)}return{tool:"getStatistics",layerName:l.title??t.layerId,summary:`${a} = ${typeof T?.[a]=="number"?T[a]:"N/A"}`,details:{fieldName:r,fieldAlias:m,statisticType:a,statistic:T?.[a]??null,summaryStatistics:T,uniqueValues:f,where:t.where,spatialFilterInfo:u}}};async function ta({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:a},o){let n=x(o,"layersAndFieldsRegistry"),{mapView:s}=L(o),l=await ea({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:a});return JSON.stringify(l,null,2)}var ra=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),aa=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),oa=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:i.union([ra,aa]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:i.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:i.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),na=w(ta,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
44
43
 
45
44
  USE THIS TOOL FOR:
46
45
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -52,7 +51,7 @@ DO NOT USE FOR:
52
51
  - "Show / list / find features" \u2014 use queryFeatures instead
53
52
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
54
53
 
55
- Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:aa}),na=async(e,t,r,a,o)=>{let n=r.map?.allLayers.find(h=>h.id===e.layerId),s=await r.whenLayerView(n),l=n.title??e.layerId,c;if(a){let h=await ne(a,r);if("error"in h)return{tool:"getTopFeatures",layerName:l,summary:"Geometry lookup failed",details:{error:h.error}};if(!h.geometry)return{tool:"getTopFeatures",layerName:l,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};c=h.geometry}else o&&(c=r.extent.clone());let d=t.groupByFields&&t.groupByFields.length>0,m=n.objectIdField,u=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,m])];try{let h;if(d){let f=new pt({where:e.where||"1=1",outFields:u,orderByFields:e.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new ft({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});h=await n.queryTopFeatures(f)}else{let f=n.createQuery();f.where=ae(n.definitionExpression,e.where||"1=1"),f.outFields=u.length?u:["*"],f.orderByFields=t.orderByFields,f.num=t.topCount,c&&(f.geometry=c,f.spatialRelationship="intersects"),a?.distance&&(f.distance=a.distance),a?.units&&(f.units=a.units),f.outSpatialReference=r.spatialReference;let x=xe(s,e.outFields,o??!1);try{h=x?await s.queryFeatures(f):await n.queryFeatures(f)}catch(b){console.warn("Client-side query failed, falling back to server:",b),h=await n.queryFeatures(f)}}let y=h.features.map(f=>f.attributes[m]),E=h.features.map(f=>{let x=f.attributes,b={};return n.fields.forEach(S=>{if(S.name===n.objectIdField){b[S.name]=x[S.name];return}let k=x[S.name],F=ee(S.name,k,n),se=S.alias||S.name,Se=F??k;b[se]=te(S.type)?re(Se,S.type,r.timeZone):Se}),b});return{tool:"getTopFeatures",layerName:l,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:E,objectIds:y,objectIdField:m,where:e.where,orderByFields:t.orderByFields,...d&&{groupByFields:t.groupByFields}}}}catch(h){return{tool:"getTopFeatures",layerName:l,summary:"Query failed",details:{error:h instanceof Error?h.message:String(h)}}}},ia=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:a},o)=>{let{mapView:n}=M(o),s=await na(e,t,n,r,a);return JSON.stringify(s,null,2)},sa=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),la=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),ca=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:i.array(i.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:i.array(i.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:i.union([sa,la]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:i.object({topCount:i.number().describe("Number of top features to return per group."),orderByFields:i.array(i.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:i.array(i.string().describe("Field(s) to group results by. Returns top N per group."))}),useCurrentExtent:i.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).")}),da=w(ia,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:ca}),ue=25,ua=async(e,t,r,a)=>{let o=t.map?.allLayers.find(f=>f.id===e.layerId),n=await t.whenLayerView(o),s=o.title??e.layerId,l;if(r){let f=await ne(r,t);if("error"in f){let x={error:f.error};return G(r)?(x.geometryLayerId=r.layerId,x.geometryWhere=r.where):X(r)&&(x.point=r.point),{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:x}}if(!f.geometry){let x={};return G(r)?(x.error=`No features found matching: ${r.where}`,x.geometryLayerId=r.layerId,x.geometryWhere=r.where):X(r)&&(x.error="Failed to create point geometry",x.point=r.point),{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:x}}l=f.geometry}else a&&(l=t.extent.clone());let c=xe(n,e.outFields,a??!1),d=o.objectIdField,m=o.createQuery();m.where=ae(o.definitionExpression,e.where||"1=1"),m.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])],m.orderByFields=e.orderByFields,l&&(m.geometry=l,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=t.spatialReference;let u,h;try{u=c?await n.queryFeatureCount(m):await o.queryFeatureCount(m),u>0&&u<=ue&&(h=c?await n.queryFeatures(m):await o.queryFeatures(m),h&&h.features.forEach(f=>{let x=f.attributes;o.fields.forEach(b=>{let S=x[b.name],k=ee(b.name,S,o)??S;x[b.name]=te(b.type)?re(k,b.type,t.timeZone):k})}))}catch(f){console.warn("Client-side query failed, falling back to server:",f),u=await o.queryFeatureCount(m),u>0&&u<=ue&&(h=await o.queryFeatures(m),h&&h.features.forEach(x=>{o.fields.forEach(b=>{let S=x.attributes[b.name],k=ee(b.name,S,o)??S;x.attributes[b.name]=te(b.type)?re(k,b.type,t.timeZone):k})}))}let y=h?.features.map(f=>f.attributes[d]),E=h?.features.map(f=>f.attributes);return{tool:"queryFeatures",layerName:s,summary:`${u} features found`,details:{totalCount:u,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...y&&{objectIds:y,objectIdField:d},...E&&{attributes:E},...u>ue&&{note:`${u} features found.`}}}};async function ma({targetLayer:e,geometryFilter:t,useCurrentExtent:r},a){let{mapView:o}=M(a),n=await ua(e,o,t,r);return JSON.stringify(n,null,2)}var ha=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),pa=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),fa=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.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:i.array(i.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:i.array(i.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:i.union([ha,pa]).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:i.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).")}),ga=w(ma,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
54
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:oa}),ia=async(e,t,r,a,o)=>{let n=r.map?.allLayers.find(h=>h.id===e.layerId),s=await r.whenLayerView(n),l=n.title??e.layerId,c;if(a){let h=await ne(a,r);if("error"in h)return{tool:"getTopFeatures",layerName:l,summary:"Geometry lookup failed",details:{error:h.error}};if(!h.geometry)return{tool:"getTopFeatures",layerName:l,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};c=h.geometry}else o&&(c=r.extent.clone());let d=t.groupByFields&&t.groupByFields.length>0,m=n.objectIdField,u=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,m])];try{let h;if(d){let f=new ft({where:e.where||"1=1",outFields:u,orderByFields:e.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new gt({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});h=await n.queryTopFeatures(f)}else{let f=n.createQuery();f.where=ae(n.definitionExpression,e.where||"1=1"),f.outFields=u.length?u:["*"],f.orderByFields=t.orderByFields,f.num=t.topCount,c&&(f.geometry=c,f.spatialRelationship="intersects"),a?.distance&&(f.distance=a.distance),a?.units&&(f.units=a.units),f.outSpatialReference=r.spatialReference;let v=ve(s,e.outFields,o??!1);try{h=v?await s.queryFeatures(f):await n.queryFeatures(f)}catch(b){console.warn("Client-side query failed, falling back to server:",b),h=await n.queryFeatures(f)}}let y=h.features.map(f=>f.attributes[m]),T=h.features.map(f=>{let v=f.attributes,b={};return n.fields.forEach(S=>{if(S.name===n.objectIdField){b[S.name]=v[S.name];return}let I=v[S.name],F=ee(S.name,I,n),se=S.alias||S.name,Te=F??I;b[se]=te(S.type)?re(Te,S.type,r.timeZone):Te}),b});return{tool:"getTopFeatures",layerName:l,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:T,objectIds:y,objectIdField:m,where:e.where,orderByFields:t.orderByFields,...d&&{groupByFields:t.groupByFields}}}}catch(h){return{tool:"getTopFeatures",layerName:l,summary:"Query failed",details:{error:h instanceof Error?h.message:String(h)}}}},sa=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:a},o)=>{let{mapView:n}=L(o),s=await ia(e,t,n,r,a);return JSON.stringify(s,null,2)},la=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),ca=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),da=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:i.array(i.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:i.array(i.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:i.union([la,ca]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:i.object({topCount:i.number().describe("Number of top features to return per group."),orderByFields:i.array(i.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:i.array(i.string().describe("Field(s) to group results by. Returns top N per group."))}),useCurrentExtent:i.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),ua=w(sa,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:da}),ue=25,ma=async(e,t,r,a)=>{let o=t.map?.allLayers.find(f=>f.id===e.layerId),n=await t.whenLayerView(o),s=o.title??e.layerId,l;if(r){let f=await ne(r,t);if("error"in f){let v={error:f.error};return G(r)?(v.geometryLayerId=r.layerId,v.geometryWhere=r.where):X(r)&&(v.point=r.point),{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:v}}if(!f.geometry){let v={};return G(r)?(v.error=`No features found matching: ${r.where}`,v.geometryLayerId=r.layerId,v.geometryWhere=r.where):X(r)&&(v.error="Failed to create point geometry",v.point=r.point),{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:v}}l=f.geometry}else a&&(l=t.extent.clone());let c=ve(n,e.outFields,a??!1),d=o.objectIdField,m=o.createQuery();m.where=ae(o.definitionExpression,e.where||"1=1"),m.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])],m.orderByFields=e.orderByFields,l&&(m.geometry=l,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=t.spatialReference;let u,h;try{u=c?await n.queryFeatureCount(m):await o.queryFeatureCount(m),u>0&&u<=ue&&(h=c?await n.queryFeatures(m):await o.queryFeatures(m),h&&h.features.forEach(f=>{let v=f.attributes;o.fields.forEach(b=>{let S=v[b.name],I=ee(b.name,S,o)??S;v[b.name]=te(b.type)?re(I,b.type,t.timeZone):I})}))}catch(f){console.warn("Client-side query failed, falling back to server:",f),u=await o.queryFeatureCount(m),u>0&&u<=ue&&(h=await o.queryFeatures(m),h&&h.features.forEach(v=>{o.fields.forEach(b=>{let S=v.attributes[b.name],I=ee(b.name,S,o)??S;v.attributes[b.name]=te(b.type)?re(I,b.type,t.timeZone):I})}))}let y=h?.features.map(f=>f.attributes[d]),T=h?.features.map(f=>f.attributes);return{tool:"queryFeatures",layerName:s,summary:`${u} features found`,details:{totalCount:u,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...y&&{objectIds:y,objectIdField:d},...T&&{attributes:T},...u>ue&&{note:`${u} features found.`}}}};async function ha({targetLayer:e,geometryFilter:t,useCurrentExtent:r},a){let{mapView:o}=L(a),n=await ma(e,o,t,r);return JSON.stringify(n,null,2)}var pa=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),fa=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.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:i.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),ga=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.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:i.array(i.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:i.array(i.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:i.union([pa,fa]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:i.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).")}),ya=w(ha,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
56
55
 
57
56
  USE THIS TOOL FOR:
58
57
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -61,13 +60,13 @@ USE THIS TOOL FOR:
61
60
  - Spatial queries \u2014 finding features near/within/intersecting other features
62
61
  - Any question where the user wants to SEE or COUNT matching features
63
62
 
64
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:fa}),Je=[Yr,oa,da,ga],Ye=[Br,Mr,Rr],ya=async(e,t)=>{await p({text:"Requesting LLM for layer filter results"},t);let r=await L("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=He(),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.agentExecutionContext.messages),inputVariables:n,tools:Ye}),l=[...e.agentExecutionContext.messages,s];if(!((s.tool_calls?.length??0)>0))return await p({text:"LLM determined no filter changes needed"},t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:l}};let c=[...l,s],d=s.content.toString();return await be(s,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:c},outputMessage:d}},wa=async(e,t)=>{await p({text:"Requesting LLM for layer query results"},t);let r=await L("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=He(),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.agentExecutionContext.messages),inputVariables:n,tools:Je}),l=[...e.agentExecutionContext.messages,s],c=s.content.toString();return await be(s,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:l},outputMessage:c}},ba=async(e,t)=>{try{await p({text:"Requesting LLM for summary on query results"},t);let r=await L("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.agentExecutionContext.messages),inputVariables:a}),n=typeof o=="string"?o:o.content,s=new Z(n);return await p({text:`Received response from LLM: ${n}`},t),{...e,outputMessage:n,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,s]}}}catch(r){throw await p({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${r instanceof Error?r.message:String(r)}`)}};async function xa(e,t){let r=await new q(Ye).invoke({messages:$(e.agentExecutionContext.messages)},t),a=[...e.agentExecutionContext.messages,...r.messages],o=r.messages.map(s=>new Z({content:s.content,additional_kwargs:s.additional_kwargs}));await p({text:`Finished executing layer filter tool: ${r.messages.map(s=>s.content).join(", ")}`},t);let n=[...a,...o];return{...e,agentExecutionContext:{...e.agentExecutionContext,messages:n}}}var va=new q(Je);async function Ea(e,t){let{messages:r}=await va.invoke({messages:$(e.agentExecutionContext.messages)},t),a=[],o=[];for(let s of r){let l=s.content,c;typeof l!="string"&&(c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:l}});try{typeof l=="string"?c=JSON.parse(l):c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:l}}}catch{c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:l}}}a.push(c),c.details&&typeof c.details=="object"&&"error"in c.details?o.push(`- ${c.tool}: Error - ${String(c.details.error)}`):o.push(`- ${c.layerName}: ${c.summary}`)}let n=[...e.agentExecutionContext.messages,...r];return await p({text:`Finished executing layer query tool: ${o.join(", ")}`},t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:n},queryResponse:a}}var Sa=10,Ta=["string","small-integer","integer"],ka=async(e,t)=>{let r=null,a=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){r=await Qe({layer:e,field:t.name});let o=t.domain?.type==="coded-value"?t.domain:null;(Ta.includes(t.type)||o)&&(a=(await Ue({layer:e,field:t.name})).uniqueValueInfos.sort((n,s)=>s.count-n.count).slice(0,Sa),o&&(a=a.map(n=>({...n,value:o.getName(n.value)??n.value}))))}}catch(o){console.error(`Error fetching statistics for field ${t.name}:`,o)}return{summaryStatistics:r,uniqueValues:a}};async function Ia(e,t,r){let a=[],o=[];for(let n of e){let s=function(h){let y=t.get(h)?.layerItem;return y?[y.name&&`Name: ${y.name}`,y.title&&`Title: ${y.title}`,y.description&&`Description: ${y.description}`].filter(Boolean).join(" | "):h},{layerId:l,results:c}=n,d=r.map?.allLayers.find(h=>h.id===l),m=t.get(l)?.fieldRegistry;if(!m)continue;let u=a.find(h=>h.layerId===l);u||(u={layerId:l,layerSummary:s(l),fieldInfos:[]},a.push(u));for(let h of c){let y=m.get(h.name);if(y){if(!y.statistics){let E=ka(d,y).then(f=>{m.set(y.name,{...y,statistics:f}),y.statistics=f});o.push(E)}u.fieldInfos.push(y)}}}return await Promise.all(o),a}var Ca=async(e,t)=>{try{await p({text:"Getting statistics for vector search results"},t);let r=v(t,"layersAndFieldsRegistry"),{mapView:a}=M(t),o=await Ia(e.vectorSearchFieldResults,r,a);return await p({text:"Statistics retrieved"},t),{...e,layerFieldInfo:o}}catch(r){throw await p({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${r instanceof Error?r.message:String(r)}`)}},Oe=.7,_a=10,$a=async(e,t)=>{try{await p({text:"Similarity search to find fields"},t);let r=v(t,"fieldSearch"),a=v(t,"layersAndFieldsRegistry"),o=v(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Oe,topResults:_a,embeddingCache:o}),s=n.map(({layerId:c,results:d})=>{let m=d.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
63
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:ga}),Ye=[Xr,na,ua,ya],Xe=[Qr,zr,Mr],wa=async(e,t)=>{await p({text:"Requesting LLM for layer filter results"},t);let r=await q("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=Je(),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 O({promptText:r,modelTier:"advanced",messages:j(e.agentExecutionContext.messages),inputVariables:n,tools:Xe}),l=[...e.agentExecutionContext.messages,s];if(!((s.tool_calls?.length??0)>0))return await p({text:"LLM determined no filter changes needed"},t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:l}};let c=[...l,s],d=s.content.toString();return await be(s,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:c},outputMessage:d}},ba=async(e,t)=>{await p({text:"Requesting LLM for layer query results"},t);let r=await q("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=Je(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await O({promptText:r,modelTier:"advanced",messages:j(e.agentExecutionContext.messages),inputVariables:n,tools:Ye}),l=[...e.agentExecutionContext.messages,s],c=s.content.toString();return await be(s,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:l},outputMessage:c}},va=async(e,t)=>{try{await p({text:"Requesting LLM for summary on query results"},t);let r=await q("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:j(e.agentExecutionContext.messages),inputVariables:a}),n=typeof o=="string"?o:o.content,s=new H(n);return await p({text:`Received response from LLM: ${n}`},t),{...e,outputMessage:n,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,s]}}}catch(r){throw await p({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${r instanceof Error?r.message:String(r)}`)}};async function xa(e,t){let r=await new M(Xe).invoke({messages:j(e.agentExecutionContext.messages)},t),a=[...e.agentExecutionContext.messages,...r.messages],o=r.messages.map(s=>new H({content:s.content,additional_kwargs:s.additional_kwargs}));await p({text:`Finished executing layer filter tool: ${r.messages.map(s=>s.content).join(", ")}`},t);let n=[...a,...o];return{...e,agentExecutionContext:{...e.agentExecutionContext,messages:n}}}var Sa=new M(Ye);async function Ta(e,t){let{messages:r}=await Sa.invoke({messages:j(e.agentExecutionContext.messages)},t),a=[],o=[];for(let s of r){let l=s.content,c;typeof l!="string"&&(c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:l}});try{typeof l=="string"?c=JSON.parse(l):c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:l}}}catch{c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:l}}}a.push(c),c.details&&typeof c.details=="object"&&"error"in c.details?o.push(`- ${c.tool}: Error - ${String(c.details.error)}`):o.push(`- ${c.layerName}: ${c.summary}`)}let n=[...e.agentExecutionContext.messages,...r];return await p({text:`Finished executing layer query tool: ${o.join(", ")}`},t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:n},queryResponse:a}}var Ea=10,Ia=["string","small-integer","integer"],ka=async(e,t)=>{let r=null,a=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){r=await Qe({layer:e,field:t.name});let o=t.domain?.type==="coded-value"?t.domain:null;(Ia.includes(t.type)||o)&&(a=(await Ue({layer:e,field:t.name})).uniqueValueInfos.sort((n,s)=>s.count-n.count).slice(0,Ea),o&&(a=a.map(n=>({...n,value:o.getName(n.value)??n.value}))))}}catch(o){console.error(`Error fetching statistics for field ${t.name}:`,o)}return{summaryStatistics:r,uniqueValues:a}};async function Ca(e,t,r){let a=[],o=[];for(let n of e){let s=function(h){let y=t.get(h)?.layerItem;return y?[y.name&&`Name: ${y.name}`,y.title&&`Title: ${y.title}`,y.description&&`Description: ${y.description}`].filter(Boolean).join(" | "):h},{layerId:l,results:c}=n,d=r.map?.allLayers.find(h=>h.id===l),m=t.get(l)?.fieldRegistry;if(!m)continue;let u=a.find(h=>h.layerId===l);u||(u={layerId:l,layerSummary:s(l),fieldInfos:[]},a.push(u));for(let h of c){let y=m.get(h.name);if(y){if(!y.statistics){let T=ka(d,y).then(f=>{m.set(y.name,{...y,statistics:f}),y.statistics=f});o.push(T)}u.fieldInfos.push(y)}}}return await Promise.all(o),a}var $a=async(e,t)=>{try{await p({text:"Getting statistics for vector search results"},t);let r=x(t,"layersAndFieldsRegistry"),{mapView:a}=L(t),o=await Ca(e.vectorSearchFieldResults,r,a);return await p({text:"Statistics retrieved"},t),{...e,layerFieldInfo:o}}catch(r){throw await p({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${r instanceof Error?r.message:String(r)}`)}},Oe=.7,_a=10,Na=async(e,t)=>{try{await p({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:_a,embeddingCache:o}),s=n.map(({layerId:c,results:d})=>{let m=d.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
65
64
  `);return`${a.get(c)?.layerItem.name??c}:
66
65
  ${m}`}).join(`
67
66
  `),l;return n.length>0?l=`Vector search completed. Matching layers and fields with scores:
68
- ${s}`:l=`No vector search results found for score over ${Oe}.`,await p({text:l},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await p({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)}`)}},Na=.7,Fa=async(e,t)=>{try{await p({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=v(t,"layerSearch"),a=v(t,"layersAndFieldsRegistry"),o=v(t,"embeddingCache"),n=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Na,embeddingCache:o}),s=n.map(d=>d.id),l=n.map(({id:d,score:m})=>`${a.get(d)?.layerItem.name??d} (${m.toFixed(2)})`).join(`
67
+ ${s}`:l=`No vector search results found for score over ${Oe}.`,await p({text:l},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await p({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)}`)}},Fa=.7,Aa=async(e,t)=>{try{await p({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:Fa,embeddingCache:o}),s=n.map(d=>d.id),l=n.map(({id:d,score:m})=>`${a.get(d)?.layerItem.name??d} (${m.toFixed(2)})`).join(`
69
68
  `),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
70
- ${l}`:c="Vector search completed. No matching layers found.",await p({text:c},t),{...e,vectorSearchLayerIds:s}}catch(r){throw await p({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)}`)}},Aa=(e,t)=>oe(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),Ra=()=>new R(Ze).addNode("requireDataExplorationServices",Aa).addNode("vectorSearchLayers",Fa).addNode("vectorSearchFields",$a).addNode("fieldStatistics",Ca).addNode("queryAgent",wa).addNode("queryTools",Ea).addNode("summarizeQueryResponseLLM",ba).addNode("filterAgent",ya).addNode("filterTools",xa).addNode("earlyExit",$r).addEdge(A,"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.agentExecutionContext.messages[e.agentExecutionContext.messages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.agentExecutionContext.messages[e.agentExecutionContext.messages.length-1]?.tool_calls?.length??0)>0?"filterTools":T).addEdge("filterTools",T).addEdge("earlyExit",T),qa=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
69
+ ${l}`:c="Vector search completed. No matching layers found.",await p({text:c},t),{...e,vectorSearchLayerIds:s}}catch(r){throw await p({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)}`)}},Ra=(e,t)=>oe(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),Ma=()=>new R(Ze).addNode("requireDataExplorationServices",Ra).addNode("vectorSearchLayers",Aa).addNode("vectorSearchFields",Na).addNode("fieldStatistics",$a).addNode("queryAgent",ba).addNode("queryTools",Ta).addNode("summarizeQueryResponseLLM",va).addNode("filterAgent",wa).addNode("filterTools",xa).addNode("earlyExit",Nr).addEdge(A,"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.agentExecutionContext.messages[e.agentExecutionContext.messages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.agentExecutionContext.messages[e.agentExecutionContext.messages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),qa=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
71
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.
72
71
  _Example: “Only show stations where Brand is Shell”_
73
72
  _Example: “Make Shell stations stand out on the map”_
@@ -75,13 +74,13 @@ ${l}`:c="Vector search completed. No matching layers found.",await p({text:c},t)
75
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.
76
75
  _Example: “How many features are there?”_
77
76
  _Example: “What’s the average population?”_
78
- _Example: “Which values are in the status field?”_`,Fs={id:"dataExploration",name:"Data Exploration Agent",description:qa,createGraph:Ra,workspace:Ze},De=.7,La=10,Ma=async(e,t)=>{try{await p({text:"Similarity search to find fields"},t);let r=v(t,"fieldSearch"),a=v(t,"layersAndFieldsRegistry"),o=v(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:De,topResults:La,embeddingCache:o}),s=n.map(({layerId:c,results:d})=>{let m=d.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
77
+ _Example: “Which values are in the status field?”_`,As={id:"dataExploration",name:"Data Exploration Agent",description:qa,createGraph:Ma,workspace:Ze},De=.7,La=10,za=async(e,t)=>{try{await p({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:La,embeddingCache:o}),s=n.map(({layerId:c,results:d})=>{let m=d.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
79
78
  `);return`${a.get(c)?.layerItem.name??c}:
80
79
  ${m}`}).join(`
81
80
  `),l;return n.length>0?l=`Vector search completed. Matching layers and fields with scores:
82
- ${s}`:l=`No vector search results found for score over ${De}.`,await p({text:l},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await p({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=.7,ja=async(e,t)=>{try{await p({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=v(t,"layerSearch"),a=v(t,"layersAndFieldsRegistry"),o=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:za}),n=o.map(c=>c.id),s=o.map(({id:c,score:d})=>`${a.get(c)?.layerItem.name??c} (${d.toFixed(2)})`).join(`
81
+ ${s}`:l=`No vector search results found for score over ${De}.`,await p({text:l},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await p({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)}`)}},ja=.7,Oa=async(e,t)=>{try{await p({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:ja}),n=o.map(c=>c.id),s=o.map(({id:c,score:d})=>`${a.get(c)?.layerItem.name??c} (${d.toFixed(2)})`).join(`
83
82
  `),l;return n.length>0?l=`Vector search completed. Matching layers with scores:
84
- ${s}`:l="Vector search completed. No matching layers found.",await p({text:l},t),{...e,vectorSearchLayerIds:n}}catch(r){throw await p({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 Oa(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n?s=yt({basemapTheme:await qe(a),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:s=wt({basemapTheme:await qe(a),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:a,attributes:t.map(l=>({field:l,label:r.fields.find(c=>c.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function Da(e){return await gt(e)}async function Va({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:n?"chart-size":"chart",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=await Oa(c),m=await Da(d);return l.renderer=m.renderer,l.visible=!0,`Chart renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying chart renderer: ${d instanceof Error?d.message:String(d)}`}}var Pa=["mapView"];function _(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=Pa.filter(a=>!(a in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function Ga({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=_(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Va({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var Ba=i.object({layerId:i.string().describe("The id of the layer to apply the chart renderer to"),fields:i.array(i.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),includeSize:i.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Qa=w(Ga,{name:"chart",description:`Label: Charts
83
+ ${s}`:l="Vector search completed. No matching layers found.",await p({text:l},t),{...e,vectorSearchLayerIds:n}}catch(r){throw await p({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 Da(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n?s=wt({basemapTheme:await Me(a),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:s=bt({basemapTheme:await Me(a),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:a,attributes:t.map(l=>({field:l,label:r.fields.find(c=>c.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function Va(e){return await yt(e)}async function Pa({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:n?"chart-size":"chart",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=await Da(c),m=await Va(d);return l.renderer=m.renderer,l.visible=!0,`Chart renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying chart renderer: ${d instanceof Error?d.message:String(d)}`}}var Ga=["mapView"];function _(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=Ga.filter(a=>!(a in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function Ba({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await Pa({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var Qa=i.object({layerId:i.string().describe("The id of the layer to apply the chart renderer to"),fields:i.array(i.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),includeSize:i.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Ua=w(Ba,{name:"chart",description:`Label: Charts
85
84
  Description: Show the values of two or more categories as a proportion of the total using a pie chart.
86
85
  Keywords: pie, chart, all categories, breakdown, proportion
87
86
  Example: Show the total number of homes built in each decade using a pie chart for each feature.
@@ -91,19 +90,19 @@ ${s}`:l="Vector search completed. No matching layers found.",await p({text:l},t)
91
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.
92
91
  Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
93
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.
94
- Fields: This style requires 2-8 number fields.`,schema:Ba});function Ua(e){let{fields:t,layer:r,view:a,theme:o,colorSchemeTags:n}=e,s=t[0],l;return n&&(l=ye({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:l}}async function Wa(e){return await bt(e)}async function Ka({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"color-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Ua(c),m=await Wa(d);return l.renderer=m.renderer,l.visible=!0,`Color-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Za({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Ka({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Ha=i.object({layerId:i.string().describe("The id of the layer to apply the color-age renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Ja=w(Za,{name:"color-age",description:`Label: Age (color)
93
+ Fields: This style requires 2-8 number fields.`,schema:Qa});function Wa(e){let{fields:t,layer:r,view:a,theme:o,colorSchemeTags:n}=e,s=t[0],l;return n&&(l=ye({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:l}}async function Ka(e){return await vt(e)}async function Ha({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"color-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Wa(c),m=await Ka(d);return l.renderer=m.renderer,l.visible=!0,`Color-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Za({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await Ha({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Ja=i.object({layerId:i.string().describe("The id of the layer to apply the color-age renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Ya=w(Za,{name:"color-age",description:`Label: Age (color)
95
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.
96
95
  Keywords: since, age, how old, how long
97
96
  Example: Show the age of each feature based on its reported date.
98
- Fields: This style requires at least one field with a date type.`,schema:Ha});function Ya(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,{theme:n}=e,s=t[1],l=t[0],c;return o&&(c=ye({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:l,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function Xa(e){return await xt(e)}async function eo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"color",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Ya(c),m=await Xa(d);return l.renderer=m.renderer,l.visible=!0,`Color renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color renderer: ${d instanceof Error?d.message:String(d)}`}}async function to({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await eo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var ro=i.object({layerId:i.string().describe("The id of the layer to apply the color renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the color renderer"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),ao=w(to,{name:"color",description:`Label: Counts and Amounts (color)
97
+ Fields: This style requires at least one field with a date type.`,schema:Ja});function Xa(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,{theme:n}=e,s=t[1],l=t[0],c;return o&&(c=ye({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:l,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function eo(e){return await xt(e)}async function to({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"color",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Xa(c),m=await eo(d);return l.renderer=m.renderer,l.visible=!0,`Color renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color renderer: ${d instanceof Error?d.message:String(d)}`}}async function ro({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await to({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var ao=i.object({layerId:i.string().describe("The id of the layer to apply the color renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the color renderer"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),oo=w(ro,{name:"color",description:`Label: Counts and Amounts (color)
99
98
  Description: Vary color along a continuous color ramp to represent numeric or ranked data.
100
99
  Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
101
100
  Example: Color each feature based on the population density.
102
- 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:ro});function oo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o,theme:n}=e,s,l,c=t[0];return o&&(l=ye({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:c,normalizationField:s,theme:n,colorOptions:{colorScheme:l}}}async function no(e){return await vt(e)}async function io({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"color-size-univariate",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=oo(c),m=await no(d);return l.renderer=m.renderer,l.visible=!0,`Color-size-univariate renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-size-univariate renderer: ${d instanceof Error?d.message:String(d)}`}}async function so({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 lo=i.object({layerId:i.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:i.array(i.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),co=w(so,{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:ao});function no(e){let{fields:t,layer:r,view:a,colorSchemeTags:o,theme:n}=e,s,l,c=t[0];return o&&(l=ye({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:c,normalizationField:s,theme:n,colorOptions:{colorScheme:l}}}async function io(e){return await St(e)}async function so({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"color-size-univariate",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=no(c),m=await io(d);return l.renderer=m.renderer,l.visible=!0,`Color-size-univariate renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-size-univariate renderer: ${d instanceof Error?d.message:String(d)}`}}async function lo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await so({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var co=i.object({layerId:i.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:i.array(i.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),uo=w(lo,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
103
102
  Description: Vary symbol size and color based on the values of two numeric attributes.
104
103
  Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
105
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.
106
- 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:lo});function uo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n;return o&&(n=St({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(l=>l.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function mo(e){return await Et(e)}async function ho({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let l={styleName:"dot-density",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=uo(l),d=await mo(c);return s.renderer=d.renderer,s.visible=!0,`Dot Density renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function po({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 fo=i.object({layerId:i.string().describe("The id of the layer to apply the dot density renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use")}),go=w(po,{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:co});function mo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n;return o&&(n=Et({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(l=>l.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function ho(e){return await Tt(e)}async function po({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let l={styleName:"dot-density",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=mo(l),d=await ho(c);return s.renderer=d.renderer,s.visible=!0,`Dot Density renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function fo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await k({type:"show-legend",data:{layerIds:[e]}},a),await po({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var go=i.object({layerId:i.string().describe("The id of the layer to apply the dot density renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use")}),yo=w(fo,{name:"dot-density",description:`Dot Density
107
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.
108
107
  **Use cases:**
109
108
  - Population distribution visualization
@@ -114,11 +113,11 @@ ${s}`:l="Vector search completed. No matching layers found.",await p({text:l},t)
114
113
  - Visualize distribution of different crops across regions
115
114
  - Display demographic patterns within census tracts
116
115
  **Fields:** Requires 2-8 number fields.
117
- **Keywords:** density, how much, how many, total, number, amount`,schema:fo});function yo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s=t[0];return o&&(n=kt({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:r,view:a,field:s,heatmapScheme:n}}async function wo(e){return await Tt(e)}async function bo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let l={styleName:"heatmap",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=yo(l),d=await wo(c);return s.renderer=d.renderer,s.visible=!0,`Heatmap renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function xo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await bo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var vo=i.object({layerId:i.string().describe("The id of the layer to apply the heatmap renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use")}),Eo=w(xo,{name:"heatmap",description:`Label: Heat Map
116
+ **Keywords:** density, how much, how many, total, number, amount`,schema:go});function wo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s=t[0];return o&&(n=kt({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:r,view:a,field:s,heatmapScheme:n}}async function bo(e){return await It(e)}async function vo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let l={styleName:"heatmap",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=wo(l),d=await bo(c);return s.renderer=d.renderer,s.visible=!0,`Heatmap renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function xo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await k({type:"show-legend",data:{layerIds:[e]}},a),await vo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var So=i.object({layerId:i.string().describe("The id of the layer to apply the heatmap renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use")}),To=w(xo,{name:"heatmap",description:`Label: Heat Map
118
117
  Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
119
118
  Keywords: density, heatmap, hot spots, pattern, cluster
120
119
  Example: Create a heatmap
121
- Fields: This typically requires zero or one field of type number.`,schema:vo});function So(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n&&(s=Ct({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:a,fields:t.map(l=>({name:l})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function To(e){return await It(e)}async function ko({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:n?"predominance-size":"predominance",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=So(c),m=await To(d);return l.renderer=m.renderer,l.visible=!0,`Predominance renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying predominance renderer: ${d instanceof Error?d.message:String(d)}`}}async function Io({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=_(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await ko({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var Co=i.object({layerId:i.string().describe("The id of the layer to apply the predominance renderer to"),fields:i.array(i.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),includeSize:i.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),_o=w(Io,{name:"predominance",description:`Label: Predominant category
120
+ Fields: This typically requires zero or one field of type number.`,schema:So});function Eo(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n&&(s=$t({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:a,fields:t.map(l=>({name:l})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function Io(e){return await Ct(e)}async function ko({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:n?"predominance-size":"predominance",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=Eo(c),m=await Io(d);return l.renderer=m.renderer,l.visible=!0,`Predominance renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying predominance renderer: ${d instanceof Error?d.message:String(d)}`}}async function Co({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await ko({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var $o=i.object({layerId:i.string().describe("The id of the layer to apply the predominance renderer to"),fields:i.array(i.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),includeSize:i.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),_o=w(Co,{name:"predominance",description:`Label: Predominant category
122
121
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
123
122
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
124
123
  Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
@@ -128,15 +127,15 @@ Fields: This typically requires zero or one field of type number.`,schema:vo});f
128
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.
129
128
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
130
129
  Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
131
- Fields: This style relies on 2-10 number fields.`,schema:Co});function $o(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s={field:t[0]},l={field:t[1]};return o&&(n=$t({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field1:s,field2:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function No(e){return await _t(e)}async function Fo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let l={styleName:"relationship",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=$o(l),d=await No(c);return s.renderer=d.renderer,s.visible=!0,`Relationship renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function Ao({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await Fo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Ro=i.object({layerId:i.string().describe("The id of the layer to apply the relationship renderer to"),fields:i.array(i.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use")}),qo=w(Ao,{name:"relationship",description:`Label: Relationship
130
+ Fields: This style relies on 2-10 number fields.`,schema:$o});function No(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s={field:t[0]},l={field:t[1]};return o&&(n=Nt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field1:s,field2:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function Fo(e){return await _t(e)}async function Ao({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let l={styleName:"relationship",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=No(l),d=await Fo(c);return s.renderer=d.renderer,s.visible=!0,`Relationship renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function Ro({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await k({type:"show-legend",data:{layerIds:[e]}},a),await Ao({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Mo=i.object({layerId:i.string().describe("The id of the layer to apply the relationship renderer to"),fields:i.array(i.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use")}),qo=w(Ro,{name:"relationship",description:`Label: Relationship
132
131
  Description: Overlays two color ramps to represent the relationship between two numeric attributes.
133
132
  Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
134
133
  Example: Show the relationship between tree height and carbon storage
135
- Fields: This style requires two number fields.`,schema:Ro});function Lo(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 Mo(e){return await Nt(e)}async function zo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"size-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Lo(c),m=await Mo(d);return l.renderer=m.renderer,l.visible=!0,`Size-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function jo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await zo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Oo=i.object({layerId:i.string().describe("The id of the layer to apply the size-age renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Do=w(jo,{name:"size-age",description:`Label: Age (size)
134
+ Fields: This style requires two number fields.`,schema:Mo});function Lo(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 zo(e){return await Ft(e)}async function jo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"size-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Lo(c),m=await zo(d);return l.renderer=m.renderer,l.visible=!0,`Size-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Oo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await jo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Do=i.object({layerId:i.string().describe("The id of the layer to apply the size-age renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Vo=w(Oo,{name:"size-age",description:`Label: Age (size)
136
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.
137
136
  Keywords: since, age, how old, how long
138
137
  Example: Change the size of features so older features are larger than new features.
139
- Fields: This style requires at least one field with a date type.`,schema:Oo});function Vo(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 Po(e){return await Ft(e)}async function Go({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"size",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Vo(c),m=await Po(d);return l.renderer=m.renderer,l.visible=!0,`Size renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size renderer: ${d instanceof Error?d.message:String(d)}`}}async function Bo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Go({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Qo=i.object({layerId:i.string().describe("The id of the layer to apply the size renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Uo=w(Bo,{name:"size",description:`Label: Counts and Amounts (size)
138
+ Fields: This style requires at least one field with a date type.`,schema:Do});function Po(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 Go(e){return await At(e)}async function Bo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"size",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Po(c),m=await Go(d);return l.renderer=m.renderer,l.visible=!0,`Size renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size renderer: ${d instanceof Error?d.message:String(d)}`}}async function Qo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await Bo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Uo=i.object({layerId:i.string().describe("The id of the layer to apply the size renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Wo=w(Qo,{name:"size",description:`Label: Counts and Amounts (size)
140
139
  Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
141
140
  Keywords: graduated size, proportional size, how much, total, number, amount, size
142
141
  Example: Vary the size of each point based on the total population.
@@ -146,27 +145,27 @@ Fields: This typically requires zero or one field of type number.`,schema:vo});f
146
145
  Description: Vary symbol sizes along a continuous ramp to represent dates.
147
146
  Keywords: graduated size, proportional size, classed size, how much, total, number, when
148
147
  Example: Vary the size of each feature based on the date a ticket was completed.
149
- Fields: This style requires a single field with a date type.`,schema:Qo});function Wo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n=t[0],s=t[1],l=t[2],c;return o&&(c=Rt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field:n,field2:s,field3:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function Ko(e){return await At(e)}async function Zo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"type",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Wo(c),m=await Ko(d);return l.renderer=m.renderer,l.visible=!0,`Type renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying type renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ho({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Zo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Jo=i.object({layerId:i.string().describe("The id of the layer to apply the type renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),Yo=w(Ho,{name:"type",description:`Label: Types (unique symbols)
148
+ Fields: This style requires a single field with a date type.`,schema:Uo});function Ko(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n=t[0],s=t[1],l=t[2],c;return o&&(c=Mt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field:n,field2:s,field3:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function Ho(e){return await Rt(e)}async function Zo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,l=e?.allLayers.find(d=>d.id===r);if(!l)return`Could not find layer for id: ${r}`;let c={styleName:"type",fields:a,layer:l,view:s,colorSchemeTags:o,theme:n};try{let d=Ko(c),m=await Ho(d);return l.renderer=m.renderer,l.visible=!0,`Type renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying type renderer: ${d instanceof Error?d.message:String(d)}`}}async function Jo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await Zo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Yo=i.object({layerId:i.string().describe("The id of the layer to apply the type renderer to"),fields:i.array(i.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),theme:i.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),Xo=w(Jo,{name:"type",description:`Label: Types (unique symbols)
150
149
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
151
150
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
152
151
  Example: Color each feature based on the region it belongs to
153
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:Jo}),Xe=[Qa,Ja,ao,co,go,Eo,_o,qo,Do,Uo,Yo],Xo=async(e,t)=>{await p({text:"Requesting LLM for layer query results"},t);let r=await L("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:$(e.agentExecutionContext.messages),inputVariables:a,tools:Xe});return await be(o,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,o]}}};async function en(e,t){let r=await new q(Xe).invoke({messages:$(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:Yo}),et=[Ua,Ya,oo,uo,yo,To,_o,qo,Vo,Wo,Xo],en=async(e,t)=>{await p({text:"Requesting LLM for layer query results"},t);let r=await q("navigation_intent_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await O({promptText:r,modelTier:"advanced",messages:j(e.agentExecutionContext.messages),inputVariables:a,tools:et});return await be(o,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,o]}}};async function tn(e,t){let r=await new M(et).invoke({messages:j(e.agentExecutionContext.messages)},t),a=r.messages.map(n=>n.text).join(`
154
153
  `);await p({text:`Finished executing layer filter tool: ${a}`},t);let o=r.messages.map(n=>n.text).join(`
155
- `);return{...e,outputMessage:o}}var et=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),selectedLayerId:g()}),tn=async(e,t)=>(await p({text:"Exiting Layer Styling agent"},t),e),rn=async(e,t)=>{try{await p({text:"Populating layer and field info"},t);let r=[];for(let a of e.vectorSearchFieldResults){let o=function(m){let u=l.get(m)?.layerItem;return u?[u.name&&`Name: ${u.name}`,u.title&&`Title: ${u.title}`,u.description&&`Description: ${u.description}`].filter(Boolean).join(" | "):m},{layerId:n,results:s}=a,l=v(t,"layersAndFieldsRegistry"),c=l.get(n)?.fieldRegistry;if(!c)continue;let d=r.find(m=>m.layerId===n);d||(d={layerId:n,layerSummary:o(n),fieldInfos:[]},r.push(d));for(let m of s){let u=c.get(m.name);u&&d.fieldInfos.push(u)}}return await p({text:"Populated layerFieldInfo"},t),{...e,layerFieldInfo:r}}catch(r){throw await p({text:"Error populating layerFieldInfo"},t),new Error(`Error populating layerFieldInfo: ${r instanceof Error?r.message:String(r)}`)}},an=(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!==Ve.id||a.id!=="reviewLayerSelection"){let n={agentId:Ve.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...r]};throw new ke(n)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},on=(e,t)=>oe(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,t),nn=()=>new R(et).addNode("requireLayerStylingServices",on).addNode("vectorSearchLayers",ja).addNode("layerSelectionHITL",an).addNode("vectorSearchFields",Ma).addNode("populateLayerFieldInfo",rn).addNode("agent",Xo).addNode("tools",en).addNode("earlyExit",tn).addEdge(A,"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",T).addEdge("earlyExit",T),sn=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
154
+ `);return{...e,outputMessage:o}}var tt=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),selectedLayerId:g()}),rn=async(e,t)=>(await p({text:"Exiting Layer Styling agent"},t),e),an=async(e,t)=>{try{await p({text:"Populating layer and field info"},t);let r=[];for(let a of e.vectorSearchFieldResults){let o=function(m){let u=l.get(m)?.layerItem;return u?[u.name&&`Name: ${u.name}`,u.title&&`Title: ${u.title}`,u.description&&`Description: ${u.description}`].filter(Boolean).join(" | "):m},{layerId:n,results:s}=a,l=x(t,"layersAndFieldsRegistry"),c=l.get(n)?.fieldRegistry;if(!c)continue;let d=r.find(m=>m.layerId===n);d||(d={layerId:n,layerSummary:o(n),fieldInfos:[]},r.push(d));for(let m of s){let u=c.get(m.name);u&&d.fieldInfos.push(u)}}return await p({text:"Populated layerFieldInfo"},t),{...e,layerFieldInfo:r}}catch(r){throw await p({text:"Error populating layerFieldInfo"},t),new Error(`Error populating layerFieldInfo: ${r instanceof Error?r.message:String(r)}`)}},on=(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!==Ve.id||a.id!=="reviewLayerSelection"){let n={agentId:Ve.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...r]};throw new Ie(n)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},nn=(e,t)=>oe(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,t),sn=()=>new R(tt).addNode("requireLayerStylingServices",nn).addNode("vectorSearchLayers",Oa).addNode("layerSelectionHITL",on).addNode("vectorSearchFields",za).addNode("populateLayerFieldInfo",an).addNode("agent",en).addNode("tools",tn).addNode("earlyExit",rn).addEdge(A,"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),ln=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.
156
155
  _Example: “Color points by sales amount”_
157
156
  _Example: “Show population density with a color gradient”_
158
157
  _Example: “Create a relationship map between height and depth”_
159
- _Example: “Vary circle sizes according to population”_`,Ve={id:"layerStyling",name:"Layer Styling Agent",description:sn,createGraph:nn,workspace:et},tt=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),summary:g({reducer:D,default:()=>""}),status:g({reducer:D,default:()=>"success"})}),ln=(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”_`,Ve={id:"layerStyling",name:"Layer Styling Agent",description:ln,createGraph:sn,workspace:tt},rt=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),summary:g({reducer:C,default:()=>""}),status:g({reducer:C}),helpInternalState:g({reducer:C,default:()=>({toolCallMessage:void 0})})}),cn=(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(`
160
159
  `);return`**${r.layerItem.title}** has ${a.length} field(s):
161
160
 
162
- ${o}`},cn=async({layerTitle:e},t)=>{let r=v(t,"layersAndFieldsRegistry");return ln(r,e)},dn=w(cn,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use when the user asks to see fields, columns, or attributes of a specific layer.",schema:i.object({layerTitle:i.string().describe("The title or partial title of the layer to list fields for.")})}),rt=[dn],un=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(l=>l.name).slice(0,10).join(", "),s=a.size>10?` (and ${a.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
161
+ ${o}`},dn=async({layerTitle:e},t)=>{let r=x(t,"layersAndFieldsRegistry");return cn(r,e)},un=w(dn,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use when the user asks to see fields, columns, or attributes of a specific layer.",schema:i.object({layerTitle:i.string().describe("The title or partial title of the layer to list fields for.")})}),at=[un],mn=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(l=>l.name).slice(0,10).join(", "),s=a.size>10?` (and ${a.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
163
162
  Fields: ${n}${s}`}).join(`
164
163
 
165
164
  `);return`This map contains ${e.size} layer(s):
166
165
 
167
- ${t}`},mn=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: ${r.agent.description}`).join(`
168
- `):"No agents currently available."};async function hn(e,t){let r=await L("help_prompt"),a=v(t,"layersAndFieldsRegistry"),o=v(t,"agentRegistry");try{let n=await j({promptText:r,modelTier:"fast",tools:rt,inputVariables:{layerSummary:un(a),agents:mn(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}}),s=n.content.toString(),l=[...e.agentExecutionContext.messages,n];return{...e,agentExecutionContext:{...e.agentExecutionContext,messages:l},outputMessage:s,summary:"Provided map-related help based on the assigned task.",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 pn=(e,t)=>oe(["agentRegistry"],"Help Agent")(e,t);async function fn(e,t){let r=await new q(rt).invoke({messages:e.agentExecutionContext.messages},t),a=[...e.agentExecutionContext.messages,...r.messages],o=r.messages.map(n=>n.text).join(`
169
- `);return{...e,agentExecutionContext:{...e.agentExecutionContext,messages:a},outputMessage:o}}var gn=()=>new R(tt).addNode("requireHelpServices",pn).addNode("agent",hn).addNode("tools",fn).addEdge(A,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>(e.agentExecutionContext.messages[e.agentExecutionContext.messages.length-1]?.tool_calls?.length??0)>0?"tools":T).addEdge("tools",T),yn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
166
+ ${t}`},hn=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 pn(e,t){let r=await q("help_prompt"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"agentRegistry");try{let n=await O({promptText:r,modelTier:"fast",tools:at,inputVariables:{layerSummary:mn(a),agents:hn(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}}),s=(n.tool_calls?.length??0)>0,l=typeof n.text=="string"?n.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:s?n:void 0},outputMessage:s?e.outputMessage:l,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 fn=(e,t)=>oe(["agentRegistry"],"Help Agent")(e,t);async function gn(e,t){let r=new M(at);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 p({text:`Finished executing help tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?He(o):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await p({text:`Help tool execution failed: ${o}`},t),{...e,outputMessage:`Help tool execution failed: ${o}`,status:"failed",summary:`Help tool execution failed: ${o}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var yn=()=>new R(rt).addNode("requireHelpServices",fn).addNode("agent",pn).addNode("tools",gn).addEdge(A,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":E).addEdge("tools",E),wn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
170
169
 
171
170
  _Example: “Tell me about this map”_
172
171
  _Example: “List all layers in this map”_
@@ -179,18 +178,18 @@ ${t}`},mn=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: $
179
178
 
180
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.
181
180
  _Example: "Create a chart"_
182
- _Example: "Create a table"_`,As={id:"help",name:"Help Agent",description:yn,createGraph:gn,workspace:tt},Rs=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),intent:g({reducer:(e,t)=>t})}),J={conversationId:""},wn=["linkChartView"],bn=["knowledgeGraph"];function ie(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=wn.filter(a=>!(a in t));if(r.length)throw new Error(`Link Chart context missing: ${r.join(", ")}`);return t}function ve(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(`Knowledge Graph context missing: ${r.join(", ")}`);return t}var he=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=pe.fromDataModel(t)}},pe=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(B.fromEntityType(a));for(let a of t.relationshipTypes)r.relationshipTypes.push(fe.fromRelationshipType(a));return r.identifierInfo={mappingInfo:{identifierMapsTo:xn(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}},B=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=vn(t.role);for(let a of t.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:En(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}},fe=class extends B{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=B.fromEntityType(t);r.observedEndPoints=[];for(let a of t.endPoints)r.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return r}},xn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},vn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function En(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 Sn(e,t,r,a){let{graphQuery:o,explanation:n}=await Ee(e,t,r,a);return`Generated Graph Query:
181
+ _Example: "Create a table"_`,Rs={id:"help",name:"Help Agent",description:wn,createGraph:yn,workspace:rt},Ms=g.Root({agentExecutionContext:g({reducer:Q,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[]})}),outputMessage:g({reducer:U,default:()=>""}),intent:g({reducer:(e,t)=>t})}),J={conversationId:""},bn=["linkChartView"],vn=["knowledgeGraph"];function ie(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}function xe(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=vn.filter(a=>!(a in t));if(r.length)throw new Error(`Knowledge Graph context missing: ${r.join(", ")}`);return t}var he=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=pe.fromDataModel(t)}},pe=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(B.fromEntityType(a));for(let a of t.relationshipTypes)r.relationshipTypes.push(fe.fromRelationshipType(a));return r.identifierInfo={mappingInfo:{identifierMapsTo:xn(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}},B=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=Sn(t.role);for(let a of t.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:Tn(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}},fe=class extends B{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=B.fromEntityType(t);r.observedEndPoints=[];for(let a of t.endPoints)r.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return r}},xn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},Sn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function Tn(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 En(e,t,r,a){let{graphQuery:o,explanation:n}=await Se(e,t,r,a);return`Generated Graph Query:
183
182
  ${o}
184
183
 
185
- Explanation: ${n}`}async function Ee(e,t,r,a){let o={message:e,context:new he(t)};J.conversationId&&(o.conversationId=J.conversationId),await p({text:"Attempting to generate a cypher query from your prompt..."},a);let n=await Le(`${r}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Me.findCredential(O.getDefault().url)?.token??""}});if(n.httpStatus!==200)throw new Error(`Graph query service returned an error: ${n.httpStatus}`,{cause:n.data});J.conversationId||(J.conversationId=n.data.conversationId);let s=!1,l=Date.now(),c=n.data.sequenceNumber,d="",m="",u=1;for(;!s;){await new Promise(y=>setTimeout(y,1e3)),await p({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,u)}`},a),u=u%3+1;let h=await Le(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:n.data.conversationId,inquiryId:n.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Me.findCredential(O.getDefault().url)?.token??""}});if(h.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${h.httpStatus}`,{cause:h.data});if(h.data.context)d=h.data.context.graphQuery,m=h.data.message||"";else if(!h.data.hasMore)s=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=h.data.sequenceNumber}return{graphQuery:d,explanation:m}}function Y(e,t){if(!(!e||typeof e!="object")){if(kn(e))for(let r of e.path)Y(r,t);else if(Tn(e))t.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let r of e)Y(r,t);else if(In(e))for(let r of Object.values(e.properties??{}))Y(r,t)}}function Tn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function kn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function In(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function Cn(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}var _n=async e=>{let t=new Map,r=e.resultRowsStream.getReader();for(;;){let{done:a,value:o}=await r.read();if(a)break;for(let n of o)for(let s of n)Y(s,t)}return Array.from(t.values())};async function $n(e,t,r,a,o){let{graphQuery:n,explanation:s}=await Ee(e,t.dataModel,r,o);await p({text:`Attempting to execute query: ${n.substring(0,500)}${n.length>500?"...":""}`},o);let l=await qt(t,new We({openCypherQuery:n}),{signal:o?.signal,timeout:o?.timeout}),c=await _n(l);return await p({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:
184
+ Explanation: ${n}`}async function Se(e,t,r,a){let o={message:e,context:new he(t)};J.conversationId&&(o.conversationId=J.conversationId),await p({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:Le.findCredential(D.getDefault().url)?.token??""}});if(n.httpStatus!==200)throw new Error(`Graph query service returned an error: ${n.httpStatus}`,{cause:n.data});J.conversationId||(J.conversationId=n.data.conversationId);let s=!1,l=Date.now(),c=n.data.sequenceNumber,d="",m="",u=1;for(;!s;){await new Promise(y=>setTimeout(y,1e3)),await p({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,u)}`},a),u=u%3+1;let h=await qe(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:n.data.conversationId,inquiryId:n.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Le.findCredential(D.getDefault().url)?.token??""}});if(h.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${h.httpStatus}`,{cause:h.data});if(h.data.context)d=h.data.context.graphQuery,m=h.data.message||"";else if(!h.data.hasMore)s=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=h.data.sequenceNumber}return{graphQuery:d,explanation:m}}function Y(e,t){if(!(!e||typeof e!="object")){if(kn(e))for(let r of e.path)Y(r,t);else if(In(e))t.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let r of e)Y(r,t);else if(Cn(e))for(let r of Object.values(e.properties??{}))Y(r,t)}}function In(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function kn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Cn(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function $n(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}var _n=async e=>{let t=new Map,r=e.resultRowsStream.getReader();for(;;){let{done:a,value:o}=await r.read();if(a)break;for(let n of o)for(let s of n)Y(s,t)}return Array.from(t.values())};async function Nn(e,t,r,a,o){let{graphQuery:n,explanation:s}=await Se(e,t.dataModel,r,o);await p({text:`Attempting to execute query: ${n.substring(0,500)}${n.length>500?"...":""}`},o);let l=await qt(t,new We({openCypherQuery:n}),{signal:o?.signal,timeout:o?.timeout}),c=await _n(l);return await p({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:
186
185
  ${n}
187
186
 
188
- Explanation: ${s}`}async function Nn({prompt:e},t){let{knowledgeGraph:r}=ve(t),{linkChartView:a}=ie(t),o=O.getDefault().helperServices,n=await L("arcgis_knowledge_current_lc_context"),s=Cn(a.map,r),l=`${e}
187
+ Explanation: ${s}`}async function Fn({prompt:e},t){let{knowledgeGraph:r}=xe(t),{linkChartView:a}=ie(t),o=D.getDefault().helperServices,n=await q("arcgis_knowledge_current_lc_context"),s=$n(a.map,r),l=`${e}
189
188
 
190
- ${n}${JSON.stringify(s)}`;return await $n(l,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Fn=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),qs=w(Nn,{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:Fn});async function An(e,t){return await t.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function Rn({layout:e},t){let{linkChartView:r}=ie(t);return await An(e,r)}var qn=i.object({layout:i.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")}),Ls=w(Rn,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:qn});function Ln(e,t){return t.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function Mn({setting:e},t){let{linkChartView:r}=ie(t);return Ln(e,r)}var zn=i.object({setting:i.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Ms=w(Mn,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:zn});async function jn(e,t,r,a,o){let{graphQuery:n,explanation:s}=await Ee(e,t.dataModel,r,o);await p({text:`Attempting to create link chart from derived query: ${n}`},o);let l=await Lt.fromCypherQuery(t,new We({openCypherQuery:n}));return await p({text:"Link chart created successfully, loading..."},o),a.map=l,await l.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart:
189
+ ${n}${JSON.stringify(s)}`;return await Nn(l,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var An=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),qs=w(Fn,{name:"addRecords",description:"Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt.",schema:An});async function Rn(e,t){return await t.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function Mn({layout:e},t){let{linkChartView:r}=ie(t);return await Rn(e,r)}var qn=i.object({layout:i.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")}),Ls=w(Mn,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:qn});function Ln(e,t){return t.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function zn({setting:e},t){let{linkChartView:r}=ie(t);return Ln(e,r)}var jn=i.object({setting:i.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),zs=w(zn,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:jn});async function On(e,t,r,a,o){let{graphQuery:n,explanation:s}=await Se(e,t.dataModel,r,o);await p({text:`Attempting to create link chart from derived query: ${n}`},o);let l=await Lt.fromCypherQuery(t,new We({openCypherQuery:n}));return await p({text:"Link chart created successfully, loading..."},o),a.map=l,await l.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart:
191
190
  ${n}
192
191
 
193
- Explanation: ${s}`}async function On({prompt:e},t){let{knowledgeGraph:r}=ve(t),{linkChartView:a}=ie(t),o=O.getDefault().helperServices;return await jn(e,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Dn=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),zs=w(On,{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:Dn});async function Vn({prompt:e},t){let{knowledgeGraph:r}=ve(t),a=O.getDefault().helperServices;return await Sn(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t)}var Pn=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),js=w(Vn,{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:Pn});var Os=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).
192
+ Explanation: ${s}`}async function Dn({prompt:e},t){let{knowledgeGraph:r}=xe(t),{linkChartView:a}=ie(t),o=D.getDefault().helperServices;return await On(e,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Vn=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),js=w(Dn,{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:Vn});async function Pn({prompt:e},t){let{knowledgeGraph:r}=xe(t),a=D.getDefault().helperServices;return await En(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t)}var Gn=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Os=w(Pn,{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:Gn});var Ds=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).
194
193
  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.
195
194
  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,
196
195
  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
@@ -222,4 +221,4 @@ _example: "Find all the products supplied by Supplier X and add them to my visua
222
221
  _example: "Expand the link chart from 'Entity D' to show its direct connections"_
223
222
  _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
224
223
  _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
225
- _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_`;return{a:Ns,b:Fs,c:Ve,d:As}},"Graphic","geometry/Point","geometry/Extent","symbols/PictureMarkerSymbol","rest/locator","portal/Portal","config","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","rest/knowledgeGraph/GraphQueryStreaming","request","identity/IdentityManager","rest/knowledgeGraphService","WebLinkChart",a)
224
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_`;return{a:Fs,b:As,c:Ve,d:Rs}},"Graphic","geometry/Point","geometry/Extent","symbols/PictureMarkerSymbol","rest/locator","portal/Portal","config","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","rest/knowledgeGraph/GraphQueryStreaming","request","identity/IdentityManager","rest/knowledgeGraphService","WebLinkChart",a)