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