@arcgis/ai-components 5.2.0-next.23 → 5.2.0-next.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/cdn/3AXQTBIA.js +134 -0
  2. package/dist/cdn/3EMHTJ2C.js +180 -0
  3. package/dist/cdn/{HCR23HJB.js → 4D4XBLDN.js} +1 -1
  4. package/dist/cdn/{ROLXMEVE.js → 4JK6XZLV.js} +1 -1
  5. package/dist/cdn/{KTOL6IN7.js → 6ELX5G6N.js} +5 -5
  6. package/dist/cdn/{U53OEX6L.js → CZCEK4Z5.js} +1 -1
  7. package/dist/cdn/{3YMSOD5D.js → E6CUTFFK.js} +1 -1
  8. package/dist/cdn/{PDEBKVBO.js → G7PX6SLG.js} +1 -1
  9. package/dist/cdn/{GJUD7EA3.js → IGZWQJW7.js} +1 -1
  10. package/dist/cdn/LEPJUN3X.js +22 -0
  11. package/dist/cdn/{ASSH4WSC.js → QUXNVDLI.js} +1 -1
  12. package/dist/cdn/{VDXSALQI.js → RQ7Y7JY3.js} +1 -1
  13. package/dist/cdn/{XGS5EIA5.js → TNEA5K7L.js} +1 -1
  14. package/dist/cdn/{PDT6I6TZ.js → VD5GRVML.js} +1 -1
  15. package/dist/cdn/W2IHPJ54.js +34 -0
  16. package/dist/cdn/{BFPMQT3A.js → X64XUQX2.js} +1 -1
  17. package/dist/cdn/ZMSJQB65.js +99 -0
  18. package/dist/cdn/agent-utils/index.js +1 -1
  19. package/dist/cdn/index.js +1 -1
  20. package/dist/chunks/adapter.js +1200 -1103
  21. package/dist/chunks/arcgisKnowledgeGraph.js +91 -74
  22. package/dist/chunks/arcgis_knowledge_current_lc_context.js +19 -2
  23. package/dist/chunks/arcgis_knowledge_current_map_context.js +31 -2
  24. package/dist/chunks/arcgis_knowledge_cypher_query_prompt.js +102 -0
  25. package/dist/chunks/arcgis_knowledge_summarize_result_prompt.js +116 -27
  26. package/dist/docs/api.json +1 -1
  27. package/dist/docs/docs.json +1 -1
  28. package/dist/docs/web-types.json +1 -1
  29. package/package.json +4 -4
  30. package/dist/cdn/5QAHYX7Y.js +0 -5
  31. package/dist/cdn/AXDZBBNL.js +0 -45
  32. package/dist/cdn/ICA7JOSU.js +0 -161
  33. package/dist/cdn/KMQ3SP4I.js +0 -5
