@arcgis/portal-components 5.1.0-next.122 → 5.1.0-next.124

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.
@@ -36,11 +36,26 @@ Latest user request:
36
36
  Prior steps:
37
37
  {priorSteps}
38
38
 
39
+ Last navigated features from shared state (if available):
40
+ {lastNavigatedFeatures}
41
+
39
42
  Use the assigned task as the primary instruction for the current query.
40
43
  Use the latest user request as supporting context when needed.
41
44
  Use prior steps only when the assigned task or user request clearly depends on earlier results.
45
+ Use lastNavigatedFeatures as authoritative context for map-navigation references when present.
42
46
  Use chat history only when necessary to understand conversational references, and do not override the assigned task.
43
47
 
48
+ ### Anchor selection rule (strict, single source of truth)
49
+
50
+ When the request is referential (for example: "this", "it", "that", "those", "them", "of those", "the same one(s)"), choose exactly one anchor using this priority order:
51
+
52
+ 1. Explicit entity named in the current request (if present)
53
+ 2. \`lastNavigatedFeatures\` (if present)
54
+ 3. The immediately previous successful relevant step from \`priorSteps\`
55
+
56
+ After selecting the anchor, keep that anchor for this query and do not switch to an older entity.
57
+ If \`lastNavigatedFeatures\` is used as the anchor, reuse its \`layerId\` and \`where\` for query scope unless the current request explicitly overrides it.
58
+
44
59
  ### Fresh WHERE clause rule
45
60
 
46
61
  Start with a fresh WHERE clause for each new question. Do not inherit filters from previous questions UNLESS the assigned task explicitly references previous results (see "Referencing Previously Identified Features" below).
@@ -63,11 +78,9 @@ Start with a fresh WHERE clause for each new question. Do not inherit filters fr
63
78
 
64
79
  This is an exception to the "fresh WHERE clause" rule above.
65
80
 
66
- When the assigned task uses words like "these", "those", "them", "the same ones" referring to features from a previous turn:
67
-
68
- - If the previous query used useCurrentExtent: true \u2192 use useCurrentExtent: true with where: "1=1"
69
- - If the previous assistant response mentions specific objectIds or feature IDs \u2192 use {{objectIdField}} IN (id1, id2, ...) to scope to those features
70
- - If neither is available, use the same WHERE clause and layer from the previous query turn to re-select the same features
81
+ - If the anchored context indicates \`useCurrentExtent: true\`, use \`useCurrentExtent: true\` with \`where: "1=1"\`.
82
+ - If the anchored context includes specific feature IDs/objectIds, scope to those IDs.
83
+ - Otherwise, use the anchored \`layerId\` + \`where\` combination.
71
84
 
72
85
  ### Mixed Questions
73
86
 
@@ -117,5 +117,4 @@ Do not reinterpret the request into a different form.
117
117
  - \`requiresFollowUp\` should indicate a likely next agent step, not uncertainty about the current request
118
118
  - Set \`requiresFollowUp\` to \`true\` only when another orchestration step will likely be needed after this agent succeeds
119
119
  - Set \`requiresFollowUp\` to \`false\` when a successful result from this agent would likely complete the user-visible task
120
- - Default to \`false\`
121
120
  `;export{e as default};
@@ -58,6 +58,7 @@ In all cases:
58
58
 
59
59
  - Focus on **notable attribute values**, **commonalities or differences**, and **interesting trends**.
60
60
  - If the feature list is empty or not meaningful, state that clearly.
61
+ - Only use fields present in query results. Do not make guesses.
61
62
 
62
63
  ### STRICT OUTPUT RULES
