@useago/sdk 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +2 -0
  2. package/dist/AgoClient-DPZdN5n2.js +905 -0
  3. package/dist/AgoClient-DPZdN5n2.js.map +1 -0
  4. package/dist/AgoClient-wMVUQqCD.cjs +976 -0
  5. package/dist/AgoClient-wMVUQqCD.cjs.map +1 -0
  6. package/dist/angular.cjs +138 -100
  7. package/dist/angular.cjs.map +1 -1
  8. package/dist/angular.d.ts +1 -0
  9. package/dist/angular.js +139 -103
  10. package/dist/angular.js.map +1 -1
  11. package/dist/client/AgoClient.d.ts +56 -0
  12. package/dist/client/types.d.ts +5 -1
  13. package/dist/createMockClient-Ci_N2tH8.cjs +104 -0
  14. package/dist/createMockClient-Ci_N2tH8.cjs.map +1 -0
  15. package/dist/createMockClient-U0ae_AYy.js +99 -0
  16. package/dist/createMockClient-U0ae_AYy.js.map +1 -0
  17. package/dist/devtools/index.d.ts +2 -0
  18. package/dist/devtools/initDevPanel.d.ts +15 -0
  19. package/dist/devtools.cjs +182 -0
  20. package/dist/devtools.cjs.map +1 -0
  21. package/dist/devtools.d.ts +2 -0
  22. package/dist/devtools.js +181 -0
  23. package/dist/devtools.js.map +1 -0
  24. package/dist/functions--c6lx3ic.cjs +480 -0
  25. package/dist/functions--c6lx3ic.cjs.map +1 -0
  26. package/dist/functions-C9F1dnmh.js +398 -0
  27. package/dist/functions-C9F1dnmh.js.map +1 -0
  28. package/dist/helpers/factory.d.ts +20 -0
  29. package/dist/helpers.cjs +14 -305
  30. package/dist/helpers.d.ts +1 -0
  31. package/dist/helpers.js +2 -306
  32. package/dist/index.cjs +316 -151
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.ts +14 -9
  35. package/dist/index.js +289 -163
  36. package/dist/index.js.map +1 -1
  37. package/dist/react/components/ChatWidget.d.ts +2 -0
  38. package/dist/react/components/Markdown.d.ts +12 -0
  39. package/dist/react/components/Message.d.ts +2 -0
  40. package/dist/react/components/index.d.ts +2 -0
  41. package/dist/react/context/AgoContext.d.ts +29 -3
  42. package/dist/react/context/index.d.ts +1 -1
  43. package/dist/react/hooks/index.d.ts +1 -0
  44. package/dist/react/hooks/useAgoContext.d.ts +40 -0
  45. package/dist/react/hooks/useAgoFunction.d.ts +14 -2
  46. package/dist/react/hooks/useAgoStore.d.ts +17 -0
  47. package/dist/react/index.d.ts +5 -1
  48. package/dist/react.cjs +22130 -10274
  49. package/dist/react.cjs.map +1 -1
  50. package/dist/react.d.ts +1 -0
  51. package/dist/react.js +22128 -10289
  52. package/dist/react.js.map +1 -1
  53. package/dist/rolldown-runtime-BqCkTl7Q.cjs +50 -0
  54. package/dist/rolldown-runtime-CNZpIYwj.js +33 -0
  55. package/dist/state/ClientContextRegistry.d.ts +64 -0
  56. package/dist/state/createStore.d.ts +30 -0
  57. package/dist/vue/composables/useAgoStore.d.ts +18 -0
  58. package/dist/vue/index.d.ts +1 -0
  59. package/dist/vue.cjs +312 -208
  60. package/dist/vue.cjs.map +1 -1
  61. package/dist/vue.d.ts +1 -0
  62. package/dist/vue.js +311 -218
  63. package/dist/vue.js.map +1 -1
  64. package/dist/widget/types.d.ts +1 -0
  65. package/dist/widget.cjs +0 -2
  66. package/dist/widget.d.ts +1 -0
  67. package/dist/widget.js +0 -2
  68. package/package.json +6 -1
  69. package/dist/AgoClient-B-SONi_K.js +0 -861
  70. package/dist/AgoClient-B-SONi_K.js.map +0 -1
  71. package/dist/AgoClient-xTWfMWKh.cjs +0 -860
  72. package/dist/AgoClient-xTWfMWKh.cjs.map +0 -1
  73. package/dist/createMockClient-B1DcBiIK.js +0 -94
  74. package/dist/createMockClient-B1DcBiIK.js.map +0 -1
  75. package/dist/createMockClient-BqNSJUu4.cjs +0 -93
  76. package/dist/createMockClient-BqNSJUu4.cjs.map +0 -1
  77. package/dist/helpers.cjs.map +0 -1
  78. package/dist/helpers.js.map +0 -1
  79. package/dist/widget.cjs.map +0 -1
  80. package/dist/widget.js.map +0 -1
