@arcgis/ai-components 5.1.0-next.89 → 5.1.0-next.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{A as z,Ab as _,B as A,Bb as $,C as B,Cb as aa,Fb as ba,Gb as ca,Hb as da,Ib as ea,Jb as fa,Kb as ga,Lb as ha,Mb as ia,Nb as ja,Ob as ka,Pb as la,a,b,bb as C,c,cb as D,d,db as E,e,eb as F,f,fb as G,gb as H,h as g,hb as I,i as h,ib as J,j as i,jb as K,k as j,kb as L,l as k,lb as M,m as l,mb as N,n as m,nb as O,o as n,ob as P,p as o,pb as Q,q as p,r as q,rb as R,s as r,sb as S,t as s,tb as T,u as t,ub as U,v as u,vb as V,w as v,wb as W,x as w,xb as X,y as x,yb as Y,z as y,zb as Z}from"./PLPJJRCP.js";import"./CFDTXKJ6.js";export{L as Annotation,H as AsyncBatchedStore,J as BaseChannel,E as BaseCheckpointSaver,k as BaseLangGraphError,G as BaseStore,K as BinaryOperatorAggregate,d as COMMAND_SYMBOL,i as Command,e as CommandInstance,ca as CompiledStateGraph,b as END,v as EmptyChannelError,u as EmptyInputError,R as Graph,l as GraphBubbleUp,o as GraphInterrupt,m as GraphRecursionError,n as GraphValueError,c as INTERRUPT,I as InMemoryStore,w as InvalidUpdateError,F as MemorySaver,da as MessageGraph,ia as MessagesAnnotation,aa as MessagesValue,ja as MessagesZodMeta,ka as MessagesZodState,x as MultipleSubgraphsError,p as NodeInterrupt,g as Overwrite,q as ParentCommand,_ as REMOVE_ALL_MESSAGES,X as ReducedValue,z as RemoteException,a as START,f as Send,ba as StateGraph,A as StateGraphInputError,Z as StateSchema,y as UnreachableNodeError,Y as UntrackedValue,W as UntrackedValueChannel,$ as addMessages,D as copyCheckpoint,C as emptyCheckpoint,ga as entrypoint,O as getConfig,P as getCurrentTaskInput,U as getJsonSchemaFromSchema,ha as getPreviousState,V as getSchemaDefaultGetter,M as getStore,B as getSubgraphsSeenSet,N as getWriter,Q as interrupt,j as isCommand,s as isGraphBubbleUp,t as isGraphInterrupt,h as isInterrupted,r as isParentCommand,T as isSerializableSchema,S as isStandardSchema,$ as messagesStateReducer,ea as pushMessage,fa as task,la as writer};
2
+ import{A as z,Ab as _,B as A,Bb as $,C as B,Cb as aa,Fb as ba,Gb as ca,Hb as da,Ib as ea,Jb as fa,Kb as ga,Lb as ha,Mb as ia,Nb as ja,Ob as ka,Pb as la,a,b,bb as C,c,cb as D,d,db as E,e,eb as F,f,fb as G,gb as H,h as g,hb as I,i as h,ib as J,j as i,jb as K,k as j,kb as L,l as k,lb as M,m as l,mb as N,n as m,nb as O,o as n,ob as P,p as o,pb as Q,q as p,r as q,rb as R,s as r,sb as S,t as s,tb as T,u as t,ub as U,v as u,vb as V,w as v,wb as W,x as w,xb as X,y as x,yb as Y,z as y,zb as Z}from"./YW52XJMM.js";import"./CFDTXKJ6.js";export{L as Annotation,H as AsyncBatchedStore,J as BaseChannel,E as BaseCheckpointSaver,k as BaseLangGraphError,G as BaseStore,K as BinaryOperatorAggregate,d as COMMAND_SYMBOL,i as Command,e as CommandInstance,ca as CompiledStateGraph,b as END,v as EmptyChannelError,u as EmptyInputError,R as Graph,l as GraphBubbleUp,o as GraphInterrupt,m as GraphRecursionError,n as GraphValueError,c as INTERRUPT,I as InMemoryStore,w as InvalidUpdateError,F as MemorySaver,da as MessageGraph,ia as MessagesAnnotation,aa as MessagesValue,ja as MessagesZodMeta,ka as MessagesZodState,x as MultipleSubgraphsError,p as NodeInterrupt,g as Overwrite,q as ParentCommand,_ as REMOVE_ALL_MESSAGES,X as ReducedValue,z as RemoteException,a as START,f as Send,ba as StateGraph,A as StateGraphInputError,Z as StateSchema,y as UnreachableNodeError,Y as UntrackedValue,W as UntrackedValueChannel,$ as addMessages,D as copyCheckpoint,C as emptyCheckpoint,ga as entrypoint,O as getConfig,P as getCurrentTaskInput,U as getJsonSchemaFromSchema,ha as getPreviousState,V as getSchemaDefaultGetter,M as getStore,B as getSubgraphsSeenSet,N as getWriter,Q as interrupt,j as isCommand,s as isGraphBubbleUp,t as isGraphInterrupt,h as isInterrupted,r as isParentCommand,T as isSerializableSchema,S as isStandardSchema,$ as messagesStateReducer,ea as pushMessage,fa as task,la as writer};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./SOJ4DKGV.js";import b from"./KHCTRS6Z.js";import"./PLPJJRCP.js";import{a as e,c as a}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as s,y as r}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{c:i}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=e(this,"arcgis-assistant-layer-styling-agent"),a(this)}};r("arcgis-assistant-layer-styling-agent",t);return t},b,c)
2
+ import c from"./GQTBCKGL.js";import b from"./Y63AQNL7.js";import"./YW52XJMM.js";import{a as e,c as a}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as s,y as r}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{c:i}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-layer-styling-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=e(this,"arcgis-assistant-layer-styling-agent"),a(this)}};r("arcgis-assistant-layer-styling-agent",t);return t},b,c)
@@ -0,0 +1,244 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import a from"./Y63AQNL7.js";import{Bb as G,Fb as q,L as O,M as le,Q as ce,R as V,Za as F,_a as y,a as C,b as E,g as Ee,j as Z,k as J,kb as f,q as Ie,qb as $e,u as ke}from"./YW52XJMM.js";export default $arcgis.t(([pt,we,Ge,ht,{addressToLocations:gt},j,ue,ft,Pe,Be,{formatDateOnly:yt,convertDateFormatToIntlOptions:Y,formatTimeOnly:wt,formatDate:Ce},Ke,Qe,bt,vt,{createRenderer:St},{getSchemesByTag:xt,getSchemes:Tt},{getBackgroundColorTheme:qe},{createAgeRenderer:Et,createContinuousRenderer:It},{getSchemesByTag:be},{createContinuousRenderer:kt},{createRenderer:$t},{getSchemesByTag:_t},{createRenderer:Nt},{getSchemesByTag:Ft},{createRenderer:Mt},{getSchemesByTag:Ct},{createRenderer:qt},{getSchemesByTag:At},{createAgeRenderer:Rt,createContinuousRenderer:Lt},{createRenderer:zt},{getSchemesByTag:jt},,{fetchKnowledgeGraph:Dt,executeQueryStreaming:Ot},ve,Ae,Re,,Vt,{a:l,b:g,c:k,e:_e,f:Ne,g:D}])=>{var Me=e=>Array.isArray(e)&&e.every(O),ct=e=>typeof e=="object"&&e!=null&&"messages"in e&&Me(e.messages),dt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,A=class extends $e{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:a,handleToolErrors:o}=t??{};super({name:r,tags:a,func:(n,s)=>this.run(n,s)}),this.tools=e,this.handleToolErrors=o??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(a=>a.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let a=await r.invoke({...e,type:"tool_call"},t);return O(a)&&a.getType()==="tool"||J(a)?a:new le({status:"success",name:r.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||ke(a))throw a;return new le({status:"error",content:`Error: ${a.message}
3
+ Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(dt(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Me(e))n=e;else if(ct(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(d=>d.getType()==="tool").map(d=>d.tool_call_id)),i;for(let d=n.length-1;d>=0;d-=1){let c=n[d];if(V(c)){i=c;break}}if(i==null||!V(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(d=>d.id==null||!s.has(d.id)).map(d=>this.runTool(d,t))??[])}if(!r.some(J))return Array.isArray(e)?r:{messages:r};let a=[],o=null;for(let n of r)J(n)?n.graph===Z.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>Ee(s))?o?o.goto.push(...n.goto):o=new Z({graph:Z.PARENT,goto:n.goto}):a.push(n):a.push(Array.isArray(e)?[n]:{messages:[n]});return o&&a.push(o),a}};var Pi=f.Root({llmInputMessages:f({reducer:(e,t)=>G([],t),default:()=>[]})});var K=(e,t)=>({...e,...t}),Q=(e="",t)=>{let r=typeof t=="string"?t.trim():"";if(!r)return e;let a=e.trim();if(!a)return r;if(a===r)return e;let o=a.split(`
4
+
5
+ `);return o[o.length-1]?.trim()===r?e:`${e}
6
+
7
+ ${r}`},I=(e,t)=>t??e,Ue=f.Root({agentExecutionContext:f({reducer:K,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:f({reducer:Q,default:()=>""}),summary:f({reducer:I,default:()=>""}),status:f({reducer:I}),intent:f({reducer:I}),vectorSearchLayerResults:f({reducer:I,default:()=>[]}),vectorSearchFieldResults:f({reducer:I}),navigationInternalState:f({reducer:I,default:()=>({toolCallMessage:void 0})})});async function Gt(e,t){let r=j.getDefault().helperServices,a=r.geocode.find(T=>T.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!a)throw new Error("No geocoding service found in helperServices.");let o=a.url,n=`${ue.assetsPath?.endsWith("/")?ue.assetsPath:`${ue.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await gt(o,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent)throw new Error(`Could not find location for: ${e}`);let{xmin:i,ymin:d,xmax:c,ymax:u,spatialReference:m}=s.extent,p=new Ge({xmin:i,ymin:d,xmax:c,ymax:u,spatialReference:m}),v=(i+c)/2,b=(d+u)/2,h=new we({x:v,y:b,spatialReference:m}),w=new ht({url:n,width:24,height:24}),S=new pt({geometry:h,symbol:w});return t.graphics.removeAll(),t.graphics.add(S),await t.goTo(p),`Successfully zoomed to: ${e}. Location coordinates: x=${v}, y=${b}, wkid=${m.wkid}`}var Pt=["mapView"];function $(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=Pt.filter(a=>!(a in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Bt({address:e},t){let{mapView:r}=$(t);return await Gt(e,r)}var Kt=l.object({address:l.string().describe("The full address or place name to locate.")}),Qt=y(Bt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Kt});async function Ut(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let a=r.find(n=>n.name===e);if(!a)throw new Error(`Bookmark with name "${e}" not found.`);let o=a.viewpoint;if(!o)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await t.goTo(o),`Navigated to bookmark: ${e}`}async function Wt({bookmarkName:e},t){let{mapView:r}=$(t);return await Promise.resolve(Ut(e,r))}var Ht=F.object({bookmarkName:F.string().describe("The name of the bookmark to navigate to.")}),Zt=y(Wt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Ht});async function Jt(e,t,r){let a=r.map?.allLayers.find(n=>n.id===e);if(!a)return`Error: Layer with id ${e} not found`;let o=a.createQuery();o.where=t??"1=1";try{let{extent:n,count:s}=await a.queryExtent(o);if(s===0)return`No features found in ${a.title} matching: ${t}`;if(n)await r.goTo(n);else return`Error: Unable to determine extent for ${a.title}`;return`Successfully zoomed to ${s} feature(s) in ${a.title}`}catch(n){return console.error("Error in goToFeatures:",n),`Error: ${n instanceof Error?n.message:"Unknown error"}`}}async function Yt({layerId:e,where:t},r){let{mapView:a}=$(r);return await Jt(e,t,a)}var Xt=F.object({layerId:F.string().describe("The layerId of the layer to zoom to."),where:F.string().describe("The sql-92 where clause used to query features to zoom to")}),er=y(Yt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Xt});async function tr(e){let t=new Ge({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),"Successfully zoomed to world extent"}async function rr(e,t){let{mapView:r}=$(t);return await tr(r)}var ar=F.object({}),or=y(rr,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ar});async function nr(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return"Successfully zoomed to home extent"}async function ir(e,t){let{mapView:r}=$(t);return await nr(r)}var sr=l.object({}),lr=y(ir,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:sr});async function cr(e,t){await t.when();let r=t.map?.allLayers.find(o=>o.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),`Could not find layer for: ${e}`;let a;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?a=t.map.diagramNodesExtent:a=r.fullExtent,a?(await t.goTo(a),r.visible=!0,`Successfully zoomed to: ${r.title??""}`):"Layer has no defined extent. Cannot zoom to layer."}async function dr({layerId:e},t){let{mapView:r}=$(t);return await cr(e,r)}var ur=F.object({layerId:F.string().describe("The id of the layer to navigate to")}),mr=y(dr,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:ur});async function pr(e,t){return await t.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function hr({scale:e},t){let{mapView:r}=$(t);return await pr(e,r)}var gr=l.object({scale:l.number().describe("The map scale of the view to go to.")}),fr=y(hr,{name:"goToScale",description:"Go to the specified view scale.",schema:gr});async function yr(e,t,r){let a={target:new we({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(a.zoom=r.zoom),r?.scale!==void 0&&(a.scale=r.scale),await t.goTo(a),`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}async function wr({center:e,zoom:t,scale:r},a){let{mapView:o}=$(a);return await yr(e,o,{zoom:t,scale:r})}var br=l.object({center:l.object({longitude:l.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:l.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:l.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:l.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),vr=y(wr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:br});async function Sr(e,t){return await t.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function xr({zoom:e},t){let{mapView:r}=$(t);return await Sr(e,r)}var Tr=l.object({zoom:l.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Er=y(xr,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:Tr}),Se=[Qt,Zt,er,or,lr,mr,fr,vr,Er],Le=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LSGRWCAO.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./KKHKKCYH.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./KQ6LEQHH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./MZJGADGH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./5PT7ZFXF.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./K35QKERW.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./ESTSYVJP.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./CFT5BBC6.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./SFREIREB.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./DMLSCJAM.js").then(e=>e.default)});async function R(e){let t=Object.entries(Le).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
8
+ Available prompts:
9
+ ${Object.keys(Le).join(`
10
+ `)}`);return await t[1]()}async function Ir(e,t){let r=await R("navigation_tool_prompt"),{mapView:a}=$(t),o=a.map,n=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((h,w)=>`${w+1}. layerId=${h.id} | title=${h.title??""} | name=${h.name??""} | score=${h.score.toFixed(2)}`).join(`
11
+ `):"",s=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",i=e.intent==="goToBookmark"&&o.bookmarks?.length?`Available bookmarks:
12
+ ${JSON.stringify(o.bookmarks,null,2)}`:"",d=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
13
+ ${n}`:"",c=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
14
+ ${s}`:"",u={intent:e.intent,bookmarksSection:i,layersSection:d,fieldsSection:c,currentZoom:a.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},m=await D({promptText:r,modelTier:"fast",inputVariables:u,tools:Se}),p=(m.tool_calls?.length??0)>0,v=typeof m.text=="string"?m.text.trim():"",b=v.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:p?m:void 0},outputMessage:p?e.outputMessage:v,status:p?e.status:b?"success":"failed"}}var U=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r};async function kr(e,t){let r=new A(Se);try{let a=e.navigationInternalState.toolCallMessage;if(!a)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let o=(await r.invoke({messages:[a]},t)).messages.map(n=>n.text).join(`
15
+ `);return await g({text:`Finished executing navigation tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?U(o):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await g({text:`Navigation tool execution failed: ${o}`},t),{...e,outputMessage:`Navigation tool execution failed: ${o}`,status:"failed",summary:`Navigation tool execution failed: ${o}`,navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}}async function $r(e,t){let r=await R("navigation_intent_prompt"),{mapView:a}=$(t),o=Se.map(m=>({name:m.name,description:m.description,schema:m.schema})),n=a.map,s=n.bookmarks?.length?`Available bookmarks:
16
+ ${JSON.stringify(n.bookmarks,null,2)}`:"",i={tools:o.map(({name:m,description:p,schema:v})=>`${m}: ${p}, ${JSON.stringify(v)}`).join(`
17
+ `),bookmarks:s,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},d=l.object({intent:l.string()}),c=await Ne({promptText:r,inputVariables:i,schema:d,modelTier:"fast"}),u=typeof c.intent=="string"?c.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var x=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},_r=.7,Nr=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=(await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:_r,embeddingCache:o})).map(({id:i,score:d})=>{let c=a.get(i)?.layerItem;return{id:i,title:c?.title,name:c?.name??void 0,score:d}}),s;return n.length>0?s=`Vector search completed. Matching layers:
18
+ ${n.map(i=>`- layerId=${i.id} | title=${i.title??""} | name=${i.name??""} | score=${i.score.toFixed(2)}`).join(`
19
+ `)}`:s="Vector search completed. No matching layers found.",await g({text:s},t),{...e,vectorSearchLayerResults:n}}catch(r){throw await g({text:`Error during vector search layers: ${r instanceof Error?r.message:String(r)}`},t),r}},ze=.7,Fr=10,Mr=async(e,t)=>{try{await g({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=e.vectorSearchLayerResults?.map(d=>d.id)??[];if(n.length===0)return await g({text:"No candidate layers for field search"},t),e;let s=(await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:n,minScore:ze,topResults:Fr,embeddingCache:o})).map(({layerId:d,results:c})=>{let u=a.get(d)?.fieldRegistry;return{layerId:d,layerName:a.get(d)?.layerItem.name,results:c.map(m=>{let p=u?.get(m.name);return{name:m.name,score:m.score,type:p?.type,alias:p?.alias,description:p?.description,statistics:p?.statistics}})}}),i;return s.length>0?i=`Vector search completed. Matching layers and fields:
20
+ ${s.map(d=>`${d.layerName??d.layerId}:
21
+ ${d.results.map(c=>` - ${c.name} (${c.score.toFixed(2)})`).join(`
22
+ `)}`).join(`
23
+ `)}`:i=`No vector search field results found for score over ${ze}.`,await g({text:i},t),{...e,vectorSearchFieldResults:s}}catch(r){throw await g({text:`Error during vector search fields: ${r instanceof Error?r.message:String(r)}`},t),r}},ae=(e,t)=>(r,a)=>{let o=a?.configurable?.services;for(let n of e)if(!o?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r},Cr=(e,t)=>ae(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),qr=()=>new q(Ue).addNode("requireNavigationServices",Cr).addNode("intentLLM",$r).addNode("vectorSearchLayers",Nr).addNode("vectorSearchFields",Mr).addNode("agent",Ir).addNode("tools",kr).addEdge(C,"requireNavigationServices").addEdge("requireNavigationServices","intentLLM").addConditionalEdges("intentLLM",e=>e.intent==="goToLayer"||e.intent==="goToFeatures"?"vectorSearchLayers":"agent",{vectorSearchLayers:"vectorSearchLayers",agent:"agent"}).addConditionalEdges("vectorSearchLayers",e=>e.intent==="goToFeatures"?"vectorSearchFields":"agent",{vectorSearchFields:"vectorSearchFields",agent:"agent"}).addEdge("vectorSearchFields","agent").addEdge("agent","tools").addEdge("tools",E),Ar=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
24
+ This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
25
+
26
+ Supported actions:
27
+ - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
28
+ - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
29
+ - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
30
+ - **Layers**: Zoom to the full extent of a specific layer (e.g., "Go to the water mains layer"). For the purposes of link charts, if the user requests to go to the extent of a link chart or the entities/nodes within it, that should be treated as a request to use the goToLayer tool on the link chart layer
31
+ - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
32
+ - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
33
+ - **Extents**: Reset to the initial web map extent or zoom to the full world extent (e.g., "Reset the map", "Zoom to the full world extent").
34
+ - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
35
+
36
+ _Example: “Zoom to Texas”_
37
+ _Example: “Go to the water mains layer”_
38
+ _Example: “Zoom to to the extent of my link chart”_
39
+ _Example: “Center the map on San Francisco at scale 50000”_
40
+ _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
41
+ _Example: “Go to the Downtown bookmark”_
42
+ _Example: “Where is Mount Rainier?”_`,Us={id:"navigation",name:"Navigation Agent",description:Ar,createGraph:qr,workspace:Ue},We=f.Root({agentExecutionContext:f({reducer:K,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:f({reducer:Q,default:()=>""}),summary:f({reducer:I,default:()=>""}),status:f({reducer:I}),vectorSearchLayerIds:f(),vectorSearchFieldResults:f(),layerFieldInfo:f(),queryResponse:f(),dataExplorationMessages:f({reducer:G,default:()=>[]})}),Rr=async(e,t)=>(await g({text:"Exiting Data Exploration agent"},t),e),xe=async(e,t)=>{let r=e.tool_calls??[];if(r.length===0){await g({text:`LLM did not request any tool calls: ${String(e?.content)}`},t);return}await Promise.all(r.map(async a=>await g({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},t)))},Lr=["mapView"];function L(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=Lr.filter(a=>!(a in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var zr=e=>{let t=e.map?.allLayers.filter(a=>a.type==="feature"),r=0;return t?.forEach(a=>{let o=a;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},jr=async(e,t)=>{let{mapView:r}=L(t);return zr(r)},Dr=y(jr,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:l.object({})}),Or=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let a=r;a.featureEffect&&(a.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},Vr=async(e,t)=>{let{mapView:r}=L(t);return await Or(r)},Gr=y(Vr,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:l.object({})});function te(e){return"point"in e&&e.point!==void 0}function P(e){return"layerId"in e&&e.layerId!==void 0}var oe=async(e,t)=>{if(te(e)){let{point:r}=e;return{geometry:new we({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(P(e)){let r=t.map?.allLayers.find(o=>o.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=r.title??r.id;try{let o=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!o.features.length)return{error:`No features found in geometry layer "${a}" with the specified where clause: ${e.where}`};let n;if(o.features.length===1){let s=o.features[0].geometry;if(!s)return{error:"The geometry of the first feature is undefined or null."};n=s}else{let s=o.features.map(d=>d.geometry),i=Be.executeMany(s);if(!i)return{error:"Failed to create a combined geometry."};n=i}return n.spatialReference||(n.spatialReference=t.spatialReference),{geometry:n}}catch(o){return{error:`Failed to query geometry: ${String(o)}`}}}return{error:"Invalid geometry configuration provided"}},Pr=async(e,t,r,a,o,n)=>{let s=e.map?.allLayers.find(d=>d.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let i=s.createQuery();i.where=r??"1=1",a&&(i.geometry=a,i.spatialRelationship="intersects",o&&(i.distance=o),n&&(i.units=n));try{let{extent:d,count:c}=await s.queryExtent(i);return!d||c===0?{success:!1,error:`No features found for filter (where: ${i.where}${a?", spatial filter used":""})`}:(await e.goTo(d),{success:!0})}catch(d){return{success:!1,error:d instanceof Error?d.message:String(d)}}},Br=async(e,t,r,a,o,n)=>{let s=t.map?.allLayers.find(m=>m.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let i;if(o){let m=await oe(o,t);if("error"in m)return m.error;i=m.geometry}if(s.featureEffect=null,s.featureEffect=new ft({filter:new Pe({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:a}),s.visible=!0,n)return`Applied feature effects to "${s.title??e.layerId}" within current map extent.`;let d=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,c=await Pr(t,e.layerId,d,i,o?.distance,o?.units),u=s.title??e.layerId;return c.success?`Applied feature effects to target layer "${s.title??e.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${u}" but no features matched. ${c.error}`},Kr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],z=l.enum(Kr),Qr=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:a="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:s}=L(n);return await Br(e,s,a,o,t,r)},Ur=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),Wr=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),Hr=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer on which to set a feature effect."),where:l.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:l.array(l.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:l.union([Ur,Wr]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:l.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:l.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:l.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),Zr=y(Qr,{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:Hr}),he=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},Jr=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Yr=e=>{if(typeof e=="string"&&e)return e;let t=he(e);return t?t.toISOString().slice(0,10):null},He=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),a=(Math.abs(e)%60).toString().padStart(2,"0"),o=`${t}${r}:${a}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:o}},Xr=(e,t,r)=>{let a=t?.toLowerCase();if(a==="date-only"){let n=Yr(e);return n?yt(n,Y("short-date")):e}if(a==="time-only"){if(typeof e=="string"&&e)return wt(e,Y("long-time"));let n=he(e);return n?Ce(n,{...Y("long-time"),timeZone:"UTC"}):e}let o=he(e);return o?Ce(o,{...Y("short-date-short-time"),timeZone:Jr(r)}):e},Ze=(e,t,r)=>{if(e&&typeof e!="function"){let a="getField"in r&&r.getField?.(e),o=a&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(a.name):null;if(o?.type==="coded-value"){let n=o.codedValues.find(s=>s.code===t);return n?n.name:null}}return null},ea=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,ta=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},ra=(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}},aa=(e,t,r)=>{let a=ta(e);if(!a)return e;let o={};t.dateStyle?o.dateStyle=t.dateStyle:(t.year&&(o.year=t.year),t.month&&(o.month=t.month)),t.timeStyle&&(o.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?o.hour12=!0:t.timeStyle&&t.hour12==="never"&&(o.hour12=!1),o.timeZone=ea(r);try{return new Intl.DateTimeFormat(void 0,o).format(a)}catch{return e}},Je=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,Ye=(e,t,r,a,o)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?ra(r,n):n?.type==="date-time"?aa(r,n,o):Xr(r,a,o)},oa=(e,t,r,a)=>{let o=e.fieldsIndex?.get(t),n=Ze(t,r,e)??r;return Ye(e,t,n,o?.type,a)},na=(e,t)=>Je(e,t),Xe=(e,t,r)=>{let a=e.objectIdField,o=t.features.map(s=>s.attributes[a]),n=t.features.map(s=>{let i=s.attributes,d={};return e.fields.forEach(c=>{if(!Object.hasOwn(i,c.name))return;let u=i[c.name];if(c.name===a){d[c.name]=u;return}let m=Ze(c.name,u,e)??u,p=Je(e,c.name);d[p]=Ye(e,c.name,m,c.type,r)}),d});return{objectIds:o,attributes:n}},ia=(e,t,r)=>{let a=e.createQuery();return a.outFields=[t],a.where=r||"1=1",a.num=1,a},sa=async(e,t,r,a)=>{let o=a.map?.allLayers.find(u=>u.id===e),n=ia(o,t,r.where),s=(await o.queryFeatures(n)).features[0],i=s?s.attributes[t]:null,d=oa(o,t,i,a.timeZone),c=na(o,t);return{tool:"getAttribute",layerName:o.title??e,summary:`${c} = ${d}`,details:{fieldName:t,fieldAlias:c!==t?c:void 0,value:d,where:r.where}}};async function la({layerId:e,fieldName:t,query:r},a){let{mapView:o}=L(a),n=await sa(e,t,r,o);return JSON.stringify(n,null,2)}var ca=l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:l.string().describe("The name of the field/attribute from which to get a field value."),query:l.object({where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),da=y(la,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:ca}),Te=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function re(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var ua=async e=>{let{targetLayer:t,fieldName:r,statisticType:a,mapView:o,layersAndFieldsRegistry:n,geometryFilter:s}=e,i=o.map?.allLayers.find(S=>S.id===t.layerId);if(!i)throw new Error(`Layer '${t.layerId}' not found.`);let d=await o.whenLayerView(i),c=n.get(t.layerId)?.fieldRegistry.get(r),u=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let m,p;if(s){let S=await oe(s,o);if("error"in S)throw new Error(S.error);if(!S.geometry)throw P(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");if(P(s)){let T=o.map?.allLayers.find(N=>N.id===s.layerId);m={geometryLayerName:T?.title??T?.id,geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}}else te(s)&&(m={point:s.point,distance:s.distance,units:s.units,applied:!0});p=new Pe({geometry:S.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let v=Te(d,[r],!1),b=null,h=null,w=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let S={layer:i,useFeaturesInView:v,view:v?o:void 0,field:r,sqlWhere:re(i.definitionExpression,t.where),...p&&{filter:p},outStatisticTypes:{include:[a]}};b=await Ke(S);let T=["string","small-integer","integer"],N=c.domain?.type==="coded-value"?c.domain:null;(T.includes(c.type)||N)&&(h=(await Qe({layer:i,useFeaturesInView:v,view:v?o:void 0,field:r,sqlWhere:re(i.definitionExpression,t.where),...p&&{filter:p}})).uniqueValueInfos.sort((M,W)=>W.count-M.count).slice(0,w)),h&&c.domain?.type==="coded-value"&&(h=h.map(M=>({...M,value:N?N.getName(M.value)??M.value:M.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:i.title??t.layerId,summary:`${a} = ${typeof b?.[a]=="number"?b[a]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:a,statistic:b?.[a]??null,summaryStatistics:b,uniqueValues:h,where:t.where,spatialFilterInfo:m}}};async function ma({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:a},o){let n=x(o,"layersAndFieldsRegistry"),{mapView:s}=L(o),i=await ua({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:a});return JSON.stringify(i,null,2)}var pa=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),ha=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),ga=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:l.union([pa,ha]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:l.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:l.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),fa=y(ma,{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.
43
+
44
+ USE THIS TOOL FOR:
45
+ - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
46
+ - "Most common/frequent value of [field]?" \u2014 frequency analysis
47
+ - Questions requiring a mathematical aggregation across many features
48
+
49
+ DO NOT USE FOR:
50
+ - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
51
+ - "Show / list / find features" \u2014 use queryFeatures instead
52
+ - Simple counts of features matching a condition \u2014 use queryFeatures instead
53
+
54
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:ga}),ya=async(e,t,r,a,o)=>{let n=r.map?.allLayers.find(p=>p.id===e.layerId),s=await r.whenLayerView(n),i=n.title??e.layerId,d;if(a){let p=await oe(a,r);if("error"in p)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:p.error}};if(!p.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};d=p.geometry}else o&&(d=r.extent.clone());let c=t.groupByFields&&t.groupByFields.length>0,u=n.objectIdField,m=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,u])];try{let p;if(c){let h=new bt({where:e.where||"1=1",outFields:m,orderByFields:e.orderByFields,geometry:d,spatialRelationship:d?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new vt({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});p=await n.queryTopFeatures(h)}else{let h=n.createQuery();h.where=re(n.definitionExpression,e.where||"1=1"),h.outFields=m.length?m:["*"],h.orderByFields=t.orderByFields,h.num=t.topCount,d&&(h.geometry=d,h.spatialRelationship="intersects"),a?.distance&&(h.distance=a.distance),a?.units&&(h.units=a.units),h.outSpatialReference=r.spatialReference;let w=Te(s,e.outFields,o??!1);try{p=w?await s.queryFeatures(h):await n.queryFeatures(h)}catch(S){console.warn("Client-side query failed, falling back to server:",S),p=await n.queryFeatures(h)}}let v=p.features.map(h=>h.attributes[u]),{attributes:b}=Xe(n,p,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:b,objectIds:v,objectIdField:u,where:e.where,orderByFields:t.orderByFields,...c&&{groupByFields:t.groupByFields}}}}catch(p){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:p instanceof Error?p.message:String(p)}}}},wa=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:a},o)=>{let{mapView:n}=L(o),s=await ya(e,t,n,r,a);return JSON.stringify(s,null,2)},ba=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),va=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),Sa=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:l.union([ba,va]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:l.object({topCount:l.number().describe("Number of top features to return per group."),orderByFields:l.array(l.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:l.array(l.string().describe("Field(s) to group results by. Returns top N per group."))}),useCurrentExtent:l.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),xa=y(wa,{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:Sa}),me=25,Ta=async(e,t,r,a)=>{let o=t.map?.allLayers.find(h=>h.id===e.layerId),n=await t.whenLayerView(o),s=o.title??e.layerId,i;if(r){let h=await oe(r,t);if("error"in h){let w={error:h.error};if(P(r)){let S=t.map?.allLayers.find(T=>T.id===r.layerId);w.geometryLayerName=S?.title??S?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else te(r)&&(w.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:w}}if(!h.geometry){let w={};if(P(r)){let S=t.map?.allLayers.find(T=>T.id===r.layerId);w.error=`No features found matching: ${r.where}`,w.geometryLayerName=S?.title??S?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else te(r)&&(w.error="Failed to create point geometry",w.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:w}}i=h.geometry}else a&&(i=t.extent.clone());let d=Te(n,e.outFields,a??!1),c=o.objectIdField,u=o.createQuery();u.where=re(o.definitionExpression,e.where||"1=1"),u.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,c])],u.orderByFields=e.orderByFields,i&&(u.geometry=i,u.spatialRelationship="intersects"),r?.distance&&(u.distance=r.distance),r?.units&&(u.units=r.units),u.outSpatialReference=t.spatialReference;let m,p;try{m=d?await n.queryFeatureCount(u):await o.queryFeatureCount(u),m>0&&m<=me&&(p=d?await n.queryFeatures(u):await o.queryFeatures(u))}catch(h){console.warn("Client-side query failed, falling back to server:",h),m=await o.queryFeatureCount(u),m>0&&m<=me&&(p=await o.queryFeatures(u))}let{objectIds:v,attributes:b}=p?Xe(o,p,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:s,summary:`${m} features found`,details:{totalCount:m,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...v&&{objectIds:v,objectIdField:c},...b&&{attributes:b},...m>me&&{note:`${m} features found.`}}}};async function Ea({targetLayer:e,geometryFilter:t,useCurrentExtent:r},a){let{mapView:o}=L(a),n=await Ta(e,o,t,r);return JSON.stringify(n,null,2)}var Ia=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),ka=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),$a=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:l.union([Ia,ka]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:l.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),_a=y(Ea,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
55
+
56
+ USE THIS TOOL FOR:
57
+ - "Show / display / list features where..." \u2014 finding and listing features
58
+ - "How many X are Y?" \u2014 counting features that match a condition
59
+ - "Which features..." / "Find features..." \u2014 identifying specific features
60
+ - Spatial queries \u2014 finding features near/within/intersecting other features
61
+ - Any question where the user wants to SEE or COUNT matching features
62
+
63
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:$a}),et=[da,fa,xa,_a],tt=[Zr,Gr,Dr],Na=async(e,t)=>{await g({text:"Requesting LLM for layer filter results"},t);let r=await R("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=He(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await D({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:tt}),i=[...e.dataExplorationMessages,s];if(!((s.tool_calls?.length??0)>0))return await g({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:i};let d=[...i,s],c=s.content.toString();return await xe(s,t),{...e,dataExplorationMessages:d,outputMessage:c}},Fa=async(e,t)=>{await g({text:"Requesting LLM for layer query results"},t);let r=await R("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=He(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await D({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:et}),i=s.content.toString();return await xe(s,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,s],outputMessage:i,status:"success",summary:i?U(i):"Query executed."}},Ma=async(e,t)=>{try{await g({text:"Requesting LLM for summary on query results"},t);let r=await R("summarize_query_response_prompt"),a={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await _e({promptText:r,modelTier:"fast",messages:e.dataExplorationMessages,inputVariables:a}),n=typeof o=="string"?o:o.content,s=new ce(n);await g({text:`Received response from LLM: ${n}`},t);let i=n;return{...e,outputMessage:i,status:"success",summary:i?U(i):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,s]}}catch(r){throw await g({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${r instanceof Error?r.message:String(r)}`)}};async function Ca(e,t){let r=await new A(tt).invoke({messages:e.dataExplorationMessages},t);return await g({text:`Finished executing layer filter tool: ${r.messages.map(a=>a.content).join(", ")}`},t),{...e}}var qa=new A(et);async function Aa(e,t){let{messages:r}=await qa.invoke({messages:e.dataExplorationMessages},t),a=[],o=[];for(let n of r){let s=n.content,i;typeof s!="string"&&(i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:s}});try{typeof s=="string"?i=JSON.parse(s):i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:s}}}catch{i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:s}}}a.push(i),i.details&&typeof i.details=="object"&&"error"in i.details?o.push(`- ${i.tool}: Error - ${String(i.details.error)}`):o.push(`- ${i.layerName}: ${i.summary}`)}return await g({text:`Finished executing layer query tool: ${o.join(", ")}`},t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,...r],queryResponse:a,status:"success",outputMessage:o.join(`
64
+ `),summary:o.length>0?U(o.join(`
65
+ `)):"Query executed."}}var Ra=10,La=["string","small-integer","integer"],za=async(e,t,{includeSummaryStatistics:r=!0,includeUniqueValues:a=!0}={})=>{let o=null,n=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){r&&(o=await Ke({layer:e,field:t.name}));let s=t.domain?.type==="coded-value"?t.domain:null;a&&(La.includes(t.type)||s)&&(n=(await Qe({layer:e,field:t.name})).uniqueValueInfos.sort((i,d)=>d.count-i.count).slice(0,Ra),s&&(n=n.map(i=>({...i,value:s.getName(i.value)??i.value}))))}}catch(s){console.error(`Error fetching statistics for field ${t.name}:`,s)}return{summaryStatistics:o,uniqueValues:n}};function ja(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function Da(e,t,r,a=!0){let o=[],n=[],s=[];for(let i of e){let d=function(b){let h=t.get(b)?.layerItem;return h?[h.name&&`Name: ${h.name}`,h.title&&`Title: ${h.title}`,h.description&&`Description: ${h.description}`].filter(Boolean).join(" | "):b},{layerId:c,results:u}=i,m=r.map?.allLayers.find(b=>b.id===c),p=t.get(c)?.fieldRegistry;if(!p)continue;let v=o.find(b=>b.layerId===c);v||(v={layerId:c,layerSummary:d(c),fieldInfos:[]},o.push(v));for(let b of u){let h=p.get(b.name);if(!h)continue;let w=h.statistics,S=a&&!w?.summaryStatistics,T=ja(h.type,h.domain?.type)&&!w?.uniqueValues,N=S||T;if(s.push({layerId:c,fieldName:h.name,didFetchStatistics:N}),N){let M=za(m,h,{includeSummaryStatistics:S,includeUniqueValues:T}).then(W=>{let H={summaryStatistics:w?.summaryStatistics??null,uniqueValues:w?.uniqueValues??null};S&&(H.summaryStatistics=W.summaryStatistics),T&&(H.uniqueValues=W.uniqueValues),p.set(h.name,{...h,statistics:H}),h.statistics=H});n.push(M)}v.fieldInfos.push(h)}}return await Promise.all(n),{layerFieldInfo:o,didFetchStatistics:n.length>0,fieldStatisticsFetchStatus:s}}var je=/\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 Oa(e,t){return je.test(e)||je.test(t)}var Va=async(e,t)=>{try{await g({text:"Preparing field information for vector search results"},t);let r=x(t,"layersAndFieldsRegistry"),{mapView:a}=L(t),{assignedTask:o,userRequest:n}=e.agentExecutionContext,s=Oa(o,n),{layerFieldInfo:i,didFetchStatistics:d,fieldStatisticsFetchStatus:c}=await Da(e.vectorSearchFieldResults,r,a,s);d?await g({text:"Statistics fetched"},t):await g({text:"Statistics skipped"},t);for(let u of c)await g({text:` - ${u.fieldName} - stats ${u.didFetchStatistics?"fetched":"skipped"}`},t);return await g({text:"Field information prepared"},t),{...e,layerFieldInfo:i}}catch(r){throw await g({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${r instanceof Error?r.message:String(r)}`)}},De=.7,Ga=10,Pa=async(e,t)=>{try{await g({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:De,topResults:Ga,embeddingCache:o}),s=n.map(({layerId:d,results:c})=>{let u=c.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
66
+ `);return`${a.get(d)?.layerItem.name??d}:
67
+ ${u}`}).join(`
68
+ `),i;return n.length>0?i=`Vector search completed. Matching layers and fields with scores:
69
+ ${s}`:i=`No vector search results found for score over ${De}.`,await g({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Ba=.7,Ka=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Ba,embeddingCache:o}),s=n.map(c=>c.id),i=n.map(({id:c,score:u})=>`${a.get(c)?.layerItem.name??c} (${u.toFixed(2)})`).join(`
70
+ `),d;return s.length>0?d=`Vector search completed. Matching layers with scores:
71
+ ${i}`:d="Vector search completed. No matching layers found.",await g({text:d},t),{...e,vectorSearchLayerIds:s}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Qa=(e,t)=>ae(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),Ua=()=>new q(We).addNode("requireDataExplorationServices",Qa).addNode("vectorSearchLayers",Ka).addNode("vectorSearchFields",Pa).addNode("fieldStatistics",Va).addNode("queryAgent",Fa).addNode("queryTools",Aa).addNode("summarizeQueryResponseLLM",Ma).addNode("filterAgent",Na).addNode("filterTools",Ca).addNode("earlyExit",Rr).addEdge(C,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),Wa=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
72
+ The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
73
+ _Example: “Only show stations where Brand is Shell”_
74
+ _Example: “Make Shell stations stand out on the map”_
75
+ _Example: “Gray out all stations that aren’t Shell”_
76
+ This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
77
+ _Example: “How many features are there?”_
78
+ _Example: “What’s the average population?”_
79
+ _Example: “Which values are in the status field?”_`,Ws={id:"dataExploration",name:"Data Exploration Agent",description:Wa,createGraph:Ua,workspace:We},Oe=.7,Ha=10,Za=async(e,t)=>{try{await g({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Oe,topResults:Ha,embeddingCache:o}),s=n.map(({layerId:d,results:c})=>{let u=c.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
80
+ `);return`${a.get(d)?.layerItem.name??d}:
81
+ ${u}`}).join(`
82
+ `),i;return n.length>0?i=`Vector search completed. Matching layers and fields with scores:
83
+ ${s}`:i=`No vector search results found for score over ${Oe}.`,await g({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Ja=.7,Ya=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Ja}),n=o.map(d=>d.id),s=o.map(({id:d,score:c})=>`${a.get(d)?.layerItem.name??d} (${c.toFixed(2)})`).join(`
84
+ `),i;return n.length>0?i=`Vector search completed. Matching layers with scores:
85
+ ${s}`:i="Vector search completed. No matching layers found.",await g({text:i},t),{...e,vectorSearchLayerIds:n}}catch(r){throw await g({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}};async function Xa(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n?s=xt({basemapTheme:await qe(a),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:s=Tt({basemapTheme:await qe(a),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:a,attributes:t.map(i=>({field:i,label:r.fields.find(d=>d.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function eo(e){return await St(e)}async function to({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:n?"chart-size":"chart",fields:a,layer:i,view:s,colorSchemeTags:o};try{let c=await Xa(d),u=await eo(c);return i.renderer=u.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying chart renderer: ${c instanceof Error?c.message:String(c)}`}}var ro=["mapView"];function _(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=ro.filter(a=>!(a in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function ao({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await to({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var oo=l.object({layerId:l.string().describe("The id of the layer to apply the chart renderer to"),fields:l.array(l.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),no=y(ao,{name:"chart",description:`Label: Charts
86
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart.
87
+ Keywords: pie, chart, all categories, breakdown, proportion
88
+ Example: Show the total number of homes built in each decade using a pie chart for each feature.
89
+ Fields: This style requires 2-8 number fields.
90
+
91
+ Label: Charts and Size
92
+ 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.
93
+ Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
94
+ 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.
95
+ Fields: This style requires 2-8 number fields.`,schema:oo});function io(e){let{fields:t,layer:r,view:a,theme:o,colorSchemeTags:n}=e,s=t[0],i;return n&&(i=be({geometryType:r.geometryType,includedTags:n,theme:o||"high-to-low"})[0]),{layer:r,view:a,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function so(e){return await Et(e)}async function lo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=io(d),u=await so(c);return i.renderer=u.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function co({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await lo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var uo=l.object({layerId:l.string().describe("The id of the layer to apply the color-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),mo=y(co,{name:"color-age",description:`Label: Age (color)
96
+ 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.
97
+ Keywords: since, age, how old, how long
98
+ Example: Show the age of each feature based on its reported date.
99
+ Fields: This style requires at least one field with a date type.`,schema:uo});function po(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,{theme:n}=e,s=t[1],i=t[0],d;return o&&(d=be({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:i,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:d}}async function ho(e){return await It(e)}async function go({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=po(d),u=await ho(c);return i.renderer=u.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color renderer: ${c instanceof Error?c.message:String(c)}`}}async function fo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await go({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var yo=l.object({layerId:l.string().describe("The id of the layer to apply the color renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),wo=y(fo,{name:"color",description:`Label: Counts and Amounts (color)
100
+ Description: Vary color along a continuous color ramp to represent numeric or ranked data.
101
+ Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
102
+ Example: Color each feature based on the population density.
103
+ 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:yo});function bo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o,theme:n}=e,s,i,d=t[0];return o&&(i=be({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:d,normalizationField:s,theme:n,colorOptions:{colorScheme:i}}}async function vo(e){return await kt(e)}async function So({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"color-size-univariate",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=bo(d),u=await vo(c);return i.renderer=u.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying color-size-univariate renderer: ${c instanceof Error?c.message:String(c)}`}}async function xo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await So({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var To=l.object({layerId:l.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:l.array(l.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Eo=y(xo,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
104
+ Description: Vary symbol size and color based on the values of two numeric attributes.
105
+ Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
106
+ 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.
107
+ 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:To});function Io(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n;return o&&(n=_t({includedTags:o,numColors:Math.min(t.length,8)})[0]),{layer:r,view:a,legendOptions:{unit:"units"},attributes:t.map(s=>({field:s,label:r.fields.find(i=>i.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function ko(e){return await $t(e)}async function $o({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=Io(i),c=await ko(d);return s.renderer=c.renderer,s.visible=!0,`Dot Density renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying dot density renderer: ${d instanceof Error?d.message:String(d)}`}}async function _o({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await k({type:"show-legend",data:{layerIds:[e]}},a),await $o({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var No=l.object({layerId:l.string().describe("The id of the layer to apply the dot density renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Fo=y(_o,{name:"dot-density",description:`Dot Density
108
+ Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
109
+ **Use cases:**
110
+ - Population distribution visualization
111
+ - Comparing multiple categories within areas
112
+ - Showing spatial distribution patterns
113
+ **Examples:**
114
+ - Show the density of the population based on various race/ethnic groups
115
+ - Visualize distribution of different crops across regions
116
+ - Display demographic patterns within census tracts
117
+ **Fields:** Requires 2-8 number fields.
118
+ **Keywords:** density, how much, how many, total, number, amount`,schema:No});function Mo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s=t[0];return o&&(n=Ft({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:r,view:a,field:s,heatmapScheme:n}}async function Co(e){return await Nt(e)}async function qo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=Mo(i),c=await Co(d);return s.renderer=c.renderer,s.visible=!0,`Heatmap renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying heatmap renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ao({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await k({type:"show-legend",data:{layerIds:[e]}},a),await qo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Ro=l.object({layerId:l.string().describe("The id of the layer to apply the heatmap renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Lo=y(Ao,{name:"heatmap",description:`Label: Heat Map
119
+ Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
120
+ Keywords: density, heatmap, hot spots, pattern, cluster
121
+ Example: Create a heatmap
122
+ Fields: This typically requires zero or one field of type number.`,schema:Ro});function zo(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n&&(s=Ct({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:a,fields:t.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function jo(e){return await Mt(e)}async function Do({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:n?"predominance-size":"predominance",fields:a,layer:i,view:s,colorSchemeTags:o};try{let c=zo(d),u=await jo(c);return i.renderer=u.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying predominance renderer: ${c instanceof Error?c.message:String(c)}`}}async function Oo({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await Do({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var Vo=l.object({layerId:l.string().describe("The id of the layer to apply the predominance renderer to"),fields:l.array(l.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),Go=y(Oo,{name:"predominance",description:`Label: Predominant category
123
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
124
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
125
+ Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
126
+ Fields: This style relies on 2-10 number fields.
127
+
128
+ Label: Predominant category and Size
129
+ 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.
130
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
131
+ Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
132
+ Fields: This style relies on 2-10 number fields.`,schema:Vo});function Po(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s={field:t[0]},i={field:t[1]};return o&&(n=At({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field1:s,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function Bo(e){return await qt(e)}async function Ko({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(d=>d.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:a,layer:s,view:n,colorSchemeTags:o};try{let d=Po(i),c=await Bo(d);return s.renderer=c.renderer,s.visible=!0,`Relationship renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(d){return`Error applying relationship renderer: ${d instanceof Error?d.message:String(d)}`}}async function Qo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=_(a);return await k({type:"show-legend",data:{layerIds:[e]}},a),await Ko({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Uo=l.object({layerId:l.string().describe("The id of the layer to apply the relationship renderer to"),fields:l.array(l.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Wo=y(Qo,{name:"relationship",description:`Label: Relationship
133
+ Description: Overlays two color ramps to represent the relationship between two numeric attributes.
134
+ Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
135
+ Example: Show the relationship between tree height and carbon storage
136
+ Fields: This style requires two number fields.`,schema:Uo});function Ho(e){let{fields:t,layer:r,view:a,theme:o}=e,n=t[0];return{layer:r,view:a,startTime:n,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Zo(e){return await Rt(e)}async function Jo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"size-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=Ho(d),u=await Zo(c);return i.renderer=u.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying size-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function Yo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await Jo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Xo=l.object({layerId:l.string().describe("The id of the layer to apply the size-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),en=y(Yo,{name:"size-age",description:`Label: Age (size)
137
+ 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.
138
+ Keywords: since, age, how old, how long
139
+ Example: Change the size of features so older features are larger than new features.
140
+ Fields: This style requires at least one field with a date type.`,schema:Xo});function tn(e){let{fields:t,layer:r,view:a}=e,{theme:o}=e,n=t[1],s=t[0];return{layer:r,view:a,field:s,normalizationField:n,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function rn(e){return await Lt(e)}async function an({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"size",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=tn(d),u=await rn(c);return i.renderer=u.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying size renderer: ${c instanceof Error?c.message:String(c)}`}}async function on({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await an({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var nn=l.object({layerId:l.string().describe("The id of the layer to apply the size renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),sn=y(on,{name:"size",description:`Label: Counts and Amounts (size)
141
+ Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
142
+ Keywords: graduated size, proportional size, how much, total, number, amount, size
143
+ Example: Vary the size of each point based on the total population.
144
+ 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.
145
+
146
+ Label: Continuous Timeline (size)
147
+ Description: Vary symbol sizes along a continuous ramp to represent dates.
148
+ Keywords: graduated size, proportional size, classed size, how much, total, number, when
149
+ Example: Vary the size of each feature based on the date a ticket was completed.
150
+ Fields: This style requires a single field with a date type.`,schema:nn});function ln(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n=t[0],s=t[1],i=t[2],d;return o&&(d=jt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field:n,field2:s,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:d}}async function cn(e){return await zt(e)}async function dn({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let d={styleName:"type",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let c=ln(d),u=await cn(c);return i.renderer=u.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(c){return`Error applying type renderer: ${c instanceof Error?c.message:String(c)}`}}async function un({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=_(o);return await k({type:"show-legend",data:{layerIds:[e]}},o),await dn({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var mn=l.object({layerId:l.string().describe("The id of the layer to apply the type renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),pn=y(un,{name:"type",description:`Label: Types (unique symbols)
151
+ Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
152
+ Keywords: categorical, category, type, unique, discrete, point of interest, region, group
153
+ Example: Color each feature based on the region it belongs to
154
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:mn}),rt=[no,mo,wo,Eo,Fo,Lo,Go,Wo,en,sn,pn],at=(e,t=3)=>{let r=e.map((o,n)=>o.type==="human"?n:-1).filter(o=>o!==-1);if(r.length===0)return[];let a=r.length>t?r[r.length-t]:r[0];return e.slice(a)},hn=async(e,t)=>{await g({text:"Requesting LLM for layer query results"},t);let r=await R("navigation_intent_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await D({promptText:r,modelTier:"advanced",messages:at(e.agentExecutionContext.messages),inputVariables:a,tools:rt});return await xe(o,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,o]}}};async function gn(e,t){let r=await new A(rt).invoke({messages:at(e.agentExecutionContext.messages)},t),a=r.messages.map(n=>n.text).join(`
155
+ `);await g({text:`Finished executing layer filter tool: ${a}`},t);let o=r.messages.map(n=>n.text).join(`
156
+ `);return{...e,outputMessage:o}}var ot=f.Root({agentExecutionContext:f({reducer:K,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:f({reducer:Q,default:()=>""}),vectorSearchLayerIds:f(),vectorSearchFieldResults:f(),layerFieldInfo:f(),selectedLayerId:f()}),fn=async(e,t)=>(await g({text:"Exiting Layer Styling agent"},t),e),yn=async(e,t)=>{try{await g({text:"Populating layer and field info"},t);let r=[];for(let a of e.vectorSearchFieldResults){let o=function(u){let m=i.get(u)?.layerItem;return m?[m.name&&`Name: ${m.name}`,m.title&&`Title: ${m.title}`,m.description&&`Description: ${m.description}`].filter(Boolean).join(" | "):u},{layerId:n,results:s}=a,i=x(t,"layersAndFieldsRegistry"),d=i.get(n)?.fieldRegistry;if(!d)continue;let c=r.find(u=>u.layerId===n);c||(c={layerId:n,layerSummary:o(n),fieldInfos:[]},r.push(c));for(let u of s){let m=d.get(u.name);m&&c.fieldInfos.push(m)}}return await g({text:"Populated layerFieldInfo"},t),{...e,layerFieldInfo:r}}catch(r){throw await g({text:"Error populating layerFieldInfo"},t),new Error(`Error populating layerFieldInfo: ${r instanceof Error?r.message:String(r)}`)}},wn=(e,t)=>{let r=e.vectorSearchLayerIds??[];if(r.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=t.configurable;if(!a||a.agentId!==Ve.id||a.id!=="reviewLayerSelection"){let n={agentId:Ve.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...r]};throw new Ie(n)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},bn=(e,t)=>ae(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,t),vn=()=>new q(ot).addNode("requireLayerStylingServices",bn).addNode("vectorSearchLayers",Ya).addNode("layerSelectionHITL",wn).addNode("vectorSearchFields",Za).addNode("populateLayerFieldInfo",yn).addNode("agent",hn).addNode("tools",gn).addNode("earlyExit",fn).addEdge(C,"requireLayerStylingServices").addEdge("requireLayerStylingServices","vectorSearchLayers").addConditionalEdges("layerSelectionHITL",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"populateLayerFieldInfo":"earlyExit").addEdge("populateLayerFieldInfo","agent").addEdge("agent","tools").addEdge("tools",E).addEdge("earlyExit",E),Sn=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
157
+ _Example: “Color points by sales amount”_
158
+ _Example: “Show population density with a color gradient”_
159
+ _Example: “Create a relationship map between height and depth”_
160
+ _Example: “Vary circle sizes according to population”_`,Ve={id:"layerStyling",name:"Layer Styling Agent",description:Sn,createGraph:vn,workspace:ot},nt=f.Root({agentExecutionContext:f({reducer:K,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:f({reducer:Q,default:()=>""}),summary:f({reducer:I,default:()=>""}),status:f({reducer:I}),helpInternalState:f({reducer:I,default:()=>({toolCallMessage:void 0})})}),xn=(e,t)=>{let r=Array.from(e.values()).find(({layerItem:n})=>n.title?.toLowerCase().includes(t.toLowerCase()));if(!r){let n=Array.from(e.values()).map(s=>s.layerItem.title).join(", ");return`Could not find a layer matching "${t}". Available layers: ${n}`}let a=Array.from(r.fieldRegistry.values()),o=a.map(n=>`- **${n.alias||n.name}** (\`${n.name}\`, ${n.type})${n.description?`: ${n.description}`:""}`).join(`
161
+ `);return`**${r.layerItem.title}** has ${a.length} field(s):
162
+
163
+ ${o}`},Tn=async({layerTitle:e},t)=>{let r=x(t,"layersAndFieldsRegistry");return xn(r,e)},En=y(Tn,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:l.object({layerTitle:l.string().describe("The title or partial title of the layer to list fields for.")})}),it=[En],In=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:a},o)=>{let n=Array.from(a.values()).map(i=>i.name).slice(0,10).join(", "),s=a.size>10?` (and ${a.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
164
+ Fields: ${n}${s}`}).join(`
165
+
166
+ `);return`This map contains ${e.size} layer(s):
167
+
168
+ ${t}`},kn=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: ${r.agent.description}`).join(`
169
+ `):"No agents currently available."};async function $n(e,t){let r=await R("help_prompt"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"agentRegistry");try{let n=await D({promptText:r,modelTier:"fast",tools:it,inputVariables:{layerSummary:In(a),agents:kn(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}}),s=(n.tool_calls?.length??0)>0,i=typeof n.text=="string"?n.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:s?n:void 0},outputMessage:s?e.outputMessage:i,summary:s?"Prepared help tool call from assigned task.":"Provided map-related help based on the assigned task.",status:s?e.status:"success"}}catch(n){let s=n instanceof Error?n.message:String(n);return{...e,outputMessage:`Error invoking help agent: ${s}`,summary:"Help agent execution failed.",status:"failed"}}}var _n=(e,t)=>ae(["agentRegistry"],"Help Agent")(e,t);async function Nn(e,t){let r=new A(it);try{let a=e.helpInternalState.toolCallMessage;if(!a)throw new Error("helpToolCalling: missing helpInternalState.toolCallMessage");let o=(await r.invoke({messages:[a]},t)).messages.map(n=>n.text).join(`
170
+ `);return await g({text:`Finished executing help tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?U(o):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await g({text:`Help tool execution failed: ${o}`},t),{...e,outputMessage:`Help tool execution failed: ${o}`,status:"failed",summary:`Help tool execution failed: ${o}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var Fn=()=>new q(nt).addNode("requireHelpServices",_n).addNode("agent",$n).addNode("tools",Nn).addEdge(C,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":E).addEdge("tools",E),Mn=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
171
+
172
+ _Example: “Tell me about this map”_
173
+ _Example: “List all layers in this map”_
174
+ _Example: “List fields in protected areas layer”_
175
+ _Example: “What agents are available to me?”_
176
+ _Example: “What can you do?”_
177
+ _Example: “What can I ask”_
178
+
179
+ Even if the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent.
180
+
181
+ IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond accordingly.
182
+ _Example: "Create a chart"_
183
+ _Example: "Create a table"_`,Hs={id:"help",name:"Help Agent",description:Mn,createGraph:Fn,workspace:nt},Zs=f.Root({agentExecutionContext:f({reducer:K,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:f({reducer:Q,default:()=>""}),summary:f({reducer:I,default:()=>""}),status:f({reducer:I,default:()=>"success"}),intent:f({reducer:(e,t)=>t}),arcgisKnowledgeMessages:f({reducer:G,default:()=>[]})}),X={conversationId:""},Cn=["linkChartView"],pe=["knowledgeGraph","linkChartView"];function ne(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=Cn.filter(a=>!(a in t));if(r.length)throw new Error(`Link Chart context missing: ${r.join(", ")}`);return t}async function ie(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=pe.find(a=>a in t);if(!r||pe.every(a=>a in t))throw new Error(`Knowledge Graph context should be exactly one of ${pe.join(", ")}`);if(r==="knowledgeGraph")return t;{let a=t.linkChartView.map.knowledgeGraph.url;if(!a)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Dt(a)}}}var ge=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=fe.fromDataModel(t)}},fe=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let a of t.entityTypes)r.entityTypes.push(B.fromEntityType(a));for(let a of t.relationshipTypes)r.relationshipTypes.push(ye.fromRelationshipType(a));return r.identifierInfo={mappingInfo:{identifierMapsTo:qn(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}},B=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(t){let r=new e;r.name=t.name,r.alias=t.alias?t.alias:void 0,r.role=An(t.role);for(let a of t.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:Rn(a.role),geometryDef:a.fieldType==="esriFieldTypeGeometry"?{geometryType:a.geometryType??"esriGeometryAny",hasM:a.hasM?a.hasM:void 0,hasZ:a.hasZ?a.hasZ:void 0}:void 0};r.properties.push(o)}return r}},ye=class extends B{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=B.fromEntityType(t);r.observedEndPoints=[];for(let a of t.endPoints)r.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return r}},qn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},An=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function Rn(e){switch(e){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}async function Ln(e,t,r,a){let{graphQuery:o,explanation:n}=await se(e,t,r,a);return`Generated Graph Query:
184
+ ${o}
185
+
186
+ Explanation: ${n}`}async function se(e,t,r,a){let o={message:e,context:new ge(t)};X.conversationId&&(o.conversationId=X.conversationId),await g({text:"Attempting to generate a cypher query from your prompt..."},a);let n=await Ae(`${r}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Re.findCredential(j.getDefault().url)?.token??""}});if(n.httpStatus!==200)throw new Error(`Graph query service returned an error: ${n.httpStatus}`,{cause:n.data});X.conversationId||(X.conversationId=n.data.conversationId);let s=!1,i=Date.now(),d=n.data.sequenceNumber,c="",u="",m=1;for(;!s;){await new Promise(v=>setTimeout(v,1e3)),await g({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,m)}`},a),m=m%3+1;let p=await Ae(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:n.data.conversationId,inquiryId:n.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:Re.findCredential(j.getDefault().url)?.token??""}});if(p.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${p.httpStatus}`,{cause:p.data});if(p.data.context)c=p.data.context.graphQuery,u=p.data.message||"";else if(!p.data.hasMore)s=!0;else if(Date.now()-i>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=p.data.sequenceNumber}return{graphQuery:c,explanation:u}}function zn(e){return typeof e!="object"||e===null?String(e):"details"in e&&typeof e.details=="object"&&e.details!==null&&"errorMessage"in e.details&&typeof e.details.errorMessage=="string"?e.details.errorMessage:"message"in e&&typeof e.message=="string"?e.message:String(e)}var st=async({kg:e,queryParams:t,targetStructure:r,targetStructureReducer:a,requestOptions:o,queryRowLimit:n,queryTimeoutMs:s})=>{let i=null,d=r,c=new AbortController,u=o?.signal,m=()=>{c.abort(u?.reason)};u&&(u.aborted?c.abort(u.reason):u.addEventListener("abort",m,{once:!0}));try{let p=await Ot(e,t,o);i=p.resultHeader;let v=p.resultRowsStream.getReader(),b=0,h=Date.now(),w=!1;for(;;){let{done:S,value:T}=await v.read();if(S)break;if(!w&&s&&Date.now()-h>s)return c.abort(),{type:"timeout"};for(let N of T){if(b++,n&&b>n)return c.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:d};d=a(d,N)}}}catch(p){return c.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:zn(p),error:p}}finally{u?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:d}};function ee(e,t){if(!(!e||typeof e!="object")){if(Dn(e))for(let r of e.path)ee(r,t);else if(jn(e))t.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let r of e)ee(r,t);else if(On(e))for(let r of Object.values(e.properties??{}))ee(r,t)}}function jn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Dn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function On(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function Vn(e,t){let r=[];for(let a of[...t.dataModel.entityTypes,...t.dataModel.relationshipTypes]){let o=e.getMemberIdsByType(a.name);for(let n of o)r.push({id:n,typeName:a.name})}return r}async function Gn(e,t,r,a,o){let{graphQuery:n,explanation:s}=await se(e,t.dataModel,r,o);await g({text:`Attempting to execute query: ${n.substring(0,500)}${n.length>500?"...":""}`},o);let i=await st({kg:t,queryParams:new ve({openCypherQuery:n}),targetStructure:new Map,targetStructureReducer:(d,c)=>{for(let u of c)ee(u,d);return d},requestOptions:{signal:o?.signal,timeout:o?.timeout}});if(i.type==="success"){let d=i.processedResult,c=Array.from(d.values());return await g({text:`Query Results parsed into ${c.length} unique relationships and entities. Atempting to add to link chart...`},o),await a.map.addRecords(c),a.goTo(a.map.diagramNodesExtent),`Link Chart updated successfully. Cypher Query used:
187
+ ${n}
188
+
189
+ Explanation: ${s}`}else throw new Error(`Failed to execute query. Reason: ${i.type==="aborted"?"Query was aborted.":i.type==="timeout"?"Query timed out.":`Error message: ${i.errorMessage}`}`)}async function Pn({prompt:e},t){let{knowledgeGraph:r}=await ie(t),{linkChartView:a}=ne(t),o=j.getDefault().helperServices,n=await R("arcgis_knowledge_current_lc_context"),s=Vn(a.map,r),i=`${e}
190
+
191
+ ${n}${JSON.stringify(s)}`;return await Gn(i,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Bn=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Js=y(Pn,{name:"addRecords",description:"Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt.",schema:Bn});async function Kn(e,t){return await t.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function Qn({layout:e},t){let{linkChartView:r}=ne(t);return await Kn(e,r)}var Un=l.object({layout:l.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),Ys=y(Qn,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:Un});function Wn(e,t){return t.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function Hn({setting:e},t){let{linkChartView:r}=ne(t);return Wn(e,r)}var Zn=l.object({setting:l.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Xs=y(Hn,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Zn});async function Jn(e,t,r,a,o){let{graphQuery:n,explanation:s}=await se(e,t.dataModel,r,o);await g({text:`Attempting to create link chart from derived query: ${n}`},o);let i=await Vt.fromCypherQuery(t,new ve({openCypherQuery:n}));return await g({text:"Link chart created successfully, loading..."},o),a.map=i,await i.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart:
192
+ ${n}
193
+
194
+ Explanation: ${s}`}async function Yn({prompt:e},t){let{knowledgeGraph:r}=await ie(t),{linkChartView:a}=ne(t),o=j.getDefault().helperServices;return await Jn(e,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Xn=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),el=y(Yn,{name:"createLinkChart",description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt.",schema:Xn});async function ei({prompt:e},t){let{knowledgeGraph:r}=await ie(t),a=j.getDefault().helperServices,{graphQuery:o}=await se(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t);await g({text:"Attempting to execute the generated cypher query..."},t);let n=await st({kg:r,queryParams:new ve({openCypherQuery:o}),targetStructure:new Array,targetStructureReducer:(u,m)=>(u.push(m),u),requestOptions:{signal:t?.signal,timeout:t?.timeout}});if(n.type!=="success")throw new Error(n.type==="aborted"?"Query was aborted.":n.type==="timeout"?"Query timed out.":`Query failed with error: ${n.errorMessage}`);let{processedResult:s,resultHeader:i}=n,d=i.headerKeys,c=`| ${d.join(" | ")} |
195
+ `;c+=`| ${d.map(()=>"---").join(" | ")} |
196
+ `;for(let u of s){let m=u.map(p=>typeof p=="object"?JSON.stringify(p):String(p));c+=`| ${m.join(" | ")} |
197
+ `}return`To answer the inquiry, the following cypher query was executed against the knowledge graph:
198
+
199
+ \`\`\`cypher
200
+ ${o}
201
+ \`\`\`
202
+
203
+ Query Results:
204
+
205
+ ${c}
206
+ `}var ti=l.object({prompt:l.string().describe(`The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. IMPORTANT:
207
+
208
+ REQUEST LIMIT: If the user does not specifically request for no limits or an explicit limit to be placed on the query, or the number of rows will not be limited by e.g. the number of entity or relationship types in the graph, ensure that the generated query has a reasonable row limit (e.g. 10 rows).
209
+
210
+ DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),tl=y(ei,{name:"queryGraphData",description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:ti});async function ri({prompt:e},t){let{knowledgeGraph:r}=await ie(t),a=j.getDefault().helperServices;return await Ln(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t)}var ai=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),rl=y(ri,{name:"generateCypher",description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:ai});var al=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).
211
+ 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.
212
+ 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,
213
+ 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
214
+ that exist out from specified entities and adding those to the link chart, changing whether or not nonspatial data is visible, or changing the layout of the link chart.
215
+ This agent is designed to handle requests that manipulate the specific link chart.
216
+ For knowledge graph data more generally, the agent can generate Open Cypher queries based on user prompts that represent inquiries into the data of the knowledge service and its graph database,
217
+ and can alternatively use those queries to create a new link chart visualization from the results if requested.
218
+
219
+ Supported actions:
220
+ - **Change or Apply Layout**: Changes the current layout visualization strategy of the link chart (e.g., "Change the layout to basic-grid", "Apply hierarchical layout"). Valid layout types include organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline. A best effort should be made to transform the user's request into one of these layout types.
221
+ - **Change Nonspatial Data Visibility**: Changes whether or not nonspatial data is visible on the link chart (e.g., "Show nonspatial data", "Hide nonspatial data"). Valid settings are "hidden" and "visible". A best effort should be made to transform the user's request into one of these settings.
222
+ - **Generate a cypher query**: 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. The user should explicitly request that a cypher query be returned - if they do not, the purpose of the query is for one of the other tools or skills.
223
+ - **Create a New Link Chart from a user prompt**: Identifies that the users prompt is an inquiry into the data of the knowledge service and its graph database and creates a new link chart from the results. The user should have requested that a link chart be created or made(or similar term) from their prompt
224
+ - **Add Records (entities or relationships)**: Identifies that the users prompt is an inquiry into the data of the knowledge graph service and its graph database, and that the user wants to take the result of the inquiry and add those entities and/or relationships to the link chart. The generated query should be syntactically correct and optimized for performance.
225
+ - **Query Graph Data**: Generates and executes a cypher query based on the user's prompt, and displays the results in the chat pane, allowing the user to explore the data in their knowledge graph.
226
+
227
+ _example: "Change the layout to hierarchical-bottom-to-top"_
228
+ _example: "Apply radial-root-centric layout"_
229
+ _example: "Show nonspatial data"_
230
+ _example: "Hide nonspatial data"_
231
+ _example: "Turn off nonspatial visibility"_
232
+ _example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
233
+ _example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
234
+ _example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
235
+ _example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
236
+ _example: "Find all people who work for Microsoft and put them on a new link chart"_
237
+ _example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
238
+ _example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
239
+ _example: "Find all the products supplied by Supplier X and add them to my visualization"_
240
+ _example: "Expand the link chart from 'Entity D' to show its direct connections"_
241
+ _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
242
+ _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
243
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
244
+ _example: "What is the average age of all people who work for Esri?"`;return{a:Us,b:Ws,c:Ve,d:Hs}},"Graphic","geometry/Point","geometry/Extent","symbols/PictureMarkerSymbol","rest/locator","portal/Portal","config","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphQueryStreaming","request","identity/IdentityManager","rest/knowledgeGraph/KnowledgeGraph","WebLinkChart",a)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./SOJ4DKGV.js";import b from"./KHCTRS6Z.js";import"./PLPJJRCP.js";import{a as r,c as e}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as a,y as s}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{b:i}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-data-exploration-agent"),e(this)}};s("arcgis-assistant-data-exploration-agent",t);return t},b,c)
2
+ import c from"./GQTBCKGL.js";import b from"./Y63AQNL7.js";import"./YW52XJMM.js";import{a as r,c as e}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as a,y as s}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{b:i}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-data-exploration-agent"),e(this)}};s("arcgis-assistant-data-exploration-agent",t);return t},b,c)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{a as _,b as f}from"./EUNEQNYC.js";import b from"./KHCTRS6Z.js";import{a as C}from"./YUZDB6IX.js";import"./B3E2XBTX.js";import"./PLPJJRCP.js";import{a as P}from"./KVH3PDVW.js";import"./YGW7TUNX.js";import{g as E,h as a,l as $,n,t as y,u as v,v as k,w as m,y as S}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([R,{whenOnce:O,watch:M,when:A},V,q,{property:d,subclass:z},{d:I}])=>{var j=E`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%)}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}`,H=Object.defineProperty,N=Object.getOwnPropertyDescriptor,h=(g,t,e,i)=>{for(var s=i>1?void 0:i?N(t,e):t,r=g.length-1,o;r>=0;r--)(o=g[r])&&(s=(i?o(t,e,s):o(s))||s);return i&&s&&H(t,e,s),s},l=class extends q{constructor(g){super(g),this.view=null,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await O(()=>!this.view.updating),this._set("orchestrator",await I.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([M(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(g,t){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let e=[],i;try{let s=this.orchestrator.ask(g);for await(let r of s){let o=r.runId;if(t?.aborted){yield{type:"cancelled",runId:o};break}switch(r.type){case"trace":{this._set("processingStep",r.data.text),e.push(r.data.text);break}case"completed":{let c=r.result,p=!!c.content.length,b=!!i?.length;if(!p&&!b){yield{type:"completed",error:"Could not process the request.",log:e,runId:o};return}let u=c.content;this._set("processingStep",""),yield{type:"completed",response:u,blocks:i,log:e,runId:o};return}case"ux-suggestion":{let c=r.suggestion;i=i?[...i,c]:[c];break}case"interrupt":{let{kind:c,message:p,metadata:b}=r.interrupt,u=Array.isArray(b)?b.filter(L=>typeof L=="string"):[],x=(()=>{switch(c){case"booleanChoice":return{type:"boolean-choice",message:p,options:u};case"singleSelection":return{type:"single-select",message:p,options:u};case"multipleSelection":return{type:"multi-select",message:p,options:u};case"textInput":return{type:"text-input",message:p};default:return{type:c,message:p,options:u}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:x,runId:o};break}case"cancelled":{yield{type:"cancelled",runId:o};return}case"error":{yield{type:"completed",error:r.error.message,log:e,runId:o};return}default:{console.warn("Unknown event type:",r);break}}}}catch(s){console.warn("Error during message processing:",s),yield{type:"completed",error:"An error occurred during message processing.",log:e,runId:"error"};return}finally{this._set("processing",!1)}}};h([d({readOnly:!0})],l.prototype,"orchestrator",2);h([d()],l.prototype,"agents",2);h([d()],l.prototype,"portal",2);h([d()],l.prototype,"view",2);h([d({readOnly:!0})],l.prototype,"loading",2);h([d({readOnly:!0})],l.prototype,"processing",2);h([d({readOnly:!0})],l.prototype,"processingStep",2);l=h([z("OrchestratorController")],l);var D="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",B="Embeddings not found for this web map.",F="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",w=class extends k{constructor(){super(...arguments),this._messages=C({blocking:!0}),this.#t=y(),this.#n=y(),this.#e=y(),this.#s=null,this.#o=new Map,this.#r=V.getDefault(),this.#i=t=>{t.stopPropagation(),this.cancelInterrupt()},this.#a=t=>{t.stopPropagation();let e=t.detail;this.submitInterrupt(e)},this.#l=t=>{t.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let e=t.detail;this._inputValue="",this.arcgisSubmit.emit(e),this.submitMessage(e)},this.#c=t=>{if(t.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this.#s?.abort()},this.#h=t=>{t.stopPropagation();let e=t.detail;this.arcgisFeedback.emit(e)},this.#g=t=>{t.stopPropagation();let e=t.detail;this._inputValue=e.prompt,this.arcgisPromptSelect.emit(e)},this.#p=t=>{this.arcgisSlottableRequest.emit(t.detail)},this._orchestratorController=null,this._interrupt=null,this._error=null,this._inputValue="",this.messages=new R([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.arcgisCancel=n(),this.arcgisError=n(),this.arcgisFeedback=n(),this.arcgisInterrupt=n(),this.arcgisInterruptCancel=n(),this.arcgisInterruptSubmit=n(),this.arcgisPromptSelect=n(),this.arcgisReady=n(),this.arcgisSubmit=n(),this.arcgisSlottableRequest=n({bubbles:!1,composed:!1})}static{this.properties={_orchestratorController:16,_interrupt:16,_error:16,_inputValue:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5}}static{this.styles=j}#t;#n;#e;#s;#o;#r;#i;#a;#l;#c;#h;#g;#p;async#d(){try{let t=P(this.el,this.referenceElement);await t?.componentOnReady();let e=[...this.#o.values()];return e.length?(this._orchestratorController=new l({agents:e,portal:this.#r,view:t?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(t){return this._error=t?.message??"Error initializing orchestrator.",$(this)(t),!1}}get _user(){return this.#r?.user?.fullName||this.#r?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(t){this.#o.set(t.agent.id,t)}async submitMessage(t){let e=t.trim();if(!e||(this.messages.push({id:Date.now().toString(),role:"user",content:e}),!this._orchestratorController))return;let i=this._orchestratorController.ask(e,this.#s?.signal);for await(let s of i){let r=s.runId;switch(s.type){case"completed":this.messages.push({role:"assistant",content:s.response,blocks:s.blocks,log:s.log,error:s.error,id:r});break;case"interrupt":this._interrupt={...s.payload,id:r},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":this.messages.push({role:"assistant",error:"Request cancelled.",id:r});break}}}submitInterrupt(t){this.arcgisInterruptSubmit.emit(t),this.orchestrator?.resumeInterrupt(t),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#t.value?.addEventListener("arcgisPromptSelect",this.#g),this.#t.value?.addEventListener("arcgisSubmit",this.#l),this.#t.value?.addEventListener("arcgisCancel",this.#c),this.#t.value?.addEventListener("arcgisFeedback",this.#h);let t=A(()=>!!this._interrupt&&!!this.#e.value,()=>{let e=this.#e.value;e.removeEventListener("arcgisSubmit",this.#a),e.removeEventListener("arcgisCancel",this.#i),e.addEventListener("arcgisSubmit",this.#a,{once:!0}),e.addEventListener("arcgisCancel",this.#i,{once:!0})});return queueMicrotask(()=>{this.#d().then(e=>{e?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{t.remove(),this.#t.value?.removeEventListener("arcgisPromptSelect",this.#g),this.#e.value?.removeEventListener("arcgisSubmit",this.#a),this.#e.value?.removeEventListener("arcgisCancel",this.#i),this.#t.value?.removeEventListener("arcgisSubmit",this.#l),this.#t.value?.removeEventListener("arcgisCancel",this.#c),this.#t.value?.removeEventListener("arcgisFeedback",this.#h),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this.#s?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue=""}_renderEntryMessage(){return this._interrupt?a`<slot name=interrupt><arcgis-assistant-interrupt .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${v(this.#e)}></arcgis-assistant-interrupt></slot>`:this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:a`<calcite-notice open kind=info closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:a`<slot name=entry-message></slot>`}_renderErrorNotice(){return this._error?a`<calcite-notice closable slot=entry-message open kind=danger icon width=full>${this._error===D?a`<div slot=message>${B}</div><calcite-link slot=link .href=${F} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:a`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}_renderSuggestedPrompts(){return this.suggestedPrompts?.length?a`<div class="suggested-prompts-container"><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}render(){return a`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${v(this.#t)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(t=>t.role==="assistant"?a`<arcgis-assistant-message .message=${t} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#p}><slot name=${_(t.id)??m} slot=${_(t.id)??m}>${t?.error?a`<calcite-notice class="error-notice" open icon kind=warning width=full><div slot=message>${t.error}</div></calcite-notice>`:a`<arcgis-assistant-message-text .content=${t?.content}></arcgis-assistant-message-text>`}</slot>${t.blocks?.map((e,i)=>a`<slot name=${f(t.id,i)??m} slot=${f(t.id,i)??m}><arcgis-assistant-message-block .block=${e}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:a`<arcgis-assistant-user-message .message=${t} .user=${this._user}></arcgis-assistant-user-message>`)}</slot><slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep}></arcgis-assistant-message-loading></slot></arcgis-assistant-chat></div>${this._renderSuggestedPrompts()}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} ${v(this.#n)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse?"circle-stop":"send"} @click=${()=>{this.#n.value?.submitMessage()}} round>${this.awaitingResponse?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};S("arcgis-assistant",w);return w},"core/Collection","core/reactiveUtils","portal/Portal","core/Accessor","core/accessorSupport/decorators",b)
2
+ import{a as _,b as f}from"./EUNEQNYC.js";import b from"./Y63AQNL7.js";import{a as C}from"./YUZDB6IX.js";import"./B3E2XBTX.js";import"./YW52XJMM.js";import{a as P}from"./KVH3PDVW.js";import"./YGW7TUNX.js";import{g as E,h as a,l as $,n,t as y,u as v,v as k,w as m,y as S}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([R,{whenOnce:O,watch:M,when:A},V,q,{property:d,subclass:z},{d:I}])=>{var j=E`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%)}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}`,H=Object.defineProperty,N=Object.getOwnPropertyDescriptor,h=(g,t,e,i)=>{for(var s=i>1?void 0:i?N(t,e):t,r=g.length-1,o;r>=0;r--)(o=g[r])&&(s=(i?o(t,e,s):o(s))||s);return i&&s&&H(t,e,s),s},l=class extends q{constructor(g){super(g),this.view=null,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await O(()=>!this.view.updating),this._set("orchestrator",await I.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([M(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(g,t){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let e=[],i;try{let s=this.orchestrator.ask(g);for await(let r of s){let o=r.runId;if(t?.aborted){yield{type:"cancelled",runId:o};break}switch(r.type){case"trace":{this._set("processingStep",r.data.text),e.push(r.data.text);break}case"completed":{let c=r.result,p=!!c.content.length,b=!!i?.length;if(!p&&!b){yield{type:"completed",error:"Could not process the request.",log:e,runId:o};return}let u=c.content;this._set("processingStep",""),yield{type:"completed",response:u,blocks:i,log:e,runId:o};return}case"ux-suggestion":{let c=r.suggestion;i=i?[...i,c]:[c];break}case"interrupt":{let{kind:c,message:p,metadata:b}=r.interrupt,u=Array.isArray(b)?b.filter(L=>typeof L=="string"):[],x=(()=>{switch(c){case"booleanChoice":return{type:"boolean-choice",message:p,options:u};case"singleSelection":return{type:"single-select",message:p,options:u};case"multipleSelection":return{type:"multi-select",message:p,options:u};case"textInput":return{type:"text-input",message:p};default:return{type:c,message:p,options:u}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:x,runId:o};break}case"cancelled":{yield{type:"cancelled",runId:o};return}case"error":{yield{type:"completed",error:r.error.message,log:e,runId:o};return}default:{console.warn("Unknown event type:",r);break}}}}catch(s){console.warn("Error during message processing:",s),yield{type:"completed",error:"An error occurred during message processing.",log:e,runId:"error"};return}finally{this._set("processing",!1)}}};h([d({readOnly:!0})],l.prototype,"orchestrator",2);h([d()],l.prototype,"agents",2);h([d()],l.prototype,"portal",2);h([d()],l.prototype,"view",2);h([d({readOnly:!0})],l.prototype,"loading",2);h([d({readOnly:!0})],l.prototype,"processing",2);h([d({readOnly:!0})],l.prototype,"processingStep",2);l=h([z("OrchestratorController")],l);var D="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",B="Embeddings not found for this web map.",F="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",w=class extends k{constructor(){super(...arguments),this._messages=C({blocking:!0}),this.#t=y(),this.#n=y(),this.#e=y(),this.#s=null,this.#o=new Map,this.#r=V.getDefault(),this.#i=t=>{t.stopPropagation(),this.cancelInterrupt()},this.#a=t=>{t.stopPropagation();let e=t.detail;this.submitInterrupt(e)},this.#l=t=>{t.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let e=t.detail;this._inputValue="",this.arcgisSubmit.emit(e),this.submitMessage(e)},this.#c=t=>{if(t.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this.#s?.abort()},this.#h=t=>{t.stopPropagation();let e=t.detail;this.arcgisFeedback.emit(e)},this.#g=t=>{t.stopPropagation();let e=t.detail;this._inputValue=e.prompt,this.arcgisPromptSelect.emit(e)},this.#p=t=>{this.arcgisSlottableRequest.emit(t.detail)},this._orchestratorController=null,this._interrupt=null,this._error=null,this._inputValue="",this.messages=new R([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.arcgisCancel=n(),this.arcgisError=n(),this.arcgisFeedback=n(),this.arcgisInterrupt=n(),this.arcgisInterruptCancel=n(),this.arcgisInterruptSubmit=n(),this.arcgisPromptSelect=n(),this.arcgisReady=n(),this.arcgisSubmit=n(),this.arcgisSlottableRequest=n({bubbles:!1,composed:!1})}static{this.properties={_orchestratorController:16,_interrupt:16,_error:16,_inputValue:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5}}static{this.styles=j}#t;#n;#e;#s;#o;#r;#i;#a;#l;#c;#h;#g;#p;async#d(){try{let t=P(this.el,this.referenceElement);await t?.componentOnReady();let e=[...this.#o.values()];return e.length?(this._orchestratorController=new l({agents:e,portal:this.#r,view:t?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(t){return this._error=t?.message??"Error initializing orchestrator.",$(this)(t),!1}}get _user(){return this.#r?.user?.fullName||this.#r?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(t){this.#o.set(t.agent.id,t)}async submitMessage(t){let e=t.trim();if(!e||(this.messages.push({id:Date.now().toString(),role:"user",content:e}),!this._orchestratorController))return;let i=this._orchestratorController.ask(e,this.#s?.signal);for await(let s of i){let r=s.runId;switch(s.type){case"completed":this.messages.push({role:"assistant",content:s.response,blocks:s.blocks,log:s.log,error:s.error,id:r});break;case"interrupt":this._interrupt={...s.payload,id:r},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":this.messages.push({role:"assistant",error:"Request cancelled.",id:r});break}}}submitInterrupt(t){this.arcgisInterruptSubmit.emit(t),this.orchestrator?.resumeInterrupt(t),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#t.value?.addEventListener("arcgisPromptSelect",this.#g),this.#t.value?.addEventListener("arcgisSubmit",this.#l),this.#t.value?.addEventListener("arcgisCancel",this.#c),this.#t.value?.addEventListener("arcgisFeedback",this.#h);let t=A(()=>!!this._interrupt&&!!this.#e.value,()=>{let e=this.#e.value;e.removeEventListener("arcgisSubmit",this.#a),e.removeEventListener("arcgisCancel",this.#i),e.addEventListener("arcgisSubmit",this.#a,{once:!0}),e.addEventListener("arcgisCancel",this.#i,{once:!0})});return queueMicrotask(()=>{this.#d().then(e=>{e?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{t.remove(),this.#t.value?.removeEventListener("arcgisPromptSelect",this.#g),this.#e.value?.removeEventListener("arcgisSubmit",this.#a),this.#e.value?.removeEventListener("arcgisCancel",this.#i),this.#t.value?.removeEventListener("arcgisSubmit",this.#l),this.#t.value?.removeEventListener("arcgisCancel",this.#c),this.#t.value?.removeEventListener("arcgisFeedback",this.#h),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this.#s?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue=""}_renderEntryMessage(){return this._interrupt?a`<slot name=interrupt><arcgis-assistant-interrupt .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${v(this.#e)}></arcgis-assistant-interrupt></slot>`:this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:a`<calcite-notice open kind=info closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:a`<slot name=entry-message></slot>`}_renderErrorNotice(){return this._error?a`<calcite-notice closable slot=entry-message open kind=danger icon width=full>${this._error===D?a`<div slot=message>${B}</div><calcite-link slot=link .href=${F} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:a`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}_renderSuggestedPrompts(){return this.suggestedPrompts?.length?a`<div class="suggested-prompts-container"><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}render(){return a`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${v(this.#t)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(t=>t.role==="assistant"?a`<arcgis-assistant-message .message=${t} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#p}><slot name=${_(t.id)??m} slot=${_(t.id)??m}>${t?.error?a`<calcite-notice class="error-notice" open icon kind=warning width=full><div slot=message>${t.error}</div></calcite-notice>`:a`<arcgis-assistant-message-text .content=${t?.content}></arcgis-assistant-message-text>`}</slot>${t.blocks?.map((e,i)=>a`<slot name=${f(t.id,i)??m} slot=${f(t.id,i)??m}><arcgis-assistant-message-block .block=${e}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:a`<arcgis-assistant-user-message .message=${t} .user=${this._user}></arcgis-assistant-user-message>`)}</slot><slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep}></arcgis-assistant-message-loading></slot></arcgis-assistant-chat></div>${this._renderSuggestedPrompts()}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} ${v(this.#n)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse?"circle-stop":"send"} @click=${()=>{this.#n.value?.submitMessage()}} round>${this.awaitingResponse?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};S("arcgis-assistant",w);return w},"core/Collection","core/reactiveUtils","portal/Portal","core/Accessor","core/accessorSupport/decorators",b)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./SOJ4DKGV.js";import b from"./KHCTRS6Z.js";import"./PLPJJRCP.js";import{a as i,c as e}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as a,y as s}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{a:r}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=r}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=i(this,"arcgis-assistant-navigation-agent"),e(this)}};s("arcgis-assistant-navigation-agent",t);return t},b,c)
2
+ import c from"./GQTBCKGL.js";import b from"./Y63AQNL7.js";import"./YW52XJMM.js";import{a as i,c as e}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as a,y as s}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{a:r}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=r}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=i(this,"arcgis-assistant-navigation-agent"),e(this)}};s("arcgis-assistant-navigation-agent",t);return t},b,c)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import c from"./SOJ4DKGV.js";import b from"./KHCTRS6Z.js";import"./PLPJJRCP.js";import{a as r,c as a}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as s,y as e}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{d:i}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-help-agent"),a(this)}};e("arcgis-assistant-help-agent",t);return t},b,c)
2
+ import c from"./GQTBCKGL.js";import b from"./Y63AQNL7.js";import"./YW52XJMM.js";import{a as r,c as a}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as s,y as e}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{d:i}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-help-agent"),a(this)}};e("arcgis-assistant-help-agent",t);return t},b,c)