@arcgis/ai-components 5.2.0-next.4 → 5.2.0-next.6

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.
Files changed (43) hide show
  1. package/dist/agent-utils/LLMAgent.js +22 -22
  2. package/dist/cdn/{YY2SBO3V.js → 3NI46YCE.js} +1 -1
  3. package/dist/cdn/{V5YEZSRY.js → 47FWPQ2A.js} +1 -1
  4. package/dist/cdn/{FHVXO2WG.js → AEJHYRGT.js} +4 -4
  5. package/dist/cdn/{JY6LLOUJ.js → BFZJNJL6.js} +1 -1
  6. package/dist/cdn/{MDVYQQUG.js → GCQLVNNC.js} +1 -1
  7. package/dist/cdn/{GSEPHN3A.js → JV4SI65E.js} +31 -29
  8. package/dist/cdn/R6HV42YW.js +3 -0
  9. package/dist/cdn/{S6W6HV4T.js → V7OJRG26.js} +1 -1
  10. package/dist/cdn/{4HU7735A.js → VOQX4AVB.js} +1 -1
  11. package/dist/cdn/index.js +1 -1
  12. package/dist/cdn/main.css +1 -1
  13. package/dist/chunks/adapter.js +6 -6
  14. package/dist/chunks/generateLayerDescriptions.js +236 -208
  15. package/dist/chunks/orchestrator.js +240 -201
  16. package/dist/components/arcgis-assistant-chat/customElement.d.ts +6 -1
  17. package/dist/components/arcgis-assistant-chat-entry/customElement.d.ts +2 -1
  18. package/dist/components/arcgis-assistant-interrupt/customElement.d.ts +4 -1
  19. package/dist/components/arcgis-assistant-message/customElement.d.ts +21 -0
  20. package/dist/components/arcgis-assistant-message/index.d.ts +1 -0
  21. package/dist/components/arcgis-assistant-message-block/customElement.d.ts +1 -1
  22. package/dist/components/arcgis-assistant-message-feedback/customElement.d.ts +4 -1
  23. package/dist/components/arcgis-assistant-message-footer/customElement.d.ts +4 -1
  24. package/dist/components/arcgis-assistant-message-loading/customElement.d.ts +4 -1
  25. package/dist/components/arcgis-assistant-message-log/customElement.d.ts +4 -1
  26. package/dist/components/arcgis-assistant-message-read-aloud/customElement.d.ts +4 -1
  27. package/dist/components/arcgis-assistant-message-text/customElement.d.ts +4 -1
  28. package/dist/components/arcgis-assistant-speech-input/customElement.d.ts +6 -1
  29. package/dist/components/arcgis-assistant-suggested-prompts/customElement.d.ts +4 -1
  30. package/dist/components/arcgis-assistant-user-message/customElement.d.ts +4 -1
  31. package/dist/docs/api.json +1 -1
  32. package/dist/docs/docs.json +1 -1
  33. package/dist/docs/vscode.html-custom-data.json +1 -1
  34. package/dist/docs/web-types.json +1 -1
  35. package/dist/index.d.ts +4 -0
  36. package/dist/types/lumina.d.ts +5 -0
  37. package/dist/types/preact.d.ts +6 -0
  38. package/dist/types/react.d.ts +7 -0
  39. package/dist/types/stencil.d.ts +5 -0
  40. package/dist/utils/index.d.ts +10 -14
  41. package/dist/utils/index.js +68 -78
  42. package/package.json +5 -5
  43. package/dist/cdn/ON2V5XI2.js +0 -3
@@ -1,19 +1,19 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import S from "@arcgis/core/identity/IdentityManager.js";
3
- import b from "@arcgis/core/portal/Portal.js";
4
- import { p as I, s as l, D as R, q as k, r as M, W as C } from "./generateLayerDescriptions.js";
5
- import { isGraphInterrupt as A, StateGraph as F, START as L, END as W, MemorySaver as $ } from "@langchain/langgraph/web";
6
- import { HumanMessage as D, AIMessage as j } from "@langchain/core/messages";
2
+ import R from "@arcgis/core/identity/IdentityManager.js";
3
+ import C from "@arcgis/core/portal/Portal.js";
4
+ import { p as I, q as v, s as l, D as k, r as A, t as M, W as F } from "./generateLayerDescriptions.js";
5
+ import { isGraphInterrupt as D, StateGraph as L, START as W, END as $, MemorySaver as j } from "@langchain/langgraph/web";
6
+ import { HumanMessage as q, AIMessage as H } from "@langchain/core/messages";
7
7
  import * as P from "@arcgis/core/core/reactiveUtils.js";
