@useago/sdk 0.1.6 → 0.2.0

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