@useago/sdk 0.3.2 → 0.3.4

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 (121) hide show
  1. package/dist/AgoClient-DF7M2WAz.js +575 -0
  2. package/dist/AgoClient-bjN-z2ZQ.cjs +6 -0
  3. package/dist/angular.cjs +1 -143
  4. package/dist/angular.d.cts +530 -0
  5. package/dist/angular.d.ts +530 -2
  6. package/dist/angular.js +71 -139
  7. package/dist/createFormCollector-ClzHfaBd.js +185 -0
  8. package/dist/createFormCollector-H4Me_2uj.cjs +1 -0
  9. package/dist/createMockClient-C50gjV0b.js +71 -0
  10. package/dist/createMockClient-DQvFFWnc.cjs +1 -0
  11. package/dist/devtools.cjs +26 -100
  12. package/dist/devtools.d.cts +443 -0
  13. package/dist/devtools.d.ts +443 -2
  14. package/dist/devtools.js +68 -93
  15. package/dist/functions-BH1X5kas.cjs +1 -0
  16. package/dist/functions-CWSRi3xv.js +312 -0
  17. package/dist/helpers.cjs +1 -15
  18. package/dist/{helpers/functions.d.ts → helpers.d.cts} +121 -62
  19. package/dist/helpers.d.ts +121 -2
  20. package/dist/helpers.js +16 -2
  21. package/dist/index.cjs +1 -347
  22. package/dist/index.d.cts +1150 -0
  23. package/dist/index.d.ts +1150 -20
  24. package/dist/index.js +129 -298
  25. package/dist/react.cjs +31 -22438
  26. package/dist/react.d.cts +999 -0
  27. package/dist/react.d.ts +999 -2
  28. package/dist/react.js +8416 -22376
  29. package/dist/rolldown-runtime-CaekUdDJ.cjs +1 -0
  30. package/dist/rolldown-runtime-DxmricAu.js +25 -0
  31. package/dist/vue.cjs +1 -336
  32. package/dist/vue.d.cts +1063 -0
  33. package/dist/vue.d.ts +1063 -2
  34. package/dist/vue.js +174 -316
  35. package/dist/widget.cjs +1 -0
  36. package/dist/widget.d.cts +577 -0
  37. package/dist/widget.d.ts +577 -2
  38. package/dist/widget.js +398 -0
  39. package/package.json +35 -24
  40. package/dist/AgoClient-DPZdN5n2.js +0 -905
  41. package/dist/AgoClient-DPZdN5n2.js.map +0 -1
  42. package/dist/AgoClient-wMVUQqCD.cjs +0 -976
  43. package/dist/AgoClient-wMVUQqCD.cjs.map +0 -1
  44. package/dist/angular/ago.service.d.ts +0 -98
  45. package/dist/angular/index.d.ts +0 -4
  46. package/dist/angular/provide.d.ts +0 -27
  47. package/dist/angular.cjs.map +0 -1
  48. package/dist/angular.js.map +0 -1
  49. package/dist/api/HttpClient.d.ts +0 -31
  50. package/dist/api/index.d.ts +0 -1
  51. package/dist/auto/createAgo.d.ts +0 -39
  52. package/dist/auto/index.d.ts +0 -1
  53. package/dist/client/AgoClient.d.ts +0 -169
  54. package/dist/client/errors.d.ts +0 -48
  55. package/dist/client/index.d.ts +0 -3
  56. package/dist/client/types.d.ts +0 -205
  57. package/dist/createMockClient-Ci_N2tH8.cjs +0 -104
  58. package/dist/createMockClient-Ci_N2tH8.cjs.map +0 -1
  59. package/dist/createMockClient-U0ae_AYy.js +0 -99
  60. package/dist/createMockClient-U0ae_AYy.js.map +0 -1
  61. package/dist/devtools/index.d.ts +0 -2
  62. package/dist/devtools/initDevPanel.d.ts +0 -15
  63. package/dist/devtools.cjs.map +0 -1
  64. package/dist/devtools.js.map +0 -1
  65. package/dist/functions/FunctionRegistry.d.ts +0 -41
  66. package/dist/functions/defineFunction.d.ts +0 -22
  67. package/dist/functions/index.d.ts +0 -2
  68. package/dist/functions/types.d.ts +0 -50
  69. package/dist/functions--c6lx3ic.cjs +0 -480
  70. package/dist/functions--c6lx3ic.cjs.map +0 -1
  71. package/dist/functions-C9F1dnmh.js +0 -398
  72. package/dist/functions-C9F1dnmh.js.map +0 -1
  73. package/dist/helpers/factory.d.ts +0 -20
  74. package/dist/helpers/index.d.ts +0 -1
  75. package/dist/index.cjs.map +0 -1
  76. package/dist/index.js.map +0 -1
  77. package/dist/react/components/ChatInput.d.ts +0 -12
  78. package/dist/react/components/ChatWidget.d.ts +0 -35
  79. package/dist/react/components/Markdown.d.ts +0 -12
  80. package/dist/react/components/Message.d.ts +0 -9
  81. package/dist/react/components/index.d.ts +0 -8
  82. package/dist/react/context/AgoContext.d.ts +0 -62
  83. package/dist/react/context/index.d.ts +0 -2
  84. package/dist/react/hooks/index.d.ts +0 -7
  85. package/dist/react/hooks/useAgo.d.ts +0 -14
  86. package/dist/react/hooks/useAgoContext.d.ts +0 -40
  87. package/dist/react/hooks/useAgoFunction.d.ts +0 -58
  88. package/dist/react/hooks/useAgoStore.d.ts +0 -17
  89. package/dist/react/hooks/useChat.d.ts +0 -45
  90. package/dist/react/hooks/useConversation.d.ts +0 -28
  91. package/dist/react/hooks/useMessages.d.ts +0 -26
  92. package/dist/react/index.d.ts +0 -24
  93. package/dist/react/testing.d.ts +0 -2
  94. package/dist/react.cjs.map +0 -1
  95. package/dist/react.js.map +0 -1
  96. package/dist/rolldown-runtime-BqCkTl7Q.cjs +0 -50
  97. package/dist/rolldown-runtime-CNZpIYwj.js +0 -33
  98. package/dist/state/ClientContextRegistry.d.ts +0 -64
  99. package/dist/state/createStore.d.ts +0 -30
  100. package/dist/streaming/SSEHandler.d.ts +0 -46
  101. package/dist/streaming/helpers.d.ts +0 -67
  102. package/dist/streaming/index.d.ts +0 -2
  103. package/dist/testing/createMockClient.d.ts +0 -42
  104. package/dist/testing/index.d.ts +0 -2
  105. package/dist/utils/eventEmitter.d.ts +0 -23
  106. package/dist/utils/index.d.ts +0 -2
  107. package/dist/utils/logger.d.ts +0 -14
  108. package/dist/vue/composables/useAgo.d.ts +0 -17
  109. package/dist/vue/composables/useAgoEvents.d.ts +0 -11
  110. package/dist/vue/composables/useAgoFunction.d.ts +0 -34
  111. package/dist/vue/composables/useAgoStore.d.ts +0 -18
  112. package/dist/vue/composables/useChat.d.ts +0 -251
  113. package/dist/vue/composables/useConversation.d.ts +0 -178
  114. package/dist/vue/composables/useMessages.d.ts +0 -89
  115. package/dist/vue/index.d.ts +0 -11
  116. package/dist/vue/plugin.d.ts +0 -16
  117. package/dist/vue/symbols.d.ts +0 -3
  118. package/dist/vue.cjs.map +0 -1
  119. package/dist/vue.js.map +0 -1
  120. package/dist/widget/index.d.ts +0 -1
  121. package/dist/widget/types.d.ts +0 -43
