@automattic/agenttic-client 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,462 +1,364 @@
1
- import {
2
- BarChart,
3
- ChartBlock,
4
- LineChart,
5
- createChartBlock
6
- } from "./chunk-LAB4XYXR.js";
7
-
8
- // src/react/useClientContext.ts
9
- import { useMemo } from "@wordpress/element";
10
-
11
- // src/client/utils/logger.ts
12
- var logger = (message, ...args) => {
13
- if (isDebugEnabled()) {
14
- console.log(`[agenttic-client] ${message}`, ...args);
15
- }
1
+ var Nt = Object.defineProperty;
2
+ var $t = (t, e, s) => e in t ? Nt(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
3
+ var at = (t, e, s) => $t(t, typeof e != "symbol" ? e + "" : e, s);
4
+ import gt, { useMemo as it, useCallback as j, Component as Dt, useState as X, useRef as xt, useEffect as Y } from "react";
5
+ import { j as $, C as tt, g as _t, a as jt, B as Ft, b as Ht } from "./BarChart-Cid6YH81.js";
6
+ import qt from "streamdown";
7
+ import Ut from "remark-gfm";
8
+ import { __ as H, sprintf as ft } from "@wordpress/i18n";
9
+ import { LineChart as Bt } from "@automattic/charts";
10
+ import mt from "@wordpress/api-fetch";
11
+ const N = (t, ...e) => {
12
+ Jt() && console.log(`[agenttic-client] ${t}`, ...e);
16
13
  };
17
- function isDebugEnabled() {
18
- return typeof globalThis !== "undefined" && "window" in globalThis && globalThis.window?.DEBUG === "agenttic-client";
14
+ function Jt() {
15
+ var t;
16
+ return typeof globalThis < "u" && "window" in globalThis && ((t = globalThis.window) == null ? void 0 : t.DEBUG) === "agenttic-client";
19
17
  }
20
- function formatObject(obj) {
21
- return JSON.stringify(obj, null, 2);
18
+ function Mt(t) {
19
+ return JSON.stringify(t, null, 2);
22
20
  }
23
- function log(message, ...args) {
24
- console.log(`[agenttic-client] ${message}`, ...args);
21
+ function ht(t, ...e) {
22
+ console.log(`[agenttic-client] ${t}`, ...e);
25
23
  }
26
-
27
- // src/react/useClientContext.ts
28
- function useClientContext(getClientContextCallback) {
29
- const contextProvider = useMemo(() => {
30
- if (!getClientContextCallback) {
31
- return void 0;
32
- }
33
- const provider = {
34
- getClientContext: () => {
35
- try {
36
- const context = getClientContextCallback();
37
- return context || {};
38
- } catch (error) {
39
- logger("Error getting client context: %O", error);
40
- return {};
41
- }
24
+ function Ve(t) {
25
+ return it(() => t ? {
26
+ getClientContext: () => {
27
+ try {
28
+ return t() || {};
29
+ } catch (n) {
30
+ return N("Error getting client context: %O", n), {};
42
31
  }
43
- };
44
- return provider;
45
- }, [getClientContextCallback]);
46
- return contextProvider;
47
- }
48
-
49
- // src/react/useClientTools.ts
50
- import { useCallback, useMemo as useMemo2 } from "@wordpress/element";
51
- function useClientTools(getClientTools, executeTool) {
52
- const stableGetAvailableTools = useCallback(async () => {
53
- if (!getClientTools) {
54
- return [];
55
32
  }
56
- try {
57
- return await getClientTools();
58
- } catch (error) {
59
- logger("Error getting available tools: %O", error);
33
+ } : void 0, [t]);
34
+ }
35
+ function ze(t, e) {
36
+ const s = j(async () => {
37
+ if (!t)
60
38
  return [];
39
+ try {
40
+ return await t();
41
+ } catch (r) {
42
+ return N("Error getting available tools: %O", r), [];
61
43
  }
62
- }, [getClientTools]);
63
- const stableExecuteTool = useCallback(
64
- async (toolId, args) => {
65
- if (!executeTool) {
44
+ }, [t]), n = j(
45
+ async (r, o) => {
46
+ if (!e)
66
47
  throw new Error("No executeTool callback provided");
67
- }
68
48
  try {
69
- return await executeTool(toolId, args);
70
- } catch (error) {
71
- logger("Error executing tool %s: %O", toolId, error);
72
- throw error;
49
+ return await e(r, o);
50
+ } catch (i) {
51
+ throw N("Error executing tool %s: %O", r, i), i;
73
52
  }
74
53
  },
75
- [executeTool]
54
+ [e]
76
55
  );
77
- const toolProvider = useMemo2(() => {
78
- if (!getClientTools) {
79
- return void 0;
80
- }
81
- return {
82
- getAvailableTools: stableGetAvailableTools,
83
- executeTool: stableExecuteTool
84
- };
85
- }, [stableGetAvailableTools, stableExecuteTool, getClientTools]);
86
- return toolProvider;
87
- }
88
-
89
- // src/react/useAgentChat.ts
90
- import { useCallback as useCallback3, useEffect, useMemo as useMemo3, useRef, useState as useState2 } from "react";
91
-
92
- // src/client/utils/core.ts
93
- function generateRandomId() {
94
- const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
95
- let result = "";
96
- for (let i = 0; i < 8; i++) {
97
- result += chars.charAt(Math.floor(Math.random() * chars.length));
98
- }
99
- return result;
56
+ return it(() => {
57
+ if (t)
58
+ return {
59
+ getAvailableTools: s,
60
+ executeTool: n
61
+ };
62
+ }, [s, n, t]);
63
+ }
64
+ function lt() {
65
+ const t = "abcdefghijklmnopqrstuvwxyz0123456789";
66
+ let e = "";
67
+ for (let s = 0; s < 8; s++)
68
+ e += t.charAt(Math.floor(Math.random() * t.length));
69
+ return e;
100
70
  }
101
- function generateMessageId() {
102
- return generateRandomId();
71
+ function D() {
72
+ return lt();
103
73
  }
104
- function createRequestId() {
105
- return `req-${generateRandomId()}`;
74
+ function Lt() {
75
+ return `req-${lt()}`;
106
76
  }
107
- function createTaskId() {
108
- return `task-${generateRandomId()}`;
77
+ function Wt() {
78
+ return `task-${lt()}`;
109
79
  }
110
- function createTextPart(text) {
80
+ function Tt(t) {
111
81
  return {
112
82
  type: "text",
113
- text
83
+ text: t
114
84
  };
115
85
  }
116
- function createSendMessageRequest(params, method = "message/send", tokenStreaming = false) {
117
- const request = {
86
+ function Kt(t, e = "message/send", s = !1) {
87
+ const n = {
118
88
  jsonrpc: "2.0",
119
- id: createRequestId(),
120
- method,
89
+ id: Lt(),
90
+ method: e,
121
91
  params: {
122
- id: params.id || createTaskId(),
123
- ...params
92
+ id: t.id || Wt(),
93
+ ...t
124
94
  }
125
95
  };
126
- if (tokenStreaming && method === "message/stream") {
127
- request.tokenStreaming = true;
128
- }
129
- return request;
96
+ return s && e === "message/stream" && (n.tokenStreaming = !0), n;
130
97
  }
131
- function extractTextFromMessage(message) {
132
- if (!message || !message.parts || !Array.isArray(message.parts)) {
133
- return "";
134
- }
135
- return message.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ");
98
+ function U(t) {
99
+ return !t || !t.parts || !Array.isArray(t.parts) ? "" : t.parts.filter((e) => e.type === "text").map((e) => e.text).join(" ");
136
100
  }
137
- function createToolDataPart(tool) {
101
+ function Vt(t) {
138
102
  return {
139
103
  type: "data",
140
104
  data: {
141
- toolId: tool.id,
142
- toolName: tool.name,
143
- description: tool.description,
144
- inputSchema: tool.input_schema
105
+ toolId: t.id,
106
+ toolName: t.name,
107
+ description: t.description,
108
+ inputSchema: t.input_schema
145
109
  },
146
110
  metadata: {}
147
111
  };
148
112
  }
149
- function extractToolCallsFromMessage(message) {
150
- if (!message || !message.parts || !Array.isArray(message.parts)) {
151
- return [];
152
- }
153
- return message.parts.filter(
154
- (part) => part.type === "data" && "toolCallId" in part.data && "toolId" in part.data && "arguments" in part.data
113
+ function J(t) {
114
+ return !t || !t.parts || !Array.isArray(t.parts) ? [] : t.parts.filter(
115
+ (e) => e.type === "data" && "toolCallId" in e.data && "toolId" in e.data && "arguments" in e.data
155
116
  );
156
117
  }
157
- function createToolResultDataPart(toolCallId, toolId, result, error) {
118
+ function W(t, e, s, n) {
158
119
  return {
159
120
  type: "data",
160
121
  data: {
161
- toolCallId,
162
- toolId,
163
- result
122
+ toolCallId: t,
123
+ toolId: e,
124
+ result: s
164
125
  },
165
- metadata: error ? { error } : void 0
126
+ metadata: n ? { error: n } : void 0
166
127
  };
167
128
  }
168
- function createContextDataPart(clientContext) {
129
+ function zt(t) {
169
130
  return {
170
131
  type: "data",
171
132
  data: {
172
- clientContext
133
+ clientContext: t
173
134
  },
174
135
  metadata: {}
175
136
  };
176
137
  }
177
- function createTextMessage(text) {
138
+ function rt(t) {
178
139
  return {
179
140
  role: "user",
180
- parts: [createTextPart(text)],
141
+ parts: [Tt(t)],
181
142
  kind: "message",
182
- messageId: generateMessageId(),
143
+ messageId: D(),
183
144
  metadata: {
184
145
  timestamp: Date.now()
185
146
  }
186
147
  };
187
148
  }
188
- function createAgentTextMessage(text) {
149
+ function Z(t) {
189
150
  return {
190
151
  role: "agent",
191
- parts: [createTextPart(text)],
152
+ parts: [Tt(t)],
192
153
  kind: "message",
193
- messageId: generateMessageId(),
154
+ messageId: D(),
194
155
  metadata: {
195
156
  timestamp: Date.now()
196
157
  }
197
158
  };
198
159
  }
199
- function processToolExecutionResult(executionResult) {
200
- if (executionResult && typeof executionResult === "object" && "result" in executionResult) {
201
- return {
202
- result: executionResult.result,
203
- returnToAgent: executionResult.returnToAgent !== false,
204
- // Default to true
205
- agentMessage: executionResult.agentMessage
206
- // Pass through agentMessage if present
207
- };
208
- }
209
- return {
210
- result: executionResult,
211
- returnToAgent: true
160
+ function ct(t) {
161
+ return t && typeof t == "object" && "result" in t ? {
162
+ result: t.result,
163
+ returnToAgent: t.returnToAgent !== !1,
164
+ // Default to true
165
+ agentMessage: t.agentMessage
166
+ // Pass through agentMessage if present
167
+ } : {
168
+ result: t,
169
+ returnToAgent: !0
212
170
  };
213
171
  }
214
- function createToolResultMessage(toolResults, historyDataParts = []) {
172
+ function et(t, e = []) {
215
173
  return {
216
174
  role: "user",
217
175
  kind: "message",
218
- parts: [...historyDataParts, ...toolResults],
219
- messageId: generateMessageId(),
176
+ parts: [...e, ...t],
177
+ messageId: D(),
220
178
  metadata: {
221
179
  timestamp: Date.now()
222
180
  }
223
181
  };
224
182
  }
225
- function createAbortController() {
183
+ function Ge() {
226
184
  return new AbortController();
227
185
  }
228
-
229
- // src/client/utils/internal/messages.ts
230
- async function enhanceMessageWithTools(message, toolProvider) {
231
- if (!toolProvider) {
232
- return message;
233
- }
186
+ async function Gt(t, e) {
187
+ if (!e)
188
+ return t;
234
189
  try {
235
- const tools = await toolProvider.getAvailableTools();
236
- if (tools.length === 0) {
237
- return message;
238
- }
239
- const toolParts = tools.map(createToolDataPart);
190
+ const s = await e.getAvailableTools();
191
+ if (s.length === 0)
192
+ return t;
193
+ const n = s.map(Vt);
240
194
  return {
241
- ...message,
242
- parts: [...message.parts, ...toolParts]
195
+ ...t,
196
+ parts: [...t.parts, ...n]
243
197
  };
244
- } catch (error) {
245
- logger("Warning: Failed to get tools: %s", error);
246
- return message;
198
+ } catch (s) {
199
+ return N("Warning: Failed to get tools: %s", s), t;
247
200
  }
248
201
  }
249
- function enhanceMessageWithContext(message, contextProvider) {
250
- if (!contextProvider) {
251
- return message;
252
- }
202
+ function Qt(t, e) {
203
+ if (!e)
204
+ return t;
253
205
  try {
254
- const clientContext = contextProvider.getClientContext();
255
- if (!clientContext || Object.keys(clientContext).length === 0) {
256
- return message;
257
- }
258
- const contextPart = createContextDataPart(clientContext);
206
+ const s = e.getClientContext();
207
+ if (!s || Object.keys(s).length === 0)
208
+ return t;
209
+ const n = zt(s);
259
210
  return {
260
- ...message,
261
- parts: [...message.parts, contextPart]
211
+ ...t,
212
+ parts: [...t.parts, n]
262
213
  };
263
- } catch (error) {
264
- logger("Warning: Failed to get context: %s", error);
265
- return message;
214
+ } catch (s) {
215
+ return N("Warning: Failed to get context: %s", s), t;
266
216
  }
267
217
  }
268
- async function enhanceMessage(message, toolProvider, contextProvider) {
269
- let enhancedMessage = await enhanceMessageWithTools(
270
- message,
271
- toolProvider
218
+ async function Xt(t, e, s) {
219
+ let n = await Gt(
220
+ t,
221
+ e
272
222
  );
273
- enhancedMessage = enhanceMessageWithContext(
274
- enhancedMessage,
275
- contextProvider
223
+ n = Qt(
224
+ n,
225
+ s
276
226
  );
277
- const { metadata, ...messageForAgent } = enhancedMessage;
278
- return messageForAgent;
279
- }
280
-
281
- // src/client/utils/internal/streaming.ts
282
- function parseStreamChunk(chunk, buffer = "") {
283
- const events = [];
284
- const currentStreamData = buffer + chunk;
285
- let eventPayload = "";
286
- let lastCompleteEventEnd = 0;
287
- let searchStartIndex = 0;
288
- while (searchStartIndex < currentStreamData.length) {
289
- const newlineIndex = currentStreamData.indexOf(
290
- "\n",
291
- searchStartIndex
292
- );
293
- const line = newlineIndex === -1 ? currentStreamData.substring(searchStartIndex) : currentStreamData.substring(searchStartIndex, newlineIndex);
294
- if (line.startsWith("data:")) {
295
- if (eventPayload !== "") {
296
- eventPayload += "\n";
297
- }
298
- eventPayload += line.substring(
299
- line.startsWith("data: ") ? 6 : 5
227
+ const { metadata: a, ...r } = n;
228
+ return r;
229
+ }
230
+ function Yt(t, e = "") {
231
+ const s = [], n = e + t;
232
+ let a = "", r = 0, o = 0;
233
+ for (; o < n.length; ) {
234
+ const l = n.indexOf(
235
+ `
236
+ `,
237
+ o
238
+ ), c = l === -1 ? n.substring(o) : n.substring(o, l);
239
+ if (c.startsWith("data:"))
240
+ a !== "" && (a += `
241
+ `), a += c.substring(
242
+ c.startsWith("data: ") ? 6 : 5
300
243
  );
301
- } else if (line.trim() === "") {
302
- if (eventPayload) {
303
- try {
304
- events.push(JSON.parse(eventPayload));
305
- lastCompleteEventEnd = newlineIndex === -1 ? currentStreamData.length : newlineIndex + 1;
306
- } catch (e) {
307
- logger("Failed to parse SSE event: %o", e);
308
- logger("Problematic payload: %s", eventPayload);
309
- }
310
- eventPayload = "";
244
+ else if (c.trim() === "" && a) {
245
+ try {
246
+ s.push(JSON.parse(a)), r = l === -1 ? n.length : l + 1;
247
+ } catch (g) {
248
+ N("Failed to parse SSE event: %o", g), N("Problematic payload: %s", a);
311
249
  }
250
+ a = "";
312
251
  }
313
- if (newlineIndex === -1) {
314
- searchStartIndex = currentStreamData.length;
315
- } else {
316
- searchStartIndex = newlineIndex + 1;
317
- }
252
+ l === -1 ? o = n.length : o = l + 1;
318
253
  }
319
- const nextBuffer = currentStreamData.substring(lastCompleteEventEnd);
320
- return { events, nextBuffer };
321
- }
322
- async function* parseSSEStream(stream, options = {}) {
323
- const { supportDeltas = false } = options;
324
- const reader = stream.getReader();
325
- const decoder = new TextDecoder();
326
- let buffer = "";
327
- const accumulator = new DeltaAccumulator();
328
- let currentTaskId = null;
329
- let lastStatus = null;
254
+ const i = n.substring(r);
255
+ return { events: s, nextBuffer: i };
256
+ }
257
+ async function* Zt(t, e = {}) {
258
+ var c, g, y;
259
+ const { supportDeltas: s = !1 } = e, n = t.getReader(), a = new TextDecoder();
260
+ let r = "";
261
+ const o = new te();
262
+ let i = null, l = null;
330
263
  try {
331
- while (true) {
332
- const { done, value } = await reader.read();
333
- if (done) {
264
+ for (; ; ) {
265
+ const { done: b, value: A } = await n.read();
266
+ if (b)
334
267
  break;
335
- }
336
- const chunk = decoder.decode(value, { stream: true });
337
- const { events, nextBuffer } = parseStreamChunk(chunk, buffer);
338
- if (events && Array.isArray(events)) {
339
- for (let i = 0; i < events.length; i++) {
340
- const event = events[i];
341
- if (i > 0 && event.method === "message/delta" && typeof requestAnimationFrame !== "undefined") {
342
- await new Promise((resolve) => {
343
- requestAnimationFrame(() => resolve(void 0));
344
- });
345
- }
346
- if (event.error) {
268
+ const S = a.decode(A, { stream: !0 }), { events: M, nextBuffer: x } = Yt(S, r);
269
+ if (M && Array.isArray(M))
270
+ for (let p = 0; p < M.length; p++) {
271
+ const u = M[p];
272
+ if (p > 0 && u.method === "message/delta" && typeof requestAnimationFrame < "u" && await new Promise((h) => {
273
+ requestAnimationFrame(() => h(void 0));
274
+ }), u.error)
347
275
  throw new Error(
348
- `Streaming error: ${event.error.message}`
276
+ `Streaming error: ${u.error.message}`
349
277
  );
350
- }
351
- if (supportDeltas && event.method === "message/delta" && event.params?.delta) {
352
- const delta = event.params.delta;
278
+ if (s && u.method === "message/delta" && ((c = u.params) != null && c.delta)) {
279
+ const h = u.params.delta;
353
280
  try {
354
- if (delta.deltaType === "content") {
355
- accumulator.processContentDelta(
356
- delta.content
357
- );
358
- if (!currentTaskId && event.params.id) {
359
- currentTaskId = event.params.id;
360
- }
361
- if (currentTaskId) {
362
- const currentMessage = accumulator.getCurrentMessage();
363
- yield {
364
- id: currentTaskId,
365
- status: {
366
- state: "working",
367
- message: currentMessage
368
- },
369
- final: false,
370
- text: accumulator.getTextContent()
371
- };
372
- }
281
+ if (h.deltaType === "content" && (o.processContentDelta(
282
+ h.content
283
+ ), !i && u.params.id && (i = u.params.id), i)) {
284
+ const d = o.getCurrentMessage();
285
+ yield {
286
+ id: i,
287
+ status: {
288
+ state: "working",
289
+ message: d
290
+ },
291
+ final: !1,
292
+ text: o.getTextContent()
293
+ };
373
294
  }
374
- } catch (error) {
375
- logger("Failed to process delta: %o", error);
376
- }
377
- } else if (event.result && event.result.status) {
378
- currentTaskId = event.result.id;
379
- lastStatus = event.result.status;
380
- if (accumulator.getTextContent() || accumulator.getCurrentMessage().parts.length > 0) {
381
- accumulator.reset();
382
- }
383
- const update = {
384
- id: event.result.id,
385
- status: event.result.status,
386
- final: event.result.status.state === "completed" || event.result.status.state === "failed" || event.result.status.state === "canceled",
387
- text: extractTextFromMessage(
388
- event.result.status?.message || {
389
- role: "agent",
390
- parts: []
391
- }
392
- )
393
- };
394
- yield update;
395
- } else if (event.id && event.result) {
396
- currentTaskId = event.result.id;
397
- if (event.result.status) {
398
- const update = {
399
- id: event.result.id,
400
- status: event.result.status,
401
- final: event.result.status.state === "completed" || event.result.status.state === "failed" || event.result.status.state === "canceled",
402
- text: extractTextFromMessage(
403
- event.result.status?.message || {
404
- role: "agent",
405
- parts: []
406
- }
407
- )
408
- };
409
- yield update;
295
+ } catch (d) {
296
+ N("Failed to process delta: %o", d);
410
297
  }
411
- }
298
+ } else u.result && u.result.status ? (i = u.result.id, l = u.result.status, (o.getTextContent() || o.getCurrentMessage().parts.length > 0) && o.reset(), yield {
299
+ id: u.result.id,
300
+ status: u.result.status,
301
+ final: u.result.status.state === "completed" || u.result.status.state === "failed" || u.result.status.state === "canceled",
302
+ text: U(
303
+ ((g = u.result.status) == null ? void 0 : g.message) || {
304
+ role: "agent",
305
+ parts: []
306
+ }
307
+ )
308
+ }) : u.id && u.result && (i = u.result.id, u.result.status && (yield {
309
+ id: u.result.id,
310
+ status: u.result.status,
311
+ final: u.result.status.state === "completed" || u.result.status.state === "failed" || u.result.status.state === "canceled",
312
+ text: U(
313
+ ((y = u.result.status) == null ? void 0 : y.message) || {
314
+ role: "agent",
315
+ parts: []
316
+ }
317
+ )
318
+ }));
412
319
  }
413
- }
414
- buffer = nextBuffer;
320
+ r = x;
415
321
  }
416
322
  } finally {
417
- reader.releaseLock();
323
+ n.releaseLock();
418
324
  }
419
325
  }
420
- var DeltaAccumulator = class {
421
- textContent = "";
422
- toolCalls = /* @__PURE__ */ new Map();
326
+ class te {
327
+ constructor() {
328
+ at(this, "textContent", "");
329
+ at(this, "toolCalls", /* @__PURE__ */ new Map());
330
+ }
423
331
  /**
424
332
  * Process a simple content delta (server's actual format)
425
333
  * @param content - The text content to append
426
334
  */
427
- processContentDelta(content) {
428
- this.textContent += content;
335
+ processContentDelta(e) {
336
+ this.textContent += e;
429
337
  }
430
338
  /**
431
339
  * Process a delta message and accumulate the content (original format)
432
340
  * @param delta - The delta message to process
433
341
  */
434
- processDelta(delta) {
435
- switch (delta.type) {
342
+ processDelta(e) {
343
+ switch (e.type) {
436
344
  case "content":
437
- this.textContent += delta.content;
345
+ this.textContent += e.content;
438
346
  break;
439
347
  case "tool_name":
440
- if (!this.toolCalls.has(delta.toolCallIndex)) {
441
- this.toolCalls.set(delta.toolCallIndex, {
442
- toolCallId: delta.toolCallId,
443
- toolName: "",
444
- argumentFragments: []
445
- });
446
- }
447
- const toolCall = this.toolCalls.get(delta.toolCallIndex);
448
- toolCall.toolName += delta.content;
348
+ this.toolCalls.has(e.toolCallIndex) || this.toolCalls.set(e.toolCallIndex, {
349
+ toolCallId: e.toolCallId,
350
+ toolName: "",
351
+ argumentFragments: []
352
+ });
353
+ const s = this.toolCalls.get(e.toolCallIndex);
354
+ s.toolName += e.content;
449
355
  break;
450
356
  case "tool_argument":
451
- if (!this.toolCalls.has(delta.toolCallIndex)) {
452
- this.toolCalls.set(delta.toolCallIndex, {
453
- toolCallId: delta.toolCallId,
454
- toolName: "",
455
- argumentFragments: []
456
- });
457
- }
458
- const call = this.toolCalls.get(delta.toolCallIndex);
459
- call.argumentFragments.push(delta.content);
357
+ this.toolCalls.has(e.toolCallIndex) || this.toolCalls.set(e.toolCallIndex, {
358
+ toolCallId: e.toolCallId,
359
+ toolName: "",
360
+ argumentFragments: []
361
+ }), this.toolCalls.get(e.toolCallIndex).argumentFragments.push(e.content);
460
362
  break;
461
363
  }
462
364
  }
@@ -470,715 +372,566 @@ var DeltaAccumulator = class {
470
372
  * Get the current accumulated message
471
373
  * @param role - The role for the message (default: 'agent')
472
374
  */
473
- getCurrentMessage(role = "agent") {
474
- const parts = [];
475
- if (this.textContent) {
476
- parts.push({
477
- type: "text",
478
- text: this.textContent
479
- });
480
- }
481
- for (const [index, toolCall] of this.toolCalls) {
482
- if (toolCall.toolName) {
483
- const argumentsStr = toolCall.argumentFragments.join("");
484
- let args = {};
485
- if (argumentsStr) {
375
+ getCurrentMessage(e = "agent") {
376
+ const s = [];
377
+ this.textContent && s.push({
378
+ type: "text",
379
+ text: this.textContent
380
+ });
381
+ for (const [n, a] of this.toolCalls)
382
+ if (a.toolName) {
383
+ const r = a.argumentFragments.join("");
384
+ let o = {};
385
+ if (r)
486
386
  try {
487
- args = JSON.parse(argumentsStr);
387
+ o = JSON.parse(r);
488
388
  } catch {
489
- args = { _raw: argumentsStr };
389
+ o = { _raw: r };
490
390
  }
491
- }
492
- parts.push({
391
+ s.push({
493
392
  type: "data",
494
393
  data: {
495
- toolCallId: toolCall.toolCallId,
496
- toolId: toolCall.toolName,
497
- arguments: args
394
+ toolCallId: a.toolCallId,
395
+ toolId: a.toolName,
396
+ arguments: o
498
397
  }
499
398
  });
500
399
  }
501
- }
502
400
  return {
503
- role,
504
- parts,
401
+ role: e,
402
+ parts: s,
505
403
  kind: "message",
506
- messageId: generateMessageId()
404
+ messageId: D()
507
405
  };
508
406
  }
509
407
  /**
510
408
  * Reset the accumulator
511
409
  */
512
410
  reset() {
513
- this.textContent = "";
514
- this.toolCalls.clear();
515
- }
516
- };
517
-
518
- // src/client/utils/internal/errors.ts
519
- function handleRequestError(error, timeoutId, operation = "request") {
520
- clearTimeout(timeoutId);
521
- logger("%s failed with error: %O", operation, error);
522
- if (error instanceof Error) {
523
- logger("Error message: %s", error.message);
524
- logger("Error stack: %s", error.stack);
411
+ this.textContent = "", this.toolCalls.clear();
525
412
  }
526
- throw error;
527
413
  }
528
- function validateHttpResponse(response, operation = "request") {
529
- if (!response.ok) {
530
- throw new Error(`HTTP error! status: ${response.status}`);
531
- }
414
+ function bt(t, e, s = "request") {
415
+ throw clearTimeout(e), N("%s failed with error: %O", s, t), t instanceof Error && (N("Error message: %s", t.message), N("Error stack: %s", t.stack)), t;
532
416
  }
533
- function validateJsonRpcResponse(data, operation = "request") {
534
- if (data.error) {
535
- throw new Error(`A2A ${operation} error: ${data.error.message}`);
536
- }
537
- if (!data.result) {
538
- throw new Error(`No result in ${operation} response`);
539
- }
540
- return data.result;
417
+ function St(t, e = "request") {
418
+ if (!t.ok)
419
+ throw new Error(`HTTP error! status: ${t.status}`);
541
420
  }
542
- function validateStreamingResponse(response, operation = "streaming request") {
543
- validateHttpResponse(response, operation);
544
- if (!response.body) {
545
- throw new Error(`No response body for ${operation}`);
546
- }
421
+ function ee(t, e = "request") {
422
+ if (t.error)
423
+ throw new Error(`A2A ${e} error: ${t.error.message}`);
424
+ if (!t.result)
425
+ throw new Error(`No result in ${e} response`);
426
+ return t.result;
547
427
  }
548
- function createTimeoutHandler(timeout, operation = "request") {
549
- const controller = new AbortController();
550
- const timeoutId = setTimeout(
551
- () => controller.abort(),
552
- timeout
553
- );
554
- return { timeoutId, controller };
555
- }
556
-
557
- // src/client/utils/internal/requests.ts
558
- function constructAgentUrl(agentUrl, agentId) {
559
- return `${agentUrl}/${agentId}`;
560
- }
561
- function logRequest(method, url, headers, body) {
562
- logger("Request: %s %s", method, url);
563
- logger("Headers: %o", headers);
564
- if (body) {
565
- logger("Body: %s", formatObject(body));
566
- }
428
+ function se(t, e = "streaming request") {
429
+ if (St(t, e), !t.body)
430
+ throw new Error(`No response body for ${e}`);
431
+ }
432
+ function kt(t, e = "request") {
433
+ const s = new AbortController();
434
+ return { timeoutId: setTimeout(
435
+ () => s.abort(),
436
+ t
437
+ ), controller: s };
438
+ }
439
+ function ne(t, e) {
440
+ return `${t}/${e}`;
567
441
  }
568
- async function getHeaders(authProvider, isStreaming = false) {
569
- const baseHeaders = {
442
+ function ae(t, e, s, n) {
443
+ N("Request: %s %s", t, e), N("Headers: %o", s), n && N("Body: %s", Mt(n));
444
+ }
445
+ async function oe(t, e = !1) {
446
+ const s = {
570
447
  "Content-Type": "application/json"
571
448
  };
572
- if (isStreaming) {
573
- baseHeaders.Accept = "text/event-stream";
574
- }
575
- if (authProvider) {
576
- const authHeaders = await authProvider();
577
- return { ...baseHeaders, ...authHeaders };
449
+ if (e && (s.Accept = "text/event-stream"), t) {
450
+ const n = await t();
451
+ return { ...s, ...n };
578
452
  }
579
- return baseHeaders;
453
+ return s;
580
454
  }
581
- function combineSignals(signal1, signal2) {
582
- if (!signal2) {
583
- return signal1;
584
- }
585
- const controller = new AbortController();
586
- const handleAbort = (signal) => {
587
- if (!controller.signal.aborted) {
588
- controller.abort(signal.reason);
589
- }
455
+ function At(t, e) {
456
+ if (!e)
457
+ return t;
458
+ const s = new AbortController(), n = (a) => {
459
+ s.signal.aborted || s.abort(a.reason);
590
460
  };
591
- if (signal1.aborted) {
592
- controller.abort(signal1.reason);
593
- } else {
594
- signal1.addEventListener("abort", () => handleAbort(signal1), {
595
- once: true
596
- });
597
- }
598
- if (signal2.aborted) {
599
- controller.abort(signal2.reason);
600
- } else {
601
- signal2.addEventListener("abort", () => handleAbort(signal2), {
602
- once: true
603
- });
604
- }
605
- return controller.signal;
461
+ return t.aborted ? s.abort(t.reason) : t.addEventListener("abort", () => n(t), {
462
+ once: !0
463
+ }), e.aborted ? s.abort(e.reason) : e.addEventListener("abort", () => n(e), {
464
+ once: !0
465
+ }), s.signal;
606
466
  }
607
- function createFetchOptions(headers, body, signal) {
467
+ function vt(t, e, s) {
608
468
  return {
609
469
  method: "POST",
610
- headers,
611
- body,
612
- signal
470
+ headers: t,
471
+ body: e,
472
+ signal: s
613
473
  };
614
474
  }
615
- async function prepareRequest(params, config, options, toolProvider, contextProvider, defaultSessionId) {
616
- const { message, sessionId, taskId, metadata } = params;
617
- const { agentId, agentUrl, authProvider, proxy } = config;
618
- const { isStreaming = false, enableTokenStreaming = false } = options;
619
- const effectiveSessionId = sessionId || defaultSessionId;
620
- const fullAgentUrl = constructAgentUrl(agentUrl, agentId);
621
- const enhancedMessage = await enhanceMessage(
622
- message,
623
- toolProvider,
624
- contextProvider
625
- );
626
- const request = createSendMessageRequest(
475
+ async function st(t, e, s, n, a, r) {
476
+ const { message: o, sessionId: i, taskId: l, metadata: c } = t, { agentId: g, agentUrl: y, authProvider: b, proxy: A } = e, { isStreaming: S = !1, enableTokenStreaming: M = !1 } = s, x = i || r, p = ne(y, g), u = await Xt(
477
+ o,
478
+ n,
479
+ a
480
+ ), h = Kt(
627
481
  {
628
- id: taskId,
629
- sessionId: effectiveSessionId,
630
- message: enhancedMessage,
631
- metadata
482
+ id: l,
483
+ sessionId: x,
484
+ message: u,
485
+ metadata: c
632
486
  },
633
- isStreaming ? "message/stream" : "message/send",
634
- enableTokenStreaming && isStreaming
487
+ S ? "message/stream" : "message/send",
488
+ M && S
635
489
  // Only enable token streaming if using SSE
636
- );
637
- const headers = await getHeaders(authProvider, isStreaming);
638
- logRequest("POST", fullAgentUrl, headers, request);
639
- return {
640
- request,
641
- headers,
642
- enhancedMessage,
643
- effectiveSessionId,
644
- fullAgentUrl
490
+ ), d = await oe(b, S);
491
+ return ae("POST", p, d, h), {
492
+ request: h,
493
+ headers: d,
494
+ enhancedMessage: u,
495
+ effectiveSessionId: x,
496
+ fullAgentUrl: p
645
497
  };
646
498
  }
647
- async function executeRequest(preparedRequest, config, options = {}) {
648
- const { request, headers, fullAgentUrl } = preparedRequest;
649
- const { timeout } = config;
650
- const { abortSignal: externalSignal } = options;
651
- const { timeoutId, controller: timeoutController } = createTimeoutHandler(
652
- timeout,
499
+ async function Rt(t, e, s = {}) {
500
+ const { request: n, headers: a, fullAgentUrl: r } = t, { timeout: o } = e, { abortSignal: i } = s, { timeoutId: l, controller: c } = kt(
501
+ o,
653
502
  "request"
654
- );
655
- const signal = externalSignal ? combineSignals(timeoutController.signal, externalSignal) : timeoutController.signal;
503
+ ), g = i ? At(c.signal, i) : c.signal;
656
504
  try {
657
- const fetchOptions = createFetchOptions(
658
- headers,
659
- JSON.stringify(request),
660
- signal
505
+ const y = vt(
506
+ a,
507
+ JSON.stringify(n),
508
+ g
661
509
  );
662
- logger("Making request to %s with options: %O", fullAgentUrl, {
663
- method: fetchOptions.method,
664
- headers: fetchOptions.headers
510
+ N("Making request to %s with options: %O", r, {
511
+ method: y.method,
512
+ headers: y.headers
665
513
  });
666
- const response = await fetch(fullAgentUrl, fetchOptions);
667
- clearTimeout(timeoutId);
668
- validateHttpResponse(response, "request");
669
- const data = await response.json();
670
- logger(
514
+ const b = await fetch(r, y);
515
+ clearTimeout(l), St(b, "request");
516
+ const A = await b.json();
517
+ return N(
671
518
  "Response from %s: %d %O",
672
- fullAgentUrl,
673
- response.status,
674
- formatObject(data)
675
- );
676
- return validateJsonRpcResponse(data, "request");
677
- } catch (error) {
678
- handleRequestError(error, timeoutId, "request");
519
+ r,
520
+ b.status,
521
+ Mt(A)
522
+ ), ee(A, "request");
523
+ } catch (y) {
524
+ bt(y, l, "request");
679
525
  }
680
526
  }
681
- async function* executeStreamingRequest(preparedRequest, config, options) {
682
- const { request, headers, fullAgentUrl } = preparedRequest;
683
- const {} = config;
684
- const {
685
- streamingTimeout = 6e4,
686
- abortSignal: externalSignal,
687
- enableTokenStreaming = false
688
- } = options;
689
- const { timeoutId, controller } = createTimeoutHandler(
690
- streamingTimeout,
527
+ async function* Et(t, e, s) {
528
+ const { request: n, headers: a, fullAgentUrl: r } = t, {
529
+ streamingTimeout: o = 6e4,
530
+ abortSignal: i,
531
+ enableTokenStreaming: l = !1
532
+ } = s, { timeoutId: c, controller: g } = kt(
533
+ o,
691
534
  "streaming request"
692
- );
693
- const signal = externalSignal ? combineSignals(controller.signal, externalSignal) : controller.signal;
535
+ ), y = i ? At(g.signal, i) : g.signal;
694
536
  try {
695
- const requestBody = JSON.stringify(request);
696
- const fetchOptions = createFetchOptions(headers, requestBody, signal);
697
- const response = await fetch(fullAgentUrl, fetchOptions);
698
- clearTimeout(timeoutId);
699
- validateStreamingResponse(response, "streaming request");
700
- if (!response.body) {
537
+ const b = JSON.stringify(n), A = vt(a, b, y), S = await fetch(r, A);
538
+ if (clearTimeout(c), se(S, "streaming request"), !S.body)
701
539
  throw new Error(
702
540
  "Response body is null - server may not support streaming"
703
541
  );
704
- }
705
- const supportDeltas = enableTokenStreaming && request.tokenStreaming === true;
706
- yield* parseSSEStream(response.body, {
707
- supportDeltas
542
+ const M = l && n.tokenStreaming === !0;
543
+ yield* Zt(S.body, {
544
+ supportDeltas: M
708
545
  });
709
- } catch (error) {
710
- handleRequestError(error, timeoutId, "streaming request");
546
+ } catch (b) {
547
+ bt(b, c, "streaming request");
711
548
  }
712
549
  }
713
-
714
- // src/client/index.ts
715
- var DEFAULT_TIMEOUT = 12e4;
716
- var toolResultPromises = /* @__PURE__ */ new Map();
717
- async function hasMatchingToolCallbacks(toolProvider, message) {
718
- if (!toolProvider || !message || !toolProvider.getAvailableTools) {
719
- return false;
720
- }
721
- const toolCalls = extractToolCallsFromMessage(message);
722
- if (toolCalls.length === 0) {
723
- return false;
724
- }
550
+ const re = 12e4, ut = /* @__PURE__ */ new Map();
551
+ async function ie(t, e) {
552
+ if (!t || !e || !t.getAvailableTools)
553
+ return !1;
554
+ const s = J(e);
555
+ if (s.length === 0)
556
+ return !1;
725
557
  try {
726
- const availableTools = await toolProvider.getAvailableTools();
727
- for (const toolCall of toolCalls) {
728
- const hasCallback = availableTools.some(
729
- (tool) => tool.id === toolCall.data.toolId
730
- );
731
- if (hasCallback) {
732
- return true;
733
- }
734
- }
735
- } catch (error) {
736
- return false;
558
+ const n = await t.getAvailableTools();
559
+ for (const a of s)
560
+ if (n.some(
561
+ (o) => o.id === a.data.toolId
562
+ ))
563
+ return !0;
564
+ } catch {
565
+ return !1;
737
566
  }
738
- return false;
739
- }
740
- function clearToolResultPromises() {
741
- toolResultPromises.clear();
742
- }
743
- function updateToolResultsWithResolvedPromises(toolResults) {
744
- return toolResults.map((toolResult) => {
745
- const toolCallId = toolResult.data.toolCallId;
746
- const promiseEntry = toolResultPromises.get(toolCallId);
747
- if (promiseEntry && promiseEntry.resolvedValue !== null) {
748
- const resolvedValue = promiseEntry.resolvedValue;
749
- if (resolvedValue.error) {
750
- return createToolResultDataPart(
751
- toolCallId,
752
- toolResult.data.toolId,
753
- void 0,
754
- resolvedValue.error
755
- );
756
- }
757
- return createToolResultDataPart(
758
- toolCallId,
759
- toolResult.data.toolId,
760
- resolvedValue
567
+ return !1;
568
+ }
569
+ function le() {
570
+ ut.clear();
571
+ }
572
+ function ce(t) {
573
+ return t.map((e) => {
574
+ const s = e.data.toolCallId, n = ut.get(s);
575
+ if (n && n.resolvedValue !== null) {
576
+ const a = n.resolvedValue;
577
+ return a.error ? W(
578
+ s,
579
+ e.data.toolId,
580
+ void 0,
581
+ a.error
582
+ ) : W(
583
+ s,
584
+ e.data.toolId,
585
+ a
761
586
  );
762
587
  }
763
- return toolResult;
588
+ return e;
764
589
  });
765
590
  }
766
- async function executeToolCallBatch(toolCalls, toolProvider, messageId) {
767
- const results = [];
768
- const agentMessages = [];
769
- let shouldReturnToAgent = false;
770
- for (const toolCall of toolCalls) {
771
- const { toolCallId, toolId, arguments: args } = toolCall.data;
591
+ async function Pt(t, e, s) {
592
+ const n = [], a = [];
593
+ let r = !1;
594
+ for (const o of t) {
595
+ const { toolCallId: i, toolId: l, arguments: c } = o.data;
772
596
  try {
773
- const executionResult = await toolProvider.executeTool(
774
- toolId,
775
- args,
776
- messageId,
777
- toolCallId
778
- );
779
- const { result, returnToAgent, agentMessage } = processToolExecutionResult(executionResult);
780
- if (returnToAgent) {
781
- shouldReturnToAgent = true;
782
- }
783
- if (agentMessage) {
784
- agentMessages.push(createAgentTextMessage(agentMessage));
785
- }
786
- results.push(
787
- createToolResultDataPart(
788
- toolCallId,
789
- toolId,
790
- result
597
+ const g = await e.executeTool(
598
+ l,
599
+ c,
600
+ s,
601
+ i
602
+ ), { result: y, returnToAgent: b, agentMessage: A } = ct(g);
603
+ b && (r = !0), A && a.push(Z(A)), n.push(
604
+ W(
605
+ i,
606
+ l,
607
+ y
791
608
  )
792
609
  );
793
- } catch (error) {
794
- shouldReturnToAgent = true;
795
- results.push(
796
- createToolResultDataPart(
797
- toolCallId,
798
- toolId,
610
+ } catch (g) {
611
+ r = !0, n.push(
612
+ W(
613
+ i,
614
+ l,
799
615
  void 0,
800
- error instanceof Error ? error.message : String(error)
616
+ g instanceof Error ? g.message : String(g)
801
617
  )
802
618
  );
803
619
  }
804
620
  }
805
- return { results, shouldReturnToAgent, agentMessages };
806
- }
807
- function conversationHistoryToDataParts(conversationHistory) {
808
- const historyParts = [];
809
- for (const message of conversationHistory) {
810
- for (const part of message.parts) {
811
- if (part.type === "text") {
812
- historyParts.push({
813
- type: "data",
814
- data: {
815
- role: message.role,
816
- text: part.text
817
- }
818
- });
819
- } else if (part.type === "data") {
820
- historyParts.push(part);
821
- }
822
- }
823
- }
824
- return historyParts;
621
+ return { results: n, shouldReturnToAgent: r, agentMessages: a };
825
622
  }
826
- async function continueTask(taskId, message, requestConfig, toolProvider, contextProvider, sessionId, abortSignal) {
827
- const continueParams = {
828
- message,
829
- taskId,
830
- sessionId: void 0
831
- // Use task's session
832
- };
833
- const preparedRequest = await prepareRequest(
834
- continueParams,
835
- requestConfig,
836
- { isStreaming: false, abortSignal },
837
- toolProvider,
838
- contextProvider,
839
- sessionId
623
+ function pt(t) {
624
+ const e = [];
625
+ for (const s of t)
626
+ for (const n of s.parts)
627
+ n.type === "text" ? e.push({
628
+ type: "data",
629
+ data: {
630
+ role: s.role,
631
+ text: n.text
632
+ }
633
+ }) : n.type === "data" && e.push(n);
634
+ return e;
635
+ }
636
+ async function ot(t, e, s, n, a, r, o) {
637
+ const l = await st(
638
+ {
639
+ message: e,
640
+ taskId: t,
641
+ sessionId: void 0
642
+ // Use task's session
643
+ },
644
+ s,
645
+ { isStreaming: !1 },
646
+ n,
647
+ a,
648
+ r
840
649
  );
841
- return await executeRequest(preparedRequest, requestConfig, {
842
- abortSignal
650
+ return await Rt(l, s, {
651
+ abortSignal: o
843
652
  });
844
653
  }
845
- async function continueTaskStreamed(taskId, message, requestConfig, toolProvider, contextProvider, sessionId, abortSignal, requestOptions) {
846
- const continueParams = {
847
- message,
848
- taskId,
654
+ async function yt(t, e, s, n, a, r, o, i) {
655
+ const l = {
656
+ message: e,
657
+ taskId: t,
849
658
  sessionId: void 0
850
659
  // Use task's session
851
- };
852
- const options = requestOptions || { isStreaming: true };
853
- const preparedRequest = await prepareRequest(
854
- continueParams,
855
- requestConfig,
660
+ }, c = i || { isStreaming: !0 }, g = await st(
661
+ l,
662
+ s,
856
663
  {
857
- ...options,
858
- abortSignal
664
+ ...c
859
665
  },
860
- toolProvider,
861
- contextProvider,
862
- sessionId
863
- );
864
- const stream = executeStreamingRequest(preparedRequest, requestConfig, {
865
- ...options,
866
- abortSignal
666
+ n,
667
+ a,
668
+ r
669
+ ), y = Et(g, s, {
670
+ ...c,
671
+ abortSignal: o
867
672
  });
868
- return processAgentResponseStream(
869
- stream,
870
- toolProvider,
871
- contextProvider,
872
- requestConfig,
873
- sessionId,
874
- true,
673
+ return Ot(
674
+ y,
675
+ n,
676
+ a,
677
+ s,
678
+ r,
679
+ !0,
875
680
  // withHistory
876
681
  [],
877
682
  // newConversationParts - empty for continueTask
878
- abortSignal,
879
- options
683
+ o,
684
+ c
880
685
  // Pass through the same request options
881
686
  );
882
687
  }
883
- async function* processAgentResponseStream(stream, toolProvider, contextProvider, requestConfig, sessionId, withHistory = true, newConversationParts = [], abortSignal, requestOptions) {
884
- for await (const update of stream) {
885
- yield update;
886
- if (update.status.state === "running" && update.status.message && toolProvider && await hasMatchingToolCallbacks(
887
- toolProvider,
888
- update.status.message
688
+ async function* Ot(t, e, s, n, a, r = !0, o = [], i, l) {
689
+ var c, g, y, b, A, S, M, x, p, u, h, d;
690
+ for await (const f of t) {
691
+ if (yield f, f.status.state === "running" && f.status.message && e && await ie(
692
+ e,
693
+ f.status.message
889
694
  )) {
890
- const toolCalls = extractToolCallsFromMessage(
891
- update.status.message
695
+ const T = J(
696
+ f.status.message
892
697
  );
893
- for (const toolCall of toolCalls) {
894
- const { toolCallId, toolId, arguments: args } = toolCall.data;
895
- toolProvider.executeTool(
896
- toolId,
897
- args,
898
- update.status?.message?.messageId,
899
- toolCallId
900
- ).catch((error) => {
698
+ for (const I of T) {
699
+ const { toolCallId: P, toolId: w, arguments: m } = I.data;
700
+ e.executeTool(
701
+ w,
702
+ m,
703
+ (g = (c = f.status) == null ? void 0 : c.message) == null ? void 0 : g.messageId,
704
+ P
705
+ ).catch((k) => {
901
706
  console.error(
902
- `Tool execution failed for ${toolId}:`,
903
- error
707
+ `Tool execution failed for ${w}:`,
708
+ k
904
709
  );
905
710
  });
906
711
  }
907
712
  yield {
908
- id: update.id,
713
+ id: f.id,
909
714
  status: {
910
715
  state: "running",
911
716
  message: {
912
717
  role: "agent",
913
718
  kind: "message",
914
- parts: toolCalls,
915
- messageId: generateMessageId()
719
+ parts: T,
720
+ messageId: D()
916
721
  }
917
722
  },
918
- final: false,
723
+ final: !1,
919
724
  text: ""
920
725
  };
921
726
  }
922
- if (update.status.state === "input-required" && update.status.message && toolProvider) {
923
- const toolCalls = extractToolCallsFromMessage(
924
- update.status.message
727
+ if (f.status.state === "input-required" && f.status.message && e) {
728
+ const T = J(
729
+ f.status.message
925
730
  );
926
- if (toolCalls.length > 0) {
927
- const toolResults = [];
928
- let shouldReturnToAgent = false;
929
- const toolParts = [];
930
- const agentMessages = [];
931
- for (const toolCall of toolCalls) {
731
+ if (T.length > 0) {
732
+ const I = [];
733
+ let P = !1;
734
+ const w = [], m = [];
735
+ for (const k of T) {
932
736
  const {
933
- toolCallId,
934
- toolId,
935
- arguments: args
936
- } = toolCall.data;
737
+ toolCallId: C,
738
+ toolId: E,
739
+ arguments: R
740
+ } = k.data;
937
741
  try {
938
- const executionResult = await toolProvider.executeTool(
939
- toolId,
940
- args,
941
- update.status?.message?.messageId,
942
- toolCallId
943
- );
944
- const { result, returnToAgent, agentMessage } = processToolExecutionResult(executionResult);
945
- if (returnToAgent) {
946
- shouldReturnToAgent = true;
947
- }
948
- if (agentMessage) {
949
- agentMessages.push(
950
- createAgentTextMessage(agentMessage)
951
- );
952
- }
953
- if (result.result instanceof Promise) {
954
- const promise = result.result;
955
- const promiseEntry = {
956
- promise,
742
+ const O = await e.executeTool(
743
+ E,
744
+ R,
745
+ (b = (y = f.status) == null ? void 0 : y.message) == null ? void 0 : b.messageId,
746
+ C
747
+ ), { result: v, returnToAgent: F, agentMessage: B } = ct(O);
748
+ if (F && (P = !0), B && m.push(
749
+ Z(B)
750
+ ), v.result instanceof Promise) {
751
+ const K = v.result, z = {
752
+ promise: K,
957
753
  resolvedValue: null
958
754
  };
959
- toolResultPromises.set(
960
- toolCallId,
961
- promiseEntry
962
- );
963
- promise.then((resolvedValue) => {
964
- promiseEntry.resolvedValue = resolvedValue;
965
- }).catch((error) => {
755
+ ut.set(
756
+ C,
757
+ z
758
+ ), K.then((q) => {
759
+ z.resolvedValue = q;
760
+ }).catch((q) => {
966
761
  console.error(
967
- `Promise rejected for tool call ${toolCallId}:`,
968
- error
969
- );
970
- promiseEntry.resolvedValue = {
971
- error: error instanceof Error ? error.message : String(error)
762
+ `Promise rejected for tool call ${C}:`,
763
+ q
764
+ ), z.resolvedValue = {
765
+ error: q instanceof Error ? q.message : String(q)
972
766
  };
973
767
  });
974
768
  }
975
- const toolResult = createToolResultDataPart(
976
- toolCallId,
977
- toolId,
978
- result
769
+ const _ = W(
770
+ C,
771
+ E,
772
+ v
979
773
  );
980
- toolResults.push(toolResult);
981
- toolParts.push(toolResult);
982
- } catch (error) {
983
- const toolResult = createToolResultDataPart(
984
- toolCallId,
985
- toolId,
774
+ I.push(_), w.push(_);
775
+ } catch (O) {
776
+ const v = W(
777
+ C,
778
+ E,
986
779
  void 0,
987
- error instanceof Error ? error.message : String(error)
780
+ O instanceof Error ? O.message : String(O)
988
781
  );
989
- toolResults.push(toolResult);
990
- toolParts.push(toolResult);
782
+ I.push(v), w.push(v);
991
783
  }
992
784
  }
993
- newConversationParts.push(update.status.message);
994
- if (shouldReturnToAgent) {
995
- const historyDataParts = conversationHistoryToDataParts(newConversationParts);
996
- const toolResultMessage = createToolResultMessage(
997
- toolResults,
998
- historyDataParts
785
+ if (o.push(f.status.message), P) {
786
+ const k = pt(o), C = et(
787
+ I,
788
+ k
999
789
  );
1000
790
  yield {
1001
- id: update.id,
791
+ id: f.id,
1002
792
  status: {
1003
793
  state: "working",
1004
- message: toolResultMessage
794
+ message: C
1005
795
  },
1006
- final: false,
796
+ final: !1,
1007
797
  text: ""
1008
798
  };
1009
- const continuedTaskStream = await continueTaskStreamed(
1010
- update.id,
1011
- toolResultMessage,
1012
- requestConfig,
1013
- toolProvider,
1014
- contextProvider,
1015
- sessionId,
1016
- abortSignal,
1017
- requestOptions
799
+ const E = await yt(
800
+ f.id,
801
+ C,
802
+ n,
803
+ e,
804
+ s,
805
+ a,
806
+ i,
807
+ l
1018
808
  );
1019
- let continuedTaskUpdate = null;
1020
- for await (const streamUpdate of continuedTaskStream) {
1021
- if (!streamUpdate.final) {
1022
- yield streamUpdate;
1023
- } else {
1024
- continuedTaskUpdate = streamUpdate;
1025
- }
1026
- }
1027
- if (!continuedTaskUpdate) {
809
+ let R = null;
810
+ for await (const F of E)
811
+ F.final ? R = F : yield F;
812
+ if (!R)
1028
813
  throw new Error(
1029
814
  "Continue task stream ended without final result"
1030
815
  );
1031
- }
1032
- let continuedToolCalls = continuedTaskUpdate.status?.message ? extractToolCallsFromMessage(
1033
- continuedTaskUpdate.status.message
816
+ let O = (A = R.status) != null && A.message ? J(
817
+ R.status.message
1034
818
  ) : [];
1035
- if (toolResults.length > 0) {
1036
- newConversationParts.push({
1037
- role: "agent",
1038
- kind: "message",
1039
- parts: toolResults,
1040
- messageId: generateMessageId()
1041
- });
1042
- }
1043
- let finalTask = continuedTaskUpdate;
1044
- if (continuedToolCalls.length > 0) {
1045
- yield {
1046
- ...continuedTaskUpdate,
1047
- final: false,
1048
- text: extractTextFromMessage(
1049
- continuedTaskUpdate.status?.message || {
1050
- role: "agent",
1051
- kind: "message",
819
+ I.length > 0 && o.push({
820
+ role: "agent",
821
+ kind: "message",
822
+ parts: I,
823
+ messageId: D()
824
+ });
825
+ let v = R;
826
+ if (O.length > 0)
827
+ for (yield {
828
+ ...R,
829
+ final: !1,
830
+ text: U(
831
+ ((S = R.status) == null ? void 0 : S.message) || {
1052
832
  parts: [],
1053
- messageId: generateMessageId()
833
+ messageId: D()
1054
834
  }
1055
835
  )
1056
- };
1057
- while (continuedToolCalls.length > 0) {
1058
- if (finalTask.status?.message) {
1059
- newConversationParts.push(
1060
- finalTask.status.message
1061
- );
1062
- }
836
+ }; O.length > 0; ) {
837
+ (M = v.status) != null && M.message && o.push(
838
+ v.status.message
839
+ );
1063
840
  const {
1064
- results: moreResults,
1065
- shouldReturnToAgent: moreShouldReturn
1066
- } = await executeToolCallBatch(
1067
- continuedToolCalls,
1068
- toolProvider,
1069
- finalTask.status?.message?.messageId
841
+ results: F,
842
+ shouldReturnToAgent: B
843
+ } = await Pt(
844
+ O,
845
+ e,
846
+ (p = (x = v.status) == null ? void 0 : x.message) == null ? void 0 : p.messageId
1070
847
  );
1071
- if (moreResults.length > 0) {
1072
- yield {
1073
- id: finalTask.id,
1074
- status: {
1075
- state: "working",
1076
- message: {
1077
- role: "agent",
1078
- kind: "message",
1079
- parts: moreResults,
1080
- messageId: generateMessageId()
1081
- }
1082
- // Simple message with just the results
1083
- },
1084
- final: false,
1085
- text: ""
1086
- };
1087
- }
1088
- if (moreShouldReturn) {
1089
- const moreHistoryDataParts = withHistory ? conversationHistoryToDataParts(
1090
- newConversationParts
1091
- ) : [];
1092
- const moreResultMessage = createToolResultMessage(
1093
- moreResults,
1094
- moreHistoryDataParts
1095
- );
1096
- const moreTaskStream = await continueTaskStreamed(
1097
- finalTask.id,
1098
- moreResultMessage,
1099
- requestConfig,
1100
- toolProvider,
1101
- contextProvider,
1102
- sessionId,
1103
- abortSignal,
1104
- requestOptions
1105
- );
1106
- let moreFinalTask = null;
1107
- for await (const streamUpdate of moreTaskStream) {
1108
- if (!streamUpdate.final) {
1109
- yield streamUpdate;
1110
- } else {
1111
- moreFinalTask = streamUpdate;
848
+ if (F.length > 0 && (yield {
849
+ id: v.id,
850
+ status: {
851
+ state: "working",
852
+ message: {
853
+ role: "agent",
854
+ kind: "message",
855
+ parts: F,
856
+ messageId: D()
1112
857
  }
1113
- }
1114
- if (!moreFinalTask) {
858
+ // Simple message with just the results
859
+ },
860
+ final: !1,
861
+ text: ""
862
+ }), B) {
863
+ const _ = r ? pt(
864
+ o
865
+ ) : [], K = et(
866
+ F,
867
+ _
868
+ ), z = await yt(
869
+ v.id,
870
+ K,
871
+ n,
872
+ e,
873
+ s,
874
+ a,
875
+ i,
876
+ l
877
+ );
878
+ let q = null;
879
+ for await (const nt of z)
880
+ nt.final ? q = nt : yield nt;
881
+ if (!q)
1115
882
  throw new Error(
1116
883
  "Continue task stream ended without final result"
1117
884
  );
1118
- }
1119
- finalTask = moreFinalTask;
1120
- continuedToolCalls = finalTask.status?.message ? extractToolCallsFromMessage(
1121
- finalTask.status.message
1122
- ) : [];
1123
- if (continuedToolCalls.length > 0) {
1124
- yield {
1125
- id: finalTask.id,
1126
- status: finalTask.status,
1127
- final: false,
1128
- text: extractTextFromMessage(
1129
- finalTask.status?.message || {
1130
- role: "agent",
1131
- kind: "message",
1132
- parts: [],
1133
- messageId: generateMessageId()
1134
- }
1135
- )
1136
- };
1137
- }
1138
- } else {
885
+ v = q, O = (u = v.status) != null && u.message ? J(
886
+ v.status.message
887
+ ) : [], O.length > 0 && (yield {
888
+ id: v.id,
889
+ status: v.status,
890
+ final: !1,
891
+ text: U(
892
+ ((h = v.status) == null ? void 0 : h.message) || {
893
+ parts: [],
894
+ messageId: D()
895
+ }
896
+ )
897
+ });
898
+ } else
1139
899
  break;
1140
- }
1141
900
  }
1142
- }
1143
901
  yield {
1144
- ...finalTask,
1145
- final: true,
1146
- text: extractTextFromMessage(
1147
- finalTask.status?.message || {
1148
- role: "agent",
1149
- kind: "message",
902
+ ...v,
903
+ final: !0,
904
+ text: U(
905
+ ((d = v.status) == null ? void 0 : d.message) || {
1150
906
  parts: [],
1151
- messageId: generateMessageId()
907
+ messageId: D()
1152
908
  }
1153
909
  )
1154
910
  };
1155
911
  } else {
1156
- const enhancedMessage = {
1157
- ...update.status.message,
1158
- parts: toolParts
1159
- };
1160
- const enhancedUpdate = {
1161
- ...update,
912
+ const k = {
913
+ ...f.status.message,
914
+ parts: w
915
+ }, C = {
916
+ ...f,
1162
917
  status: {
1163
- ...update.status,
1164
- message: enhancedMessage
918
+ ...f.status,
919
+ message: k
1165
920
  },
1166
- final: agentMessages.length === 0,
921
+ final: m.length === 0,
1167
922
  // Only final if no agent messages to follow
1168
- text: extractTextFromMessage(enhancedMessage)
923
+ text: U(k)
1169
924
  };
1170
- yield enhancedUpdate;
1171
- if (agentMessages.length > 0) {
1172
- const combinedAgentText = agentMessages.map((msg) => extractTextFromMessage(msg)).join(" ");
1173
- const finalAgentMessage = createAgentTextMessage(combinedAgentText);
925
+ if (yield C, m.length > 0) {
926
+ const E = m.map((O) => U(O)).join(" "), R = Z(E);
1174
927
  yield {
1175
- id: enhancedUpdate.id,
928
+ id: C.id,
1176
929
  status: {
1177
930
  state: "completed",
1178
- message: finalAgentMessage
931
+ message: R
1179
932
  },
1180
- final: true,
1181
- text: combinedAgentText
933
+ final: !0,
934
+ text: E
1182
935
  };
1183
936
  }
1184
937
  }
@@ -1186,1540 +939,1596 @@ async function* processAgentResponseStream(stream, toolProvider, contextProvider
1186
939
  }
1187
940
  }
1188
941
  }
1189
- function createClient(config) {
942
+ function ue(t) {
1190
943
  const {
1191
- agentId,
1192
- agentUrl,
1193
- authProvider,
1194
- defaultSessionId,
1195
- timeout = DEFAULT_TIMEOUT,
1196
- toolProvider,
1197
- contextProvider,
1198
- enableStreaming = false
1199
- } = config;
1200
- const requestConfig = {
1201
- agentId,
1202
- agentUrl,
1203
- authProvider,
1204
- timeout
944
+ agentId: e,
945
+ agentUrl: s,
946
+ authProvider: n,
947
+ defaultSessionId: a,
948
+ timeout: r = re,
949
+ toolProvider: o,
950
+ contextProvider: i,
951
+ enableStreaming: l = !1
952
+ } = t, c = {
953
+ agentId: e,
954
+ agentUrl: s,
955
+ authProvider: n,
956
+ timeout: r
1205
957
  };
1206
958
  return {
1207
- async sendMessage(params) {
1208
- const { withHistory = true, abortSignal } = params;
1209
- const sessionId = params.sessionId || defaultSessionId || void 0;
1210
- const newConversationParts = [];
1211
- newConversationParts.push(params.message);
1212
- const preparedRequest = await prepareRequest(
1213
- params,
1214
- requestConfig,
1215
- { isStreaming: false, abortSignal },
1216
- toolProvider,
1217
- contextProvider,
1218
- sessionId
959
+ async sendMessage(g) {
960
+ var h, d;
961
+ const { withHistory: y = !0, abortSignal: b } = g, A = g.sessionId || a || void 0, S = [];
962
+ S.push(g.message);
963
+ const M = await st(
964
+ g,
965
+ c,
966
+ { isStreaming: !1 },
967
+ o,
968
+ i,
969
+ A
1219
970
  );
1220
- let currentTask = await executeRequest(
1221
- preparedRequest,
1222
- requestConfig,
1223
- { abortSignal }
971
+ let x = await Rt(
972
+ M,
973
+ c,
974
+ { abortSignal: b }
1224
975
  );
1225
- const allToolParts = [];
1226
- const agentMessages = [];
1227
- while (currentTask.status.message && toolProvider) {
1228
- const toolCalls = extractToolCallsFromMessage(
1229
- currentTask.status.message
976
+ const p = [], u = [];
977
+ for (; x.status.message && o; ) {
978
+ const f = J(
979
+ x.status.message
1230
980
  );
1231
- if (toolCalls.length === 0) {
981
+ if (f.length === 0)
1232
982
  break;
1233
- }
1234
- allToolParts.push(...toolCalls);
1235
- const toolResults = [];
1236
- let shouldReturnToAgent = false;
1237
- for (const toolCall of toolCalls) {
983
+ p.push(...f);
984
+ const T = [];
985
+ let I = !1;
986
+ for (const P of f) {
1238
987
  const {
1239
- toolCallId,
1240
- toolId,
1241
- arguments: args
1242
- } = toolCall.data;
988
+ toolCallId: w,
989
+ toolId: m,
990
+ arguments: k
991
+ } = P.data;
1243
992
  try {
1244
- const executionResult = await toolProvider.executeTool(
1245
- toolId,
1246
- args
993
+ const C = await o.executeTool(
994
+ m,
995
+ k
996
+ ), { result: E, returnToAgent: R, agentMessage: O } = ct(C);
997
+ R && (I = !0), O && u.push(
998
+ Z(O)
1247
999
  );
1248
- const { result, returnToAgent, agentMessage } = processToolExecutionResult(executionResult);
1249
- if (returnToAgent) {
1250
- shouldReturnToAgent = true;
1251
- }
1252
- if (agentMessage) {
1253
- agentMessages.push(
1254
- createAgentTextMessage(agentMessage)
1255
- );
1256
- }
1257
- const toolResult = createToolResultDataPart(
1258
- toolCallId,
1259
- toolId,
1260
- result
1000
+ const v = W(
1001
+ w,
1002
+ m,
1003
+ E
1261
1004
  );
1262
- toolResults.push(toolResult);
1263
- allToolParts.push(toolResult);
1264
- } catch (error) {
1265
- const toolResult = createToolResultDataPart(
1266
- toolCallId,
1267
- toolId,
1005
+ T.push(v), p.push(v);
1006
+ } catch (C) {
1007
+ const E = W(
1008
+ w,
1009
+ m,
1268
1010
  void 0,
1269
- error instanceof Error ? error.message : String(error)
1011
+ C instanceof Error ? C.message : String(C)
1270
1012
  );
1271
- toolResults.push(toolResult);
1272
- allToolParts.push(toolResult);
1013
+ T.push(E), p.push(E);
1273
1014
  }
1274
1015
  }
1275
- newConversationParts.push(currentTask.status.message);
1276
- if (shouldReturnToAgent) {
1277
- const toolResultMessage = createToolResultMessage(toolResults);
1278
- currentTask = await continueTask(
1279
- currentTask.id,
1280
- toolResultMessage,
1281
- requestConfig,
1282
- toolProvider,
1283
- contextProvider,
1284
- sessionId,
1285
- abortSignal
1016
+ if (S.push(x.status.message), I) {
1017
+ const P = et(T);
1018
+ x = await ot(
1019
+ x.id,
1020
+ P,
1021
+ c,
1022
+ o,
1023
+ i,
1024
+ A,
1025
+ b
1286
1026
  );
1287
- } else {
1027
+ } else
1288
1028
  break;
1289
- }
1290
1029
  }
1291
- if (allToolParts.length > 0) {
1292
- if (currentTask.status?.message) {
1293
- const enhancedMessage = {
1294
- ...currentTask.status.message,
1295
- parts: allToolParts
1296
- };
1297
- currentTask = {
1298
- ...currentTask,
1299
- status: {
1300
- ...currentTask.status,
1301
- message: enhancedMessage
1302
- }
1303
- };
1304
- }
1030
+ if (p.length > 0 && (h = x.status) != null && h.message) {
1031
+ const f = {
1032
+ ...x.status.message,
1033
+ parts: p
1034
+ };
1035
+ x = {
1036
+ ...x,
1037
+ status: {
1038
+ ...x.status,
1039
+ message: f
1040
+ }
1041
+ };
1305
1042
  }
1306
- if (agentMessages.length > 0) {
1307
- const combinedAgentText = agentMessages.map((msg) => extractTextFromMessage(msg)).join(" ");
1308
- const finalAgentMessage = createAgentTextMessage(combinedAgentText);
1043
+ if (u.length > 0) {
1044
+ const f = u.map((I) => U(I)).join(" "), T = Z(f);
1309
1045
  return {
1310
- ...currentTask,
1046
+ ...x,
1311
1047
  // Keep the enhanced message with tool results
1312
1048
  // The agent message will be handled separately by the caller
1313
- text: combinedAgentText,
1314
- agentMessage: finalAgentMessage
1049
+ text: f,
1050
+ agentMessage: T
1315
1051
  // Add this for the caller to handle
1316
1052
  };
1317
1053
  }
1318
1054
  return {
1319
- ...currentTask,
1320
- text: extractTextFromMessage(
1321
- currentTask.status?.message || {
1322
- role: "agent",
1323
- kind: "message",
1055
+ ...x,
1056
+ text: U(
1057
+ ((d = x.status) == null ? void 0 : d.message) || {
1324
1058
  parts: [],
1325
- messageId: generateMessageId()
1059
+ messageId: D()
1326
1060
  }
1327
1061
  )
1328
1062
  };
1329
1063
  },
1330
- async *sendMessageStream(params) {
1064
+ async *sendMessageStream(g) {
1331
1065
  const {
1332
- withHistory = true,
1333
- abortSignal,
1334
- enableStreaming: requestStreaming
1335
- } = params;
1336
- const sessionId = params.sessionId || defaultSessionId || void 0;
1337
- const useTokenStreaming = requestStreaming ?? enableStreaming;
1338
- const newConversationParts = [];
1339
- newConversationParts.push(params.message);
1340
- const preparedRequest = await prepareRequest(
1341
- params,
1342
- requestConfig,
1066
+ withHistory: y = !0,
1067
+ abortSignal: b,
1068
+ enableStreaming: A
1069
+ } = g, S = g.sessionId || a || void 0, M = A ?? l, x = [];
1070
+ x.push(g.message);
1071
+ const p = await st(
1072
+ g,
1073
+ c,
1343
1074
  {
1344
- isStreaming: true,
1075
+ isStreaming: !0,
1345
1076
  // Always use message/stream endpoint for SSE
1346
- enableTokenStreaming: useTokenStreaming,
1347
- // Optional token-by-token streaming
1348
- streamingTimeout: timeout,
1349
- abortSignal
1077
+ enableTokenStreaming: M
1350
1078
  },
1351
- toolProvider,
1352
- contextProvider,
1353
- sessionId
1354
- );
1355
- const stream = executeStreamingRequest(
1356
- preparedRequest,
1357
- requestConfig,
1079
+ o,
1080
+ i,
1081
+ S
1082
+ ), u = Et(
1083
+ p,
1084
+ c,
1358
1085
  {
1359
- isStreaming: true,
1360
- enableTokenStreaming: useTokenStreaming,
1086
+ enableTokenStreaming: M,
1361
1087
  // Token streaming is optional
1362
- streamingTimeout: timeout,
1363
- abortSignal
1088
+ streamingTimeout: r,
1089
+ abortSignal: b
1364
1090
  }
1365
1091
  );
1366
- yield* processAgentResponseStream(
1367
- stream,
1368
- toolProvider,
1369
- contextProvider,
1370
- requestConfig,
1371
- sessionId,
1372
- withHistory,
1373
- newConversationParts,
1374
- abortSignal,
1092
+ yield* Ot(
1093
+ u,
1094
+ o,
1095
+ i,
1096
+ c,
1097
+ S,
1098
+ y,
1099
+ x,
1100
+ b,
1375
1101
  {
1376
- isStreaming: true,
1377
- enableTokenStreaming: useTokenStreaming,
1378
- streamingTimeout: timeout
1102
+ isStreaming: !0,
1103
+ enableTokenStreaming: M,
1104
+ streamingTimeout: r
1379
1105
  }
1380
1106
  );
1381
1107
  },
1382
- async continueTask(taskId, userInput, sessionId) {
1383
- const userMessage = createTextMessage(userInput);
1384
- const continuedTask = await continueTask(
1385
- taskId,
1386
- userMessage,
1387
- requestConfig,
1388
- toolProvider,
1389
- contextProvider,
1390
- sessionId
1108
+ async continueTask(g, y, b) {
1109
+ var x;
1110
+ const A = rt(y);
1111
+ let M = await ot(
1112
+ g,
1113
+ A,
1114
+ c,
1115
+ o,
1116
+ i,
1117
+ b
1391
1118
  );
1392
- let currentTask = continuedTask;
1393
- while (currentTask.status.state === "input-required" && currentTask.status.message && toolProvider) {
1394
- const toolCalls = extractToolCallsFromMessage(
1395
- currentTask.status.message
1119
+ for (; M.status.state === "input-required" && M.status.message && o; ) {
1120
+ const p = J(
1121
+ M.status.message
1396
1122
  );
1397
- if (toolCalls.length === 0) {
1123
+ if (p.length === 0)
1398
1124
  break;
1399
- }
1400
- const { results: toolResults, shouldReturnToAgent } = await executeToolCallBatch(toolCalls, toolProvider);
1401
- if (shouldReturnToAgent) {
1402
- const toolResultMessage = createToolResultMessage(toolResults);
1403
- currentTask = await continueTask(
1404
- currentTask.id,
1405
- toolResultMessage,
1406
- requestConfig,
1407
- toolProvider,
1408
- contextProvider,
1409
- sessionId
1125
+ const { results: u, shouldReturnToAgent: h } = await Pt(p, o);
1126
+ if (h) {
1127
+ const d = et(u);
1128
+ M = await ot(
1129
+ M.id,
1130
+ d,
1131
+ c,
1132
+ o,
1133
+ i,
1134
+ b
1410
1135
  );
1411
- } else {
1136
+ } else
1412
1137
  break;
1413
- }
1414
1138
  }
1415
1139
  return {
1416
- ...currentTask,
1417
- text: extractTextFromMessage(
1418
- currentTask.status?.message || {
1419
- role: "agent",
1420
- kind: "message",
1140
+ ...M,
1141
+ text: U(
1142
+ ((x = M.status) == null ? void 0 : x.message) || {
1421
1143
  parts: [],
1422
- messageId: generateMessageId()
1144
+ messageId: D()
1423
1145
  }
1424
1146
  )
1425
1147
  };
1426
1148
  },
1427
- async getTask(taskId) {
1149
+ async getTask(g) {
1428
1150
  throw new Error("getTask not implemented yet");
1429
1151
  },
1430
- async cancelTask(taskId) {
1152
+ async cancelTask(g) {
1431
1153
  throw new Error("cancelTask not implemented yet");
1432
1154
  }
1433
1155
  };
1434
1156
  }
1435
-
1436
- // src/react/conversationStorage.ts
1437
- var STORAGE_KEY = "a8c_agenttic_conversation_history";
1438
- function extractStorableContent(message) {
1439
- const textParts = message.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n");
1440
- const toolCalls = message.parts.filter(
1441
- (part) => part.type === "data" && "toolCallId" in part.data && "arguments" in part.data
1442
- ).map((part) => ({
1443
- toolCallId: part.data.toolCallId,
1444
- toolId: part.data.toolId,
1445
- arguments: part.data.arguments
1446
- }));
1447
- const toolResults = message.parts.filter(
1448
- (part) => part.type === "data" && "toolCallId" in part.data && "result" in part.data
1449
- ).map((part) => ({
1450
- toolCallId: part.data.toolCallId,
1451
- result: part.data.result,
1452
- error: part.data.error
1453
- }));
1454
- const hasToolInteractions = toolCalls.length > 0 || toolResults.length > 0;
1455
- const storageRole = hasToolInteractions ? "agent" : message.role;
1456
- const timestamp = message.metadata?.timestamp ?? Date.now();
1157
+ const dt = "a8c_agenttic_conversation_history";
1158
+ function de(t) {
1159
+ var i;
1160
+ const e = t.parts.filter((l) => l.type === "text").map((l) => l.text).join(`
1161
+ `), s = t.parts.filter(
1162
+ (l) => l.type === "data" && "toolCallId" in l.data && "arguments" in l.data
1163
+ ).map((l) => ({
1164
+ toolCallId: l.data.toolCallId,
1165
+ toolId: l.data.toolId,
1166
+ arguments: l.data.arguments
1167
+ })), n = t.parts.filter(
1168
+ (l) => l.type === "data" && "toolCallId" in l.data && "result" in l.data
1169
+ ).map((l) => ({
1170
+ toolCallId: l.data.toolCallId,
1171
+ result: l.data.result,
1172
+ error: l.data.error
1173
+ })), r = s.length > 0 || n.length > 0 ? "agent" : t.role, o = ((i = t.metadata) == null ? void 0 : i.timestamp) ?? Date.now();
1457
1174
  return {
1458
- role: storageRole,
1459
- content: textParts || "(No text content)",
1460
- timestamp,
1461
- ...toolCalls.length > 0 && { toolCalls },
1462
- ...toolResults.length > 0 && { toolResults }
1175
+ role: r,
1176
+ content: e || "(No text content)",
1177
+ timestamp: o,
1178
+ ...s.length > 0 && { toolCalls: s },
1179
+ ...n.length > 0 && { toolResults: n }
1463
1180
  };
1464
1181
  }
1465
- function restoreMessage(stored) {
1466
- const parts = [];
1467
- if (stored.content && stored.content !== "(No text content)") {
1468
- parts.push({
1469
- type: "text",
1470
- text: stored.content
1471
- });
1472
- }
1473
- if (stored.toolCalls) {
1474
- for (const toolCall of stored.toolCalls) {
1475
- parts.push({
1182
+ function ge(t) {
1183
+ const e = [];
1184
+ if (t.content && t.content !== "(No text content)" && e.push({
1185
+ type: "text",
1186
+ text: t.content
1187
+ }), t.toolCalls)
1188
+ for (const s of t.toolCalls)
1189
+ e.push({
1476
1190
  type: "data",
1477
1191
  data: {
1478
- toolCallId: toolCall.toolCallId,
1479
- toolId: toolCall.toolId,
1480
- arguments: toolCall.arguments
1192
+ toolCallId: s.toolCallId,
1193
+ toolId: s.toolId,
1194
+ arguments: s.arguments
1481
1195
  }
1482
1196
  });
1483
- }
1484
- }
1485
- if (stored.toolResults) {
1486
- for (const toolResult of stored.toolResults) {
1487
- parts.push({
1197
+ if (t.toolResults)
1198
+ for (const s of t.toolResults)
1199
+ e.push({
1488
1200
  type: "data",
1489
1201
  data: {
1490
- toolCallId: toolResult.toolCallId,
1491
- result: toolResult.result,
1492
- ...toolResult.error && { error: toolResult.error }
1202
+ toolCallId: s.toolCallId,
1203
+ result: s.result,
1204
+ ...s.error && { error: s.error }
1493
1205
  }
1494
1206
  });
1495
- }
1496
- }
1497
1207
  return {
1498
- role: stored.role,
1208
+ role: t.role,
1499
1209
  kind: "message",
1500
- parts,
1501
- messageId: generateMessageId(),
1210
+ parts: e,
1211
+ messageId: D(),
1502
1212
  metadata: {
1503
- timestamp: stored.timestamp
1213
+ timestamp: t.timestamp
1504
1214
  }
1505
1215
  };
1506
1216
  }
1507
- var conversationCache = /* @__PURE__ */ new Map();
1508
- var maxCacheSize = 50;
1509
- async function storeConversation(sessionId, messages, conversationStorageKey) {
1510
- const currentStorageKey = conversationStorageKey || sessionId;
1511
- conversationCache.set(currentStorageKey, [...messages]);
1512
- if (conversationCache.size > maxCacheSize) {
1513
- const firstKey = conversationCache.keys().next().value;
1514
- if (firstKey) {
1515
- conversationCache.delete(firstKey);
1516
- }
1517
- }
1518
- if (typeof sessionStorage === "undefined") {
1519
- return;
1520
- }
1521
- try {
1522
- const stored = {
1523
- storageKey: currentStorageKey,
1524
- messages: messages.map(extractStorableContent),
1525
- lastUpdated: Date.now()
1526
- };
1527
- sessionStorage.setItem(
1528
- `${STORAGE_KEY}_${currentStorageKey}`,
1529
- JSON.stringify(stored)
1530
- );
1531
- } catch (error) {
1532
- logger(
1533
- "Failed to store conversation in sessionStorage for key %s: %O",
1534
- currentStorageKey,
1535
- error
1536
- );
1217
+ const L = /* @__PURE__ */ new Map(), fe = 50;
1218
+ async function me(t, e, s) {
1219
+ const n = s || t;
1220
+ if (L.set(n, [...e]), L.size > fe) {
1221
+ const a = L.keys().next().value;
1222
+ a && L.delete(a);
1537
1223
  }
1224
+ if (!(typeof sessionStorage > "u"))
1225
+ try {
1226
+ const a = {
1227
+ storageKey: n,
1228
+ messages: e.map(de),
1229
+ lastUpdated: Date.now()
1230
+ };
1231
+ sessionStorage.setItem(
1232
+ `${dt}_${n}`,
1233
+ JSON.stringify(a)
1234
+ );
1235
+ } catch (a) {
1236
+ N(
1237
+ "Failed to store conversation in sessionStorage for key %s: %O",
1238
+ n,
1239
+ a
1240
+ );
1241
+ }
1538
1242
  }
1539
- async function loadConversation(sessionId, conversationStorageKey) {
1540
- const currentStorageKey = conversationStorageKey || sessionId;
1541
- if (conversationCache.has(currentStorageKey)) {
1542
- return [...conversationCache.get(currentStorageKey)];
1543
- }
1544
- if (typeof sessionStorage === "undefined") {
1243
+ async function he(t, e) {
1244
+ const s = e || t;
1245
+ if (L.has(s))
1246
+ return [...L.get(s)];
1247
+ if (typeof sessionStorage > "u")
1545
1248
  return [];
1546
- }
1547
1249
  try {
1548
- const stored = sessionStorage.getItem(
1549
- `${STORAGE_KEY}_${currentStorageKey}`
1250
+ const n = sessionStorage.getItem(
1251
+ `${dt}_${s}`
1550
1252
  );
1551
- if (stored) {
1552
- const conversation = JSON.parse(stored);
1553
- const messages = conversation.messages.map(restoreMessage);
1554
- conversationCache.set(currentStorageKey, messages);
1555
- return [...messages];
1253
+ if (n) {
1254
+ const r = JSON.parse(n).messages.map(ge);
1255
+ return L.set(s, r), [...r];
1556
1256
  }
1557
- } catch (error) {
1558
- logger(
1257
+ } catch (n) {
1258
+ N(
1559
1259
  "Failed to load conversation from sessionStorage for key %s: %O",
1560
- currentStorageKey,
1561
- error
1260
+ s,
1261
+ n
1562
1262
  );
1563
1263
  }
1564
1264
  return [];
1565
1265
  }
1566
- async function clearConversation(sessionId, conversationStorageKey) {
1567
- const currentStorageKey = conversationStorageKey || sessionId;
1568
- conversationCache.delete(currentStorageKey);
1569
- if (typeof sessionStorage === "undefined") {
1570
- return;
1571
- }
1572
- try {
1573
- sessionStorage.removeItem(`${STORAGE_KEY}_${currentStorageKey}`);
1574
- } catch (error) {
1575
- logger(
1576
- "Failed to clear conversation from sessionStorage for key %s: %O",
1577
- currentStorageKey,
1578
- error
1579
- );
1580
- }
1581
- }
1582
-
1583
- // src/react/conversationUtils.ts
1584
- function extractNewContentFromMessage(message) {
1585
- const newParts = message.parts.filter((part) => {
1586
- if (part.type === "text") {
1587
- return true;
1588
- }
1589
- if (part.type === "data") {
1590
- if ("role" in part.data && "text" in part.data) {
1591
- return false;
1592
- }
1593
- if ("toolCallId" in part.data && "arguments" in part.data) {
1594
- return true;
1595
- }
1596
- if ("toolCallId" in part.data && "result" in part.data) {
1597
- return true;
1598
- }
1599
- return false;
1266
+ async function pe(t, e) {
1267
+ const s = e || t;
1268
+ if (L.delete(s), !(typeof sessionStorage > "u"))
1269
+ try {
1270
+ sessionStorage.removeItem(`${dt}_${s}`);
1271
+ } catch (n) {
1272
+ N(
1273
+ "Failed to clear conversation from sessionStorage for key %s: %O",
1274
+ s,
1275
+ n
1276
+ );
1600
1277
  }
1601
- return true;
1602
- });
1278
+ }
1279
+ function G(t) {
1280
+ const e = t.parts.filter((s) => s.type === "text" ? !0 : s.type === "data" ? "role" in s.data && "text" in s.data ? !1 : "toolCallId" in s.data && "arguments" in s.data || "toolCallId" in s.data && "result" in s.data : !0);
1603
1281
  return {
1604
- ...message,
1605
- parts: newParts,
1282
+ ...t,
1283
+ parts: e,
1606
1284
  // Preserve metadata if it exists, otherwise add timestamp
1607
- metadata: message.metadata || {
1285
+ metadata: t.metadata || {
1608
1286
  timestamp: Date.now()
1609
1287
  }
1610
1288
  };
1611
1289
  }
1612
- function conversationMessagesToDataParts(conversationMessages) {
1613
- const historyParts = [];
1614
- for (const message of conversationMessages) {
1615
- for (const part of message.parts) {
1616
- if (part.type === "text") {
1617
- historyParts.push({
1290
+ function ye(t) {
1291
+ const e = [];
1292
+ for (const s of t)
1293
+ for (const n of s.parts)
1294
+ if (n.type === "text")
1295
+ e.push({
1618
1296
  type: "data",
1619
1297
  data: {
1620
- role: message.role,
1621
- text: part.text
1298
+ role: s.role,
1299
+ text: n.text
1622
1300
  }
1623
1301
  });
1624
- } else if (part.type === "data") {
1625
- if ("role" in part.data && "text" in part.data) {
1302
+ else if (n.type === "data") {
1303
+ if ("role" in n.data && "text" in n.data)
1626
1304
  continue;
1627
- }
1628
- if ("toolCallId" in part.data && "arguments" in part.data) {
1629
- historyParts.push(part);
1305
+ if ("toolCallId" in n.data && "arguments" in n.data) {
1306
+ e.push(n);
1630
1307
  continue;
1631
1308
  }
1632
- if ("toolCallId" in part.data && "result" in part.data) {
1633
- historyParts.push(part);
1309
+ if ("toolCallId" in n.data && "result" in n.data) {
1310
+ e.push(n);
1634
1311
  continue;
1635
1312
  }
1636
1313
  }
1637
- }
1638
- }
1639
- return historyParts;
1314
+ return e;
1640
1315
  }
1641
- function createTextMessageWithHistory(text, conversationMessages = []) {
1642
- const historyParts = conversationMessagesToDataParts(conversationMessages);
1316
+ function wt(t, e = []) {
1643
1317
  return {
1644
1318
  role: "user",
1645
1319
  parts: [
1646
- ...historyParts,
1320
+ ...ye(e),
1647
1321
  {
1648
1322
  type: "text",
1649
- text
1323
+ text: t
1650
1324
  }
1651
1325
  ],
1652
1326
  kind: "message",
1653
- messageId: generateMessageId(),
1327
+ messageId: D(),
1654
1328
  metadata: {
1655
1329
  timestamp: Date.now()
1656
1330
  }
1657
1331
  };
1658
1332
  }
1659
- function extractToolResultsFromMessage(message) {
1660
- if (!message?.parts) {
1661
- return [];
1662
- }
1663
- return message.parts.filter(
1664
- (part) => part.type === "data" && "toolCallId" in part.data && "result" in part.data
1665
- );
1666
- }
1667
-
1668
- // src/react/agentManager.ts
1669
- async function resolvePromisesInConversationHistory(conversationHistory) {
1670
- const resolvedHistory = [];
1671
- for (const message of conversationHistory) {
1672
- if (message.parts && Array.isArray(message.parts)) {
1673
- const hasToolResults = message.parts.some(
1674
- (part) => part.type === "data" && "toolCallId" in part.data && "result" in part.data
1675
- );
1676
- if (hasToolResults) {
1677
- const updatedParts = updateToolResultsWithResolvedPromises(
1678
- message.parts
1333
+ function we(t) {
1334
+ return t != null && t.parts ? t.parts.filter(
1335
+ (e) => e.type === "data" && "toolCallId" in e.data && "result" in e.data
1336
+ ) : [];
1337
+ }
1338
+ async function Ie(t) {
1339
+ const e = [];
1340
+ for (const s of t)
1341
+ if (s.parts && Array.isArray(s.parts))
1342
+ if (s.parts.some(
1343
+ (a) => a.type === "data" && "toolCallId" in a.data && "result" in a.data
1344
+ )) {
1345
+ const a = ce(
1346
+ s.parts
1679
1347
  );
1680
- resolvedHistory.push({
1681
- ...message,
1682
- parts: updatedParts
1348
+ e.push({
1349
+ ...s,
1350
+ parts: a
1683
1351
  });
1684
- } else {
1685
- resolvedHistory.push(message);
1686
- }
1687
- } else {
1688
- resolvedHistory.push(message);
1689
- }
1690
- }
1691
- clearToolResultPromises();
1692
- return resolvedHistory;
1693
- }
1694
- function createAgentManager() {
1695
- const agents = /* @__PURE__ */ new Map();
1696
- async function persistConversationHistory(key, messages) {
1697
- const agent = agents.get(key);
1698
- if (agent?.sessionId) {
1352
+ } else
1353
+ e.push(s);
1354
+ else
1355
+ e.push(s);
1356
+ return le(), e;
1357
+ }
1358
+ function Ce() {
1359
+ const t = /* @__PURE__ */ new Map();
1360
+ async function e(s, n) {
1361
+ const a = t.get(s);
1362
+ if (a != null && a.sessionId)
1699
1363
  try {
1700
- await storeConversation(
1701
- agent.sessionId,
1702
- messages,
1703
- agent.conversationStorageKey
1364
+ await me(
1365
+ a.sessionId,
1366
+ n,
1367
+ a.conversationStorageKey
1704
1368
  );
1705
- } catch (error) {
1706
- log(
1707
- `Failed to persist conversation history for agent ${key}:`,
1708
- error
1369
+ } catch (r) {
1370
+ ht(
1371
+ `Failed to persist conversation history for agent ${s}:`,
1372
+ r
1709
1373
  );
1710
1374
  }
1711
- }
1712
1375
  }
1713
1376
  return {
1714
- async createAgent(key, config) {
1715
- if (agents.has(key)) {
1716
- return agents.get(key).client;
1717
- }
1718
- const client = createClient(config);
1719
- const sessionId = config.sessionId || null;
1720
- const conversationStorageKey = config.conversationStorageKey;
1721
- let conversationHistory = [];
1722
- if (sessionId) {
1377
+ async createAgent(s, n) {
1378
+ if (t.has(s))
1379
+ return t.get(s).client;
1380
+ const a = ue(n), r = n.sessionId || null, o = n.conversationStorageKey;
1381
+ let i = [];
1382
+ if (r)
1723
1383
  try {
1724
- conversationHistory = await loadConversation(
1725
- sessionId,
1726
- conversationStorageKey
1384
+ i = await he(
1385
+ r,
1386
+ o
1727
1387
  );
1728
- } catch (error) {
1729
- log(
1730
- `Failed to load conversation history for agent ${key} with session ${sessionId}:`,
1731
- error
1388
+ } catch (c) {
1389
+ ht(
1390
+ `Failed to load conversation history for agent ${s} with session ${r}:`,
1391
+ c
1732
1392
  );
1733
1393
  }
1734
- }
1735
- const managedAgent = {
1736
- client,
1737
- sessionId,
1738
- conversationStorageKey,
1739
- conversationHistory
1394
+ const l = {
1395
+ client: a,
1396
+ sessionId: r,
1397
+ conversationStorageKey: o,
1398
+ conversationHistory: i
1740
1399
  };
1741
- agents.set(key, managedAgent);
1742
- return client;
1400
+ return t.set(s, l), a;
1743
1401
  },
1744
- getAgent(key) {
1745
- const agent = agents.get(key);
1746
- return agent?.client || null;
1402
+ getAgent(s) {
1403
+ const n = t.get(s);
1404
+ return (n == null ? void 0 : n.client) || null;
1747
1405
  },
1748
- hasAgent(key) {
1749
- return agents.has(key);
1406
+ hasAgent(s) {
1407
+ return t.has(s);
1750
1408
  },
1751
- removeAgent(key) {
1752
- return agents.delete(key);
1409
+ removeAgent(s) {
1410
+ return t.delete(s);
1753
1411
  },
1754
- async sendMessage(key, message, options = {}) {
1755
- const managedAgent = agents.get(key);
1756
- if (!managedAgent) {
1757
- throw new Error(`Agent with key "${key}" not found`);
1758
- }
1759
- const { withHistory = true, ...otherOptions } = options;
1760
- const { client, conversationHistory } = managedAgent;
1761
- const messageObj = options.message || createTextMessageWithHistory(message, conversationHistory);
1762
- const task = await client.sendMessage({
1763
- message: messageObj,
1764
- withHistory,
1765
- ...otherOptions
1412
+ async sendMessage(s, n, a = {}) {
1413
+ var M;
1414
+ const r = t.get(s);
1415
+ if (!r)
1416
+ throw new Error(`Agent with key "${s}" not found`);
1417
+ const { withHistory: o = !0, ...i } = a, { client: l, conversationHistory: c } = r, g = a.message || wt(n, c), y = await l.sendMessage({
1418
+ message: g,
1419
+ withHistory: o,
1420
+ ...i
1766
1421
  });
1767
- let completeAgentMessage = null;
1768
- if (task.status?.message) {
1769
- const toolParts = task.status.message.parts.filter(
1770
- (part) => part.type === "data" && "toolCallId" in part.data && ("arguments" in part.data || "result" in part.data)
1422
+ let b = null;
1423
+ if ((M = y.status) != null && M.message) {
1424
+ const x = y.status.message.parts.filter(
1425
+ (u) => u.type === "data" && "toolCallId" in u.data && ("arguments" in u.data || "result" in u.data)
1426
+ ), p = y.status.message.parts.filter(
1427
+ (u) => u.type === "text"
1771
1428
  );
1772
- const textParts = task.status.message.parts.filter(
1773
- (part) => part.type === "text"
1774
- );
1775
- completeAgentMessage = {
1429
+ b = {
1776
1430
  role: "agent",
1777
1431
  kind: "message",
1778
- parts: [...toolParts, ...textParts],
1779
- messageId: generateMessageId(),
1432
+ parts: [...x, ...p],
1433
+ messageId: D(),
1780
1434
  metadata: {
1781
1435
  timestamp: Date.now()
1782
1436
  }
1783
1437
  };
1784
1438
  }
1785
- const newConversationHistory = [
1786
- ...conversationHistory,
1439
+ const A = [
1440
+ ...c,
1787
1441
  // Store only the new content from the user message (without history parts)
1788
- createTextMessage(message),
1442
+ rt(n),
1789
1443
  // Add complete agent response with tool calls/results if present
1790
- ...completeAgentMessage ? [extractNewContentFromMessage(completeAgentMessage)] : []
1444
+ ...b ? [G(b)] : []
1791
1445
  ];
1792
- let finalConversationHistory = newConversationHistory;
1793
- if (task.agentMessage) {
1794
- const separateAgentMessage = extractNewContentFromMessage(
1795
- task.agentMessage
1446
+ let S = A;
1447
+ if (y.agentMessage) {
1448
+ const x = G(
1449
+ y.agentMessage
1796
1450
  );
1797
- finalConversationHistory = [
1798
- ...newConversationHistory,
1799
- separateAgentMessage
1451
+ S = [
1452
+ ...A,
1453
+ x
1800
1454
  ];
1801
1455
  }
1802
- managedAgent.conversationHistory = finalConversationHistory;
1803
- if (withHistory) {
1804
- await persistConversationHistory(
1805
- key,
1806
- finalConversationHistory
1807
- );
1808
- }
1809
- return task;
1456
+ return r.conversationHistory = S, o && await e(
1457
+ s,
1458
+ S
1459
+ ), y;
1810
1460
  },
1811
- async *sendMessageStream(key, message, options = {}) {
1812
- const managedAgent = agents.get(key);
1813
- if (!managedAgent) {
1814
- throw new Error(`Agent with key "${key}" not found`);
1815
- }
1816
- const { withHistory = true, ...otherOptions } = options;
1817
- const { client } = managedAgent;
1818
- let currentConversationHistory = [
1819
- ...managedAgent.conversationHistory
1820
- ];
1821
- let currentToolCallIds = [];
1822
- const resolvedConversationHistory = await resolvePromisesInConversationHistory(
1823
- currentConversationHistory
1461
+ async *sendMessageStream(s, n, a = {}) {
1462
+ var S, M, x, p, u, h;
1463
+ const r = t.get(s);
1464
+ if (!r)
1465
+ throw new Error(`Agent with key "${s}" not found`);
1466
+ const { withHistory: o = !0, ...i } = a, { client: l } = r;
1467
+ let c = [
1468
+ ...r.conversationHistory
1469
+ ], g = [];
1470
+ const y = await Ie(
1471
+ c
1824
1472
  );
1825
- managedAgent.conversationHistory = resolvedConversationHistory;
1826
- currentConversationHistory = resolvedConversationHistory;
1827
- if (withHistory) {
1828
- await persistConversationHistory(
1829
- key,
1830
- resolvedConversationHistory
1831
- );
1832
- }
1833
- const messageObj = options.message || createTextMessageWithHistory(
1834
- message,
1835
- resolvedConversationHistory
1473
+ r.conversationHistory = y, c = y, o && await e(
1474
+ s,
1475
+ y
1836
1476
  );
1837
- const userMessage = createTextMessage(message);
1838
- currentConversationHistory = [
1839
- ...currentConversationHistory,
1840
- userMessage
1841
- ];
1842
- managedAgent.conversationHistory = currentConversationHistory;
1843
- if (withHistory) {
1844
- await persistConversationHistory(
1845
- key,
1846
- currentConversationHistory
1847
- );
1848
- }
1849
- for await (const update of client.sendMessageStream({
1850
- message: messageObj,
1851
- withHistory,
1852
- ...otherOptions
1477
+ const b = a.message || wt(
1478
+ n,
1479
+ y
1480
+ ), A = rt(n);
1481
+ c = [
1482
+ ...c,
1483
+ A
1484
+ ], r.conversationHistory = c, o && await e(
1485
+ s,
1486
+ c
1487
+ );
1488
+ for await (const d of l.sendMessageStream({
1489
+ message: b,
1490
+ withHistory: o,
1491
+ ...i
1853
1492
  })) {
1854
- if (update.status?.state === "input-required" && update.status?.message) {
1855
- const toolCalls = extractToolCallsFromMessage(
1856
- update.status.message
1493
+ if (((S = d.status) == null ? void 0 : S.state) === "input-required" && ((M = d.status) != null && M.message)) {
1494
+ g = J(
1495
+ d.status.message
1496
+ ).map(
1497
+ (I) => I.data.toolCallId
1857
1498
  );
1858
- currentToolCallIds = toolCalls.map(
1859
- (call) => call.data.toolCallId
1499
+ const T = G(
1500
+ d.status.message
1860
1501
  );
1861
- const toolMessage = extractNewContentFromMessage(
1862
- update.status.message
1502
+ c = [
1503
+ ...c,
1504
+ T
1505
+ ], r.conversationHistory = c, o && await e(
1506
+ s,
1507
+ c
1863
1508
  );
1864
- currentConversationHistory = [
1865
- ...currentConversationHistory,
1866
- toolMessage
1867
- ];
1868
- managedAgent.conversationHistory = currentConversationHistory;
1869
- if (withHistory) {
1870
- await persistConversationHistory(
1871
- key,
1872
- currentConversationHistory
1873
- );
1874
- }
1875
1509
  }
1876
- if (update.status?.state === "working" && update.status?.message && !update.final) {
1877
- const allToolResults = extractToolResultsFromMessage(
1878
- update.status.message
1879
- );
1880
- const currentToolResults = allToolResults.filter(
1881
- (result) => currentToolCallIds.includes(
1882
- result.data.toolCallId
1510
+ if (((x = d.status) == null ? void 0 : x.state) === "working" && ((p = d.status) != null && p.message) && !d.final) {
1511
+ const T = we(
1512
+ d.status.message
1513
+ ).filter(
1514
+ (I) => g.includes(
1515
+ I.data.toolCallId
1883
1516
  )
1884
1517
  );
1885
- if (currentToolResults.length > 0) {
1886
- const toolResultMessage = {
1518
+ if (T.length > 0) {
1519
+ const I = {
1887
1520
  role: "agent",
1888
1521
  kind: "message",
1889
- parts: currentToolResults,
1890
- messageId: generateMessageId()
1522
+ parts: T,
1523
+ messageId: D()
1891
1524
  };
1892
- currentConversationHistory = [
1893
- ...currentConversationHistory,
1894
- extractNewContentFromMessage(toolResultMessage)
1895
- ];
1896
- managedAgent.conversationHistory = currentConversationHistory;
1897
- if (withHistory) {
1898
- await persistConversationHistory(
1899
- key,
1900
- currentConversationHistory
1901
- );
1902
- }
1903
- }
1904
- }
1905
- if (update.final && update.status?.state !== "input-required") {
1906
- currentToolCallIds = [];
1907
- let finalAgentMessage = null;
1908
- if (update.status?.message) {
1909
- finalAgentMessage = extractNewContentFromMessage(
1910
- update.status.message
1525
+ c = [
1526
+ ...c,
1527
+ G(I)
1528
+ ], r.conversationHistory = c, o && await e(
1529
+ s,
1530
+ c
1911
1531
  );
1912
- currentConversationHistory = [
1913
- ...currentConversationHistory,
1914
- finalAgentMessage
1915
- ];
1916
- managedAgent.conversationHistory = currentConversationHistory;
1917
- if (withHistory) {
1918
- await persistConversationHistory(
1919
- key,
1920
- currentConversationHistory
1921
- );
1922
- }
1923
1532
  }
1924
1533
  }
1925
- yield update;
1534
+ if (d.final && ((u = d.status) == null ? void 0 : u.state) !== "input-required") {
1535
+ g = [];
1536
+ let f = null;
1537
+ (h = d.status) != null && h.message && (f = G(
1538
+ d.status.message
1539
+ ), c = [
1540
+ ...c,
1541
+ f
1542
+ ], r.conversationHistory = c, o && await e(
1543
+ s,
1544
+ c
1545
+ ));
1546
+ }
1547
+ yield d;
1926
1548
  }
1927
1549
  },
1928
- async resetConversation(key) {
1929
- const managedAgent = agents.get(key);
1930
- if (!managedAgent) {
1931
- throw new Error(`Agent with key "${key}" not found`);
1932
- }
1933
- managedAgent.conversationHistory = [];
1934
- if (managedAgent.sessionId) {
1935
- await clearConversation(
1936
- managedAgent.sessionId,
1937
- managedAgent.conversationStorageKey
1938
- );
1939
- }
1550
+ async resetConversation(s) {
1551
+ const n = t.get(s);
1552
+ if (!n)
1553
+ throw new Error(`Agent with key "${s}" not found`);
1554
+ n.conversationHistory = [], n.sessionId && await pe(
1555
+ n.sessionId,
1556
+ n.conversationStorageKey
1557
+ );
1940
1558
  },
1941
- getConversationHistory(key) {
1942
- const managedAgent = agents.get(key);
1943
- if (!managedAgent) {
1944
- throw new Error(`Agent with key "${key}" not found`);
1945
- }
1946
- return [...managedAgent.conversationHistory];
1559
+ getConversationHistory(s) {
1560
+ const n = t.get(s);
1561
+ if (!n)
1562
+ throw new Error(`Agent with key "${s}" not found`);
1563
+ return [...n.conversationHistory];
1947
1564
  },
1948
1565
  clear() {
1949
- agents.clear();
1566
+ t.clear();
1950
1567
  }
1951
1568
  };
1952
1569
  }
1953
- var globalAgentManager = createAgentManager();
1954
- function getAgentManager() {
1955
- return globalAgentManager;
1956
- }
1957
-
1958
- // src/utils/createMessageRenderer.tsx
1959
- import Markdown from "streamdown";
1960
-
1961
- // src/markdown-extensions/index.ts
1962
- import remarkGfm from "remark-gfm";
1963
- function processMarkdownExtensions(extensions) {
1964
- const components = {};
1965
- const remarkPlugins = [];
1966
- if (extensions?.charts?.enabled) {
1967
- components.code = createChartBlock(extensions.charts.config);
1570
+ const xe = Ce();
1571
+ function It() {
1572
+ return xe;
1573
+ }
1574
+ class Me extends Dt {
1575
+ constructor(e) {
1576
+ super(e), this.state = {
1577
+ hasError: !1,
1578
+ error: null,
1579
+ errorInfo: null
1580
+ };
1581
+ }
1582
+ static getDerivedStateFromError(e) {
1583
+ return {
1584
+ hasError: !0,
1585
+ error: e,
1586
+ errorInfo: null
1587
+ };
1588
+ }
1589
+ componentDidCatch(e, s) {
1590
+ if (console.error("Chart rendering error:", e), console.error("Error info:", s), this.props.chartData) {
1591
+ console.error(
1592
+ "Chart data that caused the error:",
1593
+ this.props.chartData
1594
+ );
1595
+ try {
1596
+ const n = JSON.parse(this.props.chartData);
1597
+ console.error("Parsed chart data:", n);
1598
+ } catch {
1599
+ console.error("Could not parse chart data as JSON");
1600
+ }
1601
+ }
1602
+ this.setState({
1603
+ errorInfo: s
1604
+ });
1968
1605
  }
1969
- if (extensions?.gfm?.enabled) {
1970
- remarkPlugins.push(remarkGfm);
1606
+ render() {
1607
+ var e;
1608
+ if (this.state.hasError) {
1609
+ const s = ((e = this.state.error) == null ? void 0 : e.message) || "An error occurred while rendering the chart", n = [
1610
+ "The chart could not be rendered due to an error.",
1611
+ "The error has been logged to the console."
1612
+ ];
1613
+ return /* @__PURE__ */ $.jsx(
1614
+ tt,
1615
+ {
1616
+ message: s,
1617
+ details: n.join(`
1618
+ `)
1619
+ }
1620
+ );
1621
+ }
1622
+ return this.props.children;
1971
1623
  }
1972
- return { components, remarkPlugins };
1973
1624
  }
1974
- function mergeMarkdownComponents(extensionComponents, userComponents = {}) {
1975
- return {
1976
- ...extensionComponents,
1977
- ...userComponents
1625
+ const Te = (t) => {
1626
+ const {
1627
+ data: e,
1628
+ currency: s,
1629
+ showLegend: n = !0,
1630
+ withTooltips: a = !0,
1631
+ renderTooltip: r,
1632
+ margin: o,
1633
+ withGradientFill: i = !0,
1634
+ error: l,
1635
+ ...c
1636
+ } = t, g = {
1637
+ ..._t(),
1638
+ bottom: 80
1639
+ }, y = {
1640
+ data: e,
1641
+ withTooltips: a,
1642
+ renderTooltip: r,
1643
+ showLegend: n,
1644
+ withGradientFill: i,
1645
+ withLegendGlyph: !1,
1646
+ legendOrientation: "horizontal",
1647
+ legendAlignmentHorizontal: "center",
1648
+ legendAlignmentVertical: "bottom",
1649
+ margin: g,
1650
+ options: {
1651
+ xScale: {
1652
+ type: "time"
1653
+ },
1654
+ axis: {
1655
+ x: {
1656
+ ...jt(e)
1657
+ }
1658
+ }
1659
+ },
1660
+ ...s && { currency: s },
1661
+ ...c
1978
1662
  };
1979
- }
1980
-
1981
- // src/utils/createMessageRenderer.tsx
1982
- import { jsx } from "react/jsx-runtime";
1983
- function createMessageRenderer(options = {}) {
1984
- const { components = {}, extensions = {}, remarkPlugins = [] } = options;
1985
- const processed = processMarkdownExtensions(extensions);
1986
- const finalComponents = mergeMarkdownComponents(
1987
- processed.components,
1988
- components
1663
+ return /* @__PURE__ */ $.jsx(Ft, { error: l, children: /* @__PURE__ */ $.jsx(Bt, { ...y }) });
1664
+ }, be = ({
1665
+ data: t,
1666
+ className: e = "",
1667
+ config: s
1668
+ }) => {
1669
+ const [n, a] = X(null), [r, o] = X(
1670
+ null
1671
+ ), [i, l] = X(300), c = xt(null), g = j(
1672
+ (p) => {
1673
+ var P;
1674
+ const { tooltipData: u } = p, h = (P = u == null ? void 0 : u.nearestDatum) == null ? void 0 : P.datum;
1675
+ if (!h)
1676
+ return null;
1677
+ const d = (w) => {
1678
+ if (r != null && r.currency) {
1679
+ const { symbol: m, symbolPosition: k } = r.currency;
1680
+ let C;
1681
+ return w >= 1e6 ? C = `${(w / 1e6).toFixed(
1682
+ 1
1683
+ )}M` : w >= 1e3 ? C = `${(w / 1e3).toFixed(1)}K` : C = w.toLocaleString(), k === "right" ? `${C}${m}` : `${m}${C}`;
1684
+ }
1685
+ return w >= 1e6 ? `${(w / 1e6).toFixed(1)}M` : w >= 1e3 ? `${(w / 1e3).toFixed(1)}K` : w.toLocaleString();
1686
+ }, f = (w) => {
1687
+ const k = Math.floor(
1688
+ ((/* @__PURE__ */ new Date()).getTime() - w.getTime()) / (1e3 * 60 * 60 * 24)
1689
+ );
1690
+ return k === 0 ? H("Today", "a8c-agenttic") : k === 1 ? H("Yesterday", "a8c-agenttic") : k < 7 ? ft(
1691
+ /* translators: %d: number of days */
1692
+ H("%d days ago", "a8c-agenttic"),
1693
+ k
1694
+ ) : w.toLocaleDateString("en-US", {
1695
+ year: "numeric",
1696
+ month: "short",
1697
+ day: "numeric"
1698
+ });
1699
+ }, T = h.label, I = Object.entries(
1700
+ (u == null ? void 0 : u.datumByKey) || {}
1701
+ ).map(([w, m]) => {
1702
+ const k = m.datum;
1703
+ return {
1704
+ key: w,
1705
+ value: k.value
1706
+ };
1707
+ }).sort((w, m) => m.value - w.value);
1708
+ return /* @__PURE__ */ $.jsxs("div", { children: [
1709
+ T && /* @__PURE__ */ $.jsx(
1710
+ "div",
1711
+ {
1712
+ style: {
1713
+ fontSize: "12px",
1714
+ fontWeight: "bold",
1715
+ marginBottom: "4px",
1716
+ color: "#1e1e1e",
1717
+ borderBottom: "1px solid #eee",
1718
+ paddingBottom: "2px"
1719
+ },
1720
+ children: T
1721
+ }
1722
+ ),
1723
+ h.date && /* @__PURE__ */ $.jsx(
1724
+ "div",
1725
+ {
1726
+ style: {
1727
+ fontSize: "10px",
1728
+ opacity: 0.8,
1729
+ marginBottom: "4px"
1730
+ },
1731
+ children: f(h.date)
1732
+ }
1733
+ ),
1734
+ I.map((w) => /* @__PURE__ */ $.jsxs(
1735
+ "div",
1736
+ {
1737
+ style: { marginBottom: "2px" },
1738
+ children: [
1739
+ /* @__PURE__ */ $.jsxs("strong", { children: [
1740
+ w.key,
1741
+ ":"
1742
+ ] }),
1743
+ " ",
1744
+ d(w.value)
1745
+ ]
1746
+ },
1747
+ w.key
1748
+ ))
1749
+ ] });
1750
+ },
1751
+ [r == null ? void 0 : r.currency]
1989
1752
  );
1990
- const finalPlugins = [...processed.remarkPlugins, ...remarkPlugins];
1991
- return function MessageRenderer({ children }) {
1992
- return /* @__PURE__ */ jsx(
1993
- Markdown,
1753
+ Y(() => {
1754
+ if (a(null), o(null), !t || typeof t != "string") {
1755
+ a({
1756
+ message: H("Invalid chart data provided", "a8c-agenttic"),
1757
+ details: `Input data: ${t}`
1758
+ });
1759
+ return;
1760
+ }
1761
+ try {
1762
+ const p = JSON.parse(t.trim());
1763
+ if (!p.chartType) {
1764
+ a({
1765
+ message: H(
1766
+ "Chart data must include chartType",
1767
+ "a8c-agenttic"
1768
+ ),
1769
+ details: H("Available types: line, bar", "a8c-agenttic")
1770
+ });
1771
+ return;
1772
+ }
1773
+ if (!p.data || !Array.isArray(p.data)) {
1774
+ a({
1775
+ message: H(
1776
+ "Chart data must include a data array",
1777
+ "a8c-agenttic"
1778
+ ),
1779
+ details: `Input data: ${t}`
1780
+ });
1781
+ return;
1782
+ }
1783
+ if (p.data.length === 0) {
1784
+ a({
1785
+ message: H(
1786
+ "No data points found for chart",
1787
+ "a8c-agenttic"
1788
+ ),
1789
+ details: `Input data: ${t}`
1790
+ });
1791
+ return;
1792
+ }
1793
+ const u = p.data.map((d) => ({
1794
+ ...d,
1795
+ data: d.data.map((f) => {
1796
+ if (f.date) {
1797
+ const T = new Date(f.date);
1798
+ return isNaN(T.getTime()) ? (console.warn(
1799
+ `Invalid date string: "${f.date}" in series "${d.label}"`
1800
+ ), {
1801
+ label: f.label,
1802
+ value: f.value,
1803
+ date: void 0
1804
+ }) : {
1805
+ label: f.label,
1806
+ value: f.value,
1807
+ date: T
1808
+ };
1809
+ }
1810
+ return {
1811
+ label: f.label,
1812
+ value: f.value,
1813
+ date: void 0
1814
+ };
1815
+ })
1816
+ })), h = {
1817
+ chartType: p.chartType,
1818
+ title: p.title,
1819
+ data: u,
1820
+ currency: p.currency,
1821
+ mode: p.mode || "time-comparison"
1822
+ };
1823
+ o(h);
1824
+ } catch {
1825
+ a({
1826
+ message: H(
1827
+ "Failed to parse chart data as JSON",
1828
+ "a8c-agenttic"
1829
+ ),
1830
+ details: `Input data: ${t}`
1831
+ });
1832
+ }
1833
+ }, [t]);
1834
+ const y = j((p) => {
1835
+ if (c.current && c.current.disconnect(), p) {
1836
+ const { width: u } = p.getBoundingClientRect(), h = Math.max(280, u - 4);
1837
+ l(h), c.current = new ResizeObserver((d) => {
1838
+ for (const f of d) {
1839
+ const T = f.contentRect.width, I = Math.max(
1840
+ 280,
1841
+ T - 4
1842
+ );
1843
+ l(I);
1844
+ }
1845
+ }), c.current.observe(p);
1846
+ }
1847
+ }, []);
1848
+ if (Y(() => () => {
1849
+ c.current && (c.current.disconnect(), c.current = null);
1850
+ }, []), n)
1851
+ return /* @__PURE__ */ $.jsx(tt, { message: n.message, details: n.details });
1852
+ if (!r)
1853
+ return /* @__PURE__ */ $.jsx(
1854
+ tt,
1994
1855
  {
1995
- components: finalComponents,
1996
- remarkPlugins: finalPlugins,
1997
- children
1856
+ message: H("No chart data available", "a8c-agenttic")
1998
1857
  }
1999
1858
  );
1859
+ const A = r.data.length > 1, S = i, M = {
1860
+ data: r.data,
1861
+ currency: r.currency,
1862
+ showLegend: A,
1863
+ withTooltips: !0,
1864
+ renderTooltip: g,
1865
+ error: null,
1866
+ maxWidth: S,
1867
+ aspectRatio: 1.2,
1868
+ resizeDebounceTime: 300
1869
+ }, x = () => {
1870
+ switch (r.chartType) {
1871
+ case "line":
1872
+ return /* @__PURE__ */ $.jsx(Te, { ...M });
1873
+ case "bar":
1874
+ return /* @__PURE__ */ $.jsx(
1875
+ Ht,
1876
+ {
1877
+ ...M,
1878
+ mode: r.mode
1879
+ }
1880
+ );
1881
+ default:
1882
+ return /* @__PURE__ */ $.jsx(
1883
+ tt,
1884
+ {
1885
+ message: ft(
1886
+ /* translators: %s: chart type name */
1887
+ H("Unsupported chart type: %s", "a8c-agenttic"),
1888
+ r.chartType
1889
+ )
1890
+ }
1891
+ );
1892
+ }
2000
1893
  };
1894
+ return /* @__PURE__ */ $.jsx(Me, { chartData: t, children: /* @__PURE__ */ $.jsxs(
1895
+ "div",
1896
+ {
1897
+ ref: y,
1898
+ className: `chart-block ${e}`,
1899
+ children: [
1900
+ r.title && /* @__PURE__ */ $.jsx("h3", { className: "chart-block-title", children: r.title }),
1901
+ /* @__PURE__ */ $.jsx("div", { className: "chart-container", children: x() })
1902
+ ]
1903
+ }
1904
+ ) });
1905
+ };
1906
+ function Se(t) {
1907
+ return function(s) {
1908
+ const { children: n, className: a, ...r } = s;
1909
+ if (!(a == null ? void 0 : a.includes("language-chart")))
1910
+ return gt.createElement(
1911
+ "code",
1912
+ { className: a, ...r },
1913
+ n
1914
+ );
1915
+ const i = typeof n == "string" ? n : "";
1916
+ return gt.createElement(be, {
1917
+ data: i,
1918
+ className: "markdown-chart",
1919
+ config: t
1920
+ });
1921
+ };
1922
+ }
1923
+ function ke(t) {
1924
+ var n, a;
1925
+ const e = {}, s = [];
1926
+ return (n = t == null ? void 0 : t.charts) != null && n.enabled && (e.code = Se(t.charts.config)), (a = t == null ? void 0 : t.gfm) != null && a.enabled && s.push(Ut), { components: e, remarkPlugins: s };
2001
1927
  }
2002
-
2003
- // src/message-actions/useMessageActions.ts
2004
- import { useCallback as useCallback2, useState } from "react";
2005
-
2006
- // src/message-actions/factories.tsx
2007
- var createFeedbackActions = (config) => {
2008
- const baseCondition = config.condition || (() => true);
2009
- const feedbackByMessageId = {};
2010
- const changeListeners = [];
2011
- const notifyListeners = () => {
2012
- changeListeners.forEach((listener) => listener());
1928
+ function Ae(t, e = {}) {
1929
+ return {
1930
+ ...t,
1931
+ ...e
2013
1932
  };
2014
- const handleFeedback = async (messageId, feedback) => {
2015
- feedbackByMessageId[messageId] = feedback;
2016
- await config.onFeedback(messageId, feedback);
2017
- notifyListeners();
1933
+ }
1934
+ function ve(t = {}) {
1935
+ const { components: e = {}, extensions: s = {}, remarkPlugins: n = [] } = t, a = ke(s), r = Ae(
1936
+ a.components,
1937
+ e
1938
+ ), o = [...a.remarkPlugins, ...n];
1939
+ return function({ children: l }) {
1940
+ return /* @__PURE__ */ $.jsx(
1941
+ qt,
1942
+ {
1943
+ components: r,
1944
+ remarkPlugins: o,
1945
+ children: l
1946
+ }
1947
+ );
1948
+ };
1949
+ }
1950
+ const Re = (t) => {
1951
+ const e = t.condition || (() => !0), s = {}, n = [], a = () => {
1952
+ n.forEach((o) => o());
1953
+ }, r = async (o, i) => {
1954
+ s[o] = i, await t.onFeedback(o, i), a();
2018
1955
  };
2019
1956
  return {
2020
- getActionsForMessage: (message) => {
2021
- if (!baseCondition(message)) {
1957
+ getActionsForMessage: (o) => {
1958
+ if (!e(o))
2022
1959
  return [];
2023
- }
2024
- const feedbackState = feedbackByMessageId[message.id];
2025
- const actions = [];
2026
- actions.push({
1960
+ const i = s[o.id], l = [];
1961
+ return l.push({
2027
1962
  id: "feedback-up",
2028
- icon: config.icons.up,
1963
+ icon: t.icons.up,
2029
1964
  label: "Good response",
2030
1965
  onClick: async () => {
2031
- if (feedbackState === "up") {
2032
- delete feedbackByMessageId[message.id];
2033
- } else {
2034
- await handleFeedback(message.id, "up");
2035
- }
2036
- notifyListeners();
1966
+ i === "up" ? delete s[o.id] : await r(o.id, "up"), a();
2037
1967
  },
2038
1968
  tooltip: "This response was helpful",
2039
- pressed: feedbackState === "up",
2040
- disabled: feedbackState === "down"
1969
+ pressed: i === "up",
1970
+ disabled: i === "down"
2041
1971
  // Disable if other is selected
2042
- });
2043
- actions.push({
1972
+ }), l.push({
2044
1973
  id: "feedback-down",
2045
- icon: config.icons.down,
1974
+ icon: t.icons.down,
2046
1975
  label: "Bad response",
2047
1976
  onClick: async () => {
2048
- if (feedbackState === "down") {
2049
- delete feedbackByMessageId[message.id];
2050
- } else {
2051
- await handleFeedback(message.id, "down");
2052
- }
2053
- notifyListeners();
1977
+ i === "down" ? delete s[o.id] : await r(o.id, "down"), a();
2054
1978
  },
2055
1979
  tooltip: "This response was not helpful",
2056
- pressed: feedbackState === "down",
2057
- disabled: feedbackState === "up"
1980
+ pressed: i === "down",
1981
+ disabled: i === "up"
2058
1982
  // Disable if other is selected
2059
- });
2060
- return actions;
1983
+ }), l;
2061
1984
  },
2062
- clearFeedback: (messageId) => {
2063
- delete feedbackByMessageId[messageId];
2064
- notifyListeners();
1985
+ clearFeedback: (o) => {
1986
+ delete s[o], a();
2065
1987
  },
2066
1988
  clearAllFeedback: () => {
2067
- Object.keys(feedbackByMessageId).forEach((key) => {
2068
- delete feedbackByMessageId[key];
2069
- });
2070
- notifyListeners();
1989
+ Object.keys(s).forEach((o) => {
1990
+ delete s[o];
1991
+ }), a();
2071
1992
  },
2072
- onChange: (listener) => {
2073
- changeListeners.push(listener);
1993
+ onChange: (o) => {
1994
+ n.push(o);
2074
1995
  },
2075
- offChange: (listener) => {
2076
- const index = changeListeners.indexOf(listener);
2077
- if (index > -1) {
2078
- changeListeners.splice(index, 1);
2079
- }
1996
+ offChange: (o) => {
1997
+ const i = n.indexOf(o);
1998
+ i > -1 && n.splice(i, 1);
2080
1999
  }
2081
2000
  };
2082
2001
  };
2083
-
2084
- // src/message-actions/useMessageActions.ts
2085
- function useMessageActions() {
2086
- const [registrations, setRegistrations] = useState([]);
2087
- const registerMessageActions = useCallback2(
2088
- (registration) => {
2089
- setRegistrations((prev) => {
2090
- const existingIndex = prev.findIndex(
2091
- (r) => r.id === registration.id
2002
+ function Ee() {
2003
+ const [t, e] = X([]), s = j(
2004
+ (r) => {
2005
+ e((o) => {
2006
+ const i = o.findIndex(
2007
+ (l) => l.id === r.id
2092
2008
  );
2093
- if (existingIndex >= 0) {
2094
- const updated = [...prev];
2095
- updated[existingIndex] = registration;
2096
- return updated;
2009
+ if (i >= 0) {
2010
+ const l = [...o];
2011
+ return l[i] = r, l;
2097
2012
  }
2098
- return [...prev, registration];
2013
+ return [...o, r];
2099
2014
  });
2100
2015
  },
2101
2016
  []
2102
- );
2103
- const unregisterMessageActions = useCallback2((id) => {
2104
- setRegistrations((prev) => prev.filter((r) => r.id !== id));
2105
- }, []);
2106
- const clearAllMessageActions = useCallback2(() => {
2107
- setRegistrations([]);
2017
+ ), n = j((r) => {
2018
+ e((o) => o.filter((i) => i.id !== r));
2019
+ }, []), a = j(() => {
2020
+ e([]);
2108
2021
  }, []);
2109
2022
  return {
2110
- registerMessageActions,
2111
- unregisterMessageActions,
2112
- clearAllMessageActions,
2113
- createFeedbackActions,
2114
- registrations
2023
+ registerMessageActions: s,
2024
+ unregisterMessageActions: n,
2025
+ clearAllMessageActions: a,
2026
+ createFeedbackActions: Re,
2027
+ registrations: t
2115
2028
  };
2116
2029
  }
2117
-
2118
- // src/message-actions/resolver.ts
2119
- function resolveActionsForMessage(message, registrations) {
2120
- const allActions = registrations.flatMap((reg) => {
2121
- if (typeof reg.actions === "function") {
2122
- return reg.actions(message);
2123
- }
2124
- return reg.actions;
2125
- });
2126
- const filteredActions = allActions.filter((action) => {
2127
- if (action.condition && !action.condition(message)) {
2128
- return false;
2129
- }
2130
- return true;
2131
- }).map((action) => ({
2132
- id: action.id,
2133
- label: action.label,
2134
- icon: action.icon,
2135
- onClick: action.onClick,
2136
- tooltip: action.tooltip,
2137
- disabled: action.disabled || false,
2138
- pressed: action.pressed,
2139
- showLabel: action.showLabel
2030
+ function Pe(t, e) {
2031
+ return e.flatMap((a) => typeof a.actions == "function" ? a.actions(t) : a.actions).filter((a) => !(a.condition && !a.condition(t))).map((a) => ({
2032
+ id: a.id,
2033
+ label: a.label,
2034
+ icon: a.icon,
2035
+ onClick: a.onClick,
2036
+ tooltip: a.tooltip,
2037
+ disabled: a.disabled || !1,
2038
+ pressed: a.pressed,
2039
+ showLabel: a.showLabel
2140
2040
  }));
2141
- return filteredActions;
2142
2041
  }
2143
-
2144
- // src/react/useAgentChat.ts
2145
- var sortUIMessagesByTime = (messages) => {
2146
- return [...messages].sort((a, b) => a.timestamp - b.timestamp);
2147
- };
2148
- var transformClientMessageToUI = (clientMessage, messageActionsRegistrations = []) => {
2149
- const hasToolContent = clientMessage.parts.some((part) => {
2150
- if (part.type === "data") {
2151
- const data = part.data;
2152
- return data.toolCallId || data.toolId || data.result;
2042
+ const Q = (t) => [...t].sort((e, s) => e.timestamp - s.timestamp), V = (t, e = []) => {
2043
+ var o;
2044
+ if (t.parts.some((i) => {
2045
+ if (i.type === "data") {
2046
+ const l = i.data;
2047
+ return l.toolCallId || l.toolId || l.result;
2153
2048
  }
2154
- return false;
2155
- });
2156
- if (hasToolContent) {
2049
+ return !1;
2050
+ }))
2157
2051
  return null;
2158
- }
2159
- const content = clientMessage.parts.map((part) => {
2160
- if (part.type === "text") {
2052
+ const n = t.parts.map((i) => {
2053
+ if (i.type === "text")
2161
2054
  return {
2162
2055
  type: "text",
2163
- text: part.text
2056
+ text: i.text
2164
2057
  };
2165
- }
2166
- if (part.type === "file") {
2058
+ if (i.type === "file")
2167
2059
  return {
2168
2060
  type: "image_url",
2169
- image_url: part.file.uri || `data:${part.file.mimeType};base64,${part.file.bytes}`
2061
+ image_url: i.file.uri || `data:${i.file.mimeType};base64,${i.file.bytes}`
2170
2062
  };
2171
- }
2172
- if (part.type === "data") {
2173
- const data = part.data;
2174
- if (data.component && data.componentProps) {
2175
- return {
2176
- type: "component",
2177
- component: data.component,
2178
- componentProps: data.componentProps
2179
- };
2180
- }
2181
- return {
2063
+ if (i.type === "data") {
2064
+ const l = i.data;
2065
+ return l.component && l.componentProps ? {
2066
+ type: "component",
2067
+ component: l.component,
2068
+ componentProps: l.componentProps
2069
+ } : {
2182
2070
  type: "text",
2183
- text: JSON.stringify(data)
2071
+ text: JSON.stringify(l)
2184
2072
  };
2185
2073
  }
2186
2074
  return {
2187
2075
  type: "text",
2188
2076
  text: "[Unsupported content]"
2189
2077
  };
2190
- });
2191
- const timestamp = clientMessage.metadata?.timestamp ?? Date.now();
2192
- const uiMessage = {
2193
- id: clientMessage.messageId,
2194
- role: clientMessage.role === "agent" ? "agent" : "user",
2195
- content,
2196
- timestamp,
2197
- archived: false,
2198
- showIcon: clientMessage.role === "agent",
2199
- icon: clientMessage.role === "agent" ? "assistant" : void 0
2078
+ }), a = ((o = t.metadata) == null ? void 0 : o.timestamp) ?? Date.now(), r = {
2079
+ id: t.messageId,
2080
+ role: t.role === "agent" ? "agent" : "user",
2081
+ content: n,
2082
+ timestamp: a,
2083
+ archived: !1,
2084
+ showIcon: t.role === "agent",
2085
+ icon: t.role === "agent" ? "assistant" : void 0
2200
2086
  };
2201
- if (clientMessage.role === "agent" && messageActionsRegistrations.length > 0) {
2202
- const resolvedActions = resolveActionsForMessage(
2203
- uiMessage,
2204
- messageActionsRegistrations
2087
+ if (t.role === "agent" && e.length > 0) {
2088
+ const i = Pe(
2089
+ r,
2090
+ e
2205
2091
  );
2206
- if (resolvedActions.length > 0) {
2207
- uiMessage.actions = resolvedActions;
2208
- }
2092
+ i.length > 0 && (r.actions = i);
2209
2093
  }
2210
- return uiMessage;
2211
- };
2212
- var createNoOpContextProvider = () => ({
2094
+ return r;
2095
+ }, Oe = () => ({
2213
2096
  getClientContext: () => ({})
2214
- });
2215
- var createNoOpToolProvider = () => ({
2097
+ }), Ne = () => ({
2216
2098
  getAvailableTools: async () => [],
2217
2099
  executeTool: async () => ({
2218
- success: true,
2100
+ success: !0,
2219
2101
  result: "No tools available"
2220
2102
  })
2103
+ }), $e = (t) => ["agentId", "agentUrl", "sessionId"].every((s) => {
2104
+ const n = t[s];
2105
+ return typeof n == "string" && n.trim().length > 0;
2221
2106
  });
2222
- var validateAgentConfig = (config) => {
2223
- const required = ["agentId", "agentUrl", "sessionId"];
2224
- return required.every((key) => {
2225
- const value = config[key];
2226
- return typeof value === "string" && value.trim().length > 0;
2227
- });
2228
- };
2229
- function useAgentChat(config) {
2230
- const agentConfig = {
2231
- agentId: config.agentId,
2232
- agentUrl: config.agentUrl,
2233
- sessionId: config.sessionId
2234
- };
2235
- const isValidConfig = validateAgentConfig(agentConfig);
2236
- const [state, setState] = useState2({
2107
+ function Qe(t) {
2108
+ const e = {
2109
+ agentId: t.agentId,
2110
+ agentUrl: t.agentUrl,
2111
+ sessionId: t.sessionId
2112
+ }, s = $e(e), [n, a] = X({
2237
2113
  clientMessages: [],
2238
2114
  uiMessages: [],
2239
- isProcessing: false,
2240
- error: isValidConfig ? null : "Invalid agent configuration",
2115
+ isProcessing: !1,
2116
+ error: s ? null : "Invalid agent configuration",
2241
2117
  suggestions: [],
2242
2118
  markdownComponents: {},
2243
2119
  markdownExtensions: {},
2244
2120
  currentAbortController: null
2245
- });
2246
- const {
2247
- registerMessageActions,
2248
- unregisterMessageActions,
2249
- clearAllMessageActions,
2250
- createFeedbackActions: createFeedbackActions2,
2251
- registrations
2252
- } = useMessageActions();
2253
- const registrationsRef = useRef(registrations);
2254
- useEffect(() => {
2255
- registrationsRef.current = registrations;
2256
- }, [registrations]);
2257
- useEffect(() => {
2258
- if (!isValidConfig) {
2121
+ }), {
2122
+ registerMessageActions: r,
2123
+ unregisterMessageActions: o,
2124
+ clearAllMessageActions: i,
2125
+ createFeedbackActions: l,
2126
+ registrations: c
2127
+ } = Ee(), g = xt(c);
2128
+ Y(() => {
2129
+ g.current = c;
2130
+ }, [c]), Y(() => {
2131
+ if (!s)
2259
2132
  return;
2260
- }
2261
- const initializeAgent = async () => {
2262
- if (agentConfig.sessionId) {
2263
- const agentManager = getAgentManager();
2264
- const agentKey = `${agentConfig.agentId}-${agentConfig.sessionId}`;
2265
- if (!agentManager.hasAgent(agentKey)) {
2266
- await agentManager.createAgent(agentKey, {
2267
- agentId: agentConfig.agentId,
2268
- agentUrl: agentConfig.agentUrl,
2269
- sessionId: agentConfig.sessionId,
2270
- contextProvider: config.contextProvider || createNoOpContextProvider(),
2271
- toolProvider: config.toolProvider || createNoOpToolProvider(),
2272
- authProvider: config.authProvider,
2273
- enableStreaming: config.enableStreaming
2133
+ (async () => {
2134
+ if (e.sessionId) {
2135
+ const d = It(), f = `${e.agentId}-${e.sessionId}`;
2136
+ if (!d.hasAgent(f)) {
2137
+ await d.createAgent(f, {
2138
+ agentId: e.agentId,
2139
+ agentUrl: e.agentUrl,
2140
+ sessionId: e.sessionId,
2141
+ contextProvider: t.contextProvider || Oe(),
2142
+ toolProvider: t.toolProvider || Ne(),
2143
+ authProvider: t.authProvider,
2144
+ enableStreaming: t.enableStreaming
2274
2145
  });
2275
- const clientHistory = agentManager.getConversationHistory(agentKey);
2276
- setState((prev) => {
2277
- const uiHistory = clientHistory.map(
2278
- (msg) => transformClientMessageToUI(
2279
- msg,
2280
- registrationsRef.current
2146
+ const T = d.getConversationHistory(f);
2147
+ a((I) => {
2148
+ const P = T.map(
2149
+ (w) => V(
2150
+ w,
2151
+ g.current
2281
2152
  )
2282
2153
  ).filter(
2283
- (msg) => msg !== null
2154
+ (w) => w !== null
2284
2155
  );
2285
2156
  return {
2286
- ...prev,
2287
- clientMessages: clientHistory,
2288
- uiMessages: uiHistory
2157
+ ...I,
2158
+ clientMessages: T,
2159
+ uiMessages: P
2289
2160
  };
2290
2161
  });
2291
2162
  }
2292
2163
  }
2293
- };
2294
- initializeAgent();
2164
+ })();
2295
2165
  }, [
2296
- agentConfig.sessionId,
2297
- agentConfig.agentId,
2298
- agentConfig.agentUrl,
2299
- config.contextProvider,
2300
- config.toolProvider,
2301
- config.authProvider,
2302
- config.enableStreaming,
2303
- isValidConfig
2166
+ e.sessionId,
2167
+ e.agentId,
2168
+ e.agentUrl,
2169
+ t.contextProvider,
2170
+ t.toolProvider,
2171
+ t.authProvider,
2172
+ t.enableStreaming,
2173
+ s
2304
2174
  ]);
2305
- const onSubmit = useCallback3(
2306
- async (message) => {
2307
- if (!isValidConfig) {
2175
+ const y = j(
2176
+ async (h) => {
2177
+ var w;
2178
+ if (!s)
2308
2179
  throw new Error("Invalid agent configuration");
2309
- }
2310
- const agentManager = getAgentManager();
2311
- const agentKey = `${agentConfig.agentId}-${agentConfig.sessionId}`;
2312
- const messageTimestamp = Date.now();
2313
- const userMessage = {
2314
- id: `user-${messageTimestamp}`,
2180
+ const d = It(), f = `${e.agentId}-${e.sessionId}`, T = Date.now(), I = {
2181
+ id: `user-${T}`,
2315
2182
  role: "user",
2316
- content: [{ type: "text", text: message }],
2317
- timestamp: messageTimestamp,
2318
- archived: false,
2319
- showIcon: false
2320
- };
2321
- const abortController = new AbortController();
2322
- setState((prev) => ({
2323
- ...prev,
2324
- uiMessages: [...prev.uiMessages, userMessage],
2325
- isProcessing: true,
2183
+ content: [{ type: "text", text: h }],
2184
+ timestamp: T,
2185
+ archived: !1,
2186
+ showIcon: !1
2187
+ }, P = new AbortController();
2188
+ a((m) => ({
2189
+ ...m,
2190
+ uiMessages: [...m.uiMessages, I],
2191
+ isProcessing: !0,
2326
2192
  error: null,
2327
- currentAbortController: abortController
2193
+ currentAbortController: P
2328
2194
  }));
2329
2195
  try {
2330
- let streamingMessageId = null;
2331
- let finalMessageAdded = false;
2332
- for await (const update of agentManager.sendMessageStream(
2333
- agentKey,
2334
- message,
2196
+ let m = null, k = !1;
2197
+ for await (const C of d.sendMessageStream(
2198
+ f,
2199
+ h,
2335
2200
  {
2336
- abortSignal: abortController.signal
2201
+ abortSignal: P.signal
2337
2202
  }
2338
2203
  )) {
2339
- if (!update.final && update.text) {
2340
- if (!streamingMessageId) {
2341
- streamingMessageId = `agent-streaming-${Date.now()}`;
2342
- const streamingMessage = {
2343
- id: streamingMessageId,
2204
+ if (!C.final && C.text)
2205
+ if (m)
2206
+ a((E) => ({
2207
+ ...E,
2208
+ uiMessages: E.uiMessages.map(
2209
+ (R) => R.id === m ? {
2210
+ ...R,
2211
+ content: [
2212
+ {
2213
+ type: "text",
2214
+ text: C.text
2215
+ }
2216
+ ]
2217
+ } : R
2218
+ )
2219
+ }));
2220
+ else {
2221
+ m = `agent-streaming-${Date.now()}`;
2222
+ const E = {
2223
+ id: m,
2344
2224
  role: "agent",
2345
2225
  content: [
2346
- { type: "text", text: update.text }
2226
+ { type: "text", text: C.text }
2347
2227
  ],
2348
2228
  timestamp: Date.now(),
2349
- archived: false,
2350
- showIcon: true,
2229
+ archived: !1,
2230
+ showIcon: !0,
2351
2231
  icon: "assistant"
2352
2232
  };
2353
- setState((prev) => ({
2354
- ...prev,
2233
+ a((R) => ({
2234
+ ...R,
2355
2235
  uiMessages: [
2356
- ...prev.uiMessages,
2357
- streamingMessage
2236
+ ...R.uiMessages,
2237
+ E
2358
2238
  ]
2359
2239
  }));
2360
- } else {
2361
- setState((prev) => ({
2362
- ...prev,
2363
- uiMessages: prev.uiMessages.map(
2364
- (msg) => msg.id === streamingMessageId ? {
2365
- ...msg,
2366
- content: [
2367
- {
2368
- type: "text",
2369
- text: update.text
2370
- }
2371
- ]
2372
- } : msg
2373
- )
2374
- }));
2375
2240
  }
2376
- }
2377
- if (update.final && update.status?.message && streamingMessageId) {
2378
- finalMessageAdded = true;
2379
- const currentStreamingId = streamingMessageId;
2380
- const finalMessage = transformClientMessageToUI(
2381
- update.status.message,
2382
- registrationsRef.current
2241
+ if (C.final && ((w = C.status) != null && w.message) && m) {
2242
+ k = !0;
2243
+ const E = m, R = V(
2244
+ C.status.message,
2245
+ g.current
2383
2246
  );
2384
- if (finalMessage) {
2385
- setState((prev) => {
2386
- const updatedMessages = prev.uiMessages.map(
2387
- (msg) => msg.id === currentStreamingId ? finalMessage : msg
2388
- );
2389
- const updatedClientHistory = agentManager.getConversationHistory(
2390
- agentKey
2391
- );
2392
- return {
2393
- ...prev,
2394
- clientMessages: updatedClientHistory,
2395
- uiMessages: updatedMessages,
2396
- isProcessing: false,
2397
- currentAbortController: null
2398
- };
2399
- });
2400
- }
2401
- streamingMessageId = null;
2247
+ R && a((O) => {
2248
+ const v = O.uiMessages.map(
2249
+ (B) => B.id === E ? R : B
2250
+ ), F = d.getConversationHistory(
2251
+ f
2252
+ );
2253
+ return {
2254
+ ...O,
2255
+ clientMessages: F,
2256
+ uiMessages: v,
2257
+ isProcessing: !1,
2258
+ currentAbortController: null
2259
+ };
2260
+ }), m = null;
2402
2261
  }
2403
2262
  }
2404
- if (!finalMessageAdded) {
2405
- const updatedClientHistory = agentManager.getConversationHistory(agentKey);
2406
- setState((prev) => {
2407
- let filteredMessages = prev.uiMessages;
2408
- if (streamingMessageId) {
2409
- filteredMessages = prev.uiMessages.filter(
2410
- (msg) => msg.id !== streamingMessageId
2411
- );
2412
- }
2413
- const transformedClientMessages = updatedClientHistory.map(
2414
- (msg) => transformClientMessageToUI(
2415
- msg,
2416
- registrationsRef.current
2263
+ if (!k) {
2264
+ const C = d.getConversationHistory(f);
2265
+ a((E) => {
2266
+ let R = E.uiMessages;
2267
+ m && (R = E.uiMessages.filter(
2268
+ (_) => _.id !== m
2269
+ ));
2270
+ const O = C.map(
2271
+ (_) => V(
2272
+ _,
2273
+ g.current
2417
2274
  )
2418
2275
  ).filter(
2419
- (msg) => msg !== null
2420
- );
2421
- const clientMessageIds = new Set(
2422
- updatedClientHistory.map((msg) => msg.messageId)
2423
- );
2424
- const uiOnlyMessages = filteredMessages.filter(
2425
- (msg) => !clientMessageIds.has(msg.id) && msg.content[0]?.type === "component"
2426
- );
2427
- const mergedUIMessages = sortUIMessagesByTime([
2428
- ...transformedClientMessages,
2429
- ...uiOnlyMessages
2276
+ (_) => _ !== null
2277
+ ), v = new Set(
2278
+ C.map((_) => _.messageId)
2279
+ ), F = R.filter(
2280
+ (_) => {
2281
+ var K;
2282
+ return !v.has(_.id) && ((K = _.content[0]) == null ? void 0 : K.type) === "component";
2283
+ }
2284
+ ), B = Q([
2285
+ ...O,
2286
+ ...F
2430
2287
  ]);
2431
2288
  return {
2432
- ...prev,
2433
- clientMessages: updatedClientHistory,
2434
- uiMessages: mergedUIMessages,
2435
- isProcessing: false,
2289
+ ...E,
2290
+ clientMessages: C,
2291
+ uiMessages: B,
2292
+ isProcessing: !1,
2436
2293
  currentAbortController: null
2437
2294
  };
2438
2295
  });
2439
2296
  }
2440
- } catch (error) {
2441
- if (error instanceof Error && error.name === "AbortError") {
2442
- console.log("Request was aborted by user");
2443
- setState((prev) => ({
2444
- ...prev,
2445
- isProcessing: false,
2297
+ } catch (m) {
2298
+ if (m instanceof Error && m.name === "AbortError") {
2299
+ console.log("Request was aborted by user"), a((C) => ({
2300
+ ...C,
2301
+ isProcessing: !1,
2446
2302
  error: null,
2447
2303
  // Don't show error for user-initiated abort
2448
2304
  currentAbortController: null
2449
2305
  }));
2450
2306
  return;
2451
2307
  }
2452
- const errorMessage = error instanceof Error ? error.message : "Failed to send message";
2453
- setState((prev) => ({
2454
- ...prev,
2455
- isProcessing: false,
2456
- error: errorMessage,
2308
+ const k = m instanceof Error ? m.message : "Failed to send message";
2309
+ throw a((C) => ({
2310
+ ...C,
2311
+ isProcessing: !1,
2312
+ error: k,
2457
2313
  currentAbortController: null
2458
- }));
2459
- throw error;
2314
+ })), m;
2460
2315
  }
2461
2316
  },
2462
- [agentConfig.agentId, agentConfig.sessionId, isValidConfig]
2463
- );
2464
- const addMessage = useCallback3((message) => {
2465
- setState((prev) => ({
2466
- ...prev,
2467
- uiMessages: sortUIMessagesByTime([...prev.uiMessages, message])
2317
+ [e.agentId, e.sessionId, s]
2318
+ ), b = j((h) => {
2319
+ a((d) => ({
2320
+ ...d,
2321
+ uiMessages: Q([...d.uiMessages, h])
2468
2322
  }));
2469
- }, []);
2470
- const registerSuggestions = useCallback3((suggestions) => {
2471
- setState((prev) => ({
2472
- ...prev,
2473
- suggestions
2323
+ }, []), A = j((h) => {
2324
+ a((d) => ({
2325
+ ...d,
2326
+ suggestions: h
2474
2327
  }));
2475
- }, []);
2476
- const clearSuggestions = useCallback3(() => {
2477
- setState((prev) => ({
2478
- ...prev,
2328
+ }, []), S = j(() => {
2329
+ a((h) => ({
2330
+ ...h,
2479
2331
  suggestions: []
2480
2332
  }));
2481
- }, []);
2482
- const registerMarkdownComponents = useCallback3(
2483
- (components) => {
2484
- setState((prev) => {
2485
- const updatedComponents = {
2486
- ...prev.markdownComponents,
2487
- ...components
2488
- };
2489
- const updatedUIMessages = prev.clientMessages.map(
2490
- (msg) => transformClientMessageToUI(
2491
- msg,
2492
- registrationsRef.current
2333
+ }, []), M = j(
2334
+ (h) => {
2335
+ a((d) => {
2336
+ const f = {
2337
+ ...d.markdownComponents,
2338
+ ...h
2339
+ }, T = d.clientMessages.map(
2340
+ (m) => V(
2341
+ m,
2342
+ g.current
2493
2343
  )
2494
- ).filter((msg) => msg !== null);
2495
- const clientMessageIds = new Set(
2496
- prev.clientMessages.map((msg) => msg.messageId)
2497
- );
2498
- const uiOnlyMessages = prev.uiMessages.filter(
2499
- (msg) => !clientMessageIds.has(msg.id) && msg.content[0]?.type === "component"
2500
- );
2501
- const mergedUIMessages = sortUIMessagesByTime([
2502
- ...updatedUIMessages,
2503
- ...uiOnlyMessages
2344
+ ).filter((m) => m !== null), I = new Set(
2345
+ d.clientMessages.map((m) => m.messageId)
2346
+ ), P = d.uiMessages.filter(
2347
+ (m) => {
2348
+ var k;
2349
+ return !I.has(m.id) && ((k = m.content[0]) == null ? void 0 : k.type) === "component";
2350
+ }
2351
+ ), w = Q([
2352
+ ...T,
2353
+ ...P
2504
2354
  ]);
2505
2355
  return {
2506
- ...prev,
2507
- markdownComponents: updatedComponents,
2508
- uiMessages: mergedUIMessages
2356
+ ...d,
2357
+ markdownComponents: f,
2358
+ uiMessages: w
2509
2359
  };
2510
2360
  });
2511
2361
  },
2512
2362
  []
2513
- );
2514
- const registerMarkdownExtensions = useCallback3(
2515
- (extensions) => {
2516
- setState((prev) => {
2517
- const updatedExtensions = {
2518
- ...prev.markdownExtensions,
2519
- ...extensions
2520
- };
2521
- const updatedUIMessages = prev.clientMessages.map(
2522
- (msg) => transformClientMessageToUI(
2523
- msg,
2524
- registrationsRef.current
2363
+ ), x = j(
2364
+ (h) => {
2365
+ a((d) => {
2366
+ const f = {
2367
+ ...d.markdownExtensions,
2368
+ ...h
2369
+ }, T = d.clientMessages.map(
2370
+ (m) => V(
2371
+ m,
2372
+ g.current
2525
2373
  )
2526
- ).filter((msg) => msg !== null);
2527
- const clientMessageIds = new Set(
2528
- prev.clientMessages.map((msg) => msg.messageId)
2529
- );
2530
- const uiOnlyMessages = prev.uiMessages.filter(
2531
- (msg) => !clientMessageIds.has(msg.id) && msg.content[0]?.type === "component"
2532
- );
2533
- const mergedUIMessages = sortUIMessagesByTime([
2534
- ...updatedUIMessages,
2535
- ...uiOnlyMessages
2374
+ ).filter((m) => m !== null), I = new Set(
2375
+ d.clientMessages.map((m) => m.messageId)
2376
+ ), P = d.uiMessages.filter(
2377
+ (m) => {
2378
+ var k;
2379
+ return !I.has(m.id) && ((k = m.content[0]) == null ? void 0 : k.type) === "component";
2380
+ }
2381
+ ), w = Q([
2382
+ ...T,
2383
+ ...P
2536
2384
  ]);
2537
2385
  return {
2538
- ...prev,
2539
- markdownExtensions: updatedExtensions,
2540
- uiMessages: mergedUIMessages
2386
+ ...d,
2387
+ markdownExtensions: f,
2388
+ uiMessages: w
2541
2389
  };
2542
2390
  });
2543
2391
  },
2544
2392
  []
2545
2393
  );
2546
- useEffect(() => {
2547
- setState((prev) => {
2548
- if (prev.clientMessages.length === 0) {
2549
- return prev;
2550
- }
2551
- const updatedUIMessages = prev.clientMessages.map(
2552
- (msg) => transformClientMessageToUI(msg, registrationsRef.current)
2553
- ).filter((msg) => msg !== null);
2554
- const clientMessageIds = new Set(
2555
- prev.clientMessages.map((msg) => msg.messageId)
2556
- );
2557
- const uiOnlyMessages = prev.uiMessages.filter(
2558
- (msg) => !clientMessageIds.has(msg.id) && msg.content[0]?.type === "component"
2394
+ Y(() => {
2395
+ a((h) => {
2396
+ if (h.clientMessages.length === 0)
2397
+ return h;
2398
+ const d = h.clientMessages.map(
2399
+ (I) => V(I, g.current)
2400
+ ).filter((I) => I !== null), f = new Set(
2401
+ h.clientMessages.map((I) => I.messageId)
2402
+ ), T = h.uiMessages.filter(
2403
+ (I) => {
2404
+ var P;
2405
+ return !f.has(I.id) && ((P = I.content[0]) == null ? void 0 : P.type) === "component";
2406
+ }
2559
2407
  );
2560
2408
  return {
2561
- ...prev,
2562
- uiMessages: sortUIMessagesByTime([
2563
- ...updatedUIMessages,
2564
- ...uiOnlyMessages
2409
+ ...h,
2410
+ uiMessages: Q([
2411
+ ...d,
2412
+ ...T
2565
2413
  ])
2566
2414
  };
2567
2415
  });
2568
- }, [registrations]);
2569
- const messageRenderer = useMemo3(
2570
- () => createMessageRenderer({
2571
- components: state.markdownComponents,
2572
- extensions: state.markdownExtensions
2416
+ }, [c]);
2417
+ const p = it(
2418
+ () => ve({
2419
+ components: n.markdownComponents,
2420
+ extensions: n.markdownExtensions
2573
2421
  }),
2574
- [state.markdownComponents, state.markdownExtensions]
2575
- );
2576
- const abortCurrentRequest = useCallback3(() => {
2577
- setState((currentState) => {
2578
- if (currentState.currentAbortController) {
2579
- currentState.currentAbortController.abort();
2580
- }
2581
- return currentState;
2582
- });
2422
+ [n.markdownComponents, n.markdownExtensions]
2423
+ ), u = j(() => {
2424
+ a((h) => (h.currentAbortController && h.currentAbortController.abort(), h));
2583
2425
  }, []);
2584
2426
  return {
2585
2427
  // AgentUI props
2586
- messages: state.uiMessages,
2587
- isProcessing: state.isProcessing,
2588
- error: state.error,
2589
- onSubmit,
2590
- suggestions: state.suggestions,
2591
- messageRenderer,
2428
+ messages: n.uiMessages,
2429
+ isProcessing: n.isProcessing,
2430
+ error: n.error,
2431
+ onSubmit: y,
2432
+ suggestions: n.suggestions,
2433
+ messageRenderer: p,
2592
2434
  // UI management methods
2593
- registerSuggestions,
2594
- clearSuggestions,
2595
- registerMarkdownComponents,
2596
- registerMarkdownExtensions,
2435
+ registerSuggestions: A,
2436
+ clearSuggestions: S,
2437
+ registerMarkdownComponents: M,
2438
+ registerMarkdownExtensions: x,
2597
2439
  // Message actions methods
2598
- registerMessageActions,
2599
- unregisterMessageActions,
2600
- clearAllMessageActions,
2601
- createFeedbackActions: createFeedbackActions2,
2440
+ registerMessageActions: r,
2441
+ unregisterMessageActions: o,
2442
+ clearAllMessageActions: i,
2443
+ createFeedbackActions: l,
2602
2444
  // Tool integration
2603
- addMessage,
2445
+ addMessage: b,
2604
2446
  // Abort control
2605
- abortCurrentRequest
2447
+ abortCurrentRequest: u
2606
2448
  };
2607
2449
  }
2608
-
2609
- // src/client/types/index.ts
2610
- var A2AErrorCodes = /* @__PURE__ */ ((A2AErrorCodes2) => {
2611
- A2AErrorCodes2[A2AErrorCodes2["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
2612
- A2AErrorCodes2[A2AErrorCodes2["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
2613
- A2AErrorCodes2[A2AErrorCodes2["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
2614
- A2AErrorCodes2[A2AErrorCodes2["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
2615
- A2AErrorCodes2[A2AErrorCodes2["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
2616
- A2AErrorCodes2[A2AErrorCodes2["SERVER_ERROR"] = -32e3] = "SERVER_ERROR";
2617
- return A2AErrorCodes2;
2618
- })(A2AErrorCodes || {});
2619
-
2620
- // src/auth/jetpack.ts
2621
- import apiFetch from "@wordpress/api-fetch";
2622
- var JWT_TOKEN_ID = "jetpack-ai-jwt-token";
2623
- var JWT_TOKEN_EXPIRATION_TIME = 30 * 60 * 1e3;
2624
- function isSimpleSite() {
2625
- const hasJetpackConnection = Boolean(window.JP_CONNECTION_INITIAL_STATE);
2626
- if (hasJetpackConnection) {
2627
- return false;
2628
- }
2629
- const isSimple = Boolean(
2630
- window.Jetpack_Editor_Initial_State?.wpcomBlogId
2631
- );
2632
- return isSimple;
2633
- }
2634
- async function requestJetpackToken(errorHandler, useCachedToken = true) {
2635
- const token = localStorage.getItem(JWT_TOKEN_ID);
2636
- let tokenData;
2637
- if (token) {
2450
+ var De = /* @__PURE__ */ ((t) => (t[t.PARSE_ERROR = -32700] = "PARSE_ERROR", t[t.INVALID_REQUEST = -32600] = "INVALID_REQUEST", t[t.METHOD_NOT_FOUND = -32601] = "METHOD_NOT_FOUND", t[t.INVALID_PARAMS = -32602] = "INVALID_PARAMS", t[t.INTERNAL_ERROR = -32603] = "INTERNAL_ERROR", t[t.SERVER_ERROR = -32e3] = "SERVER_ERROR", t))(De || {});
2451
+ const Ct = "jetpack-ai-jwt-token", _e = 30 * 60 * 1e3;
2452
+ function je() {
2453
+ var s;
2454
+ return window.JP_CONNECTION_INITIAL_STATE ? !1 : !!((s = window.Jetpack_Editor_Initial_State) != null && s.wpcomBlogId);
2455
+ }
2456
+ async function Fe(t, e = !0) {
2457
+ var l, c;
2458
+ const s = localStorage.getItem(Ct);
2459
+ let n;
2460
+ if (s)
2638
2461
  try {
2639
- tokenData = JSON.parse(token);
2640
- } catch (error) {
2641
- console.warn("Invalid cached Jetpack token:", error);
2462
+ n = JSON.parse(s);
2463
+ } catch (g) {
2464
+ console.warn("Invalid cached Jetpack token:", g);
2642
2465
  }
2643
- }
2644
- if (tokenData && tokenData?.token && tokenData?.expire && tokenData?.expire > Date.now() && useCachedToken) {
2645
- return tokenData;
2646
- }
2647
- const apiNonce = window.JP_CONNECTION_INITIAL_STATE?.apiNonce;
2648
- const siteId = window.Jetpack_Editor_Initial_State?.wpcomBlogId;
2649
- let data = {
2466
+ if (n && (n != null && n.token) && (n != null && n.expire) && (n == null ? void 0 : n.expire) > Date.now() && e)
2467
+ return n;
2468
+ const a = (l = window.JP_CONNECTION_INITIAL_STATE) == null ? void 0 : l.apiNonce, r = (c = window.Jetpack_Editor_Initial_State) == null ? void 0 : c.wpcomBlogId;
2469
+ let o = {
2650
2470
  token: "",
2651
2471
  blog_id: ""
2652
2472
  };
2653
2473
  try {
2654
- if (!isSimpleSite()) {
2655
- data = await apiFetch({
2656
- path: "/jetpack/v4/jetpack-ai-jwt?_cacheBuster=" + Date.now(),
2657
- credentials: "same-origin",
2658
- headers: {
2659
- "X-WP-Nonce": apiNonce || ""
2660
- },
2661
- method: "POST"
2662
- });
2663
- } else {
2664
- data = await apiFetch({
2665
- path: "/wpcom/v2/sites/" + siteId + "/jetpack-openai-query/jwt",
2666
- method: "POST"
2667
- });
2668
- }
2669
- } catch (error) {
2670
- console.log("Failed to fetch Jetpack token:", error);
2671
- throw new Error(errorHandler(error));
2474
+ je() ? o = await mt({
2475
+ path: "/wpcom/v2/sites/" + r + "/jetpack-openai-query/jwt",
2476
+ method: "POST"
2477
+ }) : o = await mt({
2478
+ path: "/jetpack/v4/jetpack-ai-jwt?_cacheBuster=" + Date.now(),
2479
+ credentials: "same-origin",
2480
+ headers: {
2481
+ "X-WP-Nonce": a || ""
2482
+ },
2483
+ method: "POST"
2484
+ });
2485
+ } catch (g) {
2486
+ throw console.log("Failed to fetch Jetpack token:", g), new Error(t(g));
2672
2487
  }
2673
- if (!data?.token) {
2488
+ if (!(o != null && o.token))
2674
2489
  throw new Error(
2675
2490
  "Authentication failed. Please ensure Jetpack is properly connected and try again."
2676
2491
  );
2677
- }
2678
- const newTokenData = {
2679
- token: data.token,
2680
- blogId: data.blog_id || "",
2681
- expire: Date.now() + JWT_TOKEN_EXPIRATION_TIME
2492
+ const i = {
2493
+ token: o.token,
2494
+ blogId: o.blog_id || "",
2495
+ expire: Date.now() + _e
2682
2496
  };
2683
2497
  try {
2684
- localStorage.setItem(JWT_TOKEN_ID, JSON.stringify(newTokenData));
2685
- } catch (storageError) {
2686
- console.log("Error storing token in localStorage:", storageError);
2498
+ localStorage.setItem(Ct, JSON.stringify(i));
2499
+ } catch (g) {
2500
+ console.log("Error storing token in localStorage:", g);
2687
2501
  }
2688
- return newTokenData;
2502
+ return i;
2689
2503
  }
2690
- var createJetpackAuthProvider = (errorHandler) => {
2691
- return async () => {
2692
- const headers = {};
2693
- try {
2694
- const tokenData = await requestJetpackToken(errorHandler);
2695
- if (tokenData?.token) {
2696
- headers.Authorization = `${tokenData.token}`;
2697
- }
2698
- } catch (error) {
2699
- console.error("Failed to get Jetpack token for auth:", error);
2700
- throw error;
2701
- }
2702
- return headers;
2703
- };
2504
+ const Xe = (t) => async () => {
2505
+ const e = {};
2506
+ try {
2507
+ const s = await Fe(t);
2508
+ s != null && s.token && (e.Authorization = `${s.token}`);
2509
+ } catch (s) {
2510
+ throw console.error("Failed to get Jetpack token for auth:", s), s;
2511
+ }
2512
+ return e;
2704
2513
  };
2705
2514
  export {
2706
- A2AErrorCodes,
2707
- BarChart,
2708
- ChartBlock,
2709
- LineChart,
2710
- createAbortController,
2711
- createClient,
2712
- createFeedbackActions,
2713
- createJetpackAuthProvider,
2714
- createMessageRenderer,
2715
- createRequestId,
2716
- createTaskId,
2717
- createTextMessage,
2718
- extractTextFromMessage,
2719
- extractToolCallsFromMessage,
2720
- getAgentManager,
2721
- useAgentChat,
2722
- useClientContext,
2723
- useClientTools,
2724
- useMessageActions
2515
+ De as A2AErrorCodes,
2516
+ Ht as BarChart,
2517
+ be as ChartBlock,
2518
+ Te as LineChart,
2519
+ Ge as createAbortController,
2520
+ ue as createClient,
2521
+ Re as createFeedbackActions,
2522
+ Xe as createJetpackAuthProvider,
2523
+ ve as createMessageRenderer,
2524
+ Lt as createRequestId,
2525
+ Wt as createTaskId,
2526
+ rt as createTextMessage,
2527
+ U as extractTextFromMessage,
2528
+ J as extractToolCallsFromMessage,
2529
+ It as getAgentManager,
2530
+ Qe as useAgentChat,
2531
+ Ve as useClientContext,
2532
+ ze as useClientTools,
2533
+ Ee as useMessageActions
2725
2534
  };