@arcgis/ai-components 5.2.0-next.1 → 5.2.0-next.11
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.
- package/dist/agent-utils/FunctionAgent.d.ts +2 -2
- package/dist/agent-utils/LLMAgent.d.ts +2 -2
- package/dist/agent-utils/LLMAgent.js +22 -22
- package/dist/agent-utils/WorkflowAgent.d.ts +2 -2
- package/dist/agent-utils/index.d.ts +99 -0
- package/dist/agent-utils/index.js +148 -0
- package/dist/agent-utils/middlewares/trace.js +25 -33
- package/dist/agent-utils/tools/FunctionTool.d.ts +2 -2
- package/dist/agent-utils/types.d.ts +30 -1
- package/dist/agent-utils/workflows/ConditionalWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/LoopWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/ParallelWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/RouterWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/SequentialWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/SwitchWorkflow.d.ts +2 -2
- package/dist/cdn/{V2P4AIGG.js → 24QNMEFG.js} +1 -1
- package/dist/cdn/{NAUXSHIE.js → 34SG44C3.js} +2 -2
- package/dist/cdn/3JGWGKT6.js +2 -0
- package/dist/cdn/3NBDVZ2I.js +2 -0
- package/dist/cdn/3VOQD2MR.js +2 -0
- package/dist/cdn/434TAA3J.js +2 -0
- package/dist/cdn/53NTYC4I.js +2 -0
- package/dist/cdn/{4HU7735A.js → 5CV7R5IS.js} +6 -4
- package/dist/cdn/{AMP6IALT.js → 5W7S2RS4.js} +1 -1
- package/dist/cdn/{FL4W4VYN.js → 6ZW7Z36F.js} +16 -0
- package/dist/cdn/7CYGX4F4.js +2 -0
- package/dist/cdn/{DHOVCT6R.js → AZGGTNA3.js} +1 -1
- package/dist/cdn/B7WJFBOZ.js +2 -0
- package/dist/cdn/BX7FSMUU.js +56 -0
- package/dist/cdn/CHPQM77M.js +181 -0
- package/dist/cdn/DHKUXLU3.js +179 -0
- package/dist/cdn/DQSEBKOX.js +2 -0
- package/dist/cdn/DXVU45KM.js +2 -0
- package/dist/cdn/{P6OPJQMC.js → DZ2QWNUA.js} +1 -1
- package/dist/cdn/EBISDZ5H.js +2 -0
- package/dist/cdn/{MDVYQQUG.js → ERL2CB2Y.js} +5 -5
- package/dist/cdn/F6QHMKF5.js +2 -0
- package/dist/cdn/FUIGPHBH.js +2 -0
- package/dist/cdn/{AO7BQHKC.js → H2CHHGGH.js} +1 -1
- package/dist/cdn/{OH64RMOR.js → HWKDNS4K.js} +2 -2
- package/dist/cdn/IMQ4TVHF.js +16 -0
- package/dist/cdn/IOD3GDA7.js +2 -0
- package/dist/cdn/IR7PTESF.js +2 -0
- package/dist/cdn/IRZDTYO2.js +2 -0
- package/dist/cdn/JIWK6QK6.js +2 -0
- package/dist/cdn/{S6W6HV4T.js → JLKGS6Y5.js} +12 -12
- package/dist/cdn/K3JCH4XW.js +2 -0
- package/dist/cdn/KHXUWZHB.js +2 -0
- package/dist/cdn/LIFK3QSD.js +2 -0
- package/dist/cdn/NXKKG5TK.js +2 -0
- package/dist/cdn/{FX5JFRDL.js → O3EN27N5.js} +1 -1
- package/dist/cdn/O3RFFPU3.js +6 -0
- package/dist/cdn/P7DG5T3Z.js +9 -0
- package/dist/cdn/PBO6FZN6.js +2 -0
- package/dist/cdn/Q3ZW4FYA.js +3 -0
- package/dist/cdn/Q6LRANX6.js +2 -0
- package/dist/cdn/Q7TL5Q5N.js +2 -0
- package/dist/cdn/QCSN44H4.js +2 -0
- package/dist/cdn/R56X6ZKR.js +161 -0
- package/dist/cdn/{HB5A5R2E.js → RUURNLTP.js} +1 -1
- package/dist/cdn/T43LEBBE.js +47 -0
- package/dist/cdn/{ZLXN7NMF.js → T537PKP4.js} +9 -7
- package/dist/cdn/TR4GFL7X.js +2 -0
- package/dist/cdn/{3PKJWIC3.js → UPEEHMSY.js} +1 -1
- package/dist/cdn/WAIFKDR3.js +2 -0
- package/dist/cdn/WNS5ZUF5.js +2 -0
- package/dist/cdn/X4XY5HIE.js +2 -0
- package/dist/cdn/XOH56EQ2.js +2 -0
- package/dist/cdn/XON27U6U.js +2 -0
- package/dist/cdn/{H7422XUG.js → YLN2BZ5J.js} +1 -1
- package/dist/cdn/{2AXF774U.js → YUKR4AZW.js} +1 -1
- package/dist/cdn/{JY6LLOUJ.js → Z2G7MP5L.js} +3 -3
- package/dist/cdn/ZEYIBYSF.js +66 -0
- package/dist/cdn/agent-utils/index.js +2 -0
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +3 -0
- package/dist/cdn/agent-utils/middlewares/middleware.js +2 -0
- package/dist/cdn/agent-utils/middlewares/trace.js +2 -0
- package/dist/cdn/index.js +1 -1
- package/dist/cdn/main.css +1 -1
- package/dist/chunks/adapter.js +1390 -1323
- package/dist/chunks/arcgisKnowledgeGraph.js +109 -72
- package/dist/chunks/dataExplorationGraph.js +108 -96
- package/dist/chunks/generateLayerDescriptions.js +206 -168
- package/dist/chunks/helpGraph.js +16 -13
- package/dist/chunks/index.js +11 -0
- package/dist/chunks/intent_prompt.js +16 -0
- package/dist/chunks/layerStylingGraph.js +23 -20
- package/dist/chunks/navigationGraph.js +34 -30
- package/dist/chunks/orchestrator.js +241 -201
- package/dist/chunks/slottableRequestUtils.js +3 -7
- package/dist/chunks/summarize_query_response_prompt.js +9 -7
- package/dist/chunks/toolCallResponse.js +5 -3
- package/dist/components/arcgis-assistant/customElement.d.ts +15 -0
- package/dist/components/arcgis-assistant/customElement.js +228 -127
- package/dist/components/arcgis-assistant/index.js +2 -3
- package/dist/components/arcgis-assistant/types.d.ts +14 -1
- package/dist/components/arcgis-assistant-chat/customElement.d.ts +8 -2
- package/dist/components/arcgis-assistant-chat/customElement.js +7 -7
- package/dist/components/arcgis-assistant-chat-entry/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-chat-entry/customElement.js +25 -18
- package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-help-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-interrupt/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-interrupt/customElement.js +13 -9
- package/dist/components/arcgis-assistant-interrupt-preview/customElement.js +20 -0
- package/dist/components/arcgis-assistant-interrupt-preview/index.js +2 -0
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.d.ts +7 -7
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-message/customElement.d.ts +23 -0
- package/dist/components/arcgis-assistant-message/customElement.js +28 -26
- package/dist/components/arcgis-assistant-message/index.d.ts +1 -0
- package/dist/components/arcgis-assistant-message/index.js +2 -0
- package/dist/components/arcgis-assistant-message-block/customElement.d.ts +1 -1
- package/dist/components/arcgis-assistant-message-block/customElement.js +18 -11
- package/dist/components/arcgis-assistant-message-block/index.js +1 -0
- package/dist/components/arcgis-assistant-message-feedback/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-footer/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-loading/customElement.d.ts +8 -1
- package/dist/components/arcgis-assistant-message-loading/customElement.js +8 -8
- package/dist/components/arcgis-assistant-message-loading/index.js +1 -0
- package/dist/components/arcgis-assistant-message-log/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-read-aloud/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-text/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -0
- package/dist/components/arcgis-assistant-speech-input/customElement.d.ts +6 -1
- package/dist/components/arcgis-assistant-suggested-prompts/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-suggested-prompts/customElement.js +8 -8
- package/dist/components/arcgis-assistant-user-message/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-user-message/customElement.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/vscode.html-custom-data.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/loader.js +6 -5
- package/dist/orchestrator/registry/agentRegistry.d.ts +33 -0
- package/dist/types/lumina.d.ts +10 -4
- package/dist/types/preact.d.ts +11 -4
- package/dist/types/react.d.ts +12 -4
- package/dist/types/stencil.d.ts +10 -4
- package/dist/utils/index.d.ts +87 -43
- package/dist/utils/index.js +54 -49
- package/package.json +8 -7
- package/dist/cdn/462JBSEV.js +0 -422
- package/dist/cdn/7BCR6TUO.js +0 -2
- package/dist/cdn/7GH7VSB2.js +0 -2
- package/dist/cdn/7PLV4QH6.js +0 -2
- package/dist/cdn/DDLZOMUY.js +0 -2
- package/dist/cdn/FHVXO2WG.js +0 -166
- package/dist/cdn/GSEPHN3A.js +0 -106
- package/dist/cdn/MH5RPXHM.js +0 -2
- package/dist/cdn/NVI3I46B.js +0 -2
- package/dist/cdn/OAVEHGB6.js +0 -2
- package/dist/cdn/ON2V5XI2.js +0 -3
- package/dist/cdn/QR54T33D.js +0 -2
- package/dist/cdn/RVOAPUBN.js +0 -2
- package/dist/cdn/SXDLXCIM.js +0 -2
- package/dist/cdn/USMDJUFS.js +0 -2
- package/dist/cdn/V5YEZSRY.js +0 -16
- package/dist/cdn/Y333DGV6.js +0 -2
- package/dist/cdn/YY2SBO3V.js +0 -2
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{a as I}from"./434TAA3J.js";import a from"./T43LEBBE.js";import{a as M}from"./YLN2BZ5J.js";import"./QCSN44H4.js";import{a as B}from"./5W7S2RS4.js";import"./NXKKG5TK.js";import{g as A,h as g,l as L,n as p,t as v,u as E,v as P,x as S,z as D}from"./HWKDNS4K.js";import{a as y}from"./P7DG5T3Z.js";import"./BX7FSMUU.js";import{U as H,a as O,b as F,ta as T,u as W}from"./DHKUXLU3.js";import{Z as q,ja as j}from"./CHPQM77M.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([xe,{whenOnce:Ie,watch:Ce,when:Re},$e,ee,te,X,se,re,Ae,,,Le,{property:b,subclass:Pe},{a:N,d:z,e:x,g:U,h:V,i:G}])=>{var ie=async r=>{let e=await ne(),t=await N("default"),i=te.getDefault(),s=(await ee.getCredential(`${i.url}/sharing`)).token,a={type:"generateEmbeddings",webmapEmbeddings:r,auth:{apiUrl:t,token:s}};return e.postMessage(a),await new Promise((n,o)=>{let c=d=>{d.data==="completed"&&(e.removeEventListener("message",c),n())},l=d=>{e.removeEventListener("message",c),o(d instanceof Error?d:new Error("Embeddings worker error"))};e.addEventListener("message",c),e.addEventListener("error",l,{once:!0})}),e},ne=async()=>{{let r=(await import("./23EQTPO3.js")).default;return new r}},ae=r=>{r.currentIntent="none"},oe=async(r,e)=>{let t=x(e);if(r.agentExecutionContext.userRequest){let s=new j(r.agentExecutionContext.userRequest.trim());r.agentExecutionContext.messages=[...r.agentExecutionContext.messages,s],ae(r)}let i=t?.services.agentRegistry.list().map(s=>s.agent.id)??[];return await y({text:`Available agents: ${[...i].join(", ")}`},e),await y({text:"Analyzing user input"},e),r},ce=async(r,e)=>(await y({text:"Exiting..."},e),r),Q=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),le=(r,e)=>{if(!Q(r)){r!==void 0&&console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);return}let t={};for(let[i,s]of Object.entries(r)){if(!Q(s)||!("value"in s)){console.warn(`Agent "${e}" returned invalid sharedStatePatch entry for key "${i}". Ignoring that entry.`);continue}t[i]={value:s.value}}return t},de=r=>{let{previousSharedState:e,patch:t,agentId:i}=r;if(!t)return e;let s=Date.now(),a={...e};for(let[n,o]of Object.entries(t))o?.value!==void 0&&(a[n]={value:o.value,meta:{updatedByAgentId:i,updatedAt:s}});return a},J=r=>typeof r!="string"?void 0:r.trim()||void 0,ge=r=>{switch(r){case"failed":return"Agent failed without a summary.";case"unknown":return"Agent returned with unknown status.";case"success":return"Agent completed without a summary.";default:return"Agent completed without a summary."}},he=(r,e)=>{let t=J(e?.outputMessage),i=J(e?.summary),s=e?.status,a=s==="success"||s==="failed"?s:"unknown";a==="unknown"&&console.warn(`Agent "${r}" returned missing/invalid status. Defaulting to "unknown".`);let n=le(e?.sharedStatePatch,r);return{outputMessage:t,summary:i??t??ge(a),status:a,sharedStatePatch:n}},K=4e3,ue=async(r,e)=>{let t=x(e);if(t?.abortSignal?.aborted)return await y({text:"Run cancelled; skipping agent execution"},e),{...r,currentIntent:"none",requiresFollowUp:!1};let{agentRegistry:i}=t?.services??{},s=i?.get(r.currentIntent);if(!s)return console.warn(`No agent found for intent: ${r.currentIntent}`),r;await y({text:`Executing registered agent: ${s.agent.name}`},e);let a={...e??{},configurable:{...t??{},agentId:s.agent.id,context:s.getContext?await s.getContext():void 0}},n;try{let l=await s.agent.createGraph().compile().invoke({agentExecutionContext:{...r.agentExecutionContext,messages:[...r.agentExecutionContext.messages],priorSteps:structuredClone(r.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(r.agentExecutionContext.sharedState??{})}},a);n=he(s.agent.name,l),await y({text:`Finished executing registered agent: ${s.agent.name}`},e)}catch(l){if(W(l))throw l;let d=l instanceof Error?l.message:String(l);console.error(`Agent "${s.agent.name}" failed:`,l),await y({text:`Registered agent failed: ${s.agent.name}. ${d}`},e),n={status:"failed",outputMessage:`Agent execution failed: ${d}`,summary:`Agent execution failed: ${d}`}}let o=n.outputMessage,c=[...r.agentExecutionContext.messages];if(o){let l=o.length>K?`${o.slice(0,K-14)}
|
|
3
|
+
[truncated]`:o;c.push(new q(l))}return{...r,stepCount:r.stepCount+1,lastExecutedAgent:s.agent.id,requiresFollowUp:n.status==="failed"?!0:r.requiresFollowUp,finalOutputMessage:o??"",agentExecutionContext:{...r.agentExecutionContext,messages:c,priorSteps:[...r.agentExecutionContext.priorSteps??[],{agentId:s.agent.id,assignedTask:r.agentExecutionContext.assignedTask,summary:n?.summary||"No summary provided.",status:n?.status||"unknown"}],sharedState:de({previousSharedState:r.agentExecutionContext.sharedState,patch:n.sharedStatePatch,agentId:s.agent.id})}}},pe=3,me=()=>new T(z).addNode("ingestInput",oe).addNode("intentLLM",V).addNode("executeRegisteredAgent",ue).addNode("exit",ce).addEdge(O,"ingestInput").addEdge("ingestInput","intentLLM").addConditionalEdges("intentLLM",r=>r.currentIntent==="none"||r.currentIntent===r.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",r=>r.stepCount>=pe||!r.requiresFollowUp?"exit":"intentLLM").addEdge("exit",F),C=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:t}=e;if(this.agentRegistry.has(t.id))throw new Error(`Duplicate agent id: ${t.id}`);this.agentRegistry.set(t.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},R=class{constructor(e,t){this.graph=e,this.config={...t}}async waitForUser(){return await new Promise((e,t)=>{this.resolveWait=e,this.rejectWait=t})}handle(e,t){try{let i={agentId:e.agentId,id:e.id,payload:t},s=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:i},subgraphs:!0,version:"v2"});this.resolveWait?.(s)}catch(i){this.rejectWait?.(i)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("Request cancelled by user.")),this.resolveWait=void 0,this.rejectWait=void 0)}},ye=async r=>{try{return await(await U()).embedDocuments(r)}catch(e){throw console.error("Failed to generate embeddings:",e),e}},Y=async(r,e)=>{let t=e.get(r);if(t)return t;let i=await ye([r]);return e.set(r,i[0]),i[0]};async function we(r,e,t,i){let s=`req-${Date.now()}`,a={type:"layerSearch",precomputedEmbedding:i?await Y(r,i):void 0,requestId:s,minScore:t};return await new Promise(n=>{let o=c=>{c.data.requestId===s&&n(c.data.results)};e.addEventListener("message",o,{once:!0}),e.postMessage(a)})}function be(r){let{worker:e}=r;return{async searchLayers({text:t,minScore:i,embeddingCache:s}){return await we(t,e,i,s)}}}var fe=async({combinedQuery:r,layerIds:e,embeddingsWorker:t,minScore:i,topResults:s,embeddingCache:a})=>{let n=`req-${Date.now()}`,o=a?await Y(r,a):void 0,c={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:o,requestId:n,minScore:i,topResults:s};return await new Promise(l=>{let d=h=>{if(h.data.requestId!==n)return;let u=h.data.results.map(({layerId:f,results:_})=>({layerId:f,results:_}));l(u)};t.addEventListener("message",d,{once:!0}),t.postMessage(c)})};function ve(r){let{worker:e}=r;return{async searchFields({text:t,layerIds:i,minScore:s,topResults:a,embeddingCache:n}){return await fe({combinedQuery:t,layerIds:i,embeddingsWorker:e,minScore:s,topResults:a,embeddingCache:n})}}}var Ee=r=>{let e=G.safeParse(r);if(!e.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return e.data},ke=(r,e)=>{let t=new Map,i=new Map;if(e.allLayers.forEach(s=>{s instanceof se&&i.set(s.id,s)}),r.length!==i.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let s of r){let a=i.get(s.id);if(!a)throw new Error(`Layer with ID ${s.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(s.fields.length!==a.fields.length)throw new Error(`Field count mismatch for layer ID ${s.id} during registry restoration. Regenerate embeddings.`);let n={name:s.name,title:s.title,description:s.description},o=new Map;for(let c of s.fields){let l=a.fieldsIndex.get(c.name);if(!l)throw new Error(`Field with name ${c.name} not found in the original layer ${s.id} during registry restoration. Regenerate embeddings.`);o.set(c.name,{name:c.name,alias:a.getFieldAlias(c.name)??c.alias,description:c.description,type:l.type||"unknown",valueType:l.valueType||"unknown",domain:a.getFieldDomain(c.name)??void 0})}t.set(s.id,{layerItem:n,fieldRegistry:o})}return t},_e=async r=>{try{return(await re(r,{responseType:"json"})).data}catch(e){throw new Error(`Failed to fetch data from ${r}: ${String(e)}`)}},Se=async r=>{let e=r.map;if(!e?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:t}=await e.portalItem.fetchResources(),i=t.find(a=>a.resource.path==="embeddings-v01.json");if(!i?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let s=await _e(i.resource.url);return Ee(s)},k=class r{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.agentRegistry=new C,this.activeRunId="",this.cancelledRunIds=new Set,this.streamEpoch=0}static async init(e){let t=new r;try{if(e.view?.map){await X.whenOnce(()=>e.view.ready);let i=await Se(e.view),s=ke(i.layers,e.view.map);t.layersAndFieldsRegistry=s,t.embeddingsWorker=await ie(i)}return e.agents?.forEach(i=>{t.agentRegistry.register(i)}),t.orchestratorReady=!0,t}catch(i){throw console.error("Orchestrator initialization failed:",i),i}}async*ask(e){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!e.trim())return;let t=crypto.randomUUID();this.activeRunId=t,this.activeAbortController=new AbortController,this.graph||(this.graph=me().compile({checkpointer:new H}));let i=this.embeddingsWorker?be({worker:this.embeddingsWorker}):void 0,s=this.embeddingsWorker?ve({worker:this.embeddingsWorker}):void 0,a=new Map,n={version:"v2",streamMode:"custom",configurable:{thread_id:t,abortSignal:this.activeAbortController.signal,hitlResponse:null,services:{layerSearch:i,fieldSearch:s,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:a}},subgraphs:!0},o=this.graph?.streamEvents({agentExecutionContext:{userRequest:e,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},n),c=++this.streamEpoch;if(yield*this.pipeStream(o,c,t),this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}for(;;){if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let d=(await this.graph.getState(n,{subgraphs:!0})).tasks.find(h=>h.interrupts.length>0)?.interrupts[0]?.value;if(!d)break;this.currentInterrupt=d,this.interruptHandler=new R(this.graph,n),yield{runId:t,timestamp:Date.now(),type:"interrupt",interrupt:d};try{let h=await this.interruptHandler.waitForUser(),u=++this.streamEpoch;yield*this.pipeStream(h,u,t)}catch(h){if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}if(h){yield{runId:t,timestamp:Date.now(),type:"error",error:{message:h?.message}};return}}}if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let l=(await this.graph.getState(n,{subgraphs:!0})).values;if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}this.chatHistory=l.agentExecutionContext.messages.length?l.agentExecutionContext.messages:this.chatHistory,this.priorSteps=l.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=l.agentExecutionContext.sharedState??{},yield{runId:t,timestamp:Date.now(),type:"completed",result:{content:l.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}resumeInterrupt(e){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,e)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}cancel(){this.activeRunId&&(this.cancelledRunIds.add(this.activeRunId),this.activeAbortController?.abort(),++this.streamEpoch,this.interruptHandler?.cancel())}async*pipeStream(e,t,i){for await(let s of e){if(this.isRunCancelled(i)||t!==this.streamEpoch)break;s.event==="on_custom_event"&&s.name==="trace_message"?yield{runId:i,timestamp:Date.now(),type:"trace",data:s.data}:s.name==="graph_ux_suggestion"&&(yield{runId:i,timestamp:Date.now(),type:"ux-suggestion",suggestion:s.data})}}isRunCancelled(e){return this.cancelledRunIds.has(e)}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};var De=A`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%);--calcite-panel-content-bottom-space: 0}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%;background:var(--calcite-panel-background-color, var(--calcite-color-background))}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}.interrupt-waiting-message{font-style:italic;color:var(--calcite-color-text-2)}`,Me=Object.defineProperty,Oe=Object.getOwnPropertyDescriptor,w=(r,e,t,i)=>{for(var s=i>1?void 0:i?Oe(e,t):e,a=r.length-1,n;a>=0;a--)(n=r[a])&&(s=(i?n(e,t,s):n(s))||s);return i&&s&&Me(e,t,s),s},Fe=async r=>await new Promise(e=>setTimeout(e,r));async function*We(r,{chunkSize:e=5,delay:t=20}={}){let i=0;for(;i<r.length;)yield r.slice(i,i+e),i+=e,await Fe(t)}async function*Z(r,e,t,i){for await(let s of We(r)){if(i?.aborted){yield{type:"cancelled",log:t,runId:e};return}yield{type:"block-data",blockType:"text",data:{content:s},runId:e}}}var m=class extends Le{constructor(r){super(r),this.view=null,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await Ie(()=>!this.view.updating),this._set("orchestrator",await k.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([Ce(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(r,e){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let t=[],i;try{let s=this.orchestrator.ask(r);for await(let a of s){let n=a.runId;switch(a.type){case"trace":{this._set("processingStep",a.data.text),t.push(a.data.text);break}case"completed":{this._set("processing",!1),this._set("processingStep","");let o=a.result,c=!!o.content.length,l=!!i?.length;if(!c&&!l){yield{type:"completed",error:"No response received.",log:t,runId:n};return}let d=o.content;if(yield{type:"block-start",blockType:"text",runId:n},yield*Z(d,n,t,e),yield{type:"block-end",blockType:"text",runId:n},l)for(let h of i){if(e?.aborted){yield{type:"cancelled",log:t,runId:n};return}let{type:u,data:f}=h;if(yield{type:"block-start",blockType:u,runId:n},u==="text"){let _=typeof f?.content=="string"?f.content:"";yield*Z(_,n,t,e)}else yield{type:"block-data",blockType:u,data:f,runId:n};yield{type:"block-end",blockType:u,runId:n}}yield{type:"completed",response:d,blocks:i,log:t,runId:n};return}case"ux-suggestion":{let o=a.suggestion;i=i?[...i,o]:[o];break}case"interrupt":{let{kind:o,message:c,metadata:l}=a.interrupt,d=Array.isArray(l)?l.filter(u=>typeof u=="string"):[],h=(()=>{switch(o){case"booleanChoice":return{type:"boolean-choice",message:c,options:d};case"singleSelection":return{type:"single-select",message:c,options:d};case"multipleSelection":return{type:"multi-select",message:c,options:d};case"textInput":return{type:"text-input",message:c};default:return{type:o,message:c,options:d}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:h,runId:n};break}case"cancelled":{yield{type:"cancelled",log:t,runId:n};return}case"error":{yield{type:"completed",error:a.error.message,log:t,runId:n};return}default:{console.warn("Unknown event type:",a);break}}}}catch(s){console.warn("Error during message processing:",s),yield{type:"completed",error:"An error occurred during message processing.",log:t,runId:"error"};return}finally{this._set("processing",!1)}}cancel(){this.orchestrator?.cancel()}};w([b({readOnly:!0})],m.prototype,"orchestrator",2);w([b()],m.prototype,"agents",2);w([b()],m.prototype,"portal",2);w([b()],m.prototype,"view",2);w([b({readOnly:!0})],m.prototype,"loading",2);w([b({readOnly:!0})],m.prototype,"processing",2);w([b({readOnly:!0})],m.prototype,"processingStep",2);m=w([Pe("OrchestratorController")],m);var qe="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",je="Embeddings not found for this web map.",He="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",$=class extends P{constructor(){super(...arguments),this._messages=M({blocking:!0}),this.#e=v(),this.#a=v(),this.#s=v(),this.#t=null,this.#o=new Map,this.#r=$e.getDefault(),this.#i=e=>{e.stopPropagation(),this.cancelInterrupt()},this.#n=e=>{e.stopPropagation();let t=e.detail;this.submitInterrupt(t)},this.#c=e=>{e.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let t=e.detail;this._inputValue="",this.arcgisSubmit.emit(t),this.submitMessage(t)},this.#l=e=>{if(this._canceling=!0,e.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this._orchestratorController?.cancel(),this.#t?.abort(),this.#t=null},this.#d=e=>{e.stopPropagation();let t=e.detail;this.arcgisFeedback.emit(t)},this.#g=e=>{e.stopPropagation();let t=e.detail;this._inputValue=t.prompt,this.arcgisPromptSelect.emit(t)},this.#h=e=>{this.arcgisSlottableRequest.emit(e.detail)},this._orchestratorController=null,this._interrupt=null,this._interruptDetails=[],this._error=null,this._inputValue="",this._isAnswering=!1,this._canceling=!1,this.messages=new xe([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.assistantAvatarEnabled=!1,this.arcgisCancel=p(),this.arcgisError=p(),this.arcgisFeedback=p(),this.arcgisInterrupt=p(),this.arcgisInterruptCancel=p(),this.arcgisInterruptSubmit=p(),this.arcgisPromptSelect=p(),this.arcgisReady=p(),this.arcgisSubmit=p(),this.arcgisSlottableRequest=p({bubbles:!1,composed:!1}),this.arcgisResponse=p()}static{this.properties={_orchestratorController:16,_interrupt:16,_interruptDetails:16,_error:16,_inputValue:16,_isAnswering:16,_canceling:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5,assistantAvatarEnabled:5}}static{this.styles=De}#e;#a;#s;#t;#o;#r;#i;#n;#c;#l;#d;#g;#h;async#u(){try{let e=B(this.el,this.referenceElement);await e?.componentOnReady();let t=[...this.#o.values()];return t.length?(this._orchestratorController=new m({agents:t,portal:this.#r,view:e?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(e){return this._error=e?.message??"Error initializing orchestrator.",L(this)(e),!1}}get _user(){return this.#r?.user?.fullName||this.#r?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(e){this.#o.set(e.agent.id,e)}async submitMessage(e){let t=e.trim();if(!t||(this.messages.push({id:Date.now().toString(),role:"user",content:t}),!this._orchestratorController))return;this.#t=new AbortController;let i=this._orchestratorController.ask(t,this.#t?.signal);for await(let s of i){let a=s.runId,n=this.messages.at(-1);switch(s.type){case"block-start":{this._isAnswering=!0;let o={type:s.blockType,isPending:!0};if(n?.role==="assistant"&&n.id===a){let c=[...n.blocks??[],o];this.messages.splice(-1,1,{...n,blocks:c})}else this.messages.push({role:"assistant",blocks:[o],id:a,isStreaming:!0,interrupts:this._interruptDetails}),this._interruptDetails=[];break}case"block-data":{if(n?.role!=="assistant"||n?.id!==a)break;let o=[...n.blocks??[]],c=o[o.length-1],{blockType:l,data:d}=s;if(c?.type!==l||!c.isPending)break;if(l==="text"){let h=typeof c.data?.content=="string"?c.data.content:"",u=typeof d?.content=="string"?d.content:"";o[o.length-1]={...c,data:{...c.data,content:h+u}}}else o[o.length-1]={...c,data:{...c.data,...d??{}}};this.messages.splice(-1,1,{...n,blocks:o});break}case"block-end":{if(n?.role!=="assistant"||n?.id!==a)break;let o=[...n.blocks??[]],c=o[o.length-1];if(c?.type!==s.blockType||!c.isPending)break;let l=c;o[o.length-1]={...l,data:{...l.data},isPending:!1},this.messages.splice(-1,1,{...n,blocks:o});break}case"completed":s.error?(this.messages.push({role:"assistant",log:s.log,error:s.error,id:a,interrupts:this._interruptDetails}),this._interruptDetails=[]):n?.role==="assistant"&&n.id===a&&this.messages.splice(-1,1,{...n,content:s.response,blocks:n.blocks?.map(o=>({...o,isPending:!1}))??[],isStreaming:!1,log:s.log}),this._isAnswering=!1,this.#t=null,this._canceling=!1;break;case"interrupt":this._interrupt={...s.payload,id:a},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":n?.role==="assistant"&&n.id===a?this.messages.splice(-1,1,{...n,blocks:n.blocks?.filter(o=>o.type==="text"||!o.isPending)??[],isStreaming:!1,log:s.log,error:"(Stopped by user)"}):(this.messages.push({role:"assistant",log:s.log,error:"(Stopped by user)",id:a,interrupts:this._interruptDetails}),this._interruptDetails=[]),this._isAnswering=!1,this.#t=null,this._canceling=!1;break}}}submitInterrupt(e){this.arcgisInterruptSubmit.emit(e),this._interrupt&&(this._interruptDetails=[...this._interruptDetails,{interrupt:this._interrupt,response:e}]),this.orchestrator?.resumeInterrupt(e),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#e.value?.addEventListener("arcgisPromptSelect",this.#g),this.#e.value?.addEventListener("arcgisSubmit",this.#c),this.#e.value?.addEventListener("arcgisCancel",this.#l),this.#e.value?.addEventListener("arcgisFeedback",this.#d);let e=Re(()=>!!this._interrupt&&!!this.#s.value,()=>{let i=this.#s.value;i.removeEventListener("arcgisSubmit",this.#n),i.removeEventListener("arcgisCancel",this.#i),i.addEventListener("arcgisSubmit",this.#n,{once:!0}),i.addEventListener("arcgisCancel",this.#i,{once:!0})}),t=this.messages.on("after-add",i=>{let s=i.item;s.role==="assistant"&&(s.error||s.content)&&this.arcgisResponse.emit(s)});return queueMicrotask(()=>{this.#u().then(i=>{i?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{e.remove(),t.remove(),this.#e.value?.removeEventListener("arcgisPromptSelect",this.#g),this.#s.value?.removeEventListener("arcgisSubmit",this.#n),this.#s.value?.removeEventListener("arcgisCancel",this.#i),this.#e.value?.removeEventListener("arcgisSubmit",this.#c),this.#e.value?.removeEventListener("arcgisCancel",this.#l),this.#e.value?.removeEventListener("arcgisFeedback",this.#d),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this._orchestratorController?.cancel(),this.#t?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue=""}_renderEntryMessage(){return this._user?this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:g`<calcite-notice open kind=brand closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:g`<slot name=entry-message></slot>`:this._renderSignInNotice()}_renderSignInNotice(){let e=this.#r;return g`<calcite-notice slot=entry-message open kind=brand icon width=full><div slot=message>You need to sign in to use the assistant chat.</div>${e?g`<calcite-link slot=link @click=${async()=>{try{await Ae.getCredential(e.url),this._error=null,await this.#u(),this.arcgisReady.emit()}catch(t){console.error("Error signing in:",t)}}} target=_blank title="Sign in to ArcGIS Online">Sign in</calcite-link>`:g`<div slot=link>No portal information available</div>`}</calcite-notice>`}_renderErrorNotice(){return this._error?g`<calcite-notice slot=entry-message open kind=brand icon width=full>${this._error===qe?g`<div slot=message>${je}</div><calcite-link slot=link .href=${He} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:g`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}render(){return g`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${E(this.#e)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages} .interrupt=${this._interrupt}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(e=>e.role==="assistant"?g`<arcgis-assistant-message .message=${e} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#h} .assistantAvatarEnabled=${this.assistantAvatarEnabled}>${e.blocks?.map((t,i)=>g`<slot name=${I(e.id,i)??S} slot=${I(e.id,i)??S}><arcgis-assistant-message-block .block=${t}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:g`<arcgis-assistant-user-message .message=${e} .user=${this._user}></arcgis-assistant-user-message>`)}</slot>${this._interrupt?g`<div slot=message-loading><div class="interrupt-waiting-message">waiting for user input...</div> // TODO: use t9n strings</div>`:g`<slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep} .assistantAvatarEnabled=${this.assistantAvatarEnabled} .interrupts=${this._interruptDetails}></arcgis-assistant-message-loading></slot>`}</arcgis-assistant-chat></div>${this._interrupt?g`<arcgis-assistant-interrupt slot=content-bottom .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${E(this.#s)}></arcgis-assistant-interrupt>`:this.suggestedPrompts?.length?g`<div class="suggested-prompts-container" slot=content-bottom><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse||this._isAnswering} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} .disabled=${this._canceling||!this._user||!!this._interrupt} ${E(this.#a)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse||this._isAnswering?"circle-stop":"send"} @click=${()=>{this.#a.value?.submitMessage()}} round>${this.awaitingResponse||this._isAnswering?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};D("arcgis-assistant",$);return $},"core/Collection","core/reactiveUtils","portal/Portal","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","config","layers/FeatureLayer","core/Accessor","core/accessorSupport/decorators",a)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import b from"./3VOQD2MR.js";import a from"./TR4GFL7X.js";import{c as m}from"./FUIGPHBH.js";import"./DHKUXLU3.js";import"./CHPQM77M.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([{property:n,subclass:l},{watch:w},c])=>{var d=Object.defineProperty,f=Object.getOwnPropertyDescriptor,p=(e,r,s,o)=>{for(var t=o>1?void 0:o?f(r,s):r,i=e.length-1,a;i>=0;i--)(a=e[i])&&(t=(o?a(r,s,t):a(t))||t);return o&&t&&d(r,s,t),t},h=class extends c{constructor(e){super(e)}initialize(){this.addHandles(w(()=>[this.name,this.description,this.inputSchema,this.outputSchema,this.workflow],()=>this.generate(),{initial:!0,sync:!0}))}getSchemas(){return[this.inputSchema,...this.workflow.getAgents().flatMap(e=>e.getSchemas()),this.outputSchema].filter(Boolean)}generate(){let{workspace:e,createGraph:r}=this.workflow.generate();if(this._set("workspace",e),!this.middlewares?.length)this._set("createGraph",r);else{let s=this.id,o={[s]:async(i,a)=>await r().compile().invoke(i,a)},t=[{from:s,decide:()=>{}}];this._set("createGraph",()=>m(o,t,e,{agent:this,entryNode:s,middlewares:this.middlewares}))}}};p([n()],h.prototype,"workflow",2);p([n()],h.prototype,"inputSchema",2);p([n()],h.prototype,"outputSchema",2);h=p([l("WorkflowAgent")],h);return h},"core/accessorSupport/decorators","core/reactiveUtils",a,b)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{a as wd}from"./WNS5ZUF5.js";import{$ as T,$a as Ta,$b as Tb,$c as Tc,A as s,Aa as sa,Ab as sb,Ac as sc,Ad as sd,B as t,Ba as ta,Bb as tb,Bc as tc,Bd as td,C as u,Ca as ua,Cb as ub,Cc as uc,Cd as ud,D as v,Da as va,Db as vb,Dc as vc,Dd as vd,E as w,Ea as wa,Eb as wb,Ec as wc,F as x,Fa as xa,Fb as xb,Fc as xc,G as y,Ga as ya,Gb as yb,Gc as yc,H as z,Ha as za,Hb as zb,Hc as zc,I as A,Ia as Aa,Ib as Ab,Ic as Ac,J as B,Ja as Ba,Jb as Bb,Jc as Bc,K as C,Ka as Ca,Kb as Cb,Kc as Cc,L as D,La as Da,Lb as Db,Lc as Dc,M as E,Ma as Ea,Mb as Eb,Mc as Ec,N as F,Na as Fa,Nb as Fb,Nc as Fc,O as G,Oa as Ga,Ob as Gb,Oc as Gc,P as H,Pa as Ha,Pb as Hb,Pc as Hc,Q as I,Qa as Ia,Qb as Ib,Qc as Ic,R as J,Ra as Ja,Rb as Jb,Rc as Jc,S as K,Sa as Ka,Sb as Kb,Sc as Kc,T as L,Ta as La,Tb as Lb,Tc as Lc,U as M,Ua as Ma,Ub as Mb,Uc as Mc,V as N,Va as Na,Vb as Nb,Vc as Nc,W as O,Wa as Oa,Wb as Ob,Wc as Oc,X as P,Xa as Pa,Xb as Pb,Xc as Pc,Y as Q,Ya as Qa,Yb as Qb,Yc as Qc,Z as R,Za as Ra,Zb as Rb,Zc as Rc,_ as S,_a as Sa,_b as Sb,_c as Sc,a,aa as U,ab as Ua,ac as Ub,ad as Uc,b,ba as V,bb as Va,bc as Vb,bd as Vc,c,ca as W,cb as Wa,cc as Wb,cd as Wc,d,da as X,db as Xa,dc as Xb,dd as Xc,e,ea as Y,eb as Ya,ec as Yb,ed as Yc,f,fa as Z,fb as Za,fc as Zb,fd as Zc,g,ga as _,gb as _a,gc as _b,gd as _c,h,ha as $,hb as $a,hc as $b,hd as $c,i,ia as aa,ib as ab,ic as ac,id as ad,ja as ba,jb as bb,jc as bc,jd as bd,ka as ca,kb as cb,kc as cc,kd as cd,l as j,la as da,lb as db,lc as dc,ld as dd,ma as ea,mb as eb,mc as ec,md as ed,na as fa,nb as fb,nc as fc,nd as fd,oa as ga,ob as gb,oc as gc,od as gd,p as k,pa as ha,pb as hb,pc as hc,pd as hd,q as l,qa as ia,qb as ib,qc as ic,qd as id,r as m,ra as ja,rb as jb,rc as jc,rd as jd,sa as ka,sb as kb,sc as kc,sd as kd,t as n,ta as la,tb as lb,tc as lc,td as ld,u as o,ua as ma,ub as mb,uc as mc,ud as md,v as p,va as na,vb as nb,vc as nc,vd as nd,wa as oa,wb as ob,wc as oc,wd as od,xa as pa,xb as pb,xc as pc,xd as pd,y as q,ya as qa,yb as qb,yc as qc,yd as qd,z as r,za as ra,zb as rb,zc as rc,zd as rd}from"./ZEYIBYSF.js";import"./YIMNOUTF.js";export{b as $brand,m as $input,l as $output,a as NEVER,p as TimePrecision,Hb as ZodAny,Rb as ZodArray,$a as ZodBase64,bb as ZodBase64URL,wb as ZodBigInt,yb as ZodBigIntFormat,ub as ZodBoolean,Xa as ZodCIDRv4,Za as ZodCIDRv6,Ha as ZodCUID,Ja as ZodCUID2,Mc as ZodCatch,Sc as ZodCodec,ed as ZodCustom,hb as ZodCustomStringFormat,Pb as ZodDate,Ec as ZodDefault,ac as ZodDiscriminatedUnion,db as ZodE164,ra as ZodEmail,Da as ZodEmoji,oc as ZodEnum,_ as ZodError,zc as ZodExactOptional,tc as ZodFile,sd as ZodFirstPartyTypeKind,cd as ZodFunction,ta as ZodGUID,Ra as ZodIPv4,Va as ZodIPv6,W as ZodISODate,V as ZodISODateTime,Y as ZodISODuration,X as ZodISOTime,cc as ZodIntersection,pd as ZodIssueCode,fb as ZodJWT,Pa as ZodKSUID,_c as ZodLazy,rc as ZodLiteral,Ta as ZodMAC,kc as ZodMap,Oc as ZodNaN,Fa as ZodNanoID,Lb as ZodNever,Ic as ZodNonOptional,Fb as ZodNull,Bc as ZodNullable,mb as ZodNumber,ob as ZodNumberFormat,Ub as ZodObject,xc as ZodOptional,Qc as ZodPipe,Gc as ZodPrefault,Vc as ZodPreprocess,ad as ZodPromise,Wc as ZodReadonly,$ as ZodRealError,gc as ZodRecord,mc as ZodSet,oa as ZodString,qa as ZodStringFormat,Kc as ZodSuccess,Bb as ZodSymbol,Yc as ZodTemplateLiteral,vc as ZodTransform,ec as ZodTuple,ma as ZodType,La as ZodULID,Aa as ZodURL,va as ZodUUID,Db as ZodUndefined,Yb as ZodUnion,Jb as ZodUnknown,Nb as ZodVoid,Na as ZodXID,_b as ZodXor,na as _ZodString,Fc as _default,dd as _function,Ib as any,Sb as array,ab as base64,cb as base64url,xb as bigint,vb as boolean,Nc as catch,fd as check,Ya as cidrv4,_a as cidrv6,d as clone,Tc as codec,ud as coerce,c as config,U as core,Ia as cuid,Ka as cuid2,gd as custom,Qb as date,fa as decode,ha as decodeAsync,wd as default,jd as describe,bc as discriminatedUnion,eb as e164,sa as email,Ea as emoji,ea as encode,ga as encodeAsync,K as endsWith,pc as enum,Ac as exactOptional,uc as file,f as flattenError,qb as float32,rb as float64,g as formatError,td as fromJSONSchema,dd as function,rd as getErrorMap,o as globalRegistry,s as gt,t as gte,ua as guid,lb as hash,kb as hex,jb as hostname,Ca as httpUrl,I as includes,ld as instanceof,pb as int,sb as int32,zb as int64,dc as intersection,Uc as invertCodec,Sa as ipv4,Wa as ipv6,Z as iso,nd as json,gb as jwt,Tb as keyof,Qa as ksuid,$c as lazy,E as length,sc as literal,k as locales,Xb as looseObject,jc as looseRecord,G as lowercase,q as lt,r as lte,Ua as mac,lc as map,C as maxLength,z as maxSize,kd as meta,M as mime,D as minLength,A as minSize,y as multipleOf,Pc as nan,Ga as nanoid,qc as nativeEnum,v as negative,Mb as never,x as nonnegative,Jc as nonoptional,w as nonpositive,O as normalize,Gb as null,Cc as nullable,Dc as nullish,nb as number,Vb as object,yc as optional,N as overwrite,aa as parse,ba as parseAsync,ic as partialRecord,Rc as pipe,u as positive,Hc as prefault,od as preprocess,i as prettifyError,bd as promise,L as property,Xc as readonly,hc as record,hd as refine,F as regex,j as regexes,n as registry,ja as safeDecode,la as safeDecodeAsync,ia as safeEncode,ka as safeEncodeAsync,ca as safeParse,da as safeParseAsync,nc as set,qd as setErrorMap,B as size,S as slugify,J as startsWith,Wb as strictObject,pa as string,ib as stringFormat,md as stringbool,Lc as success,id as superRefine,Cb as symbol,Zc as templateLiteral,T as toJSONSchema,Q as toLowerCase,R as toUpperCase,wc as transform,h as treeifyError,P as trim,fc as tuple,tb as uint32,Ab as uint64,Ma as ulid,Eb as undefined,Zb as union,Kb as unknown,H as uppercase,Ba as url,e as util,wa as uuid,xa as uuidv4,ya as uuidv6,za as uuidv7,Ob as void,Oa as xid,$b as xor,vd as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{b as A,d as N}from"./NXKKG5TK.js";import{a as x,b as C,c as f,d as m,e as P,f as L,k as g,m as v,n as O,o as w}from"./HWKDNS4K.js";var $=t=>(...s)=>{let e=m(),o=new t(...s),r=o.exports;f(e.at(-1));let n=o.component.manager;n.W(o,r),o.watchExports(n.W.bind(n,o)),P(o);let a=[o.component,...e].reverse();return v(a,i=>i===void 0?void 0:T(o,i,r),r)},T=(t,{host:s,key:e,isReactive:o},r)=>{let n=s,a=n[e]!==t.exports,i=n[e]!==r,l=r!==t.exports;if(a&&!i&&l&&(n[e]=t.exports),s===t.component){if(o){let p=t.component.manager;i&&p.W(t,n[e]),t.onUpdate(u=>{if(u.has(e)){let y=n[e];y!==t.exports&&p.W(t,y)}})}t.O=o?void 0:e}let c=t.component.constructor.elementProperties.get(e)?.readOnly;t.watchExports(()=>{n[e]!==t.exports&&(c?L(()=>{n[e]=t.exports}):n[e]=t.exports)})};var U="ar,bg,bs,ca,cs,da,de,el,en,es,et,fi,fr,he,hr,hu,id,it,ja,ko,lt,lv,nl,nb,no,pl,pt-BR,pt-PT,ro,ru,sk,sl,sr,sv,th,tr,uk,vi,zh-CN,zh-HK,zh-TW".split(","),F=new Set(U),h="en",W={pt:"pt-BR",nb:"no",nn:"no",zh:"zh-CN"},K=async(t,s,e="")=>{let o=`${s}/${e}`,r=`${o}${t}.json`;return _[r]??=j(t,o),await _[r]},_={},j=async(t,s)=>{let e=`${s}${t}.json`;try{let o=await fetch(e);if(o.ok)return await o.json()}catch(o){return g("error","intl",`An unknown error occurred while fetching localization strings at ${e}`,{detail:{error:o}}),{}}return t===h?{}:await j(h,s)},b=t=>{let s=N(t,"lang",globalThis.navigator?.language||h);return{lang:s,t9nLocale:D(s)}},D=t=>{let[s,e]=t.split("-"),o=s.toLowerCase(),r=o;return e&&(r=`${o}-${e.toUpperCase()}`),r=W[r]??r,F.has(r)?r:e?D(o):h},V=(t,s,e,o)=>{let r,n=()=>q(t,s(),o).then(a=>{(r?.lang!==a.lang||r.t9nLocale!==a.t9nLocale||r.t9nStrings!==a.t9nStrings)&&e(a),r=a}).catch(a=>{g("error","intl","Error updating component locale state",{detail:{error:a}})});return queueMicrotask(n),A(t,["lang"],n)},q=async(t,s,e=t.localName.split("-").slice(1).join("-"))=>{let{lang:o,t9nLocale:r}=b(t),n=`${s}/${e}/t9n`,i=e===null?{}:await K(r,n,"messages.");return{lang:o,t9nLocale:r,t9nStrings:i}};var z=t=>R(void 0,t);var E=class extends w{constructor(s,e){super(s);let o=this.exports;try{C(this.component);let r=e(this.component,this),n=this.exports!==o;if(x(r)){n||this.setProvisionalExports(r);let a=r.then(i=>{this.exports=i,super.catchUpLifecycle()}).catch(i=>{this.P.reject(i)});this.onLoad(async()=>await a)}else(!n||r!==void 0)&&(this.exports=r),queueMicrotask(()=>super.catchUpLifecycle())}catch(r){this.P.reject(r)}}catchUpLifecycle(){}},R=$(E);var nt=(t,s,e)=>z((o,r)=>{let n=s,a=O({bubbles:!1,composed:!1});return r.onUpdated(i=>{if(!n.some(c=>i.has(c)))return;let l=e(k(t,n,i)),d=e(k(t,n));l.forEach((c,p)=>{d.has(p)||a.emit({...c,data:void 0})}),d.forEach((c,p)=>{let u=l.get(p);(!u||!M(u,c))&&a.emit(c)})}),a});function k(t,s,e){let o={};return s.forEach(r=>{o[r]=e?.has(r)?e.get(r):t[r]}),o}function M(t,s){if(t===s)return!0;if(!t||!s||typeof t!="object"||typeof s!="object"||Array.isArray(t)||Array.isArray(s))return!1;let e=Object.entries(t),o=Object.entries(s);return e.length!==o.length?!1:e.every(([r,n])=>M(n,s[r]))}var at=t=>(s={})=>z((e,o)=>{let r=b(e.el),n={_lang:r.lang,_t9nLocale:r.t9nLocale,_loading:!0},a=e;o.onLifecycle(()=>V(e.el,()=>t("./assets"),({t9nLocale:l,t9nStrings:d,lang:c})=>{let p={...d,_lang:c,_t9nLocale:l,_loading:!1};o.exports=p;let u=d.componentLabel;typeof u=="string"&&"label"in e&&e.label==null&&(e.label??=u),i(a.messageOverrides)},s.name));let i=l=>{let d=o.exports,c=d._original??d,p=S(c,l);l&&(p._original=c),o.exports=p};return"messageOverrides"in a&&o.onUpdate(l=>{l.has("messageOverrides")&&i(a.messageOverrides)}),s.blocking?(o.setProvisionalExports(n,!1),o.ready):n}),S=(t,s)=>{if(!s)return t;let e={...t};return Object.entries(s).forEach(([o,r])=>{t[o]!==void 0&&(typeof r=="object"?e[o]=S(t[o],r):e[o]=r??t[o])}),e};export{nt as a,at as b};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import a from"./T43LEBBE.js";import{a as T,b as S}from"./P7DG5T3Z.js";import{_ as w,ea as Ee,g as Se,j as Q,k as B,pa as L,u as xe}from"./DHKUXLU3.js";import{L as z,P as oe,_ as j,wc as f}from"./CHPQM77M.js";import{a as s}from"./WNS5ZUF5.js";import{Dd as I}from"./ZEYIBYSF.js";export default $arcgis.t(([Ae,M,ie,Le,,Ce,ot,{addressToLocations:at},nt,it,De,{createRenderer:st},{getSchemesByTag:lt,getSchemes:ct},{getBackgroundColorTheme:Re},{createAgeRenderer:ut,createContinuousRenderer:dt},{getSchemesByTag:we},{createContinuousRenderer:pt},{createRenderer:mt},{getSchemesByTag:ht},{createRenderer:ft},{getSchemesByTag:yt},{createRenderer:gt},{getSchemesByTag:wt},{createRenderer:bt},{getSchemesByTag:vt},{createAgeRenderer:Tt,createContinuousRenderer:St},{createRenderer:xt},{getSchemesByTag:Et},It,Oe,Pe,{formatDateOnly:Nt,convertDateFormatToIntlOptions:K,formatTimeOnly:$t,formatDate:qe},kt,Ft,Mt,At,Ct,Ge,,{fetchKnowledgeGraph:_e,executeQueryStreaming:Rt,executeSearchStreaming:qt},_t,{b:D,c:Ie,k:Ne}])=>{var Me=e=>Array.isArray(e)&&e.every(z),Xe=e=>typeof e=="object"&&e!=null&&"messages"in e&&Me(e.messages),et=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,U=class extends Ee{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:o,handleToolErrors:a}=t??{};super({name:r,tags:o,func:(n,l)=>this.run(n,l)}),this.tools=e,this.handleToolErrors=a??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(o=>o.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let o=await r.invoke({...e,type:"tool_call"},t);return z(o)&&o.getType()==="tool"||B(o)?o:new oe({status:"success",name:r.name,content:typeof o=="string"?o:JSON.stringify(o),tool_call_id:e.id})}catch(o){if(!this.handleToolErrors||xe(o))throw o;return new oe({status:"error",content:`Error: ${o.message}
|
|
3
|
+
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(et(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Me(e))n=e;else if(Xe(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let l=new Set(n.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),i;for(let c=n.length-1;c>=0;c-=1){let u=n[c];if(j(u)){i=u;break}}if(i==null||!j(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(c=>c.id==null||!l.has(c.id)).map(c=>this.runTool(c,t))??[])}if(!r.some(B))return Array.isArray(e)?r:{messages:r};let o=[],a=null;for(let n of r)B(n)?n.graph===Q.PARENT&&Array.isArray(n.goto)&&n.goto.every(l=>Se(l))?a?a.goto.push(...n.goto):a=new Q({graph:Q.PARENT,goto:n.goto}):o.push(n):o.push(Array.isArray(e)?[n]:{messages:[n]});return a&&o.push(a),o}};var An=w.Root({llmInputMessages:w({reducer:(e,t)=>L([],t),default:()=>[]})});var O=(e,t)=>t??e,Oi=w.Root({...Ie(),intent:w({reducer:O}),vectorSearchLayerResults:w({reducer:O,default:()=>[]}),vectorSearchFieldResults:w({reducer:O}),navigationInternalState:w({reducer:O,default:()=>({toolCallMessage:void 0})})});async function zt(e,t){let r=M.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let a=o.url,n=`${ie.assetsPath?.endsWith("/")?ie.assetsPath:`${ie.assetsPath}/`}esri/images/search/search-symbol-32.png`,l=(await at(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!l?.extent||!l.location)throw new Error(`Could not find location for: ${e}`);let i=new nt({url:n,width:24,height:24}),c=new ot({geometry:l.location,symbol:i});t.graphics.removeAll(),t.graphics.add(c),await t.goTo(l.extent);let u={address:l.address??"",location:l.location?l.location.toJSON():null,extent:l.extent?l.extent.toJSON():null};return{text:`Successfully zoomed to ${e}.`,sharedStatePatch:{lastResolvedLocation:{value:u}}}}var jt=["mapView"];function N(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=jt.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Lt({address:e},t){let{mapView:r}=N(t);return await zt(e,r)}var Dt=s.object({address:s.string().describe("The full address or place name to locate.")}),Pi=f(Lt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Dt});async function Ot(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(n=>n.name===e);if(!o)throw new Error(`Bookmark with name "${e}" not found.`);let a=o.viewpoint;if(!a)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await t.goTo(a),{text:`Navigated to bookmark: ${e}`}}async function Pt({bookmarkName:e},t){let{mapView:r}=N(t);return await Promise.resolve(Ot(e,r))}var Gt=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),Gi=f(Pt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Gt});async function Vt(e,t,r){let o=r.map?.allLayers.find(l=>l.id===e);if(!o)return{text:`Error: Layer with id ${e} not found`};let a=t?.trim()?t:"1=1",n=o.createQuery();n.where=a;try{let{extent:l,count:i}=await o.queryExtent(n);if(i===0)return{text:`No features found in ${o.title} matching: ${a}`,where:a};if(l)await r.goTo(l);else return{text:`Error: Unable to determine extent for ${o.title}`,where:a};let c={layerId:e,layerTitle:o.title??e,where:a,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${o.title} matching: ${a}`,where:a,sharedStatePatch:{lastNavigatedFeatures:{value:c}}}}catch(l){return console.error("Error in goToFeatures:",l),{text:`Error: ${l instanceof Error?l.message:"Unknown error"}`,where:a}}}async function Qt({layerId:e,where:t},r){let{mapView:o}=N(r);return await Vt(e,t,o)}var Bt=I.object({layerId:I.string().describe("The layerId of the layer to zoom to."),where:I.string().describe("The sql-92 where clause used to query features to zoom to")}),Vi=f(Qt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Bt});async function Ut(e){let t=new it({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"Successfully zoomed to world extent"}}async function Kt(e,t){let{mapView:r}=N(t);return await Ut(r)}var Wt=I.object({}),Qi=f(Kt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Wt});async function Ht(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function Jt(e,t){let{mapView:r}=N(t);return await Ht(r)}var Zt=s.object({}),Bi=f(Jt,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:Zt});async function Yt(e,t){await t.when();let r=t.map?.allLayers.find(a=>a.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),{text:`Could not find layer for: ${e}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?o=t.map.diagramNodesExtent:o=r.fullExtent,o?(await t.goTo(o),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function Xt({layerId:e},t){let{mapView:r}=N(t);return await Yt(e,r)}var er=I.object({layerId:I.string().describe("The id of the layer to navigate to")}),Ui=f(Xt,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:er});async function tr(e,t){return await t.goTo({scale:e}),{text:`Successfully zoomed to: ${e}`}}async function rr({scale:e},t){let{mapView:r}=N(t);return await tr(e,r)}var or=s.object({scale:s.number().describe("The map scale of the view to go to.")}),Ki=f(rr,{name:"goToScale",description:"Go to the specified view scale.",schema:or});async function ar(e,t,r){let o={target:new De({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await t.goTo(o),{text:`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function nr({center:e,zoom:t,scale:r},o){let{mapView:a}=N(o);return await ar(e,a,{zoom:t,scale:r})}var ir=s.object({center:s.object({longitude:s.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:s.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:s.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:s.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),Wi=f(nr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:ir});async function sr(e,t){return await t.goTo({zoom:e}),{text:`Successfully zoomed to: ${e}`}}async function lr({zoom:e},t){let{mapView:r}=N(t);return await sr(e,r)}var cr=s.object({zoom:s.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Hi=f(lr,{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:cr}),ze=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./KMQ3SP4I.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./5QAHYX7Y.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./5ZZGKP7N.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./AXDZBBNL.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./ZS2TZ6BF.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./LQ6R5YRN.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./X2ZDYHCG.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./T537PKP4.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./F2AHA4GB.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./FX7UOGHP.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./NE7E52YR.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./6YMR4QSD.js").then(e=>e.default)});async function le(e){let t=Object.entries(ze).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
|
|
4
|
+
Available prompts:
|
|
5
|
+
${Object.keys(ze).join(`
|
|
6
|
+
`)}`);return await t[1]()}var ur=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r},Ve=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},Ji=(e,t)=>(r,o)=>{let a=o?.configurable?.services;for(let n of e)if(!a?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r};async function dr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,l;return n?l=lt({basemapTheme:await Re(o),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:l=ct({basemapTheme:await Re(o),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:o,attributes:t.map(i=>({field:i,label:r.fields.find(c=>c.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),pieChartScheme:l}}async function pr(e){return await st(e)}async function mr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,includeSize:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:n?"chart-size":"chart",fields:o,layer:i,view:l,colorSchemeTags:a};try{let u=await dr(c),d=await pr(u);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying chart renderer: ${u instanceof Error?u.message:String(u)}`}}var hr=["mapView"];function x(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=hr.filter(o=>!(o in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function fr({layerId:e,fields:t,colorSchemes:r,includeSize:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await mr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var yr=s.object({layerId:s.string().describe("The id of the layer to apply the chart renderer to"),fields:s.array(s.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),includeSize:s.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Zi=f(fr,{name:"chart",description:`Label: Charts
|
|
7
|
+
Description: Show the values of two or more categories as a proportion of the total using a pie chart.
|
|
8
|
+
Keywords: pie, chart, all categories, breakdown, proportion
|
|
9
|
+
Example: Show the total number of homes built in each decade using a pie chart for each feature.
|
|
10
|
+
Fields: This style requires 2-8 number fields.
|
|
11
|
+
|
|
12
|
+
Label: Charts and Size
|
|
13
|
+
Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
|
|
14
|
+
Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
|
|
15
|
+
Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
|
|
16
|
+
Fields: This style requires 2-8 number fields.`,schema:yr});function gr(e){let{fields:t,layer:r,view:o,theme:a,colorSchemeTags:n}=e,l=t[0],i;return n&&(i=we({geometryType:r.geometryType,includedTags:n,theme:a||"high-to-low"})[0]),{layer:r,view:o,startTime:l,endTime:new Date,theme:a,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function wr(e){return await ut(e)}async function br({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"color-age",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let u=gr(c),d=await wr(u);return i.renderer=d.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying color-age renderer: ${u instanceof Error?u.message:String(u)}`}}async function vr({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await br({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var Tr=s.object({layerId:s.string().describe("The id of the layer to apply the color-age renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Yi=f(vr,{name:"color-age",description:`Label: Age (color)
|
|
17
|
+
Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
18
|
+
Keywords: since, age, how old, how long
|
|
19
|
+
Example: Show the age of each feature based on its reported date.
|
|
20
|
+
Fields: This style requires at least one field with a date type.`,schema:Tr});function Sr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,{theme:n}=e,l=t[1],i=t[0],c;return a&&(c=we({geometryType:r.geometryType,includedTags:a,theme:n||"high-to-low"})[0]),{layer:r,view:o,field:i,normalizationField:l,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function xr(e){return await dt(e)}async function Er({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"color",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let u=Sr(c),d=await xr(u);return i.renderer=d.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying color renderer: ${u instanceof Error?u.message:String(u)}`}}async function Ir({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await Er({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var Nr=s.object({layerId:s.string().describe("The id of the layer to apply the color renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the color renderer"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Xi=f(Ir,{name:"color",description:`Label: Counts and Amounts (color)
|
|
21
|
+
Description: Vary color along a continuous color ramp to represent numeric or ranked data.
|
|
22
|
+
Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
|
|
23
|
+
Example: Color each feature based on the population density.
|
|
24
|
+
Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:Nr});function $r(e){let{fields:t,layer:r,view:o,colorSchemeTags:a,theme:n}=e,l,i,c=t[0];return a&&(i=we({geometryType:r.geometryType,includedTags:a,theme:n||"high-to-low"})[0]),{layer:r,view:o,field:c,normalizationField:l,theme:n,colorOptions:{colorScheme:i}}}async function kr(e){return await pt(e)}async function Fr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"color-size-univariate",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let u=$r(c),d=await kr(u);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying color-size-univariate renderer: ${u instanceof Error?u.message:String(u)}`}}async function Mr({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await Fr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var Ar=s.object({layerId:s.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:s.array(s.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),es=f(Mr,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
|
|
25
|
+
Description: Vary symbol size and color based on the values of two numeric attributes.
|
|
26
|
+
Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
|
|
27
|
+
Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
|
|
28
|
+
Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:Ar});function Cr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n;return a&&(n=ht({includedTags:a,numColors:Math.min(t.length,8)})[0]),{layer:r,view:o,legendOptions:{unit:"units"},attributes:t.map(l=>({field:l,label:r.fields.find(i=>i.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function Rr(e){return await mt(e)}async function qr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a}){let n=t,l=e?.allLayers.find(c=>c.id===r);if(!l)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:o,layer:l,view:n,colorSchemeTags:a};try{let c=Cr(i),u=await Rr(c);return l.renderer=u.renderer,l.visible=!0,`Dot Density renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function _r({layerId:e,fields:t,colorSchemes:r},o){let{mapView:a}=x(o);return await S({type:"show-legend",data:{layerIds:[e]}},o),await qr({arcgisMap:a.map,arcgisMapView:a,layerId:e,fields:t,colorSchemes:r})}var zr=s.object({layerId:s.string().describe("The id of the layer to apply the dot density renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use")}),ts=f(_r,{name:"dot-density",description:`Dot Density
|
|
29
|
+
Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
|
|
30
|
+
**Use cases:**
|
|
31
|
+
- Population distribution visualization
|
|
32
|
+
- Comparing multiple categories within areas
|
|
33
|
+
- Showing spatial distribution patterns
|
|
34
|
+
**Examples:**
|
|
35
|
+
- Show the density of the population based on various race/ethnic groups
|
|
36
|
+
- Visualize distribution of different crops across regions
|
|
37
|
+
- Display demographic patterns within census tracts
|
|
38
|
+
**Fields:** Requires 2-8 number fields.
|
|
39
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:zr});function jr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n,l=t[0];return a&&(n=yt({includedTags:a,basemap:o.map?.basemap||"topo"})[0]),{layer:r,view:o,field:l,heatmapScheme:n}}async function Lr(e){return await ft(e)}async function Dr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a}){let n=t,l=e?.allLayers.find(c=>c.id===r);if(!l)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:o,layer:l,view:n,colorSchemeTags:a};try{let c=jr(i),u=await Lr(c);return l.renderer=u.renderer,l.visible=!0,`Heatmap renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function Or({layerId:e,fields:t,colorSchemes:r},o){let{mapView:a}=x(o);return await S({type:"show-legend",data:{layerIds:[e]}},o),await Dr({arcgisMap:a.map,arcgisMapView:a,layerId:e,fields:t,colorSchemes:r})}var Pr=s.object({layerId:s.string().describe("The id of the layer to apply the heatmap renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use")}),rs=f(Or,{name:"heatmap",description:`Label: Heat Map
|
|
40
|
+
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
41
|
+
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
42
|
+
Example: Create a heatmap
|
|
43
|
+
Fields: This typically requires zero or one field of type number.`,schema:Pr});function Gr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,l;return n&&(l=wt({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:o,fields:t.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),predominanceScheme:l}}async function Vr(e){return await gt(e)}async function Qr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,includeSize:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:n?"predominance-size":"predominance",fields:o,layer:i,view:l,colorSchemeTags:a};try{let u=Gr(c),d=await Vr(u);return i.renderer=d.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying predominance renderer: ${u instanceof Error?u.message:String(u)}`}}async function Br({layerId:e,fields:t,colorSchemes:r,includeSize:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await Qr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var Ur=s.object({layerId:s.string().describe("The id of the layer to apply the predominance renderer to"),fields:s.array(s.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),includeSize:s.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),os=f(Br,{name:"predominance",description:`Label: Predominant category
|
|
44
|
+
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
45
|
+
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
46
|
+
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
47
|
+
Fields: This style relies on 2-10 number fields.
|
|
48
|
+
|
|
49
|
+
Label: Predominant category and Size
|
|
50
|
+
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
|
|
51
|
+
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
|
|
52
|
+
Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
|
|
53
|
+
Fields: This style relies on 2-10 number fields.`,schema:Ur});function Kr(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n,l={field:t[0]},i={field:t[1]};return a&&(n=vt({geometryType:r.geometryType,includedTags:a})[0]),{layer:r,view:o,field1:l,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function Wr(e){return await bt(e)}async function Hr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a}){let n=t,l=e?.allLayers.find(c=>c.id===r);if(!l)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:o,layer:l,view:n,colorSchemeTags:a};try{let c=Kr(i),u=await Wr(c);return l.renderer=u.renderer,l.visible=!0,`Relationship renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function Jr({layerId:e,fields:t,colorSchemes:r},o){let{mapView:a}=x(o);return await S({type:"show-legend",data:{layerIds:[e]}},o),await Hr({arcgisMap:a.map,arcgisMapView:a,layerId:e,fields:t,colorSchemes:r})}var Zr=s.object({layerId:s.string().describe("The id of the layer to apply the relationship renderer to"),fields:s.array(s.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use")}),as=f(Jr,{name:"relationship",description:`Label: Relationship
|
|
54
|
+
Description: Overlays two color ramps to represent the relationship between two numeric attributes.
|
|
55
|
+
Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
|
|
56
|
+
Example: Show the relationship between tree height and carbon storage
|
|
57
|
+
Fields: This style requires two number fields.`,schema:Zr});function Yr(e){let{fields:t,layer:r,view:o,theme:a}=e,n=t[0];return{layer:r,view:o,startTime:n,endTime:new Date,theme:a,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Xr(e){return await Tt(e)}async function eo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"size-age",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let u=Yr(c),d=await Xr(u);return i.renderer=d.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying size-age renderer: ${u instanceof Error?u.message:String(u)}`}}async function to({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await eo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var ro=s.object({layerId:s.string().describe("The id of the layer to apply the size-age renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),ns=f(to,{name:"size-age",description:`Label: Age (size)
|
|
58
|
+
Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
59
|
+
Keywords: since, age, how old, how long
|
|
60
|
+
Example: Change the size of features so older features are larger than new features.
|
|
61
|
+
Fields: This style requires at least one field with a date type.`,schema:ro});function oo(e){let{fields:t,layer:r,view:o}=e,{theme:a}=e,n=t[1],l=t[0];return{layer:r,view:o,field:l,normalizationField:n,theme:a,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function ao(e){return await St(e)}async function no({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"size",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let u=oo(c),d=await ao(u);return i.renderer=d.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying size renderer: ${u instanceof Error?u.message:String(u)}`}}async function io({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await no({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var so=s.object({layerId:s.string().describe("The id of the layer to apply the size renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),is=f(io,{name:"size",description:`Label: Counts and Amounts (size)
|
|
62
|
+
Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
|
|
63
|
+
Keywords: graduated size, proportional size, how much, total, number, amount, size
|
|
64
|
+
Example: Vary the size of each point based on the total population.
|
|
65
|
+
Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.
|
|
66
|
+
|
|
67
|
+
Label: Continuous Timeline (size)
|
|
68
|
+
Description: Vary symbol sizes along a continuous ramp to represent dates.
|
|
69
|
+
Keywords: graduated size, proportional size, classed size, how much, total, number, when
|
|
70
|
+
Example: Vary the size of each feature based on the date a ticket was completed.
|
|
71
|
+
Fields: This style requires a single field with a date type.`,schema:so});function lo(e){let{fields:t,layer:r,view:o,colorSchemeTags:a}=e,n=t[0],l=t[1],i=t[2],c;return a&&(c=Et({geometryType:r.geometryType,includedTags:a})[0]),{layer:r,view:o,field:n,field2:l,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function co(e){return await xt(e)}async function uo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,theme:n}){let l=t,i=e?.allLayers.find(u=>u.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"type",fields:o,layer:i,view:l,colorSchemeTags:a,theme:n};try{let u=lo(c),d=await co(u);return i.renderer=d.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(u){return`Error applying type renderer: ${u instanceof Error?u.message:String(u)}`}}async function po({layerId:e,fields:t,colorSchemes:r,theme:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await uo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:o})}var mo=s.object({layerId:s.string().describe("The id of the layer to apply the type renderer to"),fields:s.array(s.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:s.array(s.string()).optional().describe("Optional color scheme tags to use"),theme:s.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),ss=f(po,{name:"type",description:`Label: Types (unique symbols)
|
|
72
|
+
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
73
|
+
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
74
|
+
Example: Color each feature based on the region it belongs to
|
|
75
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:mo}),ls=w.Root({...D(),vectorSearchLayerIds:w(),vectorSearchFieldResults:w(),layerFieldInfo:w(),selectedLayerId:w()}),cs=w.Root({...D(),vectorSearchLayerIds:w(),vectorSearchFieldResults:w(),layerFieldInfo:w(),queryResponse:w(),dataExplorationMessages:w({reducer:L,default:()=>[]})}),ho=["mapView"];function A(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=ho.filter(o=>!(o in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var fo=e=>{let t=e.map?.allLayers.filter(o=>o.type==="feature"),r=0;return t?.forEach(o=>{let a=o;a.featureEffect&&(a.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},yo=async(e,t)=>{let{mapView:r}=A(t);return fo(r)},go=f(yo,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:s.object({})}),wo=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},bo=async(e,t)=>{let{mapView:r}=A(t);return await wo(r)},vo=f(bo,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:s.object({})}),je=750;function Z(e){return"point"in e&&e.point!==void 0}function P(e){return"layerId"in e&&e.layerId!==void 0}var X=async(e,t)=>{if(Z(e)){let{point:r}=e;return{geometry:new De({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(P(e)){let r=t.map?.allLayers.find(n=>n.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let o=r.title??r.id,a=e.where?.trim()||"1=1";try{let n=await r.queryFeatures({where:a,returnGeometry:!0,outSpatialReference:t.spatialReference,num:je+1});if(!n.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${a}`};if(n.features.length>je)return{error:`Geometry filter for layer "${o}" matched too many features (${n.features.length}+). Please narrow the geometry layer filter.`};let l=n.features.map(c=>c.geometry).filter(c=>!!c);if(!l.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=l.length===1?l[0]:Pe.executeMany(l);return i?(i.spatialReference||(i.spatialReference=t.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(n){return{error:`Failed to query geometry: ${String(n)}`}}}return{error:"Invalid geometry configuration provided"}},To=async(e,t,r,o,a,n)=>{let l=e.map?.allLayers.find(c=>c.id===t);if(!l)return{success:!1,error:`Layer '${t}' not found.`};let i=l.createQuery();i.where=r??"1=1",o&&(i.geometry=o,i.spatialRelationship="intersects",a&&(i.distance=a),n&&(i.units=n));try{let{extent:c,count:u}=await l.queryExtent(i);return!c||u===0?{success:!1,error:`No features found for filter (where: ${i.where}${o?", spatial filter used":""})`}:(await e.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},So=async(e,t,r,o,a,n)=>{let l=t.map?.allLayers.find(p=>p.id===e.layerId);if(!l)return`Could not find target layer with ID: ${e.layerId}`;let i;if(a){let p=await X(a,t);if("error"in p)return p.error;i=p.geometry}if(l.featureEffect=null,l.featureEffect=new It({filter:new Oe({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:i,spatialRelationship:"intersects",distance:a?.distance,units:a?.units}),includedEffect:r,excludedEffect:o}),l.visible=!0,n)return`Applied feature effects to "${l.title??e.layerId}" within current map extent.`;let c=e.objectIds?.length?`${l.objectIdField} IN (${e.objectIds.join(",")})`:e.where,u=await To(t,e.layerId,c,i,a?.distance,a?.units),d=l.title??e.layerId;return u.success?`Applied feature effects to target layer "${l.title??e.layerId}"${a&&"layerId"in a?` using geometry from layer "${a.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${u.error}`},xo=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],k=s.enum(xo),Eo=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:l}=A(n);return await So(e,l,o,a,t,r)},Io=s.object({layerId:s.string().describe("The layerId of the layer containing the geometry by which to filter."),where:s.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:s.number().optional().describe("The buffer distance around the geometry."),units:k.optional().describe("The units for the distance buffer.")}),No=s.object({point:s.object({x:s.number().describe("X coordinate (longitude) from navigation result"),y:s.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:s.object({wkid:s.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:s.number().optional().describe("Optional buffer distance around the point."),units:k.optional().describe("The units for the distance buffer.")}),$o=s.object({targetLayer:s.object({layerId:s.string().describe("The layerId of the layer on which to set a feature effect."),where:s.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:s.array(s.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:s.union([Io,No]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:s.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:s.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:s.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),ko=f(Eo,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:$o}),ce=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Fo=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Mo=e=>{if(typeof e=="string"&&e)return e;let t=ce(e);return t?t.toISOString().slice(0,10):null},us=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),o=(Math.abs(e)%60).toString().padStart(2,"0"),a=`${t}${r}:${o}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:a}},Ao=(e,t,r)=>{let o=t?.toLowerCase();if(o==="date-only"){let n=Mo(e);return n?Nt(n,K("short-date")):e}if(o==="time-only"){if(typeof e=="string"&&e)return $t(e,K("long-time"));let n=ce(e);return n?qe(n,{...K("long-time"),timeZone:"UTC"}):e}let a=ce(e);return a?qe(a,{...K("short-date-short-time"),timeZone:Fo(r)}):e},Qe=(e,t,r)=>{if(e&&typeof e!="function"){let o="getField"in r&&r.getField?.(e),a=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(a?.type==="coded-value"){let n=a.codedValues.find(l=>l.code===t);return n?n.name:null}}return null},Co=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Ro=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},qo=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},_o=(e,t,r)=>{let o=Ro(e);if(!o)return e;let a={};t.dateStyle?a.dateStyle=t.dateStyle:(t.year&&(a.year=t.year),t.month&&(a.month=t.month)),t.timeStyle&&(a.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?a.hour12=!0:t.timeStyle&&t.hour12==="never"&&(a.hour12=!1),a.timeZone=Co(r);try{return new Intl.DateTimeFormat(void 0,a).format(o)}catch{return e}},Be=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,Ue=(e,t,r,o,a)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?qo(r,n):n?.type==="date-time"?_o(r,n,a):Ao(r,o,a)},zo=(e,t,r,o)=>{let a=e.fieldsIndex?.get(t),n=Qe(t,r,e)??r;return Ue(e,t,n,a?.type,o)},jo=(e,t)=>Be(e,t),Ke=(e,t,r)=>{let o=e.objectIdField,a=t.features.map(l=>l.attributes[o]),n=t.features.map(l=>{let i=l.attributes,c={};return e.fields.forEach(u=>{if(!Object.hasOwn(i,u.name))return;let d=i[u.name];if(u.name===o){c[u.name]=d;return}let p=Qe(u.name,d,e)??d,m=Be(e,u.name);c[m]=Ue(e,u.name,p,u.type,r)}),c});return{objectIds:a,attributes:n}},Lo=(e,t,r)=>{let o=e.createQuery();return o.outFields=[t],o.where=r||"1=1",o.num=1,o},Do=async(e,t,r,o)=>{let a=o.map?.allLayers.find(d=>d.id===e),n=Lo(a,t,r.where),l=(await a.queryFeatures(n)).features[0],i=l?l.attributes[t]:null,c=zo(a,t,i,o.timeZone),u=jo(a,t);return{tool:"getAttribute",layerName:a.title??e,summary:`${u} = ${c}`,details:{fieldName:t,fieldAlias:u!==t?u:void 0,value:c,where:r.where}}};async function Oo({layerId:e,fieldName:t,query:r},o){let{mapView:a}=A(o),n=await Do(e,t,r,a);return JSON.stringify(n,null,2)}var Po=s.object({layerId:s.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:s.string().describe("The name of the field/attribute from which to get a field value."),query:s.object({where:s.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Go=f(Oo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Po}),be=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function Y(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var Vo=async e=>{let{targetLayer:t,fieldName:r,statisticType:o,mapView:a,layersAndFieldsRegistry:n,geometryFilter:l}=e,i=a.map?.allLayers.find(v=>v.id===t.layerId);if(!i)throw new Error(`Layer '${t.layerId}' not found.`);let c=await a.whenLayerView(i),u=n.get(t.layerId)?.fieldRegistry.get(r),d=u?.alias;if(!u)throw new Error(`Field '${r}' not found.`);let p,m;if(l){let v=await X(l,a);if("error"in v)throw new Error(v.error);if(!v.geometry)throw P(l)?new Error(`No features found matching: ${l.where}`):new Error("Failed to create geometry");if(P(l)){let E=a.map?.allLayers.find(F=>F.id===l.layerId);p={geometryLayerName:E?.title??E?.id,geometryLayerId:l.layerId,geometryWhere:l.where,distance:l.distance,units:l.units,applied:!0}}else Z(l)&&(p={point:l.point,distance:l.distance,units:l.units,applied:!0});m=new Oe({geometry:v.geometry,distance:l.distance,units:l.units,spatialRelationship:"intersects"})}let g=be(c,[r],!1),y=null,h=null,b=10;if(u.type!=="geometry"&&u.type!=="oid"&&u.type!=="global-id")try{let v={layer:i,useFeaturesInView:g,view:g?a:void 0,field:r,sqlWhere:Y(i.definitionExpression,t.where),...m&&{filter:m},outStatisticTypes:{include:[o]}};y=await kt(v);let E=["string","small-integer","integer"],F=u.domain?.type==="coded-value"?u.domain:null;(E.includes(u.type)||F)&&(h=(await Ft({layer:i,useFeaturesInView:g,view:g?a:void 0,field:r,sqlWhere:Y(i.definitionExpression,t.where),...m&&{filter:m}})).uniqueValueInfos.sort((C,Ze)=>Ze.count-C.count).slice(0,b)),h&&u.domain?.type==="coded-value"&&(h=h.map(C=>({...C,value:F?F.getName(C.value)??C.value:C.value})))}catch(v){console.error("Statistics error:",v)}return{tool:"getStatistics",layerName:i.title??t.layerId,summary:`${o} = ${typeof y?.[o]=="number"?y[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:y?.[o]??null,summaryStatistics:y,uniqueValues:h,where:t.where,spatialFilterInfo:p}}};async function Qo({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:o},a){let n=Ve(a,"layersAndFieldsRegistry"),{mapView:l}=A(a),i=await Vo({targetLayer:e,fieldName:t,statisticType:r,mapView:l,layersAndFieldsRegistry:n,geometryFilter:o});return JSON.stringify(i,null,2)}var Bo=s.object({layerId:s.string().describe("The layerId of the layer containing the geometry by which to filter."),where:s.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:s.number().optional().describe("The buffer distance around the geometry."),units:k.optional().describe("The units for the distance buffer.")}),Uo=s.object({point:s.object({x:s.number().describe("X coordinate (longitude) from navigation result"),y:s.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:s.object({wkid:s.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:s.number().optional().describe("Optional buffer distance around the point."),units:k.optional().describe("The units for the distance buffer.")}),Ko=s.object({targetLayer:s.object({layerId:s.string().describe("The layerId of the layer containing the field from which to get a value."),where:s.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:s.union([Bo,Uo]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:s.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:s.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Wo=f(Qo,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
|
|
76
|
+
|
|
77
|
+
USE THIS TOOL FOR:
|
|
78
|
+
- "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
|
|
79
|
+
- "Most common/frequent value of [field]?" \u2014 frequency analysis
|
|
80
|
+
- Questions requiring a mathematical aggregation across many features
|
|
81
|
+
|
|
82
|
+
DO NOT USE FOR:
|
|
83
|
+
- "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
|
|
84
|
+
- "Show / list / find features" \u2014 use queryFeatures instead
|
|
85
|
+
- Simple counts of features matching a condition \u2014 use queryFeatures instead
|
|
86
|
+
|
|
87
|
+
Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Ko}),Ho=async(e,t,r,o,a)=>{let n=r.map?.allLayers.find(m=>m.id===e.layerId),l=await r.whenLayerView(n),i=n.title??e.layerId,c;if(o){let m=await X(o,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 o?o.where:"unknown criteria"}`}};c=m.geometry}else a&&(c=r.extent.clone());let u=t.groupByFields&&t.groupByFields.length>0,d=n.objectIdField,p=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])];try{let m;if(u){let h=new Mt({where:e.where||"1=1",outFields:p,orderByFields:e.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new At({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});m=await n.queryTopFeatures(h)}else{let h=n.createQuery();h.where=Y(n.definitionExpression,e.where||"1=1"),h.outFields=p.length?p:["*"],h.orderByFields=t.orderByFields,h.num=t.topCount,c&&(h.geometry=c,h.spatialRelationship="intersects"),o?.distance&&(h.distance=o.distance),o?.units&&(h.units=o.units),h.outSpatialReference=r.spatialReference;let b=be(l,e.outFields,a??!1);try{m=b?await l.queryFeatures(h):await n.queryFeatures(h)}catch(v){console.warn("Client-side query failed, falling back to server:",v),m=await n.queryFeatures(h)}}let g=m.features.map(h=>h.attributes[d]),{attributes:y}=Ke(n,m,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:y,objectIds:g,objectIdField:d,where:e.where,orderByFields:t.orderByFields,...u&&{groupByFields:t.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},Jo=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:o},a)=>{let{mapView:n}=A(a),l=await Ho(e,t,n,r,o);return JSON.stringify(l,null,2)},Zo=s.object({layerId:s.string().describe("The layerId of the layer containing the geometry by which to filter."),where:s.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:s.number().optional().describe("The buffer distance around the geometry."),units:k.optional().describe("The units for the distance buffer.")}),Yo=s.object({point:s.object({x:s.number().describe("X coordinate (longitude) from navigation result"),y:s.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:s.object({wkid:s.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:s.number().optional().describe("Optional buffer distance around the point."),units:k.optional().describe("The units for the distance buffer.")}),Xo=s.object({targetLayer:s.object({layerId:s.string().describe("The layerId of the layer containing the field from which to get a value."),where:s.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:s.array(s.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:s.array(s.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:s.union([Zo,Yo]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:s.object({topCount:s.number().describe("Number of top features to return per group."),orderByFields:s.array(s.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:s.array(s.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:s.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),ea=f(Jo,{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:Xo}),se=25,ta=async(e,t,r,o)=>{let a=t.map?.allLayers.find(h=>h.id===e.layerId),n=await t.whenLayerView(a),l=a.title??e.layerId,i;if(r){let h=await X(r,t);if("error"in h){let b={error:h.error};if(P(r)){let v=t.map?.allLayers.find(E=>E.id===r.layerId);b.geometryLayerName=v?.title??v?.id,b.geometryLayerId=r.layerId,b.geometryWhere=r.where}else Z(r)&&(b.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"Geometry lookup failed",details:b}}if(!h.geometry){let b={};if(P(r)){let v=t.map?.allLayers.find(E=>E.id===r.layerId);b.error=`No features found matching: ${r.where}`,b.geometryLayerName=v?.title??v?.id,b.geometryLayerId=r.layerId,b.geometryWhere=r.where}else Z(r)&&(b.error="Failed to create point geometry",b.point=r.point);return{tool:"queryFeatures",layerName:l,summary:"No features found for geometry filter",details:b}}i=h.geometry}else o&&(i=t.extent.clone());let c=be(n,e.outFields,o??!1),u=a.objectIdField,d=a.createQuery();d.where=Y(a.definitionExpression,e.where||"1=1"),d.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,u])],d.orderByFields=e.orderByFields,i&&(d.geometry=i,d.spatialRelationship="intersects"),r?.distance&&(d.distance=r.distance),r?.units&&(d.units=r.units),d.outSpatialReference=t.spatialReference;let p,m;try{p=c?await n.queryFeatureCount(d):await a.queryFeatureCount(d),p>0&&p<=se&&(m=c?await n.queryFeatures(d):await a.queryFeatures(d))}catch(h){console.warn("Client-side query failed, falling back to server:",h),p=await a.queryFeatureCount(d),p>0&&p<=se&&(m=await a.queryFeatures(d))}let{objectIds:g,attributes:y}=m?Ke(a,m,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:l,summary:`${p} features found`,details:{totalCount:p,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...g&&{objectIds:g,objectIdField:u},...y&&{attributes:y},...p>se&&{note:`${p} features found.`}}}};async function ra({targetLayer:e,geometryFilter:t,useCurrentExtent:r},o){let{mapView:a}=A(o),n=await ta(e,a,t,r);return JSON.stringify(n,null,2)}var oa=s.object({layerId:s.string().describe("The layerId of the layer containing the geometry by which to filter."),where:s.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:s.number().optional().describe("The buffer distance around the geometry."),units:k.optional().describe("The units for the distance buffer.")}),aa=s.object({point:s.object({x:s.number().describe("X coordinate (longitude) from navigation result"),y:s.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:s.object({wkid:s.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:s.number().optional().describe("Optional buffer distance around the point."),units:k.optional().describe("The units for the distance buffer.")}),na=s.object({targetLayer:s.object({layerId:s.string().describe("The layerId of the layer containing the field from which to get a value."),where:s.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:s.array(s.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:s.array(s.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:s.union([oa,aa]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:s.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),ia=f(ra,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
88
|
+
|
|
89
|
+
USE THIS TOOL FOR:
|
|
90
|
+
- "Show / display / list features where..." \u2014 finding and listing features
|
|
91
|
+
- "How many X are Y?" \u2014 counting features that match a condition
|
|
92
|
+
- "Which features..." / "Find features..." \u2014 identifying specific features
|
|
93
|
+
- Spatial queries \u2014 finding features near/within/intersecting other features
|
|
94
|
+
- Any question where the user wants to SEE or COUNT matching features
|
|
95
|
+
|
|
96
|
+
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:na}),sa=[Go,Wo,ea,ia],ds=[ko,vo,go],la=new U(sa,{handleToolErrors:!1});async function ps(e,t){let{messages:r}=await la.invoke({messages:e.dataExplorationMessages},t),o=[],a=[];for(let n of r){let l=n.content,i;typeof l!="string"&&(i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:l}});try{typeof l=="string"?i=JSON.parse(l):i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:l}}}catch{i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:l}}}o.push(i),i.details&&typeof i.details=="object"&&"error"in i.details?a.push(`- ${i.tool}: Error - ${String(i.details.error)}`):a.push(`- ${i.layerName}: ${i.summary}`)}return await T({text:`Finished executing layer query tool: ${a.join(", ")}`},t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,...r],queryResponse:o,status:"success",summary:a.length>0?ur(a.join(`
|
|
97
|
+
`)):"Query executed."}}var ms=w.Root({...D(),helpInternalState:w({reducer:O,default:()=>({toolCallMessage:void 0})})}),ca=(e,t)=>{let r=Array.from(e.values()).find(({layerItem:n})=>n.title?.toLowerCase().includes(t.toLowerCase()));if(!r){let n=Array.from(e.values()).map(l=>l.layerItem.title).join(", ");return`Could not find a layer matching "${t}". Available layers: ${n}`}let o=Array.from(r.fieldRegistry.values()),a=o.map(n=>`- **${n.alias||n.name}** (\`${n.name}\`, ${n.type})${n.description?`: ${n.description}`:""}`).join(`
|
|
98
|
+
`);return`**${r.layerItem.title}** has ${o.length} field(s):
|
|
99
|
+
|
|
100
|
+
${a}`},ua=async({layerTitle:e},t)=>{let r=Ve(t,"layersAndFieldsRegistry");return ca(r,e)},hs=f(ua,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:s.object({layerTitle:s.string().describe("The title or partial title of the layer to list fields for.")})}),fs=w.Root({...D(),intent:w({reducer:(e,t)=>t}),arcgisKnowledgeMessages:w({reducer:L,default:()=>[]}),arcgisKnowledgeToolResult:w({reducer:(e,t)=>t,default:()=>null})}),W={conversationId:""};function ve(e){let t=e.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!t||t?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function $(e){return!!e?.map&&!("activeLinkChartLayer"in e.map)}async function ee(e){!e||$(e)||!e.map?.diagramNodesExtent||await e.goTo(e.map.diagramNodesExtent)}function te(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in t))throw new Error("View context missing");let r=t.view;return r.map&&!("activeLinkChartLayer"in r.map)&&ve(r),{view:r}}function ys(e){let t=e?.configurable?.context;if(We(e)==="knowledgeGraph")return"knowledgeGraph";let r=t.view;return $(r)?(ve(r),"map"):"linkChart"}async function V(e){let t=e?.configurable?.context;if(We(e)==="knowledgeGraph")return t;{let r=t.view.map;if(r&&"activeLinkChartLayer"in r){let o=r.knowledgeGraph?.url;if(!o)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await _e(o)}}else{ve(t.view);let o=(t.view.map?.allLayers.find(a=>a.type==="knowledge-graph")).url;if(!o)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await _e(o)}}}}function We(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in t&&"view"in t)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in t)return"knowledgeGraph";if("view"in t)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var ue=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=de.fromDataModel(t)}},de=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let o of t.entityTypes)r.entityTypes.push(G.fromEntityType(o));for(let o of t.relationshipTypes)r.relationshipTypes.push(pe.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:da(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}static getDataModelTypesSummary(t){let r=t.entityTypes.map(a=>a.name).join(", "),o=t.relationshipTypes.map(a=>a.name).join(", ");return`Entity Types: ${r}.
|
|
101
|
+
Relationship Types: ${o}.`}},G=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(t){let r=new e;r.name=t.name,r.alias=t.alias?t.alias:void 0,r.role=pa(t.role);for(let o of t.properties){let a={name:o.name,alias:o.alias?o.alias:void 0,fieldType:o.fieldType,role:ma(o.role),geometryDef:o.fieldType==="esriFieldTypeGeometry"?{geometryType:o.geometryType??"esriGeometryAny",hasM:o.hasM?o.hasM:void 0,hasZ:o.hasZ?o.hasZ:void 0}:void 0};r.properties.push(a)}return r}},pe=class extends G{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=G.fromEntityType(t);r.observedEndPoints=[];for(let o of t.endPoints)r.observedEndPoints.push({originEntityType:o.originEntityType,destinationEntityType:o.destinationEntityType});return r}},da=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},pa=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function ma(e){switch(e){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function re(e){return e?.configurable?.abortSignal}function ha(e,t){return t?`${e}
|
|
102
|
+
|
|
103
|
+
Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
|
|
104
|
+
|
|
105
|
+
Attempt Number: ${t.attemptCount}
|
|
106
|
+
Execution Error: ${t.executionError}
|
|
107
|
+
Failed Query:
|
|
108
|
+
${t.failedGraphQuery}`:e}async function fa(e,t,r,o){let{graphQuery:a,explanation:n}=await Te(e,t,r,o);return{graphQuery:a,explanation:n}}async function Te(e,t,r,o,a){let n={message:ha(e,a),context:new ue(t)};W.conversationId&&(n.conversationId=W.conversationId);let l=re(o);await T({text:"Attempting to generate a cypher query from your prompt..."},o);let i=await Ce(`${r}/chat`,{method:"post",body:JSON.stringify(n),headers:{"Content-Type":"application/json",token:Ae.findCredential(M.getDefault().url)?.token??""},signal:l});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});W.conversationId||(W.conversationId=i.data.conversationId);let c=!1,u=Date.now(),d=i.data.sequenceNumber,p="",m="",g=1;for(;!c;){await new Promise(h=>setTimeout(h,1e3)),await T({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,g)}`},o),g=g%3+1;let y=await Ce(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:Ae.findCredential(M.getDefault().url)?.token??""},signal:l});if(y.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${y.httpStatus}`,{cause:y.data});if(y.data.context?.kind){if(y.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${y.data.message}`,{cause:y.data});p=y.data.context.graphQuery,m=y.data.message||"",c=!0}else if(!y.data.hasMore)c=!0;else if(Date.now()-u>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=y.data.sequenceNumber}return{graphQuery:p,explanation:m}}var R=3;function He(e,t=100){let r={};for(let o of Object.entries(e.properties??{})){let[a,n]=o;typeof n=="string"&&n.length>t?r[a]=`${n.slice(0,t)}... (truncated, original length: ${n.length})`:r[a]=n}return e.properties=r,e}function _(e){return typeof e!="object"||e===null?String(e):"details"in e&&typeof e.details=="object"&&e.details!==null&&"errorMessage"in e.details&&typeof e.details.errorMessage=="string"?e.details.errorMessage:"message"in e&&typeof e.message=="string"?e.message:String(e)}var ya=async({kg:e,queryParams:t,targetStructure:r,targetStructureReducer:o,requestOptions:a,queryRowLimit:n,queryTimeoutMs:l})=>{let i=null,c=r,u=new AbortController,d=a?.signal,p=()=>{u.abort(d?.reason)};d&&(d.aborted?u.abort(d.reason):d.addEventListener("abort",p,{once:!0}));try{let m=await Rt(e,t,a);i=m.resultHeader;let g=m.resultRowsStream.getReader(),y=0,h=Date.now(),b=!1;for(;;){let{done:v,value:E}=await g.read();if(v)break;if(!b&&l&&Date.now()-h>l)return u.abort(),{type:"timeout"};for(let F of E){if(y++,n&&y>n)return u.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:c};c=o(c,F)}}}catch(m){return u.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:_(m),error:m}}finally{d?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:c}};async function Je({prompt:e,kg:t,graphQueryServiceUrl:r,targetStructure:o,targetStructureReducer:a,requestOptions:n,queryRowLimit:l,queryTimeoutMs:i,config:c}){let u;for(let d=1;d<=R;d++){let p;try{p=await Te(e,t.dataModel,r,c,u)}catch(y){return{type:"generation-error",errorMessage:_(y),error:y}}await T({text:`Attempting to execute query: ${p.graphQuery.substring(0,500)}${p.graphQuery.length>500?"...":""}`},c);let m=await ya({kg:t,queryParams:new Ge({openCypherQuery:p.graphQuery}),targetStructure:o,targetStructureReducer:a,requestOptions:n,queryRowLimit:l,queryTimeoutMs:i}),g=m.type==="aborted"?"Query execution was aborted.":m.type==="timeout"?"Query execution timed out.":m.type==="error"?`Query failed with error: ${m.errorMessage}`:"";if(m.type==="success")return{type:"success",graphQuery:p.graphQuery,explanation:p.explanation,rowLimitReached:m.rowLimitReached,resultHeader:m.resultHeader,processedResult:m.processedResult};if(m.type==="aborted")return{type:"aborted",errorMessage:g,graphQuery:p.graphQuery,explanation:p.explanation};if(d>=R)return m.type==="timeout"?{type:"timeout",errorMessage:g,graphQuery:p.graphQuery,explanation:p.explanation}:{type:"execution-error",errorMessage:g,error:m.error,graphQuery:p.graphQuery,explanation:p.explanation};u={failedGraphQuery:p.graphQuery,executionError:g,attemptCount:d},await T({text:`Attempt ${d} failed with error: ${g}. Retrying...`},c)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${R} attempts.`)}var ga=async({kg:e,searchQuery:t,typeCategoryFilter:r,namedTypesFilter:o,searchResultLimit:a,requestOptions:n})=>{let l=[],i=[r];r==="both"&&!e.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let c=a??1/0;try{for(let u of i){let d=c-l.length;if(d<=0)break;let p=(await qt(e,new _t({searchQuery:t,typeCategoryFilter:u,namedTypesFilter:o??void 0,num:d}),n)).resultRowsStream.getReader(),m=!1;for(;!m;){let{done:g,value:y}=await p.read();if(g){m=!0;break}for(let h of y)for(let b of h)l.push(b)}}}catch(u){let d=_(u);return n?.signal?.aborted?{type:"aborted",errorMessage:d,error:u}:{type:"error",errorMessage:d,error:u}}return{type:"success",results:l}};function wa(e,t){q(e,r=>{t.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function q(e,t){if(!(!e||typeof e!="object")){if(va(e))for(let r of e.path)q(r,t);else if(ba(e))t(e);else if(Array.isArray(e))for(let r of e)q(r,t);else if(Ta(e))for(let r of Object.values(e.properties??{}))q(r,t)}}function ba(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function va(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Ta(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function Sa(e,t){let r=[];for(let o of[...t.dataModel.entityTypes,...t.dataModel.relationshipTypes]){let a=e.getMemberIdsByType(o.name);for(let n of a)r.push({id:n,typeName:o.name})}return r}function xa(e){let t=[],r=[],o=e?.allLayers.find(a=>a.type==="knowledge-graph")?.inclusionModeDefinition;if(o?.generateAllSublayers)return{allNamedTypesFullyDynamic:!0,idTypePairs:t,dynamicTypes:r};for(let[a,n]of o?.namedTypeDefinitions??[])if(n.useAllData)r.push(a);else for(let[l]of n.members)t.push({id:l,typeName:a});return{allNamedTypesFullyDynamic:!1,idTypePairs:t,dynamicTypes:r}}async function Ea(e,t,r,o,a){let{view:n}=o,l=await Je({prompt:e,kg:t,graphQueryServiceUrl:r,targetStructure:new Map,targetStructureReducer:(p,m)=>{for(let g of m)wa(g,p);return p},requestOptions:{signal:re(a),timeout:a?.timeout},config:a});if(l.type!=="success"){let p=l.type==="generation-error"?l.errorMessage:`${l.errorMessage} Cypher query: ${l.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${p}`)}let{graphQuery:i,explanation:c,processedResult:u}=l,d=Array.from(u.values());return await T({text:`Query Results parsed into ${d.length} unique relationships and entities. Atempting to add to link chart...`},a),!$(n)&&n?.map?(await n.map.addRecords(d),await ee(n),{generatedQuery:i,explanation:c,addedIdTypePairs:d}):(await n?.map?.allLayers.find(p=>p.type==="knowledge-graph")?.addRecords(d),{generatedQuery:i,explanation:c,addedIdTypePairs:d})}var H="addRecords",Ia=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Na=async({prompt:e},t)=>{let{knowledgeGraph:r}=await V(t),o=te(t),{view:a}=o,n=M.getDefault().helperServices,l=e;if(!$(a)&&a.map){let i=a.map,c=await le("arcgis_knowledge_current_lc_context"),u=Sa(i,r);l=`${e}
|
|
109
|
+
|
|
110
|
+
${c}${JSON.stringify(u)}`}else if($(a)&&a.map){let i=a.map,{allNamedTypesFullyDynamic:c,idTypePairs:u,dynamicTypes:d}=xa(i),p=await le("arcgis_knowledge_current_map_context");if(l=`${e}
|
|
111
|
+
|
|
112
|
+
${p}${JSON.stringify(u)} and all entities or relationships with the the following typeNames in the array: ${JSON.stringify(d)}`,c)return{toolName:H,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}}}try{let{generatedQuery:i,explanation:c,addedIdTypePairs:u}=await Ea(l,r,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,o,t);return{toolName:H,status:"success",summary:`Records added successfully. Cypher Query used: ${i}
|
|
113
|
+
|
|
114
|
+
Number of records added: ${u.length}`,details:{generatedQuery:i,explanation:c,addedIdTypePairs:u}}}catch(i){let c=_(i);return console.error(`Failed to add records to the link chart. ${c}`,i),{toolName:H,status:"error",errorMessage:`Failed to add records to the link chart. ${c}`,error:i}}},gs=f(Na,{name:H,description:"Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt.",schema:Ia});async function $a(e,t){return await t.map?.applyLayout(e),await ee(t),{appliedLayout:e}}var me="applyLayout",ka=s.object({layout:s.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),Fa=async({layout:e},t)=>{let{view:r}=te(t);if($(r))return{toolName:me,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:o}=await $a(e,r);return{toolName:me,status:"success",summary:`Successfully applied layout: ${o}.`,details:{appliedLayout:o}}}},ws=f(Fa,{name:me,description:"Apply a diagram layout to the link chart",schema:ka});async function Ma(e,t){return t.map?.changeNonspatialDataDisplay(e),await ee(t),{appliedNonspatialDataDisplayMode:e}}var he="changeNonspatialVisibility",Aa=s.object({setting:s.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Ca=async({setting:e},t)=>{let{view:r}=te(t);if($(r))return{toolName:he,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:o}=await Ma(e,r);return{toolName:he,status:"success",summary:`Successfully applied nonspatial visibility setting: ${o}.`,details:{appliedNonspatialDataDisplayMode:o}}}},bs=f(Ca,{name:he,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Aa});async function Ra(e,t,r,o,a){let n,l="";for(let i=1;i<=R;i++){let{graphQuery:c,explanation:u}=await Te(e,t.dataModel,r,a,n);try{await T({text:`Attempting to create link chart from derived query: ${c}`},a);let d=await Ct.fromCypherQuery(t,new Ge({openCypherQuery:c}));await T({text:"Link chart created successfully, loading..."},a),await d.load();let p=o.map;return o.map=d,await o.when(),await Le.whenOnce(()=>!o.updating),d.entityCount===0&&d.relationshipCount===0?(o.map===d&&(o.map=p),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
|
|
115
|
+
${c}
|
|
116
|
+
|
|
117
|
+
Explanation: ${u}`}):(await ee(o),{type:"success",graphQuery:c,explanation:u})}catch(d){let p=_(d);if(i>=R){l=p;break}n={failedGraphQuery:c,executionError:p,attemptCount:i},await T({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},a)}}return{type:"error",errorMessage:`Failed to create link chart after ${R} attempts. Last error: ${l}`}}var J="createLinkChart",qa=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),_a=async({prompt:e},t)=>{let{knowledgeGraph:r}=await V(t),{view:o}=te(t);if($(o))return{toolName:J,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let a=M.getDefault().helperServices,n=await Ra(e,r,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,o,t);if(n.type==="error")return{toolName:J,status:"error",errorMessage:n.errorMessage,error:new Error};let{graphQuery:l,explanation:i}=n;return{toolName:J,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
|
|
118
|
+
${l}
|
|
119
|
+
|
|
120
|
+
Explanation: ${i}`,details:{generatedQuery:l,explanation:i}}}},vs=f(_a,{name:J,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt.",schema:qa}),fe="queryGraphData",za=s.object({prompt:s.string().describe(`The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. IMPORTANT:
|
|
121
|
+
|
|
122
|
+
REQUEST LIMIT: If the user does not specifically request for no limits or an explicit limit to be placed on the query, or the number of rows will not be limited by e.g. the number of entity or relationship types in the graph, ensure that the generated query has a reasonable row limit (e.g. 10 rows).
|
|
123
|
+
|
|
124
|
+
DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),ja=async({prompt:e},t)=>{let{knowledgeGraph:r}=await V(t),o=M.getDefault().helperServices,a=await Je({prompt:e,kg:r,graphQueryServiceUrl:`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(m,g)=>(m.push(g),m),requestOptions:{signal:re(t),timeout:t?.timeout},config:t});if(a.type!=="success"){let m=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;return{toolName:fe,status:"error",errorMessage:`Failed to query the knowledge graph. ${m}`,error:"error"in a?a.error:null}}let{graphQuery:n,explanation:l,processedResult:i,resultHeader:c}=a,u=c.headerKeys;for(let m of i)for(let g of m)q(g,y=>He(y));let d=50,p=i.slice(0,d).map(m=>JSON.stringify(m));return{toolName:fe,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
|
|
125
|
+
|
|
126
|
+
\`\`\`cypher
|
|
127
|
+
${n}
|
|
128
|
+
\`\`\`
|
|
129
|
+
|
|
130
|
+
Query Results:
|
|
131
|
+
${p.length} result(s) found.
|
|
132
|
+
|
|
133
|
+
Column Headers: ${u.join(", ")}
|
|
134
|
+
|
|
135
|
+
${p.length>d?`Showing top ${d} results:
|
|
136
|
+
|
|
137
|
+
`:`Results:
|
|
138
|
+
|
|
139
|
+
`}${p.join(`
|
|
140
|
+
`)}
|
|
141
|
+
`,details:{generatedQuery:n,explanation:l,resultHeader:c,queryResults:i}}},Ts=f(ja,{name:fe,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:za}),ye="generateCypher",La=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Da=async({prompt:e},t)=>{let{knowledgeGraph:r}=await V(t),o=M.getDefault().helperServices;try{let{graphQuery:a,explanation:n}=await fa(e,r.dataModel,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,t);return{toolName:ye,status:"success",summary:`Generated Graph Query:
|
|
142
|
+
${a}
|
|
143
|
+
|
|
144
|
+
Explanation: ${n}`,details:{generatedQuery:a,explanation:n}}}catch(a){let n=_(a);return{toolName:ye,status:"error",errorMessage:`Failed to generate Cypher query. ${n}`,error:a}}},Ss=f(Da,{name:ye,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:La}),Oa=e=>{let t=e.dataModel,r=new Map;for(let i of t.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[c,u]of i.searchProperties.entries()){let d=r.get(c)??new Set;u.propertyNames.forEach(p=>d.add(p)),r.set(c,d)}let o=t.entityTypes.filter(i=>r.has(i.name)),a=t.relationshipTypes.filter(i=>r.has(i.name)),n=`Entity Types:
|
|
145
|
+
${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
146
|
+
`)}`,l=`Relationship Types:
|
|
147
|
+
${a.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
148
|
+
`)}`;return`${n}
|
|
149
|
+
|
|
150
|
+
${l}`};async function Pa(e,t){let r=await le("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:e,dataModelForSearch:Oa(t)},a=s.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),n=s.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),l=s.array(s.enum(t.dataModel.entityTypes.map(c=>c.name).concat(t.dataModel.relationshipTypes.map(c=>c.name)))).min(1),i=s.object({query:s.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:l.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:a,resultLimit:n});return await Ne({promptText:r,inputVariables:o,schema:i})}var ge="searchGraphData",Ga=s.object({prompt:s.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),Va=async({prompt:e},t)=>{let{knowledgeGraph:r}=await V(t);await T({text:"Generating search query for the user inquiry"},t);let o=await Pa(e,r);await T({text:"Executing graph search with generated search query"},t);let a=await ga({kg:r,searchQuery:o.query,typeCategoryFilter:o.typeCategoryFilter,namedTypesFilter:o.typeFilters,searchResultLimit:o.resultLimit,requestOptions:{signal:re(t),timeout:t?.timeout}});if(a.type!=="success")return{toolName:ge,status:"error",errorMessage:a.errorMessage,error:"error"in a?a.error:null};for(let i of a.results)q(i,c=>He(c));let n=10,l=a.results.slice(0,n);return{toolName:ge,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
|
|
151
|
+
Query: ${o.query}
|
|
152
|
+
Type Category Filter: ${o.typeCategoryFilter}
|
|
153
|
+
Named Type Filters: ${o.typeFilters?o.typeFilters.join(", "):"None"}
|
|
154
|
+
Result Limit: ${o.resultLimit??"No limit"}
|
|
155
|
+
|
|
156
|
+
Search Results: ${a.results.length} result(s) found.
|
|
157
|
+
|
|
158
|
+
${a.results.length>n?`Showing top ${n} results:
|
|
159
|
+
|
|
160
|
+
`:""}${l.map(i=>JSON.stringify(i)).join(`
|
|
161
|
+
`)}`,details:{generatedSearchQuery:o,searchResults:a.results}}},xs=f(Va,{name:ge,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:Ga});return{a:U,b:Oi,c:N,d:Pi,e:Gi,f:Vi,g:Qi,h:Bi,i:Ui,j:Ki,k:Wi,l:Hi,m:le,n:ur,o:Ve,p:Ji,q:Zi,r:Yi,s:Xi,t:es,u:ts,v:rs,w:os,x:as,y:ns,z:is,A:ss,B:ls,C:cs,D:A,E:us,F:sa,G:ds,H:ps,I:ms,J:hs,K:fs,L:ys,M:V,N:de,O:gs,P:ws,Q:bs,R:vs,S:Ts,T:Ss,U:xs}},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming",a)
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import{a as s,b as i}from"./
|
|
2
|
+
import{a as s,b as i}from"./5W7S2RS4.js";import{c as r}from"./NXKKG5TK.js";function c(e,n){let t=s(e.el,e.referenceElement);if(t)return t;let o=r(e.el,"arcgis-assistant"),a=s(e.el,o?.referenceElement);if(a)return a;throw new Error(`${n}: Reference element not found`)}function g(e,n){let t=c(e,n).view;if(!t)throw new Error(`${n}: Reference element does not have a view`);return t}function m(e){return typeof e=="function"}function w(e){let n=r(e.el,"arcgis-assistant");if(n===void 0)throw new Error("arcgis-assistant-agent must be used within an arcgis-assistant element");n.register({agent:e.agent,getContext:async()=>await e.getContext?.()??e.context??{}})}function f(e){let n=i(e.el,e.referenceElement);if(n)return n;let t=r(e.el,"arcgis-assistant");return s(e.el,t?.referenceElement)||null}function E(e){let n=f(e);return n?n.view:null}export{g as a,m as b,w as c,E as d};
|