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