8
- import q from "@arcgis/core/layers/FeatureLayer.js";
9
- import H from "@arcgis/core/request.js";
10
- const O = async (t) => {
11
- const e = await T(), s = await I("default"), n = b.getDefault(), i = (await S.getCredential(`${n.url}/sharing`)).token, a = {
8
+ import O from "@arcgis/core/layers/FeatureLayer.js";
9
+ import T from "@arcgis/core/request.js";
10
+ const U = async (t) => {
11
+ const e = await N(), r = await I("default"), s = C.getDefault(), a = (await R.getCredential(`${s.url}/sharing`)).token, i = {
12
12
  type: "generateEmbeddings",
13
13
  webmapEmbeddings: t,
14
- auth: { apiUrl: s, token: i }
14
+ auth: { apiUrl: r, token: a }
15
15
  };
16
- return e.postMessage(a), await new Promise((c, d) => {
16
+ return e.postMessage(i), await new Promise((c, d) => {
17
17
  const o = (u) => {
18
18
  u.data === "completed" && (e.removeEventListener("message", o), c());
19
19
  }, g = (u) => {
@@ -21,58 +21,59 @@ const O = async (t) => {
21
21
  };
22
22
  e.addEventListener("message", o), e.addEventListener("error", g, { once: !0 });
23
23
  }), e;
24
- }, T = async () => {
24
+ }, N = async () => {
25
25
  {
26
26
  const t = (await import("./embeddings.worker.js")).default;
27
27
  return new t();
28
28
  }
29
- }, U = (t) => {
29
+ }, G = (t) => {
30
30
  t.currentIntent = "none";
31
- }, N = async (t, e) => {
31
+ }, _ = async (t, e) => {
32
+ const r = v(e);
32
33
  if (t.agentExecutionContext.userRequest) {
33
- const n = new D(t.agentExecutionContext.userRequest.trim());
34
- t.agentExecutionContext.messages = [...t.agentExecutionContext.messages, n], U(t);
34
+ const n = new q(t.agentExecutionContext.userRequest.trim());
35
+ t.agentExecutionContext.messages = [...t.agentExecutionContext.messages, n], G(t);
35
36
  }
36
- const s = e?.configurable?.services.agentRegistry.list().map((n) => n.agent.id) ?? [];
37
+ const s = r?.services.agentRegistry.list().map((n) => n.agent.id) ?? [];
37
38
  return await l({ text: `Available agents: ${[...s].join(", ")}` }, e), await l({ text: "Analyzing user input" }, e), t;
38
- }, G = async (t, e) => (await l({ text: "Exiting..." }, e), t), y = (t) => typeof t == "object" && t !== null && !Array.isArray(t), _ = (t, e) => {
39
- if (!y(t)) {
39
+ }, V = async (t, e) => (await l({ text: "Exiting..." }, e), t), w = (t) => typeof t == "object" && t !== null && !Array.isArray(t), z = (t, e) => {
40
+ if (!w(t)) {
40
41
  t !== void 0 && console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);
41
42
  return;
42
43
  }
43
- const s = {};
44
- for (const [n, r] of Object.entries(t)) {
45
- if (!y(r) || !("value" in r)) {
44
+ const r = {};
45
+ for (const [s, n] of Object.entries(t)) {
46
+ if (!w(n) || !("value" in n)) {
46
47
  console.warn(
47
- `Agent "${e}" returned invalid sharedStatePatch entry for key "${n}". Ignoring that entry.`
48
+ `Agent "${e}" returned invalid sharedStatePatch entry for key "${s}". Ignoring that entry.`
48
49
  );
49
50
  continue;
50
51
  }
51
- s[n] = { value: r.value };
52
+ r[s] = { value: n.value };
52
53
  }
53
- return s;
54
- }, V = (t) => {
55
- const { previousSharedState: e, patch: s, agentId: n } = t;
56
- if (!s)
54
+ return r;
55
+ }, Q = (t) => {
56
+ const { previousSharedState: e, patch: r, agentId: s } = t;
57
+ if (!r)
57
58
  return e;
58
- const r = Date.now(), i = {
59
+ const n = Date.now(), a = {
59
60
  ...e
60
61
  };
61
- for (const [a, c] of Object.entries(s))
62
- c?.value !== void 0 && (i[a] = {
62
+ for (const [i, c] of Object.entries(r))
63
+ c?.value !== void 0 && (a[i] = {
63
64
  value: c.value,
64
65
  meta: {
65
- updatedByAgentId: n,
66
- updatedAt: r
66
+ updatedByAgentId: s,
67
+ updatedAt: n
67
68
  }
68
69
  });
69
- return i;
70
- }, w = (t) => {
70
+ return a;
71
+ }, f = (t) => {
71
72
  if (typeof t != "string")
72
73
  return;
73
74
  const e = t.trim();
74
75
  return e || void 0;
75
- }, z = (t) => {
76
+ }, B = (t) => {
76
77
  switch (t) {
77
78
  case "failed":
78
79
  return "Agent failed without a summary.";
@@ -83,32 +84,39 @@ const O = async (t) => {
83
84
  default:
84
85
  return "Agent completed without a summary.";
85
86
  }
86
- }, Q = (t, e) => {
87
- const s = w(e?.outputMessage), n = w(e?.summary), r = e?.status, i = r === "success" || r === "failed" ? r : "unknown";
88
- i === "unknown" && console.warn(`Agent "${t}" returned missing/invalid status. Defaulting to "unknown".`);
89
- const a = _(e?.sharedStatePatch, t);
87
+ }, J = (t, e) => {
88
+ const r = f(e?.outputMessage), s = f(e?.summary), n = e?.status, a = n === "success" || n === "failed" ? n : "unknown";
89
+ a === "unknown" && console.warn(`Agent "${t}" returned missing/invalid status. Defaulting to "unknown".`);
90
+ const i = z(e?.sharedStatePatch, t);
90
91
  return {
91
- outputMessage: s,
92
- summary: n ?? s ?? z(i),
93
- status: i,
94
- sharedStatePatch: a
92
+ outputMessage: r,
93
+ summary: s ?? r ?? B(a),
94
+ status: a,
95
+ sharedStatePatch: i
95
96
  };
96
- }, f = 4e3, B = async (t, e) => {
97
- const s = e?.configurable, { agentRegistry: n } = s.services, r = n?.get(t.currentIntent);
98
- if (!r)
97
+ }, E = 4e3, K = async (t, e) => {
98
+ const r = v(e);
99
+ if (r?.abortSignal?.aborted)
100
+ return await l({ text: "Run cancelled; skipping agent execution" }, e), {
101
+ ...t,
102
+ currentIntent: "none",
103
+ requiresFollowUp: !1
104
+ };
105
+ const { agentRegistry: s } = r?.services ?? {}, n = s?.get(t.currentIntent);
106
+ if (!n)
99
107
  return console.warn(`No agent found for intent: ${t.currentIntent}`), t;
100
- await l({ text: `Executing registered agent: ${r.agent.name}` }, e);
101
- const i = {
108
+ await l({ text: `Executing registered agent: ${n.agent.name}` }, e);
109
+ const a = {
102
110
  ...e ?? {},
103
111
  configurable: {
104
- ...s ?? {},
105
- agentId: r.agent.id,
106
- context: r.getContext ? await r.getContext() : void 0
112
+ ...r ?? {},
113
+ agentId: n.agent.id,
114
+ context: n.getContext ? await n.getContext() : void 0
107
115
  }
108
116
  };
109
- let a;
117
+ let i;
110
118
  try {
111
- const o = await r.agent.createGraph().compile().invoke(
119
+ const o = await n.agent.createGraph().compile().invoke(
112
120
  {
113
121
  agentExecutionContext: {
114
122
  ...t.agentExecutionContext,
@@ -119,30 +127,30 @@ const O = async (t) => {
119
127
  sharedState: structuredClone(t.agentExecutionContext.sharedState ?? {})
120
128
  }
121
129
  },
122
- i
130
+ a
123
131
  );
124
- a = Q(r.agent.name, o), await l({ text: `Finished executing registered agent: ${r.agent.name}` }, e);
132
+ i = J(n.agent.name, o), await l({ text: `Finished executing registered agent: ${n.agent.name}` }, e);
125
133
  } catch (o) {
126
- if (A(o))
134
+ if (D(o))
127
135
  throw o;
128
136
  const g = o instanceof Error ? o.message : String(o);
129
- console.error(`Agent "${r.agent.name}" failed:`, o), await l({ text: `Registered agent failed: ${r.agent.name}. ${g}` }, e), a = {
137
+ console.error(`Agent "${n.agent.name}" failed:`, o), await l({ text: `Registered agent failed: ${n.agent.name}. ${g}` }, e), i = {
130
138
  status: "failed",
131
139
  outputMessage: `Agent execution failed: ${g}`,
132
140
  summary: `Agent execution failed: ${g}`
133
141
  };
134
142
  }
135
- const c = a.outputMessage, d = [...t.agentExecutionContext.messages];
143
+ const c = i.outputMessage, d = [...t.agentExecutionContext.messages];
136
144
  if (c) {
137
- const o = c.length > f ? `${c.slice(0, f - 14)}
145
+ const o = c.length > E ? `${c.slice(0, E - 14)}
138
146
  [truncated]` : c;
139
- d.push(new j(o));
147
+ d.push(new H(o));
140
148
  }
141
149
  return {
142
150
  ...t,
143
151
  stepCount: t.stepCount + 1,
144
- lastExecutedAgent: r.agent.id,
145
- requiresFollowUp: a.status === "failed" ? !0 : t.requiresFollowUp,
152
+ lastExecutedAgent: n.agent.id,
153
+ requiresFollowUp: i.status === "failed" ? !0 : t.requiresFollowUp,
146
154
  finalOutputMessage: c ?? "",
147
155
  agentExecutionContext: {
148
156
  ...t.agentExecutionContext,
@@ -150,32 +158,32 @@ const O = async (t) => {
150
158
  priorSteps: [
151
159
  ...t.agentExecutionContext.priorSteps ?? [],
152
160
  {
153
- agentId: r.agent.id,
161
+ agentId: n.agent.id,
154
162
  assignedTask: t.agentExecutionContext.assignedTask,
155
- summary: a?.summary || "No summary provided.",
156
- status: a?.status || "unknown"
163
+ summary: i?.summary || "No summary provided.",
164
+ status: i?.status || "unknown"
157
165
  }
158
166
  ],
159
- sharedState: V({
167
+ sharedState: Q({
160
168
  previousSharedState: t.agentExecutionContext.sharedState,
161
- patch: a.sharedStatePatch,
162
- agentId: r.agent.id
169
+ patch: i.sharedStatePatch,
170
+ agentId: n.agent.id
163
171
  })
164
172
  }
165
173
  };
166
- }, J = 3, K = () => new F(R).addNode("ingestInput", N).addNode("intentLLM", k).addNode("executeRegisteredAgent", B).addNode("exit", G).addEdge(L, "ingestInput").addEdge("ingestInput", "intentLLM").addConditionalEdges("intentLLM", (e) => e.currentIntent === "none" || e.currentIntent === e.lastExecutedAgent ? "exit" : "executeRegisteredAgent").addConditionalEdges(
174
+ }, X = 3, Y = () => new L(k).addNode("ingestInput", _).addNode("intentLLM", A).addNode("executeRegisteredAgent", K).addNode("exit", V).addEdge(W, "ingestInput").addEdge("ingestInput", "intentLLM").addConditionalEdges("intentLLM", (e) => e.currentIntent === "none" || e.currentIntent === e.lastExecutedAgent ? "exit" : "executeRegisteredAgent").addConditionalEdges(
167
175
  "executeRegisteredAgent",
168
- (e) => e.stepCount >= J || !e.requiresFollowUp ? "exit" : "intentLLM"
169
- ).addEdge("exit", W);
170
- class X {
176
+ (e) => e.stepCount >= X || !e.requiresFollowUp ? "exit" : "intentLLM"
177
+ ).addEdge("exit", $);
178
+ class Z {
171
179
  constructor() {
172
180
  this.agentRegistry = /* @__PURE__ */ new Map();
173
181
  }
174
182
  register(e) {
175
- const { agent: s } = e;
176
- if (this.agentRegistry.has(s.id))
177
- throw new Error(`Duplicate agent id: ${s.id}`);
178
- this.agentRegistry.set(s.id, e);
183
+ const { agent: r } = e;
184
+ if (this.agentRegistry.has(r.id))
185
+ throw new Error(`Duplicate agent id: ${r.id}`);
186
+ this.agentRegistry.set(r.id, e);
179
187
  }
180
188
  get(e) {
181
189
  return this.agentRegistry.get(e);
@@ -184,42 +192,42 @@ class X {
184
192
  return [...this.agentRegistry.values()];
185
193
  }
186
194
  }
187
- class Y {
195
+ class ee {
188
196
  /**
189
197
  * Create a new InterruptHandler tied to a specific compiled graph and config.
190
198
  */
191
- constructor(e, s) {
192
- this.graph = e, this.config = { ...s };
199
+ constructor(e, r) {
200
+ this.graph = e, this.config = { ...r };
193
201
  }
194
202
  /**
195
203
  * Returns a promise that resolves when the user provides a HITL response.
196
204
  */
197
205
  async waitForUser() {
198
- return await new Promise((e, s) => {
199
- this.resolveWait = e, this.rejectWait = s;
206
+ return await new Promise((e, r) => {
207
+ this.resolveWait = e, this.rejectWait = r;
200
208
  });
201
209
  }
202
210
  /**
203
211
  * Resume graph execution after the UI responds to an interrupt.
204
212
  */
205
- handle(e, s) {
213
+ handle(e, r) {
206
214
  try {
207
- const n = {
215
+ const s = {
208
216
  agentId: e.agentId,
209
217
  id: e.id,
210
- payload: s
211
- }, r = this.graph.streamEvents(null, {
218
+ payload: r
219
+ }, n = this.graph.streamEvents(null, {
212
220
  ...this.config,
213
221
  configurable: {
214
222
  ...this.config.configurable,
215
- hitlResponse: n
223
+ hitlResponse: s
216
224
  },
217
225
  subgraphs: !0,
218
226
  version: "v2"
219
227
  });
220
- this.resolveWait?.(r);
221
- } catch (n) {
222
- this.rejectWait?.(n);
228
+ this.resolveWait?.(n);
229
+ } catch (s) {
230
+ this.rejectWait?.(s);
223
231
  } finally {
224
232
  this.resolveWait = void 0, this.rejectWait = void 0;
225
233
  }
@@ -231,157 +239,157 @@ class Y {
231
239
  this.rejectWait && (this.rejectWait(new Error("Request cancelled by user.")), this.resolveWait = void 0, this.rejectWait = void 0);
232
240
  }
233
241
  }
234
- const Z = async (t) => {
242
+ const te = async (t) => {
235
243
  try {
236
244
  return await (await M()).embedDocuments(t);
237
245
  } catch (e) {
238
246
  throw console.error("Failed to generate embeddings:", e), e;
239
247
  }
240
- }, E = async (t, e) => {
241
- const s = e.get(t);
242
- if (s)
243
- return s;
244
- const n = await Z([t]);
245
- return e.set(t, n[0]), n[0];
248
+ }, b = async (t, e) => {
249
+ const r = e.get(t);
250
+ if (r)
251
+ return r;
252
+ const s = await te([t]);
253
+ return e.set(t, s[0]), s[0];
246
254
  };
247
- async function ee(t, e, s, n) {
248
- const r = `req-${Date.now()}`, a = {
255
+ async function re(t, e, r, s) {
256
+ const n = `req-${Date.now()}`, i = {
249
257
  type: "layerSearch",
250
- precomputedEmbedding: n ? await E(t, n) : void 0,
251
- requestId: r,
252
- minScore: s
258
+ precomputedEmbedding: s ? await b(t, s) : void 0,
259
+ requestId: n,
260
+ minScore: r
253
261
  };
254
262
  return await new Promise((c) => {
255
263
  const d = (o) => {
256
- o.data.requestId === r && c(o.data.results);
264
+ o.data.requestId === n && c(o.data.results);
257
265
  };
258
- e.addEventListener("message", d, { once: !0 }), e.postMessage(a);
266
+ e.addEventListener("message", d, { once: !0 }), e.postMessage(i);
259
267
  });
260
268
  }
261
- function te(t) {
269
+ function ne(t) {
262
270
  const { worker: e } = t;
263
271
  return {
264
272
  async searchLayers({
265
- text: s,
266
- minScore: n,
267
- embeddingCache: r
273
+ text: r,
274
+ minScore: s,
275
+ embeddingCache: n
268
276
  }) {
269
- return await ee(s, e, n, r);
277
+ return await re(r, e, s, n);
270
278
  }
271
279
  };
272
280
  }
273
- const re = async ({
281
+ const se = async ({
274
282
  combinedQuery: t,
275
283
  layerIds: e,
276
- embeddingsWorker: s,
277
- minScore: n,
278
- topResults: r,
279
- embeddingCache: i
284
+ embeddingsWorker: r,
285
+ minScore: s,
286
+ topResults: n,
287
+ embeddingCache: a
280
288
  }) => {
281
- const a = `req-${Date.now()}`, c = i ? await E(t, i) : void 0, d = {
289
+ const i = `req-${Date.now()}`, c = a ? await b(t, a) : void 0, d = {
282
290
  type: "fieldSearch",
283
291
  layerIdForFieldsSearch: e,
284
292
  precomputedEmbedding: c,
285
- requestId: a,
286
- minScore: n,
287
- topResults: r
293
+ requestId: i,
294
+ minScore: s,
295
+ topResults: n
288
296
  };
289
297
  return await new Promise((o) => {
290
298
  const g = (u) => {
291
- if (u.data.requestId !== a)
299
+ if (u.data.requestId !== i)
292
300
  return;
293
- const p = u.data.results.map(({ layerId: m, results: h }) => ({
294
- layerId: m,
295
- results: h
301
+ const p = u.data.results.map(({ layerId: y, results: m }) => ({
302
+ layerId: y,
303
+ results: m
296
304
  }));
297
305
  o(p);
298
306
  };
299
- s.addEventListener("message", g, { once: !0 }), s.postMessage(d);
307
+ r.addEventListener("message", g, { once: !0 }), r.postMessage(d);
300
308
  });
301
309
  };
302
- function ne(t) {
310
+ function ae(t) {
303
311
  const { worker: e } = t;
304
312
  return {
305
- async searchFields({ text: s, layerIds: n, minScore: r, topResults: i, embeddingCache: a }) {
306
- return await re({
307
- combinedQuery: s,
308
- layerIds: n,
313
+ async searchFields({ text: r, layerIds: s, minScore: n, topResults: a, embeddingCache: i }) {
314
+ return await se({
315
+ combinedQuery: r,
316
+ layerIds: s,
309
317
  embeddingsWorker: e,
310
- minScore: r,
311
- topResults: i,
312
- embeddingCache: a
318
+ minScore: n,
319
+ topResults: a,
320
+ embeddingCache: i
313
321
  });
314
322
  }
315
323
  };
316
324
  }
317
- const se = (t) => {
318
- const e = C.safeParse(t);
325
+ const ie = (t) => {
326
+ const e = F.safeParse(t);
319
327
  if (!e.success)
320
328
  throw new Error("Embeddings response validation failed. Regenerate embeddings.");
321
329
  return e.data;
322
- }, ae = (t, e) => {
323
- const s = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
324
- if (e.allLayers.forEach((r) => {
325
- r instanceof q && n.set(r.id, r);
326
- }), t.length !== n.size)
330
+ }, oe = (t, e) => {
331
+ const r = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
332
+ if (e.allLayers.forEach((n) => {
333
+ n instanceof O && s.set(n.id, n);
334
+ }), t.length !== s.size)
327
335
  throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");
328
- for (const r of t) {
329
- const i = n.get(r.id);
330
- if (!i)
336
+ for (const n of t) {
337
+ const a = s.get(n.id);
338
+ if (!a)
331
339
  throw new Error(
332
- `Layer with ID ${r.id} not found in the original map during registry restoration. Regenerate embeddings.`
340
+ `Layer with ID ${n.id} not found in the original map during registry restoration. Regenerate embeddings.`
333
341
  );
334
- if (r.fields.length !== i.fields.length)
342
+ if (n.fields.length !== a.fields.length)
335
343
  throw new Error(
336
- `Field count mismatch for layer ID ${r.id} during registry restoration. Regenerate embeddings.`
344
+ `Field count mismatch for layer ID ${n.id} during registry restoration. Regenerate embeddings.`
337
345
  );
338
- const a = {
339
- name: r.name,
340
- title: r.title,
341
- description: r.description
346
+ const i = {
347
+ name: n.name,
348
+ title: n.title,
349
+ description: n.description
342
350
  }, c = /* @__PURE__ */ new Map();
343
- for (const d of r.fields) {
344
- const o = i.fieldsIndex.get(d.name);
351
+ for (const d of n.fields) {
352
+ const o = a.fieldsIndex.get(d.name);
345
353
  if (!o)
346
354
  throw new Error(
347
- `Field with name ${d.name} not found in the original layer ${r.id} during registry restoration. Regenerate embeddings.`
355
+ `Field with name ${d.name} not found in the original layer ${n.id} during registry restoration. Regenerate embeddings.`
348
356
  );
349
357
  c.set(d.name, {
350
358
  name: d.name,
351
- alias: i.getFieldAlias(d.name) ?? d.alias,
359
+ alias: a.getFieldAlias(d.name) ?? d.alias,
352
360
  description: d.description,
353
361
  type: o.type || "unknown",
354
362
  valueType: o.valueType || "unknown",
355
- domain: i.getFieldDomain(d.name) ?? void 0
363
+ domain: a.getFieldDomain(d.name) ?? void 0
356
364
  });
357
365
  }
358
- s.set(r.id, {
359
- layerItem: a,
366
+ r.set(n.id, {
367
+ layerItem: i,
360
368
  fieldRegistry: c
361
369
  });
362
370
  }
363
- return s;
364
- }, ie = async (t) => {
371
+ return r;
372
+ }, ce = async (t) => {
365
373
  try {
366
- return (await H(t, {
374
+ return (await T(t, {
367
375
  responseType: "json"
368
376
  })).data;
369
377
  } catch (e) {
370
378
  throw new Error(`Failed to fetch data from ${t}: ${String(e)}`);
371
379
  }
372
- }, oe = async (t) => {
380
+ }, de = async (t) => {
373
381
  const e = t.map;
374
382
  if (!e?.portalItem)
375
383
  throw new Error("WebMap portal item is missing.");
376
- const { resources: s } = await e.portalItem.fetchResources(), n = s.find((a) => a.resource.path === "embeddings-v01.json");
377
- if (!n?.resource.url)
384
+ const { resources: r } = await e.portalItem.fetchResources(), s = r.find((i) => i.resource.path === "embeddings-v01.json");
385
+ if (!s?.resource.url)
378
386
  throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");
379
- const r = await ie(n.resource.url);
380
- return se(r);
387
+ const n = await ce(s.resource.url);
388
+ return ie(n);
381
389
  };
382
- class v {
390
+ class x {
383
391
  constructor() {
384
- this.orchestratorReady = !1, this.chatHistory = [], this.priorSteps = [], this.sharedState = {}, this.threadId = "", this.agentRegistry = new X(), this.streamEpoch = 0;
392
+ this.orchestratorReady = !1, this.chatHistory = [], this.priorSteps = [], this.sharedState = {}, this.agentRegistry = new Z(), this.activeRunId = "", this.cancelledRunIds = /* @__PURE__ */ new Set(), this.streamEpoch = 0;
385
393
  }
386
394
  /**
387
395
  * Creates and returns an AI-ready Orchestrator instance.
@@ -389,21 +397,21 @@ class v {
389
397
  * @returns Ready Orchestrator.
390
398
  */
391
399
  static async init(e) {
392
- const s = new v();
400
+ const r = new x();
393
401
  try {
394
402
  if (e.view?.map) {
395
403
  await P.whenOnce(() => e.view.ready);
396
- const n = await oe(e.view), r = ae(
397
- n.layers,
404
+ const s = await de(e.view), n = oe(
405
+ s.layers,
398
406
  e.view.map
399
407
  );
400
- s.layersAndFieldsRegistry = r, s.embeddingsWorker = await O(n);
408
+ r.layersAndFieldsRegistry = n, r.embeddingsWorker = await U(s);
401
409
  }
402
- return e.agents?.forEach((n) => {
403
- s.agentRegistry.register(n);
404
- }), s.orchestratorReady = !0, s;
405
- } catch (n) {
406
- throw console.error("Orchestrator initialization failed:", n), n;
410
+ return e.agents?.forEach((s) => {
411
+ r.agentRegistry.register(s);
412
+ }), r.orchestratorReady = !0, r;
413
+ } catch (s) {
414
+ throw console.error("Orchestrator initialization failed:", s), s;
407
415
  }
408
416
  }
409
417
  /**
@@ -421,24 +429,26 @@ class v {
421
429
  throw new Error("Orchestrator has no registered agents.");
422
430
  if (++this.streamEpoch, !e.trim())
423
431
  return;
424
- this.threadId = String(Date.now()), this.graph || (this.graph = K().compile({ checkpointer: new $() }));
425
- const s = this.embeddingsWorker ? te({ worker: this.embeddingsWorker }) : void 0, n = this.embeddingsWorker ? ne({ worker: this.embeddingsWorker }) : void 0, r = /* @__PURE__ */ new Map(), a = {
432
+ const r = String(Date.now());
433
+ this.activeRunId = r, this.activeAbortController = new AbortController(), this.graph || (this.graph = Y().compile({ checkpointer: new j() }));
434
+ const s = this.embeddingsWorker ? ne({ worker: this.embeddingsWorker }) : void 0, n = this.embeddingsWorker ? ae({ worker: this.embeddingsWorker }) : void 0, a = /* @__PURE__ */ new Map(), c = {
426
435
  version: "v2",
427
436
  streamMode: "custom",
428
437
  configurable: {
429
438
  // eslint-disable-next-line @typescript-eslint/naming-convention
430
- thread_id: this.threadId,
439
+ thread_id: r,
440
+ abortSignal: this.activeAbortController.signal,
431
441
  hitlResponse: null,
432
442
  services: {
433
443
  layerSearch: s,
434
444
  fieldSearch: n,
435
445
  layersAndFieldsRegistry: this.layersAndFieldsRegistry,
436
446
  agentRegistry: this.agentRegistry,
437
- embeddingCache: r
447
+ embeddingCache: a
438
448
  }
439
449
  },
440
450
  subgraphs: !0
441
- }, c = this.graph?.streamEvents(
451
+ }, d = this.graph?.streamEvents(
442
452
  {
443
453
  agentExecutionContext: {
444
454
  userRequest: e,
@@ -447,36 +457,54 @@ class v {
447
457
  sharedState: this.sharedState
448
458
  }
449
459
  },
450
- a
451
- ), d = ++this.streamEpoch;
452
- for (yield* this.pipeStream(c, d); ; ) {
453
- const m = (await this.graph.getState(a, { subgraphs: !0 })).tasks.find((h) => h.interrupts.length > 0)?.interrupts[0]?.value;
460
+ c
461
+ ), o = ++this.streamEpoch;
462
+ if (yield* this.pipeStream(d, o, r), this.isRunCancelled(r)) {
463
+ yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
464
+ return;
465
+ }
466
+ for (; ; ) {
467
+ if (this.isRunCancelled(r)) {
468
+ yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
469
+ return;
470
+ }
471
+ const m = (await this.graph.getState(c, { subgraphs: !0 })).tasks.find((h) => h.interrupts.length > 0)?.interrupts[0]?.value;
454
472
  if (!m)
455
473
  break;
456
- this.currentInterrupt = m, this.interruptHandler = new Y(this.graph, a), yield { runId: this.threadId, timestamp: Date.now(), type: "interrupt", interrupt: m };
474
+ this.currentInterrupt = m, this.interruptHandler = new ee(this.graph, c), yield { runId: r, timestamp: Date.now(), type: "interrupt", interrupt: m };
457
475
  try {
458
- const h = await this.interruptHandler.waitForUser(), x = ++this.streamEpoch;
459
- yield* this.pipeStream(h, x);
476
+ const h = await this.interruptHandler.waitForUser(), S = ++this.streamEpoch;
477
+ yield* this.pipeStream(h, S, r);
460
478
  } catch (h) {
479
+ if (this.isRunCancelled(r)) {
480
+ yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
481
+ return;
482
+ }
461
483
  if (h) {
462
484
  yield {
463
- runId: this.threadId,
485
+ runId: r,
464
486
  timestamp: Date.now(),
465
487
  type: "error",
466
488
  error: { message: h?.message }
467
489
  };
468
490
  return;
469
491
  }
470
- yield { runId: this.threadId, timestamp: Date.now(), type: "cancelled" };
471
- return;
472
492
  }
473
493
  }
474
- const g = (await this.graph.getState(a, { subgraphs: !0 })).values;
475
- this.chatHistory = g.agentExecutionContext.messages.length ? g.agentExecutionContext.messages : this.chatHistory, this.priorSteps = g.agentExecutionContext.priorSteps?.slice(-5) ?? [], this.sharedState = g.agentExecutionContext.sharedState ?? {}, yield {
476
- runId: this.threadId,
494
+ if (this.isRunCancelled(r)) {
495
+ yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
496
+ return;
497
+ }
498
+ const u = (await this.graph.getState(c, { subgraphs: !0 })).values;
499
+ if (this.isRunCancelled(r)) {
500
+ yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
501
+ return;
502
+ }
503
+ this.chatHistory = u.agentExecutionContext.messages.length ? u.agentExecutionContext.messages : this.chatHistory, this.priorSteps = u.agentExecutionContext.priorSteps?.slice(-5) ?? [], this.sharedState = u.agentExecutionContext.sharedState ?? {}, yield {
504
+ runId: r,
477
505
  timestamp: Date.now(),
478
506
  type: "completed",
479
- result: { content: g.finalOutputMessage }
507
+ result: { content: u.finalOutputMessage }
480
508
  };
481
509
  }
482
510
  /**
@@ -500,20 +528,31 @@ class v {
500
528
  cancelInterrupt() {
501
529
  this.interruptHandler && this.interruptHandler.cancel();
502
530
  }
503
- async *pipeStream(e, s) {
531
+ /**
532
+ * Cancels the active run.
533
+ *
534
+ * - Aborts in-flight work for consumers that honor AbortSignal.
535
+ * - Invalidates active stream iterators via epoch bump.
536
+ * - Unblocks any pending HITL wait.
537
+ */
538
+ cancel() {
539
+ this.activeRunId && (this.cancelledRunIds.add(this.activeRunId), this.activeAbortController?.abort(), ++this.streamEpoch, this.interruptHandler?.cancel());
540
+ }
541
+ async *pipeStream(e, r, s) {
504
542
  for await (const n of e) {
505
- if (s !== this.streamEpoch) {
506
- console.log("Stale stream detected, aborting.");
543
+ if (this.isRunCancelled(s) || r !== this.streamEpoch)
507
544
  break;
508
- }
509
- n.event === "on_custom_event" && n.name === "trace_message" ? yield { runId: this.threadId, timestamp: Date.now(), type: "trace", data: n.data } : n.name === "graph_ux_suggestion" && (yield {
510
- runId: this.threadId,
545
+ n.event === "on_custom_event" && n.name === "trace_message" ? yield { runId: s, timestamp: Date.now(), type: "trace", data: n.data } : n.name === "graph_ux_suggestion" && (yield {
546
+ runId: s,
511
547
  timestamp: Date.now(),
512
548
  type: "ux-suggestion",
513
549
  suggestion: n.data
514
550
  });
515
551
  }
516
552
  }
553
+ isRunCancelled(e) {
554
+ return this.cancelledRunIds.has(e);
555
+ }
517
556
  /**
518
557
  * Disposes this instance by terminating the embeddings worker
519
558
  * and cleaning up all related resources.
@@ -523,6 +562,6 @@ class v {
523
562
  }
524
563
  }
525
564
  export {
526
- v as O,
527
- Z as g
565
+ x as O,
566
+ te as g
528
567
  };