@useago/sdk 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,28 @@
1
- var d = class extends Error {
1
+ var h = class extends Error {
2
2
  constructor(e, t, s) {
3
3
  super(e), this.code = t, this.statusCode = s, this.name = "AgoError";
4
4
  }
5
- }, h = class p extends d {
6
- constructor(t, s, r, i, o, a) {
7
- super(t, s, r), this.type = i, this.param = o, this.docUrl = a, this.name = "AgoApiError";
5
+ }, d = class v extends h {
6
+ constructor(t, s, n, i, r, a) {
7
+ super(t, s, n), this.type = i, this.param = r, this.docUrl = a, this.name = "AgoApiError";
8
8
  }
9
9
  static fromResponse(t, s) {
10
- const r = t.error;
11
- return new p(r.message, r.code, s, r.type, r.param, r.doc_url);
10
+ const n = t.error;
11
+ return new v(n.doc_url ? `${n.message} See ${n.doc_url}` : n.message, n.code, s, n.type, n.param, n.doc_url);
12
12
  }
13
- }, u = class extends d {
13
+ }, u = class extends h {
14
14
  constructor(e, t) {
15
15
  super(e, "network_error"), this.originalError = t, this.name = "AgoNetworkError";
16
16
  }
17
- }, m = class extends d {
18
- constructor(e) {
19
- super(e, "stream_error"), this.name = "AgoStreamError";
17
+ }, m = class extends h {
18
+ constructor(e, t = "stream_error") {
19
+ super(e, t), this.name = "AgoStreamError";
20
20
  }
21
- }, g = class extends d {
21
+ }, g = class extends h {
22
22
  constructor(e, t, s) {
23
23
  super(e, "function_error"), this.functionName = t, this.originalError = s, this.name = "AgoFunctionError";
24
24
  }
25
- }, y = class {
25
+ }, E = class {
26
26
  constructor(e = !1) {
27
27
  this.enabled = e;
28
28
  }
@@ -44,25 +44,25 @@ var d = class extends Error {
44
44
  debug(...e) {
45
45
  this.enabled && console.debug("[AGO SDK]", ...e);
46
46
  }
47
- }, n = new y(), f = "ago_widget_id";
48
- function C() {
47
+ }, o = new E(), f = "ago_widget_id";
48
+ function _() {
49
49
  if (typeof localStorage < "u") {
50
50
  const t = localStorage.getItem(f);
51
51
  if (t) return t;
52
52
  }
53
- const e = crypto.randomUUID();
53
+ const e = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
54
54
  if (typeof localStorage < "u") try {
55
55
  localStorage.setItem(f, e);
56
56
  } catch {
57
57
  }
58
58
  return e;
59
59
  }
60
- var E = class {
60
+ var S = class {
61
61
  constructor(e) {
62
- this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-Widget-Id": e.widgetId || C() }, 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);
62
+ this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-User-Anon-Id": e.widgetId || _() }, 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
63
  }
64
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"]);
65
+ e.baseUrl && (this.baseUrl = e.baseUrl.replace(/\/$/, "")), e.widgetId && (this.headers["X-User-Anon-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
66
  }
67
67
  async get(e) {
68
68
  return this.request("GET", e);
@@ -72,9 +72,9 @@ var E = class {
72
72
  }
73
73
  async postStream(e, t) {
74
74
  const s = `${this.baseUrl}${e}`;
75
- n.debug("POST (stream)", s, t);
75
+ o.debug("POST (stream)", s, t);
76
76
  try {
77
- const r = await fetch(s, {
77
+ const n = await fetch(s, {
78
78
  method: "POST",
79
79
  headers: {
80
80
  ...this.headers,
@@ -82,31 +82,31 @@ var E = class {
82
82
  },
83
83
  body: t ? JSON.stringify(t) : void 0
84
84
  });
85
- return r.ok || await this.handleErrorResponse(r), r;
86
- } catch (r) {
87
- throw r instanceof h ? r : new u(`Network error: ${r instanceof Error ? r.message : "Unknown error"}`, r instanceof Error ? r : void 0);
85
+ return n.ok || await this.handleErrorResponse(n), n;
86
+ } catch (n) {
87
+ throw n instanceof d ? n : new u(`Network error: ${n instanceof Error ? n.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, n instanceof Error ? n : void 0);
88
88
  }
89
89
  }
90
90
  async postFormData(e, t) {
91
91
  const s = `${this.baseUrl}${e}`;
92
- n.debug("POST (formData)", s);
93
- const r = { ...this.headers };
92
+ o.debug("POST (formData)", s);
93
+ const n = { ...this.headers };
94
94
  try {
95
95
  const i = await fetch(s, {
96
96
  method: "POST",
97
- headers: r,
97
+ headers: n,
98
98
  body: t
99
99
  });
100
100
  return i.ok || await this.handleErrorResponse(i), i;
101
101
  } catch (i) {
102
- throw i instanceof h ? i : new u(`Network error: ${i instanceof Error ? i.message : "Unknown error"}`, i instanceof Error ? i : void 0);
102
+ throw i instanceof d ? i : new u(`Network error: ${i instanceof Error ? i.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, i instanceof Error ? i : void 0);
103
103
  }
104
104
  }
105
105
  async request(e, t, s) {
106
- const r = `${this.baseUrl}${t}`;
107
- n.debug(e, r, s);
106
+ const n = `${this.baseUrl}${t}`;
107
+ o.debug(e, n, s);
108
108
  try {
109
- const i = await fetch(r, {
109
+ const i = await fetch(n, {
110
110
  method: e,
111
111
  headers: {
112
112
  ...this.headers,
@@ -116,7 +116,7 @@ var E = class {
116
116
  });
117
117
  return i.ok || await this.handleErrorResponse(i), i.status === 204 ? void 0 : i.json();
118
118
  } catch (i) {
119
- throw i instanceof h ? i : new u(`Network error: ${i instanceof Error ? i.message : "Unknown error"}`, i instanceof Error ? i : void 0);
119
+ throw i instanceof d ? i : new u(`Network error: ${i instanceof Error ? i.message : "Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`, i instanceof Error ? i : void 0);
120
120
  }
121
121
  }
122
122
  async handleErrorResponse(e) {
@@ -125,33 +125,35 @@ var E = class {
125
125
  t = await e.json();
126
126
  } catch {
127
127
  }
128
- throw t?.error ? h.fromResponse(t, e.status) : new h(`HTTP ${e.status}: ${e.statusText}`, "http_error", e.status, "api_error");
128
+ if (t?.error) throw d.fromResponse(t, e.status);
129
+ let s = "";
130
+ throw e.status === 401 || e.status === 403 ? s = " Check `userJwt` (and that it has not expired)." : e.status === 404 && (s = " Check that `baseUrl` points at your AGO API root."), new d(`HTTP ${e.status}: ${e.statusText}.${s}`, "http_error", e.status, "api_error");
129
131
  }
130
- }, b = class {
132
+ }, k = class {
131
133
  constructor() {
132
134
  this.functions = /* @__PURE__ */ new Map();
133
135
  }
134
136
  register(e, t, s) {
135
137
  if (typeof e == "object") {
136
- const { name: i, handler: o, description: a, parameters: c } = e;
137
- return this.register(i, o, {
138
+ const { name: i, handler: r, description: a, parameters: l } = e;
139
+ return this.register(i, r, {
138
140
  description: a,
139
- parameters: c
141
+ parameters: l
140
142
  });
141
143
  }
142
- const r = e;
143
- if (!t || !s) throw new Error("handler and schema are required");
144
- this.functions.has(r) && n.warn(`Function "${r}" is being overwritten`), this.functions.set(r, {
144
+ const n = e;
145
+ if (!t || !s) throw new h(`registerFunction("${n}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`, "function_invalid_registration");
146
+ this.functions.has(n) && o.warn(`Function "${n}" is being overwritten`), this.functions.set(n, {
145
147
  schema: {
146
148
  ...s,
147
- name: r
149
+ name: n
148
150
  },
149
151
  handler: t
150
- }), n.log(`Registered function: ${r}`);
152
+ }), o.log(`Registered function: ${n}`);
151
153
  }
152
154
  unregister(e) {
153
155
  const t = this.functions.delete(e);
154
- return t && n.log(`Unregistered function: ${e}`), t;
156
+ return t && o.log(`Unregistered function: ${e}`), t;
155
157
  }
156
158
  get(e) {
157
159
  return this.functions.get(e);
@@ -165,70 +167,70 @@ var E = class {
165
167
  async execute(e, t) {
166
168
  const s = this.functions.get(e);
167
169
  if (!s) throw new g(`Function "${e}" is not registered`, e);
168
- n.log(`Executing function: ${e}`, t);
170
+ o.log(`Executing function: ${e}`, t);
169
171
  try {
170
- const r = await s.handler(t);
171
- return n.log(`Function ${e} completed:`, r), r;
172
- } catch (r) {
173
- throw n.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);
172
+ const n = await s.handler(t);
173
+ return o.log(`Function ${e} completed:`, n), n;
174
+ } catch (n) {
175
+ throw o.error(`Function ${e} failed:`, n), new g(`Function "${e}" execution failed: ${n instanceof Error ? n.message : "Unknown error"}`, e, n instanceof Error ? n : void 0);
174
176
  }
175
177
  }
176
178
  clear() {
177
- this.functions.clear(), n.log("Cleared all registered functions");
179
+ this.functions.clear(), o.log("Cleared all registered functions");
178
180
  }
179
181
  get size() {
180
182
  return this.functions.size;
181
183
  }
182
- }, _ = class {
184
+ }, A = class {
183
185
  constructor() {
184
186
  this.entries = /* @__PURE__ */ new Map(), this.dynamicProviders = /* @__PURE__ */ new Map();
185
187
  }
186
188
  set(e, t) {
187
- this.entries.set(e, t), n.log(`ClientContext set: ${e}`);
189
+ this.entries.set(e, t), o.log(`ClientContext set: ${e}`);
188
190
  }
189
191
  remove(e) {
190
192
  const t = this.entries.delete(e);
191
- return t && n.log(`ClientContext removed: ${e}`), t;
193
+ return t && o.log(`ClientContext removed: ${e}`), t;
192
194
  }
193
195
  addDynamicProvider(e, t) {
194
- this.dynamicProviders.set(e, t), n.log(`DynamicContext provider added: ${e}`);
196
+ this.dynamicProviders.set(e, t), o.log(`DynamicContext provider added: ${e}`);
195
197
  }
196
198
  removeDynamicProvider(e) {
197
199
  const t = this.dynamicProviders.delete(e);
198
- return t && n.log(`DynamicContext provider removed: ${e}`), t;
200
+ return t && o.log(`DynamicContext provider removed: ${e}`), t;
199
201
  }
200
202
  getSnapshot() {
201
203
  if (this.entries.size === 0 && this.dynamicProviders.size === 0) return null;
202
204
  const e = {};
203
205
  for (const [t, s] of this.entries) e[t] = s;
204
206
  for (const [t, s] of this.dynamicProviders) try {
205
- const r = s();
206
- r && (e[t] = r);
207
- } catch (r) {
208
- n.error(`DynamicContext provider "${t}" threw:`, r);
207
+ const n = s();
208
+ n && (e[t] = n);
209
+ } catch (n) {
210
+ o.error(`DynamicContext provider "${t}" threw:`, n);
209
211
  }
210
212
  return Object.keys(e).length === 0 ? null : { entries: e };
211
213
  }
212
214
  clear() {
213
- this.entries.clear(), this.dynamicProviders.clear(), n.log("ClientContext cleared");
215
+ this.entries.clear(), this.dynamicProviders.clear(), o.log("ClientContext cleared");
214
216
  }
215
- }, k = class {
217
+ }, x = class {
216
218
  constructor(e) {
217
219
  this.callbacks = e, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0, this.answerCompleteEmitted = !1;
218
220
  }
219
221
  async processStream(e) {
220
- if (!e.body) throw new m("Response has no body");
222
+ if (!e.body) throw new m("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.", "stream_no_body");
221
223
  const t = e.body.getReader(), s = new TextDecoder();
222
224
  try {
223
225
  for (; ; ) {
224
- const { done: r, value: i } = await t.read();
225
- if (r) break;
226
- const o = s.decode(i, { stream: !0 });
227
- this.buffer += o, this.processBuffer();
226
+ const { done: n, value: i } = await t.read();
227
+ if (n) break;
228
+ const r = s.decode(i, { stream: !0 });
229
+ this.buffer += r, this.processBuffer();
228
230
  }
229
231
  return this.buffer.trim() && this.processBuffer(), this.buildFinalMessage();
230
- } catch (r) {
231
- const i = r instanceof Error ? r : new m("Stream processing failed");
232
+ } catch (n) {
233
+ const i = n instanceof Error ? n : new m("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
232
234
  throw this.callbacks.onError?.(i), i;
233
235
  } finally {
234
236
  t.releaseLock();
@@ -243,14 +245,14 @@ var E = class {
243
245
  if (!t.trim()) continue;
244
246
  const s = t.split(`
245
247
  `);
246
- for (const r of s)
247
- if (!r.startsWith(": ") && r.startsWith("data: ")) {
248
- const i = r.slice(6);
248
+ for (const n of s)
249
+ if (!n.startsWith(": ") && n.startsWith("data: ")) {
250
+ const i = n.slice(6);
249
251
  try {
250
- const o = JSON.parse(i);
251
- this.handleChunk(o);
252
- } catch (o) {
253
- n.warn("Failed to parse SSE data:", i, o);
252
+ const r = JSON.parse(i);
253
+ this.handleChunk(r);
254
+ } catch (r) {
255
+ o.warn("Failed to parse SSE data:", i, r);
254
256
  }
255
257
  }
256
258
  }
@@ -282,7 +284,7 @@ var E = class {
282
284
  }), e.tool_call_data && e.type && e.type !== "client_function") {
283
285
  const t = this.parseToolCall(e);
284
286
  this.callbacks.onToolCall?.(t);
285
- const s = this.toolCalls.findIndex((r) => r.id === t.id);
287
+ const s = this.toolCalls.findIndex((n) => n.id === t.id);
286
288
  s >= 0 ? this.toolCalls[s] = t : this.toolCalls.push(t);
287
289
  }
288
290
  e.follow_up_replies && (this.followUpReplies = e.follow_up_replies), this.message.status === "DONE" && !this.answerCompleteEmitted && this.message.id && (this.answerCompleteEmitted = !0, this.callbacks.onAnswerComplete?.(this.buildMessage()));
@@ -320,11 +322,11 @@ var E = class {
320
322
  return this.callbacks.onComplete?.(e), e;
321
323
  }
322
324
  };
323
- function x(e) {
325
+ function R(e) {
324
326
  const t = e.message.toLowerCase();
325
327
  return t.includes("load failed") || t.includes("failed to fetch") || t.includes("network") || t.includes("abort");
326
328
  }
327
- var S = class {
329
+ var $ = class {
328
330
  constructor() {
329
331
  this.handlers = /* @__PURE__ */ new Map();
330
332
  }
@@ -337,99 +339,124 @@ var S = class {
337
339
  }
338
340
  emit(e, t) {
339
341
  const s = this.handlers.get(e);
340
- s && s.forEach((r) => {
342
+ s && s.forEach((n) => {
341
343
  try {
342
- r(t);
344
+ n(t);
343
345
  } catch (i) {
344
346
  console.error(`Error in event handler for ${String(e)}:`, i);
345
347
  }
346
348
  });
347
349
  }
348
350
  once(e, t) {
349
- const s = ((r) => {
350
- this.off(e, s), t(r);
351
+ const s = ((n) => {
352
+ this.off(e, s), t(n);
351
353
  });
352
354
  this.on(e, s);
353
355
  }
354
356
  waitFor(e, t) {
355
- return new Promise((s, r) => {
357
+ return new Promise((s, n) => {
356
358
  let i;
357
- const o = ((a) => {
359
+ const r = ((a) => {
358
360
  i && clearTimeout(i), s(a);
359
361
  });
360
- this.once(e, o), t?.timeout && (i = setTimeout(() => {
361
- this.off(e, o), r(/* @__PURE__ */ new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`));
362
+ this.once(e, r), t?.timeout && (i = setTimeout(() => {
363
+ this.off(e, r), n(/* @__PURE__ */ new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`));
362
364
  }, t.timeout));
363
365
  });
364
366
  }
365
367
  removeAllListeners(e) {
366
368
  e ? this.handlers.delete(e) : this.handlers.clear();
367
369
  }
368
- }, $ = class w {
370
+ }, p = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).', I = /^[a-z][a-z0-9+.-]*:\/\//i, y = !1;
371
+ function w(e, t = "AgoClient") {
372
+ if (typeof e != "object" || e === null) throw new h(`${t}: ${p}`, "config_missing_base_url");
373
+ const s = e.baseUrl;
374
+ if (typeof s != "string" || s.trim() === "") throw new h(`${t}: ${p}`, "config_missing_base_url");
375
+ !s.startsWith("/") && !I.test(s) && (y || (y = !0, console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)));
376
+ }
377
+ var U = class C {
369
378
  constructor(t) {
370
- this.config = t, this.httpClient = new E(t), this.functionRegistry = new b(), this.contextRegistry = new _(), this.eventEmitter = new S(), t.debug && n.enable(), n.log("AgoClient initialized");
379
+ this.warnedEmptyConversations = /* @__PURE__ */ new Set(), w(t, "AgoClient"), this.config = t, this.httpClient = new S(t), this.functionRegistry = new k(), this.contextRegistry = new A(), this.eventEmitter = new $(), t.debug && o.enable(), o.log("AgoClient initialized");
371
380
  }
372
381
  async sendMessage(t, s) {
373
- const r = this.functionRegistry.getSchemas(), i = this.contextRegistry.getSnapshot(), o = this.config.agent || this.config.defaultAgentId, a = {
382
+ const n = this.functionRegistry.getSchemas(), i = this.contextRegistry.getSnapshot(), r = this.config.agent || this.config.defaultAgentId, a = {
374
383
  content: t,
375
384
  conversation_id: s?.conversationId,
376
- agent_id: s?.agentId || o
385
+ agent_id: s?.agentId || r
377
386
  };
378
- r.length > 0 && (a.client_functions = r), i && (a.client_context = i);
379
- let c;
387
+ n.length > 0 && (a.client_functions = n), i && (a.client_context = i);
388
+ let l;
380
389
  if (s?.files && s.files.length > 0) {
381
- const l = new FormData();
382
- l.append("content", t), s.conversationId && l.append("conversation_id", s.conversationId), (s.agentId || o) && l.append("agent_id", s.agentId || o || ""), r.length > 0 && l.append("client_functions", JSON.stringify(r)), i && l.append("client_context", JSON.stringify(i));
383
- for (const v of s.files) l.append("files", v);
384
- c = await this.httpClient.postFormData("/api/sdk/v1/messages", l);
385
- } else c = await this.httpClient.postStream("/api/sdk/v1/messages", a);
386
- return this.processSSEResponse(c);
390
+ const c = new FormData();
391
+ c.append("content", t), s.conversationId && c.append("conversation_id", s.conversationId), (s.agentId || r) && c.append("agent_id", s.agentId || r || ""), n.length > 0 && c.append("client_functions", JSON.stringify(n)), i && c.append("client_context", JSON.stringify(i));
392
+ for (const b of s.files) c.append("files", b);
393
+ l = await this.httpClient.postFormData("/api/sdk/v1/messages", c);
394
+ } else l = await this.httpClient.postStream("/api/sdk/v1/messages", a);
395
+ return this.processSSEResponse(l);
387
396
  }
388
397
  async processSSEResponse(t) {
389
- return new k({
390
- onStart: (s) => {
391
- this.eventEmitter.emit("message:start", s);
398
+ let s = !1;
399
+ const n = await new x({
400
+ onStart: (i) => {
401
+ this.eventEmitter.emit("message:start", i);
392
402
  },
393
- onChunk: (s) => {
394
- this.eventEmitter.emit("message:chunk", s);
403
+ onChunk: (i) => {
404
+ this.eventEmitter.emit("message:chunk", i);
395
405
  },
396
- onToolCall: (s) => {
397
- this.eventEmitter.emit("toolCall:received", s), s.type === "form" && this.eventEmitter.emit("toolCall:form", s);
406
+ onToolCall: (i) => {
407
+ this.eventEmitter.emit("toolCall:received", i), i.type === "form" && this.eventEmitter.emit("toolCall:form", i);
398
408
  },
399
- onClientFunction: async (s) => {
400
- this.eventEmitter.emit("function:invoke", s), await this.handleClientFunctionInvocation(s);
409
+ onClientFunction: async (i) => {
410
+ s = !0, this.eventEmitter.emit("function:invoke", i), await this.handleClientFunctionInvocation(i);
401
411
  },
402
- onAnswerComplete: (s) => {
403
- this.eventEmitter.emit("message:answer-complete", s);
412
+ onAnswerComplete: (i) => {
413
+ this.eventEmitter.emit("message:answer-complete", i);
404
414
  },
405
- onComplete: (s) => {
406
- this.eventEmitter.emit("message:complete", s);
415
+ onComplete: (i) => {
416
+ this.eventEmitter.emit("message:complete", i);
407
417
  },
408
- onError: (s) => {
409
- this.eventEmitter.emit("message:error", { error: s.message });
418
+ onError: (i) => {
419
+ this.eventEmitter.emit("message:error", {
420
+ error: i.message,
421
+ code: i instanceof h ? i.code : void 0
422
+ });
410
423
  }
411
424
  }).processStream(t);
425
+ return this.maybeFlagEmptyReply(n, s), n;
426
+ }
427
+ maybeFlagEmptyReply(t, s) {
428
+ t.status === "DONE" && (t.content ?? "").trim() === "" && !s && !(t.toolCalls && t.toolCalls.length > 0) && !(t.followUpReplies && t.followUpReplies.length > 0) && setTimeout(() => {
429
+ if (this.eventEmitter.emit("message:empty", {
430
+ conversationId: t.conversationId ?? "",
431
+ messageId: t.id ?? ""
432
+ }), this.config.warnOnEmptyReply === !1) return;
433
+ const n = t.conversationId || "(no conversation)";
434
+ if (this.warnedEmptyConversations.has(n)) return;
435
+ this.warnedEmptyConversations.add(n);
436
+ const i = this.config.agent || this.config.defaultAgentId;
437
+ t.id ? console.warn("[AGO] Reply completed with empty content. Possible causes: " + (i ? `the agent "${i}" may not exist for this tenant, ` : "an unknown `agent` slug, ") + "or the agent replied with no text. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.") : console.warn("[AGO] The stream completed without any message data. Possible causes: " + (i ? `the agent "${i}" may not exist for this tenant, or ` : "") + "`baseUrl` does not point at an AGO endpoint that returns server-sent events. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.");
438
+ }, 0);
412
439
  }
413
440
  async handleClientFunctionInvocation(t) {
414
- let s, r;
441
+ let s, n;
415
442
  try {
416
443
  s = await this.functionRegistry.execute(t.functionName, t.arguments);
417
444
  } catch (i) {
418
- r = i instanceof Error ? i.message : "Unknown error", n.error("Client function execution failed:", i);
445
+ n = i instanceof Error ? i.message : "Unknown error", o.error("Client function execution failed:", i);
419
446
  }
420
447
  if (t.invocationId) try {
421
448
  await this.submitToolCallForm(t.invocationId, {
422
449
  result: s,
423
- error: r,
450
+ error: n,
424
451
  _type: "client_function_result"
425
452
  });
426
453
  } catch (i) {
427
- n.error("Failed to submit function result:", i);
454
+ o.error("Failed to submit function result:", i);
428
455
  }
429
456
  this.eventEmitter.emit("function:result", {
430
457
  invocationId: t.invocationId,
431
458
  result: s,
432
- error: r
459
+ error: n
433
460
  });
434
461
  }
435
462
  async getConversations() {
@@ -440,7 +467,7 @@ var S = class {
440
467
  }));
441
468
  }
442
469
  async getConversation(t) {
443
- const s = await this.httpClient.get(`/api/sdk/v1/conversations/${t}`), r = {
470
+ const s = await this.httpClient.get(`/api/sdk/v1/conversations/${t}`), n = {
444
471
  id: s.id,
445
472
  title: s.title,
446
473
  lastMessageDate: new Date(s.last_message_date),
@@ -451,10 +478,10 @@ var S = class {
451
478
  role: i.role,
452
479
  status: i.status,
453
480
  createdAt: new Date(i.created_at),
454
- toolCalls: w.mapPersistedToolCalls(i.tool_call_data)
481
+ toolCalls: C.mapPersistedToolCalls(i.tool_call_data)
455
482
  }))
456
483
  };
457
- return this.eventEmitter.emit("conversation:loaded", r), r;
484
+ return this.eventEmitter.emit("conversation:loaded", n), n;
458
485
  }
459
486
  static mapPersistedToolCalls(t) {
460
487
  if (!(!t || t.length === 0))
@@ -501,8 +528,8 @@ var S = class {
501
528
  async submitFeedback(t, s) {
502
529
  await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`, { rating: s });
503
530
  }
504
- registerFunction(t, s, r) {
505
- typeof t == "object" ? this.functionRegistry.register(t) : this.functionRegistry.register(t, s, r);
531
+ registerFunction(t, s, n) {
532
+ typeof t == "object" ? this.functionRegistry.register(t) : this.functionRegistry.register(t, s, n);
506
533
  }
507
534
  register(t) {
508
535
  if (Array.isArray(t)) for (const s of t) this.functionRegistry.register(s);
@@ -515,13 +542,13 @@ var S = class {
515
542
  return this.functionRegistry.getSchemas();
516
543
  }
517
544
  registerNavigationFunction(t, s) {
518
- const r = s.map((o) => o.name), i = s.map((o) => `- "${o.name}": ${o.description}`).join(`
545
+ const n = s.map((r) => r.name), i = s.map((r) => `- "${r.name}": ${r.description}`).join(`
519
546
  `);
520
- this.registerFunction("navigateToPage", async (o) => {
521
- const a = o.page, c = s.find((l) => l.name === a);
522
- return c ? (t(c.path), {
547
+ this.registerFunction("navigateToPage", async (r) => {
548
+ const a = r.page, l = s.find((c) => c.name === a);
549
+ return l ? (t(l.path), {
523
550
  success: !0,
524
- navigatedTo: c.path
551
+ navigatedTo: l.path
525
552
  }) : {
526
553
  success: !1,
527
554
  error: `Unknown page: ${a}`
@@ -534,7 +561,7 @@ ${i}`,
534
561
  properties: { page: {
535
562
  type: "string",
536
563
  description: "The page to navigate to",
537
- enum: r
564
+ enum: n
538
565
  } },
539
566
  required: ["page"]
540
567
  }
@@ -586,26 +613,30 @@ ${i}`,
586
613
  return this.eventEmitter.waitFor(t, s);
587
614
  }
588
615
  updateConfig(t) {
589
- this.config = {
616
+ const s = {};
617
+ for (const [i, r] of Object.entries(t)) r !== void 0 && (s[i] = r);
618
+ const n = {
590
619
  ...this.config,
591
- ...t
592
- }, this.httpClient.updateConfig(t), t.debug !== void 0 && (t.debug ? n.enable() : n.disable());
620
+ ...s
621
+ };
622
+ w(n, "AgoClient.updateConfig"), this.config = n, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? o.enable() : o.disable());
593
623
  }
594
624
  destroy() {
595
- this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), n.log("AgoClient destroyed");
625
+ this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), o.log("AgoClient destroyed");
596
626
  }
597
627
  };
598
628
  export {
599
- _ as a,
600
- h as c,
601
- u as d,
602
- m as f,
629
+ R as a,
630
+ o as c,
631
+ g as d,
632
+ u as f,
603
633
  x as i,
604
634
  d as l,
605
- S as n,
606
- b as o,
607
- k as r,
608
- n as s,
609
- $ as t,
610
- g as u
635
+ w as n,
636
+ A as o,
637
+ m as p,
638
+ $ as r,
639
+ k as s,
640
+ U as t,
641
+ h as u
611
642
  };
package/dist/angular.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-0x2Du_62.cjs");var n=class{constructor(e){this.client=new o.AgoClient(e),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(e){const t=this.client;return{subscribe(i){const s=r=>{i.next?.(r)};return t.on(e,s),{unsubscribe:()=>t.off(e,s)}}}}sendMessage(e,t){return this.client.sendMessage(e,t)}getConversations(){return this.client.getConversations()}getConversation(e){return this.client.getConversation(e)}getMessages(e){return this.client.getMessages(e)}submitToolCallForm(e,t){return this.client.submitToolCallForm(e,t)}confirmToolCall(e){return this.client.confirmToolCall(e)}rejectToolCall(e){return this.client.rejectToolCall(e)}submitFeedback(e,t){return this.client.submitFeedback(e,t)}registerFunction(e,t,i){typeof e=="object"?this.client.registerFunction(e):this.client.registerFunction(e,t,i)}unregisterFunction(e){return this.client.unregisterFunction(e)}registerNavigationFunction(e,t){this.client.registerNavigationFunction(e,t)}on(e,t){this.client.on(e,t)}off(e,t){this.client.off(e,t)}updateConfig(e){this.client.updateConfig(e)}getClient(){return this.client}destroy(){this.client.destroy()}};function c(e){return{provide:n,useValue:new n(e)}}exports.AgoService=n;exports.provideAgo=c;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-_fig8FoN.cjs");var n=class{constructor(e){this.client=new o.AgoClient(e),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(e){const t=this.client;return{subscribe(i){const s=r=>{i.next?.(r)};return t.on(e,s),{unsubscribe:()=>t.off(e,s)}}}}sendMessage(e,t){return this.client.sendMessage(e,t)}getConversations(){return this.client.getConversations()}getConversation(e){return this.client.getConversation(e)}getMessages(e){return this.client.getMessages(e)}submitToolCallForm(e,t){return this.client.submitToolCallForm(e,t)}confirmToolCall(e){return this.client.confirmToolCall(e)}rejectToolCall(e){return this.client.rejectToolCall(e)}submitFeedback(e,t){return this.client.submitFeedback(e,t)}registerFunction(e,t,i){typeof e=="object"?this.client.registerFunction(e):this.client.registerFunction(e,t,i)}unregisterFunction(e){return this.client.unregisterFunction(e)}registerNavigationFunction(e,t){this.client.registerNavigationFunction(e,t)}on(e,t){this.client.on(e,t)}off(e,t){this.client.off(e,t)}updateConfig(e){this.client.updateConfig(e)}getClient(){return this.client}destroy(){this.client.destroy()}};function c(e){return{provide:n,useValue:new n(e)}}exports.AgoService=n;exports.provideAgo=c;