@arcgis/ai-orchestrator 5.1.0-next.93 → 5.1.0-next.95

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.
@@ -1,2 +1,3 @@
1
1
  export declare const replaceReducer: <T>(_prev: T, next: T) => T;
2
2
  export declare const mergeReducer: <T extends object>(prev: T, next: Partial<T>) => T;
3
+ export declare const accumulateOutputMessageReducer: (current: string | undefined, update: unknown) => string;
@@ -1,8 +1,11 @@
1
- import { AgentExecutionContext } from '../../types/types';
1
+ import { AgentExecutionContextShape, SharedState } from '../../types/types';
2
+ type WritableAgentExecutionContext<TState extends SharedState = SharedState> = AgentExecutionContextShape<TState>;
2
3
  export declare const DispatcherGraphState: import('@langchain/langgraph').AnnotationRoot<{
3
- agentExecutionContext: import('@langchain/langgraph').BaseChannel<AgentExecutionContext, AgentExecutionContext | import('@langchain/langgraph').OverwriteValue<AgentExecutionContext>, unknown>;
4
+ agentExecutionContext: import('@langchain/langgraph').BaseChannel<WritableAgentExecutionContext<SharedState<Record<string, unknown>>>, WritableAgentExecutionContext<SharedState<Record<string, unknown>>> | import('@langchain/langgraph').OverwriteValue<WritableAgentExecutionContext<SharedState<Record<string, unknown>>>>, unknown>;
4
5
  currentIntent: import('@langchain/langgraph').BaseChannel<string, string | import('@langchain/langgraph').OverwriteValue<string>, unknown>;
5
6
  requiresFollowUp: import('@langchain/langgraph').BaseChannel<boolean, boolean | import('@langchain/langgraph').OverwriteValue<boolean>, unknown>;
6
7
  stepCount: import('@langchain/langgraph').BaseChannel<number, number | import('@langchain/langgraph').OverwriteValue<number>, unknown>;
8
+ finalOutputMessage: import('@langchain/langgraph').BaseChannel<string, string | import('@langchain/langgraph').OverwriteValue<string>, unknown>;
7
9
  }>;
8
10
  export type DispatcherGraphStateType = typeof DispatcherGraphState.State;
11
+ export {};
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export { createChatModel } from './providers/arcgis/aiFactory';
5
5
  export { createWebmapEmbeddings } from './embeddings/webmapEmbeddings';
6
6
  export { getEmbeddings } from './embeddings/embeddingsUtil';
7
7
  export { cosineSimilarity } from './embeddings/cosineSimilarity';
8
+ export { createAgentRuntimeState, createAgentRuntimeStateWithSharedState } from './utils/baseAgentState';
8
9
  export type { CustomConfigurableType, VectorSearchFieldResults, LayersAndFieldsRegistry, Services, FieldInfo, FieldStatistics, ChatHistory, AgentExecutionContext, AgentStatus, PriorStep, SharedState, SharedStatePatch, } from './types/types';
9
10
  export type { UXSuggestion } from './orchestrator/orchestratorEvents';
10
11
  export type { UiInterrupt } from './hitl/types';
