@arcgis/ai-components 5.2.0-next.26 → 5.2.0-next.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import e from"./ZIXEFGIT.js";import d from"./HOCTVCHH.js";import c from"./VZMWVTXW.js";import b from"./EBRNMPPO.js";import{a,c as s}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=a(this,"arcgis-assistant-data-exploration-agent"),this.#i=s(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-data-exploration-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","views/LinkChartView","rest/knowledgeGraphService",b,c,d,e)
2
+ import e from"./PKHQW7QU.js";import d from"./HOCTVCHH.js";import c from"./AFLQZIKS.js";import b from"./EBRNMPPO.js";import{a,c as s}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=a(this,"arcgis-assistant-data-exploration-agent"),this.#i=s(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-data-exploration-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","views/LinkChartView","rest/knowledgeGraphService",b,c,d,e)
@@ -1,9 +1,9 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import a from"./EBRNMPPO.js";import{a as S,b as x}from"./4RZPOYZ7.js";import{_ as b,ea as xe,g as Te,j as B,k as U,pa as D,u as Se}from"./CJIV4KJZ.js";import{L as z,P as oe,_ as j,wc as y}from"./IKEF7ZHH.js";import{a as s}from"./WNS5ZUF5.js";import{Dd as N}from"./ZEYIBYSF.js";export default $arcgis.t(([Me,F,ie,je,,Ae,nt,{addressToLocations:it},st,lt,De,{createRenderer:ct},{getSchemesByTag:ut,getSchemes:dt},{getBackgroundColorTheme:qe},{createAgeRenderer:pt,createContinuousRenderer:mt},{getSchemesByTag:ge},{createContinuousRenderer:ht},{createRenderer:ft},{getSchemesByTag:yt},{createRenderer:gt},{getSchemesByTag:wt},{createRenderer:bt},{getSchemesByTag:vt},{createRenderer:Tt},{getSchemesByTag:St},{createAgeRenderer:xt,createContinuousRenderer:Et},{createRenderer:It},{getSchemesByTag:Nt},kt,Le,Oe,{formatDateOnly:$t,convertDateFormatToIntlOptions:W,formatTimeOnly:Ft,formatDate:Ce},Mt,At,qt,Ct,Rt,Pe,,{fetchKnowledgeGraph:Re,executeQueryStreaming:_t,executeSearchStreaming:zt},jt,{getBindParametersFromCypherQuery:Dt},{b:L,c:Ee,q:Ie}])=>{var Fe=e=>Array.isArray(e)&&e.every(z),tt=e=>typeof e=="object"&&e!=null&&"messages"in e&&Fe(e.messages),rt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,K=class extends xe{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:o,handleToolErrors:a}=t??{};super({name:r,tags:o,func:(n,l)=>this.run(n,l)}),this.tools=e,this.handleToolErrors=a??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(o=>o.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let o=await r.invoke({...e,type:"tool_call"},t);return z(o)&&o.getType()==="tool"||U(o)?o:new oe({status:"success",name:r.name,content:typeof o=="string"?o:JSON.stringify(o),tool_call_id:e.id})}catch(o){if(!this.handleToolErrors||Se(o))throw o;return new oe({status:"error",content:`Error: ${o.message}
3
- Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(rt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Fe(e))n=e;else if(tt(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let l=new Set(n.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=n.length-1;u>=0;u-=1){let c=n[u];if(j(c)){i=c;break}}if(i==null||!j(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!l.has(u.id)).map(u=>this.runTool(u,t))??[])}if(!r.some(U))return Array.isArray(e)?r:{messages:r};let o=[],a=null;for(let n of r)U(n)?n.graph===B.PARENT&&Array.isArray(n.goto)&&n.goto.every(l=>Te(l))?a?a.goto.push(...n.goto):a=new B({graph:B.PARENT,goto:n.goto}):o.push(n):o.push(Array.isArray(e)?[n]:{messages:[n]});return a&&o.push(a),o}};var Dn=b.Root({llmInputMessages:b({reducer:(e,t)=>D([],t),default:()=>[]})});var O=(e,t)=>t??e,Wi=b.Root({...Ee(),intent:b({reducer:O}),vectorSearchLayerResults:b({reducer:O,default:()=>[]}),vectorSearchFieldResults:b({reducer:O}),navigationInternalState:b({reducer:O,default:()=>({toolCallMessage:void 0})})});async function Lt(e,t){let r=F.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let a=o.url,n=`${ie.assetsPath?.endsWith("/")?ie.assetsPath:`${ie.assetsPath}/`}esri/images/search/search-symbol-32.png`,l=(await it(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!l?.extent||!l.location)throw new Error(`Could not find location for: ${e}`);let i=new st({url:n,width:24,height:24}),u=new nt({geometry:l.location,symbol:i});t.graphics.removeAll(),t.graphics.add(u),await t.goTo(l.extent);let c={address:l.address??"",location:l.location?l.location.toJSON():null,extent:l.extent?l.extent.toJSON():null};return{text:`Successfully zoomed to ${e}.`,sharedStatePatch:{lastResolvedLocation:{value:c}}}}var Ot=["mapView"];function k(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=Ot.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Pt({address:e},t){let{mapView:r}=k(t);return await Lt(e,r)}var Gt=s.object({address:s.string().describe("The full address or place name to locate.")}),Hi=y(Pt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Gt});async function Vt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(n=>n.name===e);if(!o)throw new Error(`Bookmark with name "${e}" not found.`);let a=o.viewpoint;if(!a)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await t.goTo(a),{text:`Navigated to bookmark: ${e}`}}async function Qt({bookmarkName:e},t){let{mapView:r}=k(t);return await Promise.resolve(Vt(e,r))}var Bt=N.object({bookmarkName:N.string().describe("The name of the bookmark to navigate to.")}),Ji=y(Qt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Bt});async function Ut(e,t,r){let o=r.map?.allLayers.find(l=>l.id===e);if(!o)return{text:`Error: Layer with id ${e} not found`};let a=t?.trim()?t:"1=1",n=o.createQuery();n.where=a;try{let{extent:l,count:i}=await o.queryExtent(n);if(i===0)return{text:`No features found in ${o.title} matching: ${a}`,where:a};if(l)await r.goTo(l);else return{text:`Error: Unable to determine extent for ${o.title}`,where:a};let u={layerId:e,layerTitle:o.title??e,where:a,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${o.title} matching: ${a}`,where:a,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(l){return console.error("Error in goToFeatures:",l),{text:`Error: ${l instanceof Error?l.message:"Unknown error"}`,where:a}}}async function Kt({layerId:e,where:t},r){let{mapView:o}=k(r);return await Ut(e,t,o)}var Wt=N.object({layerId:N.string().describe("The layerId of the layer to zoom to."),where:N.string().describe("The sql-92 where clause used to query features to zoom to")}),Zi=y(Kt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Wt});async function Ht(e){let t=new lt({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"Successfully zoomed to world extent"}}async function Jt(e,t){let{mapView:r}=k(t);return await Ht(r)}var Zt=N.object({}),Yi=y(Jt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Zt});async function Yt(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function Xt(e,t){let{mapView:r}=k(t);return await Yt(r)}var er=s.object({}),Xi=y(Xt,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:er});async function tr(e,t){await t.when();let r=t.map?.allLayers.find(a=>a.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),{text:`Could not find layer for: ${e}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?o=t.map.diagramNodesExtent:o=r.fullExtent,o?(await t.goTo(o),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function rr({layerId:e},t){let{mapView:r}=k(t);return await tr(e,r)}var or=N.object({layerId:N.string().describe("The id of the layer to navigate to")}),es=y(rr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:or});async function ar(e,t){return await t.goTo({scale:e}),{text:`Successfully zoomed to: ${e}`}}async function nr({scale:e},t){let{mapView:r}=k(t);return await ar(e,r)}var ir=s.object({scale:s.number().describe("The map scale of the view to go to.")}),ts=y(nr,{name:"goToScale",description:"Go to the specified view scale.",schema:ir});async function sr(e,t,r){let o={target:new De({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await t.goTo(o),{text:`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function lr({center:e,zoom:t,scale:r},o){let{mapView:a}=k(o);return await sr(e,a,{zoom:t,scale:r})}var cr=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.")}),rs=y(lr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:cr});async function ur(e,t){return await t.goTo({zoom:e}),{text:`Successfully zoomed to: ${e}`}}async function dr({zoom:e},t){let{mapView:r}=k(t);return await ur(e,r)}var pr=s.object({zoom:s.number().min(1).max(20).describe("The zoom level of the view to go to.")}),os=y(dr,{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:pr}),_e=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LEPJUN3X.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./W2IHPJ54.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./ZMSJQB65.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./5ZZGKP7N.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./3AXQTBIA.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./ZS2TZ6BF.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./LQ6R5YRN.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./TNMXWUXU.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./T537PKP4.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./4I4MCV7V.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./FX7UOGHP.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./KTK4HNL2.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./6YMR4QSD.js").then(e=>e.default)});async function Z(e){let t=Object.entries(_e).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
2
+ import a from"./EBRNMPPO.js";import{a as S,b as x}from"./4RZPOYZ7.js";import{_ as b,ea as xe,g as Te,j as B,k as U,pa as D,u as Se}from"./CJIV4KJZ.js";import{L as z,P as oe,_ as j,wc as y}from"./IKEF7ZHH.js";import{a as s}from"./WNS5ZUF5.js";import{Dd as N}from"./ZEYIBYSF.js";export default $arcgis.t(([Me,F,ie,je,,Ae,nt,{addressToLocations:it},st,lt,De,{createRenderer:ct},{getSchemesByTag:ut,getSchemes:dt},{getBackgroundColorTheme:Re},{createAgeRenderer:pt,createContinuousRenderer:mt},{getSchemesByTag:ge},{createContinuousRenderer:ht},{createRenderer:ft},{getSchemesByTag:yt},{createRenderer:gt},{getSchemesByTag:wt},{createRenderer:bt},{getSchemesByTag:vt},{createRenderer:Tt},{getSchemesByTag:St},{createAgeRenderer:xt,createContinuousRenderer:Et},{createRenderer:It},{getSchemesByTag:Nt},kt,Le,Oe,{formatDateOnly:$t,convertDateFormatToIntlOptions:W,formatTimeOnly:Ft,formatDate:qe},Mt,At,Rt,qt,Ct,Pe,,{fetchKnowledgeGraph:Ce,executeQueryStreaming:_t,executeSearchStreaming:zt},jt,{getBindParametersFromCypherQuery:Dt},{b:L,c:Ee,q:Ie}])=>{var Fe=e=>Array.isArray(e)&&e.every(z),tt=e=>typeof e=="object"&&e!=null&&"messages"in e&&Fe(e.messages),rt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,K=class extends xe{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:o,handleToolErrors:a}=t??{};super({name:r,tags:o,func:(n,l)=>this.run(n,l)}),this.tools=e,this.handleToolErrors=a??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(o=>o.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let o=await r.invoke({...e,type:"tool_call"},t);return z(o)&&o.getType()==="tool"||U(o)?o:new oe({status:"success",name:r.name,content:typeof o=="string"?o:JSON.stringify(o),tool_call_id:e.id})}catch(o){if(!this.handleToolErrors||Se(o))throw o;return new oe({status:"error",content:`Error: ${o.message}
3
+ Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(rt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Fe(e))n=e;else if(tt(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let l=new Set(n.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=n.length-1;u>=0;u-=1){let c=n[u];if(j(c)){i=c;break}}if(i==null||!j(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!l.has(u.id)).map(u=>this.runTool(u,t))??[])}if(!r.some(U))return Array.isArray(e)?r:{messages:r};let o=[],a=null;for(let n of r)U(n)?n.graph===B.PARENT&&Array.isArray(n.goto)&&n.goto.every(l=>Te(l))?a?a.goto.push(...n.goto):a=new B({graph:B.PARENT,goto:n.goto}):o.push(n):o.push(Array.isArray(e)?[n]:{messages:[n]});return a&&o.push(a),o}};var Dn=b.Root({llmInputMessages:b({reducer:(e,t)=>D([],t),default:()=>[]})});var O=(e,t)=>t??e,Wi=b.Root({...Ee(),intent:b({reducer:O}),vectorSearchLayerResults:b({reducer:O,default:()=>[]}),vectorSearchFieldResults:b({reducer:O}),navigationInternalState:b({reducer:O,default:()=>({toolCallMessage:void 0})})});async function Lt(e,t){let r=F.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let a=o.url,n=`${ie.assetsPath?.endsWith("/")?ie.assetsPath:`${ie.assetsPath}/`}esri/images/search/search-symbol-32.png`,l=(await it(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!l?.extent||!l.location)throw new Error(`Could not find location for: ${e}`);let i=new st({url:n,width:24,height:24}),u=new nt({geometry:l.location,symbol:i});t.graphics.removeAll(),t.graphics.add(u),await t.goTo(l.extent);let c={address:l.address??"",location:l.location?l.location.toJSON():null,extent:l.extent?l.extent.toJSON():null};return{text:`Successfully zoomed to ${e}.`,sharedStatePatch:{lastResolvedLocation:{value:c}}}}var Ot=["mapView"];function k(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=Ot.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Pt({address:e},t){let{mapView:r}=k(t);return await Lt(e,r)}var Gt=s.object({address:s.string().describe("The full address or place name to locate.")}),Hi=y(Pt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Gt});async function Vt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(n=>n.name===e);if(!o)throw new Error(`Bookmark with name "${e}" not found.`);let a=o.viewpoint;if(!a)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await t.goTo(a),{text:`Navigated to bookmark: ${e}`}}async function Qt({bookmarkName:e},t){let{mapView:r}=k(t);return await Promise.resolve(Vt(e,r))}var Bt=N.object({bookmarkName:N.string().describe("The name of the bookmark to navigate to.")}),Ji=y(Qt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Bt});async function Ut(e,t,r){let o=r.map?.allLayers.find(l=>l.id===e);if(!o)return{text:`Error: Layer with id ${e} not found`};let a=t?.trim()?t:"1=1",n=o.createQuery();n.where=a;try{let{extent:l,count:i}=await o.queryExtent(n);if(i===0)return{text:`No features found in ${o.title} matching: ${a}`,where:a};if(l)await r.goTo(l);else return{text:`Error: Unable to determine extent for ${o.title}`,where:a};let u={layerId:e,layerTitle:o.title??e,where:a,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${o.title} matching: ${a}`,where:a,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(l){return console.error("Error in goToFeatures:",l),{text:`Error: ${l instanceof Error?l.message:"Unknown error"}`,where:a}}}async function Kt({layerId:e,where:t},r){let{mapView:o}=k(r);return await Ut(e,t,o)}var Wt=N.object({layerId:N.string().describe("The layerId of the layer to zoom to."),where:N.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),Zi=y(Kt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Wt});async function Ht(e){let t=new lt({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"Successfully zoomed to world extent"}}async function Jt(e,t){let{mapView:r}=k(t);return await Ht(r)}var Zt=N.object({}),Yi=y(Jt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Zt});async function Yt(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function Xt(e,t){let{mapView:r}=k(t);return await Yt(r)}var er=s.object({}),Xi=y(Xt,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:er});async function tr(e,t){await t.when();let r=t.map?.allLayers.find(a=>a.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),{text:`Could not find layer for: ${e}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?o=t.map.diagramNodesExtent:o=r.fullExtent,o?(await t.goTo(o),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function rr({layerId:e},t){let{mapView:r}=k(t);return await tr(e,r)}var or=N.object({layerId:N.string().describe("The id of the layer to navigate to")}),es=y(rr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:or});async function ar(e,t){return await t.goTo({scale:e}),{text:`Successfully zoomed to: ${e}`}}async function nr({scale:e},t){let{mapView:r}=k(t);return await ar(e,r)}var ir=s.object({scale:s.number().describe("The map scale of the view to go to.")}),ts=y(nr,{name:"goToScale",description:"Go to the specified view scale.",schema:ir});async function sr(e,t,r){let o={target:new De({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await t.goTo(o),{text:`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function lr({center:e,zoom:t,scale:r},o){let{mapView:a}=k(o);return await sr(e,a,{zoom:t,scale:r})}var cr=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.")}),rs=y(lr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:cr});async function ur(e,t){return await t.goTo({zoom:e}),{text:`Successfully zoomed to: ${e}`}}async function dr({zoom:e},t){let{mapView:r}=k(t);return await ur(e,r)}var pr=s.object({zoom:s.number().min(1).max(20).describe("The zoom level of the view to go to.")}),os=y(dr,{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:pr}),_e=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LEPJUN3X.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./W2IHPJ54.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./ZMSJQB65.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./5ZZGKP7N.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./3AXQTBIA.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./ZS2TZ6BF.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./LQ6R5YRN.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./TNMXWUXU.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./T537PKP4.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./4I4MCV7V.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./FX7UOGHP.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./KTK4HNL2.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./6YMR4QSD.js").then(e=>e.default)});async function Z(e){let t=Object.entries(_e).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
4
4
  Available prompts:
5
5
  ${Object.keys(_e).join(`
6
- `)}`);return await t[1]()}var mr=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r},Ge=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},as=(e,t)=>(r,o)=>{let a=o?.configurable?.services;for(let n of e)if(!a?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r};async function hr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,l;return n?l=ut({basemapTheme:await qe(o),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:l=dt({basemapTheme:await qe(o),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:o,attributes:t.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),pieChartScheme:l}}async function fr(e){return await ct(e)}async function yr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,includeSize:n}){let l=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:n?"chart-size":"chart",fields:o,layer:i,view:l,colorSchemeTags:a};try{let c=await hr(u),d=await fr(c);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying chart renderer: ${c instanceof Error?c.message:String(c)}`}}var gr=["mapView"];function I(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=gr.filter(o=>!(o in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function wr({layerId:e,fields:t,colorSchemes:r,includeSize:o},a){let{mapView:n}=I(a);return await x({type:"show-legend",data:{layerIds:[e]}},a),await yr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var br=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)")}),ns=y(wr,{name:"chart",description:`Label: Charts
6
+ `)}`);return await t[1]()}var mr=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r},Ge=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},as=(e,t)=>(r,o)=>{let a=o?.configurable?.services;for(let n of e)if(!a?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r};async function hr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,l;return n?l=ut({basemapTheme:await Re(o),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:l=dt({basemapTheme:await Re(o),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:o,attributes:t.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),pieChartScheme:l}}async function fr(e){return await ct(e)}async function yr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,includeSize:n}){let l=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:n?"chart-size":"chart",fields:o,layer:i,view:l,colorSchemeTags:a};try{let c=await hr(u),d=await fr(c);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying chart renderer: ${c instanceof Error?c.message:String(c)}`}}var gr=["mapView"];function I(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=gr.filter(o=>!(o in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function wr({layerId:e,fields:t,colorSchemes:r,includeSize:o},a){let{mapView:n}=I(a);return await x({type:"show-legend",data:{layerIds:[e]}},a),await yr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var br=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)")}),ns=y(wr,{name:"chart",description:`Label: Charts
7
7
  Description: Show the values of two or more categories as a proportion of the total using a pie chart.
8
8
  Keywords: pie, chart, all categories, breakdown, proportion
9
9
  Example: Show the total number of homes built in each decade using a pie chart for each feature.
@@ -21,11 +21,11 @@ ${Object.keys(_e).join(`
21
21
  Description: Vary color along a continuous color ramp to represent numeric or ranked data.
22
22
  Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
23
23
  Example: Color each feature based on the population density.
24
- 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:Fr});function Mr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a,theme:n}=e,l,i,u=t[0];return a&&(i=ge({geometryType:r.geometryType,includedTags:a,theme:n||"high-to-low"})[0]),{layer:r,view:o,field:u,normalizationField:l,theme:n,colorOptions:{colorScheme:i}}}async function Ar(e){return await ht(e)}async function qr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let c=Mr(u),d=await Ar(c);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying color-size-univariate renderer: ${c instanceof Error?c.message:String(c)}`}}async function Cr({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=I(a);return await x({type:"show-legend",data:{layerIds:[e]}},a),await qr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var Rr=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")}),ls=y(Cr,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
24
+ 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:Fr});function Mr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a,theme:n}=e,l,i,u=t[0];return a&&(i=ge({geometryType:r.geometryType,includedTags:a,theme:n||"high-to-low"})[0]),{layer:r,view:o,field:u,normalizationField:l,theme:n,colorOptions:{colorScheme:i}}}async function Ar(e){return await ht(e)}async function Rr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let c=Mr(u),d=await Ar(c);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying color-size-univariate renderer: ${c instanceof Error?c.message:String(c)}`}}async function qr({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=I(a);return await x({type:"show-legend",data:{layerIds:[e]}},a),await Rr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var Cr=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")}),ls=y(qr,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
25
25
  Description: Vary symbol size and color based on the values of two numeric attributes.
26
26
  Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
27
27
  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.
28
- 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:Rr});function _r(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n;return a&&(n=yt({includedTags:a,numColors:Math.min(t.length,8)})[0]),{layer:r,view:o,legendOptions:{unit:"units"},attributes:t.map(l=>({field:l,label:r.fields.find(i=>i.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function zr(e){return await ft(e)}async function jr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a}){let n=t,l=e?.allLayers.find(u=>u.id===r);if(!l)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:o,layer:l,view:n,colorSchemeTags:a};try{let u=_r(i),c=await zr(u);return l.renderer=c.renderer,l.visible=!0,`Dot Density renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function Dr({layerId:e,fields:t,colorSchemes:r},o){let{mapView:a}=I(o);return await x({type:"show-legend",data:{layerIds:[e]}},o),await jr({arcgisMap:a.map,arcgisMapView:a,layerId:e,fields:t,colorSchemes:r})}var Lr=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")}),cs=y(Dr,{name:"dot-density",description:`Dot Density
28
+ 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:Cr});function _r(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n;return a&&(n=yt({includedTags:a,numColors:Math.min(t.length,8)})[0]),{layer:r,view:o,legendOptions:{unit:"units"},attributes:t.map(l=>({field:l,label:r.fields.find(i=>i.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function zr(e){return await ft(e)}async function jr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a}){let n=t,l=e?.allLayers.find(u=>u.id===r);if(!l)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:o,layer:l,view:n,colorSchemeTags:a};try{let u=_r(i),c=await zr(u);return l.renderer=c.renderer,l.visible=!0,`Dot Density renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function Dr({layerId:e,fields:t,colorSchemes:r},o){let{mapView:a}=I(o);return await x({type:"show-legend",data:{layerIds:[e]}},o),await jr({arcgisMap:a.map,arcgisMapView:a,layerId:e,fields:t,colorSchemes:r})}var Lr=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")}),cs=y(Dr,{name:"dot-density",description:`Dot Density
29
29
  Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
30
30
  **Use cases:**
31
31
  - Population distribution visualization
@@ -72,7 +72,7 @@ Fields: This typically requires zero or one field of type number.`,schema:Qr});f
72
72
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
73
73
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
74
74
  Example: Color each feature based on the region it belongs to
75
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:yo}),ys=b.Root({...L(),vectorSearchLayerIds:b(),vectorSearchFieldResults:b(),layerFieldInfo:b(),selectedLayerId:b()}),gs=b.Root({...L(),vectorSearchLayerIds:b(),vectorSearchFieldResults:b(),layerFieldInfo:b(),queryResponse:b(),dataExplorationMessages:b({reducer:D,default:()=>[]})}),go=["mapView"];function M(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=go.filter(o=>!(o in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var wo=e=>{let t=e.map?.allLayers.filter(o=>o.type==="feature"),r=0;return t?.forEach(o=>{let a=o;a.featureEffect&&(a.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},bo=async(e,t)=>{let{mapView:r}=M(t);return wo(r)},vo=y(bo,{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({})}),To=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},So=async(e,t)=>{let{mapView:r}=M(t);return await To(r)},xo=y(So,{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({})}),ze=750;function Y(e){return"point"in e&&e.point!==void 0}function P(e){return"layerId"in e&&e.layerId!==void 0}var ee=async(e,t)=>{if(Y(e)){let{point:r}=e;return{geometry:new De({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(P(e)){let r=t.map?.allLayers.find(n=>n.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let o=r.title??r.id,a=e.where?.trim()||"1=1";try{let n=await r.queryFeatures({where:a,returnGeometry:!0,outSpatialReference:t.spatialReference,num:ze+1});if(!n.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${a}`};if(n.features.length>ze)return{error:`Geometry filter for layer "${o}" matched too many features (${n.features.length}+). Please narrow the geometry layer filter.`};let l=n.features.map(u=>u.geometry).filter(u=>!!u);if(!l.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=l.length===1?l[0]:Oe.executeMany(l);return i?(i.spatialReference||(i.spatialReference=t.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(n){return{error:`Failed to query geometry: ${String(n)}`}}}return{error:"Invalid geometry configuration provided"}},Eo=async(e,t,r,o,a,n)=>{let l=e.map?.allLayers.find(u=>u.id===t);if(!l)return{success:!1,error:`Layer '${t}' not found.`};let i=l.createQuery();i.where=r??"1=1",o&&(i.geometry=o,i.spatialRelationship="intersects",a&&(i.distance=a),n&&(i.units=n));try{let{extent:u,count:c}=await l.queryExtent(i);return!u||c===0?{success:!1,error:`No features found for filter (where: ${i.where}${o?", spatial filter used":""})`}:(await e.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},Io=async(e,t,r,o,a,n)=>{let l=t.map?.allLayers.find(m=>m.id===e.layerId);if(!l)return`Could not find target layer with ID: ${e.layerId}`;let i;if(a){let m=await ee(a,t);if("error"in m)return m.error;i=m.geometry}if(l.featureEffect=null,l.featureEffect=new kt({filter:new Le({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:i,spatialRelationship:"intersects",distance:a?.distance,units:a?.units}),includedEffect:r,excludedEffect:o}),l.visible=!0,n)return`Applied feature effects to "${l.title??e.layerId}" within current map extent.`;let u=e.objectIds?.length?`${l.objectIdField} IN (${e.objectIds.join(",")})`:e.where,c=await Eo(t,e.layerId,u,i,a?.distance,a?.units),d=l.title??e.layerId;return c.success?`Applied feature effects to target layer "${l.title??e.layerId}"${a&&"layerId"in a?` using geometry from layer "${a.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${c.error}`},No=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],$=s.enum(No),ko=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:l}=M(n);return await Io(e,l,o,a,t,r)},$o=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:$.optional().describe("The units for the distance buffer.")}),Fo=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:$.optional().describe("The units for the distance buffer.")}),Mo=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."),objectIds:s.array(s.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:s.union([$o,Fo]).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.")}),Ao=y(ko,{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:Mo}),qo=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Ve=e=>{if(!e)return!1;let t=e.toLowerCase();return qo.has(t)},le=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Co=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Ro=e=>{if(typeof e=="string"&&e)return e;let t=le(e);return t?t.toISOString().slice(0,10):null},ws=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),o=(Math.abs(e)%60).toString().padStart(2,"0"),a=`${t}${r}:${o}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:a}},_o=(e,t,r)=>{let o=t?.toLowerCase();if(o&&!Ve(o))return e;if(o==="date-only"){let n=Ro(e);return n?$t(n,W("short-date")):e}if(o==="time-only"){if(typeof e=="string"&&e)return Ft(e,W("long-time"));let n=le(e);return n?Ce(n,{...W("long-time"),timeZone:"UTC"}):e}let a=le(e);return a?Ce(a,{...W("short-date-short-time"),timeZone:Co(r)}):e},Qe=(e,t,r)=>{if(e&&typeof e!="function"){let o="getField"in r&&r.getField?.(e),a=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(a?.type==="coded-value"){let n=a.codedValues.find(l=>l.code===t);return n?n.name:null}}return null},zo=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,jo=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Do=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},Lo=(e,t,r)=>{let o=jo(e);if(!o)return e;let a={};t.dateStyle?a.dateStyle=t.dateStyle:(t.year&&(a.year=t.year),t.month&&(a.month=t.month)),t.timeStyle&&(a.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?a.hour12=!0:t.timeStyle&&t.hour12==="never"&&(a.hour12=!1),a.timeZone=zo(r);try{return new Intl.DateTimeFormat(void 0,a).format(o)}catch{return e}},Be=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,Ue=(e,t,r,o,a)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?Do(r,n):n?.type==="date-time"?!o||Ve(o)?Lo(r,n,a):r:_o(r,o,a)},Oo=(e,t,r,o)=>{let a=e.fieldsIndex?.get(t),n=Qe(t,r,e)??r;return Ue(e,t,n,a?.type,o)},Po=(e,t)=>Be(e,t),Ke=(e,t,r)=>{let o=e.objectIdField,a=t.features.map(l=>l.attributes[o]),n=t.features.map(l=>{let i=l.attributes,u={};return e.fields.forEach(c=>{if(!Object.hasOwn(i,c.name))return;let d=i[c.name];if(c.name===o){u[c.name]=d;return}let m=Qe(c.name,d,e)??d,p=Be(e,c.name);u[p]=Ue(e,c.name,m,c.type,r)}),u});return{objectIds:a,attributes:n}},Go=(e,t,r)=>{let o=e.createQuery();return o.outFields=[t],o.where=r||"1=1",o.num=1,o},Vo=async(e,t,r,o)=>{let a=o.map?.allLayers.find(d=>d.id===e),n=Go(a,t,r.where),l=(await a.queryFeatures(n)).features[0],i=l?l.attributes[t]:null,u=Oo(a,t,i,o.timeZone),c=Po(a,t);return{tool:"getAttribute",layerName:a.title??e,summary:`${c} = ${u}`,details:{fieldName:t,fieldAlias:c!==t?c:void 0,value:u,where:r.where}}};async function Qo({layerId:e,fieldName:t,query:r},o){let{mapView:a}=M(o),n=await Vo(e,t,r,a);return JSON.stringify(n,null,2)}var Bo=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.")})}),Uo=y(Qo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Bo}),we=(e,t,r)=>{if(!(r?e.hasAllFeaturesInView:e.hasAllFeatures))return!1;let o=new Set((e.availableFields??[]).map(a=>a.toLowerCase()));return o.has("*")?!0:t.every(a=>o.has(a.toLowerCase()))};function X(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var Ko=async e=>{let{targetLayer:t,fieldName:r,statisticType:o,mapView:a,layersAndFieldsRegistry:n,geometryFilter:l}=e,i=a.map?.allLayers.find(g=>g.id===t.layerId);if(!i)throw new Error(`Layer '${t.layerId}' not found.`);let u=await a.whenLayerView(i),c=n.get(t.layerId)?.fieldRegistry.get(r),d=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let m,p;if(l){let g=await ee(l,a);if("error"in g)throw new Error(g.error);if(!g.geometry)throw P(l)?new Error(`No features found matching: ${l.where}`):new Error("Failed to create geometry");if(P(l)){let T=a.map?.allLayers.find(E=>E.id===l.layerId);m={geometryLayerName:T?.title??T?.id,geometryLayerId:l.layerId,geometryWhere:l.where,distance:l.distance,units:l.units,applied:!0}}else Y(l)&&(m={point:l.point,distance:l.distance,units:l.units,applied:!0});p=new Le({geometry:g.geometry,distance:l.distance,units:l.units,spatialRelationship:"intersects"})}let w=we(u,[r],!1),f=null,h=null,v=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let g={layer:i,useFeaturesInView:w,view:w?a:void 0,field:r,sqlWhere:X(i.definitionExpression,t.where),...p&&{filter:p},outStatisticTypes:{include:[o]}};f=await Mt(g);let T=["string","small-integer","integer"],E=c.domain?.type==="coded-value"?c.domain:null;(T.includes(c.type)||E)&&(h=(await At({layer:i,useFeaturesInView:w,view:w?a:void 0,field:r,sqlWhere:X(i.definitionExpression,t.where),...p&&{filter:p}})).uniqueValueInfos.sort((q,Xe)=>Xe.count-q.count).slice(0,v)),h&&c.domain?.type==="coded-value"&&(h=h.map(q=>({...q,value:E?E.getName(q.value)??q.value:q.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:i.title??t.layerId,summary:`${o} = ${typeof f?.[o]=="number"?f[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:f?.[o]??null,summaryStatistics:f,uniqueValues:h,where:t.where,spatialFilterInfo:m}}};async function Wo({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:o},a){let n=Ge(a,"layersAndFieldsRegistry"),{mapView:l}=M(a),i=await Ko({targetLayer:e,fieldName:t,statisticType:r,mapView:l,layersAndFieldsRegistry:n,geometryFilter:o});return JSON.stringify(i,null,2)}var Ho=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:$.optional().describe("The units for the distance buffer.")}),Jo=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:$.optional().describe("The units for the distance buffer.")}),Zo=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([Ho,Jo]).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.")}),Yo=y(Wo,{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.
75
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:yo}),ys=b.Root({...L(),vectorSearchLayerIds:b(),vectorSearchFieldResults:b(),layerFieldInfo:b(),selectedLayerId:b()}),gs=b.Root({...L(),vectorSearchLayerIds:b(),vectorSearchFieldResults:b(),layerFieldInfo:b(),queryResponse:b(),dataExplorationMessages:b({reducer:D,default:()=>[]})}),go=["mapView"];function M(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=go.filter(o=>!(o in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var wo=e=>{let t=e.map?.allLayers.filter(o=>o.type==="feature"),r=0;return t?.forEach(o=>{let a=o;a.featureEffect&&(a.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},bo=async(e,t)=>{let{mapView:r}=M(t);return wo(r)},vo=y(bo,{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({})}),To=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},So=async(e,t)=>{let{mapView:r}=M(t);return await To(r)},xo=y(So,{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({})}),ze=750;function Y(e){return"point"in e&&e.point!==void 0}function P(e){return"layerId"in e&&e.layerId!==void 0}var ee=async(e,t)=>{if(Y(e)){let{point:r}=e;return{geometry:new De({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(P(e)){let r=t.map?.allLayers.find(n=>n.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let o=r.title??r.id,a=e.where?.trim()||"1=1";try{let n=await r.queryFeatures({where:a,returnGeometry:!0,outSpatialReference:t.spatialReference,num:ze+1});if(!n.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${a}`};if(n.features.length>ze)return{error:`Geometry filter for layer "${o}" matched too many features (${n.features.length}+). Please narrow the geometry layer filter.`};let l=n.features.map(u=>u.geometry).filter(u=>!!u);if(!l.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=l.length===1?l[0]:Oe.executeMany(l);return i?(i.spatialReference||(i.spatialReference=t.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(n){return{error:`Failed to query geometry: ${String(n)}`}}}return{error:"Invalid geometry configuration provided"}},Eo=async(e,t,r,o,a,n)=>{let l=e.map?.allLayers.find(u=>u.id===t);if(!l)return{success:!1,error:`Layer '${t}' not found.`};let i=l.createQuery();i.where=r??"1=1",o&&(i.geometry=o,i.spatialRelationship="intersects",a&&(i.distance=a),n&&(i.units=n));try{let{extent:u,count:c}=await l.queryExtent(i);return!u||c===0?{success:!1,error:`No features found for filter (where: ${i.where}${o?", spatial filter used":""})`}:(await e.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},Io=async(e,t,r,o,a,n)=>{let l=t.map?.allLayers.find(m=>m.id===e.layerId);if(!l)return`Could not find target layer with ID: ${e.layerId}`;let i;if(a){let m=await ee(a,t);if("error"in m)return m.error;i=m.geometry}if(l.featureEffect=null,l.featureEffect=new kt({filter:new Le({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:i,spatialRelationship:"intersects",distance:a?.distance,units:a?.units}),includedEffect:r,excludedEffect:o}),l.visible=!0,n)return`Applied feature effects to "${l.title??e.layerId}" within current map extent.`;let u=e.objectIds?.length?`${l.objectIdField} IN (${e.objectIds.join(",")})`:e.where,c=await Eo(t,e.layerId,u,i,a?.distance,a?.units),d=l.title??e.layerId;return c.success?`Applied feature effects to target layer "${l.title??e.layerId}"${a&&"layerId"in a?` using geometry from layer "${a.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${c.error}`},No=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],$=s.enum(No),ko=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:l}=M(n);return await Io(e,l,o,a,t,r)},$o=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:$.optional().describe("The units for the distance buffer.")}),Fo=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:$.optional().describe("The units for the distance buffer.")}),Mo=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."),objectIds:s.array(s.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:s.union([$o,Fo]).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.")}),Ao=y(ko,{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:Mo}),Ro=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Ve=e=>{if(!e)return!1;let t=e.toLowerCase();return Ro.has(t)},le=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},qo=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Co=e=>{if(typeof e=="string"&&e)return e;let t=le(e);return t?t.toISOString().slice(0,10):null},ws=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),o=(Math.abs(e)%60).toString().padStart(2,"0"),a=`${t}${r}:${o}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:a}},_o=(e,t,r)=>{let o=t?.toLowerCase();if(o&&!Ve(o))return e;if(o==="date-only"){let n=Co(e);return n?$t(n,W("short-date")):e}if(o==="time-only"){if(typeof e=="string"&&e)return Ft(e,W("long-time"));let n=le(e);return n?qe(n,{...W("long-time"),timeZone:"UTC"}):e}let a=le(e);return a?qe(a,{...W("short-date-short-time"),timeZone:qo(r)}):e},Qe=(e,t,r)=>{if(e&&typeof e!="function"){let o="getField"in r&&r.getField?.(e),a=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(a?.type==="coded-value"){let n=a.codedValues.find(l=>l.code===t);return n?n.name:null}}return null},zo=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,jo=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Do=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},Lo=(e,t,r)=>{let o=jo(e);if(!o)return e;let a={};t.dateStyle?a.dateStyle=t.dateStyle:(t.year&&(a.year=t.year),t.month&&(a.month=t.month)),t.timeStyle&&(a.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?a.hour12=!0:t.timeStyle&&t.hour12==="never"&&(a.hour12=!1),a.timeZone=zo(r);try{return new Intl.DateTimeFormat(void 0,a).format(o)}catch{return e}},Be=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,Ue=(e,t,r,o,a)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?Do(r,n):n?.type==="date-time"?!o||Ve(o)?Lo(r,n,a):r:_o(r,o,a)},Oo=(e,t,r,o)=>{let a=e.fieldsIndex?.get(t),n=Qe(t,r,e)??r;return Ue(e,t,n,a?.type,o)},Po=(e,t)=>Be(e,t),Ke=(e,t,r)=>{let o=e.objectIdField,a=t.features.map(l=>l.attributes[o]),n=t.features.map(l=>{let i=l.attributes,u={};return e.fields.forEach(c=>{if(!Object.hasOwn(i,c.name))return;let d=i[c.name];if(c.name===o){u[c.name]=d;return}let m=Qe(c.name,d,e)??d,p=Be(e,c.name);u[p]=Ue(e,c.name,m,c.type,r)}),u});return{objectIds:a,attributes:n}},Go=(e,t,r)=>{let o=e.createQuery();return o.outFields=[t],o.where=r||"1=1",o.num=1,o},Vo=async(e,t,r,o)=>{let a=o.map?.allLayers.find(d=>d.id===e),n=Go(a,t,r.where),l=(await a.queryFeatures(n)).features[0],i=l?l.attributes[t]:null,u=Oo(a,t,i,o.timeZone),c=Po(a,t);return{tool:"getAttribute",layerName:a.title??e,summary:`${c} = ${u}`,details:{fieldName:t,fieldAlias:c!==t?c:void 0,value:u,where:r.where}}};async function Qo({layerId:e,fieldName:t,query:r},o){let{mapView:a}=M(o),n=await Vo(e,t,r,a);return JSON.stringify(n,null,2)}var Bo=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.")})}),Uo=y(Qo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Bo}),we=(e,t,r)=>{if(!(r?e.hasAllFeaturesInView:e.hasAllFeatures))return!1;let o=new Set((e.availableFields??[]).map(a=>a.toLowerCase()));return o.has("*")?!0:t.every(a=>o.has(a.toLowerCase()))};function X(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var Ko=async e=>{let{targetLayer:t,fieldName:r,statisticType:o,mapView:a,layersAndFieldsRegistry:n,geometryFilter:l}=e,i=a.map?.allLayers.find(g=>g.id===t.layerId);if(!i)throw new Error(`Layer '${t.layerId}' not found.`);let u=await a.whenLayerView(i),c=n.get(t.layerId)?.fieldRegistry.get(r),d=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let m,p;if(l){let g=await ee(l,a);if("error"in g)throw new Error(g.error);if(!g.geometry)throw P(l)?new Error(`No features found matching: ${l.where}`):new Error("Failed to create geometry");if(P(l)){let T=a.map?.allLayers.find(E=>E.id===l.layerId);m={geometryLayerName:T?.title??T?.id,geometryLayerId:l.layerId,geometryWhere:l.where,distance:l.distance,units:l.units,applied:!0}}else Y(l)&&(m={point:l.point,distance:l.distance,units:l.units,applied:!0});p=new Le({geometry:g.geometry,distance:l.distance,units:l.units,spatialRelationship:"intersects"})}let w=we(u,[r],!1),f=null,h=null,v=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let g={layer:i,useFeaturesInView:w,view:w?a:void 0,field:r,sqlWhere:X(i.definitionExpression,t.where),...p&&{filter:p},outStatisticTypes:{include:[o]}};f=await Mt(g);let T=["string","small-integer","integer"],E=c.domain?.type==="coded-value"?c.domain:null;(T.includes(c.type)||E)&&(h=(await At({layer:i,useFeaturesInView:w,view:w?a:void 0,field:r,sqlWhere:X(i.definitionExpression,t.where),...p&&{filter:p}})).uniqueValueInfos.sort((R,Xe)=>Xe.count-R.count).slice(0,v)),h&&c.domain?.type==="coded-value"&&(h=h.map(R=>({...R,value:E?E.getName(R.value)??R.value:R.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:i.title??t.layerId,summary:`${o} = ${typeof f?.[o]=="number"?f[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:f?.[o]??null,summaryStatistics:f,uniqueValues:h,where:t.where,spatialFilterInfo:m}}};async function Wo({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:o},a){let n=Ge(a,"layersAndFieldsRegistry"),{mapView:l}=M(a),i=await Ko({targetLayer:e,fieldName:t,statisticType:r,mapView:l,layersAndFieldsRegistry:n,geometryFilter:o});return JSON.stringify(i,null,2)}var Ho=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:$.optional().describe("The units for the distance buffer.")}),Jo=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:$.optional().describe("The units for the distance buffer.")}),Zo=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([Ho,Jo]).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.")}),Yo=y(Wo,{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.
76
76
 
77
77
  USE THIS TOOL FOR:
78
78
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -84,7 +84,7 @@ DO NOT USE FOR:
84
84
  - "Show / list / find features" \u2014 use queryFeatures instead
85
85
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
86
86
 
87
- 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:Zo}),Xo=e=>e.flatMap(t=>t.split(",")).map(t=>t.trim()).map(t=>t.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(t=>!!t),ea=async(e,t,r,o,a)=>{let n=r.map?.allLayers.find(p=>p.id===e.layerId),l=await r.whenLayerView(n),i=n.title??e.layerId,u;if(o){let p=await ee(o,r);if("error"in p)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:p.error}};if(!p.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in o?o.where:"unknown criteria"}`}};u=p.geometry}else a&&(u=r.extent.clone());let c=t.groupByFields&&t.groupByFields.length>0,d=n.objectIdField,m=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])];try{let p;if(c){let h=new qt({where:e.where||"1=1",outFields:m,orderByFields:e.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new Ct({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});p=await n.queryTopFeatures(h)}else{let h=n.createQuery();h.where=X(n.definitionExpression,e.where||"1=1"),h.outFields=m.length?m:["*"],h.orderByFields=t.orderByFields,h.returnGeometry=!1,h.num=t.topCount,u&&(h.geometry=u,h.spatialRelationship="intersects"),o?.distance&&(h.distance=o.distance),o?.units&&(h.units=o.units),h.outSpatialReference=r.spatialReference;let v=[...new Set([...e.outFields,...Xo(t.orderByFields)])],g=we(l,v,a??!1);try{p=g?await l.queryFeatures(h):await n.queryFeatures(h)}catch(T){console.warn("Client-side query failed, falling back to server:",T),p=await n.queryFeatures(h)}}let w=p.features.map(h=>h.attributes[d]),{attributes:f}=Ke(n,p,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:f,objectIds:w,objectIdField:d,where:e.where,orderByFields:t.orderByFields,...c&&{groupByFields:t.groupByFields}}}}catch(p){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:p instanceof Error?p.message:String(p)}}}},ta=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:o},a)=>{let{mapView:n}=M(a),l=await ea(e,t,n,r,o);return JSON.stringify(l,null,2)},ra=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:$.optional().describe("The units for the distance buffer.")}),oa=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:$.optional().describe("The units for the distance buffer.")}),aa=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([ra,oa]).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."))}).required(),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).")}),na=y(ta,{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:aa}),se=25,ia=e=>e.flatMap(t=>t.split(",")).map(t=>t.trim()).map(t=>t.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(t=>!!t),sa=async(e,t,r,o)=>{let a=t.map?.allLayers.find(v=>v.id===e.layerId),n=await t.whenLayerView(a),l=a.title??e.layerId,i;if(r){let v=await ee(r,t);if("error"in v){let g={error:v.error};if(P(r)){let T=t.map?.allLayers.find(E=>E.id===r.layerId);g.geometryLayerName=T?.title??T?.id,g.geometryLayerId=r.layerId,g.geometryWhere=r.where}else Y(r)&&(g.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"Geometry lookup failed",details:g}}if(!v.geometry){let g={};if(P(r)){let T=t.map?.allLayers.find(E=>E.id===r.layerId);g.error=`No features found matching: ${r.where}`,g.geometryLayerName=T?.title??T?.id,g.geometryLayerId=r.layerId,g.geometryWhere=r.where}else Y(r)&&(g.error="Failed to create point geometry",g.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"No features found for geometry filter",details:g}}i=v.geometry}else o&&(i=t.extent.clone());let u=[...new Set([...e.outFields,...ia(e.orderByFields)])],c=we(n,u,o??!1),d=a.objectIdField,m=a.createQuery();m.where=X(a.definitionExpression,e.where||"1=1"),m.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])],m.orderByFields=e.orderByFields,i&&(m.geometry=i,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=t.spatialReference;let p,w;try{p=c?await n.queryFeatureCount(m):await a.queryFeatureCount(m),p>0&&p<=se&&(w=c?await n.queryFeatures(m):await a.queryFeatures(m))}catch(v){console.warn("Client-side query failed, falling back to server:",v),p=await a.queryFeatureCount(m),p>0&&p<=se&&(w=await a.queryFeatures(m))}let{objectIds:f,attributes:h}=w?Ke(a,w,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:l,summary:`${p} features found`,details:{totalCount:p,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...f&&{objectIds:f,objectIdField:d},...h&&{attributes:h},...p>se&&{note:`${p} features found.`}}}};async function la({targetLayer:e,geometryFilter:t,useCurrentExtent:r},o){let{mapView:a}=M(o),n=await sa(e,a,t,r);return JSON.stringify(n,null,2)}var ca=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:$.optional().describe("The units for the distance buffer.")}),ua=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:$.optional().describe("The units for the distance buffer.")}),da=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([ca,ua]).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', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),pa=y(la,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
87
+ 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:Zo}),Xo=e=>e.flatMap(t=>t.split(",")).map(t=>t.trim()).map(t=>t.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(t=>!!t),ea=async(e,t,r,o,a)=>{let n=r.map?.allLayers.find(p=>p.id===e.layerId),l=await r.whenLayerView(n),i=n.title??e.layerId,u;if(o){let p=await ee(o,r);if("error"in p)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:p.error}};if(!p.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in o?o.where:"unknown criteria"}`}};u=p.geometry}else a&&(u=r.extent.clone());let c=t.groupByFields&&t.groupByFields.length>0,d=n.objectIdField,m=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])];try{let p;if(c){let h=new Rt({where:e.where||"1=1",outFields:m,orderByFields:e.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new qt({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});p=await n.queryTopFeatures(h)}else{let h=n.createQuery();h.where=X(n.definitionExpression,e.where||"1=1"),h.outFields=m.length?m:["*"],h.orderByFields=t.orderByFields,h.returnGeometry=!1,h.num=t.topCount,u&&(h.geometry=u,h.spatialRelationship="intersects"),o?.distance&&(h.distance=o.distance),o?.units&&(h.units=o.units),h.outSpatialReference=r.spatialReference;let v=[...new Set([...e.outFields,...Xo(t.orderByFields)])],g=we(l,v,a??!1);try{p=g?await l.queryFeatures(h):await n.queryFeatures(h)}catch(T){console.warn("Client-side query failed, falling back to server:",T),p=await n.queryFeatures(h)}}let w=p.features.map(h=>h.attributes[d]),{attributes:f}=Ke(n,p,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:f,objectIds:w,objectIdField:d,where:e.where,orderByFields:t.orderByFields,...c&&{groupByFields:t.groupByFields}}}}catch(p){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:p instanceof Error?p.message:String(p)}}}},ta=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:o},a)=>{let{mapView:n}=M(a),l=await ea(e,t,n,r,o);return JSON.stringify(l,null,2)},ra=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:$.optional().describe("The units for the distance buffer.")}),oa=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:$.optional().describe("The units for the distance buffer.")}),aa=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([ra,oa]).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."))}).required(),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).")}),na=y(ta,{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:aa}),se=25,ia=e=>e.flatMap(t=>t.split(",")).map(t=>t.trim()).map(t=>t.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(t=>!!t),sa=async(e,t,r,o)=>{let a=t.map?.allLayers.find(v=>v.id===e.layerId),n=await t.whenLayerView(a),l=a.title??e.layerId,i;if(r){let v=await ee(r,t);if("error"in v){let g={error:v.error};if(P(r)){let T=t.map?.allLayers.find(E=>E.id===r.layerId);g.geometryLayerName=T?.title??T?.id,g.geometryLayerId=r.layerId,g.geometryWhere=r.where}else Y(r)&&(g.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"Geometry lookup failed",details:g}}if(!v.geometry){let g={};if(P(r)){let T=t.map?.allLayers.find(E=>E.id===r.layerId);g.error=`No features found matching: ${r.where}`,g.geometryLayerName=T?.title??T?.id,g.geometryLayerId=r.layerId,g.geometryWhere=r.where}else Y(r)&&(g.error="Failed to create point geometry",g.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"No features found for geometry filter",details:g}}i=v.geometry}else o&&(i=t.extent.clone());let u=[...new Set([...e.outFields,...ia(e.orderByFields)])],c=we(n,u,o??!1),d=a.objectIdField,m=a.createQuery();m.where=X(a.definitionExpression,e.where||"1=1"),m.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])],m.orderByFields=e.orderByFields,i&&(m.geometry=i,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=t.spatialReference;let p,w;try{p=c?await n.queryFeatureCount(m):await a.queryFeatureCount(m),p>0&&p<=se&&(w=c?await n.queryFeatures(m):await a.queryFeatures(m))}catch(v){console.warn("Client-side query failed, falling back to server:",v),p=await a.queryFeatureCount(m),p>0&&p<=se&&(w=await a.queryFeatures(m))}let{objectIds:f,attributes:h}=w?Ke(a,w,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:l,summary:`${p} features found`,details:{totalCount:p,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...f&&{objectIds:f,objectIdField:d},...h&&{attributes:h},...p>se&&{note:`${p} features found.`}}}};async function la({targetLayer:e,geometryFilter:t,useCurrentExtent:r},o){let{mapView:a}=M(o),n=await sa(e,a,t,r);return JSON.stringify(n,null,2)}var ca=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:$.optional().describe("The units for the distance buffer.")}),ua=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:$.optional().describe("The units for the distance buffer.")}),da=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([ca,ua]).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', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),pa=y(la,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
88
88
 
89
89
  USE THIS TOOL FOR:
90
90
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -97,7 +97,7 @@ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema
97
97
  `)):"Query executed."}}var Ts=b.Root({...L(),helpInternalState:b({reducer:O,default:()=>({toolCallMessage:void 0})})}),fa=(e,t)=>{let r=Array.from(e.values()).find(({layerItem:n})=>n.title?.toLowerCase().includes(t.toLowerCase()));if(!r){let n=Array.from(e.values()).map(l=>l.layerItem.title).join(", ");return`Could not find a layer matching "${t}". Available layers: ${n}`}let o=Array.from(r.fieldRegistry.values()),a=o.map(n=>`- **${n.alias||n.name}** (\`${n.name}\`, ${n.type})${n.description?`: ${n.description}`:""}`).join(`
98
98
  `);return`**${r.layerItem.title}** has ${o.length} field(s):
99
99
 
100
- ${a}`},ya=async({layerTitle:e},t)=>{let r=Ge(t,"layersAndFieldsRegistry");return fa(r,e)},Ss=y(ya,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:s.object({layerTitle:s.string().describe("The title or partial title of the layer to list fields for.")})}),xs=b.Root({...L(),intent:b({reducer:(e,t)=>t}),arcgisKnowledgeMessages:b({reducer:D,default:()=>[]}),arcgisKnowledgeToolResult:b({reducer:(e,t)=>t,default:()=>null})});function be(e){let t=e.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!t||t?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function A(e){return!!e?.map&&!("activeLinkChartLayer"in e.map)}async function te(e){!e||A(e)||!e.map?.diagramNodesExtent||await e.goTo(e.map.diagramNodesExtent)}function V(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in t))throw new Error("View context missing");let r=t.view;return r.map&&!("activeLinkChartLayer"in r.map)&&be(r),{view:r}}function Es(e){let t=e?.configurable?.context;if(We(e)==="knowledgeGraph")return"knowledgeGraph";let r=t.view;return A(r)?(be(r),"map"):"linkChart"}async function Q(e){let t=e?.configurable?.context;if(We(e)==="knowledgeGraph")return t;{let r=t.view.map;if(r&&"activeLinkChartLayer"in r){let o=r.knowledgeGraph?.url;if(!o)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Re(o)}}else{be(t.view);let o=(t.view.map?.allLayers.find(a=>a.type==="knowledge-graph")).url;if(!o)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await Re(o)}}}}function We(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in t&&"view"in t)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in t)return"knowledgeGraph";if("view"in t)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var ce=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ue.fromDataModel(t)}},ue=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let o of t.entityTypes)r.entityTypes.push(G.fromEntityType(o));for(let o of t.relationshipTypes)r.relationshipTypes.push(de.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:ga(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}static getDataModelTypesSummary(t){let r=t.entityTypes.map(a=>a.name).join(", "),o=t.relationshipTypes.map(a=>a.name).join(", ");return`Entity Types: ${r}.
100
+ ${a}`},ya=async({layerTitle:e},t)=>{let r=Ge(t,"layersAndFieldsRegistry");return fa(r,e)},Ss=y(ya,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:s.object({layerTitle:s.string().describe("The title or partial title of the layer to list fields for.")})}),xs=b.Root({...L(),intent:b({reducer:(e,t)=>t}),arcgisKnowledgeMessages:b({reducer:D,default:()=>[]}),arcgisKnowledgeToolResult:b({reducer:(e,t)=>t,default:()=>null})});function be(e){let t=e.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!t||t?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function A(e){return!!e?.map&&!("activeLinkChartLayer"in e.map)}async function te(e){!e||A(e)||!e.map?.diagramNodesExtent||await e.goTo(e.map.diagramNodesExtent)}function V(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in t))throw new Error("View context missing");let r=t.view;return r.map&&!("activeLinkChartLayer"in r.map)&&be(r),{view:r}}function Es(e){let t=e?.configurable?.context;if(We(e)==="knowledgeGraph")return"knowledgeGraph";let r=t.view;return A(r)?(be(r),"map"):"linkChart"}async function Q(e){let t=e?.configurable?.context;if(We(e)==="knowledgeGraph")return t;{let r=t.view.map;if(r&&"activeLinkChartLayer"in r){let o=r.knowledgeGraph?.url;if(!o)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Ce(o)}}else{be(t.view);let o=(t.view.map?.allLayers.find(a=>a.type==="knowledge-graph")).url;if(!o)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await Ce(o)}}}}function We(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in t&&"view"in t)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in t)return"knowledgeGraph";if("view"in t)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var ce=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ue.fromDataModel(t)}},ue=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let o of t.entityTypes)r.entityTypes.push(G.fromEntityType(o));for(let o of t.relationshipTypes)r.relationshipTypes.push(de.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:ga(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}static getDataModelTypesSummary(t){let r=t.entityTypes.map(a=>a.name).join(", "),o=t.relationshipTypes.map(a=>a.name).join(", ");return`Entity Types: ${r}.
101
101
  Relationship Types: ${o}.`}},G=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(t){let r=new e;r.name=t.name,r.alias=t.alias?t.alias:void 0,r.role=wa(t.role);for(let o of t.properties){let a={name:o.name,alias:o.alias?o.alias:void 0,fieldType:o.fieldType,role:ba(o.role),geometryDef:o.fieldType==="esriFieldTypeGeometry"?{geometryType:o.geometryType??"esriGeometryAny",hasM:o.hasM?o.hasM:void 0,hasZ:o.hasZ?o.hasZ:void 0}:void 0};r.properties.push(a)}return r}},de=class extends G{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=G.fromEntityType(t);r.observedEndPoints=[];for(let o of t.endPoints)r.observedEndPoints.push({originEntityType:o.originEntityType,destinationEntityType:o.destinationEntityType});return r}},ga=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},wa=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function ba(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"}}function re(e){return e?.signal}async function va(e,t){let r=await Z("arcgis_knowledge_cypher_query_prompt");return t?`${e} ${r}
102
102
 
103
103
  Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
@@ -105,15 +105,15 @@ Your previous attempt to generate a cypher query failed. See the details below a
105
105
  Attempt Number: ${t.attemptCount}
106
106
  Execution Error: ${t.executionError}
107
107
  Failed Query:
108
- ${t.failedGraphQuery}`:`${e} ${r}`}async function Ta(e,t,r,o){let{graphQuery:a,explanation:n}=await ve(e,t,r,o);return{graphQuery:a,explanation:n}}async function ve(e,t,r,o,a){let n={message:await va(e,a),context:new ce(t)},l=re(o);await S({text:"Attempting to generate a cypher query from your prompt..."},o);let i=await Ae(`${r}/chat`,{method:"post",body:JSON.stringify(n),headers:{"Content-Type":"application/json",token:Me.findCredential(F.getDefault().url)?.token??""},signal:l});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,c=Date.now(),d=i.data.sequenceNumber,m="",p="",w=1;for(;!u;){await new Promise(h=>setTimeout(h,1e3)),await S({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,w)}`},o),w=w%3+1;let f=await Ae(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:Me.findCredential(F.getDefault().url)?.token??""},signal:l});if(f.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${f.httpStatus}`,{cause:f.data});if(f.data.context?.kind){if(f.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${f.data.message}`,{cause:f.data});m=f.data.context.graphQuery,p=f.data.message||"",u=!0}else if(!f.data.hasMore)u=!0;else if(Date.now()-c>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=f.data.sequenceNumber}return{graphQuery:m,explanation:p}}function Sa(e,t){C(e,r=>{t.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function C(e,t){if(!(!e||typeof e!="object")){if(Ea(e))for(let r of e.path)C(r,t);else if(xa(e))t(e);else if(Array.isArray(e))for(let r of e)C(r,t);else if(Ia(e))for(let r of Object.values(e.properties??{}))C(r,t)}}function xa(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Ea(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Ia(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function Na(e,t){let r=[],o=[],a=[[t.dataModel.entityTypes,r],[t.dataModel.relationshipTypes,o]];for(let[n,l]of a)for(let i of n){let u=e.getMemberIdsByType(i.name);l.push(...u)}return{entityIds:r,relationshipIds:o}}function ka(e,t){let r={entityIds:new Array,relationshipIds:new Array},o=[],a=e?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!a)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:o};let n=[[t.dataModel.entityTypes,r.entityIds],[t.dataModel.relationshipTypes,r.relationshipIds]],l=!0;for(let[i,u]of n)for(let c of i){let d=a.namedTypeDefinitions.get(c.name);if(!d){l=!1,o.push(c.name);continue}if(!d.useAllData){l=!1,o.push(c.name);for(let[m]of d.members||[])u.push(m)}}return{allNamedTypesFullyDynamic:l,bindParameters:r,nonDynamicTypes:o}}var R=3;function He(e,t=100){let r={};for(let o of Object.entries(e.properties??{})){let[a,n]=o;typeof n=="string"&&n.length>t?r[a]=`${n.slice(0,t)}... (truncated, original length: ${n.length})`:r[a]=n}return e.properties=r,e}function _(e){return typeof e!="object"||e===null?String(e):"details"in e&&typeof e.details=="object"&&e.details!==null&&"errorMessage"in e.details&&typeof e.details.errorMessage=="string"?e.details.errorMessage:"message"in e&&typeof e.message=="string"?e.message:String(e)}var $a=async({kg:e,queryParams:t,targetStructure:r,targetStructureReducer:o,requestOptions:a,queryRowLimit:n,queryTimeoutMs:l})=>{let i=null,u=r,c=new AbortController,d=a?.signal,m=()=>{c.abort(d?.reason)};d&&(d.aborted?c.abort(d.reason):d.addEventListener("abort",m,{once:!0}));try{let p=await _t(e,t,a);i=p.resultHeader;let w=p.resultRowsStream.getReader(),f=0,h=Date.now(),v=!1;for(;;){let{done:g,value:T}=await w.read();if(g)break;if(!v&&l&&Date.now()-h>l)return c.abort(),{type:"timeout"};for(let E of T){if(f++,n&&f>n)return c.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=o(u,E)}}}catch(p){return c.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:_(p),error:p}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function Je({prompt:e,bindParameters:t,kg:r,graphQueryServiceUrl:o,targetStructure:a,targetStructureReducer:n,requestOptions:l,queryRowLimit:i,queryTimeoutMs:u,config:c}){let d;for(let m=1;m<=R;m++){let p;try{p=await ve(e,r.dataModel,o,c,d)}catch(v){return{type:"generation-error",errorMessage:_(v),error:v}}await S({text:`Attempting to execute query: ${p.graphQuery.substring(0,500)}${p.graphQuery.length>500?"...":""}`},c);let w=await Fa(p.graphQuery,t),f=await $a({kg:r,queryParams:new Pe({openCypherQuery:p.graphQuery,bindParameters:w}),targetStructure:a,targetStructureReducer:n,requestOptions:l,queryRowLimit:i,queryTimeoutMs:u}),h=f.type==="aborted"?"Query execution was aborted.":f.type==="timeout"?"Query execution timed out.":f.type==="error"?`Query failed with error: ${f.errorMessage}`:"";if(f.type==="success")return{type:"success",graphQuery:p.graphQuery,explanation:p.explanation,rowLimitReached:f.rowLimitReached,resultHeader:f.resultHeader,processedResult:f.processedResult};if(f.type==="aborted")return{type:"aborted",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation};if(m>=R)return f.type==="timeout"?{type:"timeout",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation}:{type:"execution-error",errorMessage:h,error:f.error,graphQuery:p.graphQuery,explanation:p.explanation};d={failedGraphQuery:p.graphQuery,executionError:h,attemptCount:m},await S({text:`Attempt ${m} failed with error: ${h}. Retrying...`},c)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${R} attempts.`)}var Fa=async(e,t)=>{if(!t)return{};let{bindParameters:r,parseErrors:o}=await Dt(e);if(o)return t;let a={};for(let n of r)n in t&&(a[n]=t[n]);return a},Ma=async({kg:e,searchQuery:t,typeCategoryFilter:r,namedTypesFilter:o,searchResultLimit:a,requestOptions:n})=>{let l=[],i=[r];r==="both"&&!e.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=a??1/0;try{for(let c of i){let d=u-l.length;if(d<=0)break;let m=(await zt(e,new jt({searchQuery:t,typeCategoryFilter:c,namedTypesFilter:o??void 0,num:d}),n)).resultRowsStream.getReader(),p=!1;for(;!p;){let{done:w,value:f}=await m.read();if(w){p=!0;break}for(let h of f)for(let v of h)l.push(v)}}}catch(c){let d=_(c);return n?.signal?.aborted?{type:"aborted",errorMessage:d,error:c}:{type:"error",errorMessage:d,error:c}}return{type:"success",results:l}},Ze="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Ye({prompt:e,view:t,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:o=!1}){let a=[e];if(o&&a.push(Ze),!A(t)&&t.map){let d=await Z("arcgis_knowledge_current_lc_context"),m=Na(t.map,r);return a.push(d),{enhancedPrompt:a.join(`
108
+ ${t.failedGraphQuery}`:`${e} ${r}`}async function Ta(e,t,r,o){let{graphQuery:a,explanation:n}=await ve(e,t,r,o);return{graphQuery:a,explanation:n}}async function ve(e,t,r,o,a){let n={message:await va(e,a),context:new ce(t)},l=re(o);await S({text:"Attempting to generate a cypher query from your prompt..."},o);let i=await Ae(`${r}/chat`,{method:"post",body:JSON.stringify(n),headers:{"Content-Type":"application/json",token:Me.findCredential(F.getDefault().url)?.token??""},signal:l});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,c=Date.now(),d=i.data.sequenceNumber,m="",p="",w=1;for(;!u;){await new Promise(h=>setTimeout(h,1e3)),await S({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,w)}`},o),w=w%3+1;let f=await Ae(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:Me.findCredential(F.getDefault().url)?.token??""},signal:l});if(f.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${f.httpStatus}`,{cause:f.data});if(f.data.context?.kind){if(f.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${f.data.message}`,{cause:f.data});m=f.data.context.graphQuery,p=f.data.message||"",u=!0}else if(!f.data.hasMore)u=!0;else if(Date.now()-c>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=f.data.sequenceNumber}return{graphQuery:m,explanation:p}}function Sa(e,t){q(e,r=>{t.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function q(e,t){if(!(!e||typeof e!="object")){if(Ea(e))for(let r of e.path)q(r,t);else if(xa(e))t(e);else if(Array.isArray(e))for(let r of e)q(r,t);else if(Ia(e))for(let r of Object.values(e.properties??{}))q(r,t)}}function xa(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Ea(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Ia(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function Na(e,t){let r=[],o=[],a=[[t.dataModel.entityTypes,r],[t.dataModel.relationshipTypes,o]];for(let[n,l]of a)for(let i of n){let u=e.getMemberIdsByType(i.name);l.push(...u)}return{entityIds:r,relationshipIds:o}}function ka(e,t){let r={entityIds:new Array,relationshipIds:new Array},o=[],a=e?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!a)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:o};let n=[[t.dataModel.entityTypes,r.entityIds],[t.dataModel.relationshipTypes,r.relationshipIds]],l=!0;for(let[i,u]of n)for(let c of i){let d=a.namedTypeDefinitions.get(c.name);if(!d){l=!1,o.push(c.name);continue}if(!d.useAllData){l=!1,o.push(c.name);for(let[m]of d.members||[])u.push(m)}}return{allNamedTypesFullyDynamic:l,bindParameters:r,nonDynamicTypes:o}}var C=3;function He(e,t=100){let r={};for(let o of Object.entries(e.properties??{})){let[a,n]=o;typeof n=="string"&&n.length>t?r[a]=`${n.slice(0,t)}... (truncated, original length: ${n.length})`:r[a]=n}return e.properties=r,e}function _(e){return typeof e!="object"||e===null?String(e):"details"in e&&typeof e.details=="object"&&e.details!==null&&"errorMessage"in e.details&&typeof e.details.errorMessage=="string"?e.details.errorMessage:"message"in e&&typeof e.message=="string"?e.message:String(e)}var $a=async({kg:e,queryParams:t,targetStructure:r,targetStructureReducer:o,requestOptions:a,queryRowLimit:n,queryTimeoutMs:l})=>{let i=null,u=r,c=new AbortController,d=a?.signal,m=()=>{c.abort(d?.reason)};d&&(d.aborted?c.abort(d.reason):d.addEventListener("abort",m,{once:!0}));try{let p=await _t(e,t,a);i=p.resultHeader;let w=p.resultRowsStream.getReader(),f=0,h=Date.now(),v=!1;for(;;){let{done:g,value:T}=await w.read();if(g)break;if(!v&&l&&Date.now()-h>l)return c.abort(),{type:"timeout"};for(let E of T){if(f++,n&&f>n)return c.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=o(u,E)}}}catch(p){return c.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:_(p),error:p}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function Je({prompt:e,bindParameters:t,kg:r,graphQueryServiceUrl:o,targetStructure:a,targetStructureReducer:n,requestOptions:l,queryRowLimit:i,queryTimeoutMs:u,config:c}){let d;for(let m=1;m<=C;m++){let p;try{p=await ve(e,r.dataModel,o,c,d)}catch(v){return{type:"generation-error",errorMessage:_(v),error:v}}await S({text:`Attempting to execute query: ${p.graphQuery.substring(0,500)}${p.graphQuery.length>500?"...":""}`},c);let w=await Fa(p.graphQuery,t),f=await $a({kg:r,queryParams:new Pe({openCypherQuery:p.graphQuery,bindParameters:w}),targetStructure:a,targetStructureReducer:n,requestOptions:l,queryRowLimit:i,queryTimeoutMs:u}),h=f.type==="aborted"?"Query execution was aborted.":f.type==="timeout"?"Query execution timed out.":f.type==="error"?`Query failed with error: ${f.errorMessage}`:"";if(f.type==="success")return{type:"success",graphQuery:p.graphQuery,explanation:p.explanation,rowLimitReached:f.rowLimitReached,resultHeader:f.resultHeader,processedResult:f.processedResult};if(f.type==="aborted")return{type:"aborted",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation};if(m>=C)return f.type==="timeout"?{type:"timeout",errorMessage:h,graphQuery:p.graphQuery,explanation:p.explanation}:{type:"execution-error",errorMessage:h,error:f.error,graphQuery:p.graphQuery,explanation:p.explanation};d={failedGraphQuery:p.graphQuery,executionError:h,attemptCount:m},await S({text:`Attempt ${m} failed with error: ${h}. Retrying...`},c)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${C} attempts.`)}var Fa=async(e,t)=>{if(!t)return{};let{bindParameters:r,parseErrors:o}=await Dt(e);if(o)return t;let a={};for(let n of r)n in t&&(a[n]=t[n]);return a},Ma=async({kg:e,searchQuery:t,typeCategoryFilter:r,namedTypesFilter:o,searchResultLimit:a,requestOptions:n})=>{let l=[],i=[r];r==="both"&&!e.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=a??1/0;try{for(let c of i){let d=u-l.length;if(d<=0)break;let m=(await zt(e,new jt({searchQuery:t,typeCategoryFilter:c,namedTypesFilter:o??void 0,num:d}),n)).resultRowsStream.getReader(),p=!1;for(;!p;){let{done:w,value:f}=await m.read();if(w){p=!0;break}for(let h of f)for(let v of h)l.push(v)}}}catch(c){let d=_(c);return n?.signal?.aborted?{type:"aborted",errorMessage:d,error:c}:{type:"error",errorMessage:d,error:c}}return{type:"success",results:l}},Ze="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Ye({prompt:e,view:t,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:o=!1}){let a=[e];if(o&&a.push(Ze),!A(t)&&t.map){let d=await Z("arcgis_knowledge_current_lc_context"),m=Na(t.map,r);return a.push(d),{enhancedPrompt:a.join(`
109
109
 
110
110
  `),bindParameters:m,allNamedTypesFullyDynamic:!1}}let n=t.map,{allNamedTypesFullyDynamic:l,bindParameters:i,nonDynamicTypes:u}=ka(n,r);if(l)return{enhancedPrompt:a.join(`
111
111
 
112
112
  `),bindParameters:i,allNamedTypesFullyDynamic:!0};let c=(await Z("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return a.push(c),{enhancedPrompt:a.join(`
113
113
 
114
- `),bindParameters:i,allNamedTypesFullyDynamic:l}}async function Aa(e,t,r,o,a,n){let{view:l}=a,i=await Je({prompt:e,bindParameters:t,kg:r,graphQueryServiceUrl:o,targetStructure:new Map,targetStructureReducer:(p,w)=>{for(let f of w)Sa(f,p);return p},requestOptions:{signal:re(n),timeout:n?.timeout},config:n});if(i.type!=="success"){let p=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${p}`)}let{graphQuery:u,explanation:c,processedResult:d}=i,m=Array.from(d.values());return await S({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},n),!A(l)&&l?.map?(await l.map.addRecords(m),await te(l),{generatedQuery:u,explanation:c,addedIdTypePairs:m}):(await l?.map?.allLayers.find(p=>p.type==="knowledge-graph")?.addRecords(m),{generatedQuery:u,explanation:c,addedIdTypePairs:m})}var H="addRecords",qa=s.object({prompt:s.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),Ca=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t),o=V(t),{view:a}=o,n=F.getDefault().helperServices,{enhancedPrompt:l,bindParameters:i,allNamedTypesFullyDynamic:u}=await Ye({prompt:e,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:H,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:c,explanation:d,addedIdTypePairs:m}=await Aa(l,i,r,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,o,t);return{toolName:H,status:"success",summary:`Records added successfully. Cypher Query used: ${c}
114
+ `),bindParameters:i,allNamedTypesFullyDynamic:l}}async function Aa(e,t,r,o,a,n){let{view:l}=a,i=await Je({prompt:e,bindParameters:t,kg:r,graphQueryServiceUrl:o,targetStructure:new Map,targetStructureReducer:(p,w)=>{for(let f of w)Sa(f,p);return p},requestOptions:{signal:re(n),timeout:n?.timeout},config:n});if(i.type!=="success"){let p=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${p}`)}let{graphQuery:u,explanation:c,processedResult:d}=i,m=Array.from(d.values());return await S({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},n),!A(l)&&l?.map?(await l.map.addRecords(m),await te(l),{generatedQuery:u,explanation:c,addedIdTypePairs:m}):(await l?.map?.allLayers.find(p=>p.type==="knowledge-graph")?.addRecords(m),{generatedQuery:u,explanation:c,addedIdTypePairs:m})}var H="addRecords",Ra=s.object({prompt:s.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),qa=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t),o=V(t),{view:a}=o,n=F.getDefault().helperServices,{enhancedPrompt:l,bindParameters:i,allNamedTypesFullyDynamic:u}=await Ye({prompt:e,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:H,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:c,explanation:d,addedIdTypePairs:m}=await Aa(l,i,r,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,o,t);return{toolName:H,status:"success",summary:`Records added successfully. Cypher Query used: ${c}
115
115
 
116
- Number of records added: ${m.length}`,details:{generatedQuery:c,explanation:d,addedIdTypePairs:m}}}catch(c){let d=_(c);return{toolName:H,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:c}}},Is=y(Ca,{name:H,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. "add to new link chart" is not a valid prompt for this tool.
116
+ Number of records added: ${m.length}`,details:{generatedQuery:c,explanation:d,addedIdTypePairs:m}}}catch(c){let d=_(c);return{toolName:H,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:c}}},Is=y(qa,{name:H,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. "add to new link chart" is not a valid prompt for this tool.
117
117
 
118
118
  example prompts:
119
119
  - "add all suppliers and the parts they produce to the link chart"
@@ -123,15 +123,15 @@ Number of records added: ${m.length}`,details:{generatedQuery:c,explanation:d,ad
123
123
  - "expand company x through all the buildings it owns"
124
124
  - "connect company x and company y"
125
125
  - "connect all buildings on the link chart"
126
- `,schema:qa});async function Ra(e,t){return await t.map?.applyLayout(e),await te(t),{appliedLayout:e}}var pe="applyLayout",_a=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")}),za=async({layout:e},t)=>{let{view:r}=V(t);if(A(r))return{toolName:pe,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:o}=await Ra(e,r);return{toolName:pe,status:"success",summary:`Successfully applied layout: ${o}.`,details:{appliedLayout:o}}}},Ns=y(za,{name:pe,description:"Apply a diagram layout to the link chart",schema:_a});async function ja(e,t){return t.map?.changeNonspatialDataDisplay(e),await te(t),{appliedNonspatialDataDisplayMode:e}}var me="changeNonspatialVisibility",Da=s.object({setting:s.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),La=async({setting:e},t)=>{let{view:r}=V(t);if(A(r))return{toolName:me,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:o}=await ja(e,r);return{toolName:me,status:"success",summary:`Successfully applied nonspatial visibility setting: ${o}.`,details:{appliedNonspatialDataDisplayMode:o}}}},ks=y(La,{name:me,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Da});async function Oa(e,t,r,o,a){let n,l="";for(let i=1;i<=R;i++){let{graphQuery:u,explanation:c}=await ve(e,t.dataModel,r,a,n);try{await S({text:`Attempting to create link chart from derived query: ${u}`},a);let d=await Rt.fromCypherQuery(t,new Pe({openCypherQuery:u}));await S({text:"Link chart created successfully, loading..."},a),await d.load();let m=o.map;return o.map=d,await o.when(),await je.whenOnce(()=>!o.updating),d.entityCount===0&&d.relationshipCount===0?(o.map===d&&(o.map=m),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
126
+ `,schema:Ra});async function Ca(e,t){return await t.map?.applyLayout(e),await te(t),{appliedLayout:e}}var pe="applyLayout",_a=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")}),za=async({layout:e},t)=>{let{view:r}=V(t);if(A(r))return{toolName:pe,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:o}=await Ca(e,r);return{toolName:pe,status:"success",summary:`Successfully applied layout: ${o}.`,details:{appliedLayout:o}}}},Ns=y(za,{name:pe,description:"Apply a diagram layout to the link chart",schema:_a});async function ja(e,t){return t.map?.changeNonspatialDataDisplay(e),await te(t),{appliedNonspatialDataDisplayMode:e}}var me="changeNonspatialVisibility",Da=s.object({setting:s.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),La=async({setting:e},t)=>{let{view:r}=V(t);if(A(r))return{toolName:me,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:o}=await ja(e,r);return{toolName:me,status:"success",summary:`Successfully applied nonspatial visibility setting: ${o}.`,details:{appliedNonspatialDataDisplayMode:o}}}},ks=y(La,{name:me,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Da});async function Oa(e,t,r,o,a){let n,l="";for(let i=1;i<=C;i++){let{graphQuery:u,explanation:c}=await ve(e,t.dataModel,r,a,n);try{await S({text:`Attempting to create link chart from derived query: ${u}`},a);let d=await Ct.fromCypherQuery(t,new Pe({openCypherQuery:u}));await S({text:"Link chart created successfully, loading..."},a),await d.load();let m=o.map;return o.map=d,await o.when(),await je.whenOnce(()=>!o.updating),d.entityCount===0&&d.relationshipCount===0?(o.map===d&&(o.map=m),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
127
127
  ${u}
128
128
 
129
- Explanation: ${c}`}):(await te(o),{type:"success",graphQuery:u,explanation:c})}catch(d){let m=_(d);if(i>=R){l=m;break}n={failedGraphQuery:u,executionError:m,attemptCount:i},await S({text:`Attempt ${i} to create link chart failed with error: ${m}. Retrying ...`},a)}}return{type:"error",errorMessage:`Failed to create link chart after ${R} attempts. Last error: ${l}`}}var J="createLinkChart",Pa=s.object({prompt:s.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),Ga=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t),{view:o}=V(t);if(A(o))return{toolName:J,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let a=F.getDefault().helperServices,n=await Oa(`${e}
129
+ Explanation: ${c}`}):(await te(o),{type:"success",graphQuery:u,explanation:c})}catch(d){let m=_(d);if(i>=C){l=m;break}n={failedGraphQuery:u,executionError:m,attemptCount:i},await S({text:`Attempt ${i} to create link chart failed with error: ${m}. Retrying ...`},a)}}return{type:"error",errorMessage:`Failed to create link chart after ${C} attempts. Last error: ${l}`}}var J="createLinkChart",Pa=s.object({prompt:s.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),Ga=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t),{view:o}=V(t);if(A(o))return{toolName:J,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let a=F.getDefault().helperServices,n=await Oa(`${e}
130
130
 
131
131
  ${Ze}`,r,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,o,t);if(n.type==="error")return{toolName:J,status:"error",errorMessage:n.errorMessage,error:new Error};let{graphQuery:l,explanation:i}=n;return{toolName:J,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
132
132
  ${l}
133
133
 
134
- Explanation: ${i}`,details:{generatedQuery:l,explanation:i}}}},$s=y(Ga,{name:J,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 using language like 'create new link chart' or 'add to new link chart'.",schema:Pa}),he="queryGraphData",Va=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),Qa=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t),o=F.getDefault().helperServices,a=e,n=null,l=null;try{({view:l}=V(t))}catch{}l&&({enhancedPrompt:a,bindParameters:n}=await Ye({prompt:e,view:l,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await Je({prompt:a,bindParameters:n,kg:r,graphQueryServiceUrl:`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(h,v)=>(h.push(v),h),requestOptions:{signal:re(t),timeout:t?.timeout},config:t});if(i.type!=="success"){let h=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:he,status:"error",errorMessage:`Failed to query the knowledge graph. ${h}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:c,processedResult:d,resultHeader:m}=i,p=m.headerKeys;for(let h of d)for(let v of h)C(v,g=>He(g));let w=50,f=d.slice(0,w).map(h=>JSON.stringify(h));return{toolName:he,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
134
+ Explanation: ${i}`,details:{generatedQuery:l,explanation:i}}}},$s=y(Ga,{name:J,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 using language like 'create new link chart' or 'add to new link chart'.",schema:Pa}),he="queryGraphData",Va=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),Qa=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t),o=F.getDefault().helperServices,a=e,n=null,l=null;try{({view:l}=V(t))}catch{}l&&({enhancedPrompt:a,bindParameters:n}=await Ye({prompt:e,view:l,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await Je({prompt:a,bindParameters:n,kg:r,graphQueryServiceUrl:`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(h,v)=>(h.push(v),h),requestOptions:{signal:re(t),timeout:t?.timeout},config:t});if(i.type!=="success"){let h=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:he,status:"error",errorMessage:`Failed to query the knowledge graph. ${h}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:c,processedResult:d,resultHeader:m}=i,p=m.headerKeys;for(let h of d)for(let v of h)q(v,g=>He(g));let w=50,f=d.slice(0,w).map(h=>JSON.stringify(h));return{toolName:he,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
135
135
 
136
136
  \`\`\`cypher
137
137
  ${u}
@@ -157,7 +157,7 @@ ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
157
157
  ${a.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
158
158
  `)}`;return`${n}
