@opencx/widget-core 5.0.0-beta.2 → 5.0.0-beta.3

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.
package/dist/index.js CHANGED
@@ -1,187 +1,195 @@
1
- import Q from "openapi-fetch";
2
- import X from "lodash.isequal";
3
- import { v4 as I } from "uuid";
4
- const Ra = (_) => _.type === "data-keepalive", Ka = (_) => _.type === "data-turn-steered", R = "[opencx]", m = {
5
- warn: (_, ...e) => {
6
- console.warn(`${R} ${_}`, ...e);
1
+ import ae from "openapi-fetch";
2
+ import te from "lodash.isequal";
3
+ import { v4 as D } from "uuid";
4
+ const Fa = (o) => o.type === "data-keepalive", Oa = (o) => o.type === "data-turn-steered", L = "[opencx]", h = {
5
+ warn: (o, ...e) => {
6
+ console.warn(`${L} ${o}`, ...e);
7
7
  },
8
- error: (_, ...e) => {
9
- console.error(`${R} ${_}`, ...e);
8
+ error: (o, ...e) => {
9
+ console.error(`${L} ${o}`, ...e);
10
10
  }
11
- }, ee = (_) => {
12
- m.error("request failed", _.error);
13
- }, ae = (_) => {
14
- const e = Q({
15
- baseUrl: _.baseUrl
11
+ }, se = (o) => {
12
+ h.error("request failed", o.error);
13
+ }, ne = (o) => {
14
+ const e = ae({
15
+ baseUrl: o.baseUrl
16
16
  }), a = {
17
- onRequest: _.onRequest,
18
- onResponse: _.onResponse,
19
- onError: _.onError || ee
17
+ onRequest: o.onRequest,
18
+ onResponse: o.onResponse,
19
+ onError: o.onError || se
20
20
  };
21
21
  return e.use(a), e;
22
- }, te = "/backend/widget/v5/chat/stream", se = "/backend/widget/v5/chat/{sessionId}/stream", K = (_, e, a) => `${_.replace(/\/$/, "")}${a ? e.replace("{sessionId}", encodeURIComponent(a)) : e}`;
23
- class L {
22
+ }, oe = "/backend/widget/v5/chat/stream", ie = "/backend/widget/v5/chat/{sessionId}/stream", F = (o, e, a) => `${o.replace(/\/$/, "")}${a ? e.replace("{sessionId}", encodeURIComponent(a)) : e}`;
23
+ class O {
24
24
  constructor({ config: e }) {
25
- var i, l;
26
- this.userToken = null, this.constructClientOptions = (o) => {
27
- const t = this.config.apiUrl || "https://api.open.cx", s = {
25
+ var i, _;
26
+ this.userToken = null, this.constructClientOptions = (n) => {
27
+ const t = this.config.apiUrl || "https://api.open.cx", r = {
28
28
  "X-Bot-Token": this.config.token,
29
29
  "Content-Type": "application/json",
30
30
  Accept: "application/json",
31
- Authorization: o ? `Bearer ${o}` : void 0
31
+ Authorization: n ? `Bearer ${n}` : void 0
32
32
  };
33
- return { baseUrl: t, headers: s };
33
+ return { baseUrl: t, headers: r };
34
34
  }, this.createOpenAPIClient = ({
35
- baseUrl: o,
35
+ baseUrl: n,
36
36
  headers: t
37
- }) => ae({
38
- baseUrl: o,
39
- onRequest: ({ request: s }) => {
40
- Object.entries(t).forEach(([r, c]) => {
41
- c && s.headers.set(r, c);
37
+ }) => ne({
38
+ baseUrl: n,
39
+ onRequest: ({ request: r }) => {
40
+ Object.entries(t).forEach(([c, d]) => {
41
+ d && r.headers.set(c, d);
42
42
  });
43
43
  }
44
- }), this.setAuthToken = (o) => {
45
- this.userToken = o;
46
- const { baseUrl: t, headers: s } = this.constructClientOptions(o);
47
- this.client = this.createOpenAPIClient({ baseUrl: t, headers: s });
44
+ }), this.setAuthToken = (n) => {
45
+ this.userToken = n;
46
+ const { baseUrl: t, headers: r } = this.constructClientOptions(n);
47
+ this.client = this.createOpenAPIClient({ baseUrl: t, headers: r });
48
48
  }, this.getStreamAuthContext = () => {
49
- const { baseUrl: o, headers: t } = this.constructClientOptions(this.userToken), s = {};
50
- for (const [r, c] of Object.entries(t))
51
- typeof c == "string" && (["content-type", "accept"].includes(r.toLowerCase()) || (s[r] = c));
52
- return { baseUrl: o, headers: s };
49
+ const { baseUrl: n, headers: t } = this.constructClientOptions(this.userToken), r = {};
50
+ for (const [c, d] of Object.entries(t))
51
+ typeof d == "string" && (["content-type", "accept"].includes(c.toLowerCase()) || (r[c] = d));
52
+ return { baseUrl: n, headers: r };
53
53
  }, this.getStreamTransportOptions = () => {
54
- const { baseUrl: o, headers: t } = this.getStreamAuthContext();
54
+ const { baseUrl: n, headers: t } = this.getStreamAuthContext();
55
55
  return {
56
- api: K(o, te),
57
- reconnectApi: (s) => K(o, se, s),
56
+ api: F(n, oe),
57
+ reconnectApi: (r) => F(n, ie, r),
58
58
  headers: t
59
59
  };
60
- }, this.stopStream = async (o) => {
60
+ }, this.stopStream = async (n) => {
61
61
  const { response: t } = await this.client.POST(
62
62
  "/backend/widget/v5/chat/{sessionId}/stop",
63
- { params: { path: { sessionId: o } } }
63
+ { params: { path: { sessionId: n } } }
64
64
  );
65
65
  if (!t.ok)
66
66
  throw new Error(`Failed to stop stream: ${t.status}`);
67
- }, this.getAgentTurnMessages = async (o) => {
68
- const { data: t, response: s } = await this.client.GET(
67
+ }, this.getAgentTurnMessages = async (n, t) => {
68
+ const { data: r, response: c } = await this.client.GET(
69
69
  "/backend/widget/v5/chat/{sessionId}/messages",
70
- { params: { path: { sessionId: o } } }
70
+ {
71
+ params: {
72
+ path: { sessionId: n },
73
+ query: {
74
+ toolActivity: t == null ? void 0 : t.toolActivity,
75
+ reasoning: (t == null ? void 0 : t.reasoning) === void 0 ? void 0 : t.reasoning ? "true" : "false"
76
+ }
77
+ }
78
+ }
71
79
  );
72
- return t || (m.warn("agent turn messages fetch failed", s.status), null);
80
+ return r || (h.warn("agent turn messages fetch failed", c.status), null);
73
81
  }, this.createDictationSession = async ({
74
- language: o
82
+ language: n
75
83
  }) => {
76
- const { data: t, response: s } = await this.client.POST(
84
+ const { data: t, response: r } = await this.client.POST(
77
85
  "/backend/widget/v5/dictation/sessions",
78
- { body: o ? { language: o } : {} }
86
+ { body: n ? { language: n } : {} }
79
87
  );
80
88
  if (!t)
81
- throw new Error(`Failed to start dictation: ${s.status}`);
89
+ throw new Error(`Failed to start dictation: ${r.status}`);
82
90
  return t;
83
91
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
84
92
  params: {
85
93
  header: { "x-bot-token": this.config.token }
86
94
  }
87
- }), this.sendMessage = async (o, t) => await this.client.POST("/backend/widget/v2/chat/send", {
88
- body: o,
95
+ }), this.sendMessage = async (n, t) => await this.client.POST("/backend/widget/v2/chat/send", {
96
+ body: n,
89
97
  signal: t
90
- }), this.createUnverifiedContact = async (o) => await this.client.POST(
98
+ }), this.createUnverifiedContact = async (n) => await this.client.POST(
91
99
  "/backend/widget/v2/contact/create-unverified",
92
100
  {
93
101
  params: { header: { "x-bot-token": this.config.token } },
94
- body: o
102
+ body: n
95
103
  }
96
- ), this.createSession = async (o, t) => await this.client.POST("/backend/widget/v2/create-session", {
97
- body: o,
104
+ ), this.createSession = async (n, t) => await this.client.POST("/backend/widget/v2/create-session", {
105
+ body: n,
98
106
  signal: t
99
107
  }), this.pollSessionAndHistory = async ({
100
- sessionId: o,
108
+ sessionId: n,
101
109
  abortSignal: t
102
110
  }) => await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
103
- params: { path: { sessionId: o } },
111
+ params: { path: { sessionId: n } },
104
112
  signal: t
105
113
  }), this.getSessions = async ({
106
- cursor: o,
114
+ cursor: n,
107
115
  filters: t,
108
- abortSignal: s
116
+ abortSignal: r
109
117
  }) => await this.client.GET("/backend/widget/v2/sessions", {
110
118
  params: {
111
119
  query: {
112
- offset: o,
120
+ offset: n,
113
121
  filters: JSON.stringify(t)
114
122
  }
115
123
  },
116
- signal: s
124
+ signal: r
117
125
  }), this.uploadFile = async ({
118
- file: o,
126
+ file: n,
119
127
  abortSignal: t,
120
- onProgress: s
121
- }) => new Promise((r, c) => {
122
- var j;
123
- const p = new FormData();
124
- p.append("file", o);
125
- const d = new XMLHttpRequest();
128
+ onProgress: r
129
+ }) => new Promise((c, d) => {
130
+ var f;
131
+ const l = new FormData();
132
+ l.append("file", n);
133
+ const p = new XMLHttpRequest();
126
134
  if (t && (t.addEventListener("abort", () => {
127
- d.abort(), c(new DOMException("Aborted", "AbortError"));
135
+ p.abort(), d(new DOMException("Aborted", "AbortError"));
128
136
  }), t.aborted)) {
129
- c(new DOMException("Aborted", "AbortError"));
137
+ d(new DOMException("Aborted", "AbortError"));
130
138
  return;
131
139
  }
132
- d.upload.addEventListener("progress", (b) => {
133
- if (b.lengthComputable && s) {
134
- const f = Math.round(b.loaded / b.total * 100);
135
- s(f);
140
+ p.upload.addEventListener("progress", (k) => {
141
+ if (k.lengthComputable && r) {
142
+ const y = Math.round(k.loaded / k.total * 100);
143
+ r(y);
136
144
  }
137
- }), d.addEventListener("load", () => {
138
- if (d.status >= 200 && d.status < 300)
145
+ }), p.addEventListener("load", () => {
146
+ if (p.status >= 200 && p.status < 300)
139
147
  try {
140
- const b = JSON.parse(d.responseText);
141
- r(b);
142
- } catch (b) {
143
- c(new Error(`Failed to parse response: ${b}`));
148
+ const k = JSON.parse(p.responseText);
149
+ c(k);
150
+ } catch (k) {
151
+ d(new Error(`Failed to parse response: ${k}`));
144
152
  }
145
153
  else
146
- c(new Error(`Upload failed with status: ${d.status}`));
147
- }), d.addEventListener("error", () => {
148
- c(new Error("Network error occurred"));
149
- }), d.addEventListener("timeout", () => {
150
- c(new Error("Upload timed out"));
154
+ d(new Error(`Upload failed with status: ${p.status}`));
155
+ }), p.addEventListener("error", () => {
156
+ d(new Error("Network error occurred"));
157
+ }), p.addEventListener("timeout", () => {
158
+ d(new Error("Upload timed out"));
151
159
  });
152
- const { baseUrl: u } = this.constructClientOptions(this.userToken), h = `${u}/backend/widget/v2/upload`;
153
- d.open("POST", h), d.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((j = this.config.user) == null ? void 0 : j.token) ? d.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : m.error("user token not set"), d.send(p);
154
- }), this.vote = async (o) => await this.client.POST("/backend/widget/v2/chat/vote", { body: o }), this.resolveSession = async (o, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
155
- body: o,
160
+ const { baseUrl: u } = this.constructClientOptions(this.userToken), g = `${u}/backend/widget/v2/upload`;
161
+ p.open("POST", g), p.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((f = this.config.user) == null ? void 0 : f.token) ? p.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : h.error("user token not set"), p.send(l);
162
+ }), this.vote = async (n) => await this.client.POST("/backend/widget/v2/chat/vote", { body: n }), this.resolveSession = async (n, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
163
+ body: n,
156
164
  signal: t
157
- }), this.createStateCheckpoint = async (o) => await this.client.POST("/backend/widget/v2/checkpoint", {
158
- body: o
159
- }), this.submitCsat = async (o) => await this.client.POST("/backend/widget/v2/submit-csat", { body: o }), this.config = e, this.userToken = ((i = e.user) == null ? void 0 : i.token) || null;
160
- const { baseUrl: a, headers: n } = this.constructClientOptions(
161
- (l = e.user) == null ? void 0 : l.token
165
+ }), this.createStateCheckpoint = async (n) => await this.client.POST("/backend/widget/v2/checkpoint", {
166
+ body: n
167
+ }), this.submitCsat = async (n) => await this.client.POST("/backend/widget/v2/submit-csat", { body: n }), this.config = e, this.userToken = ((i = e.user) == null ? void 0 : i.token) || null;
168
+ const { baseUrl: a, headers: s } = this.constructClientOptions(
169
+ (_ = e.user) == null ? void 0 : _.token
162
170
  );
163
- this.client = this.createOpenAPIClient({ baseUrl: a, headers: n });
171
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: s });
164
172
  }
165
173
  }
166
- function ne(_, e) {
167
- m.error(`missing case for ${_} in ${e}`);
174
+ function re(o, e) {
175
+ h.error(`missing case for ${o} in ${e}`);
168
176
  }
169
- class w {
177
+ class j {
170
178
  constructor(e) {
171
179
  this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
172
- X(this.state, a) || (this.state = a, this.notifySubscribers(a));
180
+ te(this.state, a) || (this.state = a, this.notifySubscribers(a));
173
181
  }, this.setPartial = (a) => {
174
182
  if (a == null) return;
175
- const n = { ...this.state, ...a };
176
- this.set(n);
183
+ const s = { ...this.state, ...a };
184
+ this.set(s);
177
185
  }, this.reset = () => {
178
186
  this.set(this.initialState);
179
187
  }, this.notifySubscribers = (a) => {
180
188
  Array.from(this.subscribers).forEach((i) => {
181
189
  try {
182
190
  i(a);
183
- } catch (l) {
184
- m.error("state subscriber threw", l);
191
+ } catch (_) {
192
+ h.error("state subscriber threw", _);
185
193
  }
186
194
  });
187
195
  }, this.subscribe = (a) => (this.subscribers.add(a), () => {
@@ -189,9 +197,9 @@ class w {
189
197
  }), this.state = e, this.initialState = e;
190
198
  }
191
199
  }
192
- class V {
200
+ class G {
193
201
  constructor() {
194
- this.state = new w({
202
+ this.state = new j({
195
203
  isPolling: !1,
196
204
  isError: !1
197
205
  }), this.abortController = new AbortController(), this.reset = () => {
@@ -199,283 +207,283 @@ class V {
199
207
  this.abortController.abort("Resetting poller"), (e = this.stopPolling) == null || e.call(this), this.stopPolling = null;
200
208
  }, this.stopPolling = null, this.startPolling = (e, a) => {
201
209
  if (this.stopPolling) return;
202
- const n = [], i = async () => {
210
+ const s = [], i = async () => {
203
211
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
204
212
  try {
205
213
  await e(this.abortController.signal);
206
- } catch (l) {
214
+ } catch (_) {
207
215
  if (this.abortController.signal.aborted)
208
216
  return;
209
- m.error("failed to poll", l), this.state.setPartial({ isError: !0 });
217
+ h.error("failed to poll", _), this.state.setPartial({ isError: !0 });
210
218
  } finally {
211
219
  this.state.setPartial({ isPolling: !1 });
212
220
  }
213
- this.abortController.signal.aborted || n.push(setTimeout(i, a));
221
+ this.abortController.signal.aborted || s.push(setTimeout(i, a));
214
222
  };
215
223
  i(), this.stopPolling = () => {
216
- n.forEach(clearTimeout), this.state.reset();
224
+ s.forEach(clearTimeout), this.state.reset();
217
225
  };
218
226
  };
219
227
  }
220
228
  }
221
- function H(_) {
229
+ function W(o) {
222
230
  try {
223
- const e = _();
231
+ const e = o();
224
232
  return e instanceof Promise ? e.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: e };
225
233
  } catch (e) {
226
234
  return { error: e };
227
235
  }
228
236
  }
229
- class oe {
237
+ class _e {
230
238
  constructor({
231
239
  api: e,
232
240
  config: a,
233
- sessionCtx: n,
241
+ sessionCtx: s,
234
242
  messageCtx: i,
235
- sessionPollingIntervalSeconds: l
243
+ sessionPollingIntervalSeconds: _
236
244
  }) {
237
- this.poller = new V(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.reconcilingSessionId = null, this.registerPolling = () => {
238
- this.sessionCtx.sessionState.subscribe(({ session: o }) => {
239
- o != null && o.id ? this.poller.startPolling(async (t) => {
240
- this.fetchSessionAndHistory({ sessionId: o.id, abortSignal: t });
245
+ this.poller = new G(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.reconcilingSessionId = null, this.registerPolling = () => {
246
+ this.sessionCtx.sessionState.subscribe(({ session: n }) => {
247
+ n != null && n.id ? this.poller.startPolling(async (t) => {
248
+ this.fetchSessionAndHistory({ sessionId: n.id, abortSignal: t });
241
249
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
242
- }), this.sessionCtx.sessionState.subscribe(({ session: o }) => {
243
- if (o != null && o.id && !o.isOpened)
250
+ }), this.sessionCtx.sessionState.subscribe(({ session: n }) => {
251
+ if (n != null && n.id && !n.isOpened)
244
252
  try {
245
253
  this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.fetchSessionAndHistory({
246
- sessionId: o.id,
254
+ sessionId: n.id,
247
255
  abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
248
256
  });
249
257
  } catch (t) {
250
- this.fetchSessionAndFullHistoryAbortController.signal.aborted || m.error("failed to fetch session and full history", t);
258
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || h.error("failed to fetch session and full history", t);
251
259
  }
252
260
  else
253
261
  this.fetchSessionAndFullHistoryAbortController.abort();
254
- }), this.sessionCtx.sessionState.subscribe(({ session: o }) => {
255
- this.reconcilingSessionId !== null && (o == null ? void 0 : o.id) !== this.reconcilingSessionId && this.reconcileAbortController.abort();
262
+ }), this.sessionCtx.sessionState.subscribe(({ session: n }) => {
263
+ this.reconcilingSessionId !== null && (n == null ? void 0 : n.id) !== this.reconcilingSessionId && this.reconcileAbortController.abort();
256
264
  });
257
- }, this.reconcileAfterStream = async (o) => {
265
+ }, this.reconcileAfterStream = async (n) => {
258
266
  this.reconcileAbortController.abort(), this.reconcileAbortController = new AbortController();
259
267
  const { signal: t } = this.reconcileAbortController;
260
- this.reconcilingSessionId = o;
268
+ this.reconcilingSessionId = n;
261
269
  try {
262
- await this.fetchSessionAndHistory({ sessionId: o, abortSignal: t });
263
- } catch (s) {
264
- if (!t.aborted) throw s;
270
+ await this.fetchSessionAndHistory({ sessionId: n, abortSignal: t });
271
+ } catch (r) {
272
+ if (!t.aborted) throw r;
265
273
  } finally {
266
- this.reconcilingSessionId === o && (this.reconcilingSessionId = null);
274
+ this.reconcilingSessionId === n && (this.reconcilingSessionId = null);
267
275
  }
268
276
  }, this.fetchSessionAndHistory = async ({
269
- sessionId: o,
277
+ sessionId: n,
270
278
  abortSignal: t
271
279
  }) => {
272
- const s = this.messageCtx.state.get().messages.length === 0;
273
- s && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
274
- const { data: r } = await this.api.pollSessionAndHistory({
275
- sessionId: o,
280
+ const r = this.messageCtx.state.get().messages.length === 0;
281
+ r && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
282
+ const { data: c } = await this.api.pollSessionAndHistory({
283
+ sessionId: n,
276
284
  abortSignal: t
277
285
  });
278
- if (r != null && r.session && (this.sessionCtx.sessionState.setPartial({ session: r.session }), this.sessionCtx.setSessions([r.session])), r != null && r.history && r.history.length > 0) {
279
- const c = this.messageCtx.state.get().messages, p = r.history.map(this.mapHistoryToMessage).filter((d) => d !== null).filter(
280
- (d) => !c.some((u) => u.id === d.id)
286
+ if (c != null && c.session && (this.sessionCtx.sessionState.setPartial({ session: c.session }), this.sessionCtx.setSessions([c.session])), c != null && c.history && c.history.length > 0) {
287
+ const d = this.messageCtx.state.get().messages, l = c.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
288
+ (p) => !d.some((u) => u.id === p.id)
281
289
  );
282
- if (p.length > 0)
290
+ if (l.length > 0)
283
291
  if (this.messageCtx.state.setPartial({
284
- messages: [...c, ...p]
285
- }), s)
292
+ messages: [...d, ...l]
293
+ }), r)
286
294
  this.messageCtx.markAsDispatchedToOnMessageReceivedHook(
287
- p.map((d) => d.id)
295
+ l.map((p) => p.id)
288
296
  );
289
297
  else
290
- for (const d of p)
291
- this.messageCtx.dispatchToOnMessageReceivedHook(d);
298
+ for (const p of l)
299
+ this.messageCtx.dispatchToOnMessageReceivedHook(p);
292
300
  }
293
301
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
294
- }, this.mapHistoryToMessage = (o) => {
295
- var s;
302
+ }, this.mapHistoryToMessage = (n) => {
303
+ var r;
296
304
  const t = {
297
- id: o.publicId,
298
- timestamp: o.sentAt || "",
299
- attachments: o.attachments || void 0
305
+ id: n.publicId,
306
+ timestamp: n.sentAt || "",
307
+ attachments: n.attachments || void 0
300
308
  };
301
- if (o.sender.kind === "user")
309
+ if (n.sender.kind === "user")
302
310
  return {
303
311
  ...t,
304
312
  type: "USER",
305
- content: o.content.text || "",
313
+ content: n.content.text || "",
306
314
  // Backend field name (schema.ts) → widget vocabulary.
307
- markedElements: o.pickedElements
315
+ markedElements: n.pickedElements
308
316
  };
309
- if (o.sender.kind === "agent")
317
+ if (n.sender.kind === "agent")
310
318
  return {
311
319
  ...t,
312
320
  type: "AGENT",
313
321
  component: "agent_message",
314
322
  data: {
315
- message: o.content.text || ""
323
+ message: n.content.text || ""
316
324
  },
317
325
  agent: {
318
- name: o.sender.name || "",
326
+ name: n.sender.name || "",
319
327
  // Do not set avatarUrl from config here... let it be taken from the config at render time
320
328
  // Only set avatar url from the backend's response
321
- avatarUrl: o.sender.avatar || null,
322
- avatar: o.sender.avatar || null,
329
+ avatarUrl: n.sender.avatar || null,
330
+ avatar: n.sender.avatar || null,
323
331
  id: null,
324
332
  isAi: !1
325
333
  }
326
334
  };
327
- if (o.sender.kind === "ai") {
328
- const r = o.actionCalls && o.actionCalls.length > 0 ? o.actionCalls[o.actionCalls.length - 1] : void 0;
335
+ if (n.sender.kind === "ai") {
336
+ const c = n.actionCalls && n.actionCalls.length > 0 ? n.actionCalls[n.actionCalls.length - 1] : void 0;
329
337
  return {
330
338
  ...t,
331
339
  type: "AI",
332
340
  component: "bot_message",
333
341
  agent: {
334
342
  id: null,
335
- name: ((s = this.config.bot) == null ? void 0 : s.name) || "",
343
+ name: ((r = this.config.bot) == null ? void 0 : r.name) || "",
336
344
  isAi: !0,
337
345
  // Do not set avatarUrl from config here... let it be taken from the config at render time
338
346
  avatarUrl: null,
339
347
  avatar: null
340
348
  },
341
349
  data: {
342
- message: o.content.text || "",
343
- action: r ? {
344
- name: r.actionName,
345
- data: this.extractActionResult(r)
350
+ message: n.content.text || "",
351
+ action: c ? {
352
+ name: c.actionName,
353
+ data: this.extractActionResult(c)
346
354
  } : void 0
347
355
  }
348
356
  };
349
357
  }
350
- if (o.sender.kind === "system") {
351
- const r = this.constructSystemMessage(o);
352
- return r === null ? null : { ...r };
358
+ if (n.sender.kind === "system") {
359
+ const c = this.constructSystemMessage(n);
360
+ return c === null ? null : { ...c };
353
361
  }
354
362
  return null;
355
- }, this.constructSystemMessage = (o) => {
356
- if (!o || !o.systemMessagePayload) return null;
357
- switch (o.systemMessagePayload.type) {
363
+ }, this.constructSystemMessage = (n) => {
364
+ if (!n || !n.systemMessagePayload) return null;
365
+ switch (n.systemMessagePayload.type) {
358
366
  case "state_checkpoint":
359
367
  return {
360
- id: o.publicId,
368
+ id: n.publicId,
361
369
  type: "SYSTEM",
362
370
  subtype: "state_checkpoint",
363
- data: { payload: o.systemMessagePayload.payload },
364
- timestamp: o.sentAt || "",
371
+ data: { payload: n.systemMessagePayload.payload },
372
+ timestamp: n.sentAt || "",
365
373
  attachments: void 0
366
374
  };
367
375
  case "csat_requested":
368
376
  return {
369
- id: o.publicId,
377
+ id: n.publicId,
370
378
  type: "SYSTEM",
371
379
  subtype: "csat_requested",
372
380
  data: { payload: void 0 },
373
- timestamp: o.sentAt || "",
381
+ timestamp: n.sentAt || "",
374
382
  attachments: void 0
375
383
  };
376
384
  case "csat_submitted":
377
385
  return {
378
- id: o.publicId,
386
+ id: n.publicId,
379
387
  type: "SYSTEM",
380
388
  subtype: "csat_submitted",
381
389
  data: {
382
390
  payload: {
383
- score: o.systemMessagePayload.payload.score ?? void 0,
384
- feedback: o.systemMessagePayload.payload.feedback ?? void 0
391
+ score: n.systemMessagePayload.payload.score ?? void 0,
392
+ feedback: n.systemMessagePayload.payload.feedback ?? void 0
385
393
  }
386
394
  },
387
- timestamp: o.sentAt || "",
395
+ timestamp: n.sentAt || "",
388
396
  attachments: void 0
389
397
  };
390
398
  case "none":
391
399
  return null;
392
400
  default:
393
- return ne(
394
- o.systemMessagePayload,
401
+ return re(
402
+ n.systemMessagePayload,
395
403
  this.constructSystemMessage.name
396
404
  ), null;
397
405
  }
398
- }, this.extractActionResult = (o) => {
399
- const t = o.result;
406
+ }, this.extractActionResult = (n) => {
407
+ const t = n.result;
400
408
  if (t === null || typeof t != "object") return t;
401
409
  if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
402
- const s = t.responseBodyText, r = H(() => JSON.parse(s)).data;
403
- if (r) return r;
410
+ const r = t.responseBodyText, c = W(() => JSON.parse(r)).data;
411
+ if (c) return c;
404
412
  }
405
- return o.result;
406
- }, this.api = e, this.config = a, this.sessionCtx = n, this.messageCtx = i, this.sessionPollingIntervalSeconds = l, this.registerPolling();
413
+ return n.result;
414
+ }, this.api = e, this.config = a, this.sessionCtx = s, this.messageCtx = i, this.sessionPollingIntervalSeconds = _, this.registerPolling();
407
415
  }
408
416
  }
409
- class ie {
417
+ class le {
410
418
  constructor({
411
419
  config: e,
412
420
  api: a,
413
- storageCtx: n
421
+ storageCtx: s
414
422
  }) {
415
423
  var i;
416
424
  this.shouldCollectData = () => {
417
- var l;
418
- return !!(!((l = this.state.get().contact) != null && l.token) && this.config.collectUserData);
425
+ var _;
426
+ return !!(!((_ = this.state.get().contact) != null && _.token) && this.config.collectUserData);
419
427
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
420
- var l, o, t, s, r, c, p, d, u, g, h, v, j, b;
421
- if (!((l = this.config.user) != null && l.token)) {
422
- if (this.config.collectUserData && !((t = (o = this.config.user) == null ? void 0 : o.data) != null && t.email)) {
423
- if ((s = this.config.extraDataCollectionFields) != null && s.length)
428
+ var _, n, t, r, c, d, l, p, u, m, g, b, f, k;
429
+ if (!((_ = this.config.user) != null && _.token)) {
430
+ if (this.config.collectUserData && !((t = (n = this.config.user) == null ? void 0 : n.data) != null && t.email)) {
431
+ if ((r = this.config.extraDataCollectionFields) != null && r.length)
424
432
  return;
425
- const f = await ((r = this.storageCtx) == null ? void 0 : r.getContactToken());
426
- f && await this.setUnverifiedContact(f);
433
+ const y = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
434
+ y && await this.setUnverifiedContact(y);
427
435
  return;
428
436
  }
429
- if (!((p = (c = this.config.user) == null ? void 0 : c.data) != null && p.email)) {
430
- const f = await ((d = this.storageCtx) == null ? void 0 : d.getContactToken());
431
- if (f) {
432
- await this.setUnverifiedContact(f);
437
+ if (!((l = (d = this.config.user) == null ? void 0 : d.data) != null && l.email)) {
438
+ const y = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
439
+ if (y) {
440
+ await this.setUnverifiedContact(y);
433
441
  return;
434
442
  }
435
443
  }
436
444
  await this.createUnverifiedContact({
437
- email: (g = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : g.email,
438
- non_verified_name: (v = (h = this.config.user) == null ? void 0 : h.data) == null ? void 0 : v.name,
439
- non_verified_custom_data: (b = (j = this.config.user) == null ? void 0 : j.data) == null ? void 0 : b.customData
445
+ email: (m = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : m.email,
446
+ non_verified_name: (b = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : b.name,
447
+ non_verified_custom_data: (k = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : k.customData
440
448
  });
441
449
  }
442
- }, this.createUnverifiedContact = async (l, o) => {
443
- this.state.setPartial({ extraCollectedData: o });
450
+ }, this.createUnverifiedContact = async (_, n) => {
451
+ this.state.setPartial({ extraCollectedData: n });
444
452
  try {
445
453
  this.state.setPartial({
446
454
  isCreatingUnverifiedContact: !0,
447
455
  isErrorCreatingUnverifiedContact: !1
448
456
  });
449
- const { data: t } = await this.api.createUnverifiedContact(l);
457
+ const { data: t } = await this.api.createUnverifiedContact(_);
450
458
  t != null && t.token ? await this.setUnverifiedContact(t.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
451
459
  } catch (t) {
452
- this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), m.error("failed to create an unverified contact", {
460
+ this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), h.error("failed to create an unverified contact", {
453
461
  _e: t instanceof Error ? t.message : String(t)
454
462
  });
455
463
  } finally {
456
464
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
457
465
  }
458
466
  }, this.recoverFromStaleToken = async () => {
459
- var l, o, t, s, r, c, p, d, u, g;
460
- if ((l = this.config.user) != null && l.token) return !1;
467
+ var _, n, t, r, c, d, l, p, u, m;
468
+ if ((_ = this.config.user) != null && _.token) return !1;
461
469
  this.api.setAuthToken(""), this.state.setPartial({ contact: null });
462
470
  try {
463
- await ((o = this.storageCtx) == null ? void 0 : o.clearContactToken()), await ((t = this.storageCtx) == null ? void 0 : t.clearActiveSessionId());
464
- } catch (h) {
465
- m.warn("failed to clear a stale contact token", {
466
- error: h instanceof Error ? h.message : String(h)
471
+ await ((n = this.storageCtx) == null ? void 0 : n.clearContactToken()), await ((t = this.storageCtx) == null ? void 0 : t.clearActiveSessionId());
472
+ } catch (g) {
473
+ h.warn("failed to clear a stale contact token", {
474
+ error: g instanceof Error ? g.message : String(g)
467
475
  });
468
476
  }
469
477
  return await this.createUnverifiedContact({
470
- email: (r = (s = this.config.user) == null ? void 0 : s.data) == null ? void 0 : r.email,
471
- non_verified_name: (p = (c = this.config.user) == null ? void 0 : c.data) == null ? void 0 : p.name,
472
- non_verified_custom_data: (u = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : u.customData
473
- }), !!((g = this.state.get().contact) != null && g.token);
474
- }, this.setUnverifiedContact = async (l) => {
475
- var s, r, c, p;
476
- const o = await ((s = this.storageCtx) == null ? void 0 : s.getExternalContactId()), t = ((r = this.config.user) == null ? void 0 : r.externalId) || o || I();
477
- this.api.setAuthToken(l), await ((c = this.storageCtx) == null ? void 0 : c.setContactToken(l)), await ((p = this.storageCtx) == null ? void 0 : p.setExternalContactId(t)), this.state.setPartial({ contact: { token: l, externalId: t } });
478
- }, this.config = e, this.storageCtx = n, this.api = a, this.state = new w({
478
+ email: (c = (r = this.config.user) == null ? void 0 : r.data) == null ? void 0 : c.email,
479
+ non_verified_name: (l = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : l.name,
480
+ non_verified_custom_data: (u = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : u.customData
481
+ }), !!((m = this.state.get().contact) != null && m.token);
482
+ }, this.setUnverifiedContact = async (_) => {
483
+ var r, c, d, l;
484
+ const n = await ((r = this.storageCtx) == null ? void 0 : r.getExternalContactId()), t = ((c = this.config.user) == null ? void 0 : c.externalId) || n || D();
485
+ this.api.setAuthToken(_), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(_)), await ((l = this.storageCtx) == null ? void 0 : l.setExternalContactId(t)), this.state.setPartial({ contact: { token: _, externalId: t } });
486
+ }, this.config = e, this.storageCtx = s, this.api = a, this.state = new j({
479
487
  contact: (i = e.user) != null && i.token ? {
480
488
  token: e.user.token,
481
489
  // Set optional externalId from config... not local storage
@@ -487,49 +495,49 @@ class ie {
487
495
  }), this.autoCreateUnverifiedUserIfNotExists();
488
496
  }
489
497
  }
490
- class re {
498
+ class ce {
491
499
  constructor(e) {
492
- this.api = e, this.state = new w([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (a) => {
493
- const n = a.map(
500
+ this.api = e, this.state = new j([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (a) => {
501
+ const s = a.map(
494
502
  (i) => ({
495
503
  file: i,
496
- id: I(),
504
+ id: D(),
497
505
  status: "pending",
498
506
  progress: 0
499
507
  })
500
508
  );
501
- this.state.set([...this.state.get(), ...n]), n.forEach((i) => void this.upload(i));
509
+ this.state.set([...this.state.get(), ...s]), s.forEach((i) => void this.upload(i));
502
510
  }, this.cancel = (a) => {
503
- var n;
504
- (n = this.controllers.get(a)) == null || n.abort(), this.controllers.delete(a), this.state.set(this.state.get().filter((i) => i.id !== a));
511
+ var s;
512
+ (s = this.controllers.get(a)) == null || s.abort(), this.controllers.delete(a), this.state.set(this.state.get().filter((i) => i.id !== a));
505
513
  }, this.reset = () => {
506
514
  this.controllers.forEach((a) => a.abort()), this.controllers.clear(), this.state.reset();
507
515
  };
508
516
  }
509
517
  update(e, a) {
510
518
  this.state.set(
511
- this.state.get().map((n) => n.id === e ? { ...n, ...a } : n)
519
+ this.state.get().map((s) => s.id === e ? { ...s, ...a } : s)
512
520
  );
513
521
  }
514
522
  async upload(e) {
515
523
  const a = new AbortController();
516
524
  this.controllers.set(e.id, a), this.update(e.id, { status: "uploading" });
517
525
  try {
518
- const n = await this.api.uploadFile({
526
+ const s = await this.api.uploadFile({
519
527
  file: e.file,
520
528
  abortSignal: a.signal,
521
529
  onProgress: (i) => this.update(e.id, { progress: i })
522
530
  });
523
531
  this.update(e.id, {
524
532
  status: "success",
525
- fileUrl: n.fileUrl,
533
+ fileUrl: s.fileUrl,
526
534
  progress: 100
527
535
  });
528
- } catch (n) {
536
+ } catch (s) {
529
537
  a.signal.aborted || this.update(e.id, {
530
538
  status: "error",
531
539
  progress: 0,
532
- error: n instanceof Error ? n.message : "Upload failed"
540
+ error: s instanceof Error ? s.message : "Upload failed"
533
541
  });
534
542
  } finally {
535
543
  this.controllers.delete(e.id);
@@ -537,25 +545,25 @@ class re {
537
545
  }
538
546
  }
539
547
  function z() {
540
- return I();
548
+ return D();
541
549
  }
542
- class _e {
550
+ class pe {
543
551
  constructor({
544
552
  api: e,
545
553
  sessionCtx: a,
546
- messageCtx: n
554
+ messageCtx: s
547
555
  }) {
548
556
  this.submitCsat = async (i) => {
549
- var r;
550
- const l = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
551
- if (!l)
557
+ var c;
558
+ const _ = (c = this.sessionCtx.sessionState.get().session) == null ? void 0 : c.id;
559
+ if (!_)
552
560
  return { data: null, error: "No session id found" };
553
- const o = z();
561
+ const n = z();
554
562
  this.messageCtx.state.setPartial({
555
563
  messages: [
556
564
  ...this.messageCtx.state.get().messages,
557
565
  {
558
- id: o,
566
+ id: n,
559
567
  type: "SYSTEM",
560
568
  subtype: "csat_submitted",
561
569
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -568,16 +576,16 @@ class _e {
568
576
  }
569
577
  ]
570
578
  });
571
- const { data: t, error: s } = await this.api.submitCsat({
579
+ const { data: t, error: r } = await this.api.submitCsat({
572
580
  ...i,
573
- system_message_uuid: o,
574
- session_id: l
581
+ system_message_uuid: n,
582
+ session_id: _
575
583
  });
576
- return { data: t, error: s };
577
- }, this.api = e, this.sessionCtx = a, this.messageCtx = n;
584
+ return { data: t, error: r };
585
+ }, this.api = e, this.sessionCtx = a, this.messageCtx = s;
578
586
  }
579
587
  }
580
- const le = [
588
+ const de = [
581
589
  {
582
590
  action: "newparagraph",
583
591
  phrases: {
@@ -652,7 +660,7 @@ const le = [
652
660
  it: ["invia messaggio"]
653
661
  }
654
662
  }
655
- ], ce = [
663
+ ], ue = [
656
664
  "en",
657
665
  "es",
658
666
  "fr",
@@ -660,25 +668,25 @@ const le = [
660
668
  "pt",
661
669
  "it"
662
670
  ];
663
- function pe(_) {
664
- return ce.includes(_);
671
+ function me(o) {
672
+ return ue.includes(o);
665
673
  }
666
- function de(_) {
667
- return _.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
674
+ function he(o) {
675
+ return o.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
668
676
  }
669
- function ue(_) {
670
- const e = le.flatMap(
671
- (i) => _.flatMap(
672
- (l) => i.phrases[l].map((o) => ({ phrase: o, action: i.action }))
677
+ function ge(o) {
678
+ const e = de.flatMap(
679
+ (i) => o.flatMap(
680
+ (_) => i.phrases[_].map((n) => ({ phrase: n, action: i.action }))
673
681
  )
674
- ), a = e.map((i) => de(i.phrase)).sort((i, l) => l.length - i.length).join("|"), n = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
682
+ ), a = e.map((i) => he(i.phrase)).sort((i, _) => _.length - i.length).join("|"), s = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
675
683
  return {
676
684
  regex: new RegExp(
677
- `${n}(${a})` + String.raw`([.,!?;:])(?=\s|$)`,
685
+ `${s}(${a})` + String.raw`([.,!?;:])(?=\s|$)`,
678
686
  "giu"
679
687
  ),
680
688
  finalRegex: new RegExp(
681
- `${n}(${a})` + String.raw`([.,!?;:]?)(?=\s|$)`,
689
+ `${s}(${a})` + String.raw`([.,!?;:]?)(?=\s|$)`,
682
690
  "giu"
683
691
  ),
684
692
  phraseToAction: new Map(
@@ -687,40 +695,40 @@ function ue(_) {
687
695
  longestPhrase: Math.max(...e.map((i) => i.phrase.length))
688
696
  };
689
697
  }
690
- const F = /* @__PURE__ */ new Map();
691
- function A(_) {
692
- const e = _ && pe(_) && _ !== "en" ? _ : null, a = e ?? "en";
693
- let n = F.get(a);
694
- return n || (n = ue(e ? ["en", e] : ["en"]), F.set(a, n)), n;
698
+ const U = /* @__PURE__ */ new Map();
699
+ function T(o) {
700
+ const e = o && me(o) && o !== "en" ? o : null, a = e ?? "en";
701
+ let s = U.get(a);
702
+ return s || (s = ge(e ? ["en", e] : ["en"]), U.set(a, s)), s;
695
703
  }
696
- function me(_) {
697
- const e = _.replace(/\s+$/, "");
704
+ function ke(o) {
705
+ const e = o.replace(/\s+$/, "");
698
706
  if (!e) return "";
699
707
  const a = e.replace(/[.!?]+$/, "");
700
- let n = -1;
708
+ let s = -1;
701
709
  for (let i = a.length - 1; i >= 0; i--) {
702
- const l = a[i];
703
- if (l === "." || l === "!" || l === "?" || l === `
710
+ const _ = a[i];
711
+ if (_ === "." || _ === "!" || _ === "?" || _ === `
704
712
  `) {
705
- n = i + 1;
713
+ s = i + 1;
706
714
  break;
707
715
  }
708
716
  }
709
- return n === -1 ? "" : `${a.slice(0, n)} `.replace(/\n $/, `
717
+ return s === -1 ? "" : `${a.slice(0, s)} `.replace(/\n $/, `
710
718
  `);
711
719
  }
712
- const he = new RegExp(
720
+ const be = new RegExp(
713
721
  String.raw`(^- |\n(?:- )?)(\p{Ll})`,
714
722
  "gu"
715
723
  );
716
- function ge(_) {
717
- return _.replace(
718
- he,
719
- (e, a, n) => a + n.toUpperCase()
724
+ function fe(o) {
725
+ return o.replace(
726
+ be,
727
+ (e, a, s) => a + s.toUpperCase()
720
728
  );
721
729
  }
722
- function ke(_) {
723
- return _.length <= 3 && /^\s*$/.test(_) ? !0 : /[.!?\n]\s{0,3}$/.test(_.slice(-6));
730
+ function ve(o) {
731
+ return o.length <= 3 && /^\s*$/.test(o) ? !0 : /[.!?\n]\s{0,3}$/.test(o.slice(-6));
724
732
  }
725
733
  class C {
726
734
  /**
@@ -729,35 +737,35 @@ class C {
729
737
  * result never depends on delta chunking.
730
738
  */
731
739
  static process(e, a) {
732
- const n = A(a == null ? void 0 : a.language), i = a != null && a.final ? "" : C.commandPrefixTail(e, a == null ? void 0 : a.language), l = e.slice(0, e.length - i.length), o = a != null && a.final ? n.finalRegex : n.regex;
733
- let t = "", s = null, r = 0;
734
- for (const p of Array.from(l.matchAll(o))) {
735
- const [, d = ""] = p, u = n.phraseToAction.get(d.toLowerCase());
740
+ const s = T(a == null ? void 0 : a.language), i = a != null && a.final ? "" : C.commandPrefixTail(e, a == null ? void 0 : a.language), _ = e.slice(0, e.length - i.length), n = a != null && a.final ? s.finalRegex : s.regex;
741
+ let t = "", r = null, c = 0;
742
+ for (const l of Array.from(_.matchAll(n))) {
743
+ const [, p = ""] = l, u = s.phraseToAction.get(p.toLowerCase());
736
744
  if (u)
737
- if (t += l.slice(r, p.index), r = p.index + p[0].length, u === "newline") t = `${t.replace(/[ \t]+$/, "")}
745
+ if (t += _.slice(c, l.index), c = l.index + l[0].length, u === "newline") t = `${t.replace(/[ \t]+$/, "")}
738
746
  `;
739
747
  else if (u === "newparagraph")
740
748
  t = `${t.replace(/[ \t]+$/, "")}
741
749
 
742
750
  `;
743
751
  else if (u === "bullet") {
744
- const g = t.replace(/[ \t]+$/, "");
745
- t = g === "" || g.endsWith(`
746
- `) ? `${g}- ` : `${g}
752
+ const m = t.replace(/[ \t]+$/, "");
753
+ t = m === "" || m.endsWith(`
754
+ `) ? `${m}- ` : `${m}
747
755
  - `;
748
- } else if (u === "scratch") t = me(t);
756
+ } else if (u === "scratch") t = ke(t);
749
757
  else {
750
- s = u === "send" ? "send" : "stop";
758
+ r = u === "send" ? "send" : "stop";
751
759
  break;
752
760
  }
753
761
  }
754
- return s === null && (t += l.slice(r)), { text: ge(
762
+ return r === null && (t += _.slice(c)), { text: fe(
755
763
  t.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
756
764
  `).replace(/\n[ \t]+/g, `
757
765
  `).replace(/(^|\n)- +/g, "$1- ").replace(/ {2,}/g, " ").replace(/\n{3,}/g, `
758
766
 
759
767
  `)
760
- ), pendingTail: i, control: s };
768
+ ), pendingTail: i, control: r };
761
769
  }
762
770
  /**
763
771
  * Longest suffix of `raw` that could still become a command — a proper
@@ -769,15 +777,15 @@ class C {
769
777
  * mid-sentence.
770
778
  */
771
779
  static commandPrefixTail(e, a) {
772
- const n = A(a), i = Math.min(e.length, n.longestPhrase + 2);
773
- for (let l = i; l > 0; l--) {
774
- const o = e.length - l;
775
- if (!ke(e.slice(0, o))) continue;
776
- const t = e.slice(o).toLowerCase(), s = t.replace(/^\s+/, "");
777
- if (s) {
778
- for (const r of Array.from(n.phraseToAction.keys()))
779
- if (r.startsWith(s))
780
- return e.slice(o + (t.length - s.length));
780
+ const s = T(a), i = Math.min(e.length, s.longestPhrase + 2);
781
+ for (let _ = i; _ > 0; _--) {
782
+ const n = e.length - _;
783
+ if (!ve(e.slice(0, n))) continue;
784
+ const t = e.slice(n).toLowerCase(), r = t.replace(/^\s+/, "");
785
+ if (r) {
786
+ for (const c of Array.from(s.phraseToAction.keys()))
787
+ if (c.startsWith(r))
788
+ return e.slice(n + (t.length - r.length));
781
789
  }
782
790
  }
783
791
  return "";
@@ -788,12 +796,12 @@ class C {
788
796
  * the manager's silence timer.
789
797
  */
790
798
  static pendingTailIsCompletePhrase(e, a) {
791
- const n = C.commandPrefixTail(e, a).trim().toLowerCase();
792
- return n ? A(a).phraseToAction.has(n) : !1;
799
+ const s = C.commandPrefixTail(e, a).trim().toLowerCase();
800
+ return s ? T(a).phraseToAction.has(s) : !1;
793
801
  }
794
802
  }
795
- const be = 55, fe = 90;
796
- class O {
803
+ const ye = 55, we = 90;
804
+ class B {
797
805
  /**
798
806
  * Next paced step toward `processed`: normally one word per tick so text
799
807
  * flows evenly instead of landing in bursty chunks; proportionally larger
@@ -805,9 +813,9 @@ class O {
805
813
  processed: a
806
814
  }) {
807
815
  if (a.length <= e.length) return a;
808
- const n = a.length - e.length;
809
- if (n > fe)
810
- return a.slice(0, e.length + Math.ceil(n / 3));
816
+ const s = a.length - e.length;
817
+ if (s > we)
818
+ return a.slice(0, e.length + Math.ceil(s / 3));
811
819
  let i = e.length;
812
820
  for (; i < a.length && /\s/.test(a.charAt(i)); ) i++;
813
821
  for (; i < a.length && !/\s/.test(a.charAt(i)); ) i++;
@@ -818,12 +826,12 @@ class O {
818
826
  if (!e) return;
819
827
  const a = e.toLowerCase();
820
828
  if (/^zh-(cn|tw|hk)$/.test(a)) return a;
821
- const n = a.split("-")[0];
822
- return n && /^[a-z]{2,3}$/.test(n) ? n : void 0;
829
+ const s = a.split("-")[0];
830
+ return s && /^[a-z]{2,3}$/.test(s) ? s : void 0;
823
831
  }
824
832
  }
825
- const ve = 2e4;
826
- class ye {
833
+ const je = 2e4;
834
+ class Se {
827
835
  constructor() {
828
836
  this.cached = null, this.inflight = null;
829
837
  }
@@ -831,7 +839,7 @@ class ye {
831
839
  get() {
832
840
  if (!this.cached) return null;
833
841
  const e = Date.parse(this.cached.expiresAt);
834
- return Number.isNaN(e) || e - Date.now() < ve ? (this.cached = null, null) : this.cached;
842
+ return Number.isNaN(e) || e - Date.now() < je ? (this.cached = null, null) : this.cached;
835
843
  }
836
844
  /**
837
845
  * Resolve a mint, deduping concurrent requests (hover-prewarm racing a
@@ -839,7 +847,7 @@ class ye {
839
847
  */
840
848
  async resolve(e) {
841
849
  const a = this.get();
842
- return a || (this.inflight || (this.inflight = e().then((n) => (this.cached = n, n)).finally(() => {
850
+ return a || (this.inflight || (this.inflight = e().then((s) => (this.cached = s, s)).finally(() => {
843
851
  this.inflight = null;
844
852
  })), this.inflight);
845
853
  }
@@ -848,60 +856,60 @@ class ye {
848
856
  this.cached = null;
849
857
  }
850
858
  }
851
- function U(_) {
852
- return typeof _ == "object" && _ !== null && !Array.isArray(_);
859
+ function V(o) {
860
+ return typeof o == "object" && o !== null && !Array.isArray(o);
853
861
  }
854
- function we(_) {
855
- if (!U(_) || typeof _.type != "string") return null;
856
- const e = U(_.error) ? _.error : null;
862
+ function xe(o) {
863
+ if (!V(o) || typeof o.type != "string") return null;
864
+ const e = V(o.error) ? o.error : null;
857
865
  return {
858
- type: _.type,
859
- delta: typeof _.delta == "string" ? _.delta : void 0,
866
+ type: o.type,
867
+ delta: typeof o.delta == "string" ? o.delta : void 0,
860
868
  errorMessage: e && typeof e.message == "string" ? e.message : void 0
861
869
  };
862
870
  }
863
- const je = "https://api.openai.com/v1/realtime/calls", Se = 10 * 60 * 1e3, xe = 15e3, ze = 5e3;
864
- class E extends Error {
871
+ const ze = "https://api.openai.com/v1/realtime/calls", Ce = 10 * 60 * 1e3, qe = 15e3, Ee = 5e3;
872
+ class A extends Error {
865
873
  }
866
- class Ce {
874
+ class Ae {
867
875
  constructor({
868
876
  mintToken: e,
869
877
  onDelta: a,
870
- onState: n,
878
+ onState: s,
871
879
  onError: i,
872
- onLevel: l
880
+ onLevel: _
873
881
  }) {
874
- this.state = "idle", this.pc = null, this.dc = null, this.stream = null, this.audioContext = null, this.levelRaf = 0, this.timers = [], this.loggedParseFailure = !1, this.mintToken = e, this.onDelta = a, this.onState = n, this.onError = i, this.onLevel = l;
882
+ this.state = "idle", this.pc = null, this.dc = null, this.stream = null, this.audioContext = null, this.levelRaf = 0, this.timers = [], this.loggedParseFailure = !1, this.mintToken = e, this.onDelta = a, this.onState = s, this.onError = i, this.onLevel = _;
875
883
  }
876
884
  async start() {
877
885
  if (this.state === "idle") {
878
886
  this.setState("connecting"), this.timers.push(
879
887
  setTimeout(() => {
880
888
  this.state === "connecting" && this.fail("unavailable");
881
- }, xe)
882
- ), this.timers.push(setTimeout(() => this.stop(), Se));
889
+ }, qe)
890
+ ), this.timers.push(setTimeout(() => this.stop(), Ce));
883
891
  try {
884
892
  const e = this.requestMicrophone();
885
- e.then((c) => {
886
- (this.isTornDown() || this.stream && this.stream !== c) && c.getTracks().forEach((p) => p.stop());
893
+ e.then((d) => {
894
+ (this.isTornDown() || this.stream && this.stream !== d) && d.getTracks().forEach((l) => l.stop());
887
895
  }).catch(() => {
888
896
  });
889
- const [a, n] = await Promise.all([e, this.mintToken()]);
897
+ const [a, s] = await Promise.all([e, this.mintToken()]);
890
898
  if (this.isTornDown()) {
891
- a.getTracks().forEach((c) => c.stop());
899
+ a.getTracks().forEach((d) => d.stop());
892
900
  return;
893
901
  }
894
902
  this.stream = a, this.startLevelMeter(a);
895
903
  const i = new RTCPeerConnection();
896
904
  this.pc = i;
897
- const [l] = a.getAudioTracks();
898
- if (!l) throw new E("No audio track");
899
- i.addTrack(l, a);
900
- const o = i.createDataChannel("oai-events");
901
- this.dc = o, o.addEventListener(
905
+ const [_] = a.getAudioTracks();
906
+ if (!_) throw new A("No audio track");
907
+ i.addTrack(_, a);
908
+ const n = i.createDataChannel("oai-events");
909
+ this.dc = n, n.addEventListener(
902
910
  "message",
903
- (c) => this.handleServerEvent(c.data)
904
- ), o.addEventListener("open", () => {
911
+ (d) => this.handleServerEvent(d.data)
912
+ ), n.addEventListener("open", () => {
905
913
  this.state === "connecting" && this.setState("listening");
906
914
  }), i.addEventListener("connectionstatechange", () => {
907
915
  if (i.connectionState === "failed") {
@@ -911,26 +919,26 @@ class Ce {
911
919
  i.connectionState === "disconnected" && this.timers.push(
912
920
  setTimeout(() => {
913
921
  this.pc === i && i.connectionState !== "connected" && this.fail("unavailable");
914
- }, ze)
922
+ }, Ee)
915
923
  );
916
924
  });
917
925
  const t = await i.createOffer();
918
926
  await i.setLocalDescription(t);
919
- const s = await fetch(je, {
927
+ const r = await fetch(ze, {
920
928
  method: "POST",
921
929
  headers: {
922
- Authorization: `Bearer ${n.token}`,
930
+ Authorization: `Bearer ${s.token}`,
923
931
  "Content-Type": "application/sdp"
924
932
  },
925
933
  body: t.sdp
926
934
  });
927
- if (!s.ok)
928
- throw new Error(`Realtime handshake failed (${s.status})`);
929
- const r = await s.text();
935
+ if (!r.ok)
936
+ throw new Error(`Realtime handshake failed (${r.status})`);
937
+ const c = await r.text();
930
938
  if (this.isTornDown()) return;
931
- await i.setRemoteDescription({ type: "answer", sdp: r });
939
+ await i.setRemoteDescription({ type: "answer", sdp: c });
932
940
  } catch (e) {
933
- e instanceof E ? this.fail("microphone") : (m.error("dictation session failed to start", {
941
+ e instanceof A ? this.fail("microphone") : (h.error("dictation session failed to start", {
934
942
  _e: e instanceof Error ? e.message : String(e)
935
943
  }), this.fail("unavailable"));
936
944
  }
@@ -942,7 +950,7 @@ class Ce {
942
950
  async requestMicrophone() {
943
951
  var e;
944
952
  if (!((e = navigator.mediaDevices) != null && e.getUserMedia))
945
- throw new E("Microphone is not supported");
953
+ throw new A("Microphone is not supported");
946
954
  try {
947
955
  return await navigator.mediaDevices.getUserMedia({
948
956
  audio: {
@@ -952,7 +960,7 @@ class Ce {
952
960
  }
953
961
  });
954
962
  } catch (a) {
955
- throw new E(
963
+ throw new A(
956
964
  a instanceof DOMException ? a.name : "Could not access the microphone"
957
965
  );
958
966
  }
@@ -963,24 +971,24 @@ class Ce {
963
971
  try {
964
972
  a = JSON.parse(e);
965
973
  } catch {
966
- this.loggedParseFailure || (this.loggedParseFailure = !0, m.error("dictation server event was not valid JSON", {
974
+ this.loggedParseFailure || (this.loggedParseFailure = !0, h.error("dictation server event was not valid JSON", {
967
975
  snippet: e.slice(0, 120)
968
976
  }));
969
977
  return;
970
978
  }
971
- const n = we(a);
972
- if (!n) return;
973
- const { type: i, delta: l } = n;
979
+ const s = xe(a);
980
+ if (!s) return;
981
+ const { type: i, delta: _ } = s;
974
982
  if (i === "session.created" || i === "transcription_session.created") {
975
983
  this.setState("listening");
976
984
  return;
977
985
  }
978
- if (i === "conversation.item.input_audio_transcription.delta" && l) {
979
- this.state === "connecting" && this.setState("listening"), this.onDelta(l);
986
+ if (i === "conversation.item.input_audio_transcription.delta" && _) {
987
+ this.state === "connecting" && this.setState("listening"), this.onDelta(_);
980
988
  return;
981
989
  }
982
- i === "error" && (m.error("dictation server event error", {
983
- _e: n.errorMessage ?? "unknown"
990
+ i === "error" && (h.error("dictation server event error", {
991
+ _e: s.errorMessage ?? "unknown"
984
992
  }), this.fail("unavailable"));
985
993
  }
986
994
  startLevelMeter(e) {
@@ -988,22 +996,22 @@ class Ce {
988
996
  try {
989
997
  const a = new AudioContext();
990
998
  this.audioContext = a;
991
- const n = a.createMediaStreamSource(e), i = a.createAnalyser();
992
- i.fftSize = 512, n.connect(i);
993
- const l = new Uint8Array(i.frequencyBinCount), o = () => {
994
- var r;
995
- i.getByteTimeDomainData(l);
999
+ const s = a.createMediaStreamSource(e), i = a.createAnalyser();
1000
+ i.fftSize = 512, s.connect(i);
1001
+ const _ = new Uint8Array(i.frequencyBinCount), n = () => {
1002
+ var c;
1003
+ i.getByteTimeDomainData(_);
996
1004
  let t = 0;
997
- for (let c = 0; c < l.length; c++) {
998
- const p = ((l[c] ?? 128) - 128) / 128;
999
- t += p * p;
1005
+ for (let d = 0; d < _.length; d++) {
1006
+ const l = ((_[d] ?? 128) - 128) / 128;
1007
+ t += l * l;
1000
1008
  }
1001
- const s = Math.sqrt(t / l.length);
1002
- (r = this.onLevel) == null || r.call(this, Math.min(1, s * 4)), this.levelRaf = requestAnimationFrame(o);
1009
+ const r = Math.sqrt(t / _.length);
1010
+ (c = this.onLevel) == null || c.call(this, Math.min(1, r * 4)), this.levelRaf = requestAnimationFrame(n);
1003
1011
  };
1004
- this.levelRaf = requestAnimationFrame(o);
1012
+ this.levelRaf = requestAnimationFrame(n);
1005
1013
  } catch (a) {
1006
- m.error("dictation level meter unavailable", {
1014
+ h.error("dictation level meter unavailable", {
1007
1015
  _e: a instanceof Error ? a.message : String(a)
1008
1016
  });
1009
1017
  }
@@ -1015,10 +1023,10 @@ class Ce {
1015
1023
  this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(e));
1016
1024
  }
1017
1025
  teardown() {
1018
- var e, a, n, i;
1019
- this.timers.forEach((l) => clearTimeout(l)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (a = this.pc) == null || a.close(), this.pc = null, (n = this.stream) == null || n.getTracks().forEach((l) => l.stop()), this.stream = null, (i = this.audioContext) == null || i.close().catch((l) => {
1020
- m.error("failed to close dictation audio context", {
1021
- _e: String(l)
1026
+ var e, a, s, i;
1027
+ this.timers.forEach((_) => clearTimeout(_)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (a = this.pc) == null || a.close(), this.pc = null, (s = this.stream) == null || s.getTracks().forEach((_) => _.stop()), this.stream = null, (i = this.audioContext) == null || i.close().catch((_) => {
1028
+ h.error("failed to close dictation audio context", {
1029
+ _e: String(_)
1022
1030
  });
1023
1031
  }), this.audioContext = null;
1024
1032
  }
@@ -1026,43 +1034,43 @@ class Ce {
1026
1034
  this.state !== e && (this.state = e, this.onState(e));
1027
1035
  }
1028
1036
  }
1029
- const qe = 1300, Ee = { status: "idle", error: null };
1030
- class Pe {
1037
+ const Pe = 1300, Te = { status: "idle", error: null };
1038
+ class Me {
1031
1039
  constructor({ api: e, config: a }) {
1032
- this.state = new w(Ee), this.levelRef = { current: 0 }, this.mintCache = new ye(), this.session = null, this.target = null, this.prefix = "", this.raw = "", this.processed = "", this.displayed = "", this.dripTimer = null, this.silenceTimer = null, this.isActive = () => this.session !== null, this.prewarm = () => {
1033
- this.mintToken().catch((n) => {
1034
- this.mintCache.clear(), m.error("dictation token prewarm failed", {
1035
- _e: n instanceof Error ? n.message : String(n)
1040
+ this.state = new j(Te), this.levelRef = { current: 0 }, this.mintCache = new Se(), this.session = null, this.target = null, this.prefix = "", this.raw = "", this.processed = "", this.displayed = "", this.dripTimer = null, this.silenceTimer = null, this.isActive = () => this.session !== null, this.prewarm = () => {
1041
+ this.mintToken().catch((s) => {
1042
+ this.mintCache.clear(), h.error("dictation token prewarm failed", {
1043
+ _e: s instanceof Error ? s.message : String(s)
1036
1044
  });
1037
1045
  });
1038
- }, this.start = (n) => {
1039
- this.session && this.teardown(), this.target = n, this.language = O.languageHint(
1046
+ }, this.start = (s) => {
1047
+ this.session && this.teardown(), this.target = s, this.language = B.languageHint(
1040
1048
  this.config.language ?? navigator.language
1041
- ), this.prefix = n.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1042
- const i = new Ce({
1049
+ ), this.prefix = s.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1050
+ const i = new Ae({
1043
1051
  mintToken: this.mintToken,
1044
- onLevel: (l) => {
1045
- this.levelRef.current = l;
1052
+ onLevel: (_) => {
1053
+ this.levelRef.current = _;
1046
1054
  },
1047
- onState: (l) => {
1048
- i === this.session && (l === "connecting" && this.state.set({ status: "connecting", error: null }), l === "listening" && this.state.set({ status: "listening", error: null }), l === "stopped" && this.teardown());
1055
+ onState: (_) => {
1056
+ i === this.session && (_ === "connecting" && this.state.set({ status: "connecting", error: null }), _ === "listening" && this.state.set({ status: "listening", error: null }), _ === "stopped" && this.teardown());
1049
1057
  },
1050
- onError: (l) => {
1051
- i === this.session && (this.mintCache.clear(), this.teardown({ error: l, executeFinalCommand: !1 }));
1058
+ onError: (_) => {
1059
+ i === this.session && (this.mintCache.clear(), this.teardown({ error: _, executeFinalCommand: !1 }));
1052
1060
  },
1053
- onDelta: (l) => {
1061
+ onDelta: (_) => {
1054
1062
  if (i !== this.session || !this.target) return;
1055
1063
  if (!this.isConsistent()) {
1056
1064
  this.teardown();
1057
1065
  return;
1058
1066
  }
1059
- this.raw += l;
1060
- const o = this.ingest();
1061
- if (o === "stop") {
1067
+ this.raw += _;
1068
+ const n = this.ingest();
1069
+ if (n === "stop") {
1062
1070
  this.teardown();
1063
1071
  return;
1064
1072
  }
1065
- if (o === "send") {
1073
+ if (n === "send") {
1066
1074
  this.teardown({ send: !0 });
1067
1075
  return;
1068
1076
  }
@@ -1074,7 +1082,7 @@ class Pe {
1074
1082
  this.raw = `${this.raw}.`;
1075
1083
  const t = this.ingest();
1076
1084
  t === "stop" ? this.teardown() : t === "send" && this.teardown({ send: !0 });
1077
- }, qe));
1085
+ }, Pe));
1078
1086
  }
1079
1087
  });
1080
1088
  this.session = i, this.state.set({ status: "connecting", error: null }), this.dripTimer = setInterval(() => {
@@ -1084,13 +1092,13 @@ class Pe {
1084
1092
  return;
1085
1093
  }
1086
1094
  this.applyDisplayed(
1087
- O.nextDripText({
1095
+ B.nextDripText({
1088
1096
  displayed: this.displayed,
1089
1097
  processed: this.processed
1090
1098
  })
1091
1099
  );
1092
1100
  }
1093
- }, be), i.start();
1101
+ }, ye), i.start();
1094
1102
  }, this.stop = () => {
1095
1103
  this.session && this.teardown();
1096
1104
  }, this.mintToken = async () => this.mintCache.resolve(
@@ -1117,18 +1125,18 @@ class Pe {
1117
1125
  this.silenceTimer && clearTimeout(this.silenceTimer), this.silenceTimer = null;
1118
1126
  }
1119
1127
  teardown(e) {
1120
- var l;
1121
- const a = this.session, n = this.target;
1128
+ var _;
1129
+ const a = this.session, s = this.target;
1122
1130
  this.dripTimer && clearInterval(this.dripTimer), this.dripTimer = null, this.stopSilenceTimer();
1123
1131
  let i = (e == null ? void 0 : e.send) ?? !1;
1124
- if (n && this.isConsistent()) {
1125
- const o = this.ingest({ final: !0 });
1126
- (e == null ? void 0 : e.executeFinalCommand) !== !1 && o === "send" && (i = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1132
+ if (s && this.isConsistent()) {
1133
+ const n = this.ingest({ final: !0 });
1134
+ (e == null ? void 0 : e.executeFinalCommand) !== !1 && n === "send" && (i = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1127
1135
  }
1128
- this.session = null, this.target = null, a == null || a.stop(), this.levelRef.current = 0, this.state.set({ status: "idle", error: (e == null ? void 0 : e.error) ?? null }), i && ((l = n == null ? void 0 : n.onSend) == null || l.call(n));
1136
+ this.session = null, this.target = null, a == null || a.stop(), this.levelRef.current = 0, this.state.set({ status: "idle", error: (e == null ? void 0 : e.error) ?? null }), i && ((_ = s == null ? void 0 : s.onSend) == null || _.call(s));
1129
1137
  }
1130
1138
  }
1131
- const Ae = {
1139
+ const Ie = {
1132
1140
  write_a_message_placeholder: "اكتب رسالة...",
1133
1141
  your_issue_has_been_resolved: "تم حل مشكلتك!",
1134
1142
  new_conversation: "محادثة جديدة",
@@ -1228,7 +1236,7 @@ const Ae = {
1228
1236
  questions_send: "إرسال",
1229
1237
  questions_type_answer: "سأكتبها بنفسي",
1230
1238
  questions_answer_placeholder: "اكتب إجابتك…"
1231
- }, Te = {
1239
+ }, De = {
1232
1240
  write_a_message_placeholder: "একটি বার্তা লিখুন...",
1233
1241
  your_issue_has_been_resolved: "আপনার সমস্যা সমাধান হয়েছে!",
1234
1242
  new_conversation: "নতুন কথোপকথন",
@@ -1316,7 +1324,7 @@ const Ae = {
1316
1324
  questions_send: "পাঠান",
1317
1325
  questions_type_answer: "আমি লিখে দিচ্ছি",
1318
1326
  questions_answer_placeholder: "আপনার উত্তর লিখুন…"
1319
- }, Me = {
1327
+ }, Ne = {
1320
1328
  write_a_message_placeholder: "Напишете съобщение...",
1321
1329
  your_issue_has_been_resolved: "Вашият проблем е разрешен!",
1322
1330
  new_conversation: "Нов разговор",
@@ -1404,7 +1412,7 @@ const Ae = {
1404
1412
  questions_send: "Изпрати",
1405
1413
  questions_type_answer: "Ще напиша сам",
1406
1414
  questions_answer_placeholder: "Напишете отговора си…"
1407
- }, Ie = {
1415
+ }, Re = {
1408
1416
  write_a_message_placeholder: "Napište zprávu...",
1409
1417
  your_issue_has_been_resolved: "Váš problém byl vyřešen!",
1410
1418
  new_conversation: "Nová konverzace",
@@ -1492,7 +1500,7 @@ const Ae = {
1492
1500
  questions_send: "Odeslat",
1493
1501
  questions_type_answer: "Napíšu to sám",
1494
1502
  questions_answer_placeholder: "Napište svou odpověď…"
1495
- }, De = {
1503
+ }, Ke = {
1496
1504
  write_a_message_placeholder: "Skriv en besked...",
1497
1505
  your_issue_has_been_resolved: "Dit problem er løst!",
1498
1506
  new_conversation: "Ny samtale",
@@ -1580,7 +1588,7 @@ const Ae = {
1580
1588
  questions_send: "Send",
1581
1589
  questions_type_answer: "Jeg skriver det selv",
1582
1590
  questions_answer_placeholder: "Skriv dit svar…"
1583
- }, Ne = {
1591
+ }, Le = {
1584
1592
  write_a_message_placeholder: "Γράψτε ένα μήνυμα...",
1585
1593
  your_issue_has_been_resolved: "Το πρόβλημά σας επιλύθηκε!",
1586
1594
  new_conversation: "Νέα συνομιλία",
@@ -1668,7 +1676,7 @@ const Ae = {
1668
1676
  questions_send: "Αποστολή",
1669
1677
  questions_type_answer: "Θα το γράψω",
1670
1678
  questions_answer_placeholder: "Γράψτε την απάντησή σας…"
1671
- }, Re = {
1679
+ }, Fe = {
1672
1680
  write_a_message_placeholder: "Nachricht schreiben...",
1673
1681
  your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
1674
1682
  new_conversation: "Neue Konversation",
@@ -1756,7 +1764,7 @@ const Ae = {
1756
1764
  questions_send: "Senden",
1757
1765
  questions_type_answer: "Ich schreibe es selbst",
1758
1766
  questions_answer_placeholder: "Antwort eingeben…"
1759
- }, G = {
1767
+ }, $ = {
1760
1768
  write_a_message_placeholder: "Write a message...",
1761
1769
  your_issue_has_been_resolved: "Your issue has been resolved!",
1762
1770
  new_conversation: "New conversation",
@@ -1856,7 +1864,7 @@ const Ae = {
1856
1864
  questions_send: "Send",
1857
1865
  questions_type_answer: "I'll type it",
1858
1866
  questions_answer_placeholder: "Type your answer…"
1859
- }, Ke = {
1867
+ }, Oe = {
1860
1868
  write_a_message_placeholder: "Escribe un mensaje...",
1861
1869
  your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
1862
1870
  new_conversation: "Nueva conversación",
@@ -1944,7 +1952,7 @@ const Ae = {
1944
1952
  questions_send: "Enviar",
1945
1953
  questions_type_answer: "Lo escribo yo",
1946
1954
  questions_answer_placeholder: "Escribe tu respuesta…"
1947
- }, Le = {
1955
+ }, Ue = {
1948
1956
  write_a_message_placeholder: "Magsulat ng mensahe...",
1949
1957
  your_issue_has_been_resolved: "Nalutas na ang iyong isyu!",
1950
1958
  new_conversation: "Bagong usapan",
@@ -2032,7 +2040,7 @@ const Ae = {
2032
2040
  questions_send: "Ipadala",
2033
2041
  questions_type_answer: "Ako na ang magta-type",
2034
2042
  questions_answer_placeholder: "I-type ang iyong sagot…"
2035
- }, Fe = {
2043
+ }, Be = {
2036
2044
  write_a_message_placeholder: "Kirjoita viesti...",
2037
2045
  your_issue_has_been_resolved: "Ongelmasi on ratkaistu!",
2038
2046
  new_conversation: "Uusi keskustelu",
@@ -2120,7 +2128,7 @@ const Ae = {
2120
2128
  questions_send: "Lähetä",
2121
2129
  questions_type_answer: "Kirjoitan itse",
2122
2130
  questions_answer_placeholder: "Kirjoita vastauksesi…"
2123
- }, Oe = {
2131
+ }, Ve = {
2124
2132
  write_a_message_placeholder: "Écrivez un message...",
2125
2133
  your_issue_has_been_resolved: "Votre problème a été résolu !",
2126
2134
  new_conversation: "Nouvelle conversation",
@@ -2208,7 +2216,7 @@ const Ae = {
2208
2216
  questions_send: "Envoyer",
2209
2217
  questions_type_answer: "Je préfère écrire",
2210
2218
  questions_answer_placeholder: "Écrivez votre réponse…"
2211
- }, Ue = {
2219
+ }, He = {
2212
2220
  write_a_message_placeholder: "एक संदेश लिखें...",
2213
2221
  your_issue_has_been_resolved: "आपकी समस्या हल हो गई है!",
2214
2222
  new_conversation: "नई बातचीत",
@@ -2296,7 +2304,7 @@ const Ae = {
2296
2304
  questions_send: "भेजें",
2297
2305
  questions_type_answer: "मैं खुद लिखूंगा",
2298
2306
  questions_answer_placeholder: "अपना उत्तर लिखें…"
2299
- }, Be = {
2307
+ }, Ge = {
2300
2308
  write_a_message_placeholder: "Scrivi un messaggio...",
2301
2309
  your_issue_has_been_resolved: "Il tuo problema è stato risolto!",
2302
2310
  new_conversation: "Nuova conversazione",
@@ -2384,7 +2392,7 @@ const Ae = {
2384
2392
  questions_send: "Invia",
2385
2393
  questions_type_answer: "Lo scrivo io",
2386
2394
  questions_answer_placeholder: "Scrivi la tua risposta…"
2387
- }, Ve = {
2395
+ }, We = {
2388
2396
  write_a_message_placeholder: "メッセージを入力...",
2389
2397
  your_issue_has_been_resolved: "問題が解決しました!",
2390
2398
  new_conversation: "新しい会話",
@@ -2472,7 +2480,7 @@ const Ae = {
2472
2480
  questions_send: "送信",
2473
2481
  questions_type_answer: "自分で入力する",
2474
2482
  questions_answer_placeholder: "回答を入力してください…"
2475
- }, He = {
2483
+ }, $e = {
2476
2484
  write_a_message_placeholder: "메시지를 입력하세요...",
2477
2485
  your_issue_has_been_resolved: "문제가 해결되었습니다!",
2478
2486
  new_conversation: "새 대화",
@@ -2560,7 +2568,7 @@ const Ae = {
2560
2568
  questions_send: "보내기",
2561
2569
  questions_type_answer: "직접 입력할게요",
2562
2570
  questions_answer_placeholder: "답변을 입력하세요…"
2563
- }, Ge = {
2571
+ }, Ze = {
2564
2572
  write_a_message_placeholder: "Schrijf een bericht...",
2565
2573
  your_issue_has_been_resolved: "Uw probleem is opgelost!",
2566
2574
  new_conversation: "Nieuw gesprek",
@@ -2648,7 +2656,7 @@ const Ae = {
2648
2656
  questions_send: "Verzenden",
2649
2657
  questions_type_answer: "Ik typ het zelf",
2650
2658
  questions_answer_placeholder: "Typ je antwoord…"
2651
- }, We = {
2659
+ }, Je = {
2652
2660
  write_a_message_placeholder: "Skriv en melding...",
2653
2661
  your_issue_has_been_resolved: "Problemet ditt er løst!",
2654
2662
  new_conversation: "Ny samtale",
@@ -2736,7 +2744,7 @@ const Ae = {
2736
2744
  questions_send: "Send",
2737
2745
  questions_type_answer: "Jeg skriver det selv",
2738
2746
  questions_answer_placeholder: "Skriv svaret ditt…"
2739
- }, $e = {
2747
+ }, Ye = {
2740
2748
  write_a_message_placeholder: "Napisz wiadomość...",
2741
2749
  your_issue_has_been_resolved: "Twój problem został rozwiązany!",
2742
2750
  new_conversation: "Nowa rozmowa",
@@ -2824,7 +2832,7 @@ const Ae = {
2824
2832
  questions_send: "Wyślij",
2825
2833
  questions_type_answer: "Napiszę sam",
2826
2834
  questions_answer_placeholder: "Wpisz swoją odpowiedź…"
2827
- }, Ze = {
2835
+ }, Qe = {
2828
2836
  write_a_message_placeholder: "Escreva uma mensagem...",
2829
2837
  your_issue_has_been_resolved: "Seu problema foi resolvido!",
2830
2838
  new_conversation: "Nova conversa",
@@ -2912,7 +2920,7 @@ const Ae = {
2912
2920
  questions_send: "Enviar",
2913
2921
  questions_type_answer: "Prefiro escrever",
2914
2922
  questions_answer_placeholder: "Escreva a sua resposta…"
2915
- }, Je = {
2923
+ }, Xe = {
2916
2924
  write_a_message_placeholder: "Scrie un mesaj...",
2917
2925
  your_issue_has_been_resolved: "Problema ta a fost rezolvată!",
2918
2926
  new_conversation: "Conversație nouă",
@@ -3000,7 +3008,7 @@ const Ae = {
3000
3008
  questions_send: "Trimite",
3001
3009
  questions_type_answer: "Scriu eu",
3002
3010
  questions_answer_placeholder: "Scrieți răspunsul dvs.…"
3003
- }, Ye = {
3011
+ }, ea = {
3004
3012
  write_a_message_placeholder: "Skriv ett meddelande...",
3005
3013
  your_issue_has_been_resolved: "Ditt problem har lösts!",
3006
3014
  new_conversation: "Ny konversation",
@@ -3088,7 +3096,7 @@ const Ae = {
3088
3096
  questions_send: "Skicka",
3089
3097
  questions_type_answer: "Jag skriver själv",
3090
3098
  questions_answer_placeholder: "Skriv ditt svar…"
3091
- }, Qe = {
3099
+ }, aa = {
3092
3100
  write_a_message_placeholder: "Напишите сообщение...",
3093
3101
  your_issue_has_been_resolved: "Ваша проблема решена!",
3094
3102
  new_conversation: "Новый разговор",
@@ -3176,7 +3184,7 @@ const Ae = {
3176
3184
  questions_send: "Отправить",
3177
3185
  questions_type_answer: "Напишу сам",
3178
3186
  questions_answer_placeholder: "Напишите ваш ответ…"
3179
- }, Xe = {
3187
+ }, ta = {
3180
3188
  write_a_message_placeholder: "เขียนข้อความ...",
3181
3189
  your_issue_has_been_resolved: "ปัญหาของคุณได้รับการแก้ไขแล้ว!",
3182
3190
  new_conversation: "การสนทนาใหม่",
@@ -3264,7 +3272,7 @@ const Ae = {
3264
3272
  questions_send: "ส่ง",
3265
3273
  questions_type_answer: "ขอพิมพ์เอง",
3266
3274
  questions_answer_placeholder: "พิมพ์คำตอบของคุณ…"
3267
- }, ea = {
3275
+ }, sa = {
3268
3276
  write_a_message_placeholder: "Bir mesaj yazın...",
3269
3277
  your_issue_has_been_resolved: "Sorununuz çözüldü!",
3270
3278
  new_conversation: "Yeni konuşma",
@@ -3352,7 +3360,7 @@ const Ae = {
3352
3360
  questions_send: "Gönder",
3353
3361
  questions_type_answer: "Kendim yazayım",
3354
3362
  questions_answer_placeholder: "Yanıtınızı yazın…"
3355
- }, aa = {
3363
+ }, na = {
3356
3364
  write_a_message_placeholder: "پیغام لکھیں...",
3357
3365
  your_issue_has_been_resolved: "آپ کا مسئلہ حل ہو گیا ہے!",
3358
3366
  new_conversation: "نئی گفتگو",
@@ -3440,7 +3448,7 @@ const Ae = {
3440
3448
  questions_send: "بھیجیں",
3441
3449
  questions_type_answer: "میں خود لکھوں گا",
3442
3450
  questions_answer_placeholder: "اپنا جواب لکھیں…"
3443
- }, ta = {
3451
+ }, oa = {
3444
3452
  write_a_message_placeholder: "Viết tin nhắn...",
3445
3453
  your_issue_has_been_resolved: "Vấn đề của bạn đã được giải quyết!",
3446
3454
  new_conversation: "Cuộc trò chuyện mới",
@@ -3528,7 +3536,7 @@ const Ae = {
3528
3536
  questions_send: "Gửi",
3529
3537
  questions_type_answer: "Tôi sẽ tự nhập",
3530
3538
  questions_answer_placeholder: "Nhập câu trả lời của bạn…"
3531
- }, sa = {
3539
+ }, ia = {
3532
3540
  write_a_message_placeholder: "写一条消息...",
3533
3541
  your_issue_has_been_resolved: "您的问题已解决!",
3534
3542
  new_conversation: "新对话",
@@ -3616,7 +3624,7 @@ const Ae = {
3616
3624
  questions_send: "发送",
3617
3625
  questions_type_answer: "我自己输入",
3618
3626
  questions_answer_placeholder: "输入你的回答…"
3619
- }, na = {
3627
+ }, ra = {
3620
3628
  write_a_message_placeholder: "Napišite poruku...",
3621
3629
  your_issue_has_been_resolved: "Vaš problem je riješen!",
3622
3630
  new_conversation: "Novi razgovor",
@@ -3704,7 +3712,7 @@ const Ae = {
3704
3712
  questions_send: "Pošalji",
3705
3713
  questions_type_answer: "Napisat ću sam",
3706
3714
  questions_answer_placeholder: "Napišite svoj odgovor…"
3707
- }, oa = {
3715
+ }, _a = {
3708
3716
  write_a_message_placeholder: "Kirjuta sõnum...",
3709
3717
  your_issue_has_been_resolved: "Teie probleem on lahendatud!",
3710
3718
  new_conversation: "Uus vestlus",
@@ -3792,7 +3800,7 @@ const Ae = {
3792
3800
  questions_send: "Saada",
3793
3801
  questions_type_answer: "Kirjutan ise",
3794
3802
  questions_answer_placeholder: "Kirjutage oma vastus…"
3795
- }, ia = {
3803
+ }, la = {
3796
3804
  write_a_message_placeholder: "Írjon üzenetet...",
3797
3805
  your_issue_has_been_resolved: "A problémája megoldódott!",
3798
3806
  new_conversation: "Új beszélgetés",
@@ -3880,7 +3888,7 @@ const Ae = {
3880
3888
  questions_send: "Küldés",
3881
3889
  questions_type_answer: "Inkább leírom",
3882
3890
  questions_answer_placeholder: "Írja le a válaszát…"
3883
- }, ra = {
3891
+ }, ca = {
3884
3892
  write_a_message_placeholder: "Skrifaðu skilaboð...",
3885
3893
  your_issue_has_been_resolved: "Málið þitt hefur verið leyst!",
3886
3894
  new_conversation: "Nýtt samtal",
@@ -3968,7 +3976,7 @@ const Ae = {
3968
3976
  questions_send: "Senda",
3969
3977
  questions_type_answer: "Ég skrifa það",
3970
3978
  questions_answer_placeholder: "Skrifaðu svarið þitt…"
3971
- }, _a = {
3979
+ }, pa = {
3972
3980
  write_a_message_placeholder: "Rakstiet ziņojumu...",
3973
3981
  your_issue_has_been_resolved: "Jūsu problēma ir atrisināta!",
3974
3982
  new_conversation: "Jauna saruna",
@@ -4056,7 +4064,7 @@ const Ae = {
4056
4064
  questions_send: "Sūtīt",
4057
4065
  questions_type_answer: "Rakstīšu pats",
4058
4066
  questions_answer_placeholder: "Ierakstiet savu atbildi…"
4059
- }, la = {
4067
+ }, da = {
4060
4068
  write_a_message_placeholder: "Parašykite žinutę...",
4061
4069
  your_issue_has_been_resolved: "Jūsų problema išspręsta!",
4062
4070
  new_conversation: "Naujas pokalbis",
@@ -4144,7 +4152,7 @@ const Ae = {
4144
4152
  questions_send: "Siųsti",
4145
4153
  questions_type_answer: "Parašysiu pats",
4146
4154
  questions_answer_placeholder: "Parašykite savo atsakymą…"
4147
- }, ca = {
4155
+ }, ua = {
4148
4156
  write_a_message_placeholder: "Schreift eng Noriicht...",
4149
4157
  your_issue_has_been_resolved: "Äert Problem gouf geléist!",
4150
4158
  new_conversation: "Nei Konversatioun",
@@ -4232,7 +4240,7 @@ const Ae = {
4232
4240
  questions_send: "Schécken",
4233
4241
  questions_type_answer: "Ech schreiwen et selwer",
4234
4242
  questions_answer_placeholder: "Schreift Är Äntwert…"
4235
- }, pa = {
4243
+ }, ma = {
4236
4244
  write_a_message_placeholder: "Ikteb messaġġ...",
4237
4245
  your_issue_has_been_resolved: "Il-problema tiegħek ġiet riżolta!",
4238
4246
  new_conversation: "Konversazzjoni ġdida",
@@ -4320,7 +4328,7 @@ const Ae = {
4320
4328
  questions_send: "Ibgħat",
4321
4329
  questions_type_answer: "Nikteb jien",
4322
4330
  questions_answer_placeholder: "Ikteb it-tweġiba tiegħek…"
4323
- }, da = {
4331
+ }, ha = {
4324
4332
  write_a_message_placeholder: "Skriv en melding...",
4325
4333
  your_issue_has_been_resolved: "Saken din er løst!",
4326
4334
  new_conversation: "Ny samtale",
@@ -4408,7 +4416,7 @@ const Ae = {
4408
4416
  questions_send: "Send",
4409
4417
  questions_type_answer: "Jeg skriver det selv",
4410
4418
  questions_answer_placeholder: "Skriv svaret ditt…"
4411
- }, ua = {
4419
+ }, ga = {
4412
4420
  write_a_message_placeholder: "Napíšte správu...",
4413
4421
  your_issue_has_been_resolved: "Váš problém bol vyriešený!",
4414
4422
  new_conversation: "Nová konverzácia",
@@ -4496,86 +4504,86 @@ const Ae = {
4496
4504
  questions_send: "Odoslať",
4497
4505
  questions_type_answer: "Napíšem to sám",
4498
4506
  questions_answer_placeholder: "Napíšte svoju odpoveď…"
4499
- }, W = {
4500
- ar: Ae,
4501
- bn: Te,
4502
- bg: Me,
4503
- cs: Ie,
4504
- da: De,
4505
- de: Re,
4506
- el: Ne,
4507
- en: G,
4508
- es: Ke,
4509
- et: oa,
4510
- fi: Fe,
4511
- fil: Le,
4512
- fr: Oe,
4513
- hi: Ue,
4514
- hr: na,
4515
- hu: ia,
4516
- is: ra,
4517
- it: Be,
4518
- ja: Ve,
4519
- ko: He,
4520
- lb: ca,
4521
- lt: la,
4522
- lv: _a,
4523
- mt: pa,
4524
- nb: da,
4525
- nl: Ge,
4526
- no: We,
4527
- pl: $e,
4528
- pt: Ze,
4529
- ro: Je,
4530
- ru: Qe,
4531
- sk: ua,
4532
- sv: Ye,
4533
- th: Xe,
4534
- tr: ea,
4535
- ur: aa,
4536
- vi: ta,
4537
- "zh-cn": sa
4538
- }, ma = Object.keys(W);
4539
- function ha(_) {
4540
- return ma.includes(_);
4507
+ }, Z = {
4508
+ ar: Ie,
4509
+ bn: De,
4510
+ bg: Ne,
4511
+ cs: Re,
4512
+ da: Ke,
4513
+ de: Fe,
4514
+ el: Le,
4515
+ en: $,
4516
+ es: Oe,
4517
+ et: _a,
4518
+ fi: Be,
4519
+ fil: Ue,
4520
+ fr: Ve,
4521
+ hi: He,
4522
+ hr: ra,
4523
+ hu: la,
4524
+ is: ca,
4525
+ it: Ge,
4526
+ ja: We,
4527
+ ko: $e,
4528
+ lb: ua,
4529
+ lt: da,
4530
+ lv: pa,
4531
+ mt: ma,
4532
+ nb: ha,
4533
+ nl: Ze,
4534
+ no: Je,
4535
+ pl: Ye,
4536
+ pt: Qe,
4537
+ ro: Xe,
4538
+ ru: aa,
4539
+ sk: ga,
4540
+ sv: ea,
4541
+ th: ta,
4542
+ tr: sa,
4543
+ ur: na,
4544
+ vi: oa,
4545
+ "zh-cn": ia
4546
+ }, ka = Object.keys(Z);
4547
+ function ba(o) {
4548
+ return ka.includes(o);
4541
4549
  }
4542
- const ga = /* @__PURE__ */ new Set(["ar", "ur"]);
4543
- function La(_) {
4544
- return ga.has(_);
4550
+ const fa = /* @__PURE__ */ new Set(["ar", "ur"]);
4551
+ function Ua(o) {
4552
+ return fa.has(o);
4545
4553
  }
4546
- function ka(_) {
4547
- return ha(_) ? _ : "en";
4554
+ function va(o) {
4555
+ return ba(o) ? o : "en";
4548
4556
  }
4549
- function ba(_, e, a, n) {
4550
- var l;
4551
- const i = ((l = a == null ? void 0 : a[e]) == null ? void 0 : l[_]) || W[e][_] || G[_] || _;
4552
- return n ? i.replace(
4557
+ function ya(o, e, a, s) {
4558
+ var _;
4559
+ const i = ((_ = a == null ? void 0 : a[e]) == null ? void 0 : _[o]) || Z[e][o] || $[o] || o;
4560
+ return s ? i.replace(
4553
4561
  /\{(\w+)\}/g,
4554
- (o, t) => t in n ? String(n[t]) : o
4562
+ (n, t) => t in s ? String(s[t]) : n
4555
4563
  ) : i;
4556
4564
  }
4557
- function fa(_, e, a) {
4558
- return ba(
4565
+ function wa(o, e, a) {
4566
+ return ya(
4559
4567
  e,
4560
- ka(_.language),
4561
- _.translationOverrides,
4568
+ va(o.language),
4569
+ o.translationOverrides,
4562
4570
  a
4563
4571
  );
4564
4572
  }
4565
- class va {
4573
+ class ja {
4566
4574
  constructor({
4567
4575
  config: e,
4568
4576
  api: a,
4569
- contactCtx: n,
4577
+ contactCtx: s,
4570
4578
  storageCtx: i,
4571
- sessionsPollingIntervalSeconds: l,
4572
- sharedSessions: o
4579
+ sessionsPollingIntervalSeconds: _,
4580
+ sharedSessions: n
4573
4581
  }) {
4574
- this.sessionsRefresher = new V(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new w({
4582
+ this.sessionsRefresher = new G(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new j({
4575
4583
  session: null,
4576
4584
  isCreatingSession: !1,
4577
4585
  isResolvingSession: !1
4578
- }), this.sessionsState = new w({
4586
+ }), this.sessionsState = new j({
4579
4587
  data: [],
4580
4588
  cursor: void 0,
4581
4589
  isLastPage: !1,
@@ -4592,18 +4600,18 @@ class va {
4592
4600
  var t;
4593
4601
  (t = this.stopPersistingSession) == null || t.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
4594
4602
  }, this.trackActiveSession = (t) => {
4595
- var s;
4596
- (s = this.stopPersistingSession) == null || s.call(this), this.stopPersistingSession = t.sessionState.subscribe(
4603
+ var r;
4604
+ (r = this.stopPersistingSession) == null || r.call(this), this.stopPersistingSession = t.sessionState.subscribe(
4597
4605
  this.persistSession
4598
4606
  ), this.persistSession(t.sessionState.get());
4599
4607
  }, this.persistSession = ({ session: t }) => {
4600
- const s = this.storageCtx;
4601
- if (!s) return;
4602
- const r = t != null && t.isOpened ? t.id : null;
4603
- if (r === this.persistedSessionId || !r && this.persistedSessionId === null) return;
4604
- this.persistedSessionId = r, (r ? s.setActiveSessionId(r) : s.clearActiveSessionId()).catch((p) => {
4605
- m.warn("failed to persist the active session", {
4606
- error: p instanceof Error ? p.message : String(p)
4608
+ const r = this.storageCtx;
4609
+ if (!r) return;
4610
+ const c = t != null && t.isOpened ? t.id : null;
4611
+ if (c === this.persistedSessionId || !c && this.persistedSessionId === null) return;
4612
+ this.persistedSessionId = c, (c ? r.setActiveSessionId(c) : r.clearActiveSessionId()).catch((l) => {
4613
+ h.warn("failed to persist the active session", {
4614
+ error: l instanceof Error ? l.message : String(l)
4607
4615
  });
4608
4616
  });
4609
4617
  }, this.getLastActiveSessionId = async () => {
@@ -4618,8 +4626,8 @@ class va {
4618
4626
  }, this.registerSessionsRefresherWrapper = () => {
4619
4627
  var t;
4620
4628
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
4621
- (t = this.contactCtx.state.get().contact) != null && t.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: s }) => {
4622
- s != null && s.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
4629
+ (t = this.contactCtx.state.get().contact) != null && t.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: r }) => {
4630
+ r != null && r.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
4623
4631
  });
4624
4632
  }, this.registerSessionsRefresher = () => {
4625
4633
  this.sessionsRefresher.startPolling(async () => {
@@ -4627,83 +4635,83 @@ class va {
4627
4635
  }, this.sessionsPollingIntervalSeconds * 1e3);
4628
4636
  }, this.getParsedCustomData = () => Object.fromEntries(
4629
4637
  Object.entries(this.config.sessionCustomData || {}).map(
4630
- ([t, s]) => {
4631
- var r;
4632
- return typeof s == "string" ? [t, s] : typeof s == "boolean" ? [t, s] : typeof s == "number" ? [t, s] : [t, ((r = H(() => JSON.stringify(s))) == null ? void 0 : r.data) || ""];
4638
+ ([t, r]) => {
4639
+ var c;
4640
+ return typeof r == "string" ? [t, r] : typeof r == "boolean" ? [t, r] : typeof r == "number" ? [t, r] : [t, ((c = W(() => JSON.stringify(r))) == null ? void 0 : c.data) || ""];
4633
4641
  }
4634
4642
  )
4635
4643
  ), this.createSession = async () => {
4636
4644
  const { signal: t } = this.sessionAbortController;
4637
4645
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
4638
4646
  try {
4639
- const s = await this.requestSession(t);
4647
+ const r = await this.requestSession(t);
4640
4648
  if (t.aborted) return null;
4641
- if (s.session) return s.session;
4642
- if (s.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
4649
+ if (r.session) return r.session;
4650
+ if (r.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
4643
4651
  if (t.aborted) return null;
4644
- const r = await this.requestSession(t);
4645
- return t.aborted ? null : r.session ? r.session : (m.error("failed to create session", r.error), null);
4652
+ const c = await this.requestSession(t);
4653
+ return t.aborted ? null : c.session ? c.session : (h.error("failed to create session", c.error), null);
4646
4654
  }
4647
- return m.error("failed to create session", s.error), null;
4648
- } catch (s) {
4649
- return t.aborted || m.error("failed to create session", s), null;
4655
+ return h.error("failed to create session", r.error), null;
4656
+ } catch (r) {
4657
+ return t.aborted || h.error("failed to create session", r), null;
4650
4658
  } finally {
4651
4659
  t.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
4652
4660
  }
4653
4661
  }, this.requestSession = async (t) => {
4654
- var u, g, h;
4655
- const s = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, r = {
4662
+ var u, m, g;
4663
+ const r = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, c = {
4656
4664
  ...this.getParsedCustomData(),
4657
- ...s ? { external_id: s } : {}
4665
+ ...r ? { external_id: r } : {}
4658
4666
  }, {
4659
- data: c,
4660
- error: p,
4661
- response: d
4667
+ data: d,
4668
+ error: l,
4669
+ response: p
4662
4670
  } = await this.api.createSession(
4663
4671
  {
4664
- customData: Object.keys(r).length > 0 ? r : void 0
4672
+ customData: Object.keys(c).length > 0 ? c : void 0
4665
4673
  },
4666
4674
  t
4667
4675
  );
4668
- if (t.aborted || !c)
4669
- return { session: null, status: d == null ? void 0 : d.status, error: p };
4670
- this.sessionState.setPartial({ session: c });
4676
+ if (t.aborted || !d)
4677
+ return { session: null, status: p == null ? void 0 : p.status, error: l };
4678
+ this.sessionState.setPartial({ session: d });
4671
4679
  try {
4672
- (h = (g = this.config.hooks) == null ? void 0 : g.onSessionCreated) == null || h.call(g, { session: c });
4673
- } catch (v) {
4674
- m.error("onSessionCreated hook failed", v);
4680
+ (g = (m = this.config.hooks) == null ? void 0 : m.onSessionCreated) == null || g.call(m, { session: d });
4681
+ } catch (b) {
4682
+ h.error("onSessionCreated hook failed", b);
4675
4683
  }
4676
- return { session: c, status: d.status, error: void 0 };
4684
+ return { session: d, status: p.status, error: void 0 };
4677
4685
  }, this.loadMoreSessions = async () => {
4678
4686
  if (this.sessionsState.get().isLastPage) return;
4679
4687
  const { data: t } = await this.getSessions({
4680
4688
  cursor: this.sessionsState.get().cursor
4681
4689
  });
4682
4690
  if (t) {
4683
- const r = [...this.sessionsState.get().data, ...t.items].filter(
4684
- (c, p, d) => p === d.findIndex((u) => c.id === u.id)
4691
+ const c = [...this.sessionsState.get().data, ...t.items].filter(
4692
+ (d, l, p) => l === p.findIndex((u) => d.id === u.id)
4685
4693
  );
4686
4694
  this.sessionsState.setPartial({
4687
- data: r,
4695
+ data: c,
4688
4696
  cursor: t.next || void 0,
4689
4697
  isLastPage: t.next === null
4690
4698
  });
4691
4699
  }
4692
4700
  }, this.getSessions = async ({ cursor: t }) => {
4693
- var r, c;
4694
- if (!((r = this.contactCtx.state.get().contact) != null && r.token)) return { data: null };
4695
- const s = (c = this.contactCtx.state.get().contact) == null ? void 0 : c.externalId;
4701
+ var c, d;
4702
+ if (!((c = this.contactCtx.state.get().contact) != null && c.token)) return { data: null };
4703
+ const r = (d = this.contactCtx.state.get().contact) == null ? void 0 : d.externalId;
4696
4704
  return await this.api.getSessions({
4697
4705
  cursor: t,
4698
- filters: s ? {
4699
- external_id: s
4706
+ filters: r ? {
4707
+ external_id: r
4700
4708
  } : {}
4701
4709
  });
4702
4710
  }, this.setSessions = (t) => {
4703
- const s = [...t, ...this.sessionsState.get().data].filter(
4704
- (r, c, p) => c === p.findIndex((d) => r.id === d.id)
4711
+ const r = [...t, ...this.sessionsState.get().data].filter(
4712
+ (c, d, l) => d === l.findIndex((p) => c.id === p.id)
4705
4713
  );
4706
- this.sessionsState.setPartial({ data: s });
4714
+ this.sessionsState.setPartial({ data: r });
4707
4715
  }, this.refreshSessions = async () => {
4708
4716
  const { data: t } = await this.getSessions({ cursor: void 0 });
4709
4717
  t && this.setSessions(t.items);
@@ -4712,297 +4720,310 @@ class va {
4712
4720
  if (!t || !t.isOpened)
4713
4721
  return { success: !1, error: "Session is not opened" };
4714
4722
  this.sessionState.setPartial({ isResolvingSession: !0 });
4715
- const { signal: s } = this.sessionAbortController, r = await this.api.resolveSession({ session_id: t.id }, s).catch((d) => {
4716
- if (s.aborted) return null;
4717
- throw d;
4723
+ const { signal: r } = this.sessionAbortController, c = await this.api.resolveSession({ session_id: t.id }, r).catch((p) => {
4724
+ if (r.aborted) return null;
4725
+ throw p;
4718
4726
  });
4719
- if (!r || s.aborted)
4727
+ if (!c || r.aborted)
4720
4728
  return { success: !1, error: "Session was reset" };
4721
- const { data: c, error: p } = r;
4722
- return c ? (this.sessionState.setPartial({ session: c, isResolvingSession: !1 }), { success: !0, data: c }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: p });
4729
+ const { data: d, error: l } = c;
4730
+ return d ? (this.sessionState.setPartial({ session: d, isResolvingSession: !1 }), { success: !0, data: d }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: l });
4723
4731
  }, this.createStateCheckpoint = async (t) => {
4724
- var c;
4725
- const s = (c = this.sessionState.get().session) == null ? void 0 : c.id;
4726
- if (!s) return;
4727
- const { data: r } = await this.api.createStateCheckpoint({
4728
- session_id: s,
4732
+ var d;
4733
+ const r = (d = this.sessionState.get().session) == null ? void 0 : d.id;
4734
+ if (!r) return;
4735
+ const { data: c } = await this.api.createStateCheckpoint({
4736
+ session_id: r,
4729
4737
  payload: t
4730
4738
  });
4731
- return r != null && r.success ? { success: !0 } : { success: !1 };
4732
- }, this.config = e, this.api = a, this.contactCtx = n, this.storageCtx = i, this.sessionsPollingIntervalSeconds = l, o ? this.sessionsState = o : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
4739
+ return c != null && c.success ? { success: !0 } : { success: !1 };
4740
+ }, this.config = e, this.api = a, this.contactCtx = s, this.storageCtx = i, this.sessionsPollingIntervalSeconds = _, n ? this.sessionsState = n : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
4733
4741
  }
4734
4742
  }
4735
- const ya = (_, e, { sendsPageContext: a }) => {
4736
- const n = Sa(_), i = a && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(wa) } : void 0, l = a && (e.clientContext || i) ? { ...n, ...e.clientContext, ...i } : n;
4743
+ const Sa = (o, e, { sendsPageContext: a }) => {
4744
+ const s = Ca(o), i = a && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(xa) } : void 0, _ = a && (e.clientContext || i) ? { ...s, ...e.clientContext, ...i } : s;
4737
4745
  return {
4738
- clientContext: e.withPageEntity === !1 && l && "entity" in l ? ja(l, "entity") : l,
4746
+ clientContext: e.withPageEntity === !1 && _ && "entity" in _ ? za(_, "entity") : _,
4739
4747
  custom_data: {
4740
- ..._.messageCustomData || {},
4748
+ ...o.messageCustomData || {},
4741
4749
  ...e.customData || {}
4742
4750
  }
4743
4751
  };
4744
- }, wa = ({ type: _, id: e, title: a, meta: n }) => ({
4745
- type: _,
4752
+ }, xa = ({ type: o, id: e, title: a, meta: s }) => ({
4753
+ type: o,
4746
4754
  id: e,
4747
4755
  title: a,
4748
- ...n ? { meta: n } : {}
4749
- }), ja = (_, e) => {
4750
- const { [e]: a, ...n } = _;
4751
- return Object.keys(n).length > 0 ? n : void 0;
4752
- }, Sa = (_) => {
4753
- if (typeof _.context != "function") return _.context;
4756
+ ...s ? { meta: s } : {}
4757
+ }), za = (o, e) => {
4758
+ const { [e]: a, ...s } = o;
4759
+ return Object.keys(s).length > 0 ? s : void 0;
4760
+ }, Ca = (o) => {
4761
+ if (typeof o.context != "function") return o.context;
4754
4762
  try {
4755
- return _.context();
4763
+ return o.context();
4756
4764
  } catch (e) {
4757
- m.error("context getter threw; sending without context", e);
4765
+ h.error("context getter threw; sending without context", e);
4758
4766
  return;
4759
4767
  }
4760
- }, xa = (_) => {
4761
- const e = _.features;
4768
+ }, qa = (o) => {
4769
+ const e = o.features;
4762
4770
  if (!e) return;
4763
4771
  const a = {};
4764
4772
  return e.preamble !== void 0 && (a.preamble = e.preamble), e.inlineUi !== void 0 && (a.inline_ui = e.inlineUi), e.pageContext !== void 0 && (a.page_context = e.pageContext), e.clientTools !== void 0 && (a.client_tools = e.clientTools), Object.keys(a).length > 0 ? a : void 0;
4765
- }, za = ({
4766
- config: _,
4773
+ }, Ea = ({
4774
+ config: o,
4767
4775
  input: e,
4768
4776
  uuid: a,
4769
- sessionId: n,
4777
+ sessionId: s,
4770
4778
  content: i,
4771
- initialMessages: l,
4772
- sendsPageContext: o
4779
+ initialMessages: _,
4780
+ sendsPageContext: n
4773
4781
  }) => {
4774
- var t;
4782
+ var t, r, c, d, l, p;
4775
4783
  return {
4776
4784
  uuid: a,
4777
- bot_token: _.token,
4778
- headers: _.headers,
4779
- query_params: _.queryParams,
4780
- body_properties: _.bodyProperties,
4781
- session_id: n,
4785
+ bot_token: o.token,
4786
+ headers: o.headers,
4787
+ query_params: o.queryParams,
4788
+ body_properties: o.bodyProperties,
4789
+ session_id: s,
4782
4790
  content: i,
4783
4791
  attachments: e.attachments,
4784
- ...ya(_, e, { sendsPageContext: o }),
4785
- language: _.language,
4786
- features: xa(_),
4787
- capabilities: ((t = _.capabilities) == null ? void 0 : t.structuredQuestions) === void 0 ? void 0 : { structured_questions: _.capabilities.structuredQuestions },
4792
+ ...Sa(o, e, { sendsPageContext: n }),
4793
+ language: o.language,
4794
+ features: qa(o),
4795
+ presentation: o.presentation,
4796
+ capabilities: [
4797
+ (t = o.capabilities) == null ? void 0 : t.structuredQuestions,
4798
+ (r = o.capabilities) == null ? void 0 : r.richReplies,
4799
+ (c = o.capabilities) == null ? void 0 : c.pageEffects
4800
+ ].some((u) => u !== void 0) ? {
4801
+ structured_questions: (d = o.capabilities) == null ? void 0 : d.structuredQuestions,
4802
+ rich_replies: (l = o.capabilities) == null ? void 0 : l.richReplies,
4803
+ page_effects: (p = o.capabilities) == null ? void 0 : p.pageEffects
4804
+ } : void 0,
4788
4805
  exit_mode_prompt: e.exitModePrompt,
4789
- initial_messages: l.length > 0 ? l.map((s) => ({ uuid: s.id, content: s.data.message })) : void 0
4806
+ initial_messages: _.length > 0 ? _.map((u) => ({ uuid: u.id, content: u.data.message })) : void 0
4790
4807
  };
4791
4808
  }, x = class x {
4792
4809
  constructor({
4793
4810
  config: e,
4794
4811
  api: a,
4795
- sessionCtx: n,
4812
+ sessionCtx: s,
4796
4813
  contactCtx: i,
4797
- streaming: l,
4798
- sendsPageContext: o,
4799
- getClientCapabilities: t
4814
+ streaming: _,
4815
+ sendsPageContext: n,
4816
+ getClientCapabilities: t,
4817
+ getRequestConfig: r,
4818
+ isStreaming: c,
4819
+ getSendsPageContext: d
4800
4820
  }) {
4801
- this.state = new w({
4821
+ this.state = new j({
4802
4822
  messages: [],
4803
4823
  isSendingMessage: !1,
4804
4824
  isSendingMessageToAI: !1,
4825
+ settledAgentUserMessageId: null,
4805
4826
  lastAIResMightSolveUserIssue: !1,
4806
4827
  isInitialFetchLoading: !1
4807
- }), this.draftState = new w({
4828
+ }), this.draftState = new j({
4808
4829
  text: "",
4809
4830
  mentions: []
4810
4831
  }), this.agentHandlers = null, this.bufferedAgentSends = [], this.sendMessageAbortController = new AbortController(), this.messageIdsDispatchedToOnMessageReceivedHook = /* @__PURE__ */ new Set(), this.sentTextHistory = [], this.reset = () => {
4811
4832
  this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [], this.draftState.reset();
4812
- }, this.rememberSentText = (s) => {
4813
- const r = s.trim();
4814
- !r || this.sentTextHistory.at(-1) === r || (this.sentTextHistory.push(r), this.sentTextHistory.length > x.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
4815
- }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (s) => {
4816
- this.agentHandlers = s;
4817
- const r = this.bufferedAgentSends;
4818
- this.bufferedAgentSends = [], r.forEach((c) => {
4819
- x.dispatchToEngine(s, c);
4833
+ }, this.rememberSentText = (l) => {
4834
+ const p = l.trim();
4835
+ !p || this.sentTextHistory.at(-1) === p || (this.sentTextHistory.push(p), this.sentTextHistory.length > x.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
4836
+ }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (l) => {
4837
+ this.agentHandlers = l;
4838
+ const p = this.bufferedAgentSends;
4839
+ this.bufferedAgentSends = [], p.forEach((u) => {
4840
+ x.dispatchToEngine(l, u);
4820
4841
  });
4821
- }, this.unregisterAgentHandlers = (s) => {
4822
- this.agentHandlers === s && (this.agentHandlers = null);
4823
- }, this.dispatchToOnMessageReceivedHook = (s) => {
4824
- var c, p;
4825
- if (s.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(s.id))
4842
+ }, this.unregisterAgentHandlers = (l) => {
4843
+ this.agentHandlers === l && (this.agentHandlers = null);
4844
+ }, this.dispatchToOnMessageReceivedHook = (l) => {
4845
+ var u, m;
4846
+ if (l.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(l.id))
4826
4847
  return;
4827
- const r = this.sessionCtx.sessionState.get().session;
4828
- r && (this.messageIdsDispatchedToOnMessageReceivedHook.add(s.id), (p = (c = this.config.hooks) == null ? void 0 : c.onMessageReceived) == null || p.call(c, { message: s, session: r }));
4829
- }, this.markAsDispatchedToOnMessageReceivedHook = (s) => {
4830
- s.forEach(
4831
- (r) => this.messageIdsDispatchedToOnMessageReceivedHook.add(r)
4848
+ const p = this.sessionCtx.sessionState.get().session;
4849
+ p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(l.id), (m = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || m.call(u, { message: l, session: p }));
4850
+ }, this.markAsDispatchedToOnMessageReceivedHook = (l) => {
4851
+ l.forEach(
4852
+ (p) => this.messageIdsDispatchedToOnMessageReceivedHook.add(p)
4832
4853
  );
4833
4854
  }, this.buildPersistentInitialMessages = () => {
4834
- var r, c;
4835
- return !((r = this.sessionCtx.sessionState.get().session) != null && r.id) && this.state.get().messages.length === 0 && ((c = this.config.advancedInitialMessages) == null ? void 0 : c.some((p) => p.persistent)) ? (this.config.advancedInitialMessages || []).filter((p) => p.persistent).map(
4836
- (p) => ({
4855
+ var p, u;
4856
+ return !((p = this.sessionCtx.sessionState.get().session) != null && p.id) && this.state.get().messages.length === 0 && ((u = this.config.advancedInitialMessages) == null ? void 0 : u.some((m) => m.persistent)) ? (this.config.advancedInitialMessages || []).filter((m) => m.persistent).map(
4857
+ (m) => ({
4837
4858
  id: z(),
4838
4859
  component: "bot_message",
4839
4860
  type: "AI",
4840
4861
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4841
- data: { message: p.message },
4862
+ data: { message: m.message },
4842
4863
  agent: this.config.bot ? { ...this.config.bot, isAi: !0, id: null } : void 0
4843
4864
  })
4844
4865
  ) : [];
4845
4866
  }, this.ensureSessionId = async () => {
4846
- var s, r;
4847
- if (!((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
4867
+ var l, p;
4868
+ if (!((l = this.sessionCtx.sessionState.get().session) != null && l.id)) {
4848
4869
  if (!await this.sessionCtx.createSession()) return null;
4849
4870
  this.sessionCtx.refreshSessions();
4850
4871
  }
4851
- return ((r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id) ?? null;
4852
- }, this.rollbackOptimisticMessages = (s) => {
4853
- if (s.length === 0) return;
4854
- const r = new Set(s), c = this.state.get().messages, p = c.filter((d) => !r.has(d.id));
4855
- p.length !== c.length && this.state.setPartial({ messages: p });
4856
- }, this.notifySendAccepted = (s) => {
4857
- var r;
4872
+ return ((p = this.sessionCtx.sessionState.get().session) == null ? void 0 : p.id) ?? null;
4873
+ }, this.rollbackOptimisticMessages = (l) => {
4874
+ if (l.length === 0) return;
4875
+ const p = new Set(l), u = this.state.get().messages, m = u.filter((g) => !p.has(g.id));
4876
+ m.length !== u.length && this.state.setPartial({ messages: m });
4877
+ }, this.notifySendAccepted = (l) => {
4878
+ var p;
4858
4879
  try {
4859
- (r = s.onAccepted) == null || r.call(s);
4860
- } catch (c) {
4861
- m.error("send acceptance callback failed", c);
4880
+ (p = l.onAccepted) == null || p.call(l);
4881
+ } catch (u) {
4882
+ h.error("send acceptance callback failed", u);
4862
4883
  }
4863
- }, this.stageUserTurn = async (s, { pending: r }) => {
4864
- const c = this.buildUserMessage(s);
4865
- if (!c) return null;
4866
- const p = r ? { ...c, pending: !0 } : c, d = this.buildPersistentInitialMessages(), u = [
4867
- ...d.map((h) => h.id),
4868
- p.id
4884
+ }, this.stageUserTurn = async (l, { pending: p }) => {
4885
+ const u = this.buildUserMessage(l);
4886
+ if (!u) return null;
4887
+ const m = p ? { ...u, pending: !0 } : u, g = this.buildPersistentInitialMessages(), b = [
4888
+ ...g.map((k) => k.id),
4889
+ m.id
4869
4890
  ];
4870
4891
  this.state.setPartial({
4871
- messages: [...d, ...this.state.get().messages, p]
4892
+ messages: [...g, ...this.state.get().messages, m]
4872
4893
  });
4873
- let g;
4894
+ let f;
4874
4895
  try {
4875
- g = await this.ensureSessionId();
4876
- } catch (h) {
4877
- throw this.rollbackOptimisticMessages(u), h;
4896
+ f = await this.ensureSessionId();
4897
+ } catch (k) {
4898
+ throw this.rollbackOptimisticMessages(b), k;
4878
4899
  }
4879
- return g ? { sessionId: g, userMessage: p, initialMessages: d } : (this.rollbackOptimisticMessages(u), null);
4880
- }, this.buildQueuedUserMessage = (s) => {
4900
+ return f ? { sessionId: f, userMessage: m, initialMessages: g } : (this.rollbackOptimisticMessages(b), null);
4901
+ }, this.buildQueuedUserMessage = (l) => {
4902
+ var m;
4903
+ const p = this.buildUserMessage(l);
4904
+ if (!p) return null;
4905
+ const u = (m = this.sessionCtx.sessionState.get().session) == null ? void 0 : m.id;
4906
+ return u ? { sessionId: u, userMessage: { ...p, pending: !0 } } : null;
4907
+ }, this.buildUserMessage = (l) => {
4881
4908
  var p;
4882
- const r = this.buildUserMessage(s);
4883
- if (!r) return null;
4884
- const c = (p = this.sessionCtx.sessionState.get().session) == null ? void 0 : p.id;
4885
- return c ? { sessionId: c, userMessage: { ...r, pending: !0 } } : null;
4886
- }, this.buildUserMessage = (s) => {
4887
- var r;
4888
- return !s.content.trim() && (!s.attachments || s.attachments.length === 0) ? (m.warn("cannot send an empty message of no content or attachments"), null) : this.toUserMessage(
4889
- s.content.trim(),
4890
- s.attachments || void 0,
4891
- this.sendsPageContext ? x.markedElementNames(s.clientContext) : void 0,
4892
- this.sendsPageContext && ((r = s.mentions) != null && r.length) ? s.mentions : void 0
4909
+ return !l.content.trim() && (!l.attachments || l.attachments.length === 0) ? (h.warn("cannot send an empty message of no content or attachments"), null) : this.toUserMessage(
4910
+ l.content.trim(),
4911
+ l.attachments || void 0,
4912
+ this.sendsPageContext ? x.markedElementNames(l.clientContext) : void 0,
4913
+ this.sendsPageContext && ((p = l.mentions) != null && p.length) ? l.mentions : void 0
4893
4914
  );
4894
- }, this.appendUserMessageIfAbsent = (s) => {
4895
- const r = this.state.get().messages;
4896
- r.some((c) => c.id === s.id) || this.state.setPartial({ messages: [...r, s] });
4897
- }, this.markUserMessageDelivered = (s) => {
4898
- const r = this.state.get().messages, c = r.findIndex(
4899
- (u) => u.id === s && u.type === "USER" && u.pending
4915
+ }, this.appendUserMessageIfAbsent = (l) => {
4916
+ const p = this.state.get().messages;
4917
+ p.some((u) => u.id === l.id) || this.state.setPartial({ messages: [...p, l] });
4918
+ }, this.markUserMessageDelivered = (l) => {
4919
+ const p = this.state.get().messages, u = p.findIndex(
4920
+ (b) => b.id === l && b.type === "USER" && b.pending
4900
4921
  );
4901
- if (c === -1) return;
4902
- const p = r[c];
4903
- if (!p || p.type !== "USER") return;
4904
- const d = [...r];
4905
- d[c] = { ...p, pending: !1 }, this.state.setPartial({
4906
- messages: d
4922
+ if (u === -1) return;
4923
+ const m = p[u];
4924
+ if (!m || m.type !== "USER") return;
4925
+ const g = [...p];
4926
+ g[u] = { ...m, pending: !1 }, this.state.setPartial({
4927
+ messages: g
4907
4928
  });
4908
- }, this.sendMessage = async (s) => {
4909
- var c, p, d, u, g;
4929
+ }, this.sendMessage = async (l) => {
4930
+ var u, m, g, b, f;
4910
4931
  if (this.streaming) {
4911
4932
  if (!this.agentHandlers) {
4912
- this.bufferedAgentSends.push(s);
4933
+ this.bufferedAgentSends.push(l);
4913
4934
  return;
4914
4935
  }
4915
- await this.agentHandlers.send(s);
4936
+ await this.agentHandlers.send(l);
4916
4937
  return;
4917
4938
  }
4918
- let r;
4939
+ let p;
4919
4940
  try {
4920
- const h = this.sessionCtx.sessionState.get().session, j = (h == null ? void 0 : h.assignee.kind) === "ai", b = this.state.get().isSendingMessageToAI, f = this.state.get().messages.at(-1);
4921
- if (this.blocksSendWhileAwaitingReply && (b || // If last message is from user, then bot response did not arrive yet
4922
- j && (f == null ? void 0 : f.type) === "USER")) {
4923
- m.warn("cannot send messages while awaiting AI response");
4941
+ const k = this.sessionCtx.sessionState.get().session, N = (k == null ? void 0 : k.assignee.kind) === "ai", Y = this.state.get().isSendingMessageToAI, q = this.state.get().messages.at(-1);
4942
+ if (this.blocksSendWhileAwaitingReply && (Y || // If last message is from user, then bot response did not arrive yet
4943
+ N && (q == null ? void 0 : q.type) === "USER" && q.id !== this.state.get().settledAgentUserMessageId)) {
4944
+ h.warn("cannot send messages while awaiting AI response");
4924
4945
  return;
4925
4946
  }
4926
- this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), r = this.sendMessageAbortController, this.state.setPartial({
4947
+ this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), p = this.sendMessageAbortController, this.state.setPartial({
4927
4948
  lastAIResMightSolveUserIssue: !1,
4928
4949
  isSendingMessage: !0,
4929
- isSendingMessageToAI: !!j || !h
4950
+ isSendingMessageToAI: !!N || !k
4930
4951
  });
4931
- const D = await this.stageUserTurn(s, { pending: !1 });
4932
- if (!D) return;
4933
- const { sessionId: Z, userMessage: N, initialMessages: J } = D;
4934
- this.notifySendAccepted(s);
4935
- const { data: k } = await this.api.sendMessage(
4936
- za({
4952
+ const R = await this.stageUserTurn(l, { pending: !1 });
4953
+ if (!R) return;
4954
+ const { sessionId: Q, userMessage: K, initialMessages: X } = R;
4955
+ this.notifySendAccepted(l);
4956
+ const { data: v } = await this.api.sendMessage(
4957
+ Ea({
4937
4958
  config: {
4938
- ...this.config,
4959
+ ...this.getRequestConfig(),
4939
4960
  capabilities: this.getClientCapabilities()
4940
4961
  },
4941
- input: s,
4942
- uuid: N.id,
4943
- sessionId: Z,
4944
- content: N.content,
4945
- initialMessages: J,
4962
+ input: l,
4963
+ uuid: K.id,
4964
+ sessionId: Q,
4965
+ content: K.content,
4966
+ initialMessages: X,
4946
4967
  sendsPageContext: this.sendsPageContext
4947
4968
  }),
4948
- r.signal
4969
+ p.signal
4949
4970
  );
4950
- if (k != null && k.success) {
4951
- const S = this.toBotMessage(k);
4971
+ if (v != null && v.success) {
4972
+ const S = this.toBotMessage(v);
4952
4973
  if (S) {
4953
- const q = this.state.get().messages;
4954
- if (!!q.some(
4955
- (Y) => Y.id === S.id
4974
+ const E = this.state.get().messages;
4975
+ if (!!E.some(
4976
+ (ee) => ee.id === S.id
4956
4977
  )) {
4957
4978
  this.state.setPartial({
4958
- lastAIResMightSolveUserIssue: ((c = k.autopilotResponse) == null ? void 0 : c.mightSolveUserIssue) || ((p = k.uiResponse) == null ? void 0 : p.mightSolveUserIssue)
4979
+ lastAIResMightSolveUserIssue: ((u = v.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((m = v.uiResponse) == null ? void 0 : m.mightSolveUserIssue)
4959
4980
  });
4960
4981
  return;
4961
4982
  }
4962
4983
  this.state.setPartial({
4963
- messages: [...q, S],
4964
- lastAIResMightSolveUserIssue: ((d = k.autopilotResponse) == null ? void 0 : d.mightSolveUserIssue) || ((u = k.uiResponse) == null ? void 0 : u.mightSolveUserIssue)
4984
+ messages: [...E, S],
4985
+ lastAIResMightSolveUserIssue: ((g = v.autopilotResponse) == null ? void 0 : g.mightSolveUserIssue) || ((b = v.uiResponse) == null ? void 0 : b.mightSolveUserIssue)
4965
4986
  }), this.dispatchToOnMessageReceivedHook(S);
4966
4987
  }
4967
- k.session && this.sessionCtx.sessionState.setPartial({ session: k.session });
4988
+ v.session && this.sessionCtx.sessionState.setPartial({ session: v.session });
4968
4989
  } else {
4969
4990
  const S = this.toBotErrorMessage(
4970
- ((g = k == null ? void 0 : k.error) == null ? void 0 : g.message) || fa(this.config, "turn_failed_message")
4971
- ), q = this.state.get().messages;
4991
+ ((f = v == null ? void 0 : v.error) == null ? void 0 : f.message) || wa(this.config, "turn_failed_message")
4992
+ ), E = this.state.get().messages;
4972
4993
  this.state.setPartial({
4973
- messages: [...q, S]
4994
+ messages: [...E, S]
4974
4995
  });
4975
4996
  }
4976
- } catch (h) {
4977
- r != null && r.signal.aborted || m.error("failed to send message", h);
4997
+ } catch (k) {
4998
+ p != null && p.signal.aborted || h.error("failed to send message", k);
4978
4999
  } finally {
4979
- r != null && r.signal.aborted || this.state.setPartial({
5000
+ p != null && p.signal.aborted || this.state.setPartial({
4980
5001
  isSendingMessage: !1,
4981
5002
  isSendingMessageToAI: !1
4982
5003
  });
4983
5004
  }
4984
- }, this.toUserMessage = (s, r, c, p) => {
4985
- const d = (() => {
4986
- const u = this.contactCtx.state.get().extraCollectedData;
4987
- return this.state.get().messages.length === 0 && u && Object.keys(u).length > 0 ? `${Object.entries(u).filter(([h, v]) => !!v).map(([h, v]) => `${h}: ${v}`).join(`
5005
+ }, this.toUserMessage = (l, p, u, m) => {
5006
+ const g = (() => {
5007
+ const b = this.contactCtx.state.get().extraCollectedData;
5008
+ return this.state.get().messages.length === 0 && b && Object.keys(b).length > 0 ? `${Object.entries(b).filter(([k, y]) => !!y).map(([k, y]) => `${k}: ${y}`).join(`
4988
5009
  `)}
4989
5010
 
4990
- ${s}` : s;
5011
+ ${l}` : l;
4991
5012
  })();
4992
5013
  return {
4993
5014
  id: z(),
4994
5015
  type: "USER",
4995
- content: d,
4996
- attachments: r,
4997
- markedElements: c,
4998
- mentions: p,
5016
+ content: g,
5017
+ attachments: p,
5018
+ markedElements: u,
5019
+ mentions: m,
4999
5020
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
5000
5021
  };
5001
- }, this.toBotMessage = (s) => {
5002
- var r;
5003
- return s.success && s.autopilotResponse ? {
5022
+ }, this.toBotMessage = (l) => {
5023
+ var p;
5024
+ return l.success && l.autopilotResponse ? {
5004
5025
  type: "AI",
5005
- id: s.autopilotResponse.id || z(),
5026
+ id: l.autopilotResponse.id || z(),
5006
5027
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5007
5028
  component: "bot_message",
5008
5029
  agent: this.config.bot ? {
@@ -5014,35 +5035,49 @@ ${s}` : s;
5014
5035
  id: null
5015
5036
  } : void 0,
5016
5037
  data: {
5017
- message: s.autopilotResponse.value.content,
5018
- action: (r = s.uiResponse) != null && r.value.name ? {
5019
- name: s.uiResponse.value.name,
5020
- data: s.uiResponse.value.request_response
5038
+ message: l.autopilotResponse.value.content,
5039
+ action: (p = l.uiResponse) != null && p.value.name ? {
5040
+ name: l.uiResponse.value.name,
5041
+ data: l.uiResponse.value.request_response
5021
5042
  } : void 0
5022
5043
  }
5023
5044
  } : null;
5024
- }, this.toBotErrorMessage = (s) => ({
5045
+ }, this.toBotErrorMessage = (l) => ({
5025
5046
  type: "AI",
5026
5047
  id: z(),
5027
5048
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5028
5049
  component: "bot_message",
5029
5050
  data: {
5030
- message: s,
5051
+ message: l,
5031
5052
  variant: "error",
5032
5053
  action: void 0
5033
5054
  }
5034
- }), this.config = e, this.getClientCapabilities = t ?? (() => this.config.capabilities), this.api = a, this.sessionCtx = n, this.contactCtx = i, this.streaming = l, this.sendsPageContext = o;
5055
+ }), this.config = e, this.getClientCapabilities = t ?? (() => this.getRequestConfig().capabilities), this.api = a, this.sessionCtx = s, this.contactCtx = i, this.isStreaming = c ?? (() => _), this.getRequestConfig = r ?? (() => this.config), this.getSendsPageContext = d ?? (() => n);
5056
+ }
5057
+ /**
5058
+ * Current transport choice. The org or this embed may request polling
5059
+ * independently of the server's agent version.
5060
+ */
5061
+ get streaming() {
5062
+ return this.isStreaming();
5063
+ }
5064
+ get sendsPageContext() {
5065
+ return this.getSendsPageContext();
5035
5066
  }
5036
5067
  /** Hand a send to the streaming engine; its failure can never propagate. */
5037
5068
  static dispatchToEngine(e, a) {
5038
5069
  try {
5039
- Promise.resolve(e.send(a)).catch((n) => {
5040
- m.error("streaming send failed", n);
5070
+ Promise.resolve(e.send(a)).catch((s) => {
5071
+ h.error("streaming send failed", s);
5041
5072
  });
5042
- } catch (n) {
5043
- m.error("streaming send failed", n);
5073
+ } catch (s) {
5074
+ h.error("streaming send failed", s);
5044
5075
  }
5045
5076
  }
5077
+ get hasPendingAgentWork() {
5078
+ var e, a;
5079
+ return this.bufferedAgentSends.length > 0 || (((a = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : a.call(e)) ?? !1);
5080
+ }
5046
5081
  /**
5047
5082
  * Defensive read of `clientContext.page_marks` → the user bubble's context
5048
5083
  * chips: each mark contributes the element it was placed on, the note the
@@ -5053,21 +5088,21 @@ ${s}` : s;
5053
5088
  static markedElementNames(e) {
5054
5089
  const a = e == null ? void 0 : e.page_marks;
5055
5090
  if (!Array.isArray(a)) return;
5056
- const n = a.flatMap((i) => {
5091
+ const s = a.flatMap((i) => {
5057
5092
  if (typeof i != "object" || i === null) return [];
5058
- const l = i.elements, o = Array.isArray(l) ? l[0] : void 0, t = typeof o == "object" && o !== null && "name" in o ? o.name : void 0;
5093
+ const _ = i.elements, n = Array.isArray(_) ? _[0] : void 0, t = typeof n == "object" && n !== null && "name" in n ? n.name : void 0;
5059
5094
  if (typeof t != "string" || t.length === 0) return [];
5060
- const s = i.note, r = i.snapshotUrl;
5095
+ const r = i.note, c = i.snapshotUrl;
5061
5096
  return [
5062
5097
  {
5063
5098
  name: t,
5064
- ...typeof s == "string" && s.length > 0 ? { note: s } : {},
5065
- ...typeof r == "string" && r.length > 0 ? { snapshotUrl: r } : {},
5099
+ ...typeof r == "string" && r.length > 0 ? { note: r } : {},
5100
+ ...typeof c == "string" && c.length > 0 ? { snapshotUrl: c } : {},
5066
5101
  mark: i
5067
5102
  }
5068
5103
  ];
5069
5104
  });
5070
- return n.length > 0 ? n : void 0;
5105
+ return s.length > 0 ? s : void 0;
5071
5106
  }
5072
5107
  /**
5073
5108
  * The blocking engine refuses a send while the AI reply is pending unless
@@ -5078,10 +5113,10 @@ ${s}` : s;
5078
5113
  }
5079
5114
  };
5080
5115
  x.SENT_TEXT_HISTORY_MAX = 50;
5081
- let M = x;
5082
- class Ca {
5116
+ let I = x;
5117
+ class Aa {
5083
5118
  constructor(e) {
5084
- var a, n;
5119
+ var a, s;
5085
5120
  this.widget = e, this.subscriptions = [], this.disposed = !1, this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
5086
5121
  if (!this.shouldRestoreLastSession) {
5087
5122
  this.didReadStoredSession = !0;
@@ -5095,9 +5130,9 @@ class Ca {
5095
5130
  }, this.registerRoutingListener = () => {
5096
5131
  this.subscriptions.push(
5097
5132
  this.contactCtx.state.subscribe(({ contact: i }) => {
5098
- var l;
5133
+ var _;
5099
5134
  i != null && i.token && this.state.get().screen === "welcome" && this.state.setPartial({
5100
- screen: (l = this.config.router) != null && l.chatScreenOnly ? "chat" : "sessions"
5135
+ screen: (_ = this.config.router) != null && _.chatScreenOnly ? "chat" : "sessions"
5101
5136
  });
5102
5137
  })
5103
5138
  ), this.subscriptions.push(
@@ -5105,16 +5140,16 @@ class Ca {
5105
5140
  );
5106
5141
  }, this.routeFromSessions = ({
5107
5142
  isInitialFetchLoading: i,
5108
- data: l
5143
+ data: _
5109
5144
  }) => {
5110
- var o, t, s, r, c;
5145
+ var n, t, r, c, d;
5111
5146
  if (!(this.disposed || !this.didReadStoredSession)) {
5112
- if (this.restorableSessionId && !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
5113
- const p = l.find(
5114
- (d) => d.id === this.restorableSessionId && d.isOpened
5147
+ if (this.restorableSessionId && !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
5148
+ const l = _.find(
5149
+ (p) => p.id === this.restorableSessionId && p.isOpened
5115
5150
  );
5116
- if (p) {
5117
- this.restorableSessionId = null, this.toChatScreen(p.id);
5151
+ if (l) {
5152
+ this.restorableSessionId = null, this.toChatScreen(l.id);
5118
5153
  return;
5119
5154
  }
5120
5155
  if (i) return;
@@ -5122,86 +5157,87 @@ class Ca {
5122
5157
  }
5123
5158
  if ((t = this.config.router) != null && t.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5124
5159
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
5125
- !((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
5126
- const p = (r = l.find((d) => d.isOpened)) == null ? void 0 : r.id;
5127
- return p ? this.toChatScreen(p) : void 0;
5160
+ !((r = this.sessionCtx.sessionState.get().session) != null && r.id)) {
5161
+ const l = (c = _.find((p) => p.isOpened)) == null ? void 0 : c.id;
5162
+ return l ? this.toChatScreen(l) : void 0;
5128
5163
  }
5129
- l.length || ((c = this.config.router) == null ? void 0 : c.goToChatIfNoSessions) !== !1 && !i && this.state.get().screen !== "chat" && this.toChatScreen();
5164
+ _.length || ((d = this.config.router) == null ? void 0 : d.goToChatIfNoSessions) !== !1 && !i && this.state.get().screen !== "chat" && this.toChatScreen();
5130
5165
  }
5131
5166
  }, this.dispose = () => {
5132
5167
  this.disposed = !0, this.subscriptions.forEach((i) => i()), this.subscriptions = [], this.navigateConversation = void 0;
5133
5168
  }, this.toSessionsScreen = () => {
5134
5169
  this.navigateConversation || this.resetChat(), this.state.setPartial({ screen: "sessions" });
5135
5170
  }, this.toChatScreen = (i) => {
5136
- var o, t;
5171
+ var n, t;
5137
5172
  if (this.navigateConversation) return this.navigateConversation(i);
5138
5173
  this.resetChat();
5139
- let l;
5174
+ let _;
5140
5175
  if (i) {
5141
- if (l = this.sessionCtx.sessionsState.get().data.find((s) => s.id === i), !l) return;
5142
- this.sessionCtx.sessionState.setPartial({ session: l });
5176
+ if (_ = this.sessionCtx.sessionsState.get().data.find((r) => r.id === i), !_) return;
5177
+ this.sessionCtx.sessionState.setPartial({ session: _ });
5143
5178
  }
5144
- return this.state.setPartial({ screen: "chat" }), (t = (o = this.config.hooks) == null ? void 0 : o.onNavigateToChat) == null || t.call(o, { session: l }), this.widget;
5145
- }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new w({
5179
+ return this.state.setPartial({ screen: "chat" }), (t = (n = this.config.hooks) == null ? void 0 : n.onNavigateToChat) == null || t.call(n, { session: _ }), this.widget;
5180
+ }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new j({
5146
5181
  screen: this.contactCtx.shouldCollectData() ? "welcome" : (a = this.config.router) != null && a.chatScreenOnly ? "chat" : "sessions"
5147
- }), this.shouldRestoreLastSession = ((n = this.config.router) == null ? void 0 : n.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5182
+ }), this.shouldRestoreLastSession = ((s = this.config.router) == null ? void 0 : s.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5148
5183
  }
5149
5184
  }
5150
- class qa {
5185
+ class Pa {
5151
5186
  constructor({
5152
5187
  storage: e,
5153
5188
  config: a
5154
5189
  }) {
5155
5190
  this.KEYS = {
5156
- contactToken: (n) => `opencx-widget:org-token-${n}:contact-token`,
5157
- externalContactId: (n) => `opencx-widget:org-token-${n}:external-contact-id`,
5158
- companionPreference: (n, i) => `opencx-widget:org-token-${n}:companion-${i}`,
5159
- activeSession: (n) => `opencx-widget:org-token-${n}:active-session`
5160
- }, this.setContactToken = async (n) => {
5161
- await this.storage.set(this.KEYS.contactToken(this.config.token), n);
5191
+ contactToken: (s) => `opencx-widget:org-token-${s}:contact-token`,
5192
+ externalContactId: (s) => `opencx-widget:org-token-${s}:external-contact-id`,
5193
+ companionPreference: (s, i) => `opencx-widget:org-token-${s}:companion-${i}`,
5194
+ activeSession: (s) => `opencx-widget:org-token-${s}:active-session`
5195
+ }, this.setContactToken = async (s) => {
5196
+ await this.storage.set(this.KEYS.contactToken(this.config.token), s);
5162
5197
  }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken(this.config.token)), this.clearContactToken = async () => {
5163
5198
  await this.storage.remove(this.KEYS.contactToken(this.config.token));
5164
- }, this.activeSessionKey = () => this.KEYS.activeSession(this.config.token), this.getActiveSessionId = async () => this.storage.get(this.activeSessionKey()), this.setActiveSessionId = async (n) => {
5165
- await this.storage.set(this.activeSessionKey(), n);
5199
+ }, this.activeSessionKey = () => this.KEYS.activeSession(this.config.token), this.getActiveSessionId = async () => this.storage.get(this.activeSessionKey()), this.setActiveSessionId = async (s) => {
5200
+ await this.storage.set(this.activeSessionKey(), s);
5166
5201
  }, this.clearActiveSessionId = async () => {
5167
5202
  await this.storage.remove(this.activeSessionKey());
5168
- }, this.setExternalContactId = async (n) => {
5169
- await this.storage.set(this.KEYS.externalContactId(this.config.token), n);
5170
- }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.companionKey = (n) => this.KEYS.companionPreference(this.config.token, n), this.getFiniteNumber = async (n) => {
5171
- const i = await this.storage.get(n);
5203
+ }, this.setExternalContactId = async (s) => {
5204
+ await this.storage.set(this.KEYS.externalContactId(this.config.token), s);
5205
+ }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.companionKey = (s) => this.KEYS.companionPreference(this.config.token, s), this.getFiniteNumber = async (s) => {
5206
+ const i = await this.storage.get(s);
5172
5207
  if (i === null) return null;
5173
- const l = Number(i);
5174
- return Number.isFinite(l) ? l : null;
5175
- }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (n) => {
5176
- Number.isFinite(n) && await this.storage.set(this.companionKey("pill-offset-x"), String(n));
5177
- }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (n) => {
5178
- Number.isFinite(n) && await this.storage.set(this.companionKey("sidebar-width"), String(n));
5208
+ const _ = Number(i);
5209
+ return Number.isFinite(_) ? _ : null;
5210
+ }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (s) => {
5211
+ Number.isFinite(s) && await this.storage.set(this.companionKey("pill-offset-x"), String(s));
5212
+ }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (s) => {
5213
+ Number.isFinite(s) && await this.storage.set(this.companionKey("sidebar-width"), String(s));
5179
5214
  }, this.getCompanionSidebarSide = async () => {
5180
- const n = await this.storage.get(this.companionKey("sidebar-side"));
5181
- return n === "left" || n === "right" ? n : null;
5182
- }, this.setCompanionSidebarSide = async (n) => {
5183
- await this.storage.set(this.companionKey("sidebar-side"), n);
5215
+ const s = await this.storage.get(this.companionKey("sidebar-side"));
5216
+ return s === "left" || s === "right" ? s : null;
5217
+ }, this.setCompanionSidebarSide = async (s) => {
5218
+ await this.storage.set(this.companionKey("sidebar-side"), s);
5184
5219
  }, this.getCompanionLayout = async () => {
5185
- const n = await this.storage.get(this.companionKey("layout"));
5186
- return n === "compact" || n === "sidebar" ? n : null;
5187
- }, this.setCompanionLayout = async (n) => {
5188
- await this.storage.set(this.companionKey("layout"), n);
5220
+ const s = await this.storage.get(this.companionKey("layout"));
5221
+ return s === "compact" || s === "sidebar" ? s : null;
5222
+ }, this.setCompanionLayout = async (s) => {
5223
+ await this.storage.set(this.companionKey("layout"), s);
5189
5224
  }, this.getCompanionSidebarMode = async () => {
5190
- const n = await this.storage.get(this.companionKey("sidebar-mode"));
5191
- return n === "docked" || n === "floating" ? n : null;
5192
- }, this.setCompanionSidebarMode = async (n) => {
5193
- await this.storage.set(this.companionKey("sidebar-mode"), n);
5225
+ const s = await this.storage.get(this.companionKey("sidebar-mode"));
5226
+ return s === "docked" || s === "floating" ? s : null;
5227
+ }, this.setCompanionSidebarMode = async (s) => {
5228
+ await this.storage.set(this.companionKey("sidebar-mode"), s);
5194
5229
  }, this.storage = e, this.config = a;
5195
5230
  }
5196
5231
  }
5197
- function Ea({
5198
- org: _,
5232
+ function Ta({
5233
+ org: o,
5199
5234
  agent: e
5200
5235
  }) {
5201
5236
  return e ? {
5202
5237
  name: e.name,
5203
5238
  avatarUrl: e.avatar_url,
5204
5239
  streaming: e.streaming,
5240
+ ...e.presentation ? { presentation: e.presentation } : {},
5205
5241
  features: {
5206
5242
  dictation: e.features.dictation,
5207
5243
  attachments: e.features.attachments,
@@ -5209,7 +5245,7 @@ function Ea({
5209
5245
  clientTools: e.features.client_tools
5210
5246
  }
5211
5247
  } : {
5212
- name: _.name,
5248
+ name: o.name,
5213
5249
  avatarUrl: null,
5214
5250
  streaming: !1,
5215
5251
  features: {
@@ -5220,41 +5256,42 @@ function Ea({
5220
5256
  }
5221
5257
  };
5222
5258
  }
5223
- function T(_, e) {
5224
- return _ && e !== !1;
5259
+ function M(o, e) {
5260
+ return o && e !== !1;
5225
5261
  }
5226
- function Pa(_, e) {
5262
+ function Ma(o, e) {
5227
5263
  const a = e.features;
5228
5264
  return {
5229
- dictation: T(_.features.dictation, a == null ? void 0 : a.dictation),
5230
- attachments: _.features.attachments,
5231
- pageContext: T(
5232
- _.features.pageContext,
5265
+ dictation: M(o.features.dictation, a == null ? void 0 : a.dictation),
5266
+ attachments: o.features.attachments,
5267
+ pageContext: M(
5268
+ o.features.pageContext,
5233
5269
  a == null ? void 0 : a.pageContext
5234
5270
  ),
5235
- clientTools: T(
5236
- _.features.clientTools,
5271
+ clientTools: M(
5272
+ o.features.clientTools,
5237
5273
  a == null ? void 0 : a.clientTools
5238
5274
  )
5239
5275
  };
5240
5276
  }
5241
- class Aa extends Error {
5242
- constructor(e, a, n) {
5243
- super(a), this.name = "WidgetInitializationError", this.code = e, this.details = n;
5277
+ class Ia extends Error {
5278
+ constructor(e, a, s) {
5279
+ super(a), this.name = "WidgetInitializationError", this.code = e, this.details = s;
5244
5280
  }
5245
5281
  }
5246
- const y = class y {
5282
+ const w = class w {
5247
5283
  constructor({
5248
5284
  config: e,
5249
5285
  storage: a,
5250
- getClientCapabilities: n,
5251
- modes: i,
5252
- org: l,
5253
- agent: o,
5254
- parent: t
5286
+ getClientCapabilities: s,
5287
+ getRequestConfig: i,
5288
+ modes: _,
5289
+ org: n,
5290
+ agent: t,
5291
+ parent: r
5255
5292
  }) {
5256
5293
  if (this.modes = [], this.createConversation = () => {
5257
- const s = new y({
5294
+ const c = new w({
5258
5295
  config: {
5259
5296
  ...this.config,
5260
5297
  router: {
@@ -5267,32 +5304,34 @@ const y = class y {
5267
5304
  modes: this.modes,
5268
5305
  org: this.org,
5269
5306
  agent: this.agent,
5270
- parent: this
5307
+ parent: this,
5308
+ getRequestConfig: this.getRequestConfig,
5309
+ getClientCapabilities: this.getClientCapabilities
5271
5310
  });
5272
- return s.routerCtx.state.setPartial({
5311
+ return c.routerCtx.state.setPartial({
5273
5312
  screen: this.contactCtx.shouldCollectData() ? "welcome" : "chat"
5274
- }), s;
5313
+ }), c;
5275
5314
  }, this.releaseConversation = () => {
5276
5315
  this.routerCtx.dispose(), this.resetChat();
5277
5316
  }, this.resetChat = () => {
5278
5317
  this.sessionCtx.reset(), this.messageCtx.reset(), this.uploadCtx.reset();
5279
- }, this.reconcileAfterStream = (s) => this.activeSessionPollingCtx.reconcileAfterStream(s), !y.pollingIntervalsSeconds)
5318
+ }, this.reconcileAfterStream = (c) => this.activeSessionPollingCtx.reconcileAfterStream(c), !w.pollingIntervalsSeconds)
5280
5319
  throw Error(
5281
5320
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
5282
5321
  );
5283
- this.config = e, this.org = l, this.agent = o, this.features = Pa(o, e), this.api = (t == null ? void 0 : t.api) ?? new L({ config: e }), this.storageCtx = (t == null ? void 0 : t.storageCtx) ?? (a ? new qa({ storage: a, config: e }) : void 0), this.modes = i, this.contactCtx = (t == null ? void 0 : t.contactCtx) ?? new ie({
5322
+ this.config = e, this.getRequestConfig = i ?? (() => this.config), this.getClientCapabilities = s, this.org = n, this.agent = t, this.api = (r == null ? void 0 : r.api) ?? new O({ config: e }), this.storageCtx = (r == null ? void 0 : r.storageCtx) ?? (a ? new Pa({ storage: a, config: e }) : void 0), this.modes = _, this.contactCtx = (r == null ? void 0 : r.contactCtx) ?? new le({
5284
5323
  api: this.api,
5285
5324
  config: this.config,
5286
5325
  storageCtx: this.storageCtx
5287
- }), this.sessionCtx = new va({
5326
+ }), this.sessionCtx = new ja({
5288
5327
  config: this.config,
5289
5328
  api: this.api,
5290
5329
  contactCtx: this.contactCtx,
5291
5330
  // Remembers the open conversation so a reload can return to it.
5292
- storageCtx: t ? void 0 : this.storageCtx,
5293
- sharedSessions: t == null ? void 0 : t.sessionCtx.sessionsState,
5294
- sessionsPollingIntervalSeconds: y.pollingIntervalsSeconds.sessions
5295
- }), this.messageCtx = new M({
5331
+ storageCtx: r ? void 0 : this.storageCtx,
5332
+ sharedSessions: r == null ? void 0 : r.sessionCtx.sessionsState,
5333
+ sessionsPollingIntervalSeconds: w.pollingIntervalsSeconds.sessions
5334
+ }), this.messageCtx = new I({
5296
5335
  config: this.config,
5297
5336
  api: this.api,
5298
5337
  sessionCtx: this.sessionCtx,
@@ -5300,64 +5339,78 @@ const y = class y {
5300
5339
  // Streaming orgs send their turns over the AI SDK transport instead of
5301
5340
  // the blocking bot-chat send.
5302
5341
  streaming: this.streaming,
5342
+ isStreaming: () => this.streaming,
5303
5343
  sendsPageContext: this.features.pageContext,
5304
- getClientCapabilities: n
5305
- }), this.uploadCtx = new re(this.api), this.csatCtx = new _e({
5344
+ getSendsPageContext: () => this.features.pageContext,
5345
+ getClientCapabilities: s,
5346
+ getRequestConfig: i
5347
+ }), this.uploadCtx = new ce(this.api), this.csatCtx = new pe({
5306
5348
  api: this.api,
5307
5349
  sessionCtx: this.sessionCtx,
5308
5350
  messageCtx: this.messageCtx
5309
- }), this.dictationCtx = new Pe({
5351
+ }), this.dictationCtx = new Me({
5310
5352
  api: this.api,
5311
5353
  config: this.config
5312
- }), this.activeSessionPollingCtx = new oe({
5354
+ }), this.activeSessionPollingCtx = new _e({
5313
5355
  api: this.api,
5314
5356
  config: this.config,
5315
5357
  sessionCtx: this.sessionCtx,
5316
5358
  messageCtx: this.messageCtx,
5317
- sessionPollingIntervalSeconds: y.pollingIntervalsSeconds.session
5318
- }), this.routerCtx = new Ca(this);
5359
+ sessionPollingIntervalSeconds: w.pollingIntervalsSeconds.session
5360
+ }), this.routerCtx = new Aa(this);
5361
+ }
5362
+ get streaming() {
5363
+ var e, a;
5364
+ return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (a = this.messageCtx) != null && a.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming !== !1;
5319
5365
  }
5320
5366
  /**
5321
- * Whether turns stream (the v5 agent-chat engine) or use the blocking
5322
- * bot-chat send. Decided by the SERVER per org; the single source for every
5323
- * "which engine?" decision in the widget.
5367
+ * The org's features narrowed by this embed's `config.features` — the
5368
+ * answers the UI asks for, resolved against the current options.
5324
5369
  */
5325
- get streaming() {
5326
- return this.agent.streaming;
5370
+ get features() {
5371
+ return Ma(this.agent, this.getRequestConfig());
5327
5372
  }
5328
5373
  };
5329
- y.pollingIntervalsSeconds = null, y.initialize = async ({
5374
+ w.pollingIntervalsSeconds = null, w.initialize = async ({
5330
5375
  config: e,
5331
5376
  storage: a,
5332
- getClientCapabilities: n
5377
+ getClientCapabilities: s,
5378
+ getRequestConfig: i
5333
5379
  }) => {
5334
- var l, o;
5335
- const i = await new L({
5380
+ var n, t;
5381
+ const _ = await new O({
5336
5382
  config: e
5337
5383
  }).getExternalWidgetConfig();
5338
- if (!i.data)
5339
- throw m.error("widget config fetch failed", i.error), new Aa(
5384
+ if (!_.data)
5385
+ throw h.error("widget config fetch failed", _.error), new Ia(
5340
5386
  "config-fetch-failed",
5341
5387
  "Failed to fetch widget config",
5342
- i.error
5388
+ _.error
5343
5389
  );
5344
- return y.pollingIntervalsSeconds = {
5345
- session: ((l = i.data) == null ? void 0 : l.sessionPollingIntervalSeconds) || 10,
5346
- sessions: ((o = i.data) == null ? void 0 : o.sessionsPollingIntervalSeconds) || 60
5347
- }, new y({
5390
+ return w.pollingIntervalsSeconds = {
5391
+ session: ((n = _.data) == null ? void 0 : n.sessionPollingIntervalSeconds) || 10,
5392
+ sessions: ((t = _.data) == null ? void 0 : t.sessionsPollingIntervalSeconds) || 60
5393
+ }, new w({
5348
5394
  config: e,
5349
5395
  storage: a,
5350
- getClientCapabilities: n,
5351
- modes: i.data.modes || [],
5396
+ getClientCapabilities: s,
5397
+ getRequestConfig: i,
5398
+ modes: _.data.modes || [],
5352
5399
  org: {
5353
- id: i.data.org.id,
5354
- name: i.data.org.name
5400
+ id: _.data.org.id,
5401
+ name: _.data.org.name
5355
5402
  },
5356
- agent: Ea(i.data)
5403
+ agent: Ta(_.data)
5357
5404
  });
5358
5405
  };
5359
- let B = y;
5360
- class Fa {
5406
+ let H = w;
5407
+ function Ba(o, e) {
5408
+ return o ? {
5409
+ toolActivity: o.toolActivity === "hidden" || (e == null ? void 0 : e.toolActivity) === "hidden" ? "hidden" : o.toolActivity === "status" || (e == null ? void 0 : e.toolActivity) === "status" ? "status" : "details",
5410
+ reasoning: o.reasoning && (e == null ? void 0 : e.reasoning) !== !1
5411
+ } : e;
5412
+ }
5413
+ class Va {
5361
5414
  constructor({ attack: e, release: a }) {
5362
5415
  this.value = 0, this.attack = e, this.release = a;
5363
5416
  }
@@ -5372,49 +5425,50 @@ const P = [
5372
5425
  "compact",
5373
5426
  "sidebar",
5374
5427
  "fullscreen"
5375
- ], Ta = new Set(
5428
+ ], Da = new Set(
5376
5429
  P
5377
5430
  );
5378
- function $(_) {
5379
- return Ta.has(_);
5431
+ function J(o) {
5432
+ return Da.has(o);
5380
5433
  }
5381
- function Oa(_) {
5382
- if (!Array.isArray(_)) return P;
5434
+ function Ha(o) {
5435
+ if (!Array.isArray(o)) return P;
5383
5436
  const e = [], a = /* @__PURE__ */ new Set();
5384
- for (const n of _)
5385
- !$(n) || a.has(n) || (a.add(n), e.push(n));
5437
+ for (const s of o)
5438
+ !J(s) || a.has(s) || (a.add(s), e.push(s));
5386
5439
  return e.length > 0 ? e : P;
5387
5440
  }
5388
- function Ua(_, e) {
5389
- return $(_) && e.includes(_) ? _ : e[0] ?? P[0];
5441
+ function Ga(o, e) {
5442
+ return J(o) && e.includes(o) ? o : e[0] ?? P[0];
5390
5443
  }
5391
- function Ba(_, e) {
5392
- return _ === "left" || _ === "right" ? _ : e === "rtl" ? "left" : "right";
5444
+ function Wa(o, e) {
5445
+ return o === "left" || o === "right" ? o : e === "rtl" ? "left" : "right";
5393
5446
  }
5394
- function Va(_) {
5395
- return _ === "docked" ? "docked" : "floating";
5447
+ function $a(o) {
5448
+ return o === "docked" ? "docked" : "floating";
5396
5449
  }
5397
5450
  export {
5398
- Fa as DictationLevelSmoother,
5399
- w as PrimitiveState,
5400
- B as WidgetCtx,
5401
- Aa as WidgetInitializationError,
5402
- za as buildSendMessageBody,
5451
+ Va as DictationLevelSmoother,
5452
+ j as PrimitiveState,
5453
+ H as WidgetCtx,
5454
+ Ia as WidgetInitializationError,
5455
+ Ea as buildSendMessageBody,
5403
5456
  z as genUuid,
5404
- ba as getTranslation,
5405
- Ra as isAgentStreamKeepalive,
5406
- ne as isExhaustive,
5407
- U as isRecord,
5408
- La as isRtlLanguage,
5409
- ha as isSupportedLanguage,
5410
- Ka as isTurnSteeredPart,
5411
- m as log,
5412
- Oa as normalizeCompanionLayouts,
5413
- Ua as resolveCompanionDefaultLayout,
5414
- Sa as resolveConfigContext,
5415
- ka as resolveLanguage,
5416
- Va as resolveSidebarMode,
5417
- Ba as resolveSidebarSide,
5418
- fa as translate
5457
+ ya as getTranslation,
5458
+ Fa as isAgentStreamKeepalive,
5459
+ re as isExhaustive,
5460
+ V as isRecord,
5461
+ Ua as isRtlLanguage,
5462
+ ba as isSupportedLanguage,
5463
+ Oa as isTurnSteeredPart,
5464
+ h as log,
5465
+ Ha as normalizeCompanionLayouts,
5466
+ Ba as resolveClientPresentation,
5467
+ Ga as resolveCompanionDefaultLayout,
5468
+ Ca as resolveConfigContext,
5469
+ va as resolveLanguage,
5470
+ $a as resolveSidebarMode,
5471
+ Wa as resolveSidebarSide,
5472
+ wa as translate
5419
5473
  };
5420
5474
  //# sourceMappingURL=index.js.map