@arcgis/ai-components 5.2.0-next.88 → 5.2.0-next.89

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 (50) hide show
  1. package/dist/agent-utils/LLMAgent.js +1 -0
  2. package/dist/cdn/{7FY7WAA5.js → 222B5OU6.js} +1 -1
  3. package/dist/cdn/{APDJ4EPR.js → 2FOCAXWJ.js} +1 -1
  4. package/dist/cdn/6VJXUIXY.js +3 -0
  5. package/dist/cdn/{HJEYVERV.js → C5ZL5Z52.js} +5 -5
  6. package/dist/cdn/{EUM4DZDR.js → COL6QYGQ.js} +1 -1
  7. package/dist/cdn/{R7CCQNIY.js → CXP3ACSA.js} +1 -1
  8. package/dist/cdn/{ESHAIDS7.js → FUZ77UGP.js} +4 -4
  9. package/dist/cdn/{MBBDTSIF.js → HKSFWTWK.js} +5 -5
  10. package/dist/cdn/{GPXL4CYF.js → LPR72QZF.js} +2 -2
  11. package/dist/cdn/{64K5QGMS.js → LS4FJKFE.js} +1 -1
  12. package/dist/cdn/{YNWG4AIR.js → OYSPNIJI.js} +21 -21
  13. package/dist/cdn/{FAR3DFFK.js → PEYYWXFE.js} +1 -1
  14. package/dist/cdn/{C4MALUDF.js → SUYWKYWI.js} +2 -2
  15. package/dist/cdn/{PULEMR55.js → VTQKRCKU.js} +1 -1
  16. package/dist/cdn/Y5TYSBLZ.js +3 -0
  17. package/dist/cdn/{PQ5HW7F5.js → Y7QZBO46.js} +1 -1
  18. package/dist/cdn/{EMLOVMD4.js → ZVGUAOXE.js} +1 -1
  19. package/dist/cdn/agent-utils/index.js +1 -1
  20. package/dist/cdn/index.js +1 -1
  21. package/dist/chunks/adapter.js +55 -54
  22. package/dist/chunks/arcgisKnowledgeGraph.js +3 -2
  23. package/dist/chunks/dataExplorationGraph.js +3 -2
  24. package/dist/chunks/helpGraph.js +3 -2
  25. package/dist/chunks/layerStylingGraph.js +1 -0
  26. package/dist/chunks/navigationGraph.js +3 -2
  27. package/dist/chunks/orchestrator.js +322 -193
  28. package/dist/chunks/toolCallResponse.js +3 -2
  29. package/dist/components/arcgis-assistant/customElement.d.ts +16 -0
  30. package/dist/components/arcgis-assistant/customElement.js +190 -178
  31. package/dist/components/arcgis-assistant-agent/customElement.js +1 -0
  32. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -0
  33. package/dist/components/arcgis-assistant-help-agent/customElement.js +1 -0
  34. package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -0
  35. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +6 -5
  36. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -0
  37. package/dist/docs/api.json +1 -1
  38. package/dist/docs/docs.json +1 -1
  39. package/dist/docs/vscode.html-custom-data.json +1 -1
  40. package/dist/docs/web-types.json +1 -1
  41. package/dist/loader.js +1 -1
  42. package/dist/orchestrator/orchestrator/orchestratorEvents.d.ts +78 -0
  43. package/dist/types/lumina.d.ts +2 -1
  44. package/dist/types/preact.d.ts +2 -1
  45. package/dist/types/react.d.ts +2 -1
  46. package/dist/types/stencil.d.ts +2 -1
  47. package/package.json +5 -5
  48. package/dist/cdn/L7XTRDFM.js +0 -3
  49. package/dist/cdn/ZUNLFO6M.js +0 -3
  50. /package/dist/cdn/{ONMNQBPO.js → SZ2QSSB3.js} +0 -0
@@ -1,81 +1,82 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
2
  import A from "@arcgis/core/identity/IdentityManager.js";