159
159
 
160
- ${l}`};async function Wa(e,t,r){let o=await Z("arcgis_knowledge_lucene_generation_prompt"),a={inquiry:e,dataModelForSearch:Ka(t)},n=s.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),l=s.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=s.array(s.enum(t.dataModel.entityTypes.map(c=>c.name).concat(t.dataModel.relationshipTypes.map(c=>c.name)))).min(1),u=s.object({query:s.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:n,resultLimit:l});return await Ie({promptText:o,inputVariables:a,schema:u,config:r})}var ye="searchGraphData",Ha=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),Ja=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t);await S({text:"Generating search query for the user inquiry"},t);let o=await Wa(e,r,t);await S({text:"Executing graph search with generated search query"},t);let a=await Ma({kg:r,searchQuery:o.query,typeCategoryFilter:o.typeCategoryFilter,namedTypesFilter:o.typeFilters,searchResultLimit:o.resultLimit,requestOptions:{signal:re(t),timeout:t?.timeout}});if(a.type!=="success")return{toolName:ye,status:"error",errorMessage:a.errorMessage,error:"error"in a?a.error:null};for(let i of a.results)C(i,u=>He(u));let n=10,l=a.results.slice(0,n);return{toolName:ye,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
160
+ ${l}`};async function Wa(e,t,r){let o=await Z("arcgis_knowledge_lucene_generation_prompt"),a={inquiry:e,dataModelForSearch:Ka(t)},n=s.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),l=s.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=s.array(s.enum(t.dataModel.entityTypes.map(c=>c.name).concat(t.dataModel.relationshipTypes.map(c=>c.name)))).min(1),u=s.object({query:s.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:n,resultLimit:l});return await Ie({promptText:o,inputVariables:a,schema:u,config:r})}var ye="searchGraphData",Ha=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),Ja=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t);await S({text:"Generating search query for the user inquiry"},t);let o=await Wa(e,r,t);await S({text:"Executing graph search with generated search query"},t);let a=await Ma({kg:r,searchQuery:o.query,typeCategoryFilter:o.typeCategoryFilter,namedTypesFilter:o.typeFilters,searchResultLimit:o.resultLimit,requestOptions:{signal:re(t),timeout:t?.timeout}});if(a.type!=="success")return{toolName:ye,status:"error",errorMessage:a.errorMessage,error:"error"in a?a.error:null};for(let i of a.results)q(i,u=>He(u));let n=10,l=a.results.slice(0,n);return{toolName:ye,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
161
161
  Query: ${o.query}
162
162
  Type Category Filter: ${o.typeCategoryFilter}
163
163
  Named Type Filters: ${o.typeFilters?o.typeFilters.join(", "):"None"}
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import d from"./4NAXFKT2.js";import c from"./HOCTVCHH.js";import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as s,c as e}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-layer-styling-agent"),this.#i=e(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-layer-styling-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c,d)
2
+ import d from"./S27EJSLC.js";import c from"./HOCTVCHH.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as s,c as e}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-layer-styling-agent"),this.#i=e(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-layer-styling-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c,d)
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as p}from"./4RZPOYZ7.js";import{a as u,b as i,ta as c}from"./CJIV4KJZ.js";export default $arcgis.t(([,,,,,,{r:g},{I:d,J:E,a:h,m:f,n:y,o:m,p:x}])=>{var S=[E],_=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:a},s)=>{let o=Array.from(a.values()).map(n=>n.name).slice(0,10).join(", "),l=a.size>10?` (and ${a.size-10} more)`:"";return`${s+1}. "${r.title}". Description: ${r.description}
2
+ import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as p}from"./4RZPOYZ7.js";import{a as u,b as i,ta as c}from"./CJIV4KJZ.js";export default $arcgis.t(([,,,,,,{r:g},{I:d,J:E,a:h,m:f,n:y,o:m,p:x}])=>{var S=[E],_=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:a},s)=>{let o=Array.from(a.values()).map(n=>n.name).slice(0,10).join(", "),l=a.size>10?` (and ${a.size-10} more)`:"";return`${s+1}. "${r.title}". Description: ${r.description}
3
3
  Fields: ${o}${l}`}).join(`
4
4
 
5
5
  `);return`This map contains ${e.size} layer(s):
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as c,b as k}from"./4RZPOYZ7.js";import{a as w,b as d,j as f,ta as x}from"./CJIV4KJZ.js";import{Z as u}from"./IKEF7ZHH.js";export default $arcgis.t(([,,,,,,{p:_,r:b},{K:y,L:K,M:q,N:S,O:M,P:T,Q:E,R:C,S:G,T:N,U:R,a:v,m:m,n:h,p:A}])=>{var z=[T,E,N,C,M,R,G];async function $(e,a){let o=await m("arcgis_knowledge_tool_prompt"),s=K(a),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:s},r=await b({promptText:o,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:z,config:a}),i=(r.tool_calls?.length??0)>0,t=typeof r.text=="string"?r.text.trim():"",l=t.length>0,p=r.content.toString();return!i&&(s==="map"||s==="knowledgeGraph")?{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:s==="map"?"No tools were found for the current view and prompt. Maps do not support changing nonspatial visibility, layout changes, or generation from queries.":"No tools were found for the current prompt and knowledge graph service. A knowledge graph service only supports search and query.",status:"success"}:{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:i?p:t,status:i?e.status:l?"success":"failed",summary:p?h(p):"ArcGIS Knowledge Agent tool executed."}}var L={generateCypher:"generated-cypher-query",queryGraphData:"graph-query-result",searchGraphData:"graph-search-result",addRecords:"added-records",applyLayout:"applied-layout",changeNonspatialVisibility:"changed-nonspatial-visibility",createLinkChart:"created-link-chart"};function I(e){return!!e&&e.status==="success"&&!!L[e.toolName]}function D(e){return{type:L[e.toolName],data:e.details}}async function F(e,a){let o=new v(z,{handleToolErrors:!1});try{let s=await o.invoke({messages:e.arcgisKnowledgeMessages},a),n=[];for(let t of s.messages){let l;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{l=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}.
2
+ import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as c,b as k}from"./4RZPOYZ7.js";import{a as w,b as d,j as f,ta as x}from"./CJIV4KJZ.js";import{Z as u}from"./IKEF7ZHH.js";export default $arcgis.t(([,,,,,,{p:_,r:b},{K:y,L:K,M:q,N:S,O:M,P:T,Q:E,R:C,S:G,T:N,U:R,a:v,m:m,n:h,p:A}])=>{var z=[T,E,N,C,M,R,G];async function $(e,a){let o=await m("arcgis_knowledge_tool_prompt"),s=K(a),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:s},r=await b({promptText:o,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:z,config:a}),i=(r.tool_calls?.length??0)>0,t=typeof r.text=="string"?r.text.trim():"",l=t.length>0,p=r.content.toString();return!i&&(s==="map"||s==="knowledgeGraph")?{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:s==="map"?"No tools were found for the current view and prompt. Maps do not support changing nonspatial visibility, layout changes, or generation from queries.":"No tools were found for the current prompt and knowledge graph service. A knowledge graph service only supports search and query.",status:"success"}:{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:i?p:t,status:i?e.status:l?"success":"failed",summary:p?h(p):"ArcGIS Knowledge Agent tool executed."}}var L={generateCypher:"generated-cypher-query",queryGraphData:"graph-query-result",searchGraphData:"graph-search-result",addRecords:"added-records",applyLayout:"applied-layout",changeNonspatialVisibility:"changed-nonspatial-visibility",createLinkChart:"created-link-chart"};function I(e){return!!e&&e.status==="success"&&!!L[e.toolName]}function D(e){return{type:L[e.toolName],data:e.details}}async function F(e,a){let o=new v(z,{handleToolErrors:!1});try{let s=await o.invoke({messages:e.arcgisKnowledgeMessages},a),n=[];for(let t of s.messages){let l;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{l=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}.
3
3
 
4
4
  Original Content: ${t.content}`)}if(!l||typeof l!="object"||!("toolName"in l))throw new Error(`Parsed tool message content does not have expected structure. Parsed content: ${JSON.stringify(l)}`);n.push(l)}await c({text:`Finished executing ArcGIS Knowledge Agent tools: ${s.messages.filter(t=>t.name).map(t=>t.name).join(", ")}`},a);let r=n.filter(t=>typeof t!="string").map(t=>`- Called Tool: ${t.toolName}, Status: ${t.status}`),i=n[0];return i&&I(i)&&await k(D(i),a),{...e,outputMessage:r.join(`
5
5
  `),summary:r.length?h(r.join(`
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./O3CDY64C.js";import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{c as s,d as n}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as r,z as o}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,{fetchKnowledgeGraph:p},,,a])=>{var i=class extends r{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1,serviceUrl:3,context:0}}#e;#i;#t;#r;get serviceUrl(){return this.#i}set serviceUrl(t){this.#i=t}async getContext(){let t=this.context?{...this.context,knowledgeGraph:void 0,view:void 0}:{};if(this.#e)return{...t,view:this.#e};if(this.#t)try{let e=await this.#t;return{...t,knowledgeGraph:e}}catch(e){console.error("Failed to load knowledge graph via service URL:",e)}if(!this.context?.knowledgeGraph&&!this.context?.view)throw new Error("arcgis-assistant-knowledge-agent requires either a knowledgeGraph or view in context, and neither were provided");return this.context}willUpdate(t){t.has("serviceUrl")&&this.serviceUrl?this.#t=p(this.serviceUrl):this.#t=void 0}load(){this.#e=n(this)??void 0,this.#r=s(this)}disconnectedCallback(){this.#r?.unregister(this.agent.id),super.disconnectedCallback()}};o("arcgis-assistant-knowledge-agent",i);return i},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",a,b,c)
2
+ import c from"./HXOSLGWU.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{c as s,d as n}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as r,z as o}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,{fetchKnowledgeGraph:p},,,a])=>{var i=class extends r{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1,serviceUrl:3,context:0}}#e;#i;#t;#r;get serviceUrl(){return this.#i}set serviceUrl(t){this.#i=t}async getContext(){let t=this.context?{...this.context,knowledgeGraph:void 0,view:void 0}:{};if(this.#e)return{...t,view:this.#e};if(this.#t)try{let e=await this.#t;return{...t,knowledgeGraph:e}}catch(e){console.error("Failed to load knowledge graph via service URL:",e)}if(!this.context?.knowledgeGraph&&!this.context?.view)throw new Error("arcgis-assistant-knowledge-agent requires either a knowledgeGraph or view in context, and neither were provided");return this.context}willUpdate(t){t.has("serviceUrl")&&this.serviceUrl?this.#t=p(this.serviceUrl):this.#t=void 0}load(){this.#e=n(this)??void 0,this.#r=s(this)}disconnectedCallback(){this.#r?.unregister(this.agent.id),super.disconnectedCallback()}};o("arcgis-assistant-knowledge-agent",i);return i},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",a,b,c)
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./HOCTVCHH.js";import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as n}from"./4RZPOYZ7.js";import{a as I,b as S,ta as N}from"./CJIV4KJZ.js";import{Z as $}from"./IKEF7ZHH.js";export default $arcgis.t(([,,,,,,P,U,{p:k,r:T},{C:M,D:z,E:L,F:D,G:F,H:O,a:A,m:w,n:R,o:y,p:V},b])=>{var W=async(e,t)=>(await n({text:"Exiting Data Exploration agent"},t),e),B=async(e,t)=>{await n({text:"Requesting LLM for layer filter results"},t);let a=await w("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:d,userTimezoneOffset:o}=L(),s={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},i=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:s,tools:F}),r=[...e.dataExplorationMessages,i];if(!((i.tool_calls?.length??0)>0))return await n({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:r};let c=r,l=i.content.toString();return await b(i,t),{...e,dataExplorationMessages:c,outputMessage:l}},H=async(e,t)=>{await n({text:"Requesting LLM for layer query results"},t);let a=await w("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:d,userTimezoneOffset:o}=L(),s=e.agentExecutionContext.sharedState,i=s.lastNavigatedFeatures?.value,r=s.lastResolvedLocation?.value,c="none";if(i!=null)try{c=JSON.stringify(i)}catch{c="none"}let l="none";if(r!=null)try{l=JSON.stringify({address:r.address,location:r.location})}catch{l="none"}let g={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,lastNavigatedFeatures:c,lastResolvedLocation:l},m=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:g,tools:D}),h=(m.tool_calls?.length??0)>0,f=m.content.toString();return await b(m,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,m],...h?{}:{outputMessage:f},status:"success",summary:f&&!h?R(f):"Query planning completed."}},J=async(e,t)=>{try{await n({text:"Requesting LLM for summary on query results"},t);let a=await w("summarize_query_response_prompt"),d={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await k({promptText:a,modelTier:"fast",config:t,messages:e.dataExplorationMessages,inputVariables:d}),s=typeof o=="string"?o:o.content,i=new $(s);await n({text:`Received response from LLM: ${s}`},t);let r=s;return{...e,outputMessage:r,status:"success",summary:r?R(r):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,i]}}catch(a){throw await n({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${a instanceof Error?a.message:String(a)}`)}};async function K(e,t){if((e.queryResponse??[]).some(d=>{let o=d.details;return typeof o=="object"&&o!==null&&"error"in o}))return await n({text:"Skipping layer filter tool because query response contains an error."},t),{...e};let a=await new A(F,{handleToolErrors:!1}).invoke({messages:e.dataExplorationMessages},t);return await n({text:`Finished executing layer filter tool: ${a.messages.map(d=>d.content).join(", ")}`},t),{...e}}var X=10,Y=["string","small-integer","integer"],Z=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:d=!0}={})=>{let o=null,s=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(o=await P({layer:e,field:t.name}));let i=t.domain?.type==="coded-value"?t.domain:null;d&&(Y.includes(t.type)||i)&&(s=(await U({layer:e,field:t.name})).uniqueValueInfos.sort((r,c)=>c.count-r.count).slice(0,X),i&&(s=s.map(r=>({...r,value:i.getName(r.value)??r.value}))))}}catch(i){console.error(`Error fetching statistics for field ${t.name}:`,i)}return{summaryStatistics:o,uniqueValues:s}};function ee(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function te(e,t,a,d=!0){let o=[],s=[],i=[];for(let r of e){let c=function(p){let u=t.get(p)?.layerItem;return u?[u.name&&`Name: ${u.name}`,u.title&&`Title: ${u.title}`,u.description&&`Description: ${u.description}`].filter(Boolean).join(" | "):p},{layerId:l,results:g}=r,m=a.map?.allLayers.find(p=>p.id===l),h=t.get(l)?.fieldRegistry;if(!h)continue;let f=o.find(p=>p.layerId===l);f||(f={layerId:l,layerSummary:c(l),fieldInfos:[]},o.push(f));for(let p of g){let u=h.get(p.name);if(!u)continue;let x=u.statistics,v=d&&!x?.summaryStatistics,q=ee(u.type,u.domain?.type)&&!x?.uniqueValues,_=v||q;if(i.push({layerId:l,fieldName:u.name,didFetchStatistics:_}),_){let G=Z(m,u,{includeSummaryStatistics:v,includeUniqueValues:q}).then(C=>{let E={summaryStatistics:x?.summaryStatistics??null,uniqueValues:x?.uniqueValues??null};v&&(E.summaryStatistics=C.summaryStatistics),q&&(E.uniqueValues=C.uniqueValues),h.set(u.name,{...u,statistics:E}),u.statistics=E});s.push(G)}f.fieldInfos.push(u)}}return await Promise.all(s),{layerFieldInfo:o,didFetchStatistics:s.length>0,fieldStatisticsFetchStatus:i}}var j=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function ae(e,t){return j.test(e)||j.test(t)}var se=async(e,t)=>{try{await n({text:"Preparing field information for vector search results"},t);let a=y(t,"layersAndFieldsRegistry"),{mapView:d}=z(t),{assignedTask:o,userRequest:s}=e.agentExecutionContext,i=ae(o,s),{layerFieldInfo:r,didFetchStatistics:c,fieldStatisticsFetchStatus:l}=await te(e.vectorSearchFieldResults,a,d,i);c?await n({text:"Statistics fetched"},t):await n({text:"Statistics skipped"},t);for(let g of l)await n({text:` - ${g.fieldName} - stats ${g.didFetchStatistics?"fetched":"skipped"}`},t);return await n({text:"Field information prepared"},t),{...e,layerFieldInfo:r}}catch(a){throw await n({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${a instanceof Error?a.message:String(a)}`)}},Q=.7,re=10,ie=async(e,t)=>{try{await n({text:"Similarity search to find fields"},t);let a=y(t,"fieldSearch"),d=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),s=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Q,topResults:re,embeddingCache:o}),i=s.map(({layerId:c,results:l})=>{let g=l.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
2
+ import c from"./HOCTVCHH.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as n}from"./4RZPOYZ7.js";import{a as I,b as S,ta as N}from"./CJIV4KJZ.js";import{Z as $}from"./IKEF7ZHH.js";export default $arcgis.t(([,,,,,,P,U,{p:k,r:T},{C:M,D:z,E:L,F:D,G:F,H:O,a:A,m:w,n:R,o:y,p:V},b])=>{var W=async(e,t)=>(await n({text:"Exiting Data Exploration agent"},t),e),B=async(e,t)=>{await n({text:"Requesting LLM for layer filter results"},t);let a=await w("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:d,userTimezoneOffset:o}=L(),s={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},i=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:s,tools:F}),r=[...e.dataExplorationMessages,i];if(!((i.tool_calls?.length??0)>0))return await n({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:r};let c=r,l=i.content.toString();return await b(i,t),{...e,dataExplorationMessages:c,outputMessage:l}},H=async(e,t)=>{await n({text:"Requesting LLM for layer query results"},t);let a=await w("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:d,userTimezoneOffset:o}=L(),s=e.agentExecutionContext.sharedState,i=s.lastNavigatedFeatures?.value,r=s.lastResolvedLocation?.value,c="none";if(i!=null)try{c=JSON.stringify(i)}catch{c="none"}let l="none";if(r!=null)try{l=JSON.stringify({address:r.address,location:r.location})}catch{l="none"}let g={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,lastNavigatedFeatures:c,lastResolvedLocation:l},m=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:g,tools:D}),h=(m.tool_calls?.length??0)>0,f=m.content.toString();return await b(m,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,m],...h?{}:{outputMessage:f},status:"success",summary:f&&!h?R(f):"Query planning completed."}},J=async(e,t)=>{try{await n({text:"Requesting LLM for summary on query results"},t);let a=await w("summarize_query_response_prompt"),d={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await k({promptText:a,modelTier:"fast",config:t,messages:e.dataExplorationMessages,inputVariables:d}),s=typeof o=="string"?o:o.content,i=new $(s);await n({text:`Received response from LLM: ${s}`},t);let r=s;return{...e,outputMessage:r,status:"success",summary:r?R(r):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,i]}}catch(a){throw await n({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${a instanceof Error?a.message:String(a)}`)}};async function K(e,t){if((e.queryResponse??[]).some(d=>{let o=d.details;return typeof o=="object"&&o!==null&&"error"in o}))return await n({text:"Skipping layer filter tool because query response contains an error."},t),{...e};let a=await new A(F,{handleToolErrors:!1}).invoke({messages:e.dataExplorationMessages},t);return await n({text:`Finished executing layer filter tool: ${a.messages.map(d=>d.content).join(", ")}`},t),{...e}}var X=10,Y=["string","small-integer","integer"],Z=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:d=!0}={})=>{let o=null,s=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(o=await P({layer:e,field:t.name}));let i=t.domain?.type==="coded-value"?t.domain:null;d&&(Y.includes(t.type)||i)&&(s=(await U({layer:e,field:t.name})).uniqueValueInfos.sort((r,c)=>c.count-r.count).slice(0,X),i&&(s=s.map(r=>({...r,value:i.getName(r.value)??r.value}))))}}catch(i){console.error(`Error fetching statistics for field ${t.name}:`,i)}return{summaryStatistics:o,uniqueValues:s}};function ee(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function te(e,t,a,d=!0){let o=[],s=[],i=[];for(let r of e){let c=function(p){let u=t.get(p)?.layerItem;return u?[u.name&&`Name: ${u.name}`,u.title&&`Title: ${u.title}`,u.description&&`Description: ${u.description}`].filter(Boolean).join(" | "):p},{layerId:l,results:g}=r,m=a.map?.allLayers.find(p=>p.id===l),h=t.get(l)?.fieldRegistry;if(!h)continue;let f=o.find(p=>p.layerId===l);f||(f={layerId:l,layerSummary:c(l),fieldInfos:[]},o.push(f));for(let p of g){let u=h.get(p.name);if(!u)continue;let x=u.statistics,v=d&&!x?.summaryStatistics,q=ee(u.type,u.domain?.type)&&!x?.uniqueValues,_=v||q;if(i.push({layerId:l,fieldName:u.name,didFetchStatistics:_}),_){let G=Z(m,u,{includeSummaryStatistics:v,includeUniqueValues:q}).then(C=>{let E={summaryStatistics:x?.summaryStatistics??null,uniqueValues:x?.uniqueValues??null};v&&(E.summaryStatistics=C.summaryStatistics),q&&(E.uniqueValues=C.uniqueValues),h.set(u.name,{...u,statistics:E}),u.statistics=E});s.push(G)}f.fieldInfos.push(u)}}return await Promise.all(s),{layerFieldInfo:o,didFetchStatistics:s.length>0,fieldStatisticsFetchStatus:i}}var j=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function ae(e,t){return j.test(e)||j.test(t)}var se=async(e,t)=>{try{await n({text:"Preparing field information for vector search results"},t);let a=y(t,"layersAndFieldsRegistry"),{mapView:d}=z(t),{assignedTask:o,userRequest:s}=e.agentExecutionContext,i=ae(o,s),{layerFieldInfo:r,didFetchStatistics:c,fieldStatisticsFetchStatus:l}=await te(e.vectorSearchFieldResults,a,d,i);c?await n({text:"Statistics fetched"},t):await n({text:"Statistics skipped"},t);for(let g of l)await n({text:` - ${g.fieldName} - stats ${g.didFetchStatistics?"fetched":"skipped"}`},t);return await n({text:"Field information prepared"},t),{...e,layerFieldInfo:r}}catch(a){throw await n({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${a instanceof Error?a.message:String(a)}`)}},Q=.7,re=10,ie=async(e,t)=>{try{await n({text:"Similarity search to find fields"},t);let a=y(t,"fieldSearch"),d=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),s=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Q,topResults:re,embeddingCache:o}),i=s.map(({layerId:c,results:l})=>{let g=l.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
3
3
  `);return`${d.get(c)?.layerItem.name??c}:
4
4
  ${g}`}).join(`
5
5
  `),r;return s.length>0?r=`Vector search completed. Matching layers and fields with scores:
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./XVU5R3Z7.js";import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as s,c as o}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,a])=>{var t=class extends i{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-navigation-agent"),this.#i=o(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-navigation-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c)
2
+ import c from"./TSEQVE2H.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as s,c as o}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,a])=>{var t=class extends i{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-navigation-agent"),this.#i=o(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-navigation-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c)
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./HOCTVCHH.js";import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as i}from"./4RZPOYZ7.js";import{a as u,b as p,q as f,ta as S}from"./CJIV4KJZ.js";export default $arcgis.t(([,,,,,,{r:x},{A:_,B:h,a:w,m:E,o:y,p:I,q:L,r:v,s:F,t:$,u:C,v:N,w:R,x:T,y:b,z:A},q])=>{var V=.7,z=10,D=async(a,t)=>{try{await i({text:"Similarity search to find fields"},t);let e=y(t,"fieldSearch"),n=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),r=await e.searchFields({text:a.agentExecutionContext.assignedTask,layerIds:a.vectorSearchLayerIds,minScore:V,topResults:z,embeddingCache:o}),m=r.map(({layerId:d,results:c})=>{let g=c.map(s=>` - ${s.name} (${s.score.toFixed(2)})`).join(`
2
+ import c from"./HOCTVCHH.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as i}from"./4RZPOYZ7.js";import{a as u,b as p,q as f,ta as S}from"./CJIV4KJZ.js";export default $arcgis.t(([,,,,,,{r:x},{A:_,B:h,a:w,m:E,o:y,p:I,q:L,r:v,s:F,t:$,u:C,v:N,w:R,x:T,y:b,z:A},q])=>{var V=.7,z=10,D=async(a,t)=>{try{await i({text:"Similarity search to find fields"},t);let e=y(t,"fieldSearch"),n=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),r=await e.searchFields({text:a.agentExecutionContext.assignedTask,layerIds:a.vectorSearchLayerIds,minScore:V,topResults:z,embeddingCache:o}),m=r.map(({layerId:d,results:c})=>{let g=c.map(s=>` - ${s.name} (${s.score.toFixed(2)})`).join(`
3
3
  `);return`${n.get(d)?.layerItem.name??d}:
4
4
  ${g}`}).join(`
5
5
  `),l;return r.length>0?l=`Vector search completed. Matching layers and fields with scores:
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as m}from"./4RZPOYZ7.js";import{a as k,b as E,ta as $}from"./CJIV4KJZ.js";import{a as f}from"./WNS5ZUF5.js";export default $arcgis.t(([,,,,,,{q:N,r:T},{a:b,b:v,c:x,d:C,e:F,f:R,g:L,h:_,i:I,j:M,k:Z,l:A,m:S,n:q,o:p,p:j}])=>{var w=[C,F,R,L,_,I,M,Z,A];async function G(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=x(t),c=r.map.bookmarks?.map(h=>h.name).filter(Boolean)??[],s=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((h,z)=>`${z+1}. layerId=${h.id} | title=${h.title??""} | name=${h.name??""} | score=${h.score.toFixed(2)}`).join(`
2
+ import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as m}from"./4RZPOYZ7.js";import{a as k,b as E,ta as $}from"./CJIV4KJZ.js";import{a as f}from"./WNS5ZUF5.js";export default $arcgis.t(([,,,,,,{q:N,r:T},{a:b,b:v,c:x,d:C,e:F,f:R,g:L,h:_,i:I,j:M,k:Z,l:A,m:S,n:q,o:p,p:j}])=>{var w=[C,F,R,L,_,I,M,Z,A];async function G(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=x(t),c=r.map.bookmarks?.map(h=>h.name).filter(Boolean)??[],s=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((h,z)=>`${z+1}. layerId=${h.id} | title=${h.title??""} | name=${h.name??""} | score=${h.score.toFixed(2)}`).join(`
3
3
  `):"",l=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",i=e.intent==="goToBookmark"&&c.length?`Available bookmarks:
4
4
  ${c.map(h=>`- ${h}`).join(`
5
5
  `)}`:"",o=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./G3HEXUCY.js";import b from"./VZMWVTXW.js";import a from"./EBRNMPPO.js";import{a as s,c as e}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-help-agent"),this.#i=e(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-help-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c)
2
+ import c from"./HBYZSLEZ.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as s,c as e}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=s(this,"arcgis-assistant-help-agent"),this.#i=e(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-help-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c)