@@ -0,0 +1,134 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import"./YIMNOUTF.js";var e=`# ArcGIS Knowledge Agent \u2014 Action Summary
3
+
4
+ You are a Knowledge Graph assistant that has executed tool calls to answer a user request.
5
+
6
+ ## Context
7
+
8
+ **Data model**
9
+ {dataModelSummary}
10
+
11
+ **Assigned task**
12
+ {assignedTask}
13
+
14
+ **User request**
15
+ {userRequest}
16
+
17
+ **Tool result**
18
+ {toolResult}
19
+
20
+ ---
21
+
22
+ ## Goal
23
+
24
+ Generate a concise, complete Markdown response using the tool results.
25
+
26
+ ---
27
+
28
+ ## Priority Rules (Strict Order)
29
+
30
+ ### 1. User Formatting Override (Highest Priority)
31
+
32
+ - If the user specifies a format (table, list, bullets, etc.):
33
+ - Use that format exactly
34
+ - Ignore ALL default formatting rules below
35
+ - Do NOT add summaries or extra sections unless requested
36
+
37
+ ---
38
+
39
+ ### 2. Default Output (When no override)
40
+
41
+ Produce:
42
+
43
+ - **Summary**: 1\u20132 sentences (no header, no bullets)
44
+ - **Results**: Minimal, well-formatted data
45
+ - **Note (optional)**:
46
+ - 1\u20132 italicized sentences describing tool limitations
47
+
48
+ #### Limits
49
+
50
+ - maxPreviewItems: 5
51
+
52
+ ---
53
+
54
+ ### 3. Output Constraints (Non-Negotiable)
55
+
56
+ - Output **valid Markdown only** (no JSON)
57
+ - Do NOT hallucinate data (entities, fields, counts, relationships)
58
+ - Do NOT include:
59
+ - reasoning
60
+ - classification labels
61
+ - follow-up questions
62
+ - next steps
63
+ - intro phrases (\u201CHere are\u2026\u201D)
64
+ - restating the question
65
+ - End immediately after the response
66
+
67
+ ---
68
+
69
+ ### 4. Data Handling Rules
70
+
71
+ - If results are empty \u2192 clearly state no results returned
72
+ - If insufficient data \u2192 state limitation, do NOT speculate
73
+ - Do NOT output:
74
+ - raw nested objects
75
+ - large arrays
76
+ - geometry
77
+ - Summarize complex structures
78
+ - Truncate long values with \`\u2026\`
79
+ - Show entities/relationships only once
80
+ - Use:
81
+ - \u201Centity\u201D (not node)
82
+ - \u201Crelationship\u201D (not edge)
83
+ - Hide \`globalid\` and \`objectid\` unless explicitly requested
84
+
85
+ ---
86
+
87
+ ### 5. Formatting Rules (Default Mode Only)
88
+
89
+ - No headers; use _italic labels_ if needed
90
+ - Use:
91
+ - bullets \u2192 single item summaries
92
+ - tables \u2192 multiple results (limit to 5 rows)
93
+ - Reduce columns to key fields only
94
+ - Format:
95
+ - dates \u2192 \u201Cday month year\u201D
96
+ - time separate from date
97
+
98
+ ---
99
+
100
+ ### 6. Result-Type Formatting
101
+
102
+ **SEARCH_HITS**
103
+
104
+ - Highlight top match (bullets)
105
+ - Table for remaining results
106
+
107
+ **ENTITIES**
108
+
109
+ - Group by type (if multiple)
110
+ - Show key properties only
111
+
112
+ **RELATIONSHIPS**
113
+
114
+ - Format: \`(entity) \u2014[relationship]\u2192 (entity)\`
115
+
116
+ **PATHS**
117
+
118
+ - Summary + 1-3 examples
119
+
120
+ ---
121
+
122
+ ## Internal Processing (Do NOT output)
123
+
124
+ Classify results into:
125
+
126
+ - SEARCH_HITS, ENTITIES, RELATIONSHIPS, PATHS
127
+
128
+ ## Failure Handling
129
+
130
+ - If data is insufficient \u2192 clearly state limitation
131
+ - Never infer or fabricate missing information
132
+
133
+ ---
134
+ `;export{e as default};
@@ -0,0 +1,180 @@
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 g}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,at,{addressToLocations:nt},it,st,De,{createRenderer:lt},{getSchemesByTag:ct,getSchemes:ut},{getBackgroundColorTheme:qe},{createAgeRenderer:dt,createContinuousRenderer:pt},{getSchemesByTag:ge},{createContinuousRenderer:mt},{createRenderer:ht},{getSchemesByTag:ft},{createRenderer:yt},{getSchemesByTag:gt},{createRenderer:wt},{getSchemesByTag:bt},{createRenderer:vt},{getSchemesByTag:Tt},{createAgeRenderer:St,createContinuousRenderer:xt},{createRenderer:Et},{getSchemesByTag:It},Nt,Le,Oe,{formatDateOnly:kt,convertDateFormatToIntlOptions:W,formatTimeOnly:$t,formatDate:Re},Ft,Mt,At,qt,Rt,Pe,,{fetchKnowledgeGraph:_e,executeQueryStreaming:_t,executeSearchStreaming:Ct},zt,{b:L,c:Ee,q:Ie}])=>{var Fe=e=>Array.isArray(e)&&e.every(z),et=e=>typeof e=="object"&&e!=null&&"messages"in e&&Fe(e.messages),tt=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(tt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Fe(e))n=e;else if(et(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 _n=b.Root({llmInputMessages:b({reducer:(e,t)=>D([],t),default:()=>[]})});var O=(e,t)=>t??e,Vi=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 jt(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 nt(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 it({url:n,width:24,height:24}),u=new at({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 Dt=["mapView"];function k(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=Dt.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Lt({address:e},t){let{mapView:r}=k(t);return await jt(e,r)}var Ot=s.object({address:s.string().describe("The full address or place name to locate.")}),Qi=g(Lt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Ot});async function Pt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let 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 Gt({bookmarkName:e},t){let{mapView:r}=k(t);return await Promise.resolve(Pt(e,r))}var Vt=N.object({bookmarkName:N.string().describe("The name of the bookmark to navigate to.")}),Bi=g(Gt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Vt});async function Qt(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 Bt({layerId:e,where:t},r){let{mapView:o}=k(r);return await Qt(e,t,o)}var Ut=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")}),Ui=g(Bt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Ut});async function Kt(e){let t=new st({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 Wt(e,t){let{mapView:r}=k(t);return await Kt(r)}var Ht=N.object({}),Ki=g(Wt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Ht});async function Jt(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 Zt(e,t){let{mapView:r}=k(t);return await Jt(r)}var Yt=s.object({}),Wi=g(Zt,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:Yt});async function Xt(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 er({layerId:e},t){let{mapView:r}=k(t);return await Xt(e,r)}var tr=N.object({layerId:N.string().describe("The id of the layer to navigate to")}),Hi=g(er,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:tr});async function rr(e,t){return await t.goTo({scale:e}),{text:`Successfully zoomed to: ${e}`}}async function or({scale:e},t){let{mapView:r}=k(t);return await rr(e,r)}var ar=s.object({scale:s.number().describe("The map scale of the view to go to.")}),Ji=g(or,{name:"goToScale",description:"Go to the specified view scale.",schema:ar});async function nr(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 ir({center:e,zoom:t,scale:r},o){let{mapView:a}=k(o);return await nr(e,a,{zoom:t,scale:r})}var sr=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.")}),Zi=g(ir,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:sr});async function lr(e,t){return await t.goTo({zoom:e}),{text:`Successfully zoomed to: ${e}`}}async function cr({zoom:e},t){let{mapView:r}=k(t);return await lr(e,r)}var ur=s.object({zoom:s.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Yi=g(cr,{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:ur}),Ce=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(Ce).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
4
+ Available prompts:
5
+ ${Object.keys(Ce).join(`
6
+ `)}`);return await t[1]()}var dr=(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},Xi=(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 pr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,l;return n?l=ct({basemapTheme:await qe(o),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:l=ut({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 mr(e){return await lt(e)}async function hr({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 pr(u),d=await mr(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 fr=["mapView"];function I(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=fr.filter(o=>!(o in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function yr({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 hr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var gr=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)")}),es=g(yr,{name:"chart",description:`Label: Charts
7
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart.
8
+ Keywords: pie, chart, all categories, breakdown, proportion
9
+ Example: Show the total number of homes built in each decade using a pie chart for each feature.
10
+ Fields: This style requires 2-8 number fields.
11
+
12
+ Label: Charts and Size
13
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
14
+ Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
15
+ Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
16
+ Fields: This style requires 2-8 number fields.`,schema:gr});function wr(e){let{fields:t,layer:r,view:o,theme:a,colorSchemeTags:n}=e,l=t[0],i;return n&&(i=ge({geometryType:r.geometryType,includedTags:n,theme:a||"high-to-low"})[0]),{layer:r,view:o,startTime:l,endTime:new Date,theme:a,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function br(e){return await dt(e)}async function vr({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-age",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let c=wr(u),d=await br(c);return i.renderer=d.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying color-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function Tr({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 vr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var Sr=s.object({layerId:s.string().describe("The id of the layer to apply the color-age renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),ts=g(Tr,{name:"color-age",description:`Label: Age (color)
17
+ Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
18
+ Keywords: since, age, how old, how long
19
+ Example: Show the age of each feature based on its reported date.
20
+ Fields: This style requires at least one field with a date type.`,schema:Sr});function xr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,{theme:n}=e,l=t[1],i=t[0],u;return a&&(u=ge({geometryType:r.geometryType,includedTags:a,theme:n||"high-to-low"})[0]),{layer:r,view:o,field:i,normalizationField:l,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function Er(e){return await pt(e)}async function Ir({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",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let c=xr(u),d=await Er(c);return i.renderer=d.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying color renderer: ${c instanceof Error?c.message:String(c)}`}}async function Nr({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 Ir({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var kr=s.object({layerId:s.string().describe("The id of the layer to apply the color renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the color renderer"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),rs=g(Nr,{name:"color",description:`Label: Counts and Amounts (color)
21
+ Description: Vary color along a continuous color ramp to represent numeric or ranked data.
22
+ Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
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:kr});function $r(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 Fr(e){return await mt(e)}async function Mr({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=$r(u),d=await Fr(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 Ar({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 Mr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var qr=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")}),os=g(Ar,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
25
+ Description: Vary symbol size and color based on the values of two numeric attributes.
26
+ Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
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:qr});function Rr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n;return a&&(n=ft({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 _r(e){return await ht(e)}async function Cr({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=Rr(i),c=await _r(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 zr({layerId:e,fields:t,colorSchemes:r},o){let{mapView:a}=I(o);return await x({type:"show-legend",data:{layerIds:[e]}},o),await Cr({arcgisMap:a.map,arcgisMapView:a,layerId:e,fields:t,colorSchemes:r})}var jr=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")}),as=g(zr,{name:"dot-density",description:`Dot Density
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
+ **Use cases:**
31
+ - Population distribution visualization
32
+ - Comparing multiple categories within areas
33
+ - Showing spatial distribution patterns
34
+ **Examples:**
35
+ - Show the density of the population based on various race/ethnic groups
36
+ - Visualize distribution of different crops across regions
37
+ - Display demographic patterns within census tracts
38
+ **Fields:** Requires 2-8 number fields.
39
+ **Keywords:** density, how much, how many, total, number, amount`,schema:jr});function Dr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n,l=t[0];return a&&(n=gt({includedTags:a,basemap:o.map?.basemap||"topo"})[0]),{layer:r,view:o,field:l,heatmapScheme:n}}async function Lr(e){return await yt(e)}async function Or({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:"heatmap",fields:o,layer:l,view:n,colorSchemeTags:a};try{let u=Dr(i),c=await Lr(u);return l.renderer=c.renderer,l.visible=!0,`Heatmap renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function Pr({layerId:e,fields:t,colorSchemes:r},o){let{mapView:a}=I(o);return await x({type:"show-legend",data:{layerIds:[e]}},o),await Or({arcgisMap:a.map,arcgisMapView:a,layerId:e,fields:t,colorSchemes:r})}var Gr=s.object({layerId:s.string().describe("The id of the layer to apply the heatmap renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use")}),ns=g(Pr,{name:"heatmap",description:`Label: Heat Map
40
+ Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
41
+ Keywords: density, heatmap, hot spots, pattern, cluster
42
+ Example: Create a heatmap
43
+ Fields: This typically requires zero or one field of type number.`,schema:Gr});function Vr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,l;return n&&(l=bt({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:o,fields:t.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),predominanceScheme:l}}async function Qr(e){return await wt(e)}async function Br({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?"predominance-size":"predominance",fields:o,layer:i,view:l,colorSchemeTags:a};try{let c=Vr(u),d=await Qr(c);return i.renderer=d.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying predominance renderer: ${c instanceof Error?c.message:String(c)}`}}async function Ur({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 Br({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var Kr=s.object({layerId:s.string().describe("The id of the layer to apply the predominance renderer to"),fields:s.array(s.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),includeSize:s.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),is=g(Ur,{name:"predominance",description:`Label: Predominant category
44
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
45
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
46
+ Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
47
+ Fields: This style relies on 2-10 number fields.
48
+
49
+ Label: Predominant category and Size
50
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
51
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
52
+ Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
53
+ Fields: This style relies on 2-10 number fields.`,schema:Kr});function Wr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n,l={field:t[0]},i={field:t[1]};return a&&(n=Tt({geometryType:r.geometryType,includedTags:a})[0]),{layer:r,view:o,field1:l,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function Hr(e){return await vt(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:"relationship",fields:o,layer:l,view:n,colorSchemeTags:a};try{let u=Wr(i),c=await Hr(u);return l.renderer=c.renderer,l.visible=!0,`Relationship renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function Zr({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 Yr=s.object({layerId:s.string().describe("The id of the layer to apply the relationship renderer to"),fields:s.array(s.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use")}),ss=g(Zr,{name:"relationship",description:`Label: Relationship
54
+ Description: Overlays two color ramps to represent the relationship between two numeric attributes.
55
+ Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
56
+ Example: Show the relationship between tree height and carbon storage
57
+ Fields: This style requires two number fields.`,schema:Yr});function Xr(e){let{fields:t,layer:r,view:o,theme:a}=e,n=t[0];return{layer:r,view:o,startTime:n,endTime:new Date,theme:a,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function eo(e){return await St(e)}async function to({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:"size-age",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let c=Xr(u),d=await eo(c);return i.renderer=d.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying size-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function ro({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 to({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var oo=s.object({layerId:s.string().describe("The id of the layer to apply the size-age renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),ls=g(ro,{name:"size-age",description:`Label: Age (size)
58
+ Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
59
+ Keywords: since, age, how old, how long
60
+ Example: Change the size of features so older features are larger than new features.
61
+ Fields: This style requires at least one field with a date type.`,schema:oo});function ao(e){let{fields:t,layer:r,view:o}=e,{theme:a}=e,n=t[1],l=t[0];return{layer:r,view:o,field:l,normalizationField:n,theme:a,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function no(e){return await xt(e)}async function io({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:"size",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let c=ao(u),d=await no(c);return i.renderer=d.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying size renderer: ${c instanceof Error?c.message:String(c)}`}}async function so({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 io({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var lo=s.object({layerId:s.string().describe("The id of the layer to apply the size renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),cs=g(so,{name:"size",description:`Label: Counts and Amounts (size)
62
+ Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
63
+ Keywords: graduated size, proportional size, how much, total, number, amount, size
64
+ Example: Vary the size of each point based on the total population.
65
+ 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.
66
+
67
+ Label: Continuous Timeline (size)
68
+ Description: Vary symbol sizes along a continuous ramp to represent dates.
69
+ Keywords: graduated size, proportional size, classed size, how much, total, number, when
70
+ Example: Vary the size of each feature based on the date a ticket was completed.
71
+ Fields: This style requires a single field with a date type.`,schema:lo});function co(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n=t[0],l=t[1],i=t[2],u;return a&&(u=It({geometryType:r.geometryType,includedTags:a})[0]),{layer:r,view:o,field:n,field2:l,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function uo(e){return await Et(e)}async function po({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:"type",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let c=co(u),d=await uo(c);return i.renderer=d.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(c){return`Error applying type renderer: ${c instanceof Error?c.message:String(c)}`}}async function mo({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 po({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var ho=s.object({layerId:s.string().describe("The id of the layer to apply the type renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),us=g(mo,{name:"type",description:`Label: Types (unique symbols)
72
+ Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
73
+ Keywords: categorical, category, type, unique, discrete, point of interest, region, group
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:ho}),ds=b.Root({...L(),vectorSearchLayerIds:b(),vectorSearchFieldResults:b(),layerFieldInfo:b(),selectedLayerId:b()}),ps=b.Root({...L(),vectorSearchLayerIds:b(),vectorSearchFieldResults:b(),layerFieldInfo:b(),queryResponse:b(),dataExplorationMessages:b({reducer:D,default:()=>[]})}),fo=["mapView"];function M(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=fo.filter(o=>!(o in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var yo=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."},go=async(e,t)=>{let{mapView:r}=M(t);return yo(r)},wo=g(go,{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({})}),bo=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."},vo=async(e,t)=>{let{mapView:r}=M(t);return await bo(r)},To=g(vo,{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"}},So=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)}}},xo=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 Nt({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 So(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}`},Eo=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],$=s.enum(Eo),Io=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 xo(e,l,o,a,t,r)},No=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.")}),ko=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.")}),$o=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([No,ko]).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.")}),Fo=g(Io,{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:$o}),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},Mo=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Ao=e=>{if(typeof e=="string"&&e)return e;let t=le(e);return t?t.toISOString().slice(0,10):null},ms=()=>{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}},qo=(e,t,r)=>{let o=t?.toLowerCase();if(o==="date-only"){let n=Ao(e);return n?kt(n,W("short-date")):e}if(o==="time-only"){if(typeof e=="string"&&e)return $t(e,W("long-time"));let n=le(e);return n?Re(n,{...W("long-time"),timeZone:"UTC"}):e}let a=le(e);return a?Re(a,{...W("short-date-short-time"),timeZone:Mo(r)}):e},Ve=(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},Ro=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,_o=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},Co=(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}},zo=(e,t,r)=>{let o=_o(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=Ro(r);try{return new Intl.DateTimeFormat(void 0,a).format(o)}catch{return e}},Qe=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,Be=(e,t,r,o,a)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?Co(r,n):n?.type==="date-time"?zo(r,n,a):qo(r,o,a)},jo=(e,t,r,o)=>{let a=e.fieldsIndex?.get(t),n=Ve(t,r,e)??r;return Be(e,t,n,a?.type,o)},Do=(e,t)=>Qe(e,t),Ue=(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=Ve(c.name,d,e)??d,p=Qe(e,c.name);u[p]=Be(e,c.name,m,c.type,r)}),u});return{objectIds:a,attributes:n}},Lo=(e,t,r)=>{let o=e.createQuery();return o.outFields=[t],o.where=r||"1=1",o.num=1,o},Oo=async(e,t,r,o)=>{let a=o.map?.allLayers.find(d=>d.id===e),n=Lo(a,t,r.where),l=(await a.queryFeatures(n)).features[0],i=l?l.attributes[t]:null,u=jo(a,t,i,o.timeZone),c=Do(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 Po({layerId:e,fieldName:t,query:r},o){let{mapView:a}=M(o),n=await Oo(e,t,r,a);return JSON.stringify(n,null,2)}var Go=s.object({layerId:s.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:s.string().describe("The name of the field/attribute from which to get a field value."),query:s.object({where:s.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Vo=g(Po,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Go}),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 Qo=async e=>{let{targetLayer:t,fieldName:r,statisticType:o,mapView:a,layersAndFieldsRegistry:n,geometryFilter:l}=e,i=a.map?.allLayers.find(w=>w.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 w=await ee(l,a);if("error"in w)throw new Error(w.error);if(!w.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:w.geometry,distance:l.distance,units:l.units,spatialRelationship:"intersects"})}let y=we(u,[r],!1),f=null,h=null,v=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let w={layer:i,useFeaturesInView:y,view:y?a:void 0,field:r,sqlWhere:X(i.definitionExpression,t.where),...p&&{filter:p},outStatisticTypes:{include:[o]}};f=await Ft(w);let T=["string","small-integer","integer"],E=c.domain?.type==="coded-value"?c.domain:null;(T.includes(c.type)||E)&&(h=(await Mt({layer:i,useFeaturesInView:y,view:y?a:void 0,field:r,sqlWhere:X(i.definitionExpression,t.where),...p&&{filter:p}})).uniqueValueInfos.sort((q,Ye)=>Ye.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(w){console.error("Statistics error:",w)}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 Bo({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:o},a){let n=Ge(a,"layersAndFieldsRegistry"),{mapView:l}=M(a),i=await Qo({targetLayer:e,fieldName:t,statisticType:r,mapView:l,layersAndFieldsRegistry:n,geometryFilter:o});return JSON.stringify(i,null,2)}var Uo=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.")}),Ko=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.")}),Wo=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([Uo,Ko]).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.")}),Ho=g(Bo,{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
+
77
+ USE THIS TOOL FOR:
78
+ - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
79
+ - "Most common/frequent value of [field]?" \u2014 frequency analysis
80
+ - Questions requiring a mathematical aggregation across many features
81
+
82
+ DO NOT USE FOR:
83
+ - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
84
+ - "Show / list / find features" \u2014 use queryFeatures instead
85
+ - Simple counts of features matching a condition \u2014 use queryFeatures instead
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:Wo}),Jo=e=>e.flatMap(t=>t.split(",")).map(t=>t.trim()).map(t=>t.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(t=>!!t),Zo=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 At({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,...Jo(t.orderByFields)])],w=we(l,v,a??!1);try{p=w?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 y=p.features.map(h=>h.attributes[d]),{attributes:f}=Ue(n,p,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:f,objectIds:y,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)}}}},Yo=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:o},a)=>{let{mapView:n}=M(a),l=await Zo(e,t,n,r,o);return JSON.stringify(l,null,2)},Xo=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.")}),ea=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.")}),ta=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([Xo,ea]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter: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).")}),ra=g(Yo,{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:ta}),se=25,oa=e=>e.flatMap(t=>t.split(",")).map(t=>t.trim()).map(t=>t.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(t=>!!t),aa=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 w={error:v.error};if(P(r)){let T=t.map?.allLayers.find(E=>E.id===r.layerId);w.geometryLayerName=T?.title??T?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else Y(r)&&(w.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"Geometry lookup failed",details:w}}if(!v.geometry){let w={};if(P(r)){let T=t.map?.allLayers.find(E=>E.id===r.layerId);w.error=`No features found matching: ${r.where}`,w.geometryLayerName=T?.title??T?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else Y(r)&&(w.error="Failed to create point geometry",w.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"No features found for geometry filter",details:w}}i=v.geometry}else o&&(i=t.extent.clone());let u=[...new Set([...e.outFields,...oa(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,y;try{p=c?await n.queryFeatureCount(m):await a.queryFeatureCount(m),p>0&&p<=se&&(y=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&&(y=await a.queryFeatures(m))}let{objectIds:f,attributes:h}=y?Ue(a,y,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 na({targetLayer:e,geometryFilter:t,useCurrentExtent:r},o){let{mapView:a}=M(o),n=await aa(e,a,t,r);return JSON.stringify(n,null,2)}var ia=s.object({layerId:s.string().describe("The layerId of the layer containing the geometry by which to filter."),where:s.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:s.number().optional().describe("The buffer distance around the geometry."),units:$.optional().describe("The units for the distance buffer.")}),sa=s.object({point:s.object({x:s.number().describe("X coordinate (longitude) from navigation result"),y:s.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:s.object({wkid:s.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:s.number().optional().describe("Optional buffer distance around the point."),units:$.optional().describe("The units for the distance buffer.")}),la=s.object({targetLayer:s.object({layerId:s.string().describe("The layerId of the layer containing the field from which to get a value."),where:s.string().describe("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([ia,sa]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),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).")}),ca=g(na,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
88
+
89
+ USE THIS TOOL FOR:
90
+ - "Show / display / list features where..." \u2014 finding and listing features
91
+ - "How many X are Y?" \u2014 counting features that match a condition
92
+ - "Which features..." / "Find features..." \u2014 identifying specific features
93
+ - Spatial queries \u2014 finding features near/within/intersecting other features
94
+ - Any question where the user wants to SEE or COUNT matching features
95
+
96
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:la}),ua=[Vo,Ho,ra,ca],hs=[Fo,To,wo],da=new K(ua,{handleToolErrors:!1});async function fs(e,t){let{messages:r}=await da.invoke({messages:e.dataExplorationMessages},t),o=[],a=[];for(let n of r){let l=n.content,i;typeof l!="string"&&(i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:l}});try{typeof l=="string"?i=JSON.parse(l):i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:l}}}catch{i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:l}}}o.push(i),i.details&&typeof i.details=="object"&&"error"in i.details?a.push(`- ${i.tool}: Error - ${String(i.details.error)}`):a.push(`- ${i.layerName}: ${i.summary}`)}return await S({text:`Finished executing layer query tool: ${a.join(", ")}`},t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,...r],queryResponse:o,status:"success",summary:a.length>0?dr(a.join(`
97
+ `)):"Query executed."}}var ys=b.Root({...L(),helpInternalState:b({reducer:O,default:()=>({toolCallMessage:void 0})})}),pa=(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
+ `);return`**${r.layerItem.title}** has ${o.length} field(s):
99
+
100
+ ${a}`},ma=async({layerTitle:e},t)=>{let r=Ge(t,"layersAndFieldsRegistry");return pa(r,e)},gs=g(ma,{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.")})}),ws=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 bs(e){let t=e?.configurable?.context;if(Ke(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(Ke(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 _e(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 _e(o)}}}}function Ke(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:ha(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
+ 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=fa(t.role);for(let o of t.properties){let a={name:o.name,alias:o.alias?o.alias:void 0,fieldType:o.fieldType,role:ya(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}},ha=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},fa=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function ya(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 ga(e,t){let r=await Z("arcgis_knowledge_cypher_query_prompt");return t?`${e} ${r}
102
+
103
+ Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
104
+
105
+ Attempt Number: ${t.attemptCount}
106
+ Execution Error: ${t.executionError}
107
+ Failed Query:
108
+ ${t.failedGraphQuery}`:`${e} ${r}`}async function wa(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 ga(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="",y=1;for(;!u;){await new Promise(h=>setTimeout(h,1e3)),await S({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,y)}`},o),y=y%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 ba(e,t){R(e,r=>{t.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function R(e,t){if(!(!e||typeof e!="object")){if(Ta(e))for(let r of e.path)R(r,t);else if(va(e))t(e);else if(Array.isArray(e))for(let r of e)R(r,t);else if(Sa(e))for(let r of Object.values(e.properties??{}))R(r,t)}}function va(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Ta(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Sa(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function xa(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 Ea(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 _=3;function We(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 C(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 Ia=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 y=p.resultRowsStream.getReader(),f=0,h=Date.now(),v=!1;for(;;){let{done:w,value:T}=await y.read();if(w)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:C(p),error:p}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function He({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<=_;m++){let p;try{p=await ve(e,r.dataModel,o,c,d)}catch(h){return{type:"generation-error",errorMessage:C(h),error:h}}await S({text:`Attempting to execute query: ${p.graphQuery.substring(0,500)}${p.graphQuery.length>500?"...":""}`},c);let y=await Ia({kg:r,queryParams:new Pe({openCypherQuery:p.graphQuery,bindParameters:t}),targetStructure:a,targetStructureReducer:n,requestOptions:l,queryRowLimit:i,queryTimeoutMs:u}),f=y.type==="aborted"?"Query execution was aborted.":y.type==="timeout"?"Query execution timed out.":y.type==="error"?`Query failed with error: ${y.errorMessage}`:"";if(y.type==="success")return{type:"success",graphQuery:p.graphQuery,explanation:p.explanation,rowLimitReached:y.rowLimitReached,resultHeader:y.resultHeader,processedResult:y.processedResult};if(y.type==="aborted")return{type:"aborted",errorMessage:f,graphQuery:p.graphQuery,explanation:p.explanation};if(m>=_)return y.type==="timeout"?{type:"timeout",errorMessage:f,graphQuery:p.graphQuery,explanation:p.explanation}:{type:"execution-error",errorMessage:f,error:y.error,graphQuery:p.graphQuery,explanation:p.explanation};d={failedGraphQuery:p.graphQuery,executionError:f,attemptCount:m},await S({text:`Attempt ${m} failed with error: ${f}. Retrying...`},c)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${_} attempts.`)}var Na=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 Ct(e,new zt({searchQuery:t,typeCategoryFilter:c,namedTypesFilter:o??void 0,num:d}),n)).resultRowsStream.getReader(),p=!1;for(;!p;){let{done:y,value:f}=await m.read();if(y){p=!0;break}for(let h of f)for(let v of h)l.push(v)}}}catch(c){let d=C(c);return n?.signal?.aborted?{type:"aborted",errorMessage:d,error:c}:{type:"error",errorMessage:d,error:c}}return{type:"success",results:l}},Je="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Ze({prompt:e,view:t,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:o=!1}){let a=[e];if(o&&a.push(Je),!A(t)&&t.map){let d=await Z("arcgis_knowledge_current_lc_context"),m=xa(t.map,r);return a.push(d),{enhancedPrompt:a.join(`
109
+
110
+ `),bindParameters:m,allNamedTypesFullyDynamic:!1}}let n=t.map,{allNamedTypesFullyDynamic:l,bindParameters:i,nonDynamicTypes:u}=Ea(n,r);if(l)return{enhancedPrompt:a.join(`
111
+
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
+
114
+ `),bindParameters:i,allNamedTypesFullyDynamic:l}}async function ka(e,t,r,o,a,n){let{view:l}=a,i=await He({prompt:e,bindParameters:t,kg:r,graphQueryServiceUrl:o,targetStructure:new Map,targetStructureReducer:(p,y)=>{for(let f of y)ba(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",$a=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.")}),Fa=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 Ze({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 ka(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
+
116
+ Number of records added: ${m.length}`,details:{generatedQuery:c,explanation:d,addedIdTypePairs:m}}}catch(c){let d=C(c);return{toolName:H,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:c}}},vs=g(Fa,{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
+
118
+ example prompts:
119
+ - "add all suppliers and the parts they produce to the link chart"
120
+ - "show me the competitors of company x and add them to the link chart"
121
+ - "add the relationships between company x and company y to the link chart"
122
+ - "expand all the companies"
123
+ - "expand company x through all the buildings it owns"
124
+ - "connect company x and company y"
125
+ - "connect all buildings on the link chart"
126
+ `,schema:$a});async function Ma(e,t){return await t.map?.applyLayout(e),await te(t),{appliedLayout:e}}var pe="applyLayout",Aa=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")}),qa=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 Ma(e,r);return{toolName:pe,status:"success",summary:`Successfully applied layout: ${o}.`,details:{appliedLayout:o}}}},Ts=g(qa,{name:pe,description:"Apply a diagram layout to the link chart",schema:Aa});async function Ra(e,t){return t.map?.changeNonspatialDataDisplay(e),await te(t),{appliedNonspatialDataDisplayMode:e}}var me="changeNonspatialVisibility",_a=s.object({setting:s.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Ca=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 Ra(e,r);return{toolName:me,status:"success",summary:`Successfully applied nonspatial visibility setting: ${o}.`,details:{appliedNonspatialDataDisplayMode:o}}}},Ss=g(Ca,{name:me,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:_a});async function za(e,t,r,o,a){let n,l="";for(let i=1;i<=_;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:
127
+ ${u}
128
+
129
+ Explanation: ${c}`}):(await te(o),{type:"success",graphQuery:u,explanation:c})}catch(d){let m=C(d);if(i>=_){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 ${_} attempts. Last error: ${l}`}}var J="createLinkChart",ja=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.")}),Da=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 za(`${e}
130
+
131
+ ${Je}`,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
+ ${l}
133
+
134
+ Explanation: ${i}`,details:{generatedQuery:l,explanation:i}}}},xs=g(Da,{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:ja}),he="queryGraphData",La=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.")}),Oa=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 Ze({prompt:e,view:l,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await He({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)R(v,w=>We(w));let y=50,f=d.slice(0,y).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
+
136
+ \`\`\`cypher
137
+ ${u}
138
+ \`\`\`
139
+
140
+ Query Results:
141
+ ${f.length} result(s) found.
142
+
143
+ Column Headers: ${p.join(", ")}
144
+
145
+ ${f.length>y?`Showing top ${y} results:
146
+
147
+ `:`Results:
148
+
149
+ `}${f.join(`
150
+ `)}
151
+ `,details:{generatedQuery:u,explanation:c,resultHeader:m,queryResults:d}}},Es=g(Oa,{name:he,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:La}),fe="generateCypher",Pa=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Ga=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t),o=F.getDefault().helperServices;try{let{graphQuery:a,explanation:n}=await wa(e,r.dataModel,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,t);return{toolName:fe,status:"success",summary:`Generated Graph Query:
152
+ ${a}
153
+
154
+ Explanation: ${n}`,details:{generatedQuery:a,explanation:n}}}catch(a){let n=C(a);return{toolName:fe,status:"error",errorMessage:`Failed to generate Cypher query. ${n}`,error:a}}},Is=g(Ga,{name:fe,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:Pa}),Va=e=>{let t=e.dataModel,r=new Map;for(let i of t.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,c]of i.searchProperties.entries()){let d=r.get(u)??new Set;c.propertyNames.forEach(m=>d.add(m)),r.set(u,d)}let o=t.entityTypes.filter(i=>r.has(i.name)),a=t.relationshipTypes.filter(i=>r.has(i.name)),n=`Entity Types:
155
+ ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
156
+ `)}`,l=`Relationship Types:
157
+ ${a.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
158
+ `)}`;return`${n}
159
+
160
+ ${l}`};async function Qa(e,t,r){let o=await Z("arcgis_knowledge_lucene_generation_prompt"),a={inquiry:e,dataModelForSearch:Va(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",Ba=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.")}),Ua=async({prompt:e},t)=>{let{knowledgeGraph:r}=await Q(t);await S({text:"Generating search query for the user inquiry"},t);let o=await Qa(e,r,t);await S({text:"Executing graph search with generated search query"},t);let a=await Na({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)R(i,u=>We(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
+ Query: ${o.query}
162
+ Type Category Filter: ${o.typeCategoryFilter}
163
+ Named Type Filters: ${o.typeFilters?o.typeFilters.join(", "):"None"}
164
+ Result Limit: ${o.resultLimit??"No limit"}
165
+
166
+ Search Results: ${a.results.length} result(s) found.
167
+
168
+ ${a.results.length>n?`Showing top ${n} results:
169
+
170
+ `:""}${l.map(i=>JSON.stringify(i)).join(`
171
+ `)}`,details:{generatedSearchQuery:o,searchResults:a.results}}},Ns=g(Ua,{name:ye,description:`
172
+ Search the knowledge graph using one or more search texts, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.
173
+ Example prompts:
174
+ - "Find 'Bradley'"
175
+ - "find the person john smith"
176
+ - "find all people named smith"
177
+ - "Find all references to 'delayed parts shipment'"
178
+ - "Find all reports authored by someone with the title of 'Researcher'"
179
+ - "Find the first 5 reports where summary mentions flood zoning near Sacramento, and the organization name is the City of Sacramento Utilities, and tags containing stormwater".
180
+ - "Search for all john smiths and show their global ids`,schema:Ba});return{a:K,b:Vi,c:k,d:Qi,e:Bi,f:Ui,g:Ki,h:Wi,i:Hi,j:Ji,k:Zi,l:Yi,m:Z,n:dr,o:Ge,p:Xi,q:es,r:ts,s:rs,t:os,u:as,v:ns,w:is,x:ss,y:ls,z:cs,A:us,B:ds,C:ps,D:M,E:ms,F:ua,G:hs,H:fs,I:ys,J:gs,K:ws,L:bs,M:Q,N:ue,O:vs,P:Ts,Q:Ss,R:xs,S:Es,T:Is,U:Ns}},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming",a)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import d from"./XGS5EIA5.js";import c from"./HOCTVCHH.js";import b from"./ICA7JOSU.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"./TNEA5K7L.js";import c from"./HOCTVCHH.js";import b from"./3EMHTJ2C.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 c from"./HOCTVCHH.js";import b from"./ICA7JOSU.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"./3EMHTJ2C.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,9 +1,9 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import b from"./ICA7JOSU.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 y,ta as x}from"./CJIV4KJZ.js";import{Z as f}from"./IKEF7ZHH.js";export default $arcgis.t(([,,,,,,{p:_,r:b},{K:u,L:A,M:K,N:S,O:E,P:M,Q:C,R:T,S:G,T:N,U:R,a:v,m:g,n:h,p:q}])=>{var $=[M,C,N,T,E,R,G];async function L(e,o){let l=await g("arcgis_knowledge_tool_prompt"),a=A(o),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:a},s=await b({promptText:l,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:$}),r=(s.tool_calls?.length??0)>0,t=typeof s.text=="string"?s.text.trim():"",i=t.length>0,p=s.content.toString();return!r&&(a==="map"||a==="knowledgeGraph")?{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,s],outputMessage:a==="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,s],outputMessage:r?p:t,status:r?e.status:i?"success":"failed",summary:p?h(p):"ArcGIS Knowledge Agent tool executed."}}var z={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 D(e){return!!e&&e.status==="success"&&!!z[e.toolName]}function F(e){return{type:z[e.toolName],data:e.details}}async function I(e,o){let l=new v($,{handleToolErrors:!1});try{let a=await l.invoke({messages:e.arcgisKnowledgeMessages},o),n=[];for(let t of a.messages){let i;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{i=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}.
2
+ import b from"./3EMHTJ2C.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
- Original Content: ${t.content}`)}if(!i||typeof i!="object"||!("toolName"in i))throw new Error(`Parsed tool message content does not have expected structure. Parsed content: ${JSON.stringify(i)}`);n.push(i)}await c({text:`Finished executing ArcGIS Knowledge Agent tools: ${a.messages.filter(t=>t.name).map(t=>t.name).join(", ")}`},o);let s=n.filter(t=>typeof t!="string").map(t=>`- Called Tool: ${t.toolName}, Status: ${t.status}`),r=n[0];return r&&D(r)&&await k(F(r),o),{...e,outputMessage:s.join(`
5
- `),summary:s.length?h(s.join(`
6
- `)):"ArcGIS Knowledge Agent did not execute any tools or return any results.",arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,...a.messages],arcgisKnowledgeToolResult:n}}catch(a){let n=a instanceof Error?a.message:String(a);return await c({text:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`},o),{...e,outputMessage:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`,status:"failed",summary:h(`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages]}}}var j=(e,o)=>q([],"ArcgisKnowledge Agent")(e,o);async function O(e,o){let l=(e.arcgisKnowledgeToolResult??[]).map(i=>({...i,details:void 0})),{knowledgeGraph:a}=await K(o),n=S.getDataModelTypesSummary(a.dataModel),s={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,toolResult:l,dataModelSummary:n},r=await _({promptText:await g("arcgis_knowledge_summarize_result_prompt"),modelTier:"default",inputVariables:s}),t=typeof r=="string"?r:r.content;return{...e,outputMessage:t,status:"success",summary:h(t),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new f(t)]}}function m(e){return async(o,l)=>l?.signal?.aborted?(await c({text:"Knowledge Agent execution cancelled"},l),new y({goto:d,update:{outputMessage:"Knowledge Agent execution cancelled",summary:"Knowledge Agent execution cancelled",status:"failed"}})):await e(o,l)}var V=()=>new x(u).addNode("requireArcgisKnowledgeServices",j).addNode("agent",m(L)).addNode("tools",m(I)).addNode("summarizationLLM",m(O)).addEdge(w,"requireArcgisKnowledgeServices").addEdge("requireArcgisKnowledgeServices","agent").addConditionalEdges("agent",e=>(e.arcgisKnowledgeMessages[e.arcgisKnowledgeMessages.length-1]?.tool_calls?.length??0)>0?"tools":d).addConditionalEdges("tools",e=>e.status==="failed"?d:"summarizationLLM").addEdge("summarizationLLM",d),J=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
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
+ `),summary:r.length?h(r.join(`
6
+ `)):"ArcGIS Knowledge Agent did not execute any tools or return any results.",arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,...s.messages],arcgisKnowledgeToolResult:n}}catch(s){let n=s instanceof Error?s.message:String(s);return await c({text:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`},a),{...e,outputMessage:`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`,status:"failed",summary:h(`ArcGIS Knowledge Agent tool execution failed unexpectedly: ${n}`),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages]}}}var V=(e,a)=>A([],"ArcgisKnowledge Agent")(e,a);async function j(e,a){let o=(e.arcgisKnowledgeToolResult??[]).map(l=>({...l,details:void 0})),{knowledgeGraph:s}=await q(a),n=S.getDataModelTypesSummary(s.dataModel),r={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,toolResult:o,dataModelSummary:n},i=await _({promptText:await m("arcgis_knowledge_summarize_result_prompt"),modelTier:"default",inputVariables:r,config:a}),t=typeof i=="string"?i:i.content;return{...e,outputMessage:t,status:"success",summary:h(t),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new u(t)]}}async function O(e){let a=e.arcgisKnowledgeToolResult?.[0],o=a?.status==="success"?a.summary:"ArcGIS Knowledge Agent tool execution failed.";return{...e,outputMessage:o,status:"success",summary:h(o),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new u(o)]}}function g(e){return async(a,o)=>o?.signal?.aborted?(await c({text:"Knowledge Agent execution cancelled"},o),new f({goto:d,update:{outputMessage:"Knowledge Agent execution cancelled",summary:"Knowledge Agent execution cancelled",status:"failed"}})):await e(a,o)}var J=()=>new x(y).addNode("requireArcgisKnowledgeServices",V).addNode("agent",g($)).addNode("tools",g(F)).addNode("summarizationLLM",g(j)).addNode("finalizeToolSummary",g(O)).addEdge(w,"requireArcgisKnowledgeServices").addEdge("requireArcgisKnowledgeServices","agent").addConditionalEdges("agent",e=>(e.arcgisKnowledgeMessages[e.arcgisKnowledgeMessages.length-1]?.tool_calls?.length??0)>0?"tools":d).addConditionalEdges("tools",e=>{if(e.status==="failed")return d;let a=e.arcgisKnowledgeToolResult?.[0];return a?.status==="success"&&["applyLayout","changeNonspatialVisibility"].includes(a.toolName)?"finalizeToolSummary":"summarizationLLM"}).addEdge("summarizationLLM",d).addEdge("finalizeToolSummary",d),P=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
7
7
  This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
8
8
  For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
9
9
  expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
@@ -41,4 +41,4 @@ _example: "Discover and add all the relationships originating at 'Entity E' to t
41
41
  _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
42
42
  _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
43
43
  _example: "Find John Smith and all people he has made phone calls to in the last year"_
44
- _example: "What is the average age of all people who work for Esri?"_`,re={id:"arcgisKnowledge",name:"ArcgisKnowledge Agent",description:J,createGraph:V,workspace:u};return re},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request",a,b)
44
+ _example: "What is the average age of all people who work for Esri?"_`,ie={id:"arcgisKnowledge",name:"ArcgisKnowledge Agent",description:P,createGraph:J,workspace:y};return ie},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request",a,b)