@arcgis/ai-components 5.1.0-next.123 → 5.1.0-next.124
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-utils/LLMAgent.js +22 -22
- package/dist/cdn/4AUW6FQR.js +16 -0
- package/dist/cdn/{RNMI3HNM.js → CKVNSPM3.js} +18 -5
- package/dist/cdn/{SCT3365V.js → EC62ZHZL.js} +1 -0
- package/dist/cdn/{FMVJGP7T.js → GZ5ESQMU.js} +1 -1
- package/dist/cdn/{ABWPQMDL.js → JIX3GXJE.js} +1 -1
- package/dist/cdn/{JNHKMVKF.js → KYXSLPKU.js} +1 -1
- package/dist/cdn/{BXKPX3C7.js → LUWP3MUX.js} +0 -1
- package/dist/cdn/{X4F6C3WD.js → O6HYES24.js} +1 -1
- package/dist/cdn/Q26B42YD.js +3 -0
- package/dist/cdn/{AKK4LRSR.js → UJEOE2LU.js} +13 -13
- package/dist/cdn/{PK5FREHI.js → YRICFRVO.js} +24 -24
- package/dist/cdn/{NKSU25AM.js → YVHZJZZ7.js} +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/adapter.js +107 -97
- package/dist/chunks/dataExplorationGraph.js +95 -86
- package/dist/chunks/data_explore_query_prompt.js +18 -5
- package/dist/chunks/generateLayerDescriptions.js +223 -203
- package/dist/chunks/intent_prompt.js +0 -1
- package/dist/chunks/orchestrator.js +240 -201
- package/dist/chunks/summarize_query_response_prompt.js +1 -0
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/utils/index.d.ts +8 -3
- package/dist/utils/index.js +22 -18
- package/package.json +4 -4
- package/dist/cdn/CVHHLBN3.js +0 -16
- package/dist/cdn/RTU2IR5Z.js +0 -3
|
@@ -16,10 +16,10 @@ import { convertToLangChainMiddlewares as l } from "./middlewares/middleware.js"
|
|
|
16
16
|
import { c as y } from "../chunks/graph.js";
|
|
17
17
|
import { c as T } from "../chunks/state.js";
|
|
18
18
|
import { c as d, h as M, g as x } from "../chunks/utils.js";
|
|
19
|
-
var P = Object.defineProperty, b = Object.getOwnPropertyDescriptor, n = (t,
|
|
20
|
-
for (var o = e > 1 ? void 0 : e ? b(
|
|
21
|
-
(i = t[p]) && (o = (e ? i(
|
|
22
|
-
return e && o && P(
|
|
19
|
+
var P = Object.defineProperty, b = Object.getOwnPropertyDescriptor, n = (t, r, s, e) => {
|
|
20
|
+
for (var o = e > 1 ? void 0 : e ? b(r, s) : r, p = t.length - 1, i; p >= 0; p--)
|
|
21
|
+
(i = t[p]) && (o = (e ? i(r, s, o) : i(o)) || o);
|
|
22
|
+
return e && o && P(r, s, o), o;
|
|
23
23
|
};
|
|
24
24
|
let a = class extends v {
|
|
25
25
|
//#region Lifecycle
|
|
@@ -53,52 +53,52 @@ let a = class extends v {
|
|
|
53
53
|
generate() {
|
|
54
54
|
const t = T(this.getSchemas());
|
|
55
55
|
this._set("workspace", t);
|
|
56
|
-
const
|
|
56
|
+
const r = this.id, s = { [r]: this._invoke.bind(this) }, e = [{ from: r, decide: () => {
|
|
57
57
|
} }];
|
|
58
58
|
this._set(
|
|
59
59
|
"createGraph",
|
|
60
|
-
() => y(
|
|
60
|
+
() => y(s, e, t, {
|
|
61
61
|
agent: this,
|
|
62
|
-
entryNode:
|
|
62
|
+
entryNode: r,
|
|
63
63
|
middlewares: this.middlewares
|
|
64
64
|
})
|
|
65
65
|
);
|
|
66
66
|
}
|
|
67
67
|
//#endregion
|
|
68
68
|
//#region Private Methods
|
|
69
|
-
async _invoke(t,
|
|
69
|
+
async _invoke(t, r) {
|
|
70
70
|
try {
|
|
71
|
-
return this.outputSchema ? await this._invokeStructured(t,
|
|
72
|
-
} catch (
|
|
73
|
-
if (f(
|
|
74
|
-
throw
|
|
75
|
-
const e =
|
|
71
|
+
return this.outputSchema ? await this._invokeStructured(t, r) : await this._invokeUnstructured(t, r);
|
|
72
|
+
} catch (s) {
|
|
73
|
+
if (f(s))
|
|
74
|
+
throw s;
|
|
75
|
+
const e = s instanceof Error ? s.message : String(s);
|
|
76
76
|
return d({ outputMessage: e }, "failed", e);
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
|
-
async _invokeStructured(t,
|
|
79
|
+
async _invokeStructured(t, r) {
|
|
80
80
|
if (!this.outputSchema)
|
|
81
81
|
throw new Error("Output schema is required for structured invocation.");
|
|
82
82
|
const e = await h({
|
|
83
|
-
model: await u(this.modelTier),
|
|
83
|
+
model: await u({ modelTier: this.modelTier }),
|
|
84
84
|
systemPrompt: await this._getPromptWithInputVariables(t),
|
|
85
85
|
tools: this._getTools(),
|
|
86
86
|
checkpointer: !0,
|
|
87
87
|
middleware: l(this.middlewares),
|
|
88
88
|
responseFormat: this.outputSchema
|
|
89
|
-
}).invoke({ messages: t.agentExecutionContext.messages },
|
|
89
|
+
}).invoke({ messages: t.agentExecutionContext.messages }, r);
|
|
90
90
|
if (!("structuredResponse" in e) || e.structuredResponse === void 0)
|
|
91
91
|
throw new Error("LLMAgent did not receive structured output from createAgent.");
|
|
92
92
|
return M(e.structuredResponse, this.outputSchema, e.messages);
|
|
93
93
|
}
|
|
94
|
-
async _invokeUnstructured(t,
|
|
94
|
+
async _invokeUnstructured(t, r) {
|
|
95
95
|
const o = (await h({
|
|
96
|
-
model: await u(this.modelTier),
|
|
96
|
+
model: await u({ modelTier: this.modelTier }),
|
|
97
97
|
systemPrompt: await this._getPromptWithInputVariables(t),
|
|
98
98
|
tools: this._getTools(),
|
|
99
99
|
checkpointer: !0,
|
|
100
100
|
middleware: l(this.middlewares)
|
|
101
|
-
}).invoke({ messages: t.agentExecutionContext.messages },
|
|
101
|
+
}).invoke({ messages: t.agentExecutionContext.messages }, r)).messages, i = o.at(-1)?.content ?? "", c = typeof i == "string" ? i : JSON.stringify(i), g = c.trim() || "LLMAgent completed.";
|
|
102
102
|
return d(
|
|
103
103
|
{ agentExecutionContext: { ...t.agentExecutionContext, messages: o }, outputMessage: c },
|
|
104
104
|
"success",
|
|
@@ -106,10 +106,10 @@ let a = class extends v {
|
|
|
106
106
|
);
|
|
107
107
|
}
|
|
108
108
|
async _getPromptWithInputVariables(t) {
|
|
109
|
-
const
|
|
109
|
+
const r = x(t, this.inputSchema);
|
|
110
110
|
for (const { outputKey: e } of this.middlewares)
|
|
111
|
-
e && (
|
|
112
|
-
return await S.fromTemplate(this.prompt).format(
|
|
111
|
+
e && (r[String(e)] = t[e]);
|
|
112
|
+
return await S.fromTemplate(this.prompt).format(r);
|
|
113
113
|
}
|
|
114
114
|
_getTools() {
|
|
115
115
|
return this.tools?.map((t) => t.getTool()) ?? [];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import d from"./JIX3GXJE.js";import c from"./UJEOE2LU.js";import a from"./YRICFRVO.js";import{Fb as k,Q as V,a as N,b as E}from"./V7BWJN43.js";import{a as D,c as O}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as b,y as A}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,K,X,,,{f:n,l:z,n:T},{C:R,D:G,E:L,F:P,G:F,H:U,a:j,m:S,n:M,o:p,p:Q},C])=>{var Y=async(e,t)=>(await n({text:"Exiting Data Exploration agent"},t),e),Z=async(e,t)=>{await n({text:"Requesting LLM for layer filter results"},t);let a=await S("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:c,userTimezoneOffset:l}=L(),s={layerFieldInfo:e.layerFieldInfo,userTimezone:c,userTimezoneOffset:l,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},r=await T({promptText:a,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:s,tools:F}),i=[...e.dataExplorationMessages,r];if(!((r.tool_calls?.length??0)>0))return await n({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:i};let u=[...i,r],o=r.content.toString();return await C(r,t),{...e,dataExplorationMessages:u,outputMessage:o}},ee=async(e,t)=>{await n({text:"Requesting LLM for layer query results"},t);let a=await S("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:c,userTimezoneOffset:l}=L(),s=e.agentExecutionContext.sharedState.lastNavigatedFeatures,r=s&&typeof s=="object"&&"value"in s?s.value:s,i="none";if(r!=null)try{i=JSON.stringify(r)}catch{i="none"}let u={layerFieldInfo:e.layerFieldInfo,userTimezone:c,userTimezoneOffset:l,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,lastNavigatedFeatures:i},o=await T({promptText:a,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:u,tools:P}),m=o.content.toString();return await C(o,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,o],outputMessage:m,status:"success",summary:m?M(m):"Query executed."}},te=async(e,t)=>{try{await n({text:"Requesting LLM for summary on query results"},t);let a=await S("summarize_query_response_prompt"),c={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},l=await z({promptText:a,modelTier:"fast",messages:e.dataExplorationMessages,inputVariables:c}),s=typeof l=="string"?l:l.content,r=new V(s);await n({text:`Received response from LLM: ${s}`},t);let i=s;return{...e,outputMessage:i,status:"success",summary:i?M(i):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,r]}}catch(a){throw await n({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${a instanceof Error?a.message:String(a)}`)}};async function ae(e,t){let a=await new j(F).invoke({messages:e.dataExplorationMessages},t);return await n({text:`Finished executing layer filter tool: ${a.messages.map(c=>c.content).join(", ")}`},t),{...e}}var se=10,re=["string","small-integer","integer"],ie=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:c=!0}={})=>{let l=null,s=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(l=await K({layer:e,field:t.name}));let r=t.domain?.type==="coded-value"?t.domain:null;c&&(re.includes(t.type)||r)&&(s=(await X({layer:e,field:t.name})).uniqueValueInfos.sort((i,u)=>u.count-i.count).slice(0,se),r&&(s=s.map(i=>({...i,value:r.getName(i.value)??i.value}))))}}catch(r){console.error(`Error fetching statistics for field ${t.name}:`,r)}return{summaryStatistics:l,uniqueValues:s}};function oe(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function ne(e,t,a,c=!0){let l=[],s=[],r=[];for(let i of e){let u=function(g){let d=t.get(g)?.layerItem;return d?[d.name&&`Name: ${d.name}`,d.title&&`Title: ${d.title}`,d.description&&`Description: ${d.description}`].filter(Boolean).join(" | "):g},{layerId:o,results:m}=i,f=a.map?.allLayers.find(g=>g.id===o),w=t.get(o)?.fieldRegistry;if(!w)continue;let h=l.find(g=>g.layerId===o);h||(h={layerId:o,layerSummary:u(o),fieldInfos:[]},l.push(h));for(let g of m){let d=w.get(g.name);if(!d)continue;let y=d.statistics,v=c&&!y?.summaryStatistics,q=oe(d.type,d.domain?.type)&&!y?.uniqueValues,_=v||q;if(r.push({layerId:o,fieldName:d.name,didFetchStatistics:_}),_){let J=ie(f,d,{includeSummaryStatistics:v,includeUniqueValues:q}).then($=>{let x={summaryStatistics:y?.summaryStatistics??null,uniqueValues:y?.uniqueValues??null};v&&(x.summaryStatistics=$.summaryStatistics),q&&(x.uniqueValues=$.uniqueValues),w.set(d.name,{...d,statistics:x}),d.statistics=x});s.push(J)}h.fieldInfos.push(d)}}return await Promise.all(s),{layerFieldInfo:l,didFetchStatistics:s.length>0,fieldStatisticsFetchStatus:r}}var W=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function le(e,t){return W.test(e)||W.test(t)}var de=async(e,t)=>{try{await n({text:"Preparing field information for vector search results"},t);let a=p(t,"layersAndFieldsRegistry"),{mapView:c}=G(t),{assignedTask:l,userRequest:s}=e.agentExecutionContext,r=le(l,s),{layerFieldInfo:i,didFetchStatistics:u,fieldStatisticsFetchStatus:o}=await ne(e.vectorSearchFieldResults,a,c,r);u?await n({text:"Statistics fetched"},t):await n({text:"Statistics skipped"},t);for(let m of o)await n({text:` - ${m.fieldName} - stats ${m.didFetchStatistics?"fetched":"skipped"}`},t);return await n({text:"Field information prepared"},t),{...e,layerFieldInfo:i}}catch(a){throw await n({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${a instanceof Error?a.message:String(a)}`)}},B=.7,ce=10,ue=async(e,t)=>{try{await n({text:"Similarity search to find fields"},t);let a=p(t,"fieldSearch"),c=p(t,"layersAndFieldsRegistry"),l=p(t,"embeddingCache"),s=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:B,topResults:ce,embeddingCache:l}),r=s.map(({layerId:u,results:o})=>{let m=o.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
|
|
3
|
+
`);return`${c.get(u)?.layerItem.name??u}:
|
|
4
|
+
${m}`}).join(`
|
|
5
|
+
`),i;return s.length>0?i=`Vector search completed. Matching layers and fields with scores:
|
|
6
|
+
${r}`:i=`No vector search results found for score over ${B}.`,await n({text:i},t),{...e,vectorSearchFieldResults:s}}catch(a){throw await n({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},me=.7,ge=async(e,t)=>{try{await n({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let a=p(t,"layerSearch"),c=p(t,"layersAndFieldsRegistry"),l=p(t,"embeddingCache"),s=await a.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:me,embeddingCache:l}),r=s.map(o=>o.id),i=s.map(({id:o,score:m})=>`${c.get(o)?.layerItem.name??o} (${m.toFixed(2)})`).join(`
|
|
7
|
+
`),u;return r.length>0?u=`Vector search completed. Matching layers with scores:
|
|
8
|
+
${i}`:u="Vector search completed. No matching layers found.",await n({text:u},t),{...e,vectorSearchLayerIds:r}}catch(a){throw await n({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},pe=(e,t)=>Q(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),fe=()=>new k(R).addNode("requireDataExplorationServices",pe).addNode("vectorSearchLayers",ge).addNode("vectorSearchFields",ue).addNode("fieldStatistics",de).addNode("queryAgent",ee).addNode("queryTools",U).addNode("summarizeQueryResponseLLM",te).addNode("filterAgent",Z).addNode("filterTools",ae).addNode("earlyExit",Y).addEdge(N,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),he=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
|
|
9
|
+
The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
|
|
10
|
+
_Example: “Only show stations where Brand is Shell”_
|
|
11
|
+
_Example: “Make Shell stations stand out on the map”_
|
|
12
|
+
_Example: “Gray out all stations that aren’t Shell”_
|
|
13
|
+
This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
|
|
14
|
+
_Example: “How many features are there?”_
|
|
15
|
+
_Example: “What’s the average population?”_
|
|
16
|
+
_Example: “Which values are in the status field?”_`,H={id:"dataExploration",name:"Data Exploration Agent",description:he,createGraph:fe,workspace:R};var I=class extends b{constructor(){super(...arguments),this.agent=H}static{this.properties={referenceElement:1}}#e;getContext(){if(!this.#e)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#e}}load(){this.#e=D(this,"arcgis-assistant-data-exploration-agent"),O(this)}};A("arcgis-assistant-data-exploration-agent",I);return I},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,c,d)
|
|
@@ -36,11 +36,26 @@ Latest user request:
|
|
|
36
36
|
Prior steps:
|
|
37
37
|
{priorSteps}
|
|
38
38
|
|
|
39
|
+
Last navigated features from shared state (if available):
|
|
40
|
+
{lastNavigatedFeatures}
|
|
41
|
+
|
|
39
42
|
Use the assigned task as the primary instruction for the current query.
|
|
40
43
|
Use the latest user request as supporting context when needed.
|
|
41
44
|
Use prior steps only when the assigned task or user request clearly depends on earlier results.
|
|
45
|
+
Use lastNavigatedFeatures as authoritative context for map-navigation references when present.
|
|
42
46
|
Use chat history only when necessary to understand conversational references, and do not override the assigned task.
|
|
43
47
|
|
|
48
|
+
### Anchor selection rule (strict, single source of truth)
|
|
49
|
+
|
|
50
|
+
When the request is referential (for example: "this", "it", "that", "those", "them", "of those", "the same one(s)"), choose exactly one anchor using this priority order:
|
|
51
|
+
|
|
52
|
+
1. Explicit entity named in the current request (if present)
|
|
53
|
+
2. \`lastNavigatedFeatures\` (if present)
|
|
54
|
+
3. The immediately previous successful relevant step from \`priorSteps\`
|
|
55
|
+
|
|
56
|
+
After selecting the anchor, keep that anchor for this query and do not switch to an older entity.
|
|
57
|
+
If \`lastNavigatedFeatures\` is used as the anchor, reuse its \`layerId\` and \`where\` for query scope unless the current request explicitly overrides it.
|
|
58
|
+
|
|
44
59
|
### Fresh WHERE clause rule
|
|
45
60
|
|
|
46
61
|
Start with a fresh WHERE clause for each new question. Do not inherit filters from previous questions UNLESS the assigned task explicitly references previous results (see "Referencing Previously Identified Features" below).
|
|
@@ -63,11 +78,9 @@ Start with a fresh WHERE clause for each new question. Do not inherit filters fr
|
|
|
63
78
|
|
|
64
79
|
This is an exception to the "fresh WHERE clause" rule above.
|
|
65
80
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
-
|
|
69
|
-
- If the previous assistant response mentions specific objectIds or feature IDs \u2192 use {{objectIdField}} IN (id1, id2, ...) to scope to those features
|
|
70
|
-
- If neither is available, use the same WHERE clause and layer from the previous query turn to re-select the same features
|
|
81
|
+
- If the anchored context indicates \`useCurrentExtent: true\`, use \`useCurrentExtent: true\` with \`where: "1=1"\`.
|
|
82
|
+
- If the anchored context includes specific feature IDs/objectIds, scope to those IDs.
|
|
83
|
+
- Otherwise, use the anchored \`layerId\` + \`where\` combination.
|
|
71
84
|
|
|
72
85
|
### Mixed Questions
|
|
73
86
|
|
|
@@ -58,6 +58,7 @@ In all cases:
|
|
|
58
58
|
|
|
59
59
|
- Focus on **notable attribute values**, **commonalities or differences**, and **interesting trends**.
|
|
60
60
|
- If the feature list is empty or not meaningful, state that clearly.
|
|
61
|
+
- Only use fields present in query results. Do not make guesses.
|
|
61
62
|
|
|
62
63
|
### STRICT OUTPUT RULES
|
|
63
64
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import c from"./
|
|
2
|
+
import c from"./UJEOE2LU.js";import a from"./YRICFRVO.js";import{Fb as k,Q as x,a as y,b as l}from"./V7BWJN43.js";import{c as b,d as A}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as w,y as f}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,,,,{fetchKnowledgeGraph:J},{f:c,l:v,n:_},{K:u,L:K,M:S,N:M,O:G,P:T,Q:C,R:N,S:R,T:z,U:F,a:q,m:g,n:d,p:E}])=>{var L=[T,C,z,N,G,F,R];async function I(e,a){let i=await g("arcgis_knowledge_tool_prompt"),s=K(a),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:s},r=await _({promptText:i,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:L}),t=(r.tool_calls?.length??0)>0,o=typeof r.text=="string"?r.text.trim():"",h=o.length>0,p=r.content.toString();return!t&&(s==="map"||s==="knowledgeGraph")?{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:s==="map"?"No tools were found for the current view and prompt. Maps do not support changing nonspatial visibility, layout changes, or generation from queries.":"No tools were found for the current prompt and knowledge graph service. A knowledge graph service only supports search and query.",status:"success"}:{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:t?p:o,status:t?e.status:h?"success":"failed",summary:p?d(p):"ArcGIS Knowledge Agent tool executed."}}async function U(e,a){let i=new q(L);try{let s=await i.invoke({messages:e.arcgisKnowledgeMessages},a),n=[];for(let t of s.messages){let o;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{o=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}`)}if(!o||typeof o!="object"||!("toolName"in o))throw new Error(`Parsed tool message content does not have expected structure. Parsed content: ${JSON.stringify(o)}`);n.push(o)}await c({text:`Finished executing ArcGIS Knowledge Agent tools: ${s.messages.filter(t=>t.name).map(t=>t.name).join(", ")}`},a);let r=n.filter(t=>typeof t!="string").map(t=>`- Called Tool: ${t.toolName}, Status: ${t.status}`);return{...e,outputMessage:r.join(`
|
|
3
3
|
`),summary:r.length?d(r.join(`
|
|
4
4
|
`)):"ArcGIS Knowledge Agent did not execute any tools or return any results.",arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,...s.messages],arcgisKnowledgeToolResult:n}}catch(s){let n=s instanceof Error?s.message:String(s);return await c({text:`ArcGIS Knowledge Agent tool execution failed: ${n}`},a),{...e,outputMessage:`ArcGIS Knowledge Agent tool execution failed: ${n}`,status:"failed",summary:`ArcGIS Knowledge Agent tool execution failed: ${n}`,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages]}}}var D=(e,a)=>E([],"ArcgisKnowledge Agent")(e,a);async function j(e,a){let i=(e.arcgisKnowledgeToolResult??[]).map(h=>({...h,details:void 0})),{knowledgeGraph:s}=await S(a),n=M.getDataModelTypesSummary(s.dataModel),r={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,toolResult:i,dataModelSummary:n},t=await v({promptText:await g("arcgis_knowledge_summarize_result_prompt"),modelTier:"default",inputVariables:r}),o=typeof t=="string"?t:t.content;return{...e,outputMessage:o,status:"success",summary:d(o),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new x(o)]}}var O=()=>new k(u).addNode("requireArcgisKnowledgeServices",D).addNode("agent",I).addNode("tools",U).addNode("summarizationLLM",j).addEdge(y,"requireArcgisKnowledgeServices").addEdge("requireArcgisKnowledgeServices","agent").addConditionalEdges("agent",e=>(e.arcgisKnowledgeMessages[e.arcgisKnowledgeMessages.length-1]?.tool_calls?.length??0)>0?"tools":l).addConditionalEdges("tools",e=>e.status==="failed"?l:"summarizationLLM").addEdge("summarizationLLM",l),V=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
|
|
5
5
|
This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import a from"./
|
|
2
|
+
import a from"./YRICFRVO.js";export default $arcgis.t(([,,,,,{f:t}])=>{var y=async(o,r)=>{let i=o.tool_calls??[];if(i.length===0){await t({text:`LLM did not request any tool calls: ${String(o?.content)}`},r);return}await Promise.all(i.map(async a=>await t({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},r)))};return y},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request",a)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import b from"./
|
|
2
|
+
import b from"./UJEOE2LU.js";import a from"./YRICFRVO.js";import{Fb as f,a as h,b as l}from"./V7BWJN43.js";import{a as y,c as E}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as u,y as d}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{f:p,n:x},{I:c,J:H,a:S,m:_,n:w,o:m,p:v}])=>{var C=[H],b=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:o,fieldRegistry:a},s)=>{let r=Array.from(a.values()).map(n=>n.name).slice(0,10).join(", "),i=a.size>10?` (and ${a.size-10} more)`:"";return`${s+1}. "${o.title}". Description: ${o.description}
|
|
3
3
|
Fields: ${r}${i}`}).join(`
|
|
4
4
|
|
|
5
5
|
`);return`This map contains ${e.size} layer(s):
|
|
@@ -117,5 +117,4 @@ Do not reinterpret the request into a different form.
|
|
|
117
117
|
- \`requiresFollowUp\` should indicate a likely next agent step, not uncertainty about the current request
|
|
118
118
|
- Set \`requiresFollowUp\` to \`true\` only when another orchestration step will likely be needed after this agent succeeds
|
|
119
119
|
- Set \`requiresFollowUp\` to \`false\` when a successful result from this agent would likely complete the user-visible task
|
|
120
|
-
- Default to \`false\`
|
|
121
120
|
`;export{e as default};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import b from"./
|
|
2
|
+
import b from"./UJEOE2LU.js";import a from"./YRICFRVO.js";import{Fb as C,a as N,b as T}from"./V7BWJN43.js";import{a as L,c as R}from"./KLIA4JYQ.js";import"./MLQKBQSG.js";import"./YGW7TUNX.js";import{v as E,y as $}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{a:f,f:d,m:b,n:F},{a:_,b:v,c:x,d:I,e:A,f:M,g:Z,h:q,i:j,j:V,k:O,l:z,m:S,n:G,o:h,p:B}])=>{var w=[I,A,M,Z,q,j,V,O,z];async function H(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=x(t),l=r.map.bookmarks?.map(p=>p.name).filter(Boolean)??[],i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((p,W)=>`${W+1}. layerId=${p.id} | title=${p.title??""} | name=${p.name??""} | score=${p.score.toFixed(2)}`).join(`
|
|
3
3
|
`):"",c=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",n=e.intent==="goToBookmark"&&l.length?`Available bookmarks:
|
|
4
4
|
${l.map(p=>`- ${p}`).join(`
|
|
5
5
|
`)}`:"",o=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import{a as I,b as _}from"./EUNEQNYC.js";import{a as P}from"./XLFCW5OF.js";import"./M56MGI7M.js";import a from"./YRICFRVO.js";import{Fb as H,Q as F,W as O,a as D,b as W,eb as j,u as q}from"./V7BWJN43.js";import{a as B}from"./MLQKBQSG.js";import"./YGW7TUNX.js";import{g as $,h as g,l as A,n as u,t as b,u as E,v as L,w as v,y as M}from"./J2F4YIQI.js";import"./CFDTXKJ6.js";export default $arcgis.t(([_e,{whenOnce:ke,watch:Ce,when:Re},$e,ee,te,K,se,re,,,Ae,{property:w,subclass:Le},{b:N,e:z,f:m,h:S,i:U,j:V,k:T}])=>{var ie=async s=>{let e=await ne(),t=await N("default"),i=te.getDefault(),r=(await ee.getCredential(`${i.url}/sharing`)).token,n={type:"generateEmbeddings",webmapEmbeddings:s,auth:{apiUrl:t,token:r}};return e.postMessage(n),await new Promise((a,l)=>{let o=d=>{d.data==="completed"&&(e.removeEventListener("message",o),a())},c=d=>{e.removeEventListener("message",o),l(d instanceof Error?d:new Error("Embeddings worker error"))};e.addEventListener("message",o),e.addEventListener("error",c,{once:!0})}),e},ne=async()=>{{let s=(await import("./URYKQKFE.js")).default;return new s}},ae=s=>{s.currentIntent="none"},oe=async(s,e)=>{let t=S(e);if(s.agentExecutionContext.userRequest){let r=new O(s.agentExecutionContext.userRequest.trim());s.agentExecutionContext.messages=[...s.agentExecutionContext.messages,r],ae(s)}let i=t?.services.agentRegistry.list().map(r=>r.agent.id)??[];return await m({text:`Available agents: ${[...i].join(", ")}`},e),await m({text:"Analyzing user input"},e),s},ce=async(s,e)=>(await m({text:"Exiting..."},e),s),G=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),le=(s,e)=>{if(!G(s)){s!==void 0&&console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);return}let t={};for(let[i,r]of Object.entries(s)){if(!G(r)||!("value"in r)){console.warn(`Agent "${e}" returned invalid sharedStatePatch entry for key "${i}". Ignoring that entry.`);continue}t[i]={value:r.value}}return t},de=s=>{let{previousSharedState:e,patch:t,agentId:i}=s;if(!t)return e;let r=Date.now(),n={...e};for(let[a,l]of Object.entries(t))l?.value!==void 0&&(n[a]={value:l.value,meta:{updatedByAgentId:i,updatedAt:r}});return n},Q=s=>typeof s!="string"?void 0:s.trim()||void 0,ge=s=>{switch(s){case"failed":return"Agent failed without a summary.";case"unknown":return"Agent returned with unknown status.";case"success":return"Agent completed without a summary.";default:return"Agent completed without a summary."}},he=(s,e)=>{let t=Q(e?.outputMessage),i=Q(e?.summary),r=e?.status,n=r==="success"||r==="failed"?r:"unknown";n==="unknown"&&console.warn(`Agent "${s}" returned missing/invalid status. Defaulting to "unknown".`);let a=le(e?.sharedStatePatch,s);return{outputMessage:t,summary:i??t??ge(n),status:n,sharedStatePatch:a}},J=4e3,ue=async(s,e)=>{let t=S(e);if(t?.abortSignal?.aborted)return await m({text:"Run cancelled; skipping agent execution"},e),{...s,currentIntent:"none",requiresFollowUp:!1};let{agentRegistry:i}=t?.services??{},r=i?.get(s.currentIntent);if(!r)return console.warn(`No agent found for intent: ${s.currentIntent}`),s;await m({text:`Executing registered agent: ${r.agent.name}`},e);let n={...e??{},configurable:{...t??{},agentId:r.agent.id,context:r.getContext?await r.getContext():void 0}},a;try{let c=await r.agent.createGraph().compile().invoke({agentExecutionContext:{...s.agentExecutionContext,messages:[...s.agentExecutionContext.messages],priorSteps:structuredClone(s.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(s.agentExecutionContext.sharedState??{})}},n);a=he(r.agent.name,c),await m({text:`Finished executing registered agent: ${r.agent.name}`},e)}catch(c){if(q(c))throw c;let d=c instanceof Error?c.message:String(c);console.error(`Agent "${r.agent.name}" failed:`,c),await m({text:`Registered agent failed: ${r.agent.name}. ${d}`},e),a={status:"failed",outputMessage:`Agent execution failed: ${d}`,summary:`Agent execution failed: ${d}`}}let l=a.outputMessage,o=[...s.agentExecutionContext.messages];if(l){let c=l.length>J?`${l.slice(0,J-14)}
|
|
3
|
+
[truncated]`:l;o.push(new F(c))}return{...s,stepCount:s.stepCount+1,lastExecutedAgent:r.agent.id,requiresFollowUp:a.status==="failed"?!0:s.requiresFollowUp,finalOutputMessage:l??"",agentExecutionContext:{...s.agentExecutionContext,messages:o,priorSteps:[...s.agentExecutionContext.priorSteps??[],{agentId:r.agent.id,assignedTask:s.agentExecutionContext.assignedTask,summary:a?.summary||"No summary provided.",status:a?.status||"unknown"}],sharedState:de({previousSharedState:s.agentExecutionContext.sharedState,patch:a.sharedStatePatch,agentId:r.agent.id})}}},pe=3,me=()=>new H(z).addNode("ingestInput",oe).addNode("intentLLM",V).addNode("executeRegisteredAgent",ue).addNode("exit",ce).addEdge(D,"ingestInput").addEdge("ingestInput","intentLLM").addConditionalEdges("intentLLM",s=>s.currentIntent==="none"||s.currentIntent===s.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",s=>s.stepCount>=pe||!s.requiresFollowUp?"exit":"intentLLM").addEdge("exit",W),k=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:t}=e;if(this.agentRegistry.has(t.id))throw new Error(`Duplicate agent id: ${t.id}`);this.agentRegistry.set(t.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},C=class{constructor(e,t){this.graph=e,this.config={...t}}async waitForUser(){return await new Promise((e,t)=>{this.resolveWait=e,this.rejectWait=t})}handle(e,t){try{let i={agentId:e.agentId,id:e.id,payload:t},r=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:i},subgraphs:!0,version:"v2"});this.resolveWait?.(r)}catch(i){this.rejectWait?.(i)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("Request cancelled by user.")),this.resolveWait=void 0,this.rejectWait=void 0)}},ye=async s=>{try{return await(await U()).embedDocuments(s)}catch(e){throw console.error("Failed to generate embeddings:",e),e}},X=async(s,e)=>{let t=e.get(s);if(t)return t;let i=await ye([s]);return e.set(s,i[0]),i[0]};async function we(s,e,t,i){let r=`req-${Date.now()}`,n={type:"layerSearch",precomputedEmbedding:i?await X(s,i):void 0,requestId:r,minScore:t};return await new Promise(a=>{let l=o=>{o.data.requestId===r&&a(o.data.results)};e.addEventListener("message",l,{once:!0}),e.postMessage(n)})}function fe(s){let{worker:e}=s;return{async searchLayers({text:t,minScore:i,embeddingCache:r}){return await we(t,e,i,r)}}}var ve=async({combinedQuery:s,layerIds:e,embeddingsWorker:t,minScore:i,topResults:r,embeddingCache:n})=>{let a=`req-${Date.now()}`,l=n?await X(s,n):void 0,o={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:l,requestId:a,minScore:i,topResults:r};return await new Promise(c=>{let d=h=>{if(h.data.requestId!==a)return;let f=h.data.results.map(({layerId:Y,results:Z})=>({layerId:Y,results:Z}));c(f)};t.addEventListener("message",d,{once:!0}),t.postMessage(o)})};function be(s){let{worker:e}=s;return{async searchFields({text:t,layerIds:i,minScore:r,topResults:n,embeddingCache:a}){return await ve({combinedQuery:t,layerIds:i,embeddingsWorker:e,minScore:r,topResults:n,embeddingCache:a})}}}var Ee=s=>{let e=T.safeParse(s);if(!e.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return e.data},xe=(s,e)=>{let t=new Map,i=new Map;if(e.allLayers.forEach(r=>{r instanceof se&&i.set(r.id,r)}),s.length!==i.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let r of s){let n=i.get(r.id);if(!n)throw new Error(`Layer with ID ${r.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(r.fields.length!==n.fields.length)throw new Error(`Field count mismatch for layer ID ${r.id} during registry restoration. Regenerate embeddings.`);let a={name:r.name,title:r.title,description:r.description},l=new Map;for(let o of r.fields){let c=n.fieldsIndex.get(o.name);if(!c)throw new Error(`Field with name ${o.name} not found in the original layer ${r.id} during registry restoration. Regenerate embeddings.`);l.set(o.name,{name:o.name,alias:n.getFieldAlias(o.name)??o.alias,description:o.description,type:c.type||"unknown",valueType:c.valueType||"unknown",domain:n.getFieldDomain(o.name)??void 0})}t.set(r.id,{layerItem:a,fieldRegistry:l})}return t},Se=async s=>{try{return(await re(s,{responseType:"json"})).data}catch(e){throw new Error(`Failed to fetch data from ${s}: ${String(e)}`)}},Ie=async s=>{let e=s.map;if(!e?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:t}=await e.portalItem.fetchResources(),i=t.find(n=>n.resource.path==="embeddings-v01.json");if(!i?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let r=await Se(i.resource.url);return Ee(r)},x=class s{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.agentRegistry=new k,this.activeRunId="",this.cancelledRunIds=new Set,this.streamEpoch=0}static async init(e){let t=new s;try{if(e.view?.map){await K.whenOnce(()=>e.view.ready);let i=await Ie(e.view),r=xe(i.layers,e.view.map);t.layersAndFieldsRegistry=r,t.embeddingsWorker=await ie(i)}return e.agents?.forEach(i=>{t.agentRegistry.register(i)}),t.orchestratorReady=!0,t}catch(i){throw console.error("Orchestrator initialization failed:",i),i}}async*ask(e){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!e.trim())return;let t=String(Date.now());this.activeRunId=t,this.activeAbortController=new AbortController,this.graph||(this.graph=me().compile({checkpointer:new j}));let i=this.embeddingsWorker?fe({worker:this.embeddingsWorker}):void 0,r=this.embeddingsWorker?be({worker:this.embeddingsWorker}):void 0,n=new Map,a={version:"v2",streamMode:"custom",configurable:{thread_id:t,abortSignal:this.activeAbortController.signal,hitlResponse:null,services:{layerSearch:i,fieldSearch:r,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:n}},subgraphs:!0},l=this.graph?.streamEvents({agentExecutionContext:{userRequest:e,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},a),o=++this.streamEpoch;if(yield*this.pipeStream(l,o,t),this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}for(;;){if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let d=(await this.graph.getState(a,{subgraphs:!0})).tasks.find(h=>h.interrupts.length>0)?.interrupts[0]?.value;if(!d)break;this.currentInterrupt=d,this.interruptHandler=new C(this.graph,a),yield{runId:t,timestamp:Date.now(),type:"interrupt",interrupt:d};try{let h=await this.interruptHandler.waitForUser(),f=++this.streamEpoch;yield*this.pipeStream(h,f,t)}catch(h){if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}if(h){yield{runId:t,timestamp:Date.now(),type:"error",error:{message:h?.message}};return}}}if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}let c=(await this.graph.getState(a,{subgraphs:!0})).values;if(this.isRunCancelled(t)){yield{runId:t,timestamp:Date.now(),type:"cancelled",reason:"user"};return}this.chatHistory=c.agentExecutionContext.messages.length?c.agentExecutionContext.messages:this.chatHistory,this.priorSteps=c.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=c.agentExecutionContext.sharedState??{},yield{runId:t,timestamp:Date.now(),type:"completed",result:{content:c.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}resumeInterrupt(e){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,e)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}cancel(){this.activeRunId&&(this.cancelledRunIds.add(this.activeRunId),this.activeAbortController?.abort(),++this.streamEpoch,this.interruptHandler?.cancel())}async*pipeStream(e,t,i){for await(let r of e){if(this.isRunCancelled(i)||t!==this.streamEpoch)break;r.event==="on_custom_event"&&r.name==="trace_message"?yield{runId:i,timestamp:Date.now(),type:"trace",data:r.data}:r.name==="graph_ux_suggestion"&&(yield{runId:i,timestamp:Date.now(),type:"ux-suggestion",suggestion:r.data})}}isRunCancelled(e){return this.cancelledRunIds.has(e)}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};var Me=$`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%)}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}`,Pe=Object.defineProperty,De=Object.getOwnPropertyDescriptor,y=(s,e,t,i)=>{for(var r=i>1?void 0:i?De(e,t):e,n=s.length-1,a;n>=0;n--)(a=s[n])&&(r=(i?a(e,t,r):a(r))||r);return i&&r&&Pe(e,t,r),r},p=class extends Ae{constructor(s){super(s),this.view=null,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await ke(()=>!this.view.updating),this._set("orchestrator",await x.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([Ce(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(s,e){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let t=[],i;try{let r=this.orchestrator.ask(s);for await(let n of r){let a=n.runId;if(e?.aborted){yield{type:"cancelled",runId:a};break}switch(n.type){case"trace":{this._set("processingStep",n.data.text),t.push(n.data.text);break}case"completed":{let l=n.result,o=!!l.content.length,c=!!i?.length;if(!o&&!c){yield{type:"completed",error:"Could not process the request.",log:t,runId:a};return}let d=l.content;this._set("processingStep",""),yield{type:"completed",response:d,blocks:i,log:t,runId:a};return}case"ux-suggestion":{let l=n.suggestion;i=i?[...i,l]:[l];break}case"interrupt":{let{kind:l,message:o,metadata:c}=n.interrupt,d=Array.isArray(c)?c.filter(f=>typeof f=="string"):[],h=(()=>{switch(l){case"booleanChoice":return{type:"boolean-choice",message:o,options:d};case"singleSelection":return{type:"single-select",message:o,options:d};case"multipleSelection":return{type:"multi-select",message:o,options:d};case"textInput":return{type:"text-input",message:o};default:return{type:l,message:o,options:d}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:h,runId:a};break}case"cancelled":{yield{type:"cancelled",runId:a};return}case"error":{yield{type:"completed",error:n.error.message,log:t,runId:a};return}default:{console.warn("Unknown event type:",n);break}}}}catch(r){console.warn("Error during message processing:",r),yield{type:"completed",error:"An error occurred during message processing.",log:t,runId:"error"};return}finally{this._set("processing",!1)}}};y([w({readOnly:!0})],p.prototype,"orchestrator",2);y([w()],p.prototype,"agents",2);y([w()],p.prototype,"portal",2);y([w()],p.prototype,"view",2);y([w({readOnly:!0})],p.prototype,"loading",2);y([w({readOnly:!0})],p.prototype,"processing",2);y([w({readOnly:!0})],p.prototype,"processingStep",2);p=y([Le("OrchestratorController")],p);var We="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",qe="Embeddings not found for this web map.",Fe="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",R=class extends L{constructor(){super(...arguments),this._messages=P({blocking:!0}),this.#e=b(),this.#a=b(),this.#t=b(),this.#s=null,this.#o=new Map,this.#r=$e.getDefault(),this.#i=e=>{e.stopPropagation(),this.cancelInterrupt()},this.#n=e=>{e.stopPropagation();let t=e.detail;this.submitInterrupt(t)},this.#c=e=>{e.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let t=e.detail;this._inputValue="",this.arcgisSubmit.emit(t),this.submitMessage(t)},this.#l=e=>{if(e.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this.#s?.abort()},this.#d=e=>{e.stopPropagation();let t=e.detail;this.arcgisFeedback.emit(t)},this.#g=e=>{e.stopPropagation();let t=e.detail;this._inputValue=t.prompt,this.arcgisPromptSelect.emit(t)},this.#h=e=>{this.arcgisSlottableRequest.emit(e.detail)},this._orchestratorController=null,this._interrupt=null,this._error=null,this._inputValue="",this.messages=new _e([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.arcgisCancel=u(),this.arcgisError=u(),this.arcgisFeedback=u(),this.arcgisInterrupt=u(),this.arcgisInterruptCancel=u(),this.arcgisInterruptSubmit=u(),this.arcgisPromptSelect=u(),this.arcgisReady=u(),this.arcgisSubmit=u(),this.arcgisSlottableRequest=u({bubbles:!1,composed:!1})}static{this.properties={_orchestratorController:16,_interrupt:16,_error:16,_inputValue:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5}}static{this.styles=Me}#e;#a;#t;#s;#o;#r;#i;#n;#c;#l;#d;#g;#h;async#u(){try{let e=B(this.el,this.referenceElement);await e?.componentOnReady();let t=[...this.#o.values()];return t.length?(this._orchestratorController=new p({agents:t,portal:this.#r,view:e?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(e){return this._error=e?.message??"Error initializing orchestrator.",A(this)(e),!1}}get _user(){return this.#r?.user?.fullName||this.#r?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(e){this.#o.set(e.agent.id,e)}async submitMessage(e){let t=e.trim();if(!t||(this.messages.push({id:Date.now().toString(),role:"user",content:t}),!this._orchestratorController))return;let i=this._orchestratorController.ask(t,this.#s?.signal);for await(let r of i){let n=r.runId;switch(r.type){case"completed":this.messages.push({role:"assistant",content:r.response,blocks:r.blocks,log:r.log,error:r.error,id:n});break;case"interrupt":this._interrupt={...r.payload,id:n},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":this.messages.push({role:"assistant",error:"Request cancelled.",id:n});break}}}submitInterrupt(e){this.arcgisInterruptSubmit.emit(e),this.orchestrator?.resumeInterrupt(e),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#e.value?.addEventListener("arcgisPromptSelect",this.#g),this.#e.value?.addEventListener("arcgisSubmit",this.#c),this.#e.value?.addEventListener("arcgisCancel",this.#l),this.#e.value?.addEventListener("arcgisFeedback",this.#d);let e=Re(()=>!!this._interrupt&&!!this.#t.value,()=>{let t=this.#t.value;t.removeEventListener("arcgisSubmit",this.#n),t.removeEventListener("arcgisCancel",this.#i),t.addEventListener("arcgisSubmit",this.#n,{once:!0}),t.addEventListener("arcgisCancel",this.#i,{once:!0})});return queueMicrotask(()=>{this.#u().then(t=>{t?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{e.remove(),this.#e.value?.removeEventListener("arcgisPromptSelect",this.#g),this.#t.value?.removeEventListener("arcgisSubmit",this.#n),this.#t.value?.removeEventListener("arcgisCancel",this.#i),this.#e.value?.removeEventListener("arcgisSubmit",this.#c),this.#e.value?.removeEventListener("arcgisCancel",this.#l),this.#e.value?.removeEventListener("arcgisFeedback",this.#d),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this.#s?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue=""}_renderEntryMessage(){return this._interrupt?g`<slot name=interrupt><arcgis-assistant-interrupt .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${E(this.#t)}></arcgis-assistant-interrupt></slot>`:this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:g`<calcite-notice open kind=info closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:g`<slot name=entry-message></slot>`}_renderErrorNotice(){return this._error?g`<calcite-notice closable slot=entry-message open kind=danger icon width=full>${this._error===We?g`<div slot=message>${qe}</div><calcite-link slot=link .href=${Fe} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:g`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}_renderSuggestedPrompts(){return this.suggestedPrompts?.length?g`<div class="suggested-prompts-container"><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}render(){return g`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${E(this.#e)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(e=>e.role==="assistant"?g`<arcgis-assistant-message .message=${e} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#h}><slot name=${I(e.id)??v} slot=${I(e.id)??v}>${e?.error?g`<calcite-notice class="error-notice" open icon kind=warning width=full><div slot=message>${e.error}</div></calcite-notice>`:g`<arcgis-assistant-message-text .content=${e?.content}></arcgis-assistant-message-text>`}</slot>${e.blocks?.map((t,i)=>g`<slot name=${_(e.id,i)??v} slot=${_(e.id,i)??v}><arcgis-assistant-message-block .block=${t}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:g`<arcgis-assistant-user-message .message=${e} .user=${this._user}></arcgis-assistant-user-message>`)}</slot><slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep}></arcgis-assistant-message-loading></slot></arcgis-assistant-chat></div>${this._renderSuggestedPrompts()}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} ${E(this.#a)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse?"circle-stop":"send"} @click=${()=>{this.#a.value?.submitMessage()}} round>${this.awaitingResponse?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};M("arcgis-assistant",R);return R},"core/Collection","core/reactiveUtils","portal/Portal","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","layers/FeatureLayer","core/Accessor","core/accessorSupport/decorators",a)
|