@@ -0,0 +1,575 @@
1
+ var h = class extends Error {
2
+ constructor(e, t, r) {
3
+ super(e), this.code = t, this.statusCode = r, this.name = "AgoError";
4
+ }
5
+ }, l = class m extends h {
6
+ constructor(t, r, s, i, o, a) {
7
+ super(t, r, s), this.type = i, this.param = o, this.docUrl = a, this.name = "AgoApiError";
8
+ }
9
+ static fromResponse(t, r) {
10
+ const s = t.error;
11
+ return new m(s.message, s.code, r, s.type, s.param, s.doc_url);
12
+ }
13
+ }, d = class extends h {
14
+ constructor(e, t) {
15
+ super(e, "network_error"), this.originalError = t, this.name = "AgoNetworkError";
16
+ }
17
+ }, u = class extends h {
18
+ constructor(e) {
19
+ super(e, "stream_error"), this.name = "AgoStreamError";
20
+ }
21
+ }, g = class extends h {
22
+ constructor(e, t, r) {
23
+ super(e, "function_error"), this.functionName = t, this.originalError = r, this.name = "AgoFunctionError";
24
+ }
25
+ }, w = class {
26
+ constructor(e = !1) {
27
+ this.enabled = e;
28
+ }
29
+ enable() {
30
+ this.enabled = !0;
31
+ }
32
+ disable() {
33
+ this.enabled = !1;
34
+ }
35
+ log(...e) {
36
+ this.enabled && console.log("[AGO SDK]", ...e);
37
+ }
38
+ warn(...e) {
39
+ this.enabled && console.warn("[AGO SDK]", ...e);
40
+ }
41
+ error(...e) {
42
+ console.error("[AGO SDK]", ...e);
43
+ }
44
+ debug(...e) {
45
+ this.enabled && console.debug("[AGO SDK]", ...e);
46
+ }
47
+ }, n = new w(), f = "ago_widget_id";
48
+ function v() {
49
+ if (typeof localStorage < "u") {
50
+ const t = localStorage.getItem(f);
51
+ if (t) return t;
52
+ }
53
+ const e = crypto.randomUUID();
54
+ if (typeof localStorage < "u") try {
55
+ localStorage.setItem(f, e);
56
+ } catch {
57
+ }
58
+ return e;
59
+ }
60
+ var y = class {
61
+ constructor(e) {
62
+ this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-Widget-Id": e.widgetId || v() }, e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission && (this.headers["X-Widget-Permission"] = e.permission);
63
+ }
64
+ updateConfig(e) {
65
+ e.baseUrl && (this.baseUrl = e.baseUrl.replace(/\/$/, "")), e.widgetId && (this.headers["X-Widget-Id"] = e.widgetId), e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission !== void 0 && (e.permission ? this.headers["X-Widget-Permission"] = e.permission : delete this.headers["X-Widget-Permission"]);
66
+ }
67
+ async get(e) {
68
+ return this.request("GET", e);
69
+ }
70
+ async post(e, t) {
71
+ return this.request("POST", e, t);
72
+ }
73
+ async postStream(e, t) {
74
+ const r = `${this.baseUrl}${e}`;
75
+ n.debug("POST (stream)", r, t);
76
+ try {
77
+ const s = await fetch(r, {
78
+ method: "POST",
79
+ headers: {
80
+ ...this.headers,
81
+ "Content-Type": "application/json"
82
+ },
83
+ body: t ? JSON.stringify(t) : void 0
84
+ });
85
+ return s.ok || await this.handleErrorResponse(s), s;
86
+ } catch (s) {
87
+ throw s instanceof l ? s : new d(`Network error: ${s instanceof Error ? s.message : "Unknown error"}`, s instanceof Error ? s : void 0);
88
+ }
89
+ }
90
+ async postFormData(e, t) {
91
+ const r = `${this.baseUrl}${e}`;
92
+ n.debug("POST (formData)", r);
93
+ const s = { ...this.headers };
94
+ try {
95
+ const i = await fetch(r, {
96
+ method: "POST",
97
+ headers: s,
98
+ body: t
99
+ });
100
+ return i.ok || await this.handleErrorResponse(i), i;
101
+ } catch (i) {
102
+ throw i instanceof l ? i : new d(`Network error: ${i instanceof Error ? i.message : "Unknown error"}`, i instanceof Error ? i : void 0);
103
+ }
104
+ }
105
+ async request(e, t, r) {
106
+ const s = `${this.baseUrl}${t}`;
107
+ n.debug(e, s, r);
108
+ try {
109
+ const i = await fetch(s, {
110
+ method: e,
111
+ headers: {
112
+ ...this.headers,
113
+ "Content-Type": "application/json"
114
+ },
115
+ body: r ? JSON.stringify(r) : void 0
116
+ });
117
+ return i.ok || await this.handleErrorResponse(i), i.status === 204 ? void 0 : i.json();
118
+ } catch (i) {
119
+ throw i instanceof l ? i : new d(`Network error: ${i instanceof Error ? i.message : "Unknown error"}`, i instanceof Error ? i : void 0);
120
+ }
121
+ }
122
+ async handleErrorResponse(e) {
123
+ let t;
124
+ try {
125
+ t = await e.json();
126
+ } catch {
127
+ }
128
+ throw t?.error ? l.fromResponse(t, e.status) : new l(`HTTP ${e.status}: ${e.statusText}`, "http_error", e.status, "api_error");
129
+ }
130
+ }, C = class {
131
+ constructor() {
132
+ this.functions = /* @__PURE__ */ new Map();
133
+ }
134
+ register(e, t, r) {
135
+ if (typeof e == "object") {
136
+ const { name: i, handler: o, description: a, parameters: c } = e;
137
+ return this.register(i, o, {
138
+ description: a,
139
+ parameters: c
140
+ });
141
+ }
142
+ const s = e;
143
+ if (!t || !r) throw new Error("handler and schema are required");
144
+ this.functions.has(s) && n.warn(`Function "${s}" is being overwritten`), this.functions.set(s, {
145
+ schema: {
146
+ ...r,
147
+ name: s
148
+ },
149
+ handler: t
150
+ }), n.log(`Registered function: ${s}`);
151
+ }
152
+ unregister(e) {
153
+ const t = this.functions.delete(e);
154
+ return t && n.log(`Unregistered function: ${e}`), t;
155
+ }
156
+ get(e) {
157
+ return this.functions.get(e);
158
+ }
159
+ has(e) {
160
+ return this.functions.has(e);
161
+ }
162
+ getSchemas() {
163
+ return Array.from(this.functions.values()).map((e) => e.schema);
164
+ }
165
+ async execute(e, t) {
166
+ const r = this.functions.get(e);
167
+ if (!r) throw new g(`Function "${e}" is not registered`, e);
168
+ n.log(`Executing function: ${e}`, t);
169
+ try {
170
+ const s = await r.handler(t);
171
+ return n.log(`Function ${e} completed:`, s), s;
172
+ } catch (s) {
173
+ throw n.error(`Function ${e} failed:`, s), new g(`Function "${e}" execution failed: ${s instanceof Error ? s.message : "Unknown error"}`, e, s instanceof Error ? s : void 0);
174
+ }
175
+ }
176
+ clear() {
177
+ this.functions.clear(), n.log("Cleared all registered functions");
178
+ }
179
+ get size() {
180
+ return this.functions.size;
181
+ }
182
+ }, E = class {
183
+ constructor() {
184
+ this.entries = /* @__PURE__ */ new Map(), this.dynamicProviders = /* @__PURE__ */ new Map();
185
+ }
186
+ set(e, t) {
187
+ this.entries.set(e, t), n.log(`ClientContext set: ${e}`);
188
+ }
189
+ remove(e) {
190
+ const t = this.entries.delete(e);
191
+ return t && n.log(`ClientContext removed: ${e}`), t;
192
+ }
193
+ addDynamicProvider(e, t) {
194
+ this.dynamicProviders.set(e, t), n.log(`DynamicContext provider added: ${e}`);
195
+ }
196
+ removeDynamicProvider(e) {
197
+ const t = this.dynamicProviders.delete(e);
198
+ return t && n.log(`DynamicContext provider removed: ${e}`), t;
199
+ }
200
+ getSnapshot() {
201
+ if (this.entries.size === 0 && this.dynamicProviders.size === 0) return null;
202
+ const e = {};
203
+ for (const [t, r] of this.entries) e[t] = r;
204
+ for (const [t, r] of this.dynamicProviders) try {
205
+ const s = r();
206
+ s && (e[t] = s);
207
+ } catch (s) {
208
+ n.error(`DynamicContext provider "${t}" threw:`, s);
209
+ }
210
+ return Object.keys(e).length === 0 ? null : { entries: e };
211
+ }
212
+ clear() {
213
+ this.entries.clear(), this.dynamicProviders.clear(), n.log("ClientContext cleared");
214
+ }
215
+ }, b = class {
216
+ constructor(e) {
217
+ this.callbacks = e, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0;
218
+ }
219
+ async processStream(e) {
220
+ if (!e.body) throw new u("Response has no body");
221
+ const t = e.body.getReader(), r = new TextDecoder();
222
+ try {
223
+ for (; ; ) {
224
+ const { done: s, value: i } = await t.read();
225
+ if (s) break;
226
+ const o = r.decode(i, { stream: !0 });
227
+ this.buffer += o, this.processBuffer();
228
+ }
229
+ return this.buffer.trim() && this.processBuffer(), this.buildFinalMessage();
230
+ } catch (s) {
231
+ const i = s instanceof Error ? s : new u("Stream processing failed");
232
+ throw this.callbacks.onError?.(i), i;
233
+ } finally {
234
+ t.releaseLock();
235
+ }
236
+ }
237
+ processBuffer() {
238
+ const e = this.buffer.split(`
239
+
240
+ `);
241
+ this.buffer = e.pop() || "";
242
+ for (const t of e) {
243
+ if (!t.trim()) continue;
244
+ const r = t.split(`
245
+ `);
246
+ for (const s of r)
247
+ if (!s.startsWith(": ") && s.startsWith("data: ")) {
248
+ const i = s.slice(6);
249
+ try {
250
+ const o = JSON.parse(i);
251
+ this.handleChunk(o);
252
+ } catch (o) {
253
+ n.warn("Failed to parse SSE data:", i, o);
254
+ }
255
+ }
256
+ }
257
+ }
258
+ handleChunk(e) {
259
+ if (e.message_id && !this.message.id && (this.message.id = e.message_id), e.thread?.id && (this.message.conversationId = e.thread.id, this.isFirstChunk && this.message.id && (this.isFirstChunk = !1, this.callbacks.onStart?.({
260
+ conversationId: this.message.conversationId,
261
+ messageId: this.message.id
262
+ }))), e.content !== void 0 && (this.message.content = (this.message.content || "") + e.content, this.message.conversationId && this.message.id && this.callbacks.onChunk?.({
263
+ content: e.content,
264
+ conversationId: this.message.conversationId,
265
+ messageId: this.message.id
266
+ })), e.full_content !== void 0 && (this.message.content = e.full_content), e.status && (this.message.status = e.status), e.agent && (this.message.agent = {
267
+ id: e.agent.id,
268
+ name: e.agent.name,
269
+ displayName: e.agent.display_name
270
+ }), e.knowledge_sources && (this.sources = e.knowledge_sources.map((t) => {
271
+ const r = t.knowledge_document;
272
+ return {
273
+ id: r.id,
274
+ title: r.title,
275
+ url: r.use_external_link ? r.external_link_url : r.internal_link_url
276
+ };
277
+ })), e.type === "client_function" && e.function_name && this.callbacks.onClientFunction?.({
278
+ invocationId: e.id || "",
279
+ functionName: e.function_name,
280
+ arguments: e.arguments || {},
281
+ conversationId: this.message.conversationId || ""
282
+ }), e.tool_call_data && e.type && e.type !== "client_function") {
283
+ const t = this.parseToolCall(e);
284
+ this.callbacks.onToolCall?.(t);
285
+ const r = this.toolCalls.findIndex((s) => s.id === t.id);
286
+ r >= 0 ? this.toolCalls[r] = t : this.toolCalls.push(t);
287
+ }
288
+ e.follow_up_replies && (this.followUpReplies = e.follow_up_replies);
289
+ }
290
+ parseToolCall(e) {
291
+ return {
292
+ id: e.id || "",
293
+ type: e.type || "status_message",
294
+ status: e.status || "unknown",
295
+ toolName: e.tool_name || "",
296
+ toolDisplayName: e.tool_display_name,
297
+ message: e.message,
298
+ formSchema: e.form_schema,
299
+ data: e.data,
300
+ functionName: e.function_name,
301
+ arguments: e.arguments
302
+ };
303
+ }
304
+ buildFinalMessage() {
305
+ const e = {
306
+ id: this.message.id || "",
307
+ conversationId: this.message.conversationId || "",
308
+ content: this.message.content || "",
309
+ role: "assistant",
310
+ status: this.message.status || "DONE",
311
+ agent: this.message.agent,
312
+ sources: this.sources.length > 0 ? this.sources : void 0,
313
+ toolCalls: this.toolCalls.length > 0 ? this.toolCalls : void 0,
314
+ followUpReplies: this.followUpReplies.length > 0 ? this.followUpReplies : void 0,
315
+ createdAt: /* @__PURE__ */ new Date()
316
+ };
317
+ return this.callbacks.onComplete?.(e), e;
318
+ }
319
+ };
320
+ function k(e) {
321
+ const t = e.message.toLowerCase();
322
+ return t.includes("load failed") || t.includes("failed to fetch") || t.includes("network") || t.includes("abort");
323
+ }
324
+ var _ = class {
325
+ constructor() {
326
+ this.handlers = /* @__PURE__ */ new Map();
327
+ }
328
+ on(e, t) {
329
+ this.handlers.has(e) || this.handlers.set(e, /* @__PURE__ */ new Set()), this.handlers.get(e).add(t);
330
+ }
331
+ off(e, t) {
332
+ const r = this.handlers.get(e);
333
+ r && r.delete(t);
334
+ }
335
+ emit(e, t) {
336
+ const r = this.handlers.get(e);
337
+ r && r.forEach((s) => {
338
+ try {
339
+ s(t);
340
+ } catch (i) {
341
+ console.error(`Error in event handler for ${String(e)}:`, i);
342
+ }
343
+ });
344
+ }
345
+ once(e, t) {
346
+ const r = ((s) => {
347
+ this.off(e, r), t(s);
348
+ });
349
+ this.on(e, r);
350
+ }
351
+ waitFor(e, t) {
352
+ return new Promise((r, s) => {
353
+ let i;
354
+ const o = ((a) => {
355
+ i && clearTimeout(i), r(a);
356
+ });
357
+ this.once(e, o), t?.timeout && (i = setTimeout(() => {
358
+ this.off(e, o), s(/* @__PURE__ */ new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`));
359
+ }, t.timeout));
360
+ });
361
+ }
362
+ removeAllListeners(e) {
363
+ e ? this.handlers.delete(e) : this.handlers.clear();
364
+ }
365
+ }, S = class {
366
+ constructor(e) {
367
+ this.config = e, this.httpClient = new y(e), this.functionRegistry = new C(), this.contextRegistry = new E(), this.eventEmitter = new _(), e.debug && n.enable(), n.log("AgoClient initialized");
368
+ }
369
+ async sendMessage(e, t) {
370
+ const r = this.functionRegistry.getSchemas(), s = this.contextRegistry.getSnapshot(), i = this.config.agent || this.config.defaultAgentId, o = {
371
+ content: e,
372
+ conversation_id: t?.conversationId,
373
+ agent_id: t?.agentId || i
374
+ };
375
+ r.length > 0 && (o.client_functions = r), s && (o.client_context = s);
376
+ let a;
377
+ if (t?.files && t.files.length > 0) {
378
+ const c = new FormData();
379
+ c.append("content", e), t.conversationId && c.append("conversation_id", t.conversationId), (t.agentId || i) && c.append("agent_id", t.agentId || i || ""), r.length > 0 && c.append("client_functions", JSON.stringify(r)), s && c.append("client_context", JSON.stringify(s));
380
+ for (const p of t.files) c.append("files", p);
381
+ a = await this.httpClient.postFormData("/api/sdk/v1/messages", c);
382
+ } else a = await this.httpClient.postStream("/api/sdk/v1/messages", o);
383
+ return this.processSSEResponse(a);
384
+ }
385
+ async processSSEResponse(e) {
386
+ return new b({
387
+ onStart: (t) => {
388
+ this.eventEmitter.emit("message:start", t);
389
+ },
390
+ onChunk: (t) => {
391
+ this.eventEmitter.emit("message:chunk", t);
392
+ },
393
+ onToolCall: (t) => {
394
+ this.eventEmitter.emit("toolCall:received", t), t.type === "form" && this.eventEmitter.emit("toolCall:form", t);
395
+ },
396
+ onClientFunction: async (t) => {
397
+ this.eventEmitter.emit("function:invoke", t), await this.handleClientFunctionInvocation(t);
398
+ },
399
+ onComplete: (t) => {
400
+ this.eventEmitter.emit("message:complete", t);
401
+ },
402
+ onError: (t) => {
403
+ this.eventEmitter.emit("message:error", { error: t.message });
404
+ }
405
+ }).processStream(e);
406
+ }
407
+ async handleClientFunctionInvocation(e) {
408
+ let t, r;
409
+ try {
410
+ t = await this.functionRegistry.execute(e.functionName, e.arguments);
411
+ } catch (s) {
412
+ r = s instanceof Error ? s.message : "Unknown error", n.error("Client function execution failed:", s);
413
+ }
414
+ if (e.invocationId) try {
415
+ await this.submitToolCallForm(e.invocationId, {
416
+ result: t,
417
+ error: r,
418
+ _type: "client_function_result"
419
+ });
420
+ } catch (s) {
421
+ n.error("Failed to submit function result:", s);
422
+ }
423
+ this.eventEmitter.emit("function:result", {
424
+ invocationId: e.invocationId,
425
+ result: t,
426
+ error: r
427
+ });
428
+ }
429
+ async getConversations() {
430
+ return (await this.httpClient.get("/api/sdk/v1/conversations")).items.map((e) => ({
431
+ id: e.id,
432
+ title: e.title,
433
+ lastMessageDate: new Date(e.last_message_date)
434
+ }));
435
+ }
436
+ async getConversation(e) {
437
+ const t = await this.httpClient.get(`/api/sdk/v1/conversations/${e}`);
438
+ return {
439
+ id: t.id,
440
+ title: t.title,
441
+ lastMessageDate: new Date(t.last_message_date),
442
+ messages: t.messages.map((r) => ({
443
+ id: r.id,
444
+ conversationId: t.id,
445
+ content: r.content,
446
+ role: r.role,
447
+ status: r.status,
448
+ createdAt: new Date(r.created_at)
449
+ }))
450
+ };
451
+ }
452
+ async getMessages(e) {
453
+ return (await this.getConversation(e)).messages || [];
454
+ }
455
+ async submitToolCallForm(e, t) {
456
+ await this.httpClient.post(`/api/sdk/v1/tool-calls/${e}/submit`, { formData: t });
457
+ }
458
+ async confirmToolCall(e) {
459
+ await this.httpClient.post(`/api/tool-calls/${e}/confirm/`);
460
+ }
461
+ async rejectToolCall(e) {
462
+ await this.httpClient.post(`/api/tool-calls/${e}/reject/`);
463
+ }
464
+ async submitFormCollector(e, t) {
465
+ return this.httpClient.post("/api/sdk/v1/forms/submit", {
466
+ destination: e,
467
+ values: t
468
+ });
469
+ }
470
+ async submitFeedback(e, t) {
471
+ await this.httpClient.post(`/api/sdk/v1/messages/${e}/feedback`, { rating: t });
472
+ }
473
+ registerFunction(e, t, r) {
474
+ typeof e == "object" ? this.functionRegistry.register(e) : this.functionRegistry.register(e, t, r);
475
+ }
476
+ register(e) {
477
+ if (Array.isArray(e)) for (const t of e) this.functionRegistry.register(t);
478
+ else this.functionRegistry.register(e);
479
+ }
480
+ unregisterFunction(e) {
481
+ return this.functionRegistry.unregister(e);
482
+ }
483
+ getRegisteredFunctions() {
484
+ return this.functionRegistry.getSchemas();
485
+ }
486
+ registerNavigationFunction(e, t) {
487
+ const r = t.map((i) => i.name), s = t.map((i) => `- "${i.name}": ${i.description}`).join(`
488
+ `);
489
+ this.registerFunction("navigateToPage", async (i) => {
490
+ const o = i.page, a = t.find((c) => c.name === o);
491
+ return a ? (e(a.path), {
492
+ success: !0,
493
+ navigatedTo: a.path
494
+ }) : {
495
+ success: !1,
496
+ error: `Unknown page: ${o}`
497
+ };
498
+ }, {
499
+ description: `Navigate the user to a page in the application. Available pages:
500
+ ${s}`,
501
+ parameters: {
502
+ type: "object",
503
+ properties: { page: {
504
+ type: "string",
505
+ description: "The page to navigate to",
506
+ enum: r
507
+ } },
508
+ required: ["page"]
509
+ }
510
+ });
511
+ }
512
+ setContext(e, t) {
513
+ this.contextRegistry.set(e, t);
514
+ }
515
+ removeContext(e) {
516
+ return this.contextRegistry.remove(e);
517
+ }
518
+ addDynamicContext(e, t) {
519
+ this.contextRegistry.addDynamicProvider(e, t);
520
+ }
521
+ removeDynamicContext(e) {
522
+ return this.contextRegistry.removeDynamicProvider(e);
523
+ }
524
+ enableAutoPageContext() {
525
+ this.contextRegistry.addDynamicProvider("browser-page", () => {
526
+ const e = typeof window < "u" ? window.location.href : void 0, t = typeof document < "u" ? document.title : void 0;
527
+ return !e && !t ? null : {
528
+ name: "Browser page",
529
+ description: "Current page the user is viewing",
530
+ data: {
531
+ url: e,
532
+ title: t
533
+ }
534
+ };
535
+ });
536
+ }
537
+ getContextSnapshot() {
538
+ return this.contextRegistry.getSnapshot();
539
+ }
540
+ on(e, t) {
541
+ this.eventEmitter.on(e, t);
542
+ }
543
+ off(e, t) {
544
+ this.eventEmitter.off(e, t);
545
+ }
546
+ once(e, t) {
547
+ this.eventEmitter.once(e, t);
548
+ }
549
+ waitFor(e, t) {
550
+ return this.eventEmitter.waitFor(e, t);
551
+ }
552
+ updateConfig(e) {
553
+ this.config = {
554
+ ...this.config,
555
+ ...e
556
+ }, this.httpClient.updateConfig(e), e.debug !== void 0 && (e.debug ? n.enable() : n.disable());
557
+ }
558
+ destroy() {
559
+ this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), n.log("AgoClient destroyed");
560
+ }
561
+ };
562
+ export {
563
+ E as a,
564
+ l as c,
565
+ d,
566
+ u as f,
567
+ k as i,
568
+ h as l,
569
+ _ as n,
570
+ C as o,
571
+ b as r,
572
+ n as s,
573
+ S as t,
574
+ g as u
575
+ };
@@ -0,0 +1,6 @@
1
+ var u=class extends Error{constructor(e,t,s){super(e),this.code=t,this.statusCode=s,this.name="AgoError"}},l=class m extends u{constructor(t,s,r,n,o,a){super(t,s,r),this.type=n,this.param=o,this.docUrl=a,this.name="AgoApiError"}static fromResponse(t,s){const r=t.error;return new m(r.message,r.code,s,r.type,r.param,r.doc_url)}},h=class extends u{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},d=class extends u{constructor(e){super(e,"stream_error"),this.name="AgoStreamError"}},g=class extends u{constructor(e,t,s){super(e,"function_error"),this.functionName=t,this.originalError=s,this.name="AgoFunctionError"}},C=class{constructor(e=!1){this.enabled=e}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...e){this.enabled&&console.log("[AGO SDK]",...e)}warn(...e){this.enabled&&console.warn("[AGO SDK]",...e)}error(...e){console.error("[AGO SDK]",...e)}debug(...e){this.enabled&&console.debug("[AGO SDK]",...e)}},i=new C,f="ago_widget_id";function E(){if(typeof localStorage<"u"){const t=localStorage.getItem(f);if(t)return t}const e=crypto.randomUUID();if(typeof localStorage<"u")try{localStorage.setItem(f,e)}catch{}return e}var _=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-Widget-Id":e.widgetId||E()},e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission&&(this.headers["X-Widget-Permission"]=e.permission)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-Widget-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"])}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async postStream(e,t){const s=`${this.baseUrl}${e}`;i.debug("POST (stream)",s,t);try{const r=await fetch(s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0});return r.ok||await this.handleErrorResponse(r),r}catch(r){throw r instanceof l?r:new h(`Network error: ${r instanceof Error?r.message:"Unknown error"}`,r instanceof Error?r:void 0)}}async postFormData(e,t){const s=`${this.baseUrl}${e}`;i.debug("POST (formData)",s);const r={...this.headers};try{const n=await fetch(s,{method:"POST",headers:r,body:t});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof l?n:new h(`Network error: ${n instanceof Error?n.message:"Unknown error"}`,n instanceof Error?n:void 0)}}async request(e,t,s){const r=`${this.baseUrl}${t}`;i.debug(e,r,s);try{const n=await fetch(r,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});return n.ok||await this.handleErrorResponse(n),n.status===204?void 0:n.json()}catch(n){throw n instanceof l?n:new h(`Network error: ${n instanceof Error?n.message:"Unknown error"}`,n instanceof Error?n:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}throw t?.error?l.fromResponse(t,e.status):new l(`HTTP ${e.status}: ${e.statusText}`,"http_error",e.status,"api_error")}},p=class{constructor(){this.functions=new Map}register(e,t,s){if(typeof e=="object"){const{name:n,handler:o,description:a,parameters:c}=e;return this.register(n,o,{description:a,parameters:c})}const r=e;if(!t||!s)throw new Error("handler and schema are required");this.functions.has(r)&&i.warn(`Function "${r}" is being overwritten`),this.functions.set(r,{schema:{...s,name:r},handler:t}),i.log(`Registered function: ${r}`)}unregister(e){const t=this.functions.delete(e);return t&&i.log(`Unregistered function: ${e}`),t}get(e){return this.functions.get(e)}has(e){return this.functions.has(e)}getSchemas(){return Array.from(this.functions.values()).map(e=>e.schema)}async execute(e,t){const s=this.functions.get(e);if(!s)throw new g(`Function "${e}" is not registered`,e);i.log(`Executing function: ${e}`,t);try{const r=await s.handler(t);return i.log(`Function ${e} completed:`,r),r}catch(r){throw i.error(`Function ${e} failed:`,r),new g(`Function "${e}" execution failed: ${r instanceof Error?r.message:"Unknown error"}`,e,r instanceof Error?r:void 0)}}clear(){this.functions.clear(),i.log("Cleared all registered functions")}get size(){return this.functions.size}},y=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),i.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&i.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),i.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&i.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,s]of this.entries)e[t]=s;for(const[t,s]of this.dynamicProviders)try{const r=s();r&&(e[t]=r)}catch(r){i.error(`DynamicContext provider "${t}" threw:`,r)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),i.log("ClientContext cleared")}},w=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0}async processStream(e){if(!e.body)throw new d("Response has no body");const t=e.body.getReader(),s=new TextDecoder;try{for(;;){const{done:r,value:n}=await t.read();if(r)break;const o=s.decode(n,{stream:!0});this.buffer+=o,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(r){const n=r instanceof Error?r:new d("Stream processing failed");throw this.callbacks.onError?.(n),n}finally{t.releaseLock()}}processBuffer(){const e=this.buffer.split(`
2
+
3
+ `);this.buffer=e.pop()||"";for(const t of e){if(!t.trim())continue;const s=t.split(`
4
+ `);for(const r of s)if(!r.startsWith(": ")&&r.startsWith("data: ")){const n=r.slice(6);try{const o=JSON.parse(n);this.handleChunk(o)}catch(o){i.warn("Failed to parse SSE data:",n,o)}}}}handleChunk(e){if(e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const s=t.knowledge_document;return{id:s.id,title:s.title,url:s.use_external_link?s.external_link_url:s.internal_link_url}})),e.type==="client_function"&&e.function_name&&this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}),e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const s=this.toolCalls.findIndex(r=>r.id===t.id);s>=0?this.toolCalls[s]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies)}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildFinalMessage(){const e={id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date};return this.callbacks.onComplete?.(e),e}};function k(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var v=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const s=this.handlers.get(e);s&&s.delete(t)}emit(e,t){const s=this.handlers.get(e);s&&s.forEach(r=>{try{r(t)}catch(n){console.error(`Error in event handler for ${String(e)}:`,n)}})}once(e,t){const s=(r=>{this.off(e,s),t(r)});this.on(e,s)}waitFor(e,t){return new Promise((s,r)=>{let n;const o=(a=>{n&&clearTimeout(n),s(a)});this.once(e,o),t?.timeout&&(n=setTimeout(()=>{this.off(e,o),r(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},S=class{constructor(e){this.config=e,this.httpClient=new _(e),this.functionRegistry=new p,this.contextRegistry=new y,this.eventEmitter=new v,e.debug&&i.enable(),i.log("AgoClient initialized")}async sendMessage(e,t){const s=this.functionRegistry.getSchemas(),r=this.contextRegistry.getSnapshot(),n=this.config.agent||this.config.defaultAgentId,o={content:e,conversation_id:t?.conversationId,agent_id:t?.agentId||n};s.length>0&&(o.client_functions=s),r&&(o.client_context=r);let a;if(t?.files&&t.files.length>0){const c=new FormData;c.append("content",e),t.conversationId&&c.append("conversation_id",t.conversationId),(t.agentId||n)&&c.append("agent_id",t.agentId||n||""),s.length>0&&c.append("client_functions",JSON.stringify(s)),r&&c.append("client_context",JSON.stringify(r));for(const b of t.files)c.append("files",b);a=await this.httpClient.postFormData("/api/sdk/v1/messages",c)}else a=await this.httpClient.postStream("/api/sdk/v1/messages",o);return this.processSSEResponse(a)}async processSSEResponse(e){return new w({onStart:t=>{this.eventEmitter.emit("message:start",t)},onChunk:t=>{this.eventEmitter.emit("message:chunk",t)},onToolCall:t=>{this.eventEmitter.emit("toolCall:received",t),t.type==="form"&&this.eventEmitter.emit("toolCall:form",t)},onClientFunction:async t=>{this.eventEmitter.emit("function:invoke",t),await this.handleClientFunctionInvocation(t)},onComplete:t=>{this.eventEmitter.emit("message:complete",t)},onError:t=>{this.eventEmitter.emit("message:error",{error:t.message})}}).processStream(e)}async handleClientFunctionInvocation(e){let t,s;try{t=await this.functionRegistry.execute(e.functionName,e.arguments)}catch(r){s=r instanceof Error?r.message:"Unknown error",i.error("Client function execution failed:",r)}if(e.invocationId)try{await this.submitToolCallForm(e.invocationId,{result:t,error:s,_type:"client_function_result"})}catch(r){i.error("Failed to submit function result:",r)}this.eventEmitter.emit("function:result",{invocationId:e.invocationId,result:t,error:s})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(e=>({id:e.id,title:e.title,lastMessageDate:new Date(e.last_message_date)}))}async getConversation(e){const t=await this.httpClient.get(`/api/sdk/v1/conversations/${e}`);return{id:t.id,title:t.title,lastMessageDate:new Date(t.last_message_date),messages:t.messages.map(s=>({id:s.id,conversationId:t.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at)}))}}async getMessages(e){return(await this.getConversation(e)).messages||[]}async submitToolCallForm(e,t){await this.httpClient.post(`/api/sdk/v1/tool-calls/${e}/submit`,{formData:t})}async confirmToolCall(e){await this.httpClient.post(`/api/tool-calls/${e}/confirm/`)}async rejectToolCall(e){await this.httpClient.post(`/api/tool-calls/${e}/reject/`)}async submitFormCollector(e,t){return this.httpClient.post("/api/sdk/v1/forms/submit",{destination:e,values:t})}async submitFeedback(e,t){await this.httpClient.post(`/api/sdk/v1/messages/${e}/feedback`,{rating:t})}registerFunction(e,t,s){typeof e=="object"?this.functionRegistry.register(e):this.functionRegistry.register(e,t,s)}register(e){if(Array.isArray(e))for(const t of e)this.functionRegistry.register(t);else this.functionRegistry.register(e)}unregisterFunction(e){return this.functionRegistry.unregister(e)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(e,t){const s=t.map(n=>n.name),r=t.map(n=>`- "${n.name}": ${n.description}`).join(`
5
+ `);this.registerFunction("navigateToPage",async n=>{const o=n.page,a=t.find(c=>c.name===o);return a?(e(a.path),{success:!0,navigatedTo:a.path}):{success:!1,error:`Unknown page: ${o}`}},{description:`Navigate the user to a page in the application. Available pages:
6
+ ${r}`,parameters:{type:"object",properties:{page:{type:"string",description:"The page to navigate to",enum:s}},required:["page"]}})}setContext(e,t){this.contextRegistry.set(e,t)}removeContext(e){return this.contextRegistry.remove(e)}addDynamicContext(e,t){this.contextRegistry.addDynamicProvider(e,t)}removeDynamicContext(e){return this.contextRegistry.removeDynamicProvider(e)}enableAutoPageContext(){this.contextRegistry.addDynamicProvider("browser-page",()=>{const e=typeof window<"u"?window.location.href:void 0,t=typeof document<"u"?document.title:void 0;return!e&&!t?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:e,title:t}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}once(e,t){this.eventEmitter.once(e,t)}waitFor(e,t){return this.eventEmitter.waitFor(e,t)}updateConfig(e){this.config={...this.config,...e},this.httpClient.updateConfig(e),e.debug!==void 0&&(e.debug?i.enable():i.disable())}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),i.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return l}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return S}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return u}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return g}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return d}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return y}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return v}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return p}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return w}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return k}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return i}});