package/dist/index.js CHANGED
@@ -1,110 +1,150 @@
1
- import R from "@arcgis/core/identity/IdentityManager.js";
2
- import S from "@arcgis/core/portal/Portal.js";
3
- import { Annotation as x, isGraphInterrupt as ie, StateGraph as ae, START as oe, END as ce, MemorySaver as de } from "@langchain/langgraph/web";
4
- import { HumanMessage as N, AIMessage as A, isAIMessage as le, isToolMessage as ue } from "@langchain/core/messages";
5
- import { dispatchCustomEvent as O } from "@langchain/core/callbacks/dispatch/web";
6
- import h, { z as l } from "zod";
7
- import { ChatPromptTemplate as H, SystemMessagePromptTemplate as me } from "@langchain/core/prompts";
8
- import { createAgent as ge, summarizationMiddleware as pe, modelCallLimitMiddleware as he } from "langchain";
9
- import { ChatOpenAI as fe, OpenAIEmbeddings as ye } from "@langchain/openai";
10
- import * as V from "@arcgis/core/core/reactiveUtils.js";
11
- import z from "@arcgis/core/layers/FeatureLayer.js";
12
- import we from "@arcgis/core/request.js";
13
- const B = {
1
+ import A from "@arcgis/core/identity/IdentityManager.js";
2
+ import I from "@arcgis/core/portal/Portal.js";
3
+ import { Annotation as h, isGraphInterrupt as oe, StateGraph as ce, START as de, END as le, MemorySaver as ue } from "@langchain/langgraph/web";
4
+ import { HumanMessage as ge, AIMessage as W, isAIMessage as me, isToolMessage as pe } from "@langchain/core/messages";
5
+ import { dispatchCustomEvent as N } from "@langchain/core/callbacks/dispatch/web";
6
+ import f, { z as l } from "zod";
7
+ import { ChatPromptTemplate as O, SystemMessagePromptTemplate as he } from "@langchain/core/prompts";
8
+ import { createAgent as fe, summarizationMiddleware as ye, modelCallLimitMiddleware as we } from "langchain";
9
+ import { ChatOpenAI as ve, OpenAIEmbeddings as xe } from "@langchain/openai";
10
+ import * as H from "@arcgis/core/core/reactiveUtils.js";
11
+ import V from "@arcgis/core/layers/FeatureLayer.js";
12
+ import be from "@arcgis/core/request.js";
13
+ const z = {
14
14
  advanced: "gpt-5.2",
15
15
  default: "gpt-5-mini",
16
16
  fast: "gpt-5.4-nano"
17
17
  }, C = {
18
18
  default: "text-embedding-ada-002"
19
- }, M = /* @__PURE__ */ new Map();
20
- let E = null;
21
- const ve = () => {
22
- const t = S.getDefault().helperServices;
19
+ }, k = /* @__PURE__ */ new Map();
20
+ let S = null;
21
+ const Ee = () => {
22
+ const t = I.getDefault().helperServices;
23
23
  if (!t?.aiModels?.url)
24
24
  throw new Error("AI Models Service URL is not defined in the portal's helper services.");
25
25
  return t.aiModels.url;
26
- }, G = async (e) => {
27
- const t = ve();
28
- M.size === 0 && (E || (E = (async () => {
26
+ }, B = async (e) => {
27
+ const t = Ee();
28
+ k.size === 0 && (S || (S = (async () => {
29
29
  try {
30
30
  const n = await fetch(`${t}/models`);
31
31
  if (!n.ok)
32
32
  throw new Error("Failed to fetch AI service discovery data.");
33
- (await n.json()).models.forEach((i) => M.set(i.name, i));
33
+ (await n.json()).models.forEach((a) => k.set(a.name, a));
34
34
  } catch (n) {
35
- throw E = null, n;
35
+ throw S = null, n;
36
36
  }
37
- })()), await E);
38
- const r = M.get(e);
37
+ })()), await S);
38
+ const r = k.get(e);
39
39
  if (!r)
40
40
  throw new Error(`Model '${e}' is not available in the discovery service.`);
41
41
  return r.endpoint;
42
- }, xe = async (e = "default") => await G(B[e]), K = async (e = "default") => await G(C[e]), be = async (e) => {
43
- const t = await Ee(), r = await K("default"), n = S.getDefault(), i = (await R.getCredential(`${n.url}/sharing`)).token, a = {
42
+ }, Se = async (e = "default") => await B(z[e]), G = async (e = "default") => await B(C[e]), Ie = async (e) => {
43
+ const t = await Me(), r = await G("default"), n = I.getDefault(), a = (await A.getCredential(`${n.url}/sharing`)).token, i = {
44
44
  type: "generateEmbeddings",
45
45
  webmapEmbeddings: e,
46
- auth: { apiUrl: r, token: i }
46
+ auth: { apiUrl: r, token: a }
47
47
  };
48
- return t.postMessage(a), await new Promise((o, c) => {
49
- const d = (m) => {
50
- m.data === "completed" && (t.removeEventListener("message", d), o());
51
- }, u = (m) => {
52
- t.removeEventListener("message", d), c(m instanceof Error ? m : new Error("Embeddings worker error"));
48
+ return t.postMessage(i), await new Promise((o, c) => {
49
+ const d = (g) => {
50
+ g.data === "completed" && (t.removeEventListener("message", d), o());
51
+ }, u = (g) => {
52
+ t.removeEventListener("message", d), c(g instanceof Error ? g : new Error("Embeddings worker error"));
53
53
  };
54
54
  t.addEventListener("message", d), t.addEventListener("error", u, { once: !0 });
55
55
  }), t;
56
- }, Ee = async () => {
56
+ }, Me = async () => {
57
57
  {
58
58
  const e = (await import("./embeddings.worker-GH7zdYqF.js")).default;
59
59
  return new e();
60
60
  }
61
- }, P = (e, t) => t, Se = (e, t) => ({
61
+ }, b = (e, t) => t, K = (e, t) => ({
62
62
  ...e,
63
63
  ...t
64
- }), Ie = x.Root({
65
- agentExecutionContext: x({
66
- default: () => ({
67
- userRequest: "",
68
- assignedTask: "",
69
- priorSteps: [],
70
- messages: [],
71
- sharedState: {}
72
- }),
73
- reducer: Se
64
+ }), J = (e = "", t) => {
65
+ const r = typeof t == "string" ? t.trim() : "";
66
+ if (!r)
67
+ return e;
68
+ const n = e.trim();
69
+ if (!n)
70
+ return r;
71
+ if (n === r)
72
+ return e;
73
+ const s = n.split(`
74
+
75
+ `);
76
+ return s[s.length - 1]?.trim() === r ? e : `${e}
77
+
78
+ ${r}`;
79
+ }, X = () => ({
80
+ userRequest: "",
81
+ assignedTask: "",
82
+ messages: [],
83
+ priorSteps: [],
84
+ sharedState: {}
85
+ }), ke = () => ({
86
+ agentExecutionContext: h({
87
+ reducer: K,
88
+ default: X
89
+ }),
90
+ outputMessage: h({
91
+ reducer: J,
92
+ default: () => ""
93
+ }),
94
+ summary: h({
95
+ reducer: b,
96
+ default: () => ""
74
97
  }),
75
- currentIntent: x({
98
+ status: h({
99
+ reducer: b
100
+ })
101
+ }), bt = () => ({
102
+ ...ke(),
103
+ sharedStatePatch: h({
104
+ reducer: b
105
+ })
106
+ }), Re = h.Root({
107
+ agentExecutionContext: h({
108
+ default: X,
109
+ reducer: K
110
+ }),
111
+ currentIntent: h({
76
112
  default: () => "none",
77
- reducer: P
113
+ reducer: b
78
114
  }),
79
- requiresFollowUp: x({
115
+ requiresFollowUp: h({
80
116
  default: () => !0,
81
- reducer: P
117
+ reducer: b
82
118
  }),
83
- stepCount: x({
119
+ stepCount: h({
84
120
  default: () => 0,
85
121
  reducer: (e, t) => t ?? e + 1
122
+ }),
123
+ finalOutputMessage: h({
124
+ default: () => "",
125
+ reducer: J
86
126
  })
87
- }), f = async (e, t) => {
88
- await O("trace_message", e, t);
89
- }, vt = async (e, t) => {
90
- await O("graph_ux_suggestion", e, t);
91
- }, Me = (e) => {
127
+ }), y = async (e, t) => {
128
+ await N("trace_message", e, t);
129
+ }, Et = async (e, t) => {
130
+ await N("graph_ux_suggestion", e, t);
131
+ }, Ae = (e) => {
92
132
  e.currentIntent = "none";
93
- }, ke = async (e, t) => {
133
+ }, Ce = async (e, t) => {
94
134
  if (e.agentExecutionContext.userRequest) {
95
- const n = new N(e.agentExecutionContext.userRequest.trim());
96
- e.agentExecutionContext.messages = [...e.agentExecutionContext.messages, n], Me(e);
135
+ const n = new ge(e.agentExecutionContext.userRequest.trim());
136
+ e.agentExecutionContext.messages = [...e.agentExecutionContext.messages, n], Ae(e);
97
137
  }
98
138
  const r = t?.configurable?.services.agentRegistry.list().map((n) => n.agent.id) ?? [];
99
- return await f({ text: `Available agents: ${[...r].join(", ")}` }, t), await f({ text: "Analyzing user input" }, t), e;
100
- }, Re = async (e, t) => (await f({ text: "Exiting..." }, t), e), L = (e) => typeof e == "object" && e !== null && !Array.isArray(e), Ae = (e, t) => {
101
- if (!L(e)) {
139
+ return await y({ text: `Available agents: ${[...r].join(", ")}` }, t), await y({ text: "Analyzing user input" }, t), e;
140
+ }, Te = async (e, t) => (await y({ text: "Exiting..." }, t), e), P = (e) => typeof e == "object" && e !== null && !Array.isArray(e), Fe = (e, t) => {
141
+ if (!P(e)) {
102
142
  e !== void 0 && console.warn(`Agent "${t}" returned invalid sharedStatePatch. Ignoring it.`);
103
143
  return;
104
144
  }
105
145
  const r = {};
106
146
  for (const [n, s] of Object.entries(e)) {
107
- if (!L(s) || !("value" in s)) {
147
+ if (!P(s) || !("value" in s)) {
108
148
  console.warn(
109
149
  `Agent "${t}" returned invalid sharedStatePatch entry for key "${n}". Ignoring that entry.`
110
150
  );
@@ -113,28 +153,28 @@ const ve = () => {
113
153
  r[n] = { value: s.value };
114
154
  }
115
155
  return r;
116
- }, Ce = (e) => {
156
+ }, De = (e) => {
117
157
  const { previousSharedState: t, patch: r, agentId: n } = e;
118
158
  if (!r)
119
159
  return t;
120
- const s = Date.now(), i = {
160
+ const s = Date.now(), a = {
121
161
  ...t
122
162
  };
123
- for (const [a, o] of Object.entries(r))
124
- o.value !== void 0 && (i[a] = {
163
+ for (const [i, o] of Object.entries(r))
164
+ o?.value !== void 0 && (a[i] = {
125
165
  value: o.value,
126
166
  meta: {
127
167
  updatedByAgentId: n,
128
168
  updatedAt: s
129
169
  }
130
170
  });
131
- return i;
132
- }, q = (e) => {
171
+ return a;
172
+ }, L = (e) => {
133
173
  if (typeof e != "string")
134
174
  return;
135
175
  const t = e.trim();
136
176
  return t || void 0;
137
- }, Te = (e) => {
177
+ }, $e = (e) => {
138
178
  switch (e) {
139
179
  case "failed":
140
180
  return "Agent failed without a summary.";
@@ -145,22 +185,22 @@ const ve = () => {
145
185
  default:
146
186
  return "Agent completed without a summary.";
147
187
  }
148
- }, Fe = (e, t) => {
149
- const r = q(t?.outputMessage), n = q(t?.summary), s = t?.status, i = s === "success" || s === "failed" ? s : "unknown";
150
- i === "unknown" && console.warn(`Agent "${e}" returned missing/invalid status. Defaulting to "unknown".`);
151
- const a = Ae(t?.sharedStatePatch, e);
188
+ }, Pe = (e, t) => {
189
+ const r = L(t?.outputMessage), n = L(t?.summary), s = t?.status, a = s === "success" || s === "failed" ? s : "unknown";
190
+ a === "unknown" && console.warn(`Agent "${e}" returned missing/invalid status. Defaulting to "unknown".`);
191
+ const i = Fe(t?.sharedStatePatch, e);
152
192
  return {
153
193
  outputMessage: r,
154
- summary: n ?? r ?? Te(i),
155
- status: i,
156
- sharedStatePatch: a
194
+ summary: n ?? r ?? $e(a),
195
+ status: a,
196
+ sharedStatePatch: i
157
197
  };
158
- }, j = 4e3, De = async (e, t) => {
198
+ }, q = 4e3, Le = async (e, t) => {
159
199
  const r = t?.configurable, { agentRegistry: n } = r.services, s = n?.get(e.currentIntent);
160
200
  if (!s)
161
201
  return console.warn(`No agent found for intent: ${e.currentIntent}`), e;
162
- await f({ text: `Executing registered agent: ${s.agent.name}` }, t);
163
- const i = {
202
+ await y({ text: `Executing registered agent: ${s.agent.name}` }, t);
203
+ const a = {
164
204
  ...t ?? {},
165
205
  configurable: {
166
206
  ...r ?? {},
@@ -168,7 +208,7 @@ const ve = () => {
168
208
  context: s.getContext ? await s.getContext() : void 0
169
209
  }
170
210
  };
171
- let a;
211
+ let i;
172
212
  try {
173
213
  const d = await s.agent.createGraph().compile().invoke(
174
214
  {
@@ -181,29 +221,30 @@ const ve = () => {
181
221
  sharedState: structuredClone(e.agentExecutionContext.sharedState ?? {})
182
222
  }
183
223
  },
184
- i
224
+ a
185
225
  );
186
- a = Fe(s.agent.name, d), await f({ text: `Finished executing registered agent: ${s.agent.name}` }, t);
226
+ i = Pe(s.agent.name, d), await y({ text: `Finished executing registered agent: ${s.agent.name}` }, t);
187
227
  } catch (d) {
188
- if (ie(d))
228
+ if (oe(d))
189
229
  throw d;
190
230
  const u = d instanceof Error ? d.message : String(d);
191
- console.error(`Agent "${s.agent.name}" failed:`, d), await f({ text: `Registered agent failed: ${s.agent.name}. ${u}` }, t), a = {
231
+ console.error(`Agent "${s.agent.name}" failed:`, d), await y({ text: `Registered agent failed: ${s.agent.name}. ${u}` }, t), i = {
192
232
  status: "failed",
193
233
  outputMessage: `Agent execution failed: ${u}`,
194
234
  summary: `Agent execution failed: ${u}`
195
235
  };
196
236
  }
197
- const o = a.outputMessage, c = [...e.agentExecutionContext.messages];
237
+ const o = i.outputMessage, c = [...e.agentExecutionContext.messages];
198
238
  if (o) {
199
- const d = o.length > j ? `${o.slice(0, j - 14)}
239
+ const d = o.length > q ? `${o.slice(0, q - 14)}
200
240
  [truncated]` : o;
201
- c.push(new A(d));
241
+ c.push(new W(d));
202
242
  }
203
243
  return {
204
244
  ...e,
205
245
  stepCount: e.stepCount + 1,
206
- requiresFollowUp: a.status === "failed" ? !0 : e.requiresFollowUp,
246
+ requiresFollowUp: i.status === "failed" ? !0 : e.requiresFollowUp,
247
+ finalOutputMessage: o ?? "",
207
248
  agentExecutionContext: {
208
249
  ...e.agentExecutionContext,
209
250
  messages: c,
@@ -212,23 +253,23 @@ const ve = () => {
212
253
  {
213
254
  agentId: s.agent.id,
214
255
  assignedTask: e.agentExecutionContext.assignedTask,
215
- summary: a?.summary || "No summary provided.",
216
- status: a?.status || "unknown"
256
+ summary: i?.summary || "No summary provided.",
257
+ status: i?.status || "unknown"
217
258
  }
218
259
  ],
219
- sharedState: Ce({
260
+ sharedState: De({
220
261
  previousSharedState: e.agentExecutionContext.sharedState,
221
- patch: a.sharedStatePatch,
262
+ patch: i.sharedStatePatch,
222
263
  agentId: s.agent.id
223
264
  })
224
265
  }
225
266
  };
226
- }, $e = (e, t, r) => {
267
+ }, qe = (e, t, r) => {
227
268
  const n = e[t];
228
- return n ? typeof n == "function" ? n() : Promise.resolve(n) : new Promise((s, i) => {
229
- (typeof queueMicrotask == "function" ? queueMicrotask : setTimeout)(i.bind(null, /* @__PURE__ */ new Error("Unknown variable dynamic import: " + t + (t.split("/").length !== r ? ". Note that variables only represent file names one level deep." : ""))));
269
+ return n ? typeof n == "function" ? n() : Promise.resolve(n) : new Promise((s, a) => {
270
+ (typeof queueMicrotask == "function" ? queueMicrotask : setTimeout)(a.bind(null, /* @__PURE__ */ new Error("Unknown variable dynamic import: " + t + (t.split("/").length !== r ? ". Note that variables only represent file names one level deep." : ""))));
230
271
  });
231
- }, T = async (e) => (await $e(/* @__PURE__ */ Object.assign({ "./field_descriptions_prompt.md": () => import("./field_descriptions_prompt-haMV_aoG.js"), "./intent_prompt.md": () => import("./intent_prompt-D6yvMy34.js"), "./layer_descriptions_prompt.md": () => import("./layer_descriptions_prompt-NAaKWdJi.js") }), `./${e}.md`, 2)).default, Pe = async (e) => {
272
+ }, T = async (e) => (await qe(/* @__PURE__ */ Object.assign({ "./field_descriptions_prompt.md": () => import("./field_descriptions_prompt-haMV_aoG.js"), "./intent_prompt.md": () => import("./intent_prompt-D6yvMy34.js"), "./layer_descriptions_prompt.md": () => import("./layer_descriptions_prompt-NAaKWdJi.js") }), `./${e}.md`, 2)).default, Ue = async (e) => {
232
273
  const { agent: t, messages: r, config: n } = e;
233
274
  return { structuredResponse: (await t.invoke(
234
275
  {
@@ -236,65 +277,65 @@ const ve = () => {
236
277
  },
237
278
  n
238
279
  )).structuredResponse };
239
- }, J = (e) => async (t, r) => {
280
+ }, Q = (e) => async (t, r) => {
240
281
  const n = new Headers(r?.headers);
241
282
  return n.delete("Authorization"), n.delete("api-key"), e && e.length > 0 && (n.set("X-Esri-Authorization", `Bearer ${e}`), n.set("X-Esri-Request-Source", "MapsSDK")), await fetch(t, {
242
283
  ...r,
243
284
  headers: n
244
285
  });
245
- }, b = async (e = "default", t = 0) => {
246
- const r = S.getDefault(), n = await R.getCredential(`${r.url}/sharing`), s = B[e], i = await xe(e);
247
- return new fe({
286
+ }, E = async (e = "default", t = 0) => {
287
+ const r = I.getDefault(), n = await A.getCredential(`${r.url}/sharing`), s = z[e], a = await Se(e);
288
+ return new ve({
248
289
  modelName: s,
249
290
  apiKey: "dummy-key",
250
291
  // 5-mini does not support temperature parameter
251
292
  ...e !== "default" && { temperature: t },
252
293
  configuration: {
253
- baseURL: i,
254
- fetch: J(n.token)
294
+ baseURL: a,
295
+ fetch: Q(n.token)
255
296
  }
256
297
  });
257
- }, Le = async (e = "default") => {
258
- const t = S.getDefault(), r = await R.getCredential(`${t.url}/sharing`), n = C[e], s = await K(e);
259
- return new ye({
298
+ }, je = async (e = "default") => {
299
+ const t = I.getDefault(), r = await A.getCredential(`${t.url}/sharing`), n = C[e], s = await G(e);
300
+ return new xe({
260
301
  modelName: n,
261
302
  apiKey: "dummy-key",
262
303
  configuration: {
263
304
  baseURL: s,
264
- fetch: J(r.token)
305
+ fetch: Q(r.token)
265
306
  },
266
307
  batchSize: 2048,
267
308
  maxConcurrency: 10
268
309
  });
269
- }, qe = l.object({
310
+ }, _e = l.object({
270
311
  id: l.string().min(1),
271
312
  name: l.string().min(1),
272
313
  description: l.string().min(1)
273
314
  });
274
- l.array(qe);
275
- const U = (e) => JSON.stringify(e, null, 2), je = (e) => {
315
+ l.array(_e);
316
+ const U = (e) => JSON.stringify(e, null, 2), We = (e) => {
276
317
  const t = e.map((n) => n.id), r = l.enum(t);
277
318
  return l.object({
278
319
  intent: r.nullable(),
279
320
  assignedTask: l.string().nullable(),
280
321
  requiresFollowUp: l.boolean()
281
322
  });
282
- }, Ue = async (e, t) => {
323
+ }, Ne = async (e, t) => {
283
324
  try {
284
- await f({ text: "Asking LLM to route to an agent" }, t);
285
- const s = (t?.configurable?.services.agentRegistry?.list() ?? []).map(({ agent: v }) => ({
286
- id: v.id,
287
- name: v.name,
288
- description: v.description
325
+ await y({ text: "Asking LLM to route to an agent" }, t);
326
+ const s = (t?.configurable?.services.agentRegistry?.list() ?? []).map(({ agent: x }) => ({
327
+ id: x.id,
328
+ name: x.name,
329
+ description: x.description
289
330
  }));
290
331
  if (!s.length)
291
- return await f({ text: "No agents registered; skipping intent detection" }, t), { ...e, currentIntent: "none" };
292
- const i = await T("intent_prompt"), a = U(s), o = je(s), c = {
293
- registeredAgents: a,
332
+ return await y({ text: "No agents registered; skipping intent detection" }, t), { ...e, currentIntent: "none" };
333
+ const a = await T("intent_prompt"), i = U(s), o = We(s), c = {
334
+ registeredAgents: i,
294
335
  priorSteps: U(e.agentExecutionContext.priorSteps),
295
336
  userRequest: e.agentExecutionContext.userRequest
296
- }, u = await H.fromTemplate(i).format(c), m = ge({
297
- model: await b("fast"),
337
+ }, u = await O.fromTemplate(a).format(c), g = fe({
338
+ model: await E("fast"),
298
339
  tools: [],
299
340
  systemPrompt: u,
300
341
  checkpointer: !0,
@@ -303,40 +344,40 @@ const U = (e) => JSON.stringify(e, null, 2), je = (e) => {
303
344
  // Preserve recent conversation context while summarizing older messages
304
345
  // to control token usage without losing important intent signals.
305
346
  // The trigger and keep parameters can be tuned based on token limits and behavior.
306
- pe({
307
- model: await b("fast"),
347
+ ye({
348
+ model: await E("fast"),
308
349
  trigger: { tokens: 4e3 },
309
350
  keep: { messages: 6 }
310
351
  }),
311
352
  // Enforce no loop/retry.
312
353
  // 1 usual LLM call and 1 optional summarization call.
313
- he({ runLimit: 2 })
354
+ we({ runLimit: 2 })
314
355
  ]
315
- }), { structuredResponse: y } = await Pe({
316
- agent: m,
356
+ }), { structuredResponse: w } = await Ue({
357
+ agent: g,
317
358
  messages: e.agentExecutionContext.messages,
318
359
  config: t
319
360
  }), p = o.parse(
320
- y ?? { intent: null, assignedTask: null, requiresFollowUp: !1 }
321
- ), g = p.intent ?? "none", I = {
361
+ w ?? { intent: null, assignedTask: null, requiresFollowUp: !1 }
362
+ ), m = p.intent ?? "none", M = {
322
363
  ...e,
323
- currentIntent: g,
364
+ currentIntent: m,
324
365
  requiresFollowUp: p.requiresFollowUp,
325
366
  agentExecutionContext: {
326
367
  ...e.agentExecutionContext,
327
368
  assignedTask: p.assignedTask ?? ""
328
369
  }
329
370
  };
330
- if (g === "none") {
331
- const v = "I could not find a matching agent for that request. Please rephrase your question with more detail.";
332
- return await f({ text: "LLM did not identify a clear intent." }, t), {
371
+ if (m === "none") {
372
+ const x = "I could not find a matching agent for that request. Please rephrase your question with more detail.";
373
+ return await y({ text: "LLM did not identify a clear intent." }, t), {
333
374
  ...e,
334
- currentIntent: g,
375
+ currentIntent: m,
335
376
  requiresFollowUp: !1,
336
377
  agentExecutionContext: {
337
378
  ...e.agentExecutionContext,
338
379
  assignedTask: "",
339
- messages: [...e.agentExecutionContext.messages, new A(v)],
380
+ messages: [...e.agentExecutionContext.messages, new W(x)],
340
381
  priorSteps: [
341
382
  ...e.agentExecutionContext.priorSteps ?? [],
342
383
  {
@@ -349,22 +390,22 @@ const U = (e) => JSON.stringify(e, null, 2), je = (e) => {
349
390
  }
350
391
  };
351
392
  }
352
- return await f(
393
+ return await y(
353
394
  {
354
- text: `Agent picked: ${g}
395
+ text: `Agent picked: ${m}
355
396
  Task Assigned: ${p.assignedTask ?? ""}
356
397
  Requires Follow-Up: ${p.requiresFollowUp}`
357
398
  },
358
399
  t
359
- ), I;
400
+ ), M;
360
401
  } catch (r) {
361
- throw await f({ text: "Error during intent detection" }, t), new Error(`Error during intent detection: ${r instanceof Error ? r.message : String(r)}`);
402
+ throw await y({ text: "Error during intent detection" }, t), new Error(`Error during intent detection: ${r instanceof Error ? r.message : String(r)}`);
362
403
  }
363
- }, _e = 3, We = () => new ae(Ie).addNode("ingestInput", ke).addNode("intentLLM", Ue).addNode("executeRegisteredAgent", De).addNode("exit", Re).addEdge(oe, "ingestInput").addEdge("ingestInput", "intentLLM").addConditionalEdges("intentLLM", (t) => t.currentIntent === "none" ? "exit" : "executeRegisteredAgent").addConditionalEdges(
404
+ }, Oe = 3, He = () => new ce(Re).addNode("ingestInput", Ce).addNode("intentLLM", Ne).addNode("executeRegisteredAgent", Le).addNode("exit", Te).addEdge(de, "ingestInput").addEdge("ingestInput", "intentLLM").addConditionalEdges("intentLLM", (t) => t.currentIntent === "none" ? "exit" : "executeRegisteredAgent").addConditionalEdges(
364
405
  "executeRegisteredAgent",
365
- (t) => t.stepCount >= _e || !t.requiresFollowUp ? "exit" : "intentLLM"
366
- ).addEdge("exit", ce);
367
- class Ne {
406
+ (t) => t.stepCount >= Oe || !t.requiresFollowUp ? "exit" : "intentLLM"
407
+ ).addEdge("exit", le);
408
+ class Ve {
368
409
  constructor() {
369
410
  this.agentRegistry = /* @__PURE__ */ new Map();
370
411
  }
@@ -381,7 +422,7 @@ class Ne {
381
422
  return [...this.agentRegistry.values()];
382
423
  }
383
424
  }
384
- class Oe {
425
+ class ze {
385
426
  /**
386
427
  * Create a new InterruptHandler tied to a specific compiled graph and config.
387
428
  */
@@ -428,32 +469,23 @@ class Oe {
428
469
  this.rejectWait && (this.rejectWait(new Error("Request cancelled by user.")), this.resolveWait = void 0, this.rejectWait = void 0);
429
470
  }
430
471
  }
431
- const He = (e) => {
432
- let t = -1;
433
- for (let r = e.length - 1; r >= 0; r--)
434
- if (e[r] instanceof N) {
435
- t = r;
436
- break;
437
- }
438
- return t === -1 ? "" : e.slice(t + 1).filter((r) => r instanceof A).map((r) => r.content).join(`
439
- `);
440
- }, X = async (e) => {
472
+ const Y = async (e) => {
441
473
  try {
442
- return await (await Le()).embedDocuments(e);
474
+ return await (await je()).embedDocuments(e);
443
475
  } catch (t) {
444
476
  throw console.error("Failed to generate embeddings:", t), t;
445
477
  }
446
- }, Q = async (e, t) => {
478
+ }, Z = async (e, t) => {
447
479
  const r = t.get(e);
448
480
  if (r)
449
481
  return r;
450
- const n = await X([e]);
482
+ const n = await Y([e]);
451
483
  return t.set(e, n[0]), n[0];
452
484
  };
453
- async function Ve(e, t, r, n) {
454
- const s = `req-${Date.now()}`, a = {
485
+ async function Be(e, t, r, n) {
486
+ const s = `req-${Date.now()}`, i = {
455
487
  type: "layerSearch",
456
- precomputedEmbedding: n ? await Q(e, n) : void 0,
488
+ precomputedEmbedding: n ? await Z(e, n) : void 0,
457
489
  requestId: s,
458
490
  minScore: r
459
491
  };
@@ -461,10 +493,10 @@ async function Ve(e, t, r, n) {
461
493
  const c = (d) => {
462
494
  d.data.requestId === s && o(d.data.results);
463
495
  };
464
- t.addEventListener("message", c, { once: !0 }), t.postMessage(a);
496
+ t.addEventListener("message", c, { once: !0 }), t.postMessage(i);
465
497
  });
466
498
  }
467
- function ze(e) {
499
+ function Ge(e) {
468
500
  const { worker: t } = e;
469
501
  return {
470
502
  async searchLayers({
@@ -472,65 +504,65 @@ function ze(e) {
472
504
  minScore: n,
473
505
  embeddingCache: s
474
506
  }) {
475
- return await Ve(r, t, n, s);
507
+ return await Be(r, t, n, s);
476
508
  }
477
509
  };
478
510
  }
479
- const Be = async ({
511
+ const Ke = async ({
480
512
  combinedQuery: e,
481
513
  layerIds: t,
482
514
  embeddingsWorker: r,
483
515
  minScore: n,
484
516
  topResults: s,
485
- embeddingCache: i
517
+ embeddingCache: a
486
518
  }) => {
487
- const a = `req-${Date.now()}`, o = i ? await Q(e, i) : void 0, c = {
519
+ const i = `req-${Date.now()}`, o = a ? await Z(e, a) : void 0, c = {
488
520
  type: "fieldSearch",
489
521
  layerIdForFieldsSearch: t,
490
522
  precomputedEmbedding: o,
491
- requestId: a,
523
+ requestId: i,
492
524
  minScore: n,
493
525
  topResults: s
494
526
  };
495
527
  return await new Promise((d) => {
496
- const u = (m) => {
497
- if (m.data.requestId !== a)
528
+ const u = (g) => {
529
+ if (g.data.requestId !== i)
498
530
  return;
499
- const y = m.data.results.map(({ layerId: p, results: g }) => ({
531
+ const w = g.data.results.map(({ layerId: p, results: m }) => ({
500
532
  layerId: p,
501
- results: g
533
+ results: m
502
534
  }));
503
- d(y);
535
+ d(w);
504
536
  };
505
537
  r.addEventListener("message", u, { once: !0 }), r.postMessage(c);
506
538
  });
507
539
  };
508
- function Ge(e) {
540
+ function Je(e) {
509
541
  const { worker: t } = e;
510
542
  return {
511
- async searchFields({ text: r, layerIds: n, minScore: s, topResults: i, embeddingCache: a }) {
512
- return await Be({
543
+ async searchFields({ text: r, layerIds: n, minScore: s, topResults: a, embeddingCache: i }) {
544
+ return await Ke({
513
545
  combinedQuery: r,
514
546
  layerIds: n,
515
547
  embeddingsWorker: t,
516
548
  minScore: s,
517
- topResults: i,
518
- embeddingCache: a
549
+ topResults: a,
550
+ embeddingCache: i
519
551
  });
520
552
  }
521
553
  };
522
554
  }
523
- const Y = "0.1", w = 1536, Z = "openai", ee = C.default, F = `Name: {name}
555
+ const ee = "0.1", v = 1536, te = "openai", ne = C.default, F = `Name: {name}
524
556
  Title: {title}
525
557
  Description: {description}`, D = `Name: {name}
526
558
  Alias: {alias}
527
- Description: {description}`, te = l.object({
528
- schemaVersion: l.literal(Y),
559
+ Description: {description}`, re = l.object({
560
+ schemaVersion: l.literal(ee),
529
561
  modified: l.number().int().nonnegative(),
530
562
  embeddings: l.object({
531
- modelProvider: l.literal(Z),
532
- model: l.literal(ee),
533
- dimensions: l.literal(w),
563
+ modelProvider: l.literal(te),
564
+ model: l.literal(ne),
565
+ dimensions: l.literal(v),
534
566
  templates: l.object({
535
567
  layer: l.string().default(F),
536
568
  field: l.string().default(D)
@@ -542,89 +574,89 @@ Description: {description}`, te = l.object({
542
574
  name: l.string().min(1),
543
575
  title: l.string().catch(""),
544
576
  description: l.string().catch(""),
545
- vector: l.array(l.number()).length(w, {
546
- message: `Layer vector must be exactly ${w} dimensions`
577
+ vector: l.array(l.number()).length(v, {
578
+ message: `Layer vector must be exactly ${v} dimensions`
547
579
  }),
548
580
  fields: l.array(
549
581
  l.object({
550
582
  name: l.string().min(1),
551
583
  alias: l.string().catch(""),
552
584
  description: l.string().catch(""),
553
- vector: l.array(l.number()).length(w, {
554
- message: `Field vector must be exactly ${w} dimensions`
585
+ vector: l.array(l.number()).length(v, {
586
+ message: `Field vector must be exactly ${v} dimensions`
555
587
  })
556
588
  })
557
589
  )
558
590
  })
559
591
  ).default([])
560
- }), Ke = (e) => {
561
- const t = te.safeParse(e);
592
+ }), Xe = (e) => {
593
+ const t = re.safeParse(e);
562
594
  if (!t.success)
563
595
  throw new Error("Embeddings response validation failed. Regenerate embeddings.");
564
596
  return t.data;
565
- }, Je = (e, t) => {
597
+ }, Qe = (e, t) => {
566
598
  const r = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
567
599
  if (t.allLayers.forEach((s) => {
568
- s instanceof z && n.set(s.id, s);
600
+ s instanceof V && n.set(s.id, s);
569
601
  }), e.length !== n.size)
570
602
  throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");
571
603
  for (const s of e) {
572
- const i = n.get(s.id);
573
- if (!i)
604
+ const a = n.get(s.id);
605
+ if (!a)
574
606
  throw new Error(
575
607
  `Layer with ID ${s.id} not found in the original map during registry restoration. Regenerate embeddings.`
576
608
  );
577
- if (s.fields.length !== i.fields.length)
609
+ if (s.fields.length !== a.fields.length)
578
610
  throw new Error(
579
611
  `Field count mismatch for layer ID ${s.id} during registry restoration. Regenerate embeddings.`
580
612
  );
581
- const a = {
613
+ const i = {
582
614
  name: s.name,
583
615
  title: s.title,
584
616
  description: s.description
585
617
  }, o = /* @__PURE__ */ new Map();
586
618
  for (const c of s.fields) {
587
- const d = i.fieldsIndex.get(c.name);
619
+ const d = a.fieldsIndex.get(c.name);
588
620
  if (!d)
589
621
  throw new Error(
590
622
  `Field with name ${c.name} not found in the original layer ${s.id} during registry restoration. Regenerate embeddings.`
591
623
  );
592
624
  o.set(c.name, {
593
625
  name: c.name,
594
- alias: i.getFieldAlias(c.name) ?? c.alias,
626
+ alias: a.getFieldAlias(c.name) ?? c.alias,
595
627
  description: c.description,
596
628
  type: d.type || "unknown",
597
629
  valueType: d.valueType || "unknown",
598
- domain: i.getFieldDomain(c.name) ?? void 0
630
+ domain: a.getFieldDomain(c.name) ?? void 0
599
631
  });
600
632
  }
601
633
  r.set(s.id, {
602
- layerItem: a,
634
+ layerItem: i,
603
635
  fieldRegistry: o
604
636
  });
605
637
  }
606
638
  return r;
607
- }, Xe = async (e) => {
639
+ }, Ye = async (e) => {
608
640
  try {
609
- return (await we(e, {
641
+ return (await be(e, {
610
642
  responseType: "json"
611
643
  })).data;
612
644
  } catch (t) {
613
645
  throw new Error(`Failed to fetch data from ${e}: ${String(t)}`);
614
646
  }
615
- }, Qe = async (e) => {
647
+ }, Ze = async (e) => {
616
648
  const t = e.map;
617
649
  if (!t?.portalItem)
618
650
  throw new Error("WebMap portal item is missing.");
619
- const { resources: r } = await t.portalItem.fetchResources(), n = r.find((a) => a.resource.path === "embeddings-v01.json");
651
+ const { resources: r } = await t.portalItem.fetchResources(), n = r.find((i) => i.resource.path === "embeddings-v01.json");
620
652
  if (!n?.resource.url)
621
653
  throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");
622
- const s = await Xe(n.resource.url);
623
- return Ke(s);
654
+ const s = await Ye(n.resource.url);
655
+ return Xe(s);
624
656
  };
625
- class ne {
657
+ class se {
626
658
  constructor() {
627
- this.orchestratorReady = !1, this.chatHistory = [], this.priorSteps = [], this.sharedState = {}, this.threadId = "", this.agentRegistry = new Ne(), this.streamEpoch = 0;
659
+ this.orchestratorReady = !1, this.chatHistory = [], this.priorSteps = [], this.sharedState = {}, this.threadId = "", this.agentRegistry = new Ve(), this.streamEpoch = 0;
628
660
  }
629
661
  /**
630
662
  * Creates and returns an AI-ready Orchestrator instance.
@@ -632,15 +664,15 @@ class ne {
632
664
  * @returns Ready Orchestrator.
633
665
  */
634
666
  static async init(t) {
635
- const r = new ne();
667
+ const r = new se();
636
668
  try {
637
669
  if (t.view?.map) {
638
- await V.whenOnce(() => t.view.ready);
639
- const n = await Qe(t.view), s = Je(
670
+ await H.whenOnce(() => t.view.ready);
671
+ const n = await Ze(t.view), s = Qe(
640
672
  n.layers,
641
673
  t.view.map
642
674
  );
643
- r.layersAndFieldsRegistry = s, r.embeddingsWorker = await be(n);
675
+ r.layersAndFieldsRegistry = s, r.embeddingsWorker = await Ie(n);
644
676
  }
645
677
  return t.agents?.forEach((n) => {
646
678
  r.agentRegistry.register(n);
@@ -664,8 +696,8 @@ class ne {
664
696
  throw new Error("Orchestrator has no registered agents.");
665
697
  if (++this.streamEpoch, !t.trim())
666
698
  return;
667
- this.threadId = String(Date.now()), this.graph || (this.graph = We().compile({ checkpointer: new de() }));
668
- const r = this.embeddingsWorker ? ze({ worker: this.embeddingsWorker }) : void 0, n = this.embeddingsWorker ? Ge({ worker: this.embeddingsWorker }) : void 0, s = /* @__PURE__ */ new Map(), a = {
699
+ this.threadId = String(Date.now()), this.graph || (this.graph = He().compile({ checkpointer: new ue() }));
700
+ const r = this.embeddingsWorker ? Ge({ worker: this.embeddingsWorker }) : void 0, n = this.embeddingsWorker ? Je({ worker: this.embeddingsWorker }) : void 0, s = /* @__PURE__ */ new Map(), i = {
669
701
  version: "v2",
670
702
  streamMode: "custom",
671
703
  configurable: {
@@ -690,23 +722,23 @@ class ne {
690
722
  sharedState: this.sharedState
691
723
  }
692
724
  },
693
- a
725
+ i
694
726
  ), c = ++this.streamEpoch;
695
727
  for (yield* this.pipeStream(o, c); ; ) {
696
- const p = (await this.graph.getState(a, { subgraphs: !0 })).tasks.find((g) => g.interrupts.length > 0)?.interrupts[0]?.value;
728
+ const p = (await this.graph.getState(i, { subgraphs: !0 })).tasks.find((m) => m.interrupts.length > 0)?.interrupts[0]?.value;
697
729
  if (!p)
698
730
  break;
699
- this.currentInterrupt = p, this.interruptHandler = new Oe(this.graph, a), yield { runId: this.threadId, timestamp: Date.now(), type: "interrupt", interrupt: p };
731
+ this.currentInterrupt = p, this.interruptHandler = new ze(this.graph, i), yield { runId: this.threadId, timestamp: Date.now(), type: "interrupt", interrupt: p };
700
732
  try {
701
- const g = await this.interruptHandler.waitForUser(), I = ++this.streamEpoch;
702
- yield* this.pipeStream(g, I);
703
- } catch (g) {
704
- if (g) {
733
+ const m = await this.interruptHandler.waitForUser(), M = ++this.streamEpoch;
734
+ yield* this.pipeStream(m, M);
735
+ } catch (m) {
736
+ if (m) {
705
737
  yield {
706
738
  runId: this.threadId,
707
739
  timestamp: Date.now(),
708
740
  type: "error",
709
- error: { message: g?.message }
741
+ error: { message: m?.message }
710
742
  };
711
743
  return;
712
744
  }
@@ -714,12 +746,12 @@ class ne {
714
746
  return;
715
747
  }
716
748
  }
717
- const u = (await this.graph.getState(a, { subgraphs: !0 })).values;
749
+ const u = (await this.graph.getState(i, { subgraphs: !0 })).values;
718
750
  this.chatHistory = u.agentExecutionContext.messages.length ? u.agentExecutionContext.messages : this.chatHistory, this.priorSteps = u.agentExecutionContext.priorSteps?.slice(-5) ?? [], this.sharedState = u.agentExecutionContext.sharedState ?? {}, yield {
719
751
  runId: this.threadId,
720
752
  timestamp: Date.now(),
721
753
  type: "completed",
722
- result: { content: He(u.agentExecutionContext.messages) }
754
+ result: { content: u.finalOutputMessage }
723
755
  };
724
756
  }
725
757
  /**
@@ -765,63 +797,63 @@ class ne {
765
797
  this.embeddingsWorker && (this.embeddingsWorker.terminate(), this.embeddingsWorker = void 0), this.orchestratorReady = !1;
766
798
  }
767
799
  }
768
- const Ye = (e) => {
800
+ const et = (e) => {
769
801
  const t = /* @__PURE__ */ new Set();
770
802
  for (const n of e)
771
- if (le(n)) {
803
+ if (me(n)) {
772
804
  const s = n;
773
- s.tool_calls && s.tool_calls.length > 0 && s.tool_calls.forEach((i) => {
774
- i.id && t.add(i.id);
805
+ s.tool_calls && s.tool_calls.length > 0 && s.tool_calls.forEach((a) => {
806
+ a.id && t.add(a.id);
775
807
  });
776
808
  }
777
809
  return e.filter((n) => {
778
- if (ue(n)) {
810
+ if (pe(n)) {
779
811
  const s = n;
780
812
  return t.has(s.tool_call_id);
781
813
  }
782
814
  return !0;
783
815
  });
784
816
  }, $ = (e, t) => {
785
- const r = me.fromTemplate(e);
786
- return H.fromMessages([r, ...t]);
787
- }, Ze = async (e) => {
788
- const { promptText: t, modelTier: r, temperature: n, messages: s } = e, i = $(t, s ?? []), a = await b(r, n);
789
- return i.pipe(a);
790
- }, xt = async (e) => {
791
- const { promptText: t, modelTier: r = "default", temperature: n = 0, messages: s, inputVariables: i } = e, o = await (await Ze({
817
+ const r = he.fromTemplate(e);
818
+ return O.fromMessages([r, ...t]);
819
+ }, tt = async (e) => {
820
+ const { promptText: t, modelTier: r, temperature: n, messages: s } = e, a = $(t, s ?? []), i = await E(r, n);
821
+ return a.pipe(i);
822
+ }, St = async (e) => {
823
+ const { promptText: t, modelTier: r = "default", temperature: n = 0, messages: s, inputVariables: a } = e, o = await (await tt({
792
824
  promptText: t,
793
825
  modelTier: r,
794
826
  temperature: n,
795
827
  messages: s
796
- })).invoke(i ?? {});
828
+ })).invoke(a ?? {});
797
829
  if (typeof o == "string")
798
830
  return o;
799
831
  const c = o.content;
800
832
  return typeof c == "string" ? c : JSON.stringify(c);
801
- }, re = async (e) => {
802
- const { promptText: t, modelTier: r = "default", temperature: n = 0, messages: s, inputVariables: i, schema: a } = e, o = $(t, s ?? []), d = (await b(r, n)).withStructuredOutput(a);
803
- return await o.pipe(d).invoke(i ?? {});
804
- }, bt = async (e) => {
805
- const { promptText: t, modelTier: r = "default", temperature: n = 0, messages: s, inputVariables: i, tools: a } = e, o = a.length > 0 ? Ye(s ?? []) : s ?? [], c = $(t, o), d = await b(r, n);
806
- return await c.pipe(d.bindTools(a)).invoke(i ?? {});
807
- }, et = h.object({
808
- name: h.string(),
809
- description: h.string(),
810
- valueType: h.string(),
811
- alias: h.string()
812
- }), tt = h.object({
813
- fields: h.array(et)
814
- }), se = (e, t) => e.getFieldAlias(t) ?? void 0, k = (e, t) => se(e, t.name) ?? t.alias ?? "", nt = (e, t) => {
815
- const r = se(e, t.name);
833
+ }, ae = async (e) => {
834
+ const { promptText: t, modelTier: r = "default", temperature: n = 0, messages: s, inputVariables: a, schema: i } = e, o = $(t, s ?? []), d = (await E(r, n)).withStructuredOutput(i);
835
+ return await o.pipe(d).invoke(a ?? {});
836
+ }, It = async (e) => {
837
+ const { promptText: t, modelTier: r = "default", temperature: n = 0, messages: s, inputVariables: a, tools: i } = e, o = i.length > 0 ? et(s ?? []) : s ?? [], c = $(t, o), d = await E(r, n);
838
+ return await c.pipe(d.bindTools(i)).invoke(a ?? {});
839
+ }, nt = f.object({
840
+ name: f.string(),
841
+ description: f.string(),
842
+ valueType: f.string(),
843
+ alias: f.string()
844
+ }), rt = f.object({
845
+ fields: f.array(nt)
846
+ }), ie = (e, t) => e.getFieldAlias(t) ?? void 0, R = (e, t) => ie(e, t.name) ?? t.alias ?? "", st = (e, t) => {
847
+ const r = ie(e, t.name);
816
848
  return !!(r && r !== (t.alias ?? ""));
817
849
  };
818
- function _(e, t) {
850
+ function j(e, t) {
819
851
  const r = /* @__PURE__ */ new Map();
820
852
  for (const n of e.fields) {
821
- const s = t.fields.find((c) => c.name === n.name), i = k(e, n), a = nt(e, n), o = {
853
+ const s = t.fields.find((c) => c.name === n.name), a = R(e, n), i = st(e, n), o = {
822
854
  name: n.name,
823
855
  type: n.type,
824
- alias: a ? i : s?.alias ?? i,
856
+ alias: i ? a : s?.alias ?? a,
825
857
  description: s?.description ?? n.description ?? "",
826
858
  valueType: s?.valueType ?? n.valueType ?? "",
827
859
  domain: e.getFieldDomain(n.name) ?? void 0
@@ -830,111 +862,111 @@ function _(e, t) {
830
862
  }
831
863
  return r;
832
864
  }
833
- const rt = async (e) => {
834
- const r = await T("field_descriptions_prompt"), n = e.fields.filter((a) => !(k(e, a) && a.description)).map((a) => {
835
- const { name: o, type: c, description: d } = a, u = k(e, a);
865
+ const at = async (e) => {
866
+ const r = await T("field_descriptions_prompt"), n = e.fields.filter((i) => !(R(e, i) && i.description)).map((i) => {
867
+ const { name: o, type: c, description: d } = i, u = R(e, i);
836
868
  return [`Name: ${o}`, `Type: ${c}`, `Alias: ${u}`, `Description: ${d ?? "N/A"}`].join(", ");
837
869
  }).join(`
838
870
  `);
839
871
  if (n.length === 0)
840
- return _(e, { fields: [] });
872
+ return j(e, { fields: [] });
841
873
  const s = {
842
874
  existingItemTitle: e.portalItem?.title,
843
875
  existingItemDescription: e.portalItem?.description,
844
876
  existingLayerTitle: e.title,
845
877
  existingLayerDescription: e.portalItem?.description,
846
878
  fieldInformation: n
847
- }, i = await re({
879
+ }, a = await ae({
848
880
  promptText: r,
849
- schema: tt,
881
+ schema: rt,
850
882
  inputVariables: s
851
883
  });
852
- return _(e, i);
853
- }, st = h.object({
854
- title: h.string(),
855
- description: h.string(),
856
- name: h.string().nullable()
857
- }), it = async (e, t) => {
858
- const n = await T("layer_descriptions_prompt"), s = Array.from(t.values()), i = {
884
+ return j(e, a);
885
+ }, it = f.object({
886
+ title: f.string(),
887
+ description: f.string(),
888
+ name: f.string().nullable()
889
+ }), ot = async (e, t) => {
890
+ const n = await T("layer_descriptions_prompt"), s = Array.from(t.values()), a = {
859
891
  fieldInformation: JSON.stringify(s, null, 2),
860
892
  existingLayerTitle: e.title,
861
893
  existingLayerDescription: e.portalItem?.description,
862
894
  existingLayerSnippet: e.portalItem?.snippet,
863
895
  layerGeometryType: e.geometryType
864
896
  };
865
- return { ...await re({
897
+ return { ...await ae({
866
898
  promptText: n,
867
- schema: st,
868
- inputVariables: i
899
+ schema: it,
900
+ inputVariables: a
869
901
  }), name: e.title ?? null };
870
- }, at = async (e) => {
902
+ }, ct = async (e) => {
871
903
  const t = e.allLayers.toArray(), r = [], n = /* @__PURE__ */ new Map();
872
904
  for (const s of t)
873
- if (s instanceof z) {
874
- const i = (async () => {
875
- const a = await rt(s), o = await it(s, a);
876
- n.set(s.id, { layerItem: o, fieldRegistry: a });
905
+ if (s instanceof V) {
906
+ const a = (async () => {
907
+ const i = await at(s), o = await ot(s, i);
908
+ n.set(s.id, { layerItem: o, fieldRegistry: i });
877
909
  })();
878
- r.push(i);
910
+ r.push(a);
879
911
  }
880
912
  return await Promise.all(r), n;
881
- }, Et = async (e) => {
882
- await V.whenOnce(() => e.ready);
883
- const t = await at(e.map), { layers: r } = await ot(t), n = {
884
- schemaVersion: Y,
913
+ }, Mt = async (e) => {
914
+ await H.whenOnce(() => e.ready);
915
+ const t = await ct(e.map), { layers: r } = await dt(t), n = {
916
+ schemaVersion: ee,
885
917
  modified: Date.now(),
886
918
  embeddings: {
887
- modelProvider: Z,
888
- model: ee,
889
- dimensions: w,
919
+ modelProvider: te,
920
+ model: ne,
921
+ dimensions: v,
890
922
  templates: {
891
923
  layer: F,
892
924
  field: D
893
925
  }
894
926
  },
895
927
  layers: r
896
- }, s = te.safeParse(n);
928
+ }, s = re.safeParse(n);
897
929
  if (!s.success)
898
930
  throw console.error("Schema Mismatch:", s.error.format()), new Error("Webmap embedding generation failed validation.");
899
931
  return s.data;
900
- }, ot = async (e) => {
932
+ }, dt = async (e) => {
901
933
  const t = [], r = [];
902
- for (const [a, { fieldRegistry: o, layerItem: c }] of e.entries()) {
903
- const d = W(F, {
934
+ for (const [i, { fieldRegistry: o, layerItem: c }] of e.entries()) {
935
+ const d = _(F, {
904
936
  name: c.name,
905
937
  title: c.title,
906
938
  description: c.description
907
939
  });
908
940
  t.push(d);
909
941
  const u = {
910
- id: a,
942
+ id: i,
911
943
  name: c.name ?? "",
912
944
  title: c.title,
913
945
  description: c.description,
914
946
  vector: [],
915
947
  fields: []
916
948
  };
917
- for (const [, m] of o.entries()) {
918
- const y = W(D, {
919
- name: m.name,
920
- alias: m.alias,
921
- description: m.description
949
+ for (const [, g] of o.entries()) {
950
+ const w = _(D, {
951
+ name: g.name,
952
+ alias: g.alias,
953
+ description: g.description
922
954
  });
923
- t.push(y), u.fields.push({
924
- name: m.name,
925
- alias: m.alias,
926
- description: m.description,
955
+ t.push(w), u.fields.push({
956
+ name: g.name,
957
+ alias: g.alias,
958
+ description: g.description,
927
959
  vector: []
928
960
  });
929
961
  }
930
962
  r.push(u);
931
963
  }
932
- const n = await X(t);
964
+ const n = await Y(t);
933
965
  let s = 0;
934
- return { layers: r.map((a) => (a.vector = n[s++], a.fields.forEach((o) => {
966
+ return { layers: r.map((i) => (i.vector = n[s++], i.fields.forEach((o) => {
935
967
  o.vector = n[s++];
936
- }), a)) };
937
- }, W = (e, t) => e.replace(/\{(\w+)\}/gu, (r, n) => t[n] ?? ""), St = (e, t) => {
968
+ }), i)) };
969
+ }, _ = (e, t) => e.replace(/\{(\w+)\}/gu, (r, n) => t[n] ?? ""), kt = (e, t) => {
938
970
  if (e.length !== t.length)
939
971
  throw new Error("Vectors must be the same length");
940
972
  let r = 0, n = 0, s = 0;
@@ -942,21 +974,23 @@ const rt = async (e) => {
942
974
  const c = e[o], d = t[o];
943
975
  r += c * d, n += c * c, s += d * d;
944
976
  }
945
- const i = Math.sqrt(n * s);
946
- if (i === 0)
977
+ const a = Math.sqrt(n * s);
978
+ if (a === 0)
947
979
  return 0;
948
- const a = r / i;
949
- return Math.max(-1, Math.min(1, a));
980
+ const i = r / a;
981
+ return Math.max(-1, Math.min(1, i));
950
982
  };
951
983
  export {
952
- ne as Orchestrator,
953
- St as cosineSimilarity,
954
- b as createChatModel,
955
- Et as createWebmapEmbeddings,
956
- X as getEmbeddings,
957
- re as invokeStructuredPrompt,
958
- xt as invokeTextPrompt,
959
- bt as invokeToolPrompt,
960
- f as sendTraceMessage,
961
- vt as sendUXSuggestion
984
+ se as Orchestrator,
985
+ kt as cosineSimilarity,
986
+ ke as createAgentRuntimeState,
987
+ bt as createAgentRuntimeStateWithSharedState,
988
+ E as createChatModel,
989
+ Mt as createWebmapEmbeddings,
990
+ Y as getEmbeddings,
991
+ ae as invokeStructuredPrompt,
992
+ St as invokeTextPrompt,
993
+ It as invokeToolPrompt,
994
+ y as sendTraceMessage,
995
+ Et as sendUXSuggestion
962
996
  };
@@ -58,36 +58,43 @@ export type CustomConfigurableType = Record<string, unknown> & {
58
58
  };
59
59
  /** Cache for query embeddings to avoid duplicate API calls within a request */
60
60
  export type QueryEmbeddingCache = Map<string, number[]>;
61
- type SharedStateEntry = {
62
- value: unknown;
61
+ /** Stored shared state entry. `meta` is added by the orchestrator. */
62
+ type SharedStateEntry<T = unknown> = {
63
+ value: T;
63
64
  meta: {
64
65
  updatedByAgentId: string;
65
66
  updatedAt: number;
66
67
  };
67
68
  };
69
+ /** Patch shape returned by agents. `meta` is intentionally omitted. */
68
70
  type SharedStatePatchEntry<T = unknown> = {
69
71
  value: T;
70
72
  };
71
- export type SharedState = Record<string, SharedStateEntry>;
72
- export type SharedStatePatch = Record<string, SharedStatePatchEntry>;
73
- export interface AgentExecutionContext {
73
+ export type SharedState<T extends Record<string, unknown> = Record<string, unknown>> = {
74
+ [K in keyof T]?: SharedStateEntry<T[K]>;
75
+ };
76
+ export type SharedStatePatch<T extends Record<string, unknown> = Record<string, unknown>> = {
77
+ [K in keyof T]?: SharedStatePatchEntry<T[K]>;
78
+ };
79
+ export type AgentExecutionContextShape<TState extends SharedState = SharedState> = {
74
80
  userRequest: string;
75
81
  assignedTask: string;
76
82
  messages: ChatHistory;
77
83
  priorSteps: PriorStep[];
78
- sharedState: SharedState;
79
- }
84
+ sharedState: TState;
85
+ };
86
+ export type AgentExecutionContext<TState extends SharedState = SharedState> = Readonly<AgentExecutionContextShape<TState>>;
80
87
  export interface PriorStep {
81
88
  agentId: string;
82
89
  assignedTask: string;
83
90
  summary: string;
84
91
  status: AgentStatus;
85
92
  }
86
- export interface AgentResult {
93
+ export interface AgentResult<TPatch extends SharedStatePatch = SharedStatePatch> {
87
94
  status?: AgentStatus;
88
95
  outputMessage?: string;
89
96
  summary?: string;
90
- sharedStatePatch?: SharedStatePatch;
97
+ sharedStatePatch?: TPatch;
91
98
  }
92
99
  export type AgentStatus = "failed" | "success" | "unknown";
93
100
  export {};
@@ -0,0 +1,27 @@
1
+ import { BaseChannel } from '@langchain/langgraph/web';
2
+ import { AgentExecutionContext, AgentStatus, SharedStatePatch } from '../types/types';
3
+ /**
4
+ * Base state channel definitions
5
+ */
6
+ type StatelessAgentBaseState = {
7
+ agentExecutionContext: BaseChannel<AgentExecutionContext, unknown, unknown>;
8
+ outputMessage: BaseChannel<string, unknown, unknown>;
9
+ summary: BaseChannel<string, unknown, unknown>;
10
+ status: BaseChannel<AgentStatus | undefined, unknown, unknown>;
11
+ };
12
+ type StatefulAgentBaseState<TPatch extends SharedStatePatch = SharedStatePatch> = StatelessAgentBaseState & {
13
+ sharedStatePatch: BaseChannel<TPatch | undefined, unknown, unknown>;
14
+ };
15
+ /**
16
+ * Default context factory
17
+ */
18
+ export declare const createDefaultAgentExecutionContext: () => AgentExecutionContext;
19
+ /**
20
+ * Stateless base state (no shared state patch)
21
+ */
22
+ export declare const createAgentRuntimeState: () => StatelessAgentBaseState;
23
+ /**
24
+ * Stateful base state (includes shared state patch)
25
+ */
26
+ export declare const createAgentRuntimeStateWithSharedState: <TPatch extends SharedStatePatch = SharedStatePatch>() => StatefulAgentBaseState<TPatch>;
27
+ export {};
@@ -5,8 +5,3 @@ import { BaseMessage } from '@langchain/core/messages';
5
5
  * @knipIgnore
6
6
  */
7
7
  export declare const getUserContext: (messages: BaseMessage[], userCount?: number) => BaseMessage[];
8
- /**
9
- * Returns the concatenated content of all AI messages
10
- * that occur after the last HumanMessage.
11
- */
12
- export declare const finalAgentResponse: (messages: BaseMessage[]) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcgis/ai-orchestrator",
3
- "version": "5.1.0-next.93",
3
+ "version": "5.1.0-next.95",
4
4
  "description": "ArcGIS AI Orchestrator Package",
5
5
  "homepage": "https://developers.arcgis.com/javascript/latest/",
6
6
  "type": "module",