@arcgis/ai-components 5.1.0-next.59 → 5.1.0-next.60

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