@@ -1,860 +0,0 @@
1
- "use strict";
2
- class AgoError extends Error {
3
- constructor(message, code, statusCode) {
4
- super(message);
5
- this.code = code;
6
- this.statusCode = statusCode;
7
- this.name = "AgoError";
8
- }
9
- }
10
- class AgoApiError extends AgoError {
11
- constructor(message, code, statusCode, type, param, docUrl) {
12
- super(message, code, statusCode);
13
- this.type = type;
14
- this.param = param;
15
- this.docUrl = docUrl;
16
- this.name = "AgoApiError";
17
- }
18
- static fromResponse(data, statusCode) {
19
- const error = data.error;
20
- return new AgoApiError(
21
- error.message,
22
- error.code,
23
- statusCode,
24
- error.type,
25
- error.param,
26
- error.doc_url
27
- );
28
- }
29
- }
30
- class AgoNetworkError extends AgoError {
31
- constructor(message, originalError) {
32
- super(message, "network_error");
33
- this.originalError = originalError;
34
- this.name = "AgoNetworkError";
35
- }
36
- }
37
- class AgoStreamError extends AgoError {
38
- constructor(message) {
39
- super(message, "stream_error");
40
- this.name = "AgoStreamError";
41
- }
42
- }
43
- class AgoFunctionError extends AgoError {
44
- constructor(message, functionName, originalError) {
45
- super(message, "function_error");
46
- this.functionName = functionName;
47
- this.originalError = originalError;
48
- this.name = "AgoFunctionError";
49
- }
50
- }
51
- class Logger {
52
- constructor(enabled = false) {
53
- this.enabled = enabled;
54
- }
55
- enable() {
56
- this.enabled = true;
57
- }
58
- disable() {
59
- this.enabled = false;
60
- }
61
- log(...args) {
62
- if (this.enabled) {
63
- console.log("[AGO SDK]", ...args);
64
- }
65
- }
66
- warn(...args) {
67
- if (this.enabled) {
68
- console.warn("[AGO SDK]", ...args);
69
- }
70
- }
71
- error(...args) {
72
- console.error("[AGO SDK]", ...args);
73
- }
74
- debug(...args) {
75
- if (this.enabled) {
76
- console.debug("[AGO SDK]", ...args);
77
- }
78
- }
79
- }
80
- const logger = new Logger();
81
- const WIDGET_ID_KEY = "ago_widget_id";
82
- function generateWidgetId() {
83
- if (typeof localStorage !== "undefined") {
84
- const stored = localStorage.getItem(WIDGET_ID_KEY);
85
- if (stored) return stored;
86
- }
87
- const id = crypto.randomUUID();
88
- if (typeof localStorage !== "undefined") {
89
- try {
90
- localStorage.setItem(WIDGET_ID_KEY, id);
91
- } catch {
92
- }
93
- }
94
- return id;
95
- }
96
- class HttpClient {
97
- constructor(config) {
98
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
99
- this.headers = {
100
- "X-Widget-Id": config.widgetId || generateWidgetId()
101
- };
102
- if (config.userEmail) {
103
- this.headers["X-User-Email"] = config.userEmail;
104
- }
105
- if (config.userJwt) {
106
- this.headers["Authorization"] = `Bearer ${config.userJwt}`;
107
- }
108
- }
109
- /**
110
- * Update configuration (e.g., JWT token)
111
- */
112
- updateConfig(config) {
113
- if (config.baseUrl) {
114
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
115
- }
116
- if (config.widgetId) {
117
- this.headers["X-Widget-Id"] = config.widgetId;
118
- }
119
- if (config.userEmail) {
120
- this.headers["X-User-Email"] = config.userEmail;
121
- }
122
- if (config.userJwt) {
123
- this.headers["Authorization"] = `Bearer ${config.userJwt}`;
124
- }
125
- }
126
- /**
127
- * Make a GET request
128
- */
129
- async get(path) {
130
- return this.request("GET", path);
131
- }
132
- /**
133
- * Make a POST request with JSON body
134
- */
135
- async post(path, body) {
136
- return this.request("POST", path, body);
137
- }
138
- /**
139
- * Make a POST request and return the raw Response (for streaming)
140
- */
141
- async postStream(path, body) {
142
- const url = `${this.baseUrl}${path}`;
143
- logger.debug("POST (stream)", url, body);
144
- try {
145
- const response = await fetch(url, {
146
- method: "POST",
147
- headers: {
148
- ...this.headers,
149
- "Content-Type": "application/json"
150
- },
151
- body: body ? JSON.stringify(body) : void 0
152
- });
153
- if (!response.ok) {
154
- await this.handleErrorResponse(response);
155
- }
156
- return response;
157
- } catch (error) {
158
- if (error instanceof AgoApiError) {
159
- throw error;
160
- }
161
- throw new AgoNetworkError(
162
- `Network error: ${error instanceof Error ? error.message : "Unknown error"}`,
163
- error instanceof Error ? error : void 0
164
- );
165
- }
166
- }
167
- /**
168
- * Make a POST request with FormData (for file uploads)
169
- */
170
- async postFormData(path, formData) {
171
- const url = `${this.baseUrl}${path}`;
172
- logger.debug("POST (formData)", url);
173
- const headers = { ...this.headers };
174
- try {
175
- const response = await fetch(url, {
176
- method: "POST",
177
- headers,
178
- body: formData
179
- });
180
- if (!response.ok) {
181
- await this.handleErrorResponse(response);
182
- }
183
- return response;
184
- } catch (error) {
185
- if (error instanceof AgoApiError) {
186
- throw error;
187
- }
188
- throw new AgoNetworkError(
189
- `Network error: ${error instanceof Error ? error.message : "Unknown error"}`,
190
- error instanceof Error ? error : void 0
191
- );
192
- }
193
- }
194
- async request(method, path, body) {
195
- const url = `${this.baseUrl}${path}`;
196
- logger.debug(method, url, body);
197
- try {
198
- const response = await fetch(url, {
199
- method,
200
- headers: {
201
- ...this.headers,
202
- "Content-Type": "application/json"
203
- },
204
- body: body ? JSON.stringify(body) : void 0
205
- });
206
- if (!response.ok) {
207
- await this.handleErrorResponse(response);
208
- }
209
- if (response.status === 204) {
210
- return void 0;
211
- }
212
- return response.json();
213
- } catch (error) {
214
- if (error instanceof AgoApiError) {
215
- throw error;
216
- }
217
- throw new AgoNetworkError(
218
- `Network error: ${error instanceof Error ? error.message : "Unknown error"}`,
219
- error instanceof Error ? error : void 0
220
- );
221
- }
222
- }
223
- async handleErrorResponse(response) {
224
- let errorData;
225
- try {
226
- errorData = await response.json();
227
- } catch {
228
- }
229
- if (errorData == null ? void 0 : errorData.error) {
230
- throw AgoApiError.fromResponse(errorData, response.status);
231
- }
232
- throw new AgoApiError(
233
- `HTTP ${response.status}: ${response.statusText}`,
234
- "http_error",
235
- response.status,
236
- "api_error"
237
- );
238
- }
239
- }
240
- class FunctionRegistry {
241
- constructor() {
242
- this.functions = /* @__PURE__ */ new Map();
243
- }
244
- register(nameOrDef, handler, schema) {
245
- if (typeof nameOrDef === "object") {
246
- const { name: name2, handler: h, description, parameters } = nameOrDef;
247
- return this.register(name2, h, { description, parameters });
248
- }
249
- const name = nameOrDef;
250
- if (!handler || !schema) {
251
- throw new Error("handler and schema are required");
252
- }
253
- if (this.functions.has(name)) {
254
- logger.warn(`Function "${name}" is being overwritten`);
255
- }
256
- this.functions.set(name, {
257
- schema: { ...schema, name },
258
- handler
259
- });
260
- logger.log(`Registered function: ${name}`);
261
- }
262
- /**
263
- * Unregister a function
264
- */
265
- unregister(name) {
266
- const deleted = this.functions.delete(name);
267
- if (deleted) {
268
- logger.log(`Unregistered function: ${name}`);
269
- }
270
- return deleted;
271
- }
272
- /**
273
- * Get a registered function
274
- */
275
- get(name) {
276
- return this.functions.get(name);
277
- }
278
- /**
279
- * Check if a function is registered
280
- */
281
- has(name) {
282
- return this.functions.has(name);
283
- }
284
- /**
285
- * Get all registered function schemas (for sending to backend)
286
- */
287
- getSchemas() {
288
- return Array.from(this.functions.values()).map((f) => f.schema);
289
- }
290
- /**
291
- * Execute a registered function
292
- */
293
- async execute(name, args) {
294
- const registration = this.functions.get(name);
295
- if (!registration) {
296
- throw new AgoFunctionError(
297
- `Function "${name}" is not registered`,
298
- name
299
- );
300
- }
301
- logger.log(`Executing function: ${name}`, args);
302
- try {
303
- const result = await registration.handler(args);
304
- logger.log(`Function ${name} completed:`, result);
305
- return result;
306
- } catch (error) {
307
- logger.error(`Function ${name} failed:`, error);
308
- throw new AgoFunctionError(
309
- `Function "${name}" execution failed: ${error instanceof Error ? error.message : "Unknown error"}`,
310
- name,
311
- error instanceof Error ? error : void 0
312
- );
313
- }
314
- }
315
- /**
316
- * Clear all registered functions
317
- */
318
- clear() {
319
- this.functions.clear();
320
- logger.log("Cleared all registered functions");
321
- }
322
- /**
323
- * Get the number of registered functions
324
- */
325
- get size() {
326
- return this.functions.size;
327
- }
328
- }
329
- class SSEHandler {
330
- constructor(callbacks) {
331
- this.callbacks = callbacks;
332
- this.buffer = "";
333
- this.message = {};
334
- this.toolCalls = [];
335
- this.sources = [];
336
- this.followUpReplies = [];
337
- this.isFirstChunk = true;
338
- }
339
- /**
340
- * Process a streaming response
341
- */
342
- async processStream(response) {
343
- var _a, _b;
344
- if (!response.body) {
345
- throw new AgoStreamError("Response has no body");
346
- }
347
- const reader = response.body.getReader();
348
- const decoder = new TextDecoder();
349
- try {
350
- while (true) {
351
- const { done, value } = await reader.read();
352
- if (done) {
353
- break;
354
- }
355
- const text = decoder.decode(value, { stream: true });
356
- this.buffer += text;
357
- this.processBuffer();
358
- }
359
- if (this.buffer.trim()) {
360
- this.processBuffer();
361
- }
362
- return this.buildFinalMessage();
363
- } catch (error) {
364
- const streamError = error instanceof Error ? error : new AgoStreamError("Stream processing failed");
365
- (_b = (_a = this.callbacks).onError) == null ? void 0 : _b.call(_a, streamError);
366
- throw streamError;
367
- } finally {
368
- reader.releaseLock();
369
- }
370
- }
371
- processBuffer() {
372
- const parts = this.buffer.split("\n\n");
373
- this.buffer = parts.pop() || "";
374
- for (const part of parts) {
375
- if (!part.trim()) continue;
376
- const lines = part.split("\n");
377
- for (const line of lines) {
378
- if (line.startsWith(": ")) {
379
- continue;
380
- }
381
- if (line.startsWith("data: ")) {
382
- const jsonStr = line.slice(6);
383
- try {
384
- const data = JSON.parse(jsonStr);
385
- this.handleChunk(data);
386
- } catch (error) {
387
- logger.warn("Failed to parse SSE data:", jsonStr, error);
388
- }
389
- }
390
- }
391
- }
392
- }
393
- handleChunk(data) {
394
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
395
- if (data.message_id && !this.message.id) {
396
- this.message.id = data.message_id;
397
- }
398
- if ((_a = data.thread) == null ? void 0 : _a.id) {
399
- this.message.conversationId = data.thread.id;
400
- if (this.isFirstChunk && this.message.id) {
401
- this.isFirstChunk = false;
402
- (_c = (_b = this.callbacks).onStart) == null ? void 0 : _c.call(_b, {
403
- conversationId: this.message.conversationId,
404
- messageId: this.message.id
405
- });
406
- }
407
- }
408
- if (data.content !== void 0) {
409
- this.message.content = (this.message.content || "") + data.content;
410
- if (this.message.conversationId && this.message.id) {
411
- (_e = (_d = this.callbacks).onChunk) == null ? void 0 : _e.call(_d, {
412
- content: data.content,
413
- conversationId: this.message.conversationId,
414
- messageId: this.message.id
415
- });
416
- }
417
- }
418
- if (data.full_content !== void 0) {
419
- this.message.content = data.full_content;
420
- }
421
- if (data.status) {
422
- this.message.status = data.status;
423
- }
424
- if (data.agent) {
425
- this.message.agent = {
426
- id: data.agent.id,
427
- name: data.agent.name,
428
- displayName: data.agent.display_name
429
- };
430
- }
431
- if (data.knowledge_sources) {
432
- this.sources = data.knowledge_sources.map((s) => {
433
- const doc = s.knowledge_document;
434
- return {
435
- id: doc.id,
436
- title: doc.title,
437
- url: doc.use_external_link ? doc.external_link_url : doc.internal_link_url
438
- };
439
- });
440
- }
441
- if (data.type === "client_function" && data.function_name) {
442
- (_g = (_f = this.callbacks).onClientFunction) == null ? void 0 : _g.call(_f, {
443
- invocationId: data.id || "",
444
- functionName: data.function_name,
445
- arguments: data.arguments || {},
446
- conversationId: this.message.conversationId || ""
447
- });
448
- }
449
- if (data.tool_call_data && data.type && data.type !== "client_function") {
450
- const toolCall = this.parseToolCall(data);
451
- (_i = (_h = this.callbacks).onToolCall) == null ? void 0 : _i.call(_h, toolCall);
452
- const existingIndex = this.toolCalls.findIndex((t) => t.id === toolCall.id);
453
- if (existingIndex >= 0) {
454
- this.toolCalls[existingIndex] = toolCall;
455
- } else {
456
- this.toolCalls.push(toolCall);
457
- }
458
- }
459
- if (data.follow_up_replies) {
460
- this.followUpReplies = data.follow_up_replies;
461
- }
462
- }
463
- parseToolCall(data) {
464
- return {
465
- id: data.id || "",
466
- type: data.type || "status_message",
467
- status: data.status || "unknown",
468
- toolName: data.tool_name || "",
469
- toolDisplayName: data.tool_display_name,
470
- message: data.message,
471
- formSchema: data.form_schema,
472
- data: data.data,
473
- functionName: data.function_name,
474
- arguments: data.arguments
475
- };
476
- }
477
- buildFinalMessage() {
478
- var _a, _b;
479
- const message = {
480
- id: this.message.id || "",
481
- conversationId: this.message.conversationId || "",
482
- content: this.message.content || "",
483
- role: "assistant",
484
- status: this.message.status || "DONE",
485
- agent: this.message.agent,
486
- sources: this.sources.length > 0 ? this.sources : void 0,
487
- toolCalls: this.toolCalls.length > 0 ? this.toolCalls : void 0,
488
- followUpReplies: this.followUpReplies.length > 0 ? this.followUpReplies : void 0,
489
- createdAt: /* @__PURE__ */ new Date()
490
- };
491
- (_b = (_a = this.callbacks).onComplete) == null ? void 0 : _b.call(_a, message);
492
- return message;
493
- }
494
- }
495
- function isStreamNetworkError(error) {
496
- const message = error.message.toLowerCase();
497
- return message.includes("load failed") || message.includes("failed to fetch") || message.includes("network") || message.includes("abort");
498
- }
499
- class EventEmitter {
500
- constructor() {
501
- this.handlers = /* @__PURE__ */ new Map();
502
- }
503
- on(event, handler) {
504
- if (!this.handlers.has(event)) {
505
- this.handlers.set(event, /* @__PURE__ */ new Set());
506
- }
507
- this.handlers.get(event).add(handler);
508
- }
509
- off(event, handler) {
510
- const eventHandlers = this.handlers.get(event);
511
- if (eventHandlers) {
512
- eventHandlers.delete(handler);
513
- }
514
- }
515
- emit(event, data) {
516
- const eventHandlers = this.handlers.get(event);
517
- if (eventHandlers) {
518
- eventHandlers.forEach((handler) => {
519
- try {
520
- handler(data);
521
- } catch (error) {
522
- console.error(`Error in event handler for ${String(event)}:`, error);
523
- }
524
- });
525
- }
526
- }
527
- /**
528
- * Subscribe to an event and auto-unsubscribe after the first call.
529
- */
530
- once(event, handler) {
531
- const wrapper = (data) => {
532
- this.off(event, wrapper);
533
- handler(data);
534
- };
535
- this.on(event, wrapper);
536
- }
537
- /**
538
- * Returns a Promise that resolves the next time `event` fires.
539
- * Rejects if `timeout` (ms) is reached first.
540
- */
541
- waitFor(event, options) {
542
- return new Promise((resolve, reject) => {
543
- let timer;
544
- const handler = (data) => {
545
- if (timer) clearTimeout(timer);
546
- resolve(data);
547
- };
548
- this.once(event, handler);
549
- if (options == null ? void 0 : options.timeout) {
550
- timer = setTimeout(() => {
551
- this.off(event, handler);
552
- reject(new Error(`waitFor("${String(event)}") timed out after ${options.timeout}ms`));
553
- }, options.timeout);
554
- }
555
- });
556
- }
557
- removeAllListeners(event) {
558
- if (event) {
559
- this.handlers.delete(event);
560
- } else {
561
- this.handlers.clear();
562
- }
563
- }
564
- }
565
- class AgoClient {
566
- constructor(config) {
567
- this.config = config;
568
- this.httpClient = new HttpClient(config);
569
- this.functionRegistry = new FunctionRegistry();
570
- this.eventEmitter = new EventEmitter();
571
- if (config.debug) {
572
- logger.enable();
573
- }
574
- logger.log("AgoClient initialized");
575
- }
576
- // ─────────────────────────────────────────────────────────────────
577
- // Messaging
578
- // ─────────────────────────────────────────────────────────────────
579
- /**
580
- * Send a message and receive a streaming response
581
- */
582
- async sendMessage(content, options) {
583
- const clientFunctions = this.functionRegistry.getSchemas();
584
- const body = {
585
- content,
586
- conversation_id: options == null ? void 0 : options.conversationId,
587
- agent_id: (options == null ? void 0 : options.agentId) || this.config.defaultAgentId
588
- };
589
- if (clientFunctions.length > 0) {
590
- body.client_functions = clientFunctions;
591
- }
592
- let response;
593
- if ((options == null ? void 0 : options.files) && options.files.length > 0) {
594
- const formData = new FormData();
595
- formData.append("content", content);
596
- if (options.conversationId) {
597
- formData.append("conversation_id", options.conversationId);
598
- }
599
- if (options.agentId || this.config.defaultAgentId) {
600
- formData.append("agent_id", options.agentId || this.config.defaultAgentId || "");
601
- }
602
- if (clientFunctions.length > 0) {
603
- formData.append("client_functions", JSON.stringify(clientFunctions));
604
- }
605
- for (const file of options.files) {
606
- formData.append("files", file);
607
- }
608
- response = await this.httpClient.postFormData("/api/sdk/v1/messages", formData);
609
- } else {
610
- response = await this.httpClient.postStream("/api/sdk/v1/messages", body);
611
- }
612
- return this.processSSEResponse(response);
613
- }
614
- async processSSEResponse(response) {
615
- const handler = new SSEHandler({
616
- onStart: (data) => {
617
- this.eventEmitter.emit("message:start", data);
618
- },
619
- onChunk: (data) => {
620
- this.eventEmitter.emit("message:chunk", data);
621
- },
622
- onToolCall: (toolCall) => {
623
- this.eventEmitter.emit("toolCall:received", toolCall);
624
- if (toolCall.type === "form") {
625
- this.eventEmitter.emit("toolCall:form", toolCall);
626
- }
627
- },
628
- onClientFunction: async (data) => {
629
- this.eventEmitter.emit("function:invoke", data);
630
- await this.handleClientFunctionInvocation(data);
631
- },
632
- onComplete: (message) => {
633
- this.eventEmitter.emit("message:complete", message);
634
- },
635
- onError: (error) => {
636
- this.eventEmitter.emit("message:error", { error: error.message });
637
- }
638
- });
639
- return handler.processStream(response);
640
- }
641
- async handleClientFunctionInvocation(data) {
642
- let result;
643
- let error;
644
- try {
645
- result = await this.functionRegistry.execute(data.functionName, data.arguments);
646
- } catch (err) {
647
- error = err instanceof Error ? err.message : "Unknown error";
648
- logger.error("Client function execution failed:", err);
649
- }
650
- if (data.invocationId) {
651
- try {
652
- await this.submitToolCallForm(data.invocationId, {
653
- result,
654
- error,
655
- _type: "client_function_result"
656
- });
657
- } catch (submitError) {
658
- logger.error("Failed to submit function result:", submitError);
659
- }
660
- }
661
- this.eventEmitter.emit("function:result", {
662
- invocationId: data.invocationId,
663
- result,
664
- error
665
- });
666
- }
667
- // ─────────────────────────────────────────────────────────────────
668
- // Conversations
669
- // ─────────────────────────────────────────────────────────────────
670
- /**
671
- * Get list of conversations
672
- */
673
- async getConversations() {
674
- const response = await this.httpClient.get("/api/sdk/v1/conversations");
675
- return response.items.map((item) => ({
676
- id: item.id,
677
- title: item.title,
678
- lastMessageDate: new Date(item.last_message_date)
679
- }));
680
- }
681
- /**
682
- * Get a specific conversation with messages
683
- */
684
- async getConversation(conversationId) {
685
- const response = await this.httpClient.get(`/api/sdk/v1/conversations/${conversationId}`);
686
- return {
687
- id: response.id,
688
- title: response.title,
689
- lastMessageDate: new Date(response.last_message_date),
690
- messages: response.messages.map((m) => ({
691
- id: m.id,
692
- conversationId: response.id,
693
- content: m.content,
694
- role: m.role,
695
- status: m.status,
696
- createdAt: new Date(m.created_at)
697
- }))
698
- };
699
- }
700
- /**
701
- * Get messages for a conversation
702
- */
703
- async getMessages(conversationId) {
704
- const conversation = await this.getConversation(conversationId);
705
- return conversation.messages || [];
706
- }
707
- // ─────────────────────────────────────────────────────────────────
708
- // Tool Calls
709
- // ─────────────────────────────────────────────────────────────────
710
- /**
711
- * Submit form data for a tool call
712
- */
713
- async submitToolCallForm(toolCallId, formData) {
714
- await this.httpClient.post(`/api/tool-calls/${toolCallId}/submit/`, {
715
- formData
716
- });
717
- }
718
- /**
719
- * Confirm a tool call
720
- */
721
- async confirmToolCall(toolCallId) {
722
- await this.httpClient.post(`/api/tool-calls/${toolCallId}/confirm/`);
723
- }
724
- /**
725
- * Reject a tool call
726
- */
727
- async rejectToolCall(toolCallId) {
728
- await this.httpClient.post(`/api/tool-calls/${toolCallId}/reject/`);
729
- }
730
- // ─────────────────────────────────────────────────────────────────
731
- // Feedback
732
- // ─────────────────────────────────────────────────────────────────
733
- /**
734
- * Submit feedback for a message
735
- */
736
- async submitFeedback(messageId, rating) {
737
- await this.httpClient.post(`/api/sdk/v1/messages/${messageId}/feedback`, {
738
- rating
739
- });
740
- }
741
- registerFunction(nameOrDef, handler, schema) {
742
- if (typeof nameOrDef === "object") {
743
- this.functionRegistry.register(nameOrDef);
744
- } else {
745
- this.functionRegistry.register(nameOrDef, handler, schema);
746
- }
747
- }
748
- /**
749
- * Unregister a client-side function
750
- */
751
- unregisterFunction(name) {
752
- return this.functionRegistry.unregister(name);
753
- }
754
- /**
755
- * Get all registered function schemas
756
- */
757
- getRegisteredFunctions() {
758
- return this.functionRegistry.getSchemas();
759
- }
760
- /**
761
- * Register a navigation function that lets AGO navigate users to different pages.
762
- * @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
763
- * @param routes - Map of route names to paths, with descriptions for the LLM
764
- */
765
- registerNavigationFunction(navigate, routes) {
766
- const routeNames = routes.map((r) => r.name);
767
- const routeDescriptions = routes.map((r) => `- "${r.name}": ${r.description}`).join("\n");
768
- this.registerFunction(
769
- "navigateToPage",
770
- async (args) => {
771
- const pageName = args.page;
772
- const route = routes.find((r) => r.name === pageName);
773
- if (!route) {
774
- return { success: false, error: `Unknown page: ${pageName}` };
775
- }
776
- navigate(route.path);
777
- return { success: true, navigatedTo: route.path };
778
- },
779
- {
780
- description: `Navigate the user to a page in the application. Available pages:
781
- ${routeDescriptions}`,
782
- parameters: {
783
- type: "object",
784
- properties: {
785
- page: {
786
- type: "string",
787
- description: "The page to navigate to",
788
- enum: routeNames
789
- }
790
- },
791
- required: ["page"]
792
- }
793
- }
794
- );
795
- }
796
- // ─────────────────────────────────────────────────────────────────
797
- // Events
798
- // ─────────────────────────────────────────────────────────────────
799
- /**
800
- * Subscribe to an event
801
- */
802
- on(event, handler) {
803
- this.eventEmitter.on(event, handler);
804
- }
805
- /**
806
- * Unsubscribe from an event
807
- */
808
- off(event, handler) {
809
- this.eventEmitter.off(event, handler);
810
- }
811
- /**
812
- * Subscribe to an event once — auto-unsubscribes after the first call.
813
- */
814
- once(event, handler) {
815
- this.eventEmitter.once(event, handler);
816
- }
817
- /**
818
- * Returns a Promise that resolves the next time `event` fires.
819
- *
820
- * ```ts
821
- * const msg = await client.waitFor("message:complete", { timeout: 10000 });
822
- * ```
823
- */
824
- waitFor(event, options) {
825
- return this.eventEmitter.waitFor(event, options);
826
- }
827
- // ─────────────────────────────────────────────────────────────────
828
- // Configuration
829
- // ─────────────────────────────────────────────────────────────────
830
- /**
831
- * Update client configuration
832
- */
833
- updateConfig(config) {
834
- this.config = { ...this.config, ...config };
835
- this.httpClient.updateConfig(config);
836
- if (config.debug !== void 0) {
837
- config.debug ? logger.enable() : logger.disable();
838
- }
839
- }
840
- /**
841
- * Clean up resources
842
- */
843
- destroy() {
844
- this.eventEmitter.removeAllListeners();
845
- this.functionRegistry.clear();
846
- logger.log("AgoClient destroyed");
847
- }
848
- }
849
- exports.AgoApiError = AgoApiError;
850
- exports.AgoClient = AgoClient;
851
- exports.AgoError = AgoError;
852
- exports.AgoFunctionError = AgoFunctionError;
853
- exports.AgoNetworkError = AgoNetworkError;
854
- exports.AgoStreamError = AgoStreamError;
855
- exports.EventEmitter = EventEmitter;
856
- exports.FunctionRegistry = FunctionRegistry;
857
- exports.SSEHandler = SSEHandler;
858
- exports.isStreamNetworkError = isStreamNetworkError;
859
- exports.logger = logger;
860
- //# sourceMappingURL=AgoClient-xTWfMWKh.cjs.map