63
64
 
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import a from"./CSNET4R5.js";import"./S2PHM4WZ.js";import{a as so,b as il}from"./4ISLOZQ3.js";import{a as al}from"./XMHAVYOA.js";import"./RPYRSBGP.js";import{H as no,I as oo,J as ol,P as sl,h as tl,j as Mr,m as rl,v as nl}from"./ADZOZHQC.js";import{$ as De,$a as $,Aa as wt,Ba as Ue,Ca as is,D as cl,Da as Sl,E as Xe,Ea as kl,F as dl,Fa as ls,G as Xo,Ga as Cl,H as wa,Ha as $r,I as ba,Ia as Sa,J as es,Ja as El,K as Aa,Ka as Ol,L as io,La as co,M as q,Ma as Ml,N as xa,Na as po,O as pl,Oa as mo,P as R,Pa as x,Q as gt,Qa as D,R as et,Ra as ka,S as ts,T as ml,U as fl,V as Ia,W as xe,X as rs,Y as hl,Z as ns,_ as gl,a as he,aa as lo,b as B,ba as yl,ca as va,da as _l,ea as uo,f as ge,fa as yt,fb as Pl,g as ll,ga as wl,ha as bl,ia as Al,j as ne,ja as Pr,k as ue,ka as xl,la as tt,ma as Il,mb as bt,na as _t,nb as Ca,oa as os,ob as Ie,pa as rt,q as Yo,qa as ss,qb as fo,ra as vl,rb as us,sa as as,sb as ho,t as ul,ta as Tl,tb as cs,u as ao,ua as U,ub as ye,va as b,wa as Ta,xa as Fe,ya as Rr,za as Ce}from"./YJK6JAPE.js";import"./CFDTXKJ6.js";export default $arcgis.t(([pq,fq,Hh,$d,og,wq,Aq,gW,Ib,Gd,Er,Xd,,Hd,Li,lg,{addressToLocations:ug},cg,dg,ep,{createRenderer:pg},{getSchemesByTag:mg,getSchemes:fg},{getBackgroundColorTheme:Jd},{createAgeRenderer:hg,createContinuousRenderer:gg},{getSchemesByTag:Ki},{createContinuousRenderer:yg},{createRenderer:_g},{getSchemesByTag:wg},{createRenderer:bg},{getSchemesByTag:Ag},{createRenderer:xg},{getSchemesByTag:Ig},{createRenderer:vg},{getSchemesByTag:Tg},{createAgeRenderer:Sg,createContinuousRenderer:kg},{createRenderer:Cg},{getSchemesByTag:Eg},Og,tp,rp,{formatDateOnly:Mg,convertDateFormatToIntlOptions:la,formatTimeOnly:Pg,formatDate:Zd},Rg,$g,Ng,jg,Lg,np,,{fetchKnowledgeGraph:Qd,executeQueryStreaming:zg,executeSearchStreaming:Dg},Fg,,,,,,,,,,,,,,,,,,,,,A2,I2,,,,,,,,,,,vb,yp,{a:Rl,b:$l,c:Nl,d:jl,e:Ll}])=>{var d=x;async function Ea(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
2
+ import a from"./CSNET4R5.js";import"./S2PHM4WZ.js";import{a as so,b as il}from"./4ISLOZQ3.js";import{a as al}from"./XMHAVYOA.js";import"./RPYRSBGP.js";import{H as no,I as oo,J as ol,P as sl,h as tl,j as Mr,m as rl,v as nl}from"./ADZOZHQC.js";import{$ as De,$a as $,Aa as wt,Ba as Ue,Ca as is,D as cl,Da as Sl,E as Xe,Ea as kl,F as dl,Fa as ls,G as Xo,Ga as Cl,H as wa,Ha as $r,I as ba,Ia as Sa,J as es,Ja as El,K as Aa,Ka as Ol,L as io,La as co,M as q,Ma as Ml,N as xa,Na as po,O as pl,Oa as mo,P as R,Pa as x,Q as gt,Qa as D,R as et,Ra as ka,S as ts,T as ml,U as fl,V as Ia,W as xe,X as rs,Y as hl,Z as ns,_ as gl,a as he,aa as lo,b as B,ba as yl,ca as va,da as _l,ea as uo,f as ge,fa as yt,fb as Pl,g as ll,ga as wl,ha as bl,ia as Al,j as ne,ja as Pr,k as ue,ka as xl,la as tt,ma as Il,mb as bt,na as _t,nb as Ca,oa as os,ob as Ie,pa as rt,q as Yo,qa as ss,qb as fo,ra as vl,rb as us,sa as as,sb as ho,t as ul,ta as Tl,tb as cs,u as ao,ua as U,ub as ye,va as b,wa as Ta,xa as Fe,ya as Rr,za as Ce}from"./YJK6JAPE.js";import"./CFDTXKJ6.js";export default $arcgis.t(([mq,hq,Hh,$d,og,bq,xq,yW,Ib,Gd,Er,Xd,,Hd,Li,lg,{addressToLocations:ug},cg,dg,ep,{createRenderer:pg},{getSchemesByTag:mg,getSchemes:fg},{getBackgroundColorTheme:Jd},{createAgeRenderer:hg,createContinuousRenderer:gg},{getSchemesByTag:Ki},{createContinuousRenderer:yg},{createRenderer:_g},{getSchemesByTag:wg},{createRenderer:bg},{getSchemesByTag:Ag},{createRenderer:xg},{getSchemesByTag:Ig},{createRenderer:vg},{getSchemesByTag:Tg},{createAgeRenderer:Sg,createContinuousRenderer:kg},{createRenderer:Cg},{getSchemesByTag:Eg},Og,tp,rp,{formatDateOnly:Mg,convertDateFormatToIntlOptions:la,formatTimeOnly:Pg,formatDate:Zd},Rg,$g,Ng,jg,Lg,np,,{fetchKnowledgeGraph:Qd,executeQueryStreaming:zg,executeSearchStreaming:Dg},Fg,,,,,,,,,,,,,,,,,,,,,x2,v2,,,,,,,,,,,vb,yp,{a:Rl,b:$l,c:Nl,d:jl,e:Ll}])=>{var d=x;async function Ea(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
3
3
 
4
4
  If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
5
 
@@ -95,12 +95,12 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
95
95
 
96
96
  `);return o[o.length-1]?.trim()===r?t:`${t}
97
97
 
98
- ${r}`},zd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),kr=()=>({agentExecutionContext:$({reducer:jd,default:zd}),outputMessage:$({reducer:Ld,default:()=>""}),summary:$({reducer:Qn,default:()=>""}),status:$({reducer:Qn})}),ia=()=>({...kr(),sharedStatePatch:$({reducer:Qn})}),Xh=$.Root({agentExecutionContext:$({default:zd,reducer:jd}),currentIntent:$({default:()=>"none",reducer:Qn}),lastExecutedAgent:$({default:()=>"",reducer:Qn}),requiresFollowUp:$({default:()=>!0,reducer:Qn}),stepCount:$({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:$({default:()=>"",reducer:Ld})}),re=async(t,e)=>{await Ea("trace_message",t,e)},Ae=async(t,e)=>{await Ea("graph_ux_suggestion",t,e)};var eg=t=>async(e,r)=>{let n=new Headers(r?.headers);return n.delete("Authorization"),n.delete("api-key"),t&&t.length>0&&(n.set("X-Esri-Authorization",`Bearer ${t}`),n.set("X-Esri-Request-Source","MapsSDK")),await fetch(e,{...r,headers:n})},ji=async(t="default",e=0)=>{let r=$d.getDefault(),n=await Hh.getCredential(`${r.url}/sharing`),o=Nd[t],s=await Yh(t);return new sa({modelName:o,apiKey:"dummy-key",...t!=="default"&&{temperature:e},configuration:{baseURL:s,fetch:eg(n.token)}})};var tg=x.object({id:x.string().min(1),name:x.string().min(1),description:x.string().min(1)});x.array(tg);var Dd="0.1",Zn=1536,Fd="openai",Ud=Jh.default,qd=`Name: {name}
98
+ ${r}`},zd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),kr=()=>({agentExecutionContext:$({reducer:jd,default:zd}),outputMessage:$({reducer:Ld,default:()=>""}),summary:$({reducer:Qn,default:()=>""}),status:$({reducer:Qn})}),ia=()=>({...kr(),sharedStatePatch:$({reducer:Qn})}),Xh=$.Root({agentExecutionContext:$({default:zd,reducer:jd}),currentIntent:$({default:()=>"none",reducer:Qn}),lastExecutedAgent:$({default:()=>"",reducer:Qn}),requiresFollowUp:$({default:()=>!0,reducer:Qn}),stepCount:$({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:$({default:()=>"",reducer:Ld})}),re=async(t,e)=>{await Ea("trace_message",t,e)},Ae=async(t,e)=>{await Ea("graph_ux_suggestion",t,e)};var eg=(t,e)=>async(r,n)=>{let o=new Headers(n?.headers);o.delete("Authorization"),o.delete("api-key"),t&&t.length>0&&(o.set("X-Esri-Authorization",`Bearer ${t}`),o.set("X-Esri-Request-Source","MapsSDK"));let s=e&&n?.signal?AbortSignal.any([e,n.signal]):n?.signal??e;return await fetch(r,{...n,headers:o,signal:s})},ji=async(t={})=>{let{modelTier:e="default",temperature:r=0,abortSignal:n}=t,o=$d.getDefault(),s=await Hh.getCredential(`${o.url}/sharing`),a=Nd[e],i=await Yh(e);return new sa({modelName:a,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:i,fetch:eg(s.token,n)}})};var tg=x.object({id:x.string().min(1),name:x.string().min(1),description:x.string().min(1)});x.array(tg);var Dd="0.1",Zn=1536,Fd="openai",Ud=Jh.default,qd=`Name: {name}
99
99
  Title: {title}
100
100
  Description: {description}`,Bd=`Name: {name}
101
101
  Alias: {alias}
102
- Description: {description}`,Kd=x.object({schemaVersion:x.literal(Dd),modified:x.number().int().nonnegative(),embeddings:x.object({modelProvider:x.literal(Fd),model:x.literal(Ud),dimensions:x.literal(Zn),templates:x.object({layer:x.string().default(qd),field:x.string().default(Bd)})}),layers:x.array(x.object({id:x.string().min(1),name:x.string().min(1),title:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Zn,{message:`Layer vector must be exactly ${Zn} dimensions`}),fields:x.array(x.object({name:x.string().min(1),alias:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Zn,{message:`Field vector must be exactly ${Zn} dimensions`})}))})).default([])});var rg=(t,e)=>{let r=Ml.fromTemplate(t);return po.fromMessages([r,...e])};var Wo=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a}=t,i=rg(e,o??[]),u=(await ji(r,n)).withStructuredOutput(a);return await i.pipe(u).invoke(s??{})};var ng=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),oq=d.object({fields:d.array(ng)});var sq=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var Vd=t=>Array.isArray(t)&&t.every(io),sg=t=>typeof t=="object"&&t!=null&&"messages"in t&&Vd(t.messages),ag=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ht=class extends Pl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e){let r=this.tools.find(n=>n.name===t.name);try{if(r===void 0)throw new Error(`Tool "${t.name}" not found.`);let n=await r.invoke({...t,type:"tool_call"},e);return io(n)&&n.getType()==="tool"||ue(n)?n:new q({status:"success",name:r.name,content:typeof n=="string"?n:JSON.stringify(n),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||ao(n))throw n;return new q({status:"error",content:`Error: ${n.message}
103
- Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(ag(t))r=[await this.runTool(t.lg_tool_call,e)];else{let s;if(Vd(t))s=t;else if(sg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(gt(l)){i=l;break}}if(i==null||!gt(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===ne.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>ll(a))?o?o.goto.push(...s.goto):o=new ne({graph:ne.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var oB=$.Root({llmInputMessages:$({reducer:(t,e)=>fo([],e),default:()=>[]})});var Vo=(t,e)=>e??t,Ug=$.Root({...ia(),intent:$({reducer:Vo}),vectorSearchLayerResults:$({reducer:Vo,default:()=>[]}),vectorSearchFieldResults:$({reducer:Vo}),navigationInternalState:$({reducer:Vo,default:()=>({toolCallMessage:void 0})})});async function qg(t,e){let r=Er.getDefault().helperServices,n=r.geocode.find(c=>c.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Li.assetsPath?.endsWith("/")?Li.assetsPath:`${Li.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await ug(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new cg({url:s,width:24,height:24}),u=new lg({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var Bg=["mapView"];function Ye(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Bg.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Kg({address:t},e){let{mapView:r}=Ye(e);return await qg(t,r)}var Wg=d.object({address:d.string().describe("The full address or place name to locate.")}),Vg=D(Kg,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Wg});async function Gg(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function Hg({bookmarkName:t},e){let{mapView:r}=Ye(e);return await Promise.resolve(Gg(t,r))}var Jg=x.object({bookmarkName:x.string().describe("The name of the bookmark to navigate to.")}),Zg=D(Hg,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Jg});async function Qg(t,e,r){let n=r.map?.allLayers.find(s=>s.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=n.createQuery();o.where=e??"1=1";try{let{extent:s,count:a}=await n.queryExtent(o);if(a===0)return{text:`No features found in ${n.title} matching: ${e}`};if(s)await r.goTo(s);else return{text:`Error: Unable to determine extent for ${n.title}`};return{text:`Successfully zoomed to ${a} feature(s) in ${n.title}`}}catch(s){return console.error("Error in goToFeatures:",s),{text:`Error: ${s instanceof Error?s.message:"Unknown error"}`}}}async function Yg({layerId:t,where:e},r){let{mapView:n}=Ye(r);return await Qg(t,e,n)}var Xg=x.object({layerId:x.string().describe("The layerId of the layer to zoom to."),where:x.string().describe("The sql-92 where clause used to query features to zoom to")}),ey=D(Yg,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Xg});async function ty(t){let e=new dg({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function ry(t,e){let{mapView:r}=Ye(e);return await ty(r)}var ny=x.object({}),oy=D(ry,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ny});async function sy(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function ay(t,e){let{mapView:r}=Ye(e);return await sy(r)}var iy=d.object({}),ly=D(ay,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:iy});async function uy(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function cy({layerId:t},e){let{mapView:r}=Ye(e);return await uy(t,r)}var dy=x.object({layerId:x.string().describe("The id of the layer to navigate to")}),py=D(cy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:dy});async function my(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function fy({scale:t},e){let{mapView:r}=Ye(e);return await my(t,r)}var hy=d.object({scale:d.number().describe("The map scale of the view to go to.")}),gy=D(fy,{name:"goToScale",description:"Go to the specified view scale.",schema:hy});async function yy(t,e,r){let n={target:new ep({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function _y({center:t,zoom:e,scale:r},n){let{mapView:o}=Ye(n);return await yy(t,o,{zoom:e,scale:r})}var wy=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),by=D(_y,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:wy});async function Ay(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function xy({zoom:t},e){let{mapView:r}=Ye(e);return await Ay(t,r)}var Iy=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),vy=D(xy,{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:Iy}),Yd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./GOMFFUFI.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./HWLUVMK4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./65JPRIL4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./7WH33C6J.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./3AFLX4RZ.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./IBYY5ORN.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./C44LYN55.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./U5EQ4SIR.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./ZJYTQIYE.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./SX4KDMYV.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./3V7XYFTD.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./TKQAFRBM.js").then(t=>t.default)});async function Wt(t){let e=Object.entries(Yd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
102
+ Description: {description}`,Kd=x.object({schemaVersion:x.literal(Dd),modified:x.number().int().nonnegative(),embeddings:x.object({modelProvider:x.literal(Fd),model:x.literal(Ud),dimensions:x.literal(Zn),templates:x.object({layer:x.string().default(qd),field:x.string().default(Bd)})}),layers:x.array(x.object({id:x.string().min(1),name:x.string().min(1),title:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Zn,{message:`Layer vector must be exactly ${Zn} dimensions`}),fields:x.array(x.object({name:x.string().min(1),alias:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Zn,{message:`Field vector must be exactly ${Zn} dimensions`})}))})).default([])});var rg=(t,e)=>{let r=Ml.fromTemplate(t);return po.fromMessages([r,...e])};var Wo=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,abortSignal:i}=t,u=rg(e,o??[]),l=(await ji({modelTier:r,temperature:n,abortSignal:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{})};var ng=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),oq=d.object({fields:d.array(ng)});var sq=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var Vd=t=>Array.isArray(t)&&t.every(io),sg=t=>typeof t=="object"&&t!=null&&"messages"in t&&Vd(t.messages),ag=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ht=class extends Pl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e){let r=this.tools.find(n=>n.name===t.name);try{if(r===void 0)throw new Error(`Tool "${t.name}" not found.`);let n=await r.invoke({...t,type:"tool_call"},e);return io(n)&&n.getType()==="tool"||ue(n)?n:new q({status:"success",name:r.name,content:typeof n=="string"?n:JSON.stringify(n),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||ao(n))throw n;return new q({status:"error",content:`Error: ${n.message}
103
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(ag(t))r=[await this.runTool(t.lg_tool_call,e)];else{let s;if(Vd(t))s=t;else if(sg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(gt(l)){i=l;break}}if(i==null||!gt(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e))??[])}if(!r.some(ue))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ue(s)?s.graph===ne.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>ll(a))?o?o.goto.push(...s.goto):o=new ne({graph:ne.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var sB=$.Root({llmInputMessages:$({reducer:(t,e)=>fo([],e),default:()=>[]})});var Vo=(t,e)=>e??t,Ug=$.Root({...ia(),intent:$({reducer:Vo}),vectorSearchLayerResults:$({reducer:Vo,default:()=>[]}),vectorSearchFieldResults:$({reducer:Vo}),navigationInternalState:$({reducer:Vo,default:()=>({toolCallMessage:void 0})})});async function qg(t,e){let r=Er.getDefault().helperServices,n=r.geocode.find(c=>c.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Li.assetsPath?.endsWith("/")?Li.assetsPath:`${Li.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await ug(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new cg({url:s,width:24,height:24}),u=new lg({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var Bg=["mapView"];function Ye(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Bg.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Kg({address:t},e){let{mapView:r}=Ye(e);return await qg(t,r)}var Wg=d.object({address:d.string().describe("The full address or place name to locate.")}),Vg=D(Kg,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Wg});async function Gg(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function Hg({bookmarkName:t},e){let{mapView:r}=Ye(e);return await Promise.resolve(Gg(t,r))}var Jg=x.object({bookmarkName:x.string().describe("The name of the bookmark to navigate to.")}),Zg=D(Hg,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Jg});async function Qg(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function Yg({layerId:t,where:e},r){let{mapView:n}=Ye(r);return await Qg(t,e,n)}var Xg=x.object({layerId:x.string().describe("The layerId of the layer to zoom to."),where:x.string().describe("The sql-92 where clause used to query features to zoom to")}),ey=D(Yg,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Xg});async function ty(t){let e=new dg({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function ry(t,e){let{mapView:r}=Ye(e);return await ty(r)}var ny=x.object({}),oy=D(ry,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ny});async function sy(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function ay(t,e){let{mapView:r}=Ye(e);return await sy(r)}var iy=d.object({}),ly=D(ay,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:iy});async function uy(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function cy({layerId:t},e){let{mapView:r}=Ye(e);return await uy(t,r)}var dy=x.object({layerId:x.string().describe("The id of the layer to navigate to")}),py=D(cy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:dy});async function my(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function fy({scale:t},e){let{mapView:r}=Ye(e);return await my(t,r)}var hy=d.object({scale:d.number().describe("The map scale of the view to go to.")}),gy=D(fy,{name:"goToScale",description:"Go to the specified view scale.",schema:hy});async function yy(t,e,r){let n={target:new ep({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function _y({center:t,zoom:e,scale:r},n){let{mapView:o}=Ye(n);return await yy(t,o,{zoom:e,scale:r})}var wy=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),by=D(_y,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:wy});async function Ay(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function xy({zoom:t},e){let{mapView:r}=Ye(e);return await Ay(t,r)}var Iy=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),vy=D(xy,{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:Iy}),Yd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./GOMFFUFI.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./HWLUVMK4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./65JPRIL4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./7WH33C6J.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./3AFLX4RZ.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./IBYY5ORN.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./DHFEIO2X.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QMPLNNCB.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./ZJYTQIYE.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./SX4KDMYV.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./3V7XYFTD.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./TKQAFRBM.js").then(t=>t.default)});async function Wt(t){let e=Object.entries(Yd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
104
104
  Available prompts:
105
105
  ${Object.keys(Yd).join(`
106
106
  `)}`);return await e[1]()}var Xn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Ty(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=mg({basemapTheme:await Jd(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=fg({basemapTheme:await Jd(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function Sy(t){return await pg(t)}async function ky({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await Ty(u),c=await Sy(l);return i.renderer=c.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var Cy=["mapView"];function Le(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Cy.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Ey({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Le(o);return await Ae({type:"show-legend",data:{layerIds:[t]}},o),await ky({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Oy=d.object({layerId:d.string().describe("The id of the layer to apply the chart renderer to"),fields:d.array(d.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),My=D(Ey,{name:"chart",description:`Label: Charts
@@ -172,7 +172,7 @@ Fields: This typically requires zero or one field of type number.`,schema:a_});f
172
172
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
173
173
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
174
174
  Example: Color each feature based on the region it belongs to
175
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:j_}),z_=$.Root({...kr(),vectorSearchLayerIds:$(),vectorSearchFieldResults:$(),layerFieldInfo:$(),selectedLayerId:$()}),D_=$.Root({...kr(),vectorSearchLayerIds:$(),vectorSearchFieldResults:$(),layerFieldInfo:$(),queryResponse:$(),dataExplorationMessages:$({reducer:fo,default:()=>[]})}),F_=["mapView"];function Vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=F_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var U_=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},q_=async(t,e)=>{let{mapView:r}=Vt(e);return U_(r)},pK=D(q_,{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:d.object({})}),B_=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},K_=async(t,e)=>{let{mapView:r}=Vt(e);return await B_(r)},mK=D(K_,{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:d.object({})});function da(t){return"point"in t&&t.point!==void 0}function Go(t){return"layerId"in t&&t.layerId!==void 0}var fa=async(t,e)=>{if(da(t)){let{point:r}=t;return{geometry:new ep({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Go(t)){let r=e.map?.allLayers.find(o=>o.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id;try{let o=await r.queryFeatures({where:t.where,returnGeometry:!0,outSpatialReference:e.spatialReference});if(!o.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${t.where}`};let s;if(o.features.length===1){let a=o.features[0].geometry;if(!a)return{error:"The geometry of the first feature is undefined or null."};s=a}else{let a=o.features.map(u=>u.geometry),i=rp.executeMany(a);if(!i)return{error:"Failed to create a combined geometry."};s=i}return s.spatialReference||(s.spatialReference=e.spatialReference),{geometry:s}}catch(o){return{error:`Failed to query geometry: ${String(o)}`}}}return{error:"Invalid geometry configuration provided"}},W_=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},V_=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let p=await fa(o,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Og({filter:new tp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await W_(e,t.layerId,u,i,o?.distance,o?.units),c=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},G_=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Gt=d.enum(G_),H_=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=Vt(s);return await V_(t,a,n,o,e,r)},J_=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),Z_=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Q_=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.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:d.union([J_,Z_]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.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:d.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:d.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.")}),fK=D(H_,{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:Q_}),Di=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},Y_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,X_=t=>{if(typeof t=="string"&&t)return t;let e=Di(t);return e?e.toISOString().slice(0,10):null};var ew=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=X_(t);return s?Mg(s,la("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Pg(t,la("long-time"));let s=Di(t);return s?Zd(s,{...la("long-time"),timeZone:"UTC"}):t}let o=Di(t);return o?Zd(o,{...la("short-date-short-time"),timeZone:Y_(r)}):t},op=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},tw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,rw=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},nw=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},ow=(t,e,r)=>{let n=rw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=tw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},sp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,ap=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?nw(r,s):s?.type==="date-time"?ow(r,s,o):ew(r,n,o)},sw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=op(e,r,t)??r;return ap(t,e,s,o?.type,n)},aw=(t,e)=>sp(t,e),ip=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let c=i[l.name];if(l.name===n){u[l.name]=c;return}let p=op(l.name,c,t)??c,m=sp(t,l.name);u[m]=ap(t,l.name,p,l.type,r)}),u});return{objectIds:o,attributes:s}},iw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},lw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(c=>c.id===t),s=iw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=sw(o,e,i,n.timeZone),l=aw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function uw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Vt(n),s=await lw(t,e,r,o);return JSON.stringify(s,null,2)}var cw=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),dw=D(uw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:cw}),Wi=(t,e,r)=>r?t.hasAllFeaturesInView&&t.availableFields===e:t.hasAllFeatures&&t.availableFields===e;function pa(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var pw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(g=>g.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),c=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,m;if(a){let g=await fa(a,o);if("error"in g)throw new Error(g.error);if(!g.geometry)throw Go(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Go(a)){let A=o.map?.allLayers.find(k=>k.id===a.layerId);p={geometryLayerName:A?.title??A?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else da(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});m=new tp({geometry:g.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let h=Wi(u,[r],!1),_=null,I=null,C=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let g={layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:pa(i.definitionExpression,e.where),...m&&{filter:m},outStatisticTypes:{include:[n]}};_=await Rg(g);let A=["string","small-integer","integer"],k=l.domain?.type==="coded-value"?l.domain:null;(A.includes(l.type)||k)&&(I=(await $g({layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:pa(i.definitionExpression,e.where),...m&&{filter:m}})).uniqueValueInfos.sort((L,Q)=>Q.count-L.count).slice(0,C)),I&&l.domain?.type==="coded-value"&&(I=I.map(L=>({...L,value:k?k.getName(L.value)??L.value:L.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof _?.[n]=="number"?_[n]:"N/A"}`,details:{fieldName:r,fieldAlias:c,statisticType:n,statistic:_?.[n]??null,summaryStatistics:_,uniqueValues:I,where:e.where,spatialFilterInfo:p}}};async function mw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Xn(o,"layersAndFieldsRegistry"),{mapView:a}=Vt(o),i=await pw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var fw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),hw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),gw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([fw,hw]).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:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),yw=D(mw,{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.
175
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:j_}),z_=$.Root({...kr(),vectorSearchLayerIds:$(),vectorSearchFieldResults:$(),layerFieldInfo:$(),selectedLayerId:$()}),D_=$.Root({...kr(),vectorSearchLayerIds:$(),vectorSearchFieldResults:$(),layerFieldInfo:$(),queryResponse:$(),dataExplorationMessages:$({reducer:fo,default:()=>[]})}),F_=["mapView"];function Vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=F_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var U_=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},q_=async(t,e)=>{let{mapView:r}=Vt(e);return U_(r)},mK=D(q_,{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:d.object({})}),B_=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},K_=async(t,e)=>{let{mapView:r}=Vt(e);return await B_(r)},fK=D(K_,{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:d.object({})});function da(t){return"point"in t&&t.point!==void 0}function Go(t){return"layerId"in t&&t.layerId!==void 0}var fa=async(t,e)=>{if(da(t)){let{point:r}=t;return{geometry:new ep({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Go(t)){let r=e.map?.allLayers.find(o=>o.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id;try{let o=await r.queryFeatures({where:t.where,returnGeometry:!0,outSpatialReference:e.spatialReference});if(!o.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${t.where}`};let s;if(o.features.length===1){let a=o.features[0].geometry;if(!a)return{error:"The geometry of the first feature is undefined or null."};s=a}else{let a=o.features.map(u=>u.geometry),i=rp.executeMany(a);if(!i)return{error:"Failed to create a combined geometry."};s=i}return s.spatialReference||(s.spatialReference=e.spatialReference),{geometry:s}}catch(o){return{error:`Failed to query geometry: ${String(o)}`}}}return{error:"Invalid geometry configuration provided"}},W_=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},V_=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let p=await fa(o,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Og({filter:new tp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await W_(e,t.layerId,u,i,o?.distance,o?.units),c=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},G_=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Gt=d.enum(G_),H_=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=Vt(s);return await V_(t,a,n,o,e,r)},J_=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),Z_=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Q_=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.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:d.union([J_,Z_]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.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:d.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:d.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.")}),hK=D(H_,{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:Q_}),Di=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},Y_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,X_=t=>{if(typeof t=="string"&&t)return t;let e=Di(t);return e?e.toISOString().slice(0,10):null};var ew=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=X_(t);return s?Mg(s,la("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Pg(t,la("long-time"));let s=Di(t);return s?Zd(s,{...la("long-time"),timeZone:"UTC"}):t}let o=Di(t);return o?Zd(o,{...la("short-date-short-time"),timeZone:Y_(r)}):t},op=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},tw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,rw=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},nw=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},ow=(t,e,r)=>{let n=rw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=tw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},sp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,ap=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?nw(r,s):s?.type==="date-time"?ow(r,s,o):ew(r,n,o)},sw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=op(e,r,t)??r;return ap(t,e,s,o?.type,n)},aw=(t,e)=>sp(t,e),ip=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let c=i[l.name];if(l.name===n){u[l.name]=c;return}let p=op(l.name,c,t)??c,m=sp(t,l.name);u[m]=ap(t,l.name,p,l.type,r)}),u});return{objectIds:o,attributes:s}},iw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},lw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(c=>c.id===t),s=iw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=sw(o,e,i,n.timeZone),l=aw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function uw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Vt(n),s=await lw(t,e,r,o);return JSON.stringify(s,null,2)}var cw=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),dw=D(uw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:cw}),Wi=(t,e,r)=>r?t.hasAllFeaturesInView&&t.availableFields===e:t.hasAllFeatures&&t.availableFields===e;function pa(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var pw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(g=>g.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),c=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,m;if(a){let g=await fa(a,o);if("error"in g)throw new Error(g.error);if(!g.geometry)throw Go(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Go(a)){let A=o.map?.allLayers.find(k=>k.id===a.layerId);p={geometryLayerName:A?.title??A?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else da(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});m=new tp({geometry:g.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let h=Wi(u,[r],!1),_=null,I=null,C=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let g={layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:pa(i.definitionExpression,e.where),...m&&{filter:m},outStatisticTypes:{include:[n]}};_=await Rg(g);let A=["string","small-integer","integer"],k=l.domain?.type==="coded-value"?l.domain:null;(A.includes(l.type)||k)&&(I=(await $g({layer:i,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:pa(i.definitionExpression,e.where),...m&&{filter:m}})).uniqueValueInfos.sort((L,Q)=>Q.count-L.count).slice(0,C)),I&&l.domain?.type==="coded-value"&&(I=I.map(L=>({...L,value:k?k.getName(L.value)??L.value:L.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof _?.[n]=="number"?_[n]:"N/A"}`,details:{fieldName:r,fieldAlias:c,statisticType:n,statistic:_?.[n]??null,summaryStatistics:_,uniqueValues:I,where:e.where,spatialFilterInfo:p}}};async function mw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Xn(o,"layersAndFieldsRegistry"),{mapView:a}=Vt(o),i=await pw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var fw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),hw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),gw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([fw,hw]).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:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),yw=D(mw,{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.
176
176
 
177
177
  USE THIS TOOL FOR:
178
178
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -184,7 +184,7 @@ DO NOT USE FOR:
184
184
  - "Show / list / find features" \u2014 use queryFeatures instead
185
185
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
186
186
 
187
- 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:gw}),_w=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(m=>m.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let m=await fa(n,r);if("error"in m)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=m.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,c=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])];try{let m;if(l){let I=new Ng({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new jg({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});m=await s.queryTopFeatures(I)}else{let I=s.createQuery();I.where=pa(s.definitionExpression,t.where||"1=1"),I.outFields=p.length?p:["*"],I.orderByFields=e.orderByFields,I.num=e.topCount,u&&(I.geometry=u,I.spatialRelationship="intersects"),n?.distance&&(I.distance=n.distance),n?.units&&(I.units=n.units),I.outSpatialReference=r.spatialReference;let C=Wi(a,t.outFields,o??!1);try{m=C?await a.queryFeatures(I):await s.queryFeatures(I)}catch(g){console.warn("Client-side query failed, falling back to server:",g),m=await s.queryFeatures(I)}}let h=m.features.map(I=>I.attributes[c]),{attributes:_}=ip(s,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:_,objectIds:h,objectIdField:c,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},ww=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Vt(o),a=await _w(t,e,s,r,n);return JSON.stringify(a,null,2)},bw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),Aw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),xw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.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:d.union([bw,Aw]).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:d.object({topCount:d.number().describe("Number of top features to return per group."),orderByFields:d.array(d.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:d.array(d.string().describe("Field(s) to group results by. Returns top N per group."))}),useCurrentExtent:d.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).")}),Iw=D(ww,{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:xw}),zi=25,vw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(I=>I.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let I=await fa(r,e);if("error"in I){let C={error:I.error};if(Go(r)){let g=e.map?.allLayers.find(A=>A.id===r.layerId);C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else da(r)&&(C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:C}}if(!I.geometry){let C={};if(Go(r)){let g=e.map?.allLayers.find(A=>A.id===r.layerId);C.error=`No features found matching: ${r.where}`,C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else da(r)&&(C.error="Failed to create point geometry",C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:C}}i=I.geometry}else n&&(i=e.extent.clone());let u=Wi(s,t.outFields,n??!1),l=o.objectIdField,c=o.createQuery();c.where=pa(o.definitionExpression,t.where||"1=1"),c.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,l])],c.orderByFields=t.orderByFields,i&&(c.geometry=i,c.spatialRelationship="intersects"),r?.distance&&(c.distance=r.distance),r?.units&&(c.units=r.units),c.outSpatialReference=e.spatialReference;let p,m;try{p=u?await s.queryFeatureCount(c):await o.queryFeatureCount(c),p>0&&p<=zi&&(m=u?await s.queryFeatures(c):await o.queryFeatures(c))}catch(I){console.warn("Client-side query failed, falling back to server:",I),p=await o.queryFeatureCount(c),p>0&&p<=zi&&(m=await o.queryFeatures(c))}let{objectIds:h,attributes:_}=m?ip(o,m,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${p} features found`,details:{totalCount:p,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...h&&{objectIds:h,objectIdField:l},..._&&{attributes:_},...p>zi&&{note:`${p} features found.`}}}};async function Tw({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Vt(n),s=await vw(t,o,e,r);return JSON.stringify(s,null,2)}var Sw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),kw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Cw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.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:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.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:d.union([Sw,kw]).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:d.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).")}),Ew=D(Tw,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
187
+ 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:gw}),_w=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(m=>m.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let m=await fa(n,r);if("error"in m)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=m.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,c=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])];try{let m;if(l){let I=new Ng({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new jg({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});m=await s.queryTopFeatures(I)}else{let I=s.createQuery();I.where=pa(s.definitionExpression,t.where||"1=1"),I.outFields=p.length?p:["*"],I.orderByFields=e.orderByFields,I.num=e.topCount,u&&(I.geometry=u,I.spatialRelationship="intersects"),n?.distance&&(I.distance=n.distance),n?.units&&(I.units=n.units),I.outSpatialReference=r.spatialReference;let C=Wi(a,t.outFields,o??!1);try{m=C?await a.queryFeatures(I):await s.queryFeatures(I)}catch(g){console.warn("Client-side query failed, falling back to server:",g),m=await s.queryFeatures(I)}}let h=m.features.map(I=>I.attributes[c]),{attributes:_}=ip(s,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:_,objectIds:h,objectIdField:c,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},ww=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Vt(o),a=await _w(t,e,s,r,n);return JSON.stringify(a,null,2)},bw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),Aw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),xw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.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:d.union([bw,Aw]).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:d.object({topCount:d.number().describe("Number of top features to return per group."),orderByFields:d.array(d.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:d.array(d.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:d.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).")}),Iw=D(ww,{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:xw}),zi=25,vw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(I=>I.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let I=await fa(r,e);if("error"in I){let C={error:I.error};if(Go(r)){let g=e.map?.allLayers.find(A=>A.id===r.layerId);C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else da(r)&&(C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:C}}if(!I.geometry){let C={};if(Go(r)){let g=e.map?.allLayers.find(A=>A.id===r.layerId);C.error=`No features found matching: ${r.where}`,C.geometryLayerName=g?.title??g?.id,C.geometryLayerId=r.layerId,C.geometryWhere=r.where}else da(r)&&(C.error="Failed to create point geometry",C.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:C}}i=I.geometry}else n&&(i=e.extent.clone());let u=Wi(s,t.outFields,n??!1),l=o.objectIdField,c=o.createQuery();c.where=pa(o.definitionExpression,t.where||"1=1"),c.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,l])],c.orderByFields=t.orderByFields,i&&(c.geometry=i,c.spatialRelationship="intersects"),r?.distance&&(c.distance=r.distance),r?.units&&(c.units=r.units),c.outSpatialReference=e.spatialReference;let p,m;try{p=u?await s.queryFeatureCount(c):await o.queryFeatureCount(c),p>0&&p<=zi&&(m=u?await s.queryFeatures(c):await o.queryFeatures(c))}catch(I){console.warn("Client-side query failed, falling back to server:",I),p=await o.queryFeatureCount(c),p>0&&p<=zi&&(m=await o.queryFeatures(c))}let{objectIds:h,attributes:_}=m?ip(o,m,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${p} features found`,details:{totalCount:p,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...h&&{objectIds:h,objectIdField:l},..._&&{attributes:_},...p>zi&&{note:`${p} features found.`}}}};async function Tw({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Vt(n),s=await vw(t,o,e,r);return JSON.stringify(s,null,2)}var Sw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Gt.optional().describe("The units for the distance buffer.")}),kw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Gt.optional().describe("The units for the distance buffer.")}),Cw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.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:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.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:d.union([Sw,kw]).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:d.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).")}),Ew=D(Tw,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
188
188
 
189
189
  USE THIS TOOL FOR:
190
190
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -193,7 +193,7 @@ USE THIS TOOL FOR:
193
193
  - Spatial queries \u2014 finding features near/within/intersecting other features
194
194
  - Any question where the user wants to SEE or COUNT matching features
195
195
 
196
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Cw}),lp=[dw,yw,Iw,Ew];var hK=new ht(lp);var Ow=$.Root({...kr(),helpInternalState:$({reducer:Vo,default:()=>({toolCallMessage:void 0})})}),Mw=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
196
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Cw}),lp=[dw,yw,Iw,Ew];var gK=new ht(lp);var Ow=$.Root({...kr(),helpInternalState:$({reducer:Vo,default:()=>({toolCallMessage:void 0})})}),Mw=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
197
197
  `);return`**${r.layerItem.title}** has ${n.length} field(s):