3
- import C from "@arcgis/core/portal/Portal.js";
4
- import { j as k, k as b, D as M, n as D, o as F, W as $ } from "./generateLayerDescriptions.js";
5
- import { isGraphInterrupt as L, StateGraph as W, START as q, END as j, MemorySaver as H } from "@langchain/langgraph/web";
6
- import { generateGuid as P } from "@arcgis/toolkit/string";
7
- import { HumanMessage as O, AIMessage as T } from "@langchain/core/messages";
8
- import { s as l } from "./index.js";
9
- import * as U from "@arcgis/core/core/reactiveUtils.js";
10
- import N from "@arcgis/core/layers/FeatureLayer.js";
11
- import G from "@arcgis/core/request.js";
12
- const _ = async (t) => {
13
- const e = await V(), n = await k("default"), s = C.getDefault(), a = (await A.getCredential(`${s.url}/sharing`)).token, i = {
3
+ import M from "@arcgis/core/portal/Portal.js";
4
+ import { j as _, k as x, D, n as F, o as L, W as $ } from "./generateLayerDescriptions.js";
5
+ import { isGraphInterrupt as W, StateGraph as q, START as T, END as H, MemorySaver as j } from "@langchain/langgraph/web";
6
+ import { generateGuid as U } from "@arcgis/toolkit/string";
7
+ import { HumanMessage as P, AIMessage as O } from "@langchain/core/messages";
8
+ import { s as m } from "./index.js";
9
+ import { BaseCallbackHandler as N } from "@langchain/core/callbacks/base";
10
+ import * as G from "@arcgis/core/core/reactiveUtils.js";
11
+ import V from "@arcgis/core/layers/FeatureLayer.js";
12
+ import z from "@arcgis/core/request.js";
13
+ const B = async (t) => {
14
+ const e = await Q(), r = await _("default"), s = M.getDefault(), a = (await A.getCredential(`${s.url}/sharing`)).token, i = {
14
15
  type: "generateEmbeddings",
15
16
  webmapEmbeddings: t,
16
- auth: { apiUrl: n, token: a }
17
+ auth: { apiUrl: r, token: a }
17
18
  };
18
19
  return e.postMessage(i), await new Promise((c, d) => {
19
- const o = (u) => {
20
- u.data === "completed" && (e.removeEventListener("message", o), c());
21
- }, g = (u) => {
22
- e.removeEventListener("message", o), d(u instanceof Error ? u : new Error("Embeddings worker error"));
20
+ const o = (g) => {
21
+ g.data === "completed" && (e.removeEventListener("message", o), c());
22
+ }, u = (g) => {
23
+ e.removeEventListener("message", o), d(g instanceof Error ? g : new Error("Embeddings worker error"));
23
24
  };
24
- e.addEventListener("message", o), e.addEventListener("error", g, { once: !0 });
25
+ e.addEventListener("message", o), e.addEventListener("error", u, { once: !0 });
25
26
  }), e;
26
- }, V = async () => {
27
+ }, Q = async () => {
27
28
  {
28
29
  const t = (await import("./embeddings.worker.js")).default;
29
30
  return new t();
30
31
  }
31
- }, z = (t) => {
32
+ }, J = (t) => {
32
33
  t.currentIntent = "none";
33
- }, Q = async (t, e) => {
34
- const n = b(e);
34
+ }, K = async (t, e) => {
35
+ const r = x(e);
35
36
  if (t.agentExecutionContext.userRequest) {
36
- const r = new O(t.agentExecutionContext.userRequest.trim());
37
- t.agentExecutionContext.messages = [...t.agentExecutionContext.messages, r], z(t);
37
+ const n = new P(t.agentExecutionContext.userRequest.trim());
38
+ t.agentExecutionContext.messages = [...t.agentExecutionContext.messages, n], J(t);
38
39
  }
39
- const s = n?.services.agentRegistry.list().map((r) => r.agent.id) ?? [];
40
- return await l({ text: `Available agents: ${[...s].join(", ")}` }, e), await l({ text: "Analyzing user input" }, e), t;
41
- }, B = async (t, e) => (await l({ text: "Exiting..." }, e), t), f = (t) => typeof t == "object" && t !== null && !Array.isArray(t), J = (t, e) => {
42
- if (!f(t)) {
40
+ const s = r?.services.agentRegistry.list().map((n) => n.agent.id) ?? [];
41
+ return await m({ text: `Available agents: ${[...s].join(", ")}` }, e), await m({ text: "Analyzing user input" }, e), t;
42
+ }, X = async (t, e) => (await m({ text: "Exiting..." }, e), t), E = (t) => typeof t == "object" && t !== null && !Array.isArray(t), Y = (t, e) => {
43
+ if (!E(t)) {
43
44
  t !== void 0 && console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);
44
45
  return;
45
46
  }
46
- const n = {};
47
- for (const [s, r] of Object.entries(t)) {
48
- if (!f(r) || !("value" in r)) {
47
+ const r = {};
48
+ for (const [s, n] of Object.entries(t)) {
49
+ if (!E(n) || !("value" in n)) {
49
50
  console.warn(
50
51
  `Agent "${e}" returned invalid sharedStatePatch entry for key "${s}". Ignoring that entry.`
51
52
  );
52
53
  continue;
53
54
  }
54
- n[s] = { value: r.value };
55
+ r[s] = { value: n.value };
55
56
  }
56
- return n;
57
- }, K = (t) => {
58
- const { previousSharedState: e, patch: n, agentId: s } = t;
59
- if (!n)
57
+ return r;
58
+ }, Z = (t) => {
59
+ const { previousSharedState: e, patch: r, agentId: s } = t;
60
+ if (!r)
60
61
  return e;
61
- const r = Date.now(), a = {
62
+ const n = Date.now(), a = {
62
63
  ...e
63
64
  };
64
- for (const [i, c] of Object.entries(n))
65
+ for (const [i, c] of Object.entries(r))
65
66
  c?.value !== void 0 && (a[i] = {
66
67
  value: c.value,
67
68
  meta: {
68
69
  updatedByAgentId: s,
69
- updatedAt: r
70
+ updatedAt: n
70
71
  }
71
72
  });
72
73
  return a;
73
- }, E = (t) => {
74
+ }, S = (t) => {
74
75
  if (typeof t != "string")
75
76
  return;
76
77
  const e = t.trim();
77
78
  return e || void 0;
78
- }, X = (t) => {
79
+ }, ee = (t) => {
79
80
  switch (t) {
80
81
  case "failed":
81
82
  return "Agent failed without a summary.";
@@ -86,39 +87,43 @@ const _ = async (t) => {
86
87
  default:
87
88
  return "Agent completed without a summary.";
88
89
  }
89
- }, Y = (t, e) => {
90
- const n = E(e?.outputMessage), s = E(e?.summary), r = e?.status, a = r === "success" || r === "failed" ? r : "unknown";
90
+ }, te = (t, e) => {
91
+ const r = S(e?.outputMessage), s = S(e?.summary), n = e?.status, a = n === "success" || n === "failed" ? n : "unknown";
91
92
  a === "unknown" && console.warn(`Agent "${t}" returned missing/invalid status. Defaulting to "unknown".`);
92
- const i = J(e?.sharedStatePatch, t);
93
+ const i = Y(e?.sharedStatePatch, t);
93
94
  return {
94
- outputMessage: n,
95
- summary: s ?? n ?? X(a),
95
+ outputMessage: r,
96
+ summary: s ?? r ?? ee(a),
96
97
  status: a,
97
98
  sharedStatePatch: i
98
99
  };
99
- }, x = 4e3, Z = async (t, e) => {
100
- const n = b(e);
100
+ }, b = 4e3, ne = async (t, e) => {
101
+ const r = x(e);
101
102
  if (e?.signal?.aborted)
102
- return await l({ text: "Run cancelled; skipping agent execution" }, e), {
103
+ return await m({ text: "Run cancelled; skipping agent execution" }, e), {
103
104
  ...t,
104
105
  currentIntent: "none",
105
106
  requiresFollowUp: !1
106
107
  };
107
- const { agentRegistry: s } = n?.services ?? {}, r = s?.get(t.currentIntent);
108
- if (!r)
108
+ const { agentRegistry: s } = r?.services ?? {}, n = s?.get(t.currentIntent);
109
+ if (!n)
109
110
  return console.warn(`No agent found for intent: ${t.currentIntent}`), t;
110
- await l({ text: `Executing registered agent: ${r.agent.name}` }, e);
111
+ await m({ text: `Executing registered agent: ${n.agent.name}` }, e);
111
112
  const a = {
112
113
  ...e ?? {},
114
+ metadata: {
115
+ ...e?.metadata,
116
+ agentId: n.agent.id
117
+ },
113
118
  configurable: {
114
- ...n ?? {},
115
- agentId: r.agent.id,
116
- context: r.getContext ? await r.getContext() : void 0
119
+ ...r ?? {},
120
+ agentId: n.agent.id,
121
+ context: n.getContext ? await n.getContext() : void 0
117
122
  }
118
123
  };
119
124
  let i;
120
125
  try {
121
- const o = await r.agent.createGraph().compile().invoke(
126
+ const o = await n.agent.createGraph().compile().invoke(
122
127
  {
123
128
  agentExecutionContext: {
124
129
  ...t.agentExecutionContext,
@@ -131,27 +136,27 @@ const _ = async (t) => {
131
136
  },
132
137
  a
133
138
  );
134
- i = Y(r.agent.name, o), await l({ text: `Finished executing registered agent: ${r.agent.name}` }, e);
139
+ i = te(n.agent.name, o), await m({ text: `Finished executing registered agent: ${n.agent.name}` }, e);
135
140
  } catch (o) {
136
- if (L(o) || e?.signal?.aborted || o instanceof Error && o.name === "AbortError")
141
+ if (W(o) || e?.signal?.aborted || o instanceof Error && o.name === "AbortError")
137
142
  throw o;
138
- const g = o instanceof Error ? o.message : String(o);
139
- console.error(`Agent "${r.agent.name}" failed:`, o), await l({ text: `Registered agent failed: ${r.agent.name}. ${g}` }, e), i = {
143
+ const u = o instanceof Error ? o.message : String(o);
144
+ console.error(`Agent "${n.agent.name}" failed:`, o), await m({ text: `Registered agent failed: ${n.agent.name}. ${u}` }, e), i = {
140
145
  status: "failed",
141
- outputMessage: `Agent execution failed: ${g}`,
142
- summary: `Agent execution failed: ${g}`
146
+ outputMessage: `Agent execution failed: ${u}`,
147
+ summary: `Agent execution failed: ${u}`
143
148
  };
144
149
  }
145
150
  const c = i.outputMessage, d = [...t.agentExecutionContext.messages];
146
151
  if (c) {
147
- const o = c.length > x ? `${c.slice(0, x - 14)}
152
+ const o = c.length > b ? `${c.slice(0, b - 14)}
148
153
  [truncated]` : c;
149
- d.push(new T(o));
154
+ d.push(new O(o));
150
155
  }
151
156
  return {
152
157
  ...t,
153
158
  stepCount: t.stepCount + 1,
154
- lastExecutedAgent: r.agent.id,
159
+ lastExecutedAgent: n.agent.id,
155
160
  requiresFollowUp: i.status === "failed" ? !0 : t.requiresFollowUp,
156
161
  finalOutputMessage: c ?? "",
157
162
  agentExecutionContext: {
@@ -160,23 +165,23 @@ const _ = async (t) => {
160
165
  priorSteps: [
161
166
  ...t.agentExecutionContext.priorSteps ?? [],
162
167
  {
163
- agentId: r.agent.id,
168
+ agentId: n.agent.id,
164
169
  assignedTask: t.agentExecutionContext.assignedTask,
165
170
  summary: i?.summary || "No summary provided.",
166
171
  status: i?.status || "unknown"
167
172
  }
168
173
  ],
169
- sharedState: K({
174
+ sharedState: Z({
170
175
  previousSharedState: t.agentExecutionContext.sharedState,
171
176
  patch: i.sharedStatePatch,
172
- agentId: r.agent.id
177
+ agentId: n.agent.id
173
178
  })
174
179
  }
175
180
  };
176
- }, ee = async (t, e) => {
181
+ }, re = async (t, e) => {
177
182
  if (t.routing.mode !== "direct")
178
183
  throw new Error("Direct agent assignment requires direct routing.");
179
- return await l({ text: `Doing a direct route to agent: ${t.routing.agentId}` }, e), {
184
+ return await m({ text: `Doing a direct route to agent: ${t.routing.agentId}` }, e), {
180
185
  ...t,
181
186
  currentIntent: t.routing.agentId,
182
187
  requiresFollowUp: !1,
@@ -185,16 +190,93 @@ const _ = async (t) => {
185
190
  assignedTask: t.agentExecutionContext.userRequest
186
191
  }
187
192
  };
188
- }, te = 3, re = (t) => t.routing.mode === "direct" ? "assignDirectAgent" : "intentLLM", ne = (t) => t.routing.mode === "direct" || t.stepCount >= te || !t.requiresFollowUp ? "exit" : "intentLLM", se = () => new W(M).addNode("ingestInput", Q).addNode("assignDirectAgent", ee).addNode("intentLLM", D).addNode("executeRegisteredAgent", Z).addNode("exit", B).addEdge(q, "ingestInput").addConditionalEdges("ingestInput", re).addEdge("assignDirectAgent", "executeRegisteredAgent").addConditionalEdges("intentLLM", (e) => e.currentIntent === "none" || e.currentIntent === e.lastExecutedAgent ? "exit" : "executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent", ne).addEdge("exit", j);
189
- class v {
193
+ }, se = 3, ae = (t) => t.routing.mode === "direct" ? "assignDirectAgent" : "intentLLM", ie = (t) => t.routing.mode === "direct" || t.stepCount >= se || !t.requiresFollowUp ? "exit" : "intentLLM", oe = () => new q(D).addNode("ingestInput", K).addNode("assignDirectAgent", re).addNode("intentLLM", F).addNode("executeRegisteredAgent", ne).addNode("exit", X).addEdge(T, "ingestInput").addConditionalEdges("ingestInput", ae).addEdge("assignDirectAgent", "executeRegisteredAgent").addConditionalEdges("intentLLM", (e) => e.currentIntent === "none" || e.currentIntent === e.lastExecutedAgent ? "exit" : "executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent", ie).addEdge("exit", H), ce = (t, e) => {
194
+ const r = t.output?.usage_metadata ?? e.usage_metadata, s = t.output?.llmOutput?.tokenUsage, n = r?.input_tokens ?? s?.promptTokens, a = r?.output_tokens ?? s?.completionTokens, i = r?.total_tokens ?? s?.totalTokens;
195
+ if (n === void 0 || a === void 0 || i === void 0)
196
+ return;
197
+ const c = r?.input_token_details?.cache_read, d = r?.output_token_details?.reasoning;
198
+ return {
199
+ input: n,
200
+ output: a,
201
+ total: i,
202
+ ...c !== void 0 && { cacheRead: c },
203
+ ...d !== void 0 && { reasoning: d }
204
+ };
205
+ }, de = (t, e, r, s) => {
206
+ switch (t) {
207
+ case "chat_model":
208
+ case "llm":
209
+ return "model";
210
+ case "tool":
211
+ case "retriever":
212
+ return t;
213
+ case "chain":
214
+ return !s || e === "LangGraph" ? "workflow" : r === e ? "node" : "chain";
215
+ default:
216
+ return;
217
+ }
218
+ }, ue = (t) => {
219
+ if (t instanceof Error)
220
+ return { message: t.message, name: t.name };
221
+ const e = t, r = typeof e?.message == "string" ? e.message : String(t ?? "Unknown runtime error"), s = typeof e?.name == "string" ? e.name : void 0;
222
+ return { message: r, ...s && { name: s } };
223
+ }, ge = ({
224
+ event: t,
225
+ runId: e,
226
+ parentSpanId: r,
227
+ timestamp: s
228
+ }) => {
229
+ const n = /^on_(.+)_(start|end|error)$/u.exec(t.event);
230
+ if (!n)
231
+ return;
232
+ const [, a, i] = n, c = t.metadata ?? {}, d = c.langgraph_node, o = de(a, t.name, d, r);
233
+ if (!o)
234
+ return;
235
+ const u = c.agentId, g = c.model ?? c.ls_model_name, l = t.data, y = i === "end" && o === "model" ? ce(l, c) : void 0, h = t.tags?.includes("langsmith:hidden") || d === "__start__", v = {
236
+ ...g && { model: g },
237
+ ...y && { tokenUsage: y },
238
+ ...h && { internal: !0 }
239
+ }, w = {
240
+ id: t.run_id,
241
+ ...r && { parentId: r },
242
+ label: t.name,
243
+ type: o,
244
+ ...Object.keys(v).length && { metadata: v }
245
+ }, p = { runId: e, timestamp: s, type: "runtime", ...u && { agentId: u } };
246
+ switch (i) {
247
+ case "start":
248
+ return {
249
+ ...p,
250
+ phase: "started",
251
+ span: {
252
+ ...w,
253
+ ...l?.input !== void 0 && { input: l.input }
254
+ }
255
+ };
256
+ case "end":
257
+ return {
258
+ ...p,
259
+ phase: "completed",
260
+ span: {
261
+ ...w,
262
+ ...l?.output !== void 0 && { output: l.output }
263
+ }
264
+ };
265
+ case "error":
266
+ return { ...p, phase: "failed", span: { ...w, error: ue(l?.error) } };
267
+ default:
268
+ return;
269
+ }
270
+ };
271
+ class R {
190
272
  constructor() {
191
273
  this.agentRegistry = /* @__PURE__ */ new Map();
192
274
  }
193
275
  register(e) {
194
- const { agent: n } = e;
195
- if (this.agentRegistry.has(n.id))
196
- throw new Error(`Duplicate agent id: ${n.id}`);
197
- this.agentRegistry.set(n.id, e);
276
+ const { agent: r } = e;
277
+ if (this.agentRegistry.has(r.id))
278
+ throw new Error(`Duplicate agent id: ${r.id}`);
279
+ this.agentRegistry.set(r.id, e);
198
280
  }
199
281
  get(e) {
200
282
  return this.agentRegistry.get(e);
@@ -203,31 +285,31 @@ class v {
203
285
  return [...this.agentRegistry.values()];
204
286
  }
205
287
  }
206
- class ae {
288
+ class le {
207
289
  /**
208
290
  * Create a new InterruptHandler tied to a specific compiled graph and config.
209
291
  */
210
- constructor(e, n) {
211
- this.graph = e, this.config = { ...n };
292
+ constructor(e, r) {
293
+ this.graph = e, this.config = { ...r };
212
294
  }
213
295
  /**
214
296
  * Returns a promise that resolves when the user provides a HITL response.
215
297
  */
216
298
  async waitForUser() {
217
- return await new Promise((e, n) => {
218
- this.resolveWait = e, this.rejectWait = n;
299
+ return await new Promise((e, r) => {
300
+ this.resolveWait = e, this.rejectWait = r;
219
301
  });
220
302
  }
221
303
  /**
222
304
  * Resume graph execution after the UI responds to an interrupt.
223
305
  */
224
- handle(e, n) {
306
+ handle(e, r) {
225
307
  try {
226
308
  const s = {
227
309
  agentId: e.agentId,
228
310
  id: e.id,
229
- payload: n
230
- }, r = this.graph.streamEvents(null, {
311
+ payload: r
312
+ }, n = this.graph.streamEvents(null, {
231
313
  ...this.config,
232
314
  configurable: {
233
315
  ...this.config.configurable,
@@ -236,7 +318,7 @@ class ae {
236
318
  subgraphs: !0,
237
319
  version: "v2"
238
320
  });
239
- this.resolveWait?.(r);
321
+ this.resolveWait?.(n);
240
322
  } catch (s) {
241
323
  this.rejectWait?.(s);
242
324
  } finally {
@@ -250,120 +332,120 @@ class ae {
250
332
  this.rejectWait && (this.rejectWait(new Error("Request cancelled by user.")), this.resolveWait = void 0, this.rejectWait = void 0);
251
333
  }
252
334
  }
253
- const ie = async (t) => {
335
+ const he = async (t) => {
254
336
  try {
255
- return await (await F()).embedDocuments(t);
337
+ return await (await L()).embedDocuments(t);
256
338
  } catch (e) {
257
339
  throw console.error("Failed to generate embeddings:", e), e;
258
340
  }
259
- }, S = async (t, e) => {
260
- const n = e.get(t);
261
- if (n)
262
- return n;
263
- const s = await ie([t]);
341
+ }, C = async (t, e) => {
342
+ const r = e.get(t);
343
+ if (r)
344
+ return r;
345
+ const s = await he([t]);
264
346
  return e.set(t, s[0]), s[0];
265
347
  };
266
- async function oe(t, e, n, s) {
267
- const r = `req-${Date.now()}`, i = {
348
+ async function me(t, e, r, s) {
349
+ const n = `req-${Date.now()}`, i = {
268
350
  type: "layerSearch",
269
- precomputedEmbedding: s ? await S(t, s) : void 0,
270
- requestId: r,
271
- minScore: n
351
+ precomputedEmbedding: s ? await C(t, s) : void 0,
352
+ requestId: n,
353
+ minScore: r
272
354
  };
273
355
  return await new Promise((c) => {
274
356
  const d = (o) => {
275
- o.data.requestId === r && c(o.data.results);
357
+ o.data.requestId === n && c(o.data.results);
276
358
  };
277
359
  e.addEventListener("message", d, { once: !0 }), e.postMessage(i);
278
360
  });
279
361
  }
280
- function ce(t) {
362
+ function pe(t) {
281
363
  const { worker: e } = t;
282
364
  return {
283
365
  async searchLayers({
284
- text: n,
366
+ text: r,
285
367
  minScore: s,
286
- embeddingCache: r
368
+ embeddingCache: n
287
369
  }) {
288
- return await oe(n, e, s, r);
370
+ return await me(r, e, s, n);
289
371
  }
290
372
  };
291
373
  }
292
- const de = async ({
374
+ const fe = async ({
293
375
  combinedQuery: t,
294
376
  layerIds: e,
295
- embeddingsWorker: n,
377
+ embeddingsWorker: r,
296
378
  minScore: s,
297
- topResults: r,
379
+ topResults: n,
298
380
  embeddingCache: a
299
381
  }) => {
300
- const i = `req-${Date.now()}`, c = a ? await S(t, a) : void 0, d = {
382
+ const i = `req-${Date.now()}`, c = a ? await C(t, a) : void 0, d = {
301
383
  type: "fieldSearch",
302
384
  layerIdForFieldsSearch: e,
303
385
  precomputedEmbedding: c,
304
386
  requestId: i,
305
387
  minScore: s,
306
- topResults: r
388
+ topResults: n
307
389
  };
308
390
  return await new Promise((o) => {
309
- const g = (u) => {
310
- if (u.data.requestId !== i)
391
+ const u = (g) => {
392
+ if (g.data.requestId !== i)
311
393
  return;
312
- const p = u.data.results.map(({ layerId: y, results: h }) => ({
394
+ const l = g.data.results.map(({ layerId: y, results: h }) => ({
313
395
  layerId: y,
314
396
  results: h
315
397
  }));
316
- o(p);
398
+ o(l);
317
399
  };
318
- n.addEventListener("message", g, { once: !0 }), n.postMessage(d);
400
+ r.addEventListener("message", u, { once: !0 }), r.postMessage(d);
319
401
  });
320
402
  };
321
- function ge(t) {
403
+ function ye(t) {
322
404
  const { worker: e } = t;
323
405
  return {
324
- async searchFields({ text: n, layerIds: s, minScore: r, topResults: a, embeddingCache: i }) {
325
- return await de({
326
- combinedQuery: n,
406
+ async searchFields({ text: r, layerIds: s, minScore: n, topResults: a, embeddingCache: i }) {
407
+ return await fe({
408
+ combinedQuery: r,
327
409
  layerIds: s,
328
410
  embeddingsWorker: e,
329
- minScore: r,
411
+ minScore: n,
330
412
  topResults: a,
331
413
  embeddingCache: i
332
414
  });
333
415
  }
334
416
  };
335
417
  }
336
- const ue = (t) => {
418
+ const we = (t) => {
337
419
  const e = $.safeParse(t);
338
420
  if (!e.success)
339
421
  throw new Error("Embeddings response validation failed. Regenerate embeddings.");
340
422
  return e.data;
341
- }, le = (t, e) => {
342
- const n = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
343
- if (e.allLayers.forEach((r) => {
344
- r instanceof N && s.set(r.id, r);
423
+ }, ve = (t, e) => {
424
+ const r = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
425
+ if (e.allLayers.forEach((n) => {
426
+ n instanceof V && s.set(n.id, n);
345
427
  }), t.length !== s.size)
346
428
  throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");
347
- for (const r of t) {
348
- const a = s.get(r.id);
429
+ for (const n of t) {
430
+ const a = s.get(n.id);
349
431
  if (!a)
350
432
  throw new Error(
351
- `Layer with ID ${r.id} not found in the original map during registry restoration. Regenerate embeddings.`
433
+ `Layer with ID ${n.id} not found in the original map during registry restoration. Regenerate embeddings.`
352
434
  );
353
- if (r.fields.length !== a.fields.length)
435
+ if (n.fields.length !== a.fields.length)
354
436
  throw new Error(
355
- `Field count mismatch for layer ID ${r.id} during registry restoration. Regenerate embeddings.`
437
+ `Field count mismatch for layer ID ${n.id} during registry restoration. Regenerate embeddings.`
356
438
  );
357
439
  const i = {
358
- name: r.name,
359
- title: r.title,
360
- description: r.description
440
+ name: n.name,
441
+ title: n.title,
442
+ description: n.description
361
443
  }, c = /* @__PURE__ */ new Map();
362
- for (const d of r.fields) {
444
+ for (const d of n.fields) {
363
445
  const o = a.fieldsIndex.get(d.name);
364
446
  if (!o)
365
447
  throw new Error(
366
- `Field with name ${d.name} not found in the original layer ${r.id} during registry restoration. Regenerate embeddings.`
448
+ `Field with name ${d.name} not found in the original layer ${n.id} during registry restoration. Regenerate embeddings.`
367
449
  );
368
450
  c.set(d.name, {
369
451
  name: d.name,
@@ -374,33 +456,33 @@ const ue = (t) => {
374
456
  domain: a.getFieldDomain(d.name) ?? void 0
375
457
  });
376
458
  }
377
- n.set(r.id, {
459
+ r.set(n.id, {
378
460
  layerItem: i,
379
461
  fieldRegistry: c
380
462
  });
381
463
  }
382
- return n;
383
- }, he = async (t) => {
464
+ return r;
465
+ }, Ee = async (t) => {
384
466
  try {
385
- return (await G(t, {
467
+ return (await z(t, {
386
468
  responseType: "json"
387
469
  })).data;
388
470
  } catch (e) {
389
471
  throw new Error(`Failed to fetch data from ${t}: ${String(e)}`);
390
472
  }
391
- }, me = async (t) => {
473
+ }, Se = async (t) => {
392
474
  const e = t.map;
393
475
  if (!e?.portalItem)
394
476
  throw new Error("WebMap portal item is missing.");
395
- const { resources: n } = await e.portalItem.fetchResources(), s = n.find((i) => i.resource.path === "embeddings-v01.json");
477
+ const { resources: r } = await e.portalItem.fetchResources(), s = r.find((i) => i.resource.path === "embeddings-v01.json");
396
478
  if (!s?.resource.url)
397
479
  throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");
398
- const r = await he(s.resource.url);
399
- return ue(r);
480
+ const n = await Ee(s.resource.url);
481
+ return we(n);
400
482
  };
401
- class R {
483
+ class k {
402
484
  constructor() {
403
- this.orchestratorReady = !1, this.chatHistory = [], this.priorSteps = [], this.sharedState = {}, this.agentRegistry = new v(), this.activeRunId = "", this.cancelledRunIds = /* @__PURE__ */ new Set(), this.streamEpoch = 0;
485
+ this.orchestratorReady = !1, this.chatHistory = [], this.priorSteps = [], this.sharedState = {}, this.agentRegistry = new R(), this.activeRunId = "", this.cancelledRunIds = /* @__PURE__ */ new Set(), this.parentRunIds = /* @__PURE__ */ new Map(), this.activeRuntimeSpans = /* @__PURE__ */ new Map(), this.runtimeEventsEnabled = !1, this.streamEpoch = 0;
404
486
  }
405
487
  /**
406
488
  * Creates and returns an AI-ready Orchestrator instance.
@@ -408,19 +490,20 @@ class R {
408
490
  * @returns Ready Orchestrator.
409
491
  */
410
492
  static async init(e) {
411
- const n = new R();
493
+ const r = new k();
494
+ r.runtimeEventsEnabled = e.runtimeEventsEnabled ?? !1;
412
495
  try {
413
496
  if (e.view?.map) {
414
- await U.whenOnce(() => e.view.ready);
415
- const s = await me(e.view), r = le(
497
+ await G.whenOnce(() => e.view.ready);
498
+ const s = await Se(e.view), n = ve(
416
499
  s.layers,
417
500
  e.view.map
418
501
  );
419
- n.layersAndFieldsRegistry = r, n.embeddingsWorker = await _(s);
502
+ r.layersAndFieldsRegistry = n, r.embeddingsWorker = await B(s);
420
503
  }
421
504
  return e.agents?.forEach((s) => {
422
- n.agentRegistry.register(s);
423
- }), n.orchestratorReady = !0, n;
505
+ r.agentRegistry.register(s);
506
+ }), r.orchestratorReady = !0, r;
424
507
  } catch (s) {
425
508
  throw console.error("Orchestrator initialization failed:", s), s;
426
509
  }
@@ -435,21 +518,21 @@ class R {
435
518
  * @param userInput User request to process.
436
519
  * @param options Agent selection and routing behavior for this run.
437
520
  */
438
- async *ask(e, n = {}) {
521
+ async *ask(e, r = {}) {
439
522
  if (!this.orchestratorReady)
440
523
  throw new Error("Orchestrator is not ready yet.");
441
524
  if (!this.agentRegistry.list().length)
442
525
  throw new Error("Orchestrator has no registered agents.");
443
- const s = this.createRequestAgentRegistry(n);
526
+ const s = this.createRequestAgentRegistry(r);
444
527
  if (!s.list().length)
445
528
  throw new Error("Orchestrator has no agents selected for this request.");
446
529
  if (++this.streamEpoch, !e.trim())
447
530
  return;
448
- const r = P();
449
- this.activeRunId = r, this.activeAbortController = new AbortController(), this.graph || (this.graph = se().compile({ checkpointer: new H() }));
450
- const a = this.embeddingsWorker ? ce({ worker: this.embeddingsWorker }) : void 0, i = this.embeddingsWorker ? ge({ worker: this.embeddingsWorker }) : void 0, c = /* @__PURE__ */ new Map(), d = n.routing === "direct" ? { mode: "direct", agentId: n.agentId } : { mode: "auto" }, o = {
531
+ const n = U();
532
+ this.parentRunIds.clear(), this.activeRuntimeSpans.clear(), this.activeRunId = n, this.activeAbortController = new AbortController(), this.graph || (this.graph = oe().compile({ checkpointer: new j() }));
533
+ const a = this.embeddingsWorker ? pe({ worker: this.embeddingsWorker }) : void 0, i = this.embeddingsWorker ? ye({ worker: this.embeddingsWorker }) : void 0, c = /* @__PURE__ */ new Map(), d = r.routing === "direct" ? { mode: "direct", agentId: r.agentId } : { mode: "auto" }, o = {
451
534
  // eslint-disable-next-line @typescript-eslint/naming-convention
452
- thread_id: r,
535
+ thread_id: n,
453
536
  hitlResponse: null,
454
537
  services: {
455
538
  layerSearch: a,
@@ -458,13 +541,14 @@ class R {
458
541
  agentRegistry: s,
459
542
  embeddingCache: c
460
543
  }
461
- }, g = {
544
+ }, u = {
462
545
  version: "v2",
463
546
  streamMode: "custom",
464
547
  signal: this.activeAbortController.signal,
548
+ ...this.runtimeEventsEnabled && { callbacks: [this.createHierarchyCallback()] },
465
549
  configurable: o,
466
550
  subgraphs: !0
467
- }, u = this.graph?.streamEvents(
551
+ }, g = this.graph?.streamEvents(
468
552
  {
469
553
  routing: d,
470
554
  agentExecutionContext: {
@@ -474,51 +558,51 @@ class R {
474
558
  sharedState: this.sharedState
475
559
  }
476
560
  },
477
- g
478
- ), p = ++this.streamEpoch;
479
- if (yield* this.pipeStream(u, p, r), this.isRunCancelled(r)) {
480
- yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
561
+ u
562
+ ), l = ++this.streamEpoch;
563
+ if (yield* this.pipeStream(g, l, n), this.isRunCancelled(n)) {
564
+ yield* this.createCancellationEvents(n);
481
565
  return;
482
566
  }
483
567
  for (; ; ) {
484
- if (this.isRunCancelled(r)) {
485
- yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
568
+ if (this.isRunCancelled(n)) {
569
+ yield* this.createCancellationEvents(n);
486
570
  return;
487
571
  }
488
- const w = (await this.graph.getState(g, { subgraphs: !0 })).tasks.find((m) => m.interrupts.length > 0)?.interrupts[0]?.value;
489
- if (!w)
572
+ const p = (await this.graph.getState(u, { subgraphs: !0 })).tasks.find((f) => f.interrupts.length > 0)?.interrupts[0]?.value;
573
+ if (!p)
490
574
  break;
491
- this.currentInterrupt = w, this.interruptHandler = new ae(this.graph, g), yield { runId: r, timestamp: Date.now(), type: "interrupt", interrupt: w };
575
+ this.currentInterrupt = p, this.interruptHandler = new le(this.graph, u), yield* this.closeActiveRuntimeSpans(n, "interrupted"), yield { runId: n, timestamp: Date.now(), type: "interrupt", interrupt: p };
492
576
  try {
493
- const m = await this.interruptHandler.waitForUser(), I = ++this.streamEpoch;
494
- yield* this.pipeStream(m, I, r);
495
- } catch (m) {
496
- if (this.isRunCancelled(r)) {
497
- yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
577
+ const f = await this.interruptHandler.waitForUser(), I = ++this.streamEpoch;
578
+ yield* this.pipeStream(f, I, n);
579
+ } catch (f) {
580
+ if (this.isRunCancelled(n)) {
581
+ yield* this.createCancellationEvents(n);
498
582
  return;
499
583
  }
500
- if (m) {
584
+ if (f) {
501
585
  yield {
502
- runId: r,
586
+ runId: n,
503
587
  timestamp: Date.now(),
504
588
  type: "error",
505
- error: { message: m?.message }
589
+ error: { message: f?.message }
506
590
  };
507
591
  return;
508
592
  }
509
593
  }
510
594
  }
511
- if (this.isRunCancelled(r)) {
512
- yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
595
+ if (this.isRunCancelled(n)) {
596
+ yield* this.createCancellationEvents(n);
513
597
  return;
514
598
  }
515
- const h = (await this.graph.getState(g, { subgraphs: !0 })).values;
516
- if (this.isRunCancelled(r)) {
517
- yield { runId: r, timestamp: Date.now(), type: "cancelled", reason: "user" };
599
+ const h = (await this.graph.getState(u, { subgraphs: !0 })).values;
600
+ if (this.isRunCancelled(n)) {
601
+ yield* this.createCancellationEvents(n);
518
602
  return;
519
603
  }
520
604
  this.chatHistory = h.agentExecutionContext.messages.length ? h.agentExecutionContext.messages : this.chatHistory, this.priorSteps = h.agentExecutionContext.priorSteps?.slice(-5) ?? [], this.sharedState = h.agentExecutionContext.sharedState ?? {}, yield {
521
- runId: r,
605
+ runId: n,
522
606
  timestamp: Date.now(),
523
607
  type: "completed",
524
608
  result: { content: h.finalOutputMessage }
@@ -555,18 +639,63 @@ class R {
555
639
  cancel() {
556
640
  this.activeRunId && (this.cancelledRunIds.add(this.activeRunId), this.activeAbortController?.abort(), ++this.streamEpoch, this.interruptHandler?.cancel());
557
641
  }
558
- async *pipeStream(e, n, s) {
559
- for await (const r of e) {
560
- if (this.isRunCancelled(s) || n !== this.streamEpoch)
561
- break;
562
- r.event === "on_custom_event" && r.name === "trace_message" ? yield { runId: s, timestamp: Date.now(), type: "trace", data: r.data } : r.name === "graph_ux_suggestion" && (yield {
563
- runId: s,
564
- timestamp: Date.now(),
565
- type: "ux-suggestion",
566
- suggestion: r.data
567
- });
642
+ async *pipeStream(e, r, s) {
643
+ try {
644
+ for await (const n of e) {
645
+ if (this.isRunCancelled(s) || r !== this.streamEpoch)
646
+ break;
647
+ if (this.runtimeEventsEnabled) {
648
+ const a = ge({
649
+ event: n,
650
+ runId: s,
651
+ parentSpanId: this.parentRunIds.get(n.run_id),
652
+ timestamp: Date.now()
653
+ });
654
+ a && (a.phase === "started" ? this.activeRuntimeSpans.set(a.span.id, a) : this.activeRuntimeSpans.delete(a.span.id), yield a);
655
+ }
656
+ 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 {
657
+ runId: s,
658
+ timestamp: Date.now(),
659
+ type: "ux-suggestion",
660
+ suggestion: n.data
661
+ });
662
+ }
663
+ } catch (n) {
664
+ if (!this.isRunCancelled(s))
665
+ throw n;
666
+ }
667
+ }
668
+ *createCancellationEvents(e) {
669
+ yield* this.closeActiveRuntimeSpans(e, "cancelled"), yield { runId: e, timestamp: Date.now(), type: "cancelled", reason: "user" };
670
+ }
671
+ *closeActiveRuntimeSpans(e, r) {
672
+ const s = Date.now(), n = [...this.activeRuntimeSpans.values()].reverse();
673
+ this.activeRuntimeSpans.clear();
674
+ for (const a of n) {
675
+ const { input: i, ...c } = a.span;
676
+ yield {
677
+ type: "runtime",
678
+ phase: r,
679
+ runId: e,
680
+ timestamp: s,
681
+ ...a.agentId && { agentId: a.agentId },
682
+ span: c
683
+ };
568
684
  }
569
685
  }
686
+ // v2 stream events omit parent run IDs, so capture them through callbacks to preserve the normalized span hierarchy.
687
+ createHierarchyCallback() {
688
+ const e = (r, s) => {
689
+ s && this.parentRunIds.set(r, s);
690
+ };
691
+ return N.fromMethods({
692
+ handleLLMStart: (r, s, n, a) => e(n, a),
693
+ handleChatModelStart: (r, s, n, a) => e(n, a),
694
+ handleChainStart: (r, s, n, a) => e(n, a),
695
+ handleToolStart: (r, s, n, a) => e(n, a),
696
+ handleRetrieverStart: (r, s, n, a) => e(n, a)
697
+ });
698
+ }
570
699
  isRunCancelled(e) {
571
700
  return this.cancelledRunIds.has(e);
572
701
  }
@@ -575,13 +704,13 @@ class R {
575
704
  * or only the explicitly selected agents when filtering is requested.
576
705
  */
577
706
  createRequestAgentRegistry(e) {
578
- const n = e.routing === "direct" ? [e.agentId] : e.agentIds, s = n ? n.map((a) => {
707
+ const r = e.routing === "direct" ? [e.agentId] : e.agentIds, s = r ? r.map((a) => {
579
708
  const i = this.agentRegistry.get(a);
580
709
  if (!i)
581
710
  throw new Error(`Agent is not registered: ${a}`);
582
711
  return i;
583
- }) : this.agentRegistry.list(), r = new v();
584
- return s.forEach((a) => r.register(a)), r;
712
+ }) : this.agentRegistry.list(), n = new R();
713
+ return s.forEach((a) => n.register(a)), n;
585
714
  }
586
715
  /**
587
716
  * Disposes this instance by terminating the embeddings worker
@@ -592,6 +721,6 @@ class R {
592
721
  }
593
722
  }
594
723
  export {
595
- R as O,
596
- ie as g
724
+ k as O,
725
+ he as g
597
726
  };