@arcgis/ai-components 6.0.0-next.2 → 6.0.0-next.4
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/middlewares/humanInTheLoop.js +22 -20
- package/dist/agents/agents/help/helpAgent.js +10 -10
- package/dist/agents/tools/navigation/goToBookmark/adapter.js +34 -17
- package/dist/cdn/46NXKDIE.js +2 -0
- package/dist/cdn/{7APXFHDF.js → 5OGABLOF.js} +4 -4
- package/dist/cdn/CKDKQVS3.js +2 -0
- package/dist/cdn/CV5YAJMD.js +2 -0
- package/dist/cdn/{L5OYOLWV.js → CWZG7DML.js} +1 -1
- package/dist/cdn/{UJMM5QA4.js → EWZNZZ5S.js} +1 -1
- package/dist/cdn/G4L7RUTK.js +49 -0
- package/dist/cdn/H653UVNH.js +2 -0
- package/dist/cdn/{Q7BJGEFH.js → I2RQZAFF.js} +1 -1
- package/dist/cdn/JZT4ECVH.js +2 -0
- package/dist/cdn/MNMCIS4E.js +15 -0
- package/dist/cdn/{ZROI63CW.js → MSHEHZYP.js} +2 -2
- package/dist/cdn/OVH4S4ZB.js +3 -0
- package/dist/cdn/{5SRRG7WG.js → RQYDIQVD.js} +2 -2
- package/dist/cdn/TZQ6XEKW.js +2 -0
- package/dist/cdn/YIF2OD6F.js +2 -0
- package/dist/cdn/agent-utils/SkillAgent.js +1 -1
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/SKILL3.js +6 -10
- package/dist/chunks/intent_prompt.js +18 -107
- package/dist/components/arcgis-assistant/customElement.js +100 -100
- package/dist/components/arcgis-assistant/types.d.ts +2 -0
- package/dist/components/arcgis-assistant-interrupt/customElement.d.ts +6 -0
- package/dist/components/arcgis-assistant-interrupt/customElement.js +24 -23
- 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/loader.js +1 -1
- package/dist/orchestrator/types.d.ts +6 -0
- package/dist/types/lumina.d.ts +1 -1
- package/dist/types/preact.d.ts +1 -1
- package/dist/types/react.d.ts +1 -1
- package/dist/types/stencil.d.ts +1 -1
- package/package.json +5 -5
- package/dist/cdn/7XVIZ7HK.js +0 -2
- package/dist/cdn/AWH4VDPD.js +0 -2
- package/dist/cdn/G3KILEGJ.js +0 -2
- package/dist/cdn/HOMSK66Q.js +0 -2
- package/dist/cdn/MHXM37QI.js +0 -2
- package/dist/cdn/RFIN7KO6.js +0 -138
- package/dist/cdn/SG6PAUVR.js +0 -2
- package/dist/cdn/SRXUC4QB.js +0 -3
- package/dist/cdn/V66TS2BB.js +0 -2
- package/dist/cdn/ZEDDYT24.js +0 -19
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
-
import { NodeInterrupt as
|
|
2
|
+
import { NodeInterrupt as c } from "@langchain/langgraph/web";
|
|
3
3
|
import { createAgentMiddleware as f, createToolMiddleware as I } from "./middleware.js";
|
|
4
|
-
const
|
|
5
|
-
function
|
|
4
|
+
const h = "human-in-the-loop", w = "Agent execution requires approval", p = "Agent execution rejected by the user.", m = "human-in-the-loop-tool", y = "Tool execution requires approval";
|
|
5
|
+
function C(t = {}) {
|
|
6
6
|
const { outputKey: n } = t;
|
|
7
7
|
return f(
|
|
8
|
-
|
|
8
|
+
h,
|
|
9
9
|
{
|
|
10
10
|
wrapAgent: async (e, r) => {
|
|
11
11
|
const a = T(e), o = M(a, e), i = u(e.config?.configurable);
|
|
12
12
|
if (i?.agentId !== a)
|
|
13
|
-
throw new
|
|
13
|
+
throw new c(await g({ agentId: a, interruptId: o, options: t, request: e }));
|
|
14
14
|
if (i.id !== o) {
|
|
15
15
|
if (b(a, i.id))
|
|
16
16
|
return await r(e);
|
|
17
|
-
throw new
|
|
17
|
+
throw new c(await g({ agentId: a, interruptId: o, options: t, request: e }));
|
|
18
18
|
}
|
|
19
19
|
if (i.payload === !1)
|
|
20
20
|
return { outputMessage: p, status: "failed", summary: p };
|
|
@@ -25,17 +25,17 @@ function k(t = {}) {
|
|
|
25
25
|
{ outputKey: n }
|
|
26
26
|
);
|
|
27
27
|
}
|
|
28
|
-
function
|
|
28
|
+
function k(t = {}) {
|
|
29
29
|
const { outputKey: n } = t;
|
|
30
|
-
return I(
|
|
30
|
+
return I(m, {
|
|
31
31
|
wrapToolCall: async (e, r) => {
|
|
32
32
|
const a = e.tool.name, o = A(e.config?.configurable), i = R(o, e.toolCallId ?? a), l = u(e.config?.configurable);
|
|
33
33
|
if (l?.agentId !== o || l.id !== i)
|
|
34
|
-
throw new
|
|
34
|
+
throw new c(await $({ agentId: o, interruptId: i, options: t, request: e }));
|
|
35
35
|
if (l.payload === !1)
|
|
36
36
|
return `Tool call "${a}" was rejected by the user.`;
|
|
37
|
-
const d = n ? { ...e.input, [n]: l.payload } : e.input,
|
|
38
|
-
return await r(
|
|
37
|
+
const d = n ? { ...e.input, [n]: l.payload } : e.input, s = { ...e, input: d };
|
|
38
|
+
return await r(s);
|
|
39
39
|
}
|
|
40
40
|
});
|
|
41
41
|
}
|
|
@@ -46,7 +46,8 @@ async function g(t) {
|
|
|
46
46
|
id: e,
|
|
47
47
|
kind: o?.kind ?? "booleanChoice",
|
|
48
48
|
message: o?.message ?? w,
|
|
49
|
-
metadata: o?.metadata
|
|
49
|
+
metadata: o?.metadata,
|
|
50
|
+
showOtherOption: o?.showOtherOption
|
|
50
51
|
};
|
|
51
52
|
}
|
|
52
53
|
function T(t) {
|
|
@@ -66,21 +67,22 @@ function R(t, n) {
|
|
|
66
67
|
return `${t}:tool:${n}`;
|
|
67
68
|
}
|
|
68
69
|
async function $(t) {
|
|
69
|
-
const { agentId: n, interruptId: e, options: r, request: a } = t, { input: o, tool: i, toolCallId: l } = a, d = i.name,
|
|
70
|
+
const { agentId: n, interruptId: e, options: r, request: a } = t, { input: o, tool: i, toolCallId: l } = a, d = i.name, s = await r.interrupt?.({ ...a, args: o, toolName: d, toolCallId: l });
|
|
70
71
|
return {
|
|
71
72
|
agentId: n,
|
|
72
73
|
id: e,
|
|
73
|
-
kind:
|
|
74
|
-
message:
|
|
74
|
+
kind: s?.kind ?? "booleanChoice",
|
|
75
|
+
message: s?.message ?? `${y}
|
|
75
76
|
Tool: ${d}`,
|
|
76
|
-
|
|
77
|
+
showOtherOption: s?.showOtherOption,
|
|
78
|
+
metadata: s?.metadata ?? {
|
|
77
79
|
args: o,
|
|
78
80
|
toolCallId: l,
|
|
79
81
|
toolName: d
|
|
80
82
|
}
|
|
81
83
|
};
|
|
82
84
|
}
|
|
83
|
-
function
|
|
85
|
+
function v(t) {
|
|
84
86
|
return u(t?.configurable)?.payload;
|
|
85
87
|
}
|
|
86
88
|
function u(t) {
|
|
@@ -88,7 +90,7 @@ function u(t) {
|
|
|
88
90
|
return n && typeof n == "object" && "id" in n && "agentId" in n ? n : null;
|
|
89
91
|
}
|
|
90
92
|
export {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
C as createHumanInTheLoopMiddleware,
|
|
94
|
+
k as createHumanInTheLoopToolMiddleware,
|
|
95
|
+
v as getHumanInTheLoopPayload
|
|
94
96
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
2
|
import { c as o } from "../../../chunks/createSkillAgent.js";
|
|
3
|
-
const d = (
|
|
4
|
-
const
|
|
3
|
+
const d = (i, e) => {
|
|
4
|
+
const a = Array.from(i?.values() ?? []).map(({ fieldRegistry: n, layerItem: t }) => {
|
|
5
5
|
const s = Array.from(n.values(), ({ name: l }) => l);
|
|
6
6
|
return {
|
|
7
7
|
title: t.title,
|
|
@@ -9,23 +9,23 @@ const d = (a, e) => {
|
|
|
9
9
|
fields: s.slice(0, 10),
|
|
10
10
|
additionalFieldCount: Math.max(s.length - 10, 0)
|
|
11
11
|
};
|
|
12
|
-
}),
|
|
12
|
+
}), r = (e?.list() ?? []).map(({ agent: { description: n, id: t, name: s } }) => ({
|
|
13
13
|
id: t,
|
|
14
14
|
name: s,
|
|
15
15
|
description: n
|
|
16
16
|
}));
|
|
17
|
-
return JSON.stringify({ layers:
|
|
18
|
-
},
|
|
19
|
-
const e =
|
|
17
|
+
return JSON.stringify({ layers: a, agents: r }, null, 2);
|
|
18
|
+
}, p = ({ config: i }) => {
|
|
19
|
+
const e = i?.configurable?.services;
|
|
20
20
|
return d(e?.layersAndFieldsRegistry, e?.agentRegistry);
|
|
21
|
-
},
|
|
21
|
+
}, c = [async () => (await import("../../../chunks/SKILL3.js")).default], m = o({
|
|
22
22
|
id: "help",
|
|
23
23
|
name: "Help Agent",
|
|
24
|
-
description: "Answers questions about the
|
|
25
|
-
skillLoaders:
|
|
24
|
+
description: "Answers questions about the map, its layers, and fields in those layers, including listing all or matching layers by title or description and fields by name, alias, type, or description. Explains assistant capabilities and redirects unsupported map actions or unrelated questions to map-related help.",
|
|
25
|
+
skillLoaders: c,
|
|
26
26
|
modelTier: "default",
|
|
27
27
|
systemPrompt: "You are an ArcGIS map help agent.",
|
|
28
|
-
runtimeContextLoader:
|
|
28
|
+
runtimeContextLoader: p
|
|
29
29
|
});
|
|
30
30
|
export {
|
|
31
31
|
m as HelpAgent
|
|
@@ -1,30 +1,47 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
-
import { z as
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
|
|
2
|
+
import { z as s } from "zod";
|
|
3
|
+
import p from "@arcgis/core/geometry/Polygon.js";
|
|
4
|
+
import { tool as f } from "@langchain/core/tools";
|
|
5
|
+
import { f as w } from "../../../../chunks/fetchAgentContext.js";
|
|
6
|
+
async function g(o, t) {
|
|
6
7
|
const e = t.map.bookmarks;
|
|
7
8
|
if (!e || e.length === 0)
|
|
8
9
|
throw new Error("No bookmarks found in the map.");
|
|
9
|
-
const
|
|
10
|
-
if (!n)
|
|
11
|
-
throw new Error(`Bookmark with name "${o}" not found.`);
|
|
12
|
-
const a = n.viewpoint;
|
|
10
|
+
const a = e.find((h) => h.name === o);
|
|
13
11
|
if (!a)
|
|
12
|
+
throw new Error(`Bookmark with name "${o}" not found.`);
|
|
13
|
+
const n = a.viewpoint;
|
|
14
|
+
if (!n)
|
|
14
15
|
throw new Error(`Bookmark with name "${o}" does not have a valid viewpoint.`);
|
|
15
|
-
|
|
16
|
+
const i = n.targetGeometry?.extent;
|
|
17
|
+
if (!i)
|
|
18
|
+
throw new Error(`Bookmark with name "${o}" does not have a valid target geometry.`);
|
|
19
|
+
const c = p.fromExtent(i);
|
|
20
|
+
await t.goTo(n);
|
|
21
|
+
const m = `Navigated to bookmark: ${o}`, k = {
|
|
22
|
+
value: m,
|
|
23
|
+
sharedResourceAdditions: [
|
|
24
|
+
{
|
|
25
|
+
kind: "polygon",
|
|
26
|
+
description: `Bookmark: ${o}`,
|
|
27
|
+
payload: c.toJSON()
|
|
28
|
+
}
|
|
29
|
+
]
|
|
30
|
+
};
|
|
31
|
+
return [m, k];
|
|
16
32
|
}
|
|
17
|
-
async function
|
|
18
|
-
const { mapView: r } =
|
|
19
|
-
return await
|
|
33
|
+
async function d({ bookmarkName: o }, t) {
|
|
34
|
+
const { mapView: r } = w(t, ["mapView"]);
|
|
35
|
+
return await g(o, r);
|
|
20
36
|
}
|
|
21
|
-
const
|
|
22
|
-
bookmarkName:
|
|
23
|
-
}),
|
|
37
|
+
const v = s.object({
|
|
38
|
+
bookmarkName: s.string().describe("The name of the bookmark to navigate to.")
|
|
39
|
+
}), T = f(d, {
|
|
24
40
|
name: "goToBookmark",
|
|
25
41
|
description: "Go to the extent of the bookmark with the given name.",
|
|
26
|
-
schema:
|
|
42
|
+
schema: v,
|
|
43
|
+
responseFormat: "content-and-artifact"
|
|
27
44
|
});
|
|
28
45
|
export {
|
|
29
|
-
|
|
46
|
+
T as goToBookmarkTool
|
|
30
47
|
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
+
import q from"./CWZG7DML.js";import{a as p,c as m}from"./NYFL2F5L.js";import"./YD5LVM7V.js";import o from"./AOT3PM2Q.js";import k from"./YGSDJ4V3.js";import j from"./M52LKZN7.js";import i from"./UXDRYDOD.js";import h from"./2H32MDP2.js";import"./OPQCY33W.js";import"./QAVDW7A7.js";import g from"./YSEHJQ4L.js";import f from"./CV5YAJMD.js";import"./OKDXM5D4.js";import e from"./UP7RW5K2.js";import"./M5UMOOL2.js";import"./H6J65TWL.js";import"./XBWGOD6I.js";import d from"./J3T5HB77.js";import"./AGDGDULE.js";import"./FIZMK7GS.js";import"./LMAIOLS2.js";import"./7OQK2F7O.js";import c from"./Y3ZKMD47.js";import b from"./BMVPOFHU.js";import"./QBZP6XOE.js";import"./3COVQI26.js";import"./CETIZ4IQ.js";import"./PR4VMSKD.js";import"./X3YFCWQZ.js";import"./2JD3G7IW.js";import"./LDDP7NSY.js";import"./WHIWOYHN.js";import{C as n,x as a}from"./NAVK5JJ2.js";import"./OUMTV5H5.js";import{a as l}from"./I2RQZAFF.js";import"./H653UVNH.js";import"./GS5JDPZH.js";import"./2WY5MPMY.js";import"./S6OUM5X2.js";import"./XLHYQNAM.js";import"./7GDMXAF5.js";import"./5XZ5VL42.js";import"./C3VLDYS2.js";import"./A4ZVCRVF.js";import"./N2GN5WOI.js";import"./272R36XK.js";import"./5PV2GUZW.js";export default $arcgis.t(([])=>{var h=(t,i)=>{let d=Array.from(t?.values()??[]).map(({fieldRegistry:s,layerItem:r})=>{let e=Array.from(s.values(),({name:u})=>u);return{title:r.title,description:r.description,fields:e.slice(0,10),additionalFieldCount:Math.max(e.length-10,0)}}),g=(i?.list()??[]).map(({agent:{description:s,id:r,name:e}})=>({id:r,name:e,description:s}));return JSON.stringify({layers:d,agents:g},null,2)},f=({config:t})=>{let i=t?.configurable?.services;return h(i?.layersAndFieldsRegistry,i?.agentRegistry)},y=[async()=>(await import("./MNMCIS4E.js")).default],c=l({id:"help",name:"Help Agent",description:"Answers questions about the map, its layers, and fields in those layers, including listing all or matching layers by title or description and fields by name, alias, type, or description. Explains assistant capabilities and redirects unsupported map actions or unrelated questions to map-related help.",skillLoaders:y,modelTier:"default",systemPrompt:"You are an ArcGIS map help agent.",runtimeContextLoader:f});var o=class extends a{constructor(){super(...arguments),this.agent=c}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=p(this,"arcgis-assistant-help-agent"),this.#i=m(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};n("arcgis-assistant-help-agent",o);return o},"intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",b,c,d,e,f,g,h,i,j,k,o,q)
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as U}from"./5INBG23U.js";import{a as j}from"./7JIXXYZR.js";import{b as Z}from"./ZUKM4DGB.js";import{b as pe}from"./AGDGDULE.js";import"./FIZMK7GS.js";import a from"./TOUYGIGK.js";import{a as I,b as R}from"./W36IUEUB.js";import"./SUMXIUIS.js";import"./PR4VMSKD.js";import{a as he}from"./TFXK2POV.js";import{a as F}from"./2JD3G7IW.js";import"./LDDP7NSY.js";import{b as K}from"./WHIWOYHN.js";import{A as C,C as J,g as B,h as y,l as V,m as G,o as w,v as P,w as M,x as Q}from"./NAVK5JJ2.js";import{b as q}from"./OUMTV5H5.js";import"./GS5JDPZH.js";import{a as b}from"./2WY5MPMY.js";import{c as de,d as ue,e as ge}from"./S6OUM5X2.js";import{a as A,b as oe,c as le,d as ce}from"./XLHYQNAM.js";import{Ea as ae,M as ie,S as x,a as Y,b as ee,y as te}from"./7GDMXAF5.js";import{c as ne}from"./5XZ5VL42.js";import"./C3VLDYS2.js";import"./A4ZVCRVF.js";import{N as p}from"./N2GN5WOI.js";import{La as re,fa as O,ra as se}from"./272R36XK.js";import"./5PV2GUZW.js";export default $arcgis.t(([vt,{whenOnce:Et,watch:_t,when:kt},xt,Me,Te,Ee,De,Le,It,{property:k,subclass:Rt},ke,{b:X}])=>{var Re=(t,e,s)=>{let r=t[e];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((n,i)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(i.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==s?". Note that variables only represent file names one level deep.":""))))})},me=async t=>(await Re(Object.assign({"./field_descriptions_prompt.md":()=>import("./2OW3DCUT.js"),"./intent_prompt.md":()=>import("./G4L7RUTK.js"),"./layer_descriptions_prompt.md":()=>import("./XVWSIDZV.js")}),`./${t}.md`,2)).default,Se="0.1",$=1536,Ce="openai",Ae=K.default,$e=`Name: {name}
|
|
3
3
|
Title: {title}
|
|
4
4
|
Description: {description}`,Pe=`Name: {name}
|
|
5
5
|
Alias: {alias}
|
|
6
|
-
Description: {description}`,ye=p.object({schemaVersion:p.literal(Se),modified:p.number().int().nonnegative(),embeddings:p.object({modelProvider:p.literal(Ce),model:p.literal(Ae),dimensions:p.literal($),templates:p.object({layer:p.string().default($e),field:p.string().default(Pe)})}),layers:p.array(p.object({id:p.string().min(1),name:p.string().min(1),title:p.string().catch(""),description:p.string().catch(""),vector:p.array(p.number()).length($,{message:`Layer vector must be exactly ${$} dimensions`}),fields:p.array(p.object({name:p.string().min(1),alias:p.string().catch(""),description:p.string().catch(""),vector:p.array(p.number()).length($,{message:`Field vector must be exactly ${$} dimensions`})}))})).default([])});var qe=async t=>{let e=await
|
|
7
|
-
[truncated]`:d;o.push(new F(l))}return{...t,stepCount:t.stepCount+1,lastExecutedAgent:i.agent.id,requiresFollowUp:a.status==="failed"?!0:t.requiresFollowUp,finalOutputMessage:d??"",agentExecutionContext:{...t.agentExecutionContext,messages:o,priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:i.agent.id,assignedTask:t.agentExecutionContext.assignedTask,summary:a?.summary||r.noSummaryProvided,status:a?.status||"unknown"}],sharedState:ze({previousSharedState:t.agentExecutionContext.sharedState,patch:a.sharedStatePatch,agentId:i.agent.id}),sharedResources:Je({previousSharedResources:t.agentExecutionContext.sharedResources,additions:a.sharedResourceAdditions,agentId:i.agent.id})}}},Ye=async t=>{let{agent:e,messages:s,config:r}=t;return{structuredResponse:(await e.invoke({messages:s},r)).structuredResponse}},et=p.object({id:p.string().min(1),name:p.string().min(1),description:p.string().min(1)});p.array(et);var ve=t=>JSON.stringify(t,null,2),tt=t=>{let e=t.map(r=>r.id),s=p.enum(e);return p.object({intent:s.nullable(),assignedTask:p.string().nullable(),requiresFollowUp:p.boolean()})},st=async(t,e)=>{let s=N(e),r=await R({path:"./assets/orchestrator/t9n",locale:I(e)});if(e?.signal?.aborted)return await b({text:r.runCancelled},e),{...t,currentIntent:"none",finalOutputMessage:r.runCancelled,requiresFollowUp:!1};try{await b({text:r.routingToAgent},e);let n=s.services.agentRegistry?.list()??[],i=n.map(({agent:E})=>({id:E.id,name:E.name,description:E.description}));if(!i.length)return await b({text:r.noAgentsRegisteredTrace},e),{...t,currentIntent:"none",finalOutputMessage:r.noAgentsRegisteredMessage};let c=await me("intent_prompt"),a=ve(i),d=tt(i),o={registeredAgents:a,priorSteps:ve(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},l=await ne.fromTemplate(c).format(o),u=de({model:await U({modelTier:"fast",config:e}),tools:[],systemPrompt:l,responseFormat:d,middleware:[ue({model:await U({modelTier:"fast",config:e}),trigger:{tokens:4e3},keep:{messages:6}}),ge({runLimit:2})]}),{structuredResponse:g}=await Ye({agent:u,messages:t.agentExecutionContext.messages,config:e}),h=d.parse(g??{intent:null,assignedTask:null,requiresFollowUp:!1}),m=h.intent??"none",f={...t,currentIntent:m,requiresFollowUp:h.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:h.assignedTask??""}};if(m==="none"){let E=r.noMatchingAgentMessage.replace("{agentNames}",n.map(({agent:S})=>S.name).join(", "));return await b({text:r.noMatchingAgentTrace},e),{...t,currentIntent:m,requiresFollowUp:!1,finalOutputMessage:E,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new F(E)],priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:"no-intent-router",assignedTask:t.agentExecutionContext.userRequest,summary:"No matching agent found; asked user to rephrase.",status:"failed"}]}}}return await b({text:r.agentPicked.replace("{intent}",m).replace("{assignedTask}",h.assignedTask??"").replace("{requiresFollowUp}",String(h.requiresFollowUp))},e),f}catch(n){throw await b({text:r.intentDetectionErrorTrace},e),new Error(r.intentDetectionError.replace("{error}",n instanceof Error?n.message:String(n)))}},rt=async(t,e)=>{let s=await R({path:"./assets/orchestrator/t9n",locale:I(e)});if(t.routing.mode!=="direct")throw new Error(s.directAgentAssignmentRequiresDirectRouting);return await b({text:s.directRouteToAgent.replace("{agentId}",t.routing.agentId)},e),{...t,currentIntent:t.routing.agentId,requiresFollowUp:!1,agentExecutionContext:{...t.agentExecutionContext,assignedTask:t.agentExecutionContext.userRequest}}},nt=3,it=t=>t.routing.mode==="direct"?"assignDirectAgent":"intentLLM",at=t=>t.routing.mode==="direct"||t.stepCount>=nt||!t.requiresFollowUp?"exit":"intentLLM",ot=()=>new ae(Ue).addNode("ingestInput",We).addNode("assignDirectAgent",rt).addNode("intentLLM",st).addNode("executeRegisteredAgent",Xe).addNode("exit",Ne).addEdge(Y,"ingestInput").addConditionalEdges("ingestInput",it).addEdge("assignDirectAgent","executeRegisteredAgent").addConditionalEdges("intentLLM",t=>t.currentIntent==="none"||t.currentIntent===t.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",at).addEdge("exit",ee),lt=(t,e)=>{let s=t.output?.usage_metadata??e.usage_metadata,r=t.output?.llmOutput?.tokenUsage,n=s?.input_tokens??r?.promptTokens,i=s?.output_tokens??r?.completionTokens,c=s?.total_tokens??r?.totalTokens;if(n===void 0||i===void 0||c===void 0)return;let a=s?.input_token_details?.cache_read,d=s?.input_token_details?.cache_creation,o=s?.output_token_details?.reasoning;return{input:n,output:i,total:c,...a!==void 0&&{cacheRead:a},...d!==void 0&&{cacheWrite:d},...o!==void 0&&{reasoning:o}}},ct=(t,e,s,r)=>{switch(t){case"chat_model":case"llm":return"model";case"tool":case"retriever":return t;case"chain":return!r||e==="LangGraph"?"workflow":s===e?"node":"chain";default:return}},dt=t=>{if(t instanceof Error)return{message:t.message,name:t.name};let e=t,s=typeof e?.message=="string"?e.message:String(t??"Unknown runtime error"),r=typeof e?.name=="string"?e.name:void 0;return{message:s,...r&&{name:r}}},ut=({event:t,runId:e,parentSpanId:s,timestamp:r})=>{let n=/^on_(.+)_(start|end|error)$/u.exec(t.event);if(!n)return;let[,i,c]=n,a=t.metadata??{},d=a.langgraph_node,o=ct(i,t.name,d,s);if(!o)return;let l=a.agentId,u=a.model??a.ls_model_name,g=t.data,h=c==="end"&&o==="model"?lt(g,a):void 0,m=t.tags?.includes("langsmith:hidden")||d==="__start__",f={...u&&{model:u},...h&&{tokenUsage:h},...m&&{internal:!0}},E={id:t.run_id,...s&&{parentId:s},label:t.name,type:o,...Object.keys(f).length&&{metadata:f}},S={runId:e,timestamp:r,type:"runtime",...l&&{agentId:l}};switch(c){case"start":return{...S,phase:"started",span:{...E,...g?.input!==void 0&&{input:g.input}}};case"end":return{...S,phase:"completed",span:{...E,...g?.output!==void 0&&{output:g.output}}};case"error":return{...S,phase:"failed",span:{...E,error:dt(g?.error)}};default:return}},T=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:s}=e;if(this.agentRegistry.has(s.id))throw new Error(`Duplicate agent id: ${s.id}`);this.agentRegistry.set(s.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},W=class{constructor(e,s){this.graph=e,this.config={...s}}async waitForUser(){return await new Promise((e,s)=>{this.resolveWait=e,this.rejectWait=s})}handle(e,s){try{let r={agentId:e.agentId,id:e.id,payload:s},n=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:r},subgraphs:!0,version:"v2"});this.resolveWait?.(n)}catch(r){this.rejectWait?.(r)}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)}},_e=async(t,e)=>{let s=e.get(t);if(s)return s;let r=await he([t]);return e.set(t,r[0]),r[0]};async function gt(t,e,s,r){let n=`req-${Date.now()}`,i={type:"layerSearch",precomputedEmbedding:r?await _e(t,r):void 0,requestId:n,minScore:s};return await new Promise(c=>{let a=d=>{d.data.requestId===n&&c(d.data.results)};e.addEventListener("message",a,{once:!0}),e.postMessage(i)})}function ht(t){let{worker:e}=t;return{async searchLayers({text:s,minScore:r,embeddingCache:n}){return await gt(s,e,r,n)}}}var pt=async({combinedQuery:t,layerIds:e,embeddingsWorker:s,minScore:r,topResults:n,embeddingCache:i})=>{let c=`req-${Date.now()}`,a=i?await _e(t,i):void 0,d={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:a,requestId:c,minScore:r,topResults:n};return await new Promise(o=>{let l=u=>{if(u.data.requestId!==c)return;let g=u.data.results.map(({layerId:h,results:m})=>({layerId:h,results:m}));o(g)};s.addEventListener("message",l,{once:!0}),s.postMessage(d)})};function mt(t){let{worker:e}=t;return{async searchFields({text:s,layerIds:r,minScore:n,topResults:i,embeddingCache:c}){return await pt({combinedQuery:s,layerIds:r,embeddingsWorker:e,minScore:n,topResults:i,embeddingCache:c})}}}var yt=t=>{let e=ye.safeParse(t);if(!e.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return e.data},ft=(t,e)=>{let s=new Map,r=new Map;if(e.allLayers.forEach(n=>{n instanceof De&&r.set(n.id,n)}),t.length!==r.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let n of t){let i=r.get(n.id);if(!i)throw new Error(`Layer with ID ${n.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(n.fields.length!==i.fields.length)throw new Error(`Field count mismatch for layer ID ${n.id} during registry restoration. Regenerate embeddings.`);let c={name:n.name,title:n.title,description:n.description},a=new Map;for(let d of n.fields){let o=i.fieldsIndex.get(d.name);if(!o)throw new Error(`Field with name ${d.name} not found in the original layer ${n.id} during registry restoration. Regenerate embeddings.`);a.set(d.name,{name:d.name,alias:i.getFieldAlias(d.name)??d.alias,description:d.description,type:o.type||"unknown",valueType:o.valueType||"unknown",domain:i.getFieldDomain(d.name)??void 0})}s.set(n.id,{layerItem:c,fieldRegistry:a})}return s},bt=async t=>{try{return(await Le(t,{responseType:"json"})).data}catch(e){throw new Error(`Failed to fetch data from ${t}: ${String(e)}`)}},wt=async t=>{let e=t.map;if(!e?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:s}=await e.portalItem.fetchResources(),r=s.find(i=>i.resource.path==="embeddings-v01.json");if(!r?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let n=await bt(r.resource.url);return yt(n)},D=class t{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.sharedResources=[],this.agentRegistry=new T,this.activeRunId="",this.cancelledRunIds=new Set,this.parentRunIds=new Map,this.activeRuntimeSpans=new Map,this.runtimeEventsEnabled=!1,this.streamEpoch=0}static async init(e){let s=new t;s.runtimeEventsEnabled=e.runtimeEventsEnabled??!1;try{if(e.view?.map){await Ee.whenOnce(()=>e.view.ready);let r=await wt(e.view),n=ft(r.layers,e.view.map);s.layersAndFieldsRegistry=n,s.embeddingsWorker=await qe(r)}return e.agents?.forEach(r=>{s.agentRegistry.register(r)}),s.orchestratorReady=!0,s}catch(r){throw console.error("Orchestrator initialization failed:",r),r}}async*ask(e,s={}){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");let r=this.createRequestAgentRegistry(s);if(!r.list().length)throw new Error("Orchestrator has no agents selected for this request.");if(++this.streamEpoch,!e.trim()&&!s.inputParts?.length)return;if(!e.trim()&&s.routing!=="direct")throw new Error("Requests containing only structured input require direct agent routing.");let n=q();this.parentRunIds.clear(),this.activeRuntimeSpans.clear(),this.activeRunId=n,this.activeAbortController=new AbortController,this.graph||(this.graph=ot().compile({checkpointer:new ie}));let i=this.embeddingsWorker?ht({worker:this.embeddingsWorker}):void 0,c=this.embeddingsWorker?mt({worker:this.embeddingsWorker}):void 0,a=new Map,d=s.routing==="direct"?{mode:"direct",agentId:s.agentId}:{mode:"auto"},o={thread_id:n,locale:s.locale??"en",hitlResponse:null,services:{layerSearch:i,fieldSearch:c,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:r,embeddingCache:a}},l={version:"v2",streamMode:"custom",signal:this.activeAbortController.signal,...this.runtimeEventsEnabled&&{callbacks:[this.createHierarchyCallback()]},configurable:o,subgraphs:!0},u=this.graph?.streamEvents({routing:d,agentExecutionContext:{userRequest:e,inputParts:[...s.inputParts??[]],messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState,sharedResources:this.sharedResources}},l),g=++this.streamEpoch;if(yield*this.pipeStream(u,g,n),this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}for(;;){if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}let m=(await this.graph.getState(l,{subgraphs:!0})).tasks.find(f=>f.interrupts.length>0)?.interrupts[0]?.value;if(!m)break;this.currentInterrupt=m,this.interruptHandler=new W(this.graph,l),yield*this.closeActiveRuntimeSpans(n,"interrupted"),yield{runId:n,timestamp:Date.now(),type:"interrupt",interrupt:m};try{let f=await this.interruptHandler.waitForUser(),E=++this.streamEpoch;yield*this.pipeStream(f,E,n)}catch(f){if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}if(f){yield{runId:n,timestamp:Date.now(),type:"error",error:{message:f?.message}};return}}}if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}let h=(await this.graph.getState(l,{subgraphs:!0})).values;if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}this.chatHistory=h.agentExecutionContext.messages.length?h.agentExecutionContext.messages:this.chatHistory,this.priorSteps=h.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=h.agentExecutionContext.sharedState??{},this.sharedResources=h.agentExecutionContext.sharedResources??[],yield{runId:n,timestamp:Date.now(),type:"completed",result:{content:h.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.sharedResources=[]}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,s,r){try{for await(let n of e){if(this.isRunCancelled(r)||s!==this.streamEpoch)break;if(this.runtimeEventsEnabled){let i=ut({event:n,runId:r,parentSpanId:this.parentRunIds.get(n.run_id),timestamp:Date.now()});i&&(i.phase==="started"?this.activeRuntimeSpans.set(i.span.id,i):this.activeRuntimeSpans.delete(i.span.id),yield i)}n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:r,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:r,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}catch(n){if(!this.isRunCancelled(r))throw n}}*createCancellationEvents(e){yield*this.closeActiveRuntimeSpans(e,"cancelled"),yield{runId:e,timestamp:Date.now(),type:"cancelled",reason:"user"}}*closeActiveRuntimeSpans(e,s){let r=Date.now(),n=[...this.activeRuntimeSpans.values()].reverse();this.activeRuntimeSpans.clear();for(let i of n){let{input:c,...a}=i.span;yield{type:"runtime",phase:s,runId:e,timestamp:r,...i.agentId&&{agentId:i.agentId},span:a}}}createHierarchyCallback(){let e=(s,r)=>{r&&this.parentRunIds.set(s,r)};return re.fromMethods({handleLLMStart:(s,r,n,i)=>e(n,i),handleChatModelStart:(s,r,n,i)=>e(n,i),handleChainStart:(s,r,n,i)=>e(n,i),handleToolStart:(s,r,n,i)=>e(n,i),handleRetrieverStart:(s,r,n,i)=>e(n,i)})}isRunCancelled(e){return this.cancelledRunIds.has(e)}createRequestAgentRegistry(e){let s=e.routing==="direct"?[e.agentId]:e.agentIds,r=s?s.map(i=>{let c=this.agentRegistry.get(i);if(!c)throw new Error(`Agent is not registered: ${i}`);return c}):this.agentRegistry.list(),n=new T;return r.forEach(i=>n.register(i)),n}dispose(){this.sharedResources=[],this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};var St=B`: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)}`;function H(t){return t.trim()?O.lexer(t).filter(e=>e.type!=="space").map(e=>O.parser([e])):[]}var L=class{constructor(){this._stableParts=[],this._stableText="",this._rawText=""}push(e){return this._rawText+=e,this._advanceStableBoundary(),this.getParts()}finalize(){let e=this._rawText.slice(this._stableText.length);return e.trim()&&(this._stableParts.push(...H(e)),this._stableText=this._rawText),this._stableParts}getParts(){let e=this._trimIncompleteTail(this._rawText.slice(this._stableText.length)),s=e.trim()?H(e):[];return[...this._stableParts,...s]}reset(){this._stableParts=[],this._stableText="",this._rawText=""}_advanceStableBoundary(){let e=this._rawText.slice(this._stableText.length),s=this._lastSafeBoundary(e);if(s<=0)return;let r=e.slice(0,s);this._stableParts.push(...H(r)),this._stableText+=r}_lastSafeBoundary(e){let s=e.split(`
|
|
8
|
-
`),r=!1,n=0,i=0;for(let c of s)/^\s*(```|~~~)/u.test(c)&&(r=!r),i+=c.length+1,c.trim()===""&&!r&&(n=i);return n<e.length?n:0}_trimIncompleteTail(e){let s=e.lastIndexOf("<");if(s!==-1&&!e.includes(">",s))return e.slice(0,s);let r=this._earliestUnclosedTag(e);if(r!==-1)return e.slice(0,r);let n=e.lastIndexOf("[");if(n!==-1){let i=e.slice(n);if(!/\[[^\]]*\]\([^)]*\)/u.test(i))return e.slice(0,n)}return e}_earliestUnclosedTag(e){let s=new Set(["br","img","hr","input","meta","link","area","base","col","embed","source","track","wbr"]),r=/<(\/?)([a-zA-Z][\w-]*)\b[^>]*?(\/?)>/gu,n=[];for(let i=r.exec(e);i;i=r.exec(e)){let[,c,a,d]=i,o=a.toLowerCase();if(!(s.has(o)||d==="/"))if(c==="/"){for(let l=n.length-1;l>=0;l--)if(n[l].name===o){n.splice(l);break}}else n.push({name:o,index:i.index})}return n.length?n[0].index:-1}};function Ct(t){let e=new L;return e.push(t),e.finalize()}var At=async t=>await new Promise(e=>setTimeout(e,t));async function*$t(t,{chunkSize:e=15,delay:s=50}={}){let r=new L;for(let n=0;n<t.length;n+=e)yield r.push(t.slice(n,n+e)),await At(s);yield r.finalize()}var Pt=Object.defineProperty,Mt=Object.getOwnPropertyDescriptor,_=(t,e,s,r)=>{for(var n=r>1?void 0:r?Mt(e,s):e,i=t.length-1,c;i>=0;i--)(c=t[i])&&(n=(r?c(e,s,n):c(n))||n);return r&&n&&Pt(e,s,n),n},xe=t=>!t||typeof t!="object"?!1:t.name==="AbortError";async function*Ie(t,e,s,r,n=!1){if(n){if(r?.aborted){yield{type:"cancelled",log:s,runId:e};return}yield{type:"block-data",blockType:"text",data:{parts:Ct(t)},runId:e};return}for await(let i of $t(t)){if(r?.aborted){yield{type:"cancelled",log:s,runId:e};return}yield{type:"block-data",blockType:"text",data:{parts:i},runId:e}}}var v=class extends It{constructor(t){super(t),this.view=null,this.streamingDisabled=!1,this.runtimeEventsEnabled=!1,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 Et(()=>!this.view.updating),this._set("orchestrator",await D.init({agents:[...this.agents],runtimeEventsEnabled:this.runtimeEventsEnabled,view:this.view??void 0})),this.addHandles([_t(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(t,e,s){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let r=[],n,i="pending";try{let c=this.orchestrator.ask(t,e);for await(let a of c)switch(i=a.runId,a.type){case"runtime":{yield{type:"runtime",event:a,runId:i};break}case"trace":{this._set("processingStep",a.data.text),r.push(a.data.text);break}case"completed":{this._set("processing",!1),this._set("processingStep","");let d=a.result,o=!!d.content.length,l=!!n?.length;if(!o&&!l){yield{type:"completed",error:"No response received.",log:r,runId:i};return}let u=d.content;if(yield{type:"block-start",blockType:"text",runId:i},yield*Ie(u,i,r,s,this.streamingDisabled),yield{type:"block-end",blockType:"text",runId:i},l)for(let g of n){if(s?.aborted){yield{type:"cancelled",log:r,runId:i};return}let{type:h,data:m}=g;if(yield{type:"block-start",blockType:h,runId:i},h==="text"){let f=typeof m?.content=="string"?m.content:"";yield*Ie(f,i,r,s,this.streamingDisabled)}else yield{type:"block-data",blockType:h,data:m,runId:i};yield{type:"block-end",blockType:h,runId:i}}yield{type:"completed",response:u,blocks:n,log:r,runId:i};return}case"ux-suggestion":{let d=a.suggestion;n=n?[...n,d]:[d];break}case"interrupt":{let{kind:d,message:o,metadata:l}=a.interrupt,u=Array.isArray(l)?l.filter(h=>typeof h=="string"):[],g=(()=>{switch(d){case"booleanChoice":return{type:"boolean-choice",message:o,options:u};case"singleSelection":return{type:"single-select",message:o,options:u};case"multipleSelection":return{type:"multi-select",message:o,options:u};case"textInput":return{type:"text-input",message:o};default:return{type:d,message:o,options:u}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:g,runId:i};break}case"cancelled":{yield{type:"cancelled",log:r,runId:i};return}case"error":{if(s?.aborted||xe(a.error)){yield{type:"cancelled",log:r,runId:i};return}yield{type:"completed",error:a.error.message,log:r,runId:i};return}default:{console.warn("Unknown event type:",a);break}}}catch(c){if(s?.aborted||xe(c)){yield{type:"cancelled",log:r,runId:i};return}console.warn("Error during message processing:",c),yield{type:"completed",error:this.messages.messageProcessingErrorMessage,log:r,runId:"error"};return}finally{this._set("processing",!1)}}cancel(){this.orchestrator?.cancel()}};_([k({readOnly:!0})],v.prototype,"orchestrator",2);_([k()],v.prototype,"agents",2);_([k()],v.prototype,"portal",2);_([k()],v.prototype,"view",2);_([k()],v.prototype,"messages",2);_([k()],v.prototype,"streamingDisabled",2);_([k()],v.prototype,"runtimeEventsEnabled",2);_([k({readOnly:!0})],v.prototype,"loading",2);_([k({readOnly:!0})],v.prototype,"processing",2);_([k({readOnly:!0})],v.prototype,"processingStep",2);v=_([Rt("OrchestratorController")],v);var Tt="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",Dt="Embeddings not found for this web map.",Lt="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",z=class extends Q{constructor(){super(...arguments),this._messages=Z({blocking:!0}),this.#e=P(),this.#o=P(),this.#r=P(),this.#t=null,this.#n=new Map,this.#s=xt.getDefault(),this.#i=e=>{e.stopPropagation(),this.cancelInterrupt()},this.#a=e=>{e.stopPropagation();let s=e.detail;this.submitInterrupt(s)},this.#l=e=>{if(e.stopPropagation(),e.defaultPrevented)return;let s=e.detail,r=typeof s=="string"?s:s.prompt,n=typeof s=="string"?void 0:{displayText:s.displayText,parts:s.parts};if(!this.#y(r,n?.parts??[])){e.preventDefault();return}if(this.arcgisSubmit.emit(s).defaultPrevented){e.preventDefault();return}this.keepSuggestedPrompts||(this.suggestedPrompts=[]),this._inputValue="",this.submitMessage(r,n)},this.#c=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 s=e.detail;this.arcgisFeedback.emit(s)},this.#u=e=>{e.stopPropagation();let s=e.detail;this._inputValue=s.prompt,this.arcgisPromptSelect.emit(s)},this.#p=e=>{this.arcgisSlottableRequest.emit(e.detail)},this._orchestratorController=null,this._interrupt=null,this._interruptDetails=[],this._error=null,this._submissionError=null,this._inputValue="",this._isAnswering=!1,this._canceling=!1,this.messages=new vt([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.streamingDisabled=!1,this.runtimeEventsEnabled=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.assistantAvatarEnabled=!1,this.userAvatarEnabled=!1,this.arcgisCancel=w(),this.arcgisError=w(),this.arcgisFeedback=w(),this.arcgisInterrupt=w(),this.arcgisInterruptCancel=w(),this.arcgisInterruptSubmit=w(),this.arcgisPromptSelect=w(),this.arcgisReady=w(),this.arcgisResponse=w(),this.arcgisRuntime=w({bubbles:!1,composed:!1}),this.arcgisSlottableRequest=w({bubbles:!1,composed:!1}),this.arcgisSubmit=w({cancelable:!0})}static{this.properties={_orchestratorController:16,_interrupt:16,_interruptDetails:16,_error:16,_submissionError:16,_inputValue:16,_isAnswering:16,_signedInUserId:16,_canceling:16,_isSignedIn:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,alwaysUseAgentId:1,allowedAgentIds:[1,{type:Array}],commandProvider:0,entityProviders:0,suggestedPrompts:[1,{type:Array}],feedbackEnabled:5,keepSuggestedPrompts:5,streamingDisabled:5,runtimeEventsEnabled:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5,assistantAvatarEnabled:5,userAvatarEnabled:5}}static{this.styles=St}#e;#o;#r;#t;#n;#s;#i;#a;#l;#c;#d;#u;#p;get _isSignedIn(){return!!this.#s?.user||!!this._signedInUserId}get _user(){return this.#s?.user?.fullName||this.#s?.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}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}register(e){this.#n.set(e.agent.id,e),this._orchestratorController&&this.#g()}submitInterrupt(e){this.arcgisInterruptSubmit.emit(e),this._interrupt&&(this._interruptDetails=[...this._interruptDetails,{interrupt:this._interrupt,response:e}]),this.orchestrator?.resumeInterrupt(e),this._interrupt=null}async submitMessage(e,s){let r=e.trim(),n=s?.parts??[];if(!r&&!n.length||!this.#y(r,n)||(this.messages.push({id:Date.now().toString(),role:"user",content:s?.displayText?.trim()||r||n.map(o=>this.#f(o)).join(" "),parts:n}),!this._orchestratorController))return;this.#t=new AbortController,this._orchestratorController.streamingDisabled=this.streamingDisabled;let i=this.#m(n),c=this._messages._t9nLocale||"en",a={...s?.parts?{inputParts:s.parts}:{},...i?{routing:"direct",agentId:i}:{routing:"auto",agentIds:this.allowedAgentIds},locale:c},d=this._orchestratorController.ask(r,a,this.#t?.signal);for await(let o of d){let l=o.runId,u=this.messages.at(-1);switch(o.type){case"runtime":this.arcgisRuntime.emit(o.event);break;case"block-start":{this._isAnswering=!0;let g={type:o.blockType,isPending:!0};if(u?.role==="assistant"&&u.id===l){let h=[...u.blocks??[],g];this.messages.splice(-1,1,{...u,blocks:h})}else this.messages.push({role:"assistant",blocks:[g],id:l,isStreaming:!0,interrupts:this._interruptDetails}),this._interruptDetails=[];break}case"block-data":{if(u?.role!=="assistant"||u?.id!==l)break;let g=[...u.blocks??[]],h=g[g.length-1],{blockType:m,data:f}=o;if(h?.type!==m||!h.isPending)break;m==="text"?g[g.length-1]={...h,data:{...h.data,parts:f?.parts}}:g[g.length-1]={...h,data:{...h.data,...f??{}}},this.messages.splice(-1,1,{...u,blocks:g});break}case"block-end":{if(u?.role!=="assistant"||u?.id!==l)break;let g=[...u.blocks??[]],h=g[g.length-1];if(h?.type!==o.blockType||!h.isPending)break;let m=h;g[g.length-1]={...m,data:{...m.data},isPending:!1},this.messages.splice(-1,1,{...u,blocks:g});break}case"completed":o.error?(this.messages.push({role:"assistant",log:o.log,error:o.error,id:l,interrupts:this._interruptDetails}),this._interruptDetails=[]):u?.role==="assistant"&&u.id===l&&this.messages.splice(-1,1,{...u,content:o.response,blocks:u.blocks?.map(g=>({...g,data:{...g.data},isPending:!1}))??[],isStreaming:!1,log:o.log}),this._isAnswering=!1,this.#t=null,this._canceling=!1;break;case"interrupt":this._interrupt={...o.payload,id:l},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":u?.role==="assistant"&&u.id===l?this.messages.splice(-1,1,{...u,blocks:u.blocks?.filter(g=>g.type==="text"||!g.isPending)??[],isStreaming:!1,log:o.log,error:`(${this._messages.stoppedByUserLabel})`}):(this.messages.push({role:"assistant",log:o.log,error:`(${this._messages.stoppedByUserLabel})`,id:l,interrupts:this._interruptDetails}),this._interruptDetails=[]),this._isAnswering=!1,this.#t=null,this._canceling=!1;break}}}unregister(e){this.#n.delete(e),this._orchestratorController&&this.#g()}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#e.value?.addEventListener("arcgisPromptSelect",this.#u),this.#e.value?.addEventListener("arcgisSubmit",this.#l),this.#e.value?.addEventListener("arcgisCancel",this.#c),this.#e.value?.addEventListener("arcgisFeedback",this.#d);let e=kt(()=>!!this._interrupt&&!!this.#r.value,()=>{let r=this.#r.value;r.removeEventListener("arcgisSubmit",this.#a),r.removeEventListener("arcgisCancel",this.#i),r.addEventListener("arcgisSubmit",this.#a,{once:!0}),r.addEventListener("arcgisCancel",this.#i,{once:!0})}),s=this.messages.on("after-add",r=>{let n=r.item;n.role==="assistant"&&(n.error||n.content)&&this.arcgisResponse.emit(n)});return queueMicrotask(()=>{this.#h()}),()=>{e.remove(),s.remove(),this.#e.value?.removeEventListener("arcgisPromptSelect",this.#u),this.#r.value?.removeEventListener("arcgisSubmit",this.#a),this.#r.value?.removeEventListener("arcgisCancel",this.#i),this.#e.value?.removeEventListener("arcgisSubmit",this.#l),this.#e.value?.removeEventListener("arcgisCancel",this.#c),this.#e.value?.removeEventListener("arcgisFeedback",this.#d),this._orchestratorController?.destroy(),this._orchestratorController=null}})}willUpdate(e){this.hasUpdated&&e.has("runtimeEventsEnabled")&&this._orchestratorController&&(this._orchestratorController.destroy(),this._orchestratorController=null,this.#h())}#f(e){return e.kind==="command"?`/${e.id}`:`${e.trigger}${e.id}`}#m(e){for(let s of e)if(s.kind==="command"&&s.agentId)return s.agentId;return this.alwaysUseAgentId}#y(e,s){let r=s.filter(n=>n.kind==="command").length>1;return this._submissionError=r?this._messages.multipleCommands:!e.trim()&&s.length>0&&!this.#m(s)?this._messages.partsOnlyRequiresAgent:null,this._submissionError?(this.arcgisError.emit(new Error(this._submissionError)),!1):!0}async#b(){await ke.checkSignInStatus(this.#s.url);let e=await this.#s.load();if(!e.helperServices?.aiAssistantServices?.url)throw new Error(this._messages.serviceUrlNotAvailableMessage);let s=!1,r=await e.fetchSettings();if(r.aiConfig?s=r.aiConfig.aiForOrg?.enabled===!0&&r.aiConfig.aiForOrg?.aiCapabilities?.aiAgents?.enabled===!0:s=r.aiAssistantsEnabled===!0,!s)throw new Error(this._messages.aiAssistantsNotEnabledMessage);if(!e.isPortal&&e?.user?.privileges?.includes("portal:user:useAIAssistants")!==!0)throw new Error(this._messages.userPrivilegesNotSufficientMessage)}async#g(){try{this._error=null;let e=pe(this.el,this.referenceElement);await e?.componentOnReady();let s=[...this.#n.values()];return s.length?(await this.#b(),this._orchestratorController?.destroy(),this._orchestratorController=new v({agents:s,portal:this.#s,runtimeEventsEnabled:this.runtimeEventsEnabled,streamingDisabled:this.streamingDisabled,view:e?.view,messages:this._messages}),await this._orchestratorController.load(),this.requestUpdate(),!0):(this._error=this._messages.noAgentsFoundMessage,!1)}catch(e){return this._error=e?.message??this._messages.orchestratorInitializationErrorMessage,G(this)(e),!1}}async#h(){await this.#g()?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))}_reset(){this._orchestratorController?.cancel(),this.#t?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._submissionError=null,this._inputValue="",this._signedInUserId=void 0}_renderEntryMessage(){return this._isSignedIn?this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:y`<calcite-notice open kind=brand closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:y`<slot name=entry-message></slot>`:this._renderSignInNotice()}_renderSignInNotice(){let e=this.#s;return y`<calcite-notice slot=entry-message open kind=brand icon width=full><div slot=message>${this._messages.signInRequiredMessage}</div>${e?y`<calcite-link slot=link @click=${async()=>{try{let s=await ke.getCredential(`${e.url}/sharing`);this._signedInUserId=s.userId,this._error=null,this.requestUpdate(),await this.#h()}catch(s){this._error=s?.message??this._messages.signInErrorMessage,this.arcgisError.emit(new Error(this._error)),V("error",this,"Error signing in:",{detail:{error:s}})}}} target=_blank title=${this._messages.signInToArcGISOnlineLabel??C}>${this._messages.signInLabel}</calcite-link>`:y`<div slot=link>${this._messages.noPortalInformationMessage}</div>`}</calcite-notice>`}_renderErrorNotice(){return this._error?y`<calcite-notice slot=entry-message open kind=brand icon width=full>${this._error===Tt?y`<div slot=message>${Dt}</div><calcite-link slot=link .href=${Lt} target=_blank title=${this._messages.learnAboutWebMapEmbeddingsLabel??C}>${this._messages.readMoreLabel}</calcite-link>`:y`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}render(){return y`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${M(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"?y`<arcgis-assistant-message .message=${e} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#p} .assistantAvatarEnabled=${this.assistantAvatarEnabled}>${e.blocks?.map((s,r)=>y`<slot name=${j(e.id,r)??C} slot=${j(e.id,r)??C}><arcgis-assistant-message-block .block=${s}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:y`<arcgis-assistant-user-message .message=${e} .user=${this._user} .userAvatarEnabled=${this.userAvatarEnabled}></arcgis-assistant-user-message>`)}</slot>${this._interrupt?y`<div slot=message-loading><div class="interrupt-waiting-message">${this._messages.waitingForUserInputMessage}</div></div>`:y`<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?y`<slot name=interrupt><arcgis-assistant-interrupt slot=content-bottom .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${M(this.#r)}></arcgis-assistant-interrupt></slot>`:this.suggestedPrompts?.length?y`<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()}${this._submissionError?y`<div role=alert>${this._submissionError}</div>`:null}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse||this._isAnswering} .commandProvider=${this.commandProvider} .entityProviders=${this.entityProviders} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} .disabled=${this._canceling||!this._isSignedIn||!!this._interrupt||!!this._error} ${M(this.#o)}><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.#o.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>`}};J("arcgis-assistant",z);return z},"core/Collection","core/reactiveUtils","portal/Portal","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","core/Accessor","core/accessorSupport/decorators","identity/IdentityManager",a)
|
|
6
|
+
Description: {description}`,ye=p.object({schemaVersion:p.literal(Se),modified:p.number().int().nonnegative(),embeddings:p.object({modelProvider:p.literal(Ce),model:p.literal(Ae),dimensions:p.literal($),templates:p.object({layer:p.string().default($e),field:p.string().default(Pe)})}),layers:p.array(p.object({id:p.string().min(1),name:p.string().min(1),title:p.string().catch(""),description:p.string().catch(""),vector:p.array(p.number()).length($,{message:`Layer vector must be exactly ${$} dimensions`}),fields:p.array(p.object({name:p.string().min(1),alias:p.string().catch(""),description:p.string().catch(""),vector:p.array(p.number()).length($,{message:`Field vector must be exactly ${$} dimensions`})}))})).default([])});var qe=async t=>{let e=await Oe(),s=await X("default"),r=Te.getDefault(),n=(await Me.getCredential(`${r.url}/sharing`)).token,i={type:"generateEmbeddings",webmapEmbeddings:t,auth:{apiUrl:s,token:n}};return e.postMessage(i),await new Promise((c,a)=>{let d=l=>{l.data==="completed"&&(e.removeEventListener("message",d),c())},o=l=>{e.removeEventListener("message",d),a(l instanceof Error?l:new Error("Embeddings worker error"))};e.addEventListener("message",d),e.addEventListener("error",o,{once:!0})}),e},Oe=async()=>{{let t=(await import("./6J3J7VLW.js")).default;return new t}},Fe=x.Root({agentExecutionContext:x({default:ce,reducer:oe}),currentIntent:x({default:()=>"none",reducer:A}),routing:x({default:()=>({mode:"auto"}),reducer:A}),lastExecutedAgent:x({default:()=>"",reducer:A}),requiresFollowUp:x({default:()=>!0,reducer:A}),stepCount:x({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:x({default:()=>"",reducer:le})}),Ue=t=>{if(!t||typeof t!="object"||!("services"in t))return!1;let e=t.services;return!!e&&typeof e=="object"&&"agentRegistry"in e},N=t=>{let e=t?.configurable;return Ue(e)?e:void 0},je=t=>{t.currentIntent="none"},We=async(t,e)=>{let s=N(e),r=await R({path:"./assets/orchestrator/t9n",locale:I(e)});if(t.agentExecutionContext.userRequest){let i=new se(t.agentExecutionContext.userRequest.trim());t.agentExecutionContext.messages=[...t.agentExecutionContext.messages,i],je(t)}let n=s?.services.agentRegistry.list().map(i=>i.agent.id)??[];return await b({text:r.availableAgents.replace("{agentIds}",[...n].join(", "))},e),await b({text:r.analyzingUserInput},e),t},Ne=async(t,e)=>{let s=await R({path:"./assets/orchestrator/t9n",locale:I(e)});return await b({text:s.exiting},e),t},fe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),He=(t,e)=>{if(!fe(t)){t!==void 0&&console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);return}let s={};for(let[r,n]of Object.entries(t)){if(!fe(n)||!("value"in n)){console.warn(`Agent "${e}" returned invalid sharedStatePatch entry for key "${r}". Ignoring that entry.`);continue}s[r]={value:n.value}}return s},ze=t=>{let{previousSharedState:e,patch:s,agentId:r}=t;if(!s)return e;let n=Date.now(),i={...e};for(let[c,a]of Object.entries(s))a?.value!==void 0&&(i[c]={value:a.value,meta:{updatedByAgentId:r,updatedAt:n}});return i},Be=256,Ve=new Set(["point","polyline","polygon","extent","custom"]),Ge=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Qe=(t,e)=>{if(t===void 0)return;if(!Array.isArray(t)){console.warn(`Agent "${e}" returned invalid sharedResourceAdditions. Ignoring it.`);return}let s=[];for(let[r,n]of t.entries()){if(!Ge(n)||typeof n.kind!="string"||!Ve.has(n.kind)||typeof n.description!="string"||!n.description.trim()||!("payload"in n)||n.payload===void 0){console.warn(`Agent "${e}" returned invalid sharedResourceAdditions entry at index ${r}. Ignoring that entry.`);continue}let i;try{i=structuredClone(n.payload)}catch{console.warn(`Agent "${e}" returned invalid sharedResourceAdditions entry at index ${r}. Ignoring that entry.`);continue}s.push({kind:n.kind,description:n.description.trim().slice(0,Be),payload:i})}return s.length?s:void 0},Je=t=>{let{previousSharedResources:e,additions:s,agentId:r}=t;if(!s?.length)return e;let n=Date.now(),i=s.map(c=>({...c,id:q(),meta:{createdByAgentId:r,createdAt:n}}));return[...e,...i].slice(-50)},be=t=>typeof t!="string"?void 0:t.trim()||void 0,Ze=t=>{switch(t){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."}},Ke=(t,e)=>{let s=be(e?.outputMessage),r=be(e?.summary),n=e?.status,i=n==="success"||n==="failed"?n:"unknown";i==="unknown"&&console.warn(`Agent "${t}" returned missing/invalid status. Defaulting to "unknown".`);let c=He(e?.sharedStatePatch,t),a=Qe(e?.sharedResourceAdditions,t);return{outputMessage:s,summary:r??s??Ze(i),status:i,sharedStatePatch:c,sharedResourceAdditions:a}},we=4e3,Xe=async(t,e)=>{let s=N(e),r=await R({path:"./assets/orchestrator/t9n",locale:I(e)});if(e?.signal?.aborted)return await b({text:r.runCancelledAgentExecution},e),{...t,currentIntent:"none",requiresFollowUp:!1};let{agentRegistry:n}=s?.services??{},i=n?.get(t.currentIntent);if(!i)return console.warn(r.noAgentFoundForIntent.replace("{intent}",t.currentIntent)),t;await b({text:r.executingRegisteredAgent.replace("{agentName}",i.agent.name)},e);let c={...e??{},metadata:{...e?.metadata,agentId:i.agent.id},configurable:{...s??{},agentId:i.agent.id,context:i.getContext?await i.getContext():void 0}},a;try{let l=await i.agent.createGraph().compile().invoke({agentExecutionContext:{...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages],priorSteps:structuredClone(t.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(t.agentExecutionContext.sharedState??{}),sharedResources:structuredClone(t.agentExecutionContext.sharedResources??[])}},c);a=Ke(i.agent.name,l),await b({text:r.finishedExecutingRegisteredAgent.replace("{agentName}",i.agent.name)},e)}catch(l){if(te(l)||e?.signal?.aborted||l instanceof Error&&l.name==="AbortError")throw l;let g=l instanceof Error?l.message:String(l);console.error(`Agent "${i.agent.name}" failed:`,l),await b({text:r.registeredAgentFailed.replace("{agentName}",i.agent.name).replace("{error}",g)},e),a={status:"failed",outputMessage:r.agentExecutionFailed.replace("{error}",g),summary:r.agentExecutionFailed.replace("{error}",g)}}let d=a.outputMessage,o=[...t.agentExecutionContext.messages];if(d){let l=d.length>we?`${d.slice(0,we-14)}
|
|
7
|
+
[truncated]`:d;o.push(new O(l))}return{...t,stepCount:t.stepCount+1,lastExecutedAgent:i.agent.id,requiresFollowUp:a.status==="failed"?!0:t.requiresFollowUp,finalOutputMessage:d??"",agentExecutionContext:{...t.agentExecutionContext,messages:o,priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:i.agent.id,assignedTask:t.agentExecutionContext.assignedTask,summary:a?.summary||r.noSummaryProvided,status:a?.status||"unknown"}],sharedState:ze({previousSharedState:t.agentExecutionContext.sharedState,patch:a.sharedStatePatch,agentId:i.agent.id}),sharedResources:Je({previousSharedResources:t.agentExecutionContext.sharedResources,additions:a.sharedResourceAdditions,agentId:i.agent.id})}}},Ye=async t=>{let{agent:e,messages:s,config:r}=t;return{structuredResponse:(await e.invoke({messages:s},r)).structuredResponse}},et=p.object({id:p.string().min(1),name:p.string().min(1),description:p.string().min(1)});p.array(et);var ve=t=>JSON.stringify(t,null,2),tt=t=>{let e=t.map(r=>r.id),s=p.enum(e);return p.object({intent:s.nullable(),assignedTask:p.string().nullable(),requiresFollowUp:p.boolean()})},st=async(t,e)=>{let s=N(e),r=await R({path:"./assets/orchestrator/t9n",locale:I(e)});if(e?.signal?.aborted)return await b({text:r.runCancelled},e),{...t,currentIntent:"none",finalOutputMessage:r.runCancelled,requiresFollowUp:!1};try{await b({text:r.routingToAgent},e);let n=s.services.agentRegistry?.list()??[],i=n.map(({agent:E})=>({id:E.id,name:E.name,description:E.description}));if(!i.length)return await b({text:r.noAgentsRegisteredTrace},e),{...t,currentIntent:"none",finalOutputMessage:r.noAgentsRegisteredMessage};let c=await me("intent_prompt"),a=ve(i),d=tt(i),o={registeredAgents:a,priorSteps:ve(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},l=await ne.fromTemplate(c).format(o),g=de({model:await F({modelTier:"fast",config:e}),tools:[],systemPrompt:l,responseFormat:d,middleware:[ue({model:await F({modelTier:"fast",config:e}),trigger:{tokens:4e3},keep:{messages:6}}),ge({runLimit:2})]}),{structuredResponse:u}=await Ye({agent:g,messages:t.agentExecutionContext.messages,config:e}),h=d.parse(u??{intent:null,assignedTask:null,requiresFollowUp:!1}),m=h.intent??"none",f={...t,currentIntent:m,requiresFollowUp:h.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:h.assignedTask??""}};if(m==="none"){let E=r.noMatchingAgentMessage.replace("{agentNames}",n.map(({agent:S})=>S.name).join(", "));return await b({text:r.noMatchingAgentTrace},e),{...t,currentIntent:m,requiresFollowUp:!1,finalOutputMessage:E,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new O(E)],priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:"no-intent-router",assignedTask:t.agentExecutionContext.userRequest,summary:"No matching agent found; asked user to rephrase.",status:"failed"}]}}}return await b({text:r.agentPicked.replace("{intent}",m).replace("{assignedTask}",h.assignedTask??"").replace("{requiresFollowUp}",String(h.requiresFollowUp))},e),f}catch(n){throw await b({text:r.intentDetectionErrorTrace},e),new Error(r.intentDetectionError.replace("{error}",n instanceof Error?n.message:String(n)))}},rt=async(t,e)=>{let s=await R({path:"./assets/orchestrator/t9n",locale:I(e)});if(t.routing.mode!=="direct")throw new Error(s.directAgentAssignmentRequiresDirectRouting);return await b({text:s.directRouteToAgent.replace("{agentId}",t.routing.agentId)},e),{...t,currentIntent:t.routing.agentId,requiresFollowUp:!1,agentExecutionContext:{...t.agentExecutionContext,assignedTask:t.agentExecutionContext.userRequest}}},nt=3,it=t=>t.routing.mode==="direct"?"assignDirectAgent":"intentLLM",at=t=>t.routing.mode==="direct"||t.stepCount>=nt||!t.requiresFollowUp?"exit":"intentLLM",ot=()=>new ae(Fe).addNode("ingestInput",We).addNode("assignDirectAgent",rt).addNode("intentLLM",st).addNode("executeRegisteredAgent",Xe).addNode("exit",Ne).addEdge(Y,"ingestInput").addConditionalEdges("ingestInput",it).addEdge("assignDirectAgent","executeRegisteredAgent").addConditionalEdges("intentLLM",t=>t.currentIntent==="none"||t.currentIntent===t.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",at).addEdge("exit",ee),lt=(t,e)=>{let s=t.output?.usage_metadata??e.usage_metadata,r=t.output?.llmOutput?.tokenUsage,n=s?.input_tokens??r?.promptTokens,i=s?.output_tokens??r?.completionTokens,c=s?.total_tokens??r?.totalTokens;if(n===void 0||i===void 0||c===void 0)return;let a=s?.input_token_details?.cache_read,d=s?.input_token_details?.cache_creation,o=s?.output_token_details?.reasoning;return{input:n,output:i,total:c,...a!==void 0&&{cacheRead:a},...d!==void 0&&{cacheWrite:d},...o!==void 0&&{reasoning:o}}},ct=(t,e,s,r)=>{switch(t){case"chat_model":case"llm":return"model";case"tool":case"retriever":return t;case"chain":return!r||e==="LangGraph"?"workflow":s===e?"node":"chain";default:return}},dt=t=>{if(t instanceof Error)return{message:t.message,name:t.name};let e=t,s=typeof e?.message=="string"?e.message:String(t??"Unknown runtime error"),r=typeof e?.name=="string"?e.name:void 0;return{message:s,...r&&{name:r}}},ut=({event:t,runId:e,parentSpanId:s,timestamp:r})=>{let n=/^on_(.+)_(start|end|error)$/u.exec(t.event);if(!n)return;let[,i,c]=n,a=t.metadata??{},d=a.langgraph_node,o=ct(i,t.name,d,s);if(!o)return;let l=a.agentId,g=a.model??a.ls_model_name,u=t.data,h=c==="end"&&o==="model"?lt(u,a):void 0,m=t.tags?.includes("langsmith:hidden")||d==="__start__",f={...g&&{model:g},...h&&{tokenUsage:h},...m&&{internal:!0}},E={id:t.run_id,...s&&{parentId:s},label:t.name,type:o,...Object.keys(f).length&&{metadata:f}},S={runId:e,timestamp:r,type:"runtime",...l&&{agentId:l}};switch(c){case"start":return{...S,phase:"started",span:{...E,...u?.input!==void 0&&{input:u.input}}};case"end":return{...S,phase:"completed",span:{...E,...u?.output!==void 0&&{output:u.output}}};case"error":return{...S,phase:"failed",span:{...E,error:dt(u?.error)}};default:return}},T=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:s}=e;if(this.agentRegistry.has(s.id))throw new Error(`Duplicate agent id: ${s.id}`);this.agentRegistry.set(s.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},W=class{constructor(e,s){this.graph=e,this.config={...s}}async waitForUser(){return await new Promise((e,s)=>{this.resolveWait=e,this.rejectWait=s})}handle(e,s){try{let r={agentId:e.agentId,id:e.id,payload:s},n=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:r},subgraphs:!0,version:"v2"});this.resolveWait?.(n)}catch(r){this.rejectWait?.(r)}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)}},_e=async(t,e)=>{let s=e.get(t);if(s)return s;let r=await he([t]);return e.set(t,r[0]),r[0]};async function gt(t,e,s,r){let n=`req-${Date.now()}`,i={type:"layerSearch",precomputedEmbedding:r?await _e(t,r):void 0,requestId:n,minScore:s};return await new Promise(c=>{let a=d=>{d.data.requestId===n&&c(d.data.results)};e.addEventListener("message",a,{once:!0}),e.postMessage(i)})}function ht(t){let{worker:e}=t;return{async searchLayers({text:s,minScore:r,embeddingCache:n}){return await gt(s,e,r,n)}}}var pt=async({combinedQuery:t,layerIds:e,embeddingsWorker:s,minScore:r,topResults:n,embeddingCache:i})=>{let c=`req-${Date.now()}`,a=i?await _e(t,i):void 0,d={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:a,requestId:c,minScore:r,topResults:n};return await new Promise(o=>{let l=g=>{if(g.data.requestId!==c)return;let u=g.data.results.map(({layerId:h,results:m})=>({layerId:h,results:m}));o(u)};s.addEventListener("message",l,{once:!0}),s.postMessage(d)})};function mt(t){let{worker:e}=t;return{async searchFields({text:s,layerIds:r,minScore:n,topResults:i,embeddingCache:c}){return await pt({combinedQuery:s,layerIds:r,embeddingsWorker:e,minScore:n,topResults:i,embeddingCache:c})}}}var yt=t=>{let e=ye.safeParse(t);if(!e.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return e.data},ft=(t,e)=>{let s=new Map,r=new Map;if(e.allLayers.forEach(n=>{n instanceof De&&r.set(n.id,n)}),t.length!==r.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let n of t){let i=r.get(n.id);if(!i)throw new Error(`Layer with ID ${n.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(n.fields.length!==i.fields.length)throw new Error(`Field count mismatch for layer ID ${n.id} during registry restoration. Regenerate embeddings.`);let c={name:n.name,title:n.title,description:n.description},a=new Map;for(let d of n.fields){let o=i.fieldsIndex.get(d.name);if(!o)throw new Error(`Field with name ${d.name} not found in the original layer ${n.id} during registry restoration. Regenerate embeddings.`);a.set(d.name,{name:d.name,alias:i.getFieldAlias(d.name)??d.alias,description:d.description,type:o.type||"unknown",valueType:o.valueType||"unknown",domain:i.getFieldDomain(d.name)??void 0})}s.set(n.id,{layerItem:c,fieldRegistry:a})}return s},bt=async t=>{try{return(await Le(t,{responseType:"json"})).data}catch(e){throw new Error(`Failed to fetch data from ${t}: ${String(e)}`)}},wt=async t=>{let e=t.map;if(!e?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:s}=await e.portalItem.fetchResources(),r=s.find(i=>i.resource.path==="embeddings-v01.json");if(!r?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let n=await bt(r.resource.url);return yt(n)},D=class t{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.sharedResources=[],this.agentRegistry=new T,this.activeRunId="",this.cancelledRunIds=new Set,this.parentRunIds=new Map,this.activeRuntimeSpans=new Map,this.runtimeEventsEnabled=!1,this.streamEpoch=0}static async init(e){let s=new t;s.runtimeEventsEnabled=e.runtimeEventsEnabled??!1;try{if(e.view?.map){await Ee.whenOnce(()=>e.view.ready);let r=await wt(e.view),n=ft(r.layers,e.view.map);s.layersAndFieldsRegistry=n,s.embeddingsWorker=await qe(r)}return e.agents?.forEach(r=>{s.agentRegistry.register(r)}),s.orchestratorReady=!0,s}catch(r){throw console.error("Orchestrator initialization failed:",r),r}}async*ask(e,s={}){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");let r=this.createRequestAgentRegistry(s);if(!r.list().length)throw new Error("Orchestrator has no agents selected for this request.");if(++this.streamEpoch,!e.trim()&&!s.inputParts?.length)return;if(!e.trim()&&s.routing!=="direct")throw new Error("Requests containing only structured input require direct agent routing.");let n=q();this.parentRunIds.clear(),this.activeRuntimeSpans.clear(),this.activeRunId=n,this.activeAbortController=new AbortController,this.graph||(this.graph=ot().compile({checkpointer:new ie}));let i=this.embeddingsWorker?ht({worker:this.embeddingsWorker}):void 0,c=this.embeddingsWorker?mt({worker:this.embeddingsWorker}):void 0,a=new Map,d=s.routing==="direct"?{mode:"direct",agentId:s.agentId}:{mode:"auto"},o={thread_id:n,locale:s.locale??"en",hitlResponse:null,services:{layerSearch:i,fieldSearch:c,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:r,embeddingCache:a}},l={version:"v2",streamMode:"custom",signal:this.activeAbortController.signal,...this.runtimeEventsEnabled&&{callbacks:[this.createHierarchyCallback()]},configurable:o,subgraphs:!0},g=this.graph?.streamEvents({routing:d,agentExecutionContext:{userRequest:e,inputParts:[...s.inputParts??[]],messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState,sharedResources:this.sharedResources}},l),u=++this.streamEpoch;if(yield*this.pipeStream(g,u,n),this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}for(;;){if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}let m=(await this.graph.getState(l,{subgraphs:!0})).tasks.find(f=>f.interrupts.length>0)?.interrupts[0]?.value;if(!m)break;this.currentInterrupt=m,this.interruptHandler=new W(this.graph,l),yield*this.closeActiveRuntimeSpans(n,"interrupted"),yield{runId:n,timestamp:Date.now(),type:"interrupt",interrupt:m};try{let f=await this.interruptHandler.waitForUser(),E=++this.streamEpoch;yield*this.pipeStream(f,E,n)}catch(f){if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}if(f){yield{runId:n,timestamp:Date.now(),type:"error",error:{message:f?.message}};return}}}if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}let h=(await this.graph.getState(l,{subgraphs:!0})).values;if(this.isRunCancelled(n)){yield*this.createCancellationEvents(n);return}this.chatHistory=h.agentExecutionContext.messages.length?h.agentExecutionContext.messages:this.chatHistory,this.priorSteps=h.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=h.agentExecutionContext.sharedState??{},this.sharedResources=h.agentExecutionContext.sharedResources??[],yield{runId:n,timestamp:Date.now(),type:"completed",result:{content:h.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.sharedResources=[]}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,s,r){try{for await(let n of e){if(this.isRunCancelled(r)||s!==this.streamEpoch)break;if(this.runtimeEventsEnabled){let i=ut({event:n,runId:r,parentSpanId:this.parentRunIds.get(n.run_id),timestamp:Date.now()});i&&(i.phase==="started"?this.activeRuntimeSpans.set(i.span.id,i):this.activeRuntimeSpans.delete(i.span.id),yield i)}n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:r,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:r,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}catch(n){if(!this.isRunCancelled(r))throw n}}*createCancellationEvents(e){yield*this.closeActiveRuntimeSpans(e,"cancelled"),yield{runId:e,timestamp:Date.now(),type:"cancelled",reason:"user"}}*closeActiveRuntimeSpans(e,s){let r=Date.now(),n=[...this.activeRuntimeSpans.values()].reverse();this.activeRuntimeSpans.clear();for(let i of n){let{input:c,...a}=i.span;yield{type:"runtime",phase:s,runId:e,timestamp:r,...i.agentId&&{agentId:i.agentId},span:a}}}createHierarchyCallback(){let e=(s,r)=>{r&&this.parentRunIds.set(s,r)};return re.fromMethods({handleLLMStart:(s,r,n,i)=>e(n,i),handleChatModelStart:(s,r,n,i)=>e(n,i),handleChainStart:(s,r,n,i)=>e(n,i),handleToolStart:(s,r,n,i)=>e(n,i),handleRetrieverStart:(s,r,n,i)=>e(n,i)})}isRunCancelled(e){return this.cancelledRunIds.has(e)}createRequestAgentRegistry(e){let s=e.routing==="direct"?[e.agentId]:e.agentIds,r=s?s.map(i=>{let c=this.agentRegistry.get(i);if(!c)throw new Error(`Agent is not registered: ${i}`);return c}):this.agentRegistry.list(),n=new T;return r.forEach(i=>n.register(i)),n}dispose(){this.sharedResources=[],this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};var St=B`: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)}`;function H(t){return t.trim()?U.lexer(t).filter(e=>e.type!=="space").map(e=>U.parser([e])):[]}var L=class{constructor(){this._stableParts=[],this._stableText="",this._rawText=""}push(e){return this._rawText+=e,this._advanceStableBoundary(),this.getParts()}finalize(){let e=this._rawText.slice(this._stableText.length);return e.trim()&&(this._stableParts.push(...H(e)),this._stableText=this._rawText),this._stableParts}getParts(){let e=this._trimIncompleteTail(this._rawText.slice(this._stableText.length)),s=e.trim()?H(e):[];return[...this._stableParts,...s]}reset(){this._stableParts=[],this._stableText="",this._rawText=""}_advanceStableBoundary(){let e=this._rawText.slice(this._stableText.length),s=this._lastSafeBoundary(e);if(s<=0)return;let r=e.slice(0,s);this._stableParts.push(...H(r)),this._stableText+=r}_lastSafeBoundary(e){let s=e.split(`
|
|
8
|
+
`),r=!1,n=0,i=0;for(let c of s)/^\s*(```|~~~)/u.test(c)&&(r=!r),i+=c.length+1,c.trim()===""&&!r&&(n=i);return n<e.length?n:0}_trimIncompleteTail(e){let s=e.lastIndexOf("<");if(s!==-1&&!e.includes(">",s))return e.slice(0,s);let r=this._earliestUnclosedTag(e);if(r!==-1)return e.slice(0,r);let n=e.lastIndexOf("[");if(n!==-1){let i=e.slice(n);if(!/\[[^\]]*\]\([^)]*\)/u.test(i))return e.slice(0,n)}return e}_earliestUnclosedTag(e){let s=new Set(["br","img","hr","input","meta","link","area","base","col","embed","source","track","wbr"]),r=/<(\/?)([a-zA-Z][\w-]*)\b[^>]*?(\/?)>/gu,n=[];for(let i=r.exec(e);i;i=r.exec(e)){let[,c,a,d]=i,o=a.toLowerCase();if(!(s.has(o)||d==="/"))if(c==="/"){for(let l=n.length-1;l>=0;l--)if(n[l].name===o){n.splice(l);break}}else n.push({name:o,index:i.index})}return n.length?n[0].index:-1}};function Ct(t){let e=new L;return e.push(t),e.finalize()}var At=async t=>await new Promise(e=>setTimeout(e,t));async function*$t(t,{chunkSize:e=15,delay:s=50}={}){let r=new L;for(let n=0;n<t.length;n+=e)yield r.push(t.slice(n,n+e)),await At(s);yield r.finalize()}var Pt=Object.defineProperty,Mt=Object.getOwnPropertyDescriptor,_=(t,e,s,r)=>{for(var n=r>1?void 0:r?Mt(e,s):e,i=t.length-1,c;i>=0;i--)(c=t[i])&&(n=(r?c(e,s,n):c(n))||n);return r&&n&&Pt(e,s,n),n},xe=t=>!t||typeof t!="object"?!1:t.name==="AbortError";async function*Ie(t,e,s,r,n=!1){if(n){if(r?.aborted){yield{type:"cancelled",log:s,runId:e};return}yield{type:"block-data",blockType:"text",data:{parts:Ct(t)},runId:e};return}for await(let i of $t(t)){if(r?.aborted){yield{type:"cancelled",log:s,runId:e};return}yield{type:"block-data",blockType:"text",data:{parts:i},runId:e}}}var v=class extends It{constructor(t){super(t),this.view=null,this.streamingDisabled=!1,this.runtimeEventsEnabled=!1,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 Et(()=>!this.view.updating),this._set("orchestrator",await D.init({agents:[...this.agents],runtimeEventsEnabled:this.runtimeEventsEnabled,view:this.view??void 0})),this.addHandles([_t(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(t,e,s){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let r=[],n,i="pending";try{let c=this.orchestrator.ask(t,e);for await(let a of c)switch(i=a.runId,a.type){case"runtime":{yield{type:"runtime",event:a,runId:i};break}case"trace":{this._set("processingStep",a.data.text),r.push(a.data.text);break}case"completed":{this._set("processing",!1),this._set("processingStep","");let d=a.result,o=!!d.content.length,l=!!n?.length;if(!o&&!l){yield{type:"completed",error:"No response received.",log:r,runId:i};return}let g=d.content;if(yield{type:"block-start",blockType:"text",runId:i},yield*Ie(g,i,r,s,this.streamingDisabled),yield{type:"block-end",blockType:"text",runId:i},l)for(let u of n){if(s?.aborted){yield{type:"cancelled",log:r,runId:i};return}let{type:h,data:m}=u;if(yield{type:"block-start",blockType:h,runId:i},h==="text"){let f=typeof m?.content=="string"?m.content:"";yield*Ie(f,i,r,s,this.streamingDisabled)}else yield{type:"block-data",blockType:h,data:m,runId:i};yield{type:"block-end",blockType:h,runId:i}}yield{type:"completed",response:g,blocks:n,log:r,runId:i};return}case"ux-suggestion":{let d=a.suggestion;n=n?[...n,d]:[d];break}case"interrupt":{let{kind:d,message:o,metadata:l,showOtherOption:g}=a.interrupt,u=Array.isArray(l)?l.filter(m=>typeof m=="string"):[],h=(()=>{switch(d){case"booleanChoice":return{type:"boolean-choice",message:o,options:u};case"singleSelection":return{type:"single-select",message:o,options:u};case"multipleSelection":return{type:"multi-select",message:o,options:u};case"textInput":return{type:"text-input",message:o};default:return{type:d,message:o,options:u}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:{...h,showOtherOption:g},runId:i};break}case"cancelled":{yield{type:"cancelled",log:r,runId:i};return}case"error":{if(s?.aborted||xe(a.error)){yield{type:"cancelled",log:r,runId:i};return}yield{type:"completed",error:a.error.message,log:r,runId:i};return}default:{console.warn("Unknown event type:",a);break}}}catch(c){if(s?.aborted||xe(c)){yield{type:"cancelled",log:r,runId:i};return}console.warn("Error during message processing:",c),yield{type:"completed",error:this.messages.messageProcessingErrorMessage,log:r,runId:"error"};return}finally{this._set("processing",!1)}}cancel(){this.orchestrator?.cancel()}};_([k({readOnly:!0})],v.prototype,"orchestrator",2);_([k()],v.prototype,"agents",2);_([k()],v.prototype,"portal",2);_([k()],v.prototype,"view",2);_([k()],v.prototype,"messages",2);_([k()],v.prototype,"streamingDisabled",2);_([k()],v.prototype,"runtimeEventsEnabled",2);_([k({readOnly:!0})],v.prototype,"loading",2);_([k({readOnly:!0})],v.prototype,"processing",2);_([k({readOnly:!0})],v.prototype,"processingStep",2);v=_([Rt("OrchestratorController")],v);var Tt="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",Dt="Embeddings not found for this web map.",Lt="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",z=class extends Q{constructor(){super(...arguments),this._messages=Z({blocking:!0}),this.#e=P(),this.#o=P(),this.#r=P(),this.#t=null,this.#n=new Map,this.#s=xt.getDefault(),this.#i=e=>{e.stopPropagation(),this.cancelInterrupt()},this.#a=e=>{e.stopPropagation();let s=e.detail;this.submitInterrupt(s)},this.#l=e=>{if(e.stopPropagation(),e.defaultPrevented)return;let s=e.detail,r=typeof s=="string"?s:s.prompt,n=typeof s=="string"?void 0:{displayText:s.displayText,parts:s.parts};if(!this.#y(r,n?.parts??[])){e.preventDefault();return}if(this.arcgisSubmit.emit(s).defaultPrevented){e.preventDefault();return}this.keepSuggestedPrompts||(this.suggestedPrompts=[]),this._inputValue="",this.submitMessage(r,n)},this.#c=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 s=e.detail;this.arcgisFeedback.emit(s)},this.#u=e=>{e.stopPropagation();let s=e.detail;this._inputValue=s.prompt,this.arcgisPromptSelect.emit(s)},this.#p=e=>{this.arcgisSlottableRequest.emit(e.detail)},this._orchestratorController=null,this._interrupt=null,this._interruptDetails=[],this._error=null,this._submissionError=null,this._inputValue="",this._isAnswering=!1,this._canceling=!1,this.messages=new vt([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.streamingDisabled=!1,this.runtimeEventsEnabled=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.assistantAvatarEnabled=!1,this.userAvatarEnabled=!1,this.arcgisCancel=w(),this.arcgisError=w(),this.arcgisFeedback=w(),this.arcgisInterrupt=w(),this.arcgisInterruptCancel=w(),this.arcgisInterruptSubmit=w(),this.arcgisPromptSelect=w(),this.arcgisReady=w(),this.arcgisResponse=w(),this.arcgisRuntime=w({bubbles:!1,composed:!1}),this.arcgisSlottableRequest=w({bubbles:!1,composed:!1}),this.arcgisSubmit=w({cancelable:!0})}static{this.properties={_orchestratorController:16,_interrupt:16,_interruptDetails:16,_error:16,_submissionError:16,_inputValue:16,_isAnswering:16,_signedInUserId:16,_canceling:16,_isSignedIn:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,alwaysUseAgentId:1,allowedAgentIds:[1,{type:Array}],commandProvider:0,entityProviders:0,suggestedPrompts:[1,{type:Array}],feedbackEnabled:5,keepSuggestedPrompts:5,streamingDisabled:5,runtimeEventsEnabled:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5,assistantAvatarEnabled:5,userAvatarEnabled:5}}static{this.styles=St}#e;#o;#r;#t;#n;#s;#i;#a;#l;#c;#d;#u;#p;get _isSignedIn(){return!!this.#s?.user||!!this._signedInUserId}get _user(){return this.#s?.user?.fullName||this.#s?.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}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}register(e){this.#n.set(e.agent.id,e),this._orchestratorController&&this.#g()}submitInterrupt(e){this.arcgisInterruptSubmit.emit(e),this._interrupt&&(this._interruptDetails=[...this._interruptDetails,{interrupt:this._interrupt,response:e}]),this.orchestrator?.resumeInterrupt(e),this._interrupt=null}async submitMessage(e,s){let r=e.trim(),n=s?.parts??[];if(!r&&!n.length||!this.#y(r,n)||(this.messages.push({id:Date.now().toString(),role:"user",content:s?.displayText?.trim()||r||n.map(o=>this.#f(o)).join(" "),parts:n}),!this._orchestratorController))return;this.#t=new AbortController,this._orchestratorController.streamingDisabled=this.streamingDisabled;let i=this.#m(n),c=this._messages._t9nLocale||"en",a={...s?.parts?{inputParts:s.parts}:{},...i?{routing:"direct",agentId:i}:{routing:"auto",agentIds:this.allowedAgentIds},locale:c},d=this._orchestratorController.ask(r,a,this.#t?.signal);for await(let o of d){let l=o.runId,g=this.messages.at(-1);switch(o.type){case"runtime":this.arcgisRuntime.emit(o.event);break;case"block-start":{this._isAnswering=!0;let u={type:o.blockType,isPending:!0};if(g?.role==="assistant"&&g.id===l){let h=[...g.blocks??[],u];this.messages.splice(-1,1,{...g,blocks:h})}else this.messages.push({role:"assistant",blocks:[u],id:l,isStreaming:!0,interrupts:this._interruptDetails}),this._interruptDetails=[];break}case"block-data":{if(g?.role!=="assistant"||g?.id!==l)break;let u=[...g.blocks??[]],h=u[u.length-1],{blockType:m,data:f}=o;if(h?.type!==m||!h.isPending)break;m==="text"?u[u.length-1]={...h,data:{...h.data,parts:f?.parts}}:u[u.length-1]={...h,data:{...h.data,...f??{}}},this.messages.splice(-1,1,{...g,blocks:u});break}case"block-end":{if(g?.role!=="assistant"||g?.id!==l)break;let u=[...g.blocks??[]],h=u[u.length-1];if(h?.type!==o.blockType||!h.isPending)break;let m=h;u[u.length-1]={...m,data:{...m.data},isPending:!1},this.messages.splice(-1,1,{...g,blocks:u});break}case"completed":o.error?(this.messages.push({role:"assistant",log:o.log,error:o.error,id:l,interrupts:this._interruptDetails}),this._interruptDetails=[]):g?.role==="assistant"&&g.id===l&&this.messages.splice(-1,1,{...g,content:o.response,blocks:g.blocks?.map(u=>({...u,data:{...u.data},isPending:!1}))??[],isStreaming:!1,log:o.log}),this._isAnswering=!1,this.#t=null,this._canceling=!1;break;case"interrupt":this._interrupt={...o.payload,id:l},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":g?.role==="assistant"&&g.id===l?this.messages.splice(-1,1,{...g,blocks:g.blocks?.filter(u=>u.type==="text"||!u.isPending)??[],isStreaming:!1,log:o.log,error:`(${this._messages.stoppedByUserLabel})`}):(this.messages.push({role:"assistant",log:o.log,error:`(${this._messages.stoppedByUserLabel})`,id:l,interrupts:this._interruptDetails}),this._interruptDetails=[]),this._isAnswering=!1,this.#t=null,this._canceling=!1;break}}}unregister(e){this.#n.delete(e),this._orchestratorController&&this.#g()}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#e.value?.addEventListener("arcgisPromptSelect",this.#u),this.#e.value?.addEventListener("arcgisSubmit",this.#l),this.#e.value?.addEventListener("arcgisCancel",this.#c),this.#e.value?.addEventListener("arcgisFeedback",this.#d);let e=kt(()=>!!this._interrupt&&!!this.#r.value,()=>{let r=this.#r.value;r.removeEventListener("arcgisSubmit",this.#a),r.removeEventListener("arcgisCancel",this.#i),r.addEventListener("arcgisSubmit",this.#a,{once:!0}),r.addEventListener("arcgisCancel",this.#i,{once:!0})}),s=this.messages.on("after-add",r=>{let n=r.item;n.role==="assistant"&&(n.error||n.content)&&this.arcgisResponse.emit(n)});return queueMicrotask(()=>{this.#h()}),()=>{e.remove(),s.remove(),this.#e.value?.removeEventListener("arcgisPromptSelect",this.#u),this.#r.value?.removeEventListener("arcgisSubmit",this.#a),this.#r.value?.removeEventListener("arcgisCancel",this.#i),this.#e.value?.removeEventListener("arcgisSubmit",this.#l),this.#e.value?.removeEventListener("arcgisCancel",this.#c),this.#e.value?.removeEventListener("arcgisFeedback",this.#d),this._orchestratorController?.destroy(),this._orchestratorController=null}})}willUpdate(e){this.hasUpdated&&e.has("runtimeEventsEnabled")&&this._orchestratorController&&(this._orchestratorController.destroy(),this._orchestratorController=null,this.#h())}#f(e){return e.kind==="command"?`/${e.id}`:`${e.trigger}${e.id}`}#m(e){for(let s of e)if(s.kind==="command"&&s.agentId)return s.agentId;return this.alwaysUseAgentId}#y(e,s){let r=s.filter(n=>n.kind==="command").length>1;return this._submissionError=r?this._messages.multipleCommands:!e.trim()&&s.length>0&&!this.#m(s)?this._messages.partsOnlyRequiresAgent:null,this._submissionError?(this.arcgisError.emit(new Error(this._submissionError)),!1):!0}async#b(){await ke.checkSignInStatus(this.#s.url);let e=await this.#s.load();if(!e.helperServices?.aiAssistantServices?.url)throw new Error(this._messages.serviceUrlNotAvailableMessage);let s=!1,r=await e.fetchSettings();if(r.aiConfig?s=r.aiConfig.aiForOrg?.enabled===!0&&r.aiConfig.aiForOrg?.aiCapabilities?.aiAgents?.enabled===!0:s=r.aiAssistantsEnabled===!0,!s)throw new Error(this._messages.aiAssistantsNotEnabledMessage);if(!e.isPortal&&e?.user?.privileges?.includes("portal:user:useAIAssistants")!==!0)throw new Error(this._messages.userPrivilegesNotSufficientMessage)}async#g(){try{this._error=null;let e=pe(this.el,this.referenceElement);await e?.componentOnReady();let s=[...this.#n.values()];return s.length?(await this.#b(),this._orchestratorController?.destroy(),this._orchestratorController=new v({agents:s,portal:this.#s,runtimeEventsEnabled:this.runtimeEventsEnabled,streamingDisabled:this.streamingDisabled,view:e?.view,messages:this._messages}),await this._orchestratorController.load(),this.requestUpdate(),!0):(this._error=this._messages.noAgentsFoundMessage,!1)}catch(e){return this._error=e?.message??this._messages.orchestratorInitializationErrorMessage,G(this)(e),!1}}async#h(){await this.#g()?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))}_reset(){this._orchestratorController?.cancel(),this.#t?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._submissionError=null,this._inputValue="",this._signedInUserId=void 0}_renderEntryMessage(){return this._isSignedIn?this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:y`<calcite-notice open kind=brand closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:y`<slot name=entry-message></slot>`:this._renderSignInNotice()}_renderSignInNotice(){let e=this.#s;return y`<calcite-notice slot=entry-message open kind=brand icon width=full><div slot=message>${this._messages.signInRequiredMessage}</div>${e?y`<calcite-link slot=link @click=${async()=>{try{let s=await ke.getCredential(`${e.url}/sharing`);this._signedInUserId=s.userId,this._error=null,this.requestUpdate(),await this.#h()}catch(s){this._error=s?.message??this._messages.signInErrorMessage,this.arcgisError.emit(new Error(this._error)),V("error",this,"Error signing in:",{detail:{error:s}})}}} target=_blank title=${this._messages.signInToArcGISOnlineLabel??C}>${this._messages.signInLabel}</calcite-link>`:y`<div slot=link>${this._messages.noPortalInformationMessage}</div>`}</calcite-notice>`}_renderErrorNotice(){return this._error?y`<calcite-notice slot=entry-message open kind=brand icon width=full>${this._error===Tt?y`<div slot=message>${Dt}</div><calcite-link slot=link .href=${Lt} target=_blank title=${this._messages.learnAboutWebMapEmbeddingsLabel??C}>${this._messages.readMoreLabel}</calcite-link>`:y`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}render(){return y`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${M(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"?y`<arcgis-assistant-message .message=${e} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#p} .assistantAvatarEnabled=${this.assistantAvatarEnabled}>${e.blocks?.map((s,r)=>y`<slot name=${j(e.id,r)??C} slot=${j(e.id,r)??C}><arcgis-assistant-message-block .block=${s}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:y`<arcgis-assistant-user-message .message=${e} .user=${this._user} .userAvatarEnabled=${this.userAvatarEnabled}></arcgis-assistant-user-message>`)}</slot>${this._interrupt?y`<div slot=message-loading><div class="interrupt-waiting-message">${this._messages.waitingForUserInputMessage}</div></div>`:y`<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?y`<slot name=interrupt><arcgis-assistant-interrupt slot=content-bottom .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} .showOtherOption=${this._interrupt.showOtherOption??!1} ${M(this.#r)}></arcgis-assistant-interrupt></slot>`:this.suggestedPrompts?.length?y`<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()}${this._submissionError?y`<div role=alert>${this._submissionError}</div>`:null}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse||this._isAnswering} .commandProvider=${this.commandProvider} .entityProviders=${this.entityProviders} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} .disabled=${this._canceling||!this._isSignedIn||!!this._interrupt||!!this._error} ${M(this.#o)}><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.#o.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>`}};J("arcgis-assistant",z);return z},"core/Collection","core/reactiveUtils","portal/Portal","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","core/Accessor","core/accessorSupport/decorators","identity/IdentityManager",a)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
+
import p from"./CWZG7DML.js";import{a as i,c as r}from"./NYFL2F5L.js";import"./YD5LVM7V.js";import n from"./AOT3PM2Q.js";import m from"./YGSDJ4V3.js";import l from"./M52LKZN7.js";import k from"./UXDRYDOD.js";import j from"./2H32MDP2.js";import"./OPQCY33W.js";import"./QAVDW7A7.js";import h from"./YSEHJQ4L.js";import g from"./CV5YAJMD.js";import"./OKDXM5D4.js";import f from"./UP7RW5K2.js";import"./M5UMOOL2.js";import"./H6J65TWL.js";import"./XBWGOD6I.js";import d from"./J3T5HB77.js";import"./AGDGDULE.js";import"./FIZMK7GS.js";import"./LMAIOLS2.js";import"./7OQK2F7O.js";import c from"./Y3ZKMD47.js";import b from"./BMVPOFHU.js";import"./QBZP6XOE.js";import"./3COVQI26.js";import"./CETIZ4IQ.js";import"./PR4VMSKD.js";import"./X3YFCWQZ.js";import"./2JD3G7IW.js";import"./LDDP7NSY.js";import"./WHIWOYHN.js";import{C as a,x as e}from"./NAVK5JJ2.js";import"./OUMTV5H5.js";import{a as o}from"./I2RQZAFF.js";import"./H653UVNH.js";import"./GS5JDPZH.js";import"./2WY5MPMY.js";import"./S6OUM5X2.js";import"./XLHYQNAM.js";import"./7GDMXAF5.js";import"./5XZ5VL42.js";import"./C3VLDYS2.js";import"./A4ZVCRVF.js";import"./N2GN5WOI.js";import"./272R36XK.js";import"./5PV2GUZW.js";export default $arcgis.t(([])=>{var n=[async()=>(await import("./KDA5VPLO.js")).default,async()=>(await import("./LGIXZLOP.js")).default],s=o({id:"data-exploration",name:"Data Exploration Agent",description:"Explores feature-layer data and applies data-driven map filters using on-demand query and filter skills.",skillLoaders:n,modelTier:"default",systemPrompt:"You are an ArcGIS data exploration agent.",instructions:"Answer only questions about the current map's layers, features, fields, spatial relationships, or supported map actions, using returned tool results. Do not answer unrelated general-knowledge, advice, opinion, political, health, security, or other non-map requests, even when the user asks for this agent. For an unsupported request, respond only: 'I can help with questions about the data and features in this map.' Report directly relevant findings, requested calculations, and limitations that affect the answer. Do not provide unsolicited advice about dataset design, publishing, classification, grouping, future analysis, or alternative questions. Ask a clarifying question only when a map-related request cannot be answered reliably as written. A request can require both query and filter skills. Treat show, display, highlight, map, filter, reveal, emphasize, include, or exclude as visual map intent when the request targets matching features. For visual map intent, do not stop after query. First use query to identify/count the matching features, then load the filter skill and call setFeatureEffect with the same layer, where clause, geometry filter, extent setting, or object IDs. Use only tool results to describe data or map changes."});var t=class extends e{constructor(){super(...arguments),this.agent=s}static{this.properties={referenceElement:1}}#t;#e;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=i(this,"arcgis-assistant-data-exploration-agent"),this.#e=r(this)}disconnectedCallback(){this.#e?.unregister(this.agent.id),super.disconnectedCallback()}};a("arcgis-assistant-data-exploration-agent",t);return t},"intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",b,c,d,f,g,h,j,k,l,m,n,p)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
+
import{a as k}from"./QBZP6XOE.js";import{Ga as s}from"./A4ZVCRVF.js";import{N as r}from"./N2GN5WOI.js";export default $arcgis.t(([w])=>{async function d(o,e){let t=e.map.bookmarks;if(!t||t.length===0)throw new Error("No bookmarks found in the map.");let n=t.find(h=>h.name===o);if(!n)throw new Error(`Bookmark with name "${o}" not found.`);let a=n.viewpoint;if(!a)throw new Error(`Bookmark with name "${o}" does not have a valid viewpoint.`);let i=a.targetGeometry?.extent;if(!i)throw new Error(`Bookmark with name "${o}" does not have a valid target geometry.`);let c=w.fromExtent(i);await e.goTo(a);let m=`Navigated to bookmark: ${o}`,f={value:m,sharedResourceAdditions:[{kind:"polygon",description:`Bookmark: ${o}`,payload:c.toJSON()}]};return[m,f]}async function p({bookmarkName:o},e){let{mapView:t}=k(e,["mapView"]);return await d(o,t)}var g=r.object({bookmarkName:r.string().describe("The name of the bookmark to navigate to.")}),y=s(p,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:g,responseFormat:"content-and-artifact"});return y},"geometry/Polygon")
|
|
@@ -69,7 +69,7 @@ Fields: This typically requires zero or one field of type number.`,schema:Ct});f
|
|
|
69
69
|
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
70
70
|
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
71
71
|
Example: Color each feature based on the region it belongs to
|
|
72
|
-
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:ar}),Xa=y.Root({...x(),vectorSearchLayerIds:y(),vectorSearchFieldResults:y(),layerFieldInfo:y(),selectedLayerId:y()});var rn=y.Root({...x(),helpInternalState:y({reducer:E,default:()=>({toolCallMessage:void 0})})});var Te=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./XYMIFFBW.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./AMA67DVI.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./JSRNLNOE.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./UWHRBGWN.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./2HNGMLFD.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./6QOSUG64.js").then(e=>e.default),"../agents/dataExploration/skills/filter/SKILL.md":()=>import("./LGIXZLOP.js").then(e=>e.default),"../agents/dataExploration/skills/query/SKILL.md":()=>import("./KDA5VPLO.js").then(e=>e.default),"../agents/dataExplorationGraph/prompts/data_explore_filter_prompt.md":()=>import("./C5Q6E7UC.js").then(e=>e.default),"../agents/dataExplorationGraph/prompts/data_explore_query_prompt.md":()=>import("./GGAXXX5X.js").then(e=>e.default),"../agents/dataExplorationGraph/prompts/summarize_query_response_prompt.md":()=>import("./G7MCIFV2.js").then(e=>e.default),"../agents/help/skills/help/SKILL.md":()=>import("./
|
|
72
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:ar}),Xa=y.Root({...x(),vectorSearchLayerIds:y(),vectorSearchFieldResults:y(),layerFieldInfo:y(),selectedLayerId:y()});var rn=y.Root({...x(),helpInternalState:y({reducer:E,default:()=>({toolCallMessage:void 0})})});var Te=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./XYMIFFBW.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./AMA67DVI.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./JSRNLNOE.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./UWHRBGWN.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./2HNGMLFD.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./6QOSUG64.js").then(e=>e.default),"../agents/dataExploration/skills/filter/SKILL.md":()=>import("./LGIXZLOP.js").then(e=>e.default),"../agents/dataExploration/skills/query/SKILL.md":()=>import("./KDA5VPLO.js").then(e=>e.default),"../agents/dataExplorationGraph/prompts/data_explore_filter_prompt.md":()=>import("./C5Q6E7UC.js").then(e=>e.default),"../agents/dataExplorationGraph/prompts/data_explore_query_prompt.md":()=>import("./GGAXXX5X.js").then(e=>e.default),"../agents/dataExplorationGraph/prompts/summarize_query_response_prompt.md":()=>import("./G7MCIFV2.js").then(e=>e.default),"../agents/help/skills/help/SKILL.md":()=>import("./MNMCIS4E.js").then(e=>e.default),"../agents/helpGraph/prompts/help_prompt.md":()=>import("./XMQJWPXI.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./X4EQEKM7.js").then(e=>e.default),"../agents/navigation/skills/navigation/SKILL.md":()=>import("./LWEKPFV6.js").then(e=>e.default),"../agents/navigationGraph/prompts/navigation_intent_prompt.md":()=>import("./XSH4B7FP.js").then(e=>e.default),"../agents/navigationGraph/prompts/navigation_tool_prompt.md":()=>import("./HCPI2RJE.js").then(e=>e.default)});async function C(e){let t=Object.entries(Te).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
|
|
73
73
|
Available prompts:
|
|
74
74
|
${Object.keys(Te).join(`
|
|
75
75
|
`)}`);return await t[1]()}var vn=y.Root({...x(),intent:y({reducer:(e,t)=>t}),arcgisKnowledgeMessages:y({reducer:k,default:()=>[]}),arcgisKnowledgeToolResult:y({reducer:(e,t)=>t,default:()=>null})});function oe(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 M(e){return!!e?.map&&"activeLinkChartLayer"in e.map}async function G(e){!M(e)||!e.map.diagramNodesExtent||await e.goTo(e.map.diagramNodesExtent)}function z(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)&&oe(r),{view:r}}function Sn(e){let t=e?.configurable?.context;if(ke(e)==="knowledgeGraph")return"knowledgeGraph";let r=t.view;return M(r)?"linkChart":(oe(r),"map")}async function D(e){let t=e?.configurable?.context;if(ke(e)==="knowledgeGraph")return t;{let r=t.view.map;if(r&&"activeLinkChartLayer"in r){let o=r.knowledgeGraph?.url;if(!o)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await ve(o)}}else{oe(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 ve(o)}}}}function ke(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in t&&"view"in t)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in t)return"knowledgeGraph";if("view"in t)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var J=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=W.fromDataModel(t)}},W=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(q.fromEntityType(o));for(let o of t.relationshipTypes)r.relationshipTypes.push(X.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:dr(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}.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
-
import{b as W,c as M}from"./NYFL2F5L.js";import"./AGDGDULE.js";import"./FIZMK7GS.js";import{a as B}from"./FGQH46Z2.js";import"./PR4VMSKD.js";import{c as V}from"./SRXUC4QB.js";import{C as D,x as R}from"./NAVK5JJ2.js";import"./OUMTV5H5.js";import{a as z}from"./D7CRICBG.js";import"./63OF33IL.js";import"./3UVQLYUK.js";import{a as U}from"./V66TS2BB.js";import"./GS5JDPZH.js";import"./S6OUM5X2.js";import{a as H}from"./I724KIFI.js";import{a as F}from"./HU527DML.js";import{a as $,b as G}from"./WEBAQIUT.js";import{e as L}from"./XLHYQNAM.js";import{S as J,s as q}from"./7GDMXAF5.js";import{a as E}from"./5XZ5VL42.js";import"./C3VLDYS2.js";import"./A4ZVCRVF.js";import{N as c}from"./N2GN5WOI.js";import"./272R36XK.js";import"./5PV2GUZW.js";export default $arcgis.t(([oe,se,S,C,{property:a,subclass:l}])=>{var ne=Object.defineProperty,ie=Object.getOwnPropertyDescriptor,f=(e,t,r,s)=>{for(var o=s>1?void 0:s?ie(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&ne(t,r,o),o},d=class extends C{constructor(e){super(e)}static fromJSON(e){return new d({id:e.id,sourceAnchorId:e.source_anchor_id,sourceNodeId:e.source_node_id,targetAnchorId:e.target_anchor_id,targetNodeId:e.target_node_id})}};f([a()],d.prototype,"id",2);f([a()],d.prototype,"sourceAnchorId",2);f([a()],d.prototype,"sourceNodeId",2);f([a()],d.prototype,"targetAnchorId",2);f([a()],d.prototype,"targetNodeId",2);d=f([l("Edge")],d);var ae=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,I=(e,t,r,s)=>{for(var o=s>1?void 0:s?ce(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&ae(t,r,o),o},p=class extends C{constructor(e){super(e)}async load(){return await Promise.resolve(this)}compile(e){return{runtimeNode:this.createRuntimeNode(),edges:e.outgoingEdges.map(t=>({from:this.id,to:t.targetNodeId}))}}static fromJSON(e){throw new Error("BaseNode is abstract and cannot be instantiated directly.")}};I([a()],p.prototype,"id",2);I([a()],p.prototype,"label",2);I([a()],p.prototype,"type",2);p=I([l("BaseNode")],p);var de=Object.defineProperty,pe=Object.getOwnPropertyDescriptor,j=(e,t,r,s)=>{for(var o=s>1?void 0:s?pe(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&de(t,r,o),o},ue=e=>e.replace(/_([a-z])/gu,(t,r)=>r.toUpperCase()),h=class extends C{constructor(e){super(e),this.type="arcgis-tool"}async createRuntimeTools(){if(!this.name)throw new Error("ArcgisTool name is required");return[await U(ue(this.name))]}static fromJSON(e){return new h({name:e.name,requireApproval:e.require_approval})}};j([a()],h.prototype,"name",2);j([a()],h.prototype,"requireApproval",2);j([a()],h.prototype,"type",2);h=j([l("ArcgisTool")],h);var me=Object.defineProperty,he=Object.getOwnPropertyDescriptor,K=e=>{throw TypeError(e)},y=(e,t,r,s)=>{for(var o=s>1?void 0:s?he(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&me(t,r,o),o},le=(e,t,r)=>t.has(e)||K("Cannot "+r),ge=(e,t,r)=>t.has(e)?K("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),fe=(e,t,r)=>(le(e,t,"access private method"),r),x,Q,u=class extends p{constructor(e){super(e),ge(this,x),this.type="agent-node"}createRuntimeNode(){let e;return async(t,r)=>{e??=fe(this,x,Q).call(this);let s=await(await e).run(t,r),o=this.outputSchema?.safeParse(s);if(o&&!o.success)throw o.error;let n=o?.data,i=n??s.outputMessage;return{agentExecutionContext:s.agentExecutionContext,...n?{}:{outputMessage:s.outputMessage},status:s.status,summary:s.summary,nodes:{[this.id]:{output:i}}}}}compile(e){let t=e.outgoingEdges[0]?.targetNodeId;return{runtimeNode:this.createRuntimeNode(),edges:[{from:this.id,decide:r=>r.status==="failed"?void 0:t}],schemas:[c.object({output:this.outputSchema??c.string()})]}}static fromJSON(e){let t=new u({id:e.id,label:e.label,prompt:e.prompt?.content,type:"agent-node",modelTier:e.llm_model?.model_tier});return e.structured_output&&(t.outputSchema=B(e.structured_output)),t.tools=e.tools?.filter(r=>r.type==="arcgis_tool").map(r=>h.fromJSON(r)),t}};x=new WeakSet;Q=async function(){let e=this.prompt;if(!e?.trim())throw new Error(`WebAgent agent node "${this.id}" requires a prompt.`);let t=[];if(this.tools)for(let r of this.tools){let s=await r.createRuntimeTools();t.push(...s)}return new z({name:this.id,outputSchema:this.outputSchema,modelTier:this.modelTier,prompt:e,tools:t})};y([a()],u.prototype,"type",2);y([a()],u.prototype,"prompt",2);y([a()],u.prototype,"outputSchema",2);y([a()],u.prototype,"tools",2);y([a()],u.prototype,"modelTier",2);u=y([l("AgentNode")],u);var ye=Object.defineProperty,we=Object.getOwnPropertyDescriptor,T=(e,t,r,s)=>{for(var o=s>1?void 0:s?we(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&ye(t,r,o),o},g=class extends p{constructor(e){super(e),this.type="end-message-node"}createRuntimeNode(){return async e=>{let t=await E.fromTemplate(this.message,{templateFormat:"mustache"}).format(e);return{outputMessage:t,status:"success",summary:t}}}compile(e){return{runtimeNode:this.createRuntimeNode(),edges:[]}}static fromJSON(e){let t=new g({id:e.id,label:e.label,type:"end-message-node"});return t.message=e.message,t}};T([a()],g.prototype,"type",2);T([a()],g.prototype,"message",2);g=T([l("EndMessageNode")],g);var be=Object.defineProperty,Ne=Object.getOwnPropertyDescriptor,X=e=>{throw TypeError(e)},N=(e,t,r,s)=>{for(var o=s>1?void 0:s?Ne(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&be(t,r,o),o},Oe=(e,t,r)=>t.has(e)||X("Cannot "+r),Se=(e,t,r)=>t.has(e)?X("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Z=(e,t,r)=>(Oe(e,t,"access private method"),r),v,Y,ee,m=class extends p{constructor(e){super(e),Se(this,v),this.type="human-in-the-loop-node",this.conditions=[]}createRuntimeNode(){return async(e,t)=>{let r=ve(t,this.id),s=`${r}:${this.id}`,o=V(t);if(o===void 0||!Ie(o,this.response?.type))throw new q({agentId:r,id:s,kind:_e(this.response?.type),message:await Z(this,v,Y).call(this,e),metadata:Z(this,v,ee).call(this,e)});return{nodes:{[this.id]:{output:o}}}}}compile(e){return{runtimeNode:this.createRuntimeNode(),edges:[{from:this.id,decide:t=>{if(!this.conditions.length)return e.outgoingEdges[0]?.targetNodeId;let r=t.nodes?.[this.id]?.output,s=je(r),o=this.conditions.find(n=>n.outcome===s);if(o)return e.outgoingEdges.find(n=>n.sourceAnchorId===o.sourceAnchorId)?.targetNodeId}}]}}static fromJSON(e){let t=new m({id:e.id,label:e.label,type:"human-in-the-loop-node"});return t.message=e.message,t.response=e.response,t.conditions=e.conditions.map(({outcome:r,source_anchor_id:s})=>({outcome:r,sourceAnchorId:s})),t}};v=new WeakSet;Y=async function(e){if(this.message?.source==="generated")throw new Error(`Human-in-the-loop node "${this.id}" does not support generated messages yet.`);let t=this.message?.content;if(!t)throw new Error(`Human-in-the-loop node "${this.id}" requires a message content.`);return await E.fromTemplate(t,{templateFormat:"mustache"}).format(e)};ee=function(e){let t=this.response;if(!t||t.type==="confirmation"||t.type==="textInput")return;let r=t.choices;return r?.source==="fixed"?r.items?.map(s=>s.value??s.label??""):r?.source==="reference"?Ae(e,r.reference)?.map(String):void 0};N([a()],m.prototype,"type",2);N([a()],m.prototype,"message",2);N([a()],m.prototype,"response",2);N([a()],m.prototype,"conditions",2);m=N([l("HumanInTheLoopNode")],m);function ve(e,t){let r=e?.configurable?.agentId;return typeof r=="string"&&r?r:t}function _e(e){switch(e){case"singleSelect":return"singleSelection";case"multipleSelect":return"multipleSelection";case"textInput":return"textInput";default:return"booleanChoice"}}function Ie(e,t){switch(t){case"confirmation":return typeof e=="boolean";case"singleSelect":return typeof e=="string"||Array.isArray(e)&&e.length===1&&typeof e[0]=="string";case"multipleSelect":return Array.isArray(e)&&e.every(r=>typeof r=="string");case"textInput":return typeof e=="string";default:return!0}}function je(e){return e===!1?"dismissed":"confirmed"}function Ae(e,t){if(!t)return;let r=t.split(".").reduce((s,o)=>{if(s&&typeof s=="object"&&o in s)return s[o]},e);return Array.isArray(r)?r:typeof r=="string"?[r]:void 0}var Ee=Object.defineProperty,Je=Object.getOwnPropertyDescriptor,te=(e,t,r,s)=>{for(var o=s>1?void 0:s?Je(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&Ee(t,r,o),o},b=class extends p{constructor(e){super(e),this.type="start-node"}createRuntimeNode(){return e=>({question:e.agentExecutionContext.userRequest})}static fromJSON(e){return new b({id:e.id,label:e.label,type:"start-node"})}};te([a()],b.prototype,"type",2);b=te([l("StartNode")],b);function xe(e){switch(e.type){case"agent_node":return u.fromJSON(e);case"end_message_node":return g.fromJSON(e);case"human_input_node":return m.fromJSON(e);case"start_node":return b.fromJSON(e);default:throw new Error(`WebAgent node "${e.id}" uses unsupported type "${e.type}".`)}}function Pe(e={}){let t=Object.keys(e);if($(t),t.includes("nodes"))throw new Error("node state cannot define reserved field: nodes.");let r=G(e);return J.Root({...r,nodes:J({reducer:(s,o)=>({...s,...o}),default:()=>({})}),...L()})}function re(e,t={}){let r=new Set;for(let o of e)for(let n of Object.keys(o.shape??{}))n!=="nodes"&&r.add(n);let s=Object.fromEntries([...r].map(o=>[o,t[o]]));for(let[o,n]of Object.entries(t))s[o]=n;return Pe(s)}var P=class e{constructor(t,r,s){this.sourceJSON=t,this.edges=r,this.nodes=s,this._loaded=!1}static fromJSON(t){return new e(t,t.graph.edges.map(r=>d.fromJSON(r)),t.graph.nodes.map(r=>xe(r)))}async load(){return this._loadPromise??=Promise.all(this.nodes.map(async t=>await t.load())).then(()=>{this._loaded=!0}),await this._loadPromise,this}getSchemas(){let t=Object.fromEntries(this._getNodeCompilations().flatMap((r,s)=>{let o=this.nodes[s];return r.schemas?.map(n=>[o.id,n])??[]}));return[c.object({loopCounts:c.record(c.string(),c.number()).optional(),nodes:c.object(t).partial().optional(),question:c.string().optional(),variables:this._getVariablesSchema()})]}generate(){this._assertLoaded(),this._nodeCompilations=void 0;let t=this._getNodeCompilations(),r=Object.fromEntries(this.sourceJSON.variables.map(({key:w,value:A})=>[w,A])),s=re(this.getSchemas(),{variables:r}),o=this.nodes.find(w=>w.type==="start-node")?.id,n={},i=[];for(let[w,A]of this.nodes.entries()){let O=t[w];O&&(O.runtimeNode&&(n[A.id]=O.runtimeNode),i.push(...O.edges))}return{createGraph:()=>H(n,i,s,{entryNode:o}),workspace:s}}_assertLoaded(){if(!this._loaded)throw new Error("AgenticWorkflowRuntime must be loaded before it can generate a graph.")}_getNodeCompilations(){return this._assertLoaded(),this._nodeCompilations??=this.nodes.map(t=>t.compile({outgoingEdges:this.edges.filter(r=>r.sourceNodeId===t.id)}))}_getVariablesSchema(){return c.object(Object.fromEntries(this.sourceJSON.variables.map(({key:t})=>[t,c.unknown()])))}},_=class extends F{constructor(t){super(),this._createUnloadedGraph=()=>{throw new Error("WebAgent must be loaded before it can run.")},Object.assign(this,t)}async load(){if(this.portalItem){try{await this.portalItem.load()}catch(s){throw new S("web-agent:load-portal-item","Failed to load portal item",{error:s})}let r=await this.portalItem.fetchData();if(this.sourceJSON=r,!this.portalItem.title)throw new S("web-agent:missing-title","The portal item is missing a title")}if(!this.sourceJSON)throw new S("web-agent:missing-source-json","The source JSON is missing");if(!this.sourceJSON.description)throw new S("web-agent:missing-description","The source JSON is missing a description");let t=P.fromJSON(this.sourceJSON);return await t.load(),this._runtime=t,this.description=this.sourceJSON.description,this.name=this.portalItem?.title??`web-agent-${Date.now()}`,this.generate(),this}generate(){if(!this._runtime){this.workspace=re([]),this.createGraph=this._createUnloadedGraph;return}let{createGraph:t,workspace:r}=this._runtime.generate();this.workspace=r,this.createGraph=t}},k=class extends R{static{this.properties={agent:0,context:0,itemId:1,workflow:0}}#e;async getContext(){return W(this.context)?await this.context():this.context}async load(){let t;if(this.itemId){let r=se.getDefault();t=new _({portalItem:new oe({id:this.itemId,portal:r})})}else this.workflow&&(t=new _({sourceJSON:this.workflow}));if(t&&(await t.load(),this.agent=t),!this.agent)throw new Error("Failed to initialize the assistant agent because the agent registration is missing.");this.#e=M(this)}disconnectedCallback(){this.#e?.unregister(this.agent.id),super.disconnectedCallback()}};D("arcgis-assistant-agent",k);return k},"portal/PortalItem","portal/Portal","core/Error","core/Accessor","core/accessorSupport/decorators")
|
|
2
|
+
import{b as W,c as M}from"./NYFL2F5L.js";import"./AGDGDULE.js";import"./FIZMK7GS.js";import{a as B}from"./FGQH46Z2.js";import"./PR4VMSKD.js";import{c as V}from"./OVH4S4ZB.js";import{C as D,x as R}from"./NAVK5JJ2.js";import"./OUMTV5H5.js";import{a as z}from"./D7CRICBG.js";import"./63OF33IL.js";import"./3UVQLYUK.js";import{a as U}from"./H653UVNH.js";import"./GS5JDPZH.js";import"./S6OUM5X2.js";import{a as H}from"./I724KIFI.js";import{a as F}from"./HU527DML.js";import{a as $,b as G}from"./WEBAQIUT.js";import{e as L}from"./XLHYQNAM.js";import{S as J,s as q}from"./7GDMXAF5.js";import{a as E}from"./5XZ5VL42.js";import"./C3VLDYS2.js";import"./A4ZVCRVF.js";import{N as c}from"./N2GN5WOI.js";import"./272R36XK.js";import"./5PV2GUZW.js";export default $arcgis.t(([oe,se,S,C,{property:a,subclass:l}])=>{var ne=Object.defineProperty,ie=Object.getOwnPropertyDescriptor,f=(e,t,r,s)=>{for(var o=s>1?void 0:s?ie(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&ne(t,r,o),o},d=class extends C{constructor(e){super(e)}static fromJSON(e){return new d({id:e.id,sourceAnchorId:e.source_anchor_id,sourceNodeId:e.source_node_id,targetAnchorId:e.target_anchor_id,targetNodeId:e.target_node_id})}};f([a()],d.prototype,"id",2);f([a()],d.prototype,"sourceAnchorId",2);f([a()],d.prototype,"sourceNodeId",2);f([a()],d.prototype,"targetAnchorId",2);f([a()],d.prototype,"targetNodeId",2);d=f([l("Edge")],d);var ae=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,I=(e,t,r,s)=>{for(var o=s>1?void 0:s?ce(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&ae(t,r,o),o},p=class extends C{constructor(e){super(e)}async load(){return await Promise.resolve(this)}compile(e){return{runtimeNode:this.createRuntimeNode(),edges:e.outgoingEdges.map(t=>({from:this.id,to:t.targetNodeId}))}}static fromJSON(e){throw new Error("BaseNode is abstract and cannot be instantiated directly.")}};I([a()],p.prototype,"id",2);I([a()],p.prototype,"label",2);I([a()],p.prototype,"type",2);p=I([l("BaseNode")],p);var de=Object.defineProperty,pe=Object.getOwnPropertyDescriptor,j=(e,t,r,s)=>{for(var o=s>1?void 0:s?pe(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&de(t,r,o),o},ue=e=>e.replace(/_([a-z])/gu,(t,r)=>r.toUpperCase()),h=class extends C{constructor(e){super(e),this.type="arcgis-tool"}async createRuntimeTools(){if(!this.name)throw new Error("ArcgisTool name is required");return[await U(ue(this.name))]}static fromJSON(e){return new h({name:e.name,requireApproval:e.require_approval})}};j([a()],h.prototype,"name",2);j([a()],h.prototype,"requireApproval",2);j([a()],h.prototype,"type",2);h=j([l("ArcgisTool")],h);var me=Object.defineProperty,he=Object.getOwnPropertyDescriptor,K=e=>{throw TypeError(e)},y=(e,t,r,s)=>{for(var o=s>1?void 0:s?he(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&me(t,r,o),o},le=(e,t,r)=>t.has(e)||K("Cannot "+r),ge=(e,t,r)=>t.has(e)?K("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),fe=(e,t,r)=>(le(e,t,"access private method"),r),x,Q,u=class extends p{constructor(e){super(e),ge(this,x),this.type="agent-node"}createRuntimeNode(){let e;return async(t,r)=>{e??=fe(this,x,Q).call(this);let s=await(await e).run(t,r),o=this.outputSchema?.safeParse(s);if(o&&!o.success)throw o.error;let n=o?.data,i=n??s.outputMessage;return{agentExecutionContext:s.agentExecutionContext,...n?{}:{outputMessage:s.outputMessage},status:s.status,summary:s.summary,nodes:{[this.id]:{output:i}}}}}compile(e){let t=e.outgoingEdges[0]?.targetNodeId;return{runtimeNode:this.createRuntimeNode(),edges:[{from:this.id,decide:r=>r.status==="failed"?void 0:t}],schemas:[c.object({output:this.outputSchema??c.string()})]}}static fromJSON(e){let t=new u({id:e.id,label:e.label,prompt:e.prompt?.content,type:"agent-node",modelTier:e.llm_model?.model_tier});return e.structured_output&&(t.outputSchema=B(e.structured_output)),t.tools=e.tools?.filter(r=>r.type==="arcgis_tool").map(r=>h.fromJSON(r)),t}};x=new WeakSet;Q=async function(){let e=this.prompt;if(!e?.trim())throw new Error(`WebAgent agent node "${this.id}" requires a prompt.`);let t=[];if(this.tools)for(let r of this.tools){let s=await r.createRuntimeTools();t.push(...s)}return new z({name:this.id,outputSchema:this.outputSchema,modelTier:this.modelTier,prompt:e,tools:t})};y([a()],u.prototype,"type",2);y([a()],u.prototype,"prompt",2);y([a()],u.prototype,"outputSchema",2);y([a()],u.prototype,"tools",2);y([a()],u.prototype,"modelTier",2);u=y([l("AgentNode")],u);var ye=Object.defineProperty,we=Object.getOwnPropertyDescriptor,T=(e,t,r,s)=>{for(var o=s>1?void 0:s?we(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&ye(t,r,o),o},g=class extends p{constructor(e){super(e),this.type="end-message-node"}createRuntimeNode(){return async e=>{let t=await E.fromTemplate(this.message,{templateFormat:"mustache"}).format(e);return{outputMessage:t,status:"success",summary:t}}}compile(e){return{runtimeNode:this.createRuntimeNode(),edges:[]}}static fromJSON(e){let t=new g({id:e.id,label:e.label,type:"end-message-node"});return t.message=e.message,t}};T([a()],g.prototype,"type",2);T([a()],g.prototype,"message",2);g=T([l("EndMessageNode")],g);var be=Object.defineProperty,Ne=Object.getOwnPropertyDescriptor,X=e=>{throw TypeError(e)},N=(e,t,r,s)=>{for(var o=s>1?void 0:s?Ne(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&be(t,r,o),o},Oe=(e,t,r)=>t.has(e)||X("Cannot "+r),Se=(e,t,r)=>t.has(e)?X("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Z=(e,t,r)=>(Oe(e,t,"access private method"),r),v,Y,ee,m=class extends p{constructor(e){super(e),Se(this,v),this.type="human-in-the-loop-node",this.conditions=[]}createRuntimeNode(){return async(e,t)=>{let r=ve(t,this.id),s=`${r}:${this.id}`,o=V(t);if(o===void 0||!Ie(o,this.response?.type))throw new q({agentId:r,id:s,kind:_e(this.response?.type),message:await Z(this,v,Y).call(this,e),metadata:Z(this,v,ee).call(this,e)});return{nodes:{[this.id]:{output:o}}}}}compile(e){return{runtimeNode:this.createRuntimeNode(),edges:[{from:this.id,decide:t=>{if(!this.conditions.length)return e.outgoingEdges[0]?.targetNodeId;let r=t.nodes?.[this.id]?.output,s=je(r),o=this.conditions.find(n=>n.outcome===s);if(o)return e.outgoingEdges.find(n=>n.sourceAnchorId===o.sourceAnchorId)?.targetNodeId}}]}}static fromJSON(e){let t=new m({id:e.id,label:e.label,type:"human-in-the-loop-node"});return t.message=e.message,t.response=e.response,t.conditions=e.conditions.map(({outcome:r,source_anchor_id:s})=>({outcome:r,sourceAnchorId:s})),t}};v=new WeakSet;Y=async function(e){if(this.message?.source==="generated")throw new Error(`Human-in-the-loop node "${this.id}" does not support generated messages yet.`);let t=this.message?.content;if(!t)throw new Error(`Human-in-the-loop node "${this.id}" requires a message content.`);return await E.fromTemplate(t,{templateFormat:"mustache"}).format(e)};ee=function(e){let t=this.response;if(!t||t.type==="confirmation"||t.type==="textInput")return;let r=t.choices;return r?.source==="fixed"?r.items?.map(s=>s.value??s.label??""):r?.source==="reference"?Ae(e,r.reference)?.map(String):void 0};N([a()],m.prototype,"type",2);N([a()],m.prototype,"message",2);N([a()],m.prototype,"response",2);N([a()],m.prototype,"conditions",2);m=N([l("HumanInTheLoopNode")],m);function ve(e,t){let r=e?.configurable?.agentId;return typeof r=="string"&&r?r:t}function _e(e){switch(e){case"singleSelect":return"singleSelection";case"multipleSelect":return"multipleSelection";case"textInput":return"textInput";default:return"booleanChoice"}}function Ie(e,t){switch(t){case"confirmation":return typeof e=="boolean";case"singleSelect":return typeof e=="string"||Array.isArray(e)&&e.length===1&&typeof e[0]=="string";case"multipleSelect":return Array.isArray(e)&&e.every(r=>typeof r=="string");case"textInput":return typeof e=="string";default:return!0}}function je(e){return e===!1?"dismissed":"confirmed"}function Ae(e,t){if(!t)return;let r=t.split(".").reduce((s,o)=>{if(s&&typeof s=="object"&&o in s)return s[o]},e);return Array.isArray(r)?r:typeof r=="string"?[r]:void 0}var Ee=Object.defineProperty,Je=Object.getOwnPropertyDescriptor,te=(e,t,r,s)=>{for(var o=s>1?void 0:s?Je(t,r):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(s?i(t,r,o):i(o))||o);return s&&o&&Ee(t,r,o),o},b=class extends p{constructor(e){super(e),this.type="start-node"}createRuntimeNode(){return e=>({question:e.agentExecutionContext.userRequest})}static fromJSON(e){return new b({id:e.id,label:e.label,type:"start-node"})}};te([a()],b.prototype,"type",2);b=te([l("StartNode")],b);function xe(e){switch(e.type){case"agent_node":return u.fromJSON(e);case"end_message_node":return g.fromJSON(e);case"human_input_node":return m.fromJSON(e);case"start_node":return b.fromJSON(e);default:throw new Error(`WebAgent node "${e.id}" uses unsupported type "${e.type}".`)}}function Pe(e={}){let t=Object.keys(e);if($(t),t.includes("nodes"))throw new Error("node state cannot define reserved field: nodes.");let r=G(e);return J.Root({...r,nodes:J({reducer:(s,o)=>({...s,...o}),default:()=>({})}),...L()})}function re(e,t={}){let r=new Set;for(let o of e)for(let n of Object.keys(o.shape??{}))n!=="nodes"&&r.add(n);let s=Object.fromEntries([...r].map(o=>[o,t[o]]));for(let[o,n]of Object.entries(t))s[o]=n;return Pe(s)}var P=class e{constructor(t,r,s){this.sourceJSON=t,this.edges=r,this.nodes=s,this._loaded=!1}static fromJSON(t){return new e(t,t.graph.edges.map(r=>d.fromJSON(r)),t.graph.nodes.map(r=>xe(r)))}async load(){return this._loadPromise??=Promise.all(this.nodes.map(async t=>await t.load())).then(()=>{this._loaded=!0}),await this._loadPromise,this}getSchemas(){let t=Object.fromEntries(this._getNodeCompilations().flatMap((r,s)=>{let o=this.nodes[s];return r.schemas?.map(n=>[o.id,n])??[]}));return[c.object({loopCounts:c.record(c.string(),c.number()).optional(),nodes:c.object(t).partial().optional(),question:c.string().optional(),variables:this._getVariablesSchema()})]}generate(){this._assertLoaded(),this._nodeCompilations=void 0;let t=this._getNodeCompilations(),r=Object.fromEntries(this.sourceJSON.variables.map(({key:w,value:A})=>[w,A])),s=re(this.getSchemas(),{variables:r}),o=this.nodes.find(w=>w.type==="start-node")?.id,n={},i=[];for(let[w,A]of this.nodes.entries()){let O=t[w];O&&(O.runtimeNode&&(n[A.id]=O.runtimeNode),i.push(...O.edges))}return{createGraph:()=>H(n,i,s,{entryNode:o}),workspace:s}}_assertLoaded(){if(!this._loaded)throw new Error("AgenticWorkflowRuntime must be loaded before it can generate a graph.")}_getNodeCompilations(){return this._assertLoaded(),this._nodeCompilations??=this.nodes.map(t=>t.compile({outgoingEdges:this.edges.filter(r=>r.sourceNodeId===t.id)}))}_getVariablesSchema(){return c.object(Object.fromEntries(this.sourceJSON.variables.map(({key:t})=>[t,c.unknown()])))}},_=class extends F{constructor(t){super(),this._createUnloadedGraph=()=>{throw new Error("WebAgent must be loaded before it can run.")},Object.assign(this,t)}async load(){if(this.portalItem){try{await this.portalItem.load()}catch(s){throw new S("web-agent:load-portal-item","Failed to load portal item",{error:s})}let r=await this.portalItem.fetchData();if(this.sourceJSON=r,!this.portalItem.title)throw new S("web-agent:missing-title","The portal item is missing a title")}if(!this.sourceJSON)throw new S("web-agent:missing-source-json","The source JSON is missing");if(!this.sourceJSON.description)throw new S("web-agent:missing-description","The source JSON is missing a description");let t=P.fromJSON(this.sourceJSON);return await t.load(),this._runtime=t,this.description=this.sourceJSON.description,this.name=this.portalItem?.title??`web-agent-${Date.now()}`,this.generate(),this}generate(){if(!this._runtime){this.workspace=re([]),this.createGraph=this._createUnloadedGraph;return}let{createGraph:t,workspace:r}=this._runtime.generate();this.workspace=r,this.createGraph=t}},k=class extends R{static{this.properties={agent:0,context:0,itemId:1,workflow:0}}#e;async getContext(){return W(this.context)?await this.context():this.context}async load(){let t;if(this.itemId){let r=se.getDefault();t=new _({portalItem:new oe({id:this.itemId,portal:r})})}else this.workflow&&(t=new _({sourceJSON:this.workflow}));if(t&&(await t.load(),this.agent=t),!this.agent)throw new Error("Failed to initialize the assistant agent because the agent registration is missing.");this.#e=M(this)}disconnectedCallback(){this.#e?.unregister(this.agent.id),super.disconnectedCallback()}};D("arcgis-assistant-agent",k);return k},"portal/PortalItem","portal/Portal","core/Error","core/Accessor","core/accessorSupport/decorators")
|