198
198
 
199
199
  ${o}`},Pw=async({layerTitle:t},e)=>{let r=Xn(e,"layersAndFieldsRegistry");return Mw(r,t)},Rw=D(Pw,{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:d.object({layerTitle:d.string().describe("The title or partial title of the layer to list fields for.")})}),$w=$.Root({...kr(),intent:$({reducer:(t,e)=>e}),arcgisKnowledgeMessages:$({reducer:fo,default:()=>[]}),arcgisKnowledgeToolResult:$({reducer:(t,e)=>e,default:()=>null})}),ua={conversationId:""};function up(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function eo(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function ha(t){!t||eo(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function ga(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in e))throw new Error("View context missing");let r=e.view;return r.map&&!("activeLinkChartLayer"in r.map)&&up(r),{view:r}}async function to(t){let e=t?.configurable?.context;if(Nw(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let n=r.knowledgeGraph?.url;if(!n)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Qd(n)}}else{up(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await Qd(n)}}}}function Nw(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in e&&"view"in e)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in e)return"knowledgeGraph";if("view"in e)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var Fi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ma.fromDataModel(e)}},ma=class t{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(e){let r=new t;for(let n of e.entityTypes)r.entityTypes.push(Ho.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Ui.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:jw(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
@@ -261,7 +261,7 @@ ${a}`};async function _b(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
261
261
  ${o.results.length>s?`Showing top ${s} results:
262
262
 
263
263
  `:""}${a.map(i=>JSON.stringify(i)).join(`
264
- `)}`,details:{generatedQuery:n,searchResults:{...o}}}},Ab=D(bb,{name:hp,description:"Allows users to search the knowledge graph for text matching their inquiry, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.",schema:wb});var OK=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
264
+ `)}`,details:{generatedQuery:n,searchResults:{...o}}}},Ab=D(bb,{name:hp,description:"Allows users to search the knowledge graph for text matching their inquiry, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.",schema:wb});var MK=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
265
265
  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.
266
266
 
267
267
  Supported actions:
@@ -280,11 +280,11 @@ ${a}`};async function _b(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
280
280
  _Example: “Center the map on San Francisco at scale 50000”_
281
281
  _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
282
282
  _Example: “Go to the Downtown bookmark”_
283
- _Example: “Where is Mount Rainier?”_`;var r2=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.
283
+ _Example: “Where is Mount Rainier?”_`;var n2=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.
284
284
  _Example: “Color points by sales amount”_
285
285
  _Example: “Show population density with a color gradient”_
286
286
  _Example: “Create a relationship map between height and depth”_
287
- _Example: “Vary circle sizes according to population”_`;var v2=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).
287
+ _Example: “Vary circle sizes according to population”_`;var T2=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).
288
288
  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.
289
289
  _Example: “Only show stations where Brand is Shell”_
290
290
  _Example: “Make Shell stations stand out on the map”_
@@ -292,7 +292,7 @@ ${a}`};async function _b(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
292
292
  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.
293
293
  _Example: “How many features are there?”_
294
294
  _Example: “What’s the average population?”_
295
- _Example: “Which values are in the status field?”_`;var D2=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
295
+ _Example: “Which values are in the status field?”_`;var F2=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
296
296
 
297
297
  _Example: “Tell me about this map”_
298
298
  _Example: “List all layers in this map”_
@@ -305,7 +305,7 @@ ${a}`};async function _b(t,e){let r=await Wt("arcgis_knowledge_lucene_generation
305
305
 
306
306
  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.
307
307
  _Example: "Create a chart"_
308
- _Example: "Create a table"_`;var tW=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).
308
+ _Example: "Create a table"_`;var rW=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).
309
309
  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.
310
310
  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,
311
311
  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
@@ -343,7 +343,7 @@ _example: "Discover and add all the relationships originating at 'Entity E' to t
343
343
  _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
344
344
  _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
345
345
  _example: "Find John Smith and all people he has made phone calls to in the last year"_
346
- _example: "What is the average age of all people who work for Esri?"_`;var Or=Wo;var ze=re;var _a=()=>ia(),Ji=async(t,e)=>await Ae(t,e),Zi=async(t="default",e=0)=>await ji(t,e);var Zo=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},Tb=()=>({latestItemId:null,memory:{}}),Xi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:Tb()},Sb=d.object({intent:d.enum(["summarize","followUp","clarify"]),itemId:d.string().default(""),question:d.string().default("")}),kb=d.object({summary:d.string(),followUpQuestions:d.array(d.string()).default([])}),Cb=d.object({answer:d.string(),isRelevant:d.boolean()}),Eb=async(t,e)=>{await ze({text:"Answering follow-up...",agentName:"analytics"},e);let r=Xi(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Zo(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Or({promptText:Ob,schema:Cb,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Ob=`
346
+ _example: "What is the average age of all people who work for Esri?"_`;var Or=Wo;var ze=re;var _a=()=>ia(),Ji=async(t,e)=>await Ae(t,e),Zi=async({modelTier:t="default",temperature:e=0,abortSignal:r}={})=>await ji({modelTier:t,temperature:e,abortSignal:r});var Zo=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},Tb=()=>({latestItemId:null,memory:{}}),Xi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:Tb()},Sb=d.object({intent:d.enum(["summarize","followUp","clarify"]),itemId:d.string().default(""),question:d.string().default("")}),kb=d.object({summary:d.string(),followUpQuestions:d.array(d.string()).default([])}),Cb=d.object({answer:d.string(),isRelevant:d.boolean()}),Eb=async(t,e)=>{await ze({text:"Answering follow-up...",agentName:"analytics"},e);let r=Xi(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Zo(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Or({promptText:Ob,schema:Cb,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Ob=`
347
347
  You answer follow-up questions about an ArcGIS item.
348
348
 
349
349
  Ground your answer in the provided item context.
@@ -363,7 +363,7 @@ Item full context
363
363
 
364
364
  Question:
365
365
  {question}
366
- `;function ro(t){let{portal:e,user:r}=t??{};if(!t||!e||!r)throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var vp=D(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;ro(n);let{result:o,error:s}=await Rl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:d.object({itemTitle:d.string().describe("The portal item title to resolve to an item id.")})}),Mb=async(t,e)=>{await ze({text:"Analyzing intent...",agentName:"analytics"},e);let r=Zo(t.agentExecutionContext.messages),n=!!Xi(t).latestItemId,o=await po.fromTemplate(Pb).format({userMessage:r,hasSummaryContext:String(n)}),s=await _o({model:await Zi("fast"),tools:[vp],systemPrompt:o,responseFormat:Sb,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,itemId:i,question:u}=s.structuredResponse,l=a==="clarify"||a==="summarize"&&!i||a==="followUp"&&!u;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:l?"clarify":a,analyticsItemId:i||null,analyticsQuestion:u||"",status:"success",outputMessage:l?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Pb=`
366
+ `;function ro(t){let{portal:e,user:r}=t??{};if(!t||!e||!r)throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var vp=D(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;ro(n);let{result:o,error:s}=await Rl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:d.object({itemTitle:d.string().describe("The portal item title to resolve to an item id.")})}),Mb=async(t,e)=>{await ze({text:"Analyzing intent...",agentName:"analytics"},e);let r=Zo(t.agentExecutionContext.messages),n=!!Xi(t).latestItemId,o=await po.fromTemplate(Pb).format({userMessage:r,hasSummaryContext:String(n)}),s=await _o({model:await Zi({modelTier:"fast"}),tools:[vp],systemPrompt:o,responseFormat:Sb,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,itemId:i,question:u}=s.structuredResponse,l=a==="clarify"||a==="summarize"&&!i||a==="followUp"&&!u;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:l?"clarify":a,analyticsItemId:i||null,analyticsQuestion:u||"",status:"success",outputMessage:l?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Pb=`
367
367
  Classify the user analytics request.
368
368
 
369
369
  Rules:
@@ -486,7 +486,7 @@ User message:
486
486
  `,Zb=d.discriminatedUnion("destinationType",[d.object({destinationType:d.literal("portal-content")}),d.object({destinationType:d.literal("portal-groups")}),d.object({destinationType:d.literal("portal-item"),itemId:d.string().trim().min(1)}),d.object({destinationType:d.literal("portal-group"),groupId:d.string().trim().min(1)})]);function Qb(t){let e=Zb.safeParse(t);return e.success?e.data:void 0}var Sp="portal-navigation",kp=async(t,e)=>{await Ji({type:Sp,data:{...t}},e)},Yb=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ze({text:"Preparing navigation...",agentName:"group-creation"},e),await kp({destinationType:"portal-group",groupId:r},e),{}):{}},xp=(t,e)=>e??t,Cp=$.Root({..._a(),intentParams:$({reducer:xp,default:()=>({intent:"clarify"})}),createdGroupId:$({reducer:xp,default:()=>""})}),Xb=()=>new ye(Cp).addNode("detectGroupCreationIntent",Hb).addNode("createPortalGroup",Kb).addNode("addMembersToPortalGroup",Fb).addNode("suggestCreatedGroupNavigation",Yb).addEdge(he,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return B}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",B),eA=String.raw`- **portal-group-creation** - Portal group creation assistant:
487
487
  - creates a new ArcGIS Portal group for the signed-in user
488
488
  - adds users to the newly created group using @mention usernames
489
- `,tA={id:"portal-group-creation",name:"Portal Group Creation",description:eA,createGraph:Xb,workspace:Cp},Ep="portalDocAssistantMemory",rA=()=>({conversationId:""}),nA=t=>{let e=t?.[Ep]?.value;if(!e||typeof e!="object")return rA();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},oA=t=>({[Ep]:{value:t}});async function sA({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await aA({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:iA(a,s),conversationId:a[0]?.conversationId??""}}async function aA({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:vb.findCredential(t.url)?.token??""},a=await yp(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:c}=i,p=async(m,h)=>{if(!h)return;await il(1e3);let _=await yp(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:c,ackSequenceNumber:m}),headers:s,signal:n.signal});if(_.httpStatus!==200)throw new Error(`Doc assistant poll failed (${_.httpStatus})`,{cause:_.data});let I=_.data;u.push(I),await p(I.sequenceNumber,I.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function iA(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return so(e)}}var lA=async(t,e)=>{await ze({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Zo(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;ro(n);let o=nA(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await sA({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"developers"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:oA({conversationId:a||o.conversationId})}},uA=D(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;ro(n);try{return(await Nl(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:d.object({groupTitle:d.string().describe("The portal group title to resolve to a group id.")})}),Ip=d.object({shouldSuggestNavigation:d.boolean().default(!1),destinationType:d.enum(["none","portal-content","portal-item","portal-groups","portal-group"]).default("none"),itemId:d.string().default(""),groupId:d.string().default("")}),cA=async(t,e)=>{await ze({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Zo(t.agentExecutionContext.messages).trim(),o=await po.fromTemplate(pA).format({question:n,response:r}),s=await _o({model:await Zi("default"),tools:[vp,uA],systemPrompt:o,responseFormat:Ip,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),a=Ip.parse(s.structuredResponse??{});if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};let i=dA(a);return i?(await kp(i,e),{}):{}};function dA({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":return{destinationType:"portal-content"};case"portal-groups":return{destinationType:"portal-groups"};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return so(t)}}var pA=`
489
+ `,tA={id:"portal-group-creation",name:"Portal Group Creation",description:eA,createGraph:Xb,workspace:Cp},Ep="portalDocAssistantMemory",rA=()=>({conversationId:""}),nA=t=>{let e=t?.[Ep]?.value;if(!e||typeof e!="object")return rA();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},oA=t=>({[Ep]:{value:t}});async function sA({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await aA({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:iA(a,s),conversationId:a[0]?.conversationId??""}}async function aA({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:vb.findCredential(t.url)?.token??""},a=await yp(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:c}=i,p=async(m,h)=>{if(!h)return;await il(1e3);let _=await yp(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:c,ackSequenceNumber:m}),headers:s,signal:n.signal});if(_.httpStatus!==200)throw new Error(`Doc assistant poll failed (${_.httpStatus})`,{cause:_.data});let I=_.data;u.push(I),await p(I.sequenceNumber,I.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function iA(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return so(e)}}var lA=async(t,e)=>{await ze({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Zo(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;ro(n);let o=nA(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await sA({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"developers"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:oA({conversationId:a||o.conversationId})}},uA=D(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;ro(n);try{return(await Nl(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:d.object({groupTitle:d.string().describe("The portal group title to resolve to a group id.")})}),Ip=d.object({shouldSuggestNavigation:d.boolean().default(!1),destinationType:d.enum(["none","portal-content","portal-item","portal-groups","portal-group"]).default("none"),itemId:d.string().default(""),groupId:d.string().default("")}),cA=async(t,e)=>{await ze({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Zo(t.agentExecutionContext.messages).trim(),o=await po.fromTemplate(pA).format({question:n,response:r}),s=await _o({model:await Zi({modelTier:"default"}),tools:[vp,uA],systemPrompt:o,responseFormat:Ip,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),a=Ip.parse(s.structuredResponse??{});if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};let i=dA(a);return i?(await kp(i,e),{}):{}};function dA({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":return{destinationType:"portal-content"};case"portal-groups":return{destinationType:"portal-groups"};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return so(t)}}var pA=`
490
490
  You decide whether the assistant response should include a navigation action to ArcGIS Portal.
491
491
 
492
492
  Given the user question and assistant response:
package/dist/cdn/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{O as t,y as e}from"./ADZOZHQC.js";import"./CFDTXKJ6.js";var a=e(t,{"arcgis-portal-ai-assistant":[()=>import("./ZYJMB7IU.js"),"autoDestroyDisabled,config:,defaultClosed,portal:,t9n:,user:"],"arcgis-portal-ai-assistant-interrupt":[()=>import("./PVDX36UB.js"),"_messages:,message,options:,type"],"arcgis-portal-classification-banner":[()=>import("./MUVBI5FC.js"),"autoDestroyDisabled,messages:,missingExistingClassification,portalItem:,validationErrors,variant;destroy"],"arcgis-portal-classification-config":[()=>import("./WDSJYJ5S.js"),"autoDestroyDisabled,messages:,portalItem:,status,valid,values;destroy,resetForm,validateForm"],"arcgis-portal-classification-favorite":[()=>import("./ZOKEGSM2.js"),"attributeExpressionResults:,classificationValue:,favoriteClassifications:,messages:,portalItem:,resetFavoriteClassification:,selectedFavoriteClassificationName,updateClassificationData:"],"arcgis-portal-classification-form-element":[()=>import("./UKINSKXQ.js"),"attribute:,attributeKey,isRequiredErrors:,messages:,renderingInfo:,value:"],"arcgis-portal-extent-picker":[()=>import("./VV5N7ZZT.js"),"active,contentOnly,extentService,extentValue:,isArea,itemId,messages:,portal:;;getExtent"],"arcgis-portal-extent-picker-coord-field":[()=>import("./KQOPA62F.js"),"errorMessage,inputId,label,max,min,relatedErrorMessage,validateRelated:,value;;checkRelatedField,isValid,setFocus"],"arcgis-portal-field-delete":[()=>import("./TQLNWCB2.js"),"config:,fieldNames:,layer:,mapView:,messages:,options:"],"arcgis-portal-item-type":[()=>import("./PAJUJTR7.js"),"ellipsis,hideIcon,hideText,item:,messages:,portal:,scale,serviceInfo:,showHosted,user:"],"arcgis-portal-mentionable-text-area":[()=>import("./UZI3SZ4Q.js"),"disabled,maxLength,placeholder,popoverListLabel,popoverPlacement,portal:,readOnly,rows,scale,starters:,user:,value;closePopover,focusTextArea,selectItem"],"arcgis-portal-replacement-item-redirect":[()=>import("./YR52C7CN.js"),"itemId,messages:,portal:,user:;setFocus"],"arcgis-portal-user-avatar":[()=>import("./5NFLNDY2.js"),"checkOnline,description,heading,hideAvatar,messages:,portal:,scale,showName,underline,user:,username,wrap"],"arcgis-portal-voice-input":[()=>import("./SZRHACUV.js"),"language;clearText,startListening,stopListening"]});a({resourcesUrl:import.meta.url});var s=new CSSStyleSheet;s.replaceSync("@layer{:not([hydrated]):is(arcgis-portal-ai-assistant,arcgis-portal-ai-assistant-interrupt,arcgis-portal-classification-banner,arcgis-portal-classification-config,arcgis-portal-classification-favorite,arcgis-portal-classification-form-element,arcgis-portal-extent-picker,arcgis-portal-field-delete,arcgis-portal-item-type,arcgis-portal-mentionable-text-area,arcgis-portal-replacement-item-redirect,arcgis-portal-user-avatar,arcgis-portal-voice-input){visibility:hidden}}");document.adoptedStyleSheets=[...document.adoptedStyleSheets,s];window.$arcgis||Object.defineProperty(window,"$arcgis",{configurable:!1,enumerable:!0,writable:!1,value:{}}),((a,r)=>{a.t=(c,...x)=>Promise.all(x.map(x=>x.then?x:(!a?.forceESM&&a?.import||(x=>import(x+".js").then(m=>m.default??m)))("@arcgis/core/"+x))).then(c);r.p=a.t(([m])=>{r.t=m.trackAccess;r.o=m.createObservable;r.c=m.createTrackingTarget;r.r=m.runTracked},"applications/Components/reactiveUtils")})($arcgis,t)
2
+ import{O as t,y as e}from"./ADZOZHQC.js";import"./CFDTXKJ6.js";var a=e(t,{"arcgis-portal-ai-assistant":[()=>import("./VVYLDL5V.js"),"autoDestroyDisabled,config:,defaultClosed,portal:,t9n:,user:"],"arcgis-portal-ai-assistant-interrupt":[()=>import("./PVDX36UB.js"),"_messages:,message,options:,type"],"arcgis-portal-classification-banner":[()=>import("./MUVBI5FC.js"),"autoDestroyDisabled,messages:,missingExistingClassification,portalItem:,validationErrors,variant;destroy"],"arcgis-portal-classification-config":[()=>import("./WDSJYJ5S.js"),"autoDestroyDisabled,messages:,portalItem:,status,valid,values;destroy,resetForm,validateForm"],"arcgis-portal-classification-favorite":[()=>import("./ZOKEGSM2.js"),"attributeExpressionResults:,classificationValue:,favoriteClassifications:,messages:,portalItem:,resetFavoriteClassification:,selectedFavoriteClassificationName,updateClassificationData:"],"arcgis-portal-classification-form-element":[()=>import("./UKINSKXQ.js"),"attribute:,attributeKey,isRequiredErrors:,messages:,renderingInfo:,value:"],"arcgis-portal-extent-picker":[()=>import("./VV5N7ZZT.js"),"active,contentOnly,extentService,extentValue:,isArea,itemId,messages:,portal:;;getExtent"],"arcgis-portal-extent-picker-coord-field":[()=>import("./KQOPA62F.js"),"errorMessage,inputId,label,max,min,relatedErrorMessage,validateRelated:,value;;checkRelatedField,isValid,setFocus"],"arcgis-portal-field-delete":[()=>import("./TQLNWCB2.js"),"config:,fieldNames:,layer:,mapView:,messages:,options:"],"arcgis-portal-item-type":[()=>import("./PAJUJTR7.js"),"ellipsis,hideIcon,hideText,item:,messages:,portal:,scale,serviceInfo:,showHosted,user:"],"arcgis-portal-mentionable-text-area":[()=>import("./UZI3SZ4Q.js"),"disabled,maxLength,placeholder,popoverListLabel,popoverPlacement,portal:,readOnly,rows,scale,starters:,user:,value;closePopover,focusTextArea,selectItem"],"arcgis-portal-replacement-item-redirect":[()=>import("./YR52C7CN.js"),"itemId,messages:,portal:,user:;setFocus"],"arcgis-portal-user-avatar":[()=>import("./5NFLNDY2.js"),"checkOnline,description,heading,hideAvatar,messages:,portal:,scale,showName,underline,user:,username,wrap"],"arcgis-portal-voice-input":[()=>import("./SZRHACUV.js"),"language;clearText,startListening,stopListening"]});a({resourcesUrl:import.meta.url});var s=new CSSStyleSheet;s.replaceSync("@layer{:not([hydrated]):is(arcgis-portal-ai-assistant,arcgis-portal-ai-assistant-interrupt,arcgis-portal-classification-banner,arcgis-portal-classification-config,arcgis-portal-classification-favorite,arcgis-portal-classification-form-element,arcgis-portal-extent-picker,arcgis-portal-field-delete,arcgis-portal-item-type,arcgis-portal-mentionable-text-area,arcgis-portal-replacement-item-redirect,arcgis-portal-user-avatar,arcgis-portal-voice-input){visibility:hidden}}");document.adoptedStyleSheets=[...document.adoptedStyleSheets,s];window.$arcgis||Object.defineProperty(window,"$arcgis",{configurable:!1,enumerable:!0,writable:!1,value:{}}),((a,r)=>{a.t=(c,...x)=>Promise.all(x.map(x=>x.then?x:(!a?.forceESM&&a?.import||(x=>import(x+".js").then(m=>m.default??m)))("@arcgis/core/"+x))).then(c);r.p=a.t(([m])=>{r.t=m.trackAccess;r.o=m.createObservable;r.c=m.createTrackingTarget;r.r=m.runTracked},"applications/Components/reactiveUtils")})($arcgis,t)
@@ -104,7 +104,7 @@ const W = K(
104
104
  userMessage: e,
105
105
  hasSummaryContext: String(a)
106
106
  }), c = await Q({
107
- model: await F("fast"),
107
+ model: await F({ modelTier: "fast" }),
108
108
  tools: [W],
109
109
  systemPrompt: r,
110
110
  responseFormat: gt,
@@ -675,7 +675,7 @@ const Yt = async (s, t) => {
675
675
  question: a,
676
676
  response: e
677
677
  }), c = await Q({
678
- model: await F("default"),
678
+ model: await F({ modelTier: "default" }),
679
679
  tools: [W, Ht],
680
680
  systemPrompt: r,
681
681
  responseFormat: j,