@opencx/widget-core 5.3.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,109 @@
1
+ import se from "lodash.isequal";
1
2
  import { z as h } from "zod";
2
- import se from "openapi-fetch";
3
- import oe from "lodash.isequal";
4
- import { v4 as N } from "uuid";
5
- const Wa = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn-steered", L = h.object({ const: h.string(), title: h.string().optional() }), ne = h.object({
3
+ import oe from "openapi-fetch";
4
+ import { v4 as R } from "uuid";
5
+ const L = "[opencx]", k = {
6
+ warn: (i, ...e) => {
7
+ console.warn(`${L} ${i}`, ...e);
8
+ },
9
+ error: (i, ...e) => {
10
+ console.error(`${L} ${i}`, ...e);
11
+ }
12
+ };
13
+ class S {
14
+ constructor(e) {
15
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (t) => {
16
+ se(this.state, t) || (this.state = t, this.notifySubscribers(t));
17
+ }, this.setPartial = (t) => {
18
+ if (t == null) return;
19
+ const o = { ...this.state, ...t };
20
+ this.set(o);
21
+ }, this.reset = () => {
22
+ this.set(this.initialState);
23
+ }, this.notifySubscribers = (t) => {
24
+ Array.from(this.subscribers).forEach((r) => {
25
+ try {
26
+ r(t);
27
+ } catch (_) {
28
+ k.error("state subscriber threw", _);
29
+ }
30
+ });
31
+ }, this.subscribe = (t) => (this.subscribers.add(t), () => {
32
+ this.subscribers.delete(t);
33
+ }), this.state = e, this.initialState = e;
34
+ }
35
+ }
36
+ const ne = 5e3;
37
+ class ie {
38
+ constructor({
39
+ config: e,
40
+ api: t,
41
+ sessionsState: o,
42
+ setSessions: r
43
+ }) {
44
+ this.state = new S({ unreadSessionIds: [], count: 0 }), this.viewingSessionId = null, this.readsInFlight = /* @__PURE__ */ new Set(), this.retryTimer = null, this.lastNotifiedCount = null, this.subscriptions = [], this.disposed = !1, this.dispose = () => {
45
+ this.disposed = !0, this.subscriptions.forEach((_) => _()), this.subscriptions = [], this.viewingSessionId = null, this.retryTimer && clearTimeout(this.retryTimer), this.retryTimer = null;
46
+ }, this.setViewingSessionId = (_) => {
47
+ this.viewingSessionId = _, this.evaluate(this.sessionsState.get().data);
48
+ }, this.evaluate = (_) => {
49
+ const s = [];
50
+ for (const a of _)
51
+ if (a.unread === !0) {
52
+ if (a.id === this.viewingSessionId) {
53
+ this.markViewedSessionRead(a.id);
54
+ continue;
55
+ }
56
+ s.push(a.id);
57
+ }
58
+ this.state.set({ unreadSessionIds: s, count: s.length }), this.notifyCount(s.length);
59
+ }, this.markViewedSessionRead = (_) => {
60
+ if (this.readsInFlight.has(_)) return;
61
+ this.readsInFlight.add(_);
62
+ let s = !1;
63
+ this.api.markSessionRead({ sessionId: _ }).then(({ data: a }) => {
64
+ if (!a || this.disposed) return;
65
+ const n = this.sessionsState.get().data.find((c) => c.id === a.id);
66
+ n && re(n, a) ? s = !0 : this.setSessions([a]);
67
+ }).catch((a) => {
68
+ k.warn("failed to mark the session read", {
69
+ sessionId: _,
70
+ error: a instanceof Error ? a.message : String(a)
71
+ }), this.scheduleRetry();
72
+ }).finally(() => {
73
+ this.readsInFlight.delete(_), s && !this.disposed && this.evaluate(this.sessionsState.get().data);
74
+ });
75
+ }, this.scheduleRetry = () => {
76
+ this.retryTimer || this.disposed || (this.retryTimer = setTimeout(() => {
77
+ this.retryTimer = null, this.evaluate(this.sessionsState.get().data);
78
+ }, ne));
79
+ }, this.notifyCount = (_) => {
80
+ var s, a;
81
+ if (_ !== this.lastNotifiedCount) {
82
+ this.lastNotifiedCount = _;
83
+ try {
84
+ (a = (s = this.config.hooks) == null ? void 0 : s.onUnreadCountChange) == null || a.call(s, _);
85
+ } catch (n) {
86
+ k.error("onUnreadCountChange hook failed", n);
87
+ }
88
+ }
89
+ }, this.config = e, this.api = t, this.sessionsState = o, this.setSessions = r, this.subscriptions.push(
90
+ o.subscribe(({ data: _ }) => this.evaluate(_))
91
+ );
92
+ }
93
+ }
94
+ function re(i, e) {
95
+ return new Date(i.updatedAt).getTime() > new Date(e.updatedAt).getTime();
96
+ }
97
+ const Ya = (i) => i.type === "data-keepalive", Xa = (i) => i.type === "data-turn-steered", O = h.object({ const: h.string(), title: h.string().optional() }), _e = h.object({
6
98
  type: h.enum(["string", "number", "integer", "boolean", "array"]),
7
99
  title: h.string().optional(),
8
100
  description: h.string().optional(),
9
101
  default: h.union([h.string(), h.number(), h.boolean(), h.array(h.string())]).optional(),
10
102
  enum: h.array(h.string()).optional(),
11
- oneOf: h.array(L).optional(),
103
+ oneOf: h.array(O).optional(),
12
104
  items: h.object({
13
105
  enum: h.array(h.string()).optional(),
14
- anyOf: h.array(L).optional()
106
+ anyOf: h.array(O).optional()
15
107
  }).optional(),
16
108
  minItems: h.number().int().nonnegative().optional(),
17
109
  maxItems: h.number().int().nonnegative().optional(),
@@ -20,7 +112,7 @@ const Wa = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn
20
112
  minLength: h.number().optional(),
21
113
  maxLength: h.number().optional(),
22
114
  format: h.string().optional()
23
- }), ie = h.array(
115
+ }), le = h.array(
24
116
  h.object({
25
117
  id: h.string(),
26
118
  serverId: h.string(),
@@ -30,12 +122,12 @@ const Wa = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn
30
122
  form: h.object({
31
123
  message: h.string(),
32
124
  requestedSchema: h.object({
33
- properties: h.record(h.string(), ne),
125
+ properties: h.record(h.string(), _e),
34
126
  required: h.array(h.string()).optional()
35
127
  })
36
128
  })
37
129
  })
38
- ), re = h.array(
130
+ ), ce = h.array(
39
131
  h.object({
40
132
  key: h.string(),
41
133
  serverId: h.string(),
@@ -43,174 +135,167 @@ const Wa = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn
43
135
  message: h.string(),
44
136
  toolName: h.string()
45
137
  })
46
- ), O = "[opencx]", k = {
47
- warn: (i, ...e) => {
48
- console.warn(`${O} ${i}`, ...e);
49
- },
50
- error: (i, ...e) => {
51
- console.error(`${O} ${i}`, ...e);
52
- }
53
- }, _e = (i) => {
138
+ ), pe = (i) => {
54
139
  k.error("request failed", i.error);
55
- }, le = (i) => {
56
- const e = se({
140
+ }, de = (i) => {
141
+ const e = oe({
57
142
  baseUrl: i.baseUrl
58
- }), a = {
143
+ }), t = {
59
144
  onRequest: i.onRequest,
60
145
  onResponse: i.onResponse,
61
- onError: i.onError || _e
146
+ onError: i.onError || pe
62
147
  };
63
- return e.use(a), e;
148
+ return e.use(t), e;
64
149
  };
65
- class ce extends Error {
150
+ class ue extends Error {
66
151
  constructor() {
67
152
  super("This connection request expired. Preparing a new request."), this.name = "ConnectionRequestExpiredError";
68
153
  }
69
154
  }
70
- class pe extends Error {
155
+ class me extends Error {
71
156
  constructor() {
72
157
  super("This connection attempt is no longer available."), this.name = "ConnectionAttemptUnavailableError";
73
158
  }
74
159
  }
75
- const de = "/backend/widget/v5/chat/stream", ue = "/backend/widget/v5/chat/{sessionId}/stream", F = (i, e, a) => `${i.replace(/\/$/, "")}${a ? e.replace("{sessionId}", encodeURIComponent(a)) : e}`;
160
+ const he = "/backend/widget/v5/chat/stream", ge = "/backend/widget/v5/chat/{sessionId}/stream", F = (i, e, t) => `${i.replace(/\/$/, "")}${t ? e.replace("{sessionId}", encodeURIComponent(t)) : e}`;
76
161
  class U {
77
162
  constructor({ config: e }) {
78
- var r, c;
163
+ var r, _;
79
164
  this.userToken = null, this.constructClientOptions = (s) => {
80
- const t = this.config.apiUrl || "https://api.open.cx", n = {
165
+ const a = this.config.apiUrl || "https://api.open.cx", n = {
81
166
  "X-Bot-Token": this.config.token,
82
167
  "Content-Type": "application/json",
83
168
  Accept: "application/json",
84
169
  Authorization: s ? `Bearer ${s}` : void 0
85
170
  };
86
- return { baseUrl: t, headers: n };
171
+ return { baseUrl: a, headers: n };
87
172
  }, this.createOpenAPIClient = ({
88
173
  baseUrl: s,
89
- headers: t
90
- }) => le({
174
+ headers: a
175
+ }) => de({
91
176
  baseUrl: s,
92
177
  onRequest: ({ request: n }) => {
93
- Object.entries(t).forEach(([l, d]) => {
94
- d && n.headers.set(l, d);
178
+ Object.entries(a).forEach(([c, d]) => {
179
+ d && n.headers.set(c, d);
95
180
  });
96
181
  }
97
182
  }), this.listApprovalPreferences = async () => {
98
- const { baseUrl: s, headers: t } = this.getStreamAuthContext(), n = await fetch(
183
+ const { baseUrl: s, headers: a } = this.getStreamAuthContext(), n = await fetch(
99
184
  `${s}/backend/widget/v5/connections/approval-preferences`,
100
- { headers: t }
185
+ { headers: a }
101
186
  );
102
187
  if (!n.ok) throw new Error("Could not load permissions.");
103
- return re.parse(await n.json());
104
- }, this.revokeApprovalPreference = async (s, t) => {
105
- const { baseUrl: n, headers: l } = this.getStreamAuthContext();
188
+ return ce.parse(await n.json());
189
+ }, this.revokeApprovalPreference = async (s, a) => {
190
+ const { baseUrl: n, headers: c } = this.getStreamAuthContext();
106
191
  if (!(await fetch(
107
- `${n}/backend/widget/v5/connections/${encodeURIComponent(s)}/approval-preferences/${encodeURIComponent(t)}`,
108
- { method: "DELETE", headers: l }
192
+ `${n}/backend/widget/v5/connections/${encodeURIComponent(s)}/approval-preferences/${encodeURIComponent(a)}`,
193
+ { method: "DELETE", headers: c }
109
194
  )).ok) throw new Error("Could not reset permission.");
110
- }, this.listElicitations = async (s, t) => {
111
- const { baseUrl: n, headers: l } = this.getStreamAuthContext(), d = await fetch(
195
+ }, this.listElicitations = async (s, a) => {
196
+ const { baseUrl: n, headers: c } = this.getStreamAuthContext(), d = await fetch(
112
197
  `${n}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}`,
113
- { headers: l, signal: t }
198
+ { headers: c, signal: a }
114
199
  );
115
200
  if (!d.ok) throw new Error("Could not load the request.");
116
- return ie.parse(await d.json());
117
- }, this.answerElicitation = async (s, t, n) => {
118
- const { baseUrl: l, headers: d } = this.getStreamAuthContext(), _ = await fetch(
119
- `${l}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}/${encodeURIComponent(t)}`,
201
+ return le.parse(await d.json());
202
+ }, this.answerElicitation = async (s, a, n) => {
203
+ const { baseUrl: c, headers: d } = this.getStreamAuthContext(), l = await fetch(
204
+ `${c}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}/${encodeURIComponent(a)}`,
120
205
  {
121
206
  method: "POST",
122
207
  headers: { ...d, "Content-Type": "application/json" },
123
208
  body: JSON.stringify(n)
124
209
  }
125
210
  );
126
- if (!_.ok)
211
+ if (!l.ok)
127
212
  throw new Error(
128
- _.status === 400 ? "Check your answers and try again." : "This request has ended. Ask the agent to try again."
213
+ l.status === 400 ? "Check your answers and try again." : "This request has ended. Ask the agent to try again."
129
214
  );
130
215
  }, this.listConnections = async (s) => {
131
- const { data: t, error: n } = await this.client.GET(
216
+ const { data: a, error: n } = await this.client.GET(
132
217
  "/backend/widget/v5/connections",
133
218
  { signal: s }
134
219
  );
135
- if (n || !t)
220
+ if (n || !a)
136
221
  throw new Error("Could not load connections. Sign in and try again.");
137
- return t;
138
- }, this.startConnection = async (s, t, n) => {
139
- const { data: l, error: d, response: _ } = await this.client.POST(
222
+ return a;
223
+ }, this.startConnection = async (s, a, n) => {
224
+ const { data: c, error: d, response: l } = await this.client.POST(
140
225
  "/backend/widget/v5/connections/{serverId}/start",
141
226
  {
142
227
  params: { path: { serverId: s } },
143
- body: { request_id: t },
228
+ body: { request_id: a },
144
229
  signal: n
145
230
  }
146
231
  );
147
- if (_.status === 410) throw new ce();
148
- if (_.status === 404)
232
+ if (l.status === 410) throw new ue();
233
+ if (l.status === 404)
149
234
  throw new Error("This connection request is no longer available.");
150
- if (d || !l)
235
+ if (d || !c)
151
236
  throw new Error("Could not start this connection. Please try again.");
152
- return l;
153
- }, this.getConnectionAttempt = async (s, t, n) => {
154
- const { data: l, error: d, response: _ } = await this.client.GET(
237
+ return c;
238
+ }, this.getConnectionAttempt = async (s, a, n) => {
239
+ const { data: c, error: d, response: l } = await this.client.GET(
155
240
  "/backend/widget/v5/connections/{serverId}/attempts/{attemptId}",
156
241
  {
157
- params: { path: { serverId: s, attemptId: t } },
242
+ params: { path: { serverId: s, attemptId: a } },
158
243
  signal: n
159
244
  }
160
245
  );
161
- if ([401, 403, 404].includes(_.status))
162
- throw new pe();
163
- if (d || !l)
164
- throw new Error(`Could not check the connection (${_.status}).`);
165
- return l.status;
246
+ if ([401, 403, 404].includes(l.status))
247
+ throw new me();
248
+ if (d || !c)
249
+ throw new Error(`Could not check the connection (${l.status}).`);
250
+ return c.status;
166
251
  }, this.disconnectConnection = async (s) => {
167
- const { error: t } = await this.client.DELETE(
252
+ const { error: a } = await this.client.DELETE(
168
253
  "/backend/widget/v5/connections/{serverId}",
169
254
  {
170
255
  params: { path: { serverId: s } }
171
256
  }
172
257
  );
173
- if (t) throw new Error("Could not disconnect. Please try again.");
258
+ if (a) throw new Error("Could not disconnect. Please try again.");
174
259
  }, this.setAuthToken = (s) => {
175
260
  this.userToken = s;
176
- const { baseUrl: t, headers: n } = this.constructClientOptions(s);
177
- this.client = this.createOpenAPIClient({ baseUrl: t, headers: n });
261
+ const { baseUrl: a, headers: n } = this.constructClientOptions(s);
262
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: n });
178
263
  }, this.getStreamAuthContext = () => {
179
- const { baseUrl: s, headers: t } = this.constructClientOptions(this.userToken), n = {};
180
- for (const [l, d] of Object.entries(t))
181
- typeof d == "string" && (["content-type", "accept"].includes(l.toLowerCase()) || (n[l] = d));
264
+ const { baseUrl: s, headers: a } = this.constructClientOptions(this.userToken), n = {};
265
+ for (const [c, d] of Object.entries(a))
266
+ typeof d == "string" && (["content-type", "accept"].includes(c.toLowerCase()) || (n[c] = d));
182
267
  return { baseUrl: s, headers: n };
183
268
  }, this.getStreamTransportOptions = () => {
184
- const { baseUrl: s, headers: t } = this.getStreamAuthContext();
269
+ const { baseUrl: s, headers: a } = this.getStreamAuthContext();
185
270
  return {
186
- api: F(s, de),
187
- reconnectApi: (n) => F(s, ue, n),
188
- headers: t
271
+ api: F(s, he),
272
+ reconnectApi: (n) => F(s, ge, n),
273
+ headers: a
189
274
  };
190
275
  }, this.stopStream = async (s) => {
191
- const { response: t } = await this.client.POST(
276
+ const { response: a } = await this.client.POST(
192
277
  "/backend/widget/v5/chat/{sessionId}/stop",
193
278
  { params: { path: { sessionId: s } } }
194
279
  );
195
- if (!t.ok)
196
- throw new Error(`Failed to stop stream: ${t.status}`);
197
- }, this.sendPageReply = async (s, t) => {
280
+ if (!a.ok)
281
+ throw new Error(`Failed to stop stream: ${a.status}`);
282
+ }, this.sendPageReply = async (s, a) => {
198
283
  try {
199
284
  await this.client.POST("/backend/widget/v5/chat/{sessionId}/page-reply", {
200
285
  params: { path: { sessionId: s } },
201
- body: t
286
+ body: a
202
287
  });
203
288
  } catch {
204
289
  }
205
- }, this.getAgentTurnMessages = async (s, t) => {
206
- const { data: n, response: l } = await this.client.GET(
290
+ }, this.getAgentTurnMessages = async (s, a) => {
291
+ const { data: n, response: c } = await this.client.GET(
207
292
  "/backend/widget/v5/chat/{sessionId}/messages",
208
293
  {
209
294
  params: {
210
295
  path: { sessionId: s },
211
296
  query: {
212
- toolActivity: t == null ? void 0 : t.toolActivity,
213
- reasoning: (t == null ? void 0 : t.reasoning) === void 0 ? void 0 : t.reasoning ? "true" : "false"
297
+ toolActivity: a == null ? void 0 : a.toolActivity,
298
+ reasoning: (a == null ? void 0 : a.reasoning) === void 0 ? void 0 : a.reasoning ? "true" : "false"
214
299
  }
215
300
  }
216
301
  }
@@ -218,63 +303,72 @@ class U {
218
303
  return n ? {
219
304
  ...n,
220
305
  handled_connection_request_ids: n.handled_connection_request_ids ?? []
221
- } : (k.warn("agent turn messages fetch failed", l.status), null);
306
+ } : (k.warn("agent turn messages fetch failed", c.status), null);
222
307
  }, this.createDictationSession = async ({
223
308
  language: s
224
309
  }) => {
225
- const { data: t, response: n } = await this.client.POST(
310
+ const { data: a, response: n } = await this.client.POST(
226
311
  "/backend/widget/v5/dictation/sessions",
227
312
  { body: s ? { language: s } : {} }
228
313
  );
229
- if (!t)
314
+ if (!a)
230
315
  throw new Error(`Failed to start dictation: ${n.status}`);
231
- return t;
316
+ return a;
232
317
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
233
318
  params: {
234
319
  header: { "x-bot-token": this.config.token }
235
320
  }
236
- }), this.sendMessage = async (s, t) => await this.client.POST("/backend/widget/v2/chat/send", {
321
+ }), this.sendMessage = async (s, a) => await this.client.POST("/backend/widget/v2/chat/send", {
237
322
  body: s,
238
- signal: t
323
+ signal: a
239
324
  }), this.createUnverifiedContact = async (s) => await this.client.POST(
240
325
  "/backend/widget/v2/contact/create-unverified",
241
326
  {
242
327
  params: { header: { "x-bot-token": this.config.token } },
243
328
  body: s
244
329
  }
245
- ), this.createSession = async (s, t) => await this.client.POST("/backend/widget/v2/create-session", {
330
+ ), this.createSession = async (s, a) => await this.client.POST("/backend/widget/v2/create-session", {
246
331
  body: s,
247
- signal: t
332
+ signal: a
248
333
  }), this.pollSessionAndHistory = async ({
249
334
  sessionId: s,
250
- abortSignal: t
335
+ abortSignal: a
251
336
  }) => await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
252
337
  params: { path: { sessionId: s } },
253
- signal: t
254
- }), this.getSessions = async ({
338
+ signal: a
339
+ }), this.markSessionRead = async ({
340
+ sessionId: s,
341
+ abortSignal: a
342
+ }) => await this.client.POST(
343
+ "/backend/widget/v2/session/{sessionId}/read",
344
+ {
345
+ params: { path: { sessionId: s } },
346
+ signal: a
347
+ }
348
+ ), this.getSessions = async ({
255
349
  cursor: s,
256
- filters: t,
350
+ filters: a,
257
351
  abortSignal: n
258
352
  }) => await this.client.GET("/backend/widget/v2/sessions", {
259
353
  params: {
260
354
  query: {
261
355
  offset: s,
262
- filters: JSON.stringify(t)
356
+ filters: JSON.stringify(a)
263
357
  }
264
358
  },
265
359
  signal: n
266
360
  }), this.uploadFile = async ({
267
361
  file: s,
268
- abortSignal: t,
362
+ abortSignal: a,
269
363
  onProgress: n
270
- }) => new Promise((l, d) => {
364
+ }) => new Promise((c, d) => {
271
365
  var f;
272
- const _ = new FormData();
273
- _.append("file", s);
366
+ const l = new FormData();
367
+ l.append("file", s);
274
368
  const p = new XMLHttpRequest();
275
- if (t && (t.addEventListener("abort", () => {
369
+ if (a && (a.addEventListener("abort", () => {
276
370
  p.abort(), d(new DOMException("Aborted", "AbortError"));
277
- }), t.aborted)) {
371
+ }), a.aborted)) {
278
372
  d(new DOMException("Aborted", "AbortError"));
279
373
  return;
280
374
  }
@@ -287,7 +381,7 @@ class U {
287
381
  if (p.status >= 200 && p.status < 300)
288
382
  try {
289
383
  const v = JSON.parse(p.responseText);
290
- l(v);
384
+ c(v);
291
385
  } catch (v) {
292
386
  d(new Error(`Failed to parse response: ${v}`));
293
387
  }
@@ -299,45 +393,22 @@ class U {
299
393
  d(new Error("Upload timed out"));
300
394
  });
301
395
  const { baseUrl: u } = this.constructClientOptions(this.userToken), g = `${u}/backend/widget/v2/upload`;
302
- 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}`) : k.error("user token not set"), p.send(_);
303
- }), this.vote = async (s) => await this.client.POST("/backend/widget/v2/chat/vote", { body: s }), this.resolveSession = async (s, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
396
+ 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}`) : k.error("user token not set"), p.send(l);
397
+ }), this.vote = async (s) => await this.client.POST("/backend/widget/v2/chat/vote", { body: s }), this.resolveSession = async (s, a) => await this.client.POST("/backend/widget/v2/session/resolve", {
304
398
  body: s,
305
- signal: t
399
+ signal: a
306
400
  }), this.createStateCheckpoint = async (s) => await this.client.POST("/backend/widget/v2/checkpoint", {
307
401
  body: s
308
402
  }), this.submitCsat = async (s) => await this.client.POST("/backend/widget/v2/submit-csat", { body: s }), this.config = e, this.userToken = ((r = e.user) == null ? void 0 : r.token) || null;
309
- const { baseUrl: a, headers: o } = this.constructClientOptions(
310
- (c = e.user) == null ? void 0 : c.token
403
+ const { baseUrl: t, headers: o } = this.constructClientOptions(
404
+ (_ = e.user) == null ? void 0 : _.token
311
405
  );
312
- this.client = this.createOpenAPIClient({ baseUrl: a, headers: o });
406
+ this.client = this.createOpenAPIClient({ baseUrl: t, headers: o });
313
407
  }
314
408
  }
315
- function me(i, e) {
409
+ function ke(i, e) {
316
410
  k.error(`missing case for ${i} in ${e}`);
317
411
  }
318
- class S {
319
- constructor(e) {
320
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
321
- oe(this.state, a) || (this.state = a, this.notifySubscribers(a));
322
- }, this.setPartial = (a) => {
323
- if (a == null) return;
324
- const o = { ...this.state, ...a };
325
- this.set(o);
326
- }, this.reset = () => {
327
- this.set(this.initialState);
328
- }, this.notifySubscribers = (a) => {
329
- Array.from(this.subscribers).forEach((r) => {
330
- try {
331
- r(a);
332
- } catch (c) {
333
- k.error("state subscriber threw", c);
334
- }
335
- });
336
- }, this.subscribe = (a) => (this.subscribers.add(a), () => {
337
- this.subscribers.delete(a);
338
- }), this.state = e, this.initialState = e;
339
- }
340
- }
341
412
  class W {
342
413
  constructor() {
343
414
  this.state = new S({
@@ -346,20 +417,20 @@ class W {
346
417
  }), this.abortController = new AbortController(), this.reset = () => {
347
418
  var e;
348
419
  this.abortController.abort("Resetting poller"), (e = this.stopPolling) == null || e.call(this), this.stopPolling = null;
349
- }, this.stopPolling = null, this.startPolling = (e, a) => {
420
+ }, this.stopPolling = null, this.startPolling = (e, t) => {
350
421
  if (this.stopPolling) return;
351
422
  const o = [], r = async () => {
352
423
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
353
424
  try {
354
425
  await e(this.abortController.signal);
355
- } catch (c) {
426
+ } catch (_) {
356
427
  if (this.abortController.signal.aborted)
357
428
  return;
358
- k.error("failed to poll", c), this.state.setPartial({ isError: !0 });
429
+ k.error("failed to poll", _), this.state.setPartial({ isError: !0 });
359
430
  } finally {
360
431
  this.state.setPartial({ isPolling: !1 });
361
432
  }
362
- this.abortController.signal.aborted || o.push(setTimeout(r, a));
433
+ this.abortController.signal.aborted || o.push(setTimeout(r, t));
363
434
  };
364
435
  r(), this.stopPolling = () => {
365
436
  o.forEach(clearTimeout), this.state.reset();
@@ -370,26 +441,26 @@ class W {
370
441
  function $(i) {
371
442
  try {
372
443
  const e = i();
373
- return e instanceof Promise ? e.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: e };
444
+ return e instanceof Promise ? e.then((t) => ({ data: t })).catch((t) => ({ error: t })) : { data: e };
374
445
  } catch (e) {
375
446
  return { error: e };
376
447
  }
377
448
  }
378
- class he {
449
+ class be {
379
450
  constructor({
380
451
  api: e,
381
- config: a,
452
+ config: t,
382
453
  sessionCtx: o,
383
454
  messageCtx: r,
384
- sessionPollingIntervalSeconds: c
455
+ sessionPollingIntervalSeconds: _
385
456
  }) {
386
457
  this.poller = new W(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.subscriptions = [], this.reconcilingSessionId = null, this.registerPolling = () => {
387
458
  this.subscriptions.push(
388
459
  this.sessionCtx.sessionState.subscribe(({ session: s }) => {
389
- s != null && s.id ? this.poller.startPolling(async (t) => {
460
+ s != null && s.id ? this.poller.startPolling(async (a) => {
390
461
  this.fetchSessionAndHistory({
391
462
  sessionId: s.id,
392
- abortSignal: t
463
+ abortSignal: a
393
464
  });
394
465
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
395
466
  })
@@ -401,8 +472,8 @@ class he {
401
472
  sessionId: s.id,
402
473
  abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
403
474
  });
404
- } catch (t) {
405
- this.fetchSessionAndFullHistoryAbortController.signal.aborted || k.error("failed to fetch session and full history", t);
475
+ } catch (a) {
476
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || k.error("failed to fetch session and full history", a);
406
477
  }
407
478
  else
408
479
  this.fetchSessionAndFullHistoryAbortController.abort();
@@ -416,67 +487,67 @@ class he {
416
487
  this.poller.reset(), this.fetchSessionAndFullHistoryAbortController.abort(), this.reconcileAbortController.abort(), this.reconcilingSessionId = null, this.subscriptions.forEach((s) => s()), this.subscriptions = [];
417
488
  }, this.reconcileAfterStream = async (s) => {
418
489
  this.reconcileAbortController.abort(), this.reconcileAbortController = new AbortController();
419
- const { signal: t } = this.reconcileAbortController;
490
+ const { signal: a } = this.reconcileAbortController;
420
491
  this.reconcilingSessionId = s;
421
492
  try {
422
- await this.fetchSessionAndHistory({ sessionId: s, abortSignal: t });
493
+ await this.fetchSessionAndHistory({ sessionId: s, abortSignal: a });
423
494
  } catch (n) {
424
- if (!t.aborted) throw n;
495
+ if (!a.aborted) throw n;
425
496
  } finally {
426
497
  this.reconcilingSessionId === s && (this.reconcilingSessionId = null);
427
498
  }
428
499
  }, this.fetchSessionAndHistory = async ({
429
500
  sessionId: s,
430
- abortSignal: t
501
+ abortSignal: a
431
502
  }) => {
432
503
  const n = this.messageCtx.state.get().messages.length === 0;
433
504
  n && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
434
- const { data: l } = await this.api.pollSessionAndHistory({
505
+ const { data: c } = await this.api.pollSessionAndHistory({
435
506
  sessionId: s,
436
- abortSignal: t
507
+ abortSignal: a
437
508
  });
438
- if (l != null && l.session && (this.sessionCtx.sessionState.setPartial({ session: l.session }), this.sessionCtx.setSessions([l.session])), l != null && l.history && l.history.length > 0) {
439
- this.reconcileOptionPicks(l.history);
440
- const d = this.messageCtx.state.get().messages, _ = l.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
509
+ 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) {
510
+ this.reconcileOptionPicks(c.history);
511
+ const d = this.messageCtx.state.get().messages, l = c.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
441
512
  (p) => !d.some((u) => u.id === p.id)
442
513
  );
443
- if (_.length > 0)
514
+ if (l.length > 0)
444
515
  if (this.messageCtx.state.setPartial({
445
- messages: [...d, ..._]
516
+ messages: [...d, ...l]
446
517
  }), n)
447
518
  this.messageCtx.markAsDispatchedToOnMessageReceivedHook(
448
- _.map((p) => p.id)
519
+ l.map((p) => p.id)
449
520
  );
450
521
  else
451
- for (const p of _)
522
+ for (const p of l)
452
523
  this.messageCtx.dispatchToOnMessageReceivedHook(p);
453
524
  }
454
525
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
455
526
  }, this.reconcileOptionPicks = (s) => {
456
- var t;
527
+ var a;
457
528
  for (const n of s) {
458
- const l = (t = n.messageOptions) == null ? void 0 : t.pickedOptionId;
459
- l && this.messageCtx.setMessageOptionPick(n.publicId, l);
529
+ const c = (a = n.messageOptions) == null ? void 0 : a.pickedOptionId;
530
+ c && this.messageCtx.setMessageOptionPick(n.publicId, c);
460
531
  }
461
532
  }, this.mapHistoryToMessage = (s) => {
462
533
  var n;
463
- const t = {
534
+ const a = {
464
535
  id: s.publicId,
465
536
  timestamp: s.sentAt || "",
466
537
  attachments: s.attachments || void 0
467
538
  };
468
539
  if (s.sender.kind === "user")
469
540
  return {
470
- ...t,
541
+ ...a,
471
542
  type: "USER",
472
- deliveredAt: t.timestamp,
543
+ deliveredAt: a.timestamp,
473
544
  content: s.content.text || "",
474
545
  // Backend field name (schema.ts) → widget vocabulary.
475
546
  markedElements: s.pickedElements
476
547
  };
477
548
  if (s.sender.kind === "agent")
478
549
  return {
479
- ...t,
550
+ ...a,
480
551
  type: "AGENT",
481
552
  component: "agent_message",
482
553
  data: {
@@ -495,9 +566,9 @@ class he {
495
566
  ...s.messageOptions ? { messageOptions: s.messageOptions } : {}
496
567
  };
497
568
  if (s.sender.kind === "ai") {
498
- const l = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
569
+ const c = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
499
570
  return {
500
- ...t,
571
+ ...a,
501
572
  type: "AI",
502
573
  component: "bot_message",
503
574
  agent: {
@@ -510,27 +581,27 @@ class he {
510
581
  },
511
582
  data: {
512
583
  message: s.content.text || "",
513
- action: l ? {
514
- name: l.actionName,
515
- data: this.extractActionResult(l)
584
+ action: c ? {
585
+ name: c.actionName,
586
+ data: this.extractActionResult(c)
516
587
  } : void 0
517
588
  },
518
589
  ...this.constructReplyTo(s)
519
590
  };
520
591
  }
521
592
  if (s.sender.kind === "system") {
522
- const l = this.constructSystemMessage(s);
523
- return l === null ? null : { ...l };
593
+ const c = this.constructSystemMessage(s);
594
+ return c === null ? null : { ...c };
524
595
  }
525
596
  return null;
526
597
  }, this.constructReplyTo = (s) => {
527
598
  if (!s.replyTo) return {};
528
- const { publicId: t, text: n, sender: l } = s.replyTo;
599
+ const { publicId: a, text: n, sender: c } = s.replyTo;
529
600
  return {
530
601
  replyTo: {
531
- id: t,
602
+ id: a,
532
603
  text: n,
533
- sender: l
604
+ sender: c
534
605
  }
535
606
  };
536
607
  }, this.constructSystemMessage = (s) => {
@@ -571,43 +642,43 @@ class he {
571
642
  case "none":
572
643
  return null;
573
644
  default:
574
- return me(
645
+ return ke(
575
646
  s.systemMessagePayload,
576
647
  this.constructSystemMessage.name
577
648
  ), null;
578
649
  }
579
650
  }, this.extractActionResult = (s) => {
580
- const t = s.result;
581
- if (t === null || typeof t != "object") return t;
582
- if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
583
- const n = t.responseBodyText, l = $(() => JSON.parse(n)).data;
584
- if (l) return l;
651
+ const a = s.result;
652
+ if (a === null || typeof a != "object") return a;
653
+ if ("responseBodyText" in a && typeof a.responseBodyText == "string") {
654
+ const n = a.responseBodyText, c = $(() => JSON.parse(n)).data;
655
+ if (c) return c;
585
656
  }
586
657
  return s.result;
587
- }, this.api = e, this.config = a, this.sessionCtx = o, this.messageCtx = r, this.sessionPollingIntervalSeconds = c, this.registerPolling();
658
+ }, this.api = e, this.config = t, this.sessionCtx = o, this.messageCtx = r, this.sessionPollingIntervalSeconds = _, this.registerPolling();
588
659
  }
589
660
  }
590
- class ge {
661
+ class ve {
591
662
  constructor({
592
663
  config: e,
593
- api: a,
664
+ api: t,
594
665
  storageCtx: o
595
666
  }) {
596
667
  var r;
597
668
  this.shouldCollectData = () => {
598
- var c;
599
- return !!(!((c = this.state.get().contact) != null && c.token) && this.config.collectUserData);
669
+ var _;
670
+ return !!(!((_ = this.state.get().contact) != null && _.token) && this.config.collectUserData);
600
671
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
601
- var c, s, t, n, l, d, _, p, u, m, g, b, f, v;
602
- if (!((c = this.config.user) != null && c.token)) {
603
- if (this.config.collectUserData && !((t = (s = this.config.user) == null ? void 0 : s.data) != null && t.email)) {
672
+ var _, s, a, n, c, d, l, p, u, m, g, b, f, v;
673
+ if (!((_ = this.config.user) != null && _.token)) {
674
+ if (this.config.collectUserData && !((a = (s = this.config.user) == null ? void 0 : s.data) != null && a.email)) {
604
675
  if ((n = this.config.extraDataCollectionFields) != null && n.length)
605
676
  return;
606
- const y = await ((l = this.storageCtx) == null ? void 0 : l.getContactToken());
677
+ const y = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
607
678
  y && await this.setUnverifiedContact(y);
608
679
  return;
609
680
  }
610
- if (!((_ = (d = this.config.user) == null ? void 0 : d.data) != null && _.email)) {
681
+ if (!((l = (d = this.config.user) == null ? void 0 : d.data) != null && l.email)) {
611
682
  const y = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
612
683
  if (y) {
613
684
  await this.setUnverifiedContact(y);
@@ -620,43 +691,43 @@ class ge {
620
691
  non_verified_custom_data: (v = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : v.customData
621
692
  });
622
693
  }
623
- }, this.createUnverifiedContact = async (c, s) => {
694
+ }, this.createUnverifiedContact = async (_, s) => {
624
695
  this.state.setPartial({ extraCollectedData: s });
625
696
  try {
626
697
  this.state.setPartial({
627
698
  isCreatingUnverifiedContact: !0,
628
699
  isErrorCreatingUnverifiedContact: !1
629
700
  });
630
- const { data: t } = await this.api.createUnverifiedContact(c);
631
- t != null && t.token ? await this.setUnverifiedContact(t.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
632
- } catch (t) {
701
+ const { data: a } = await this.api.createUnverifiedContact(_);
702
+ a != null && a.token ? await this.setUnverifiedContact(a.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
703
+ } catch (a) {
633
704
  this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), k.error("failed to create an unverified contact", {
634
- _e: t instanceof Error ? t.message : String(t)
705
+ _e: a instanceof Error ? a.message : String(a)
635
706
  });
636
707
  } finally {
637
708
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
638
709
  }
639
710
  }, this.recoverFromStaleToken = async () => {
640
- var c, s, t, n, l, d, _, p, u, m;
641
- if ((c = this.config.user) != null && c.token) return !1;
711
+ var _, s, a, n, c, d, l, p, u, m;
712
+ if ((_ = this.config.user) != null && _.token) return !1;
642
713
  this.api.setAuthToken(""), this.state.setPartial({ contact: null });
643
714
  try {
644
- await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((t = this.storageCtx) == null ? void 0 : t.clearActiveSessionId());
715
+ await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((a = this.storageCtx) == null ? void 0 : a.clearActiveSessionId());
645
716
  } catch (g) {
646
717
  k.warn("failed to clear a stale contact token", {
647
718
  error: g instanceof Error ? g.message : String(g)
648
719
  });
649
720
  }
650
721
  return await this.createUnverifiedContact({
651
- email: (l = (n = this.config.user) == null ? void 0 : n.data) == null ? void 0 : l.email,
652
- non_verified_name: (_ = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : _.name,
722
+ email: (c = (n = this.config.user) == null ? void 0 : n.data) == null ? void 0 : c.email,
723
+ non_verified_name: (l = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : l.name,
653
724
  non_verified_custom_data: (u = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : u.customData
654
725
  }), !!((m = this.state.get().contact) != null && m.token);
655
- }, this.setUnverifiedContact = async (c) => {
656
- var n, l, d, _;
657
- const s = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), t = ((l = this.config.user) == null ? void 0 : l.externalId) || s || N();
658
- this.api.setAuthToken(c), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(c)), await ((_ = this.storageCtx) == null ? void 0 : _.setExternalContactId(t)), this.state.setPartial({ contact: { token: c, externalId: t } });
659
- }, this.config = e, this.storageCtx = o, this.api = a, this.state = new S({
726
+ }, this.setUnverifiedContact = async (_) => {
727
+ var n, c, d, l;
728
+ const s = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), a = ((c = this.config.user) == null ? void 0 : c.externalId) || s || R();
729
+ this.api.setAuthToken(_), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(_)), await ((l = this.storageCtx) == null ? void 0 : l.setExternalContactId(a)), this.state.setPartial({ contact: { token: _, externalId: a } });
730
+ }, this.config = e, this.storageCtx = o, this.api = t, this.state = new S({
660
731
  contact: (r = e.user) != null && r.token ? {
661
732
  token: e.user.token,
662
733
  // Set optional externalId from config... not local storage
@@ -668,37 +739,37 @@ class ge {
668
739
  }), this.autoCreateUnverifiedUserIfNotExists();
669
740
  }
670
741
  }
671
- class ke {
742
+ class fe {
672
743
  constructor(e) {
673
- this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (a) => {
674
- const o = a.map(
744
+ this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (t) => {
745
+ const o = t.map(
675
746
  (r) => ({
676
747
  file: r,
677
- id: N(),
748
+ id: R(),
678
749
  status: "pending",
679
750
  progress: 0
680
751
  })
681
752
  );
682
753
  this.state.set([...this.state.get(), ...o]), o.forEach((r) => void this.upload(r));
683
- }, this.cancel = (a) => {
754
+ }, this.cancel = (t) => {
684
755
  var o;
685
- (o = this.controllers.get(a)) == null || o.abort(), this.controllers.delete(a), this.state.set(this.state.get().filter((r) => r.id !== a));
756
+ (o = this.controllers.get(t)) == null || o.abort(), this.controllers.delete(t), this.state.set(this.state.get().filter((r) => r.id !== t));
686
757
  }, this.reset = () => {
687
- this.controllers.forEach((a) => a.abort()), this.controllers.clear(), this.state.reset();
758
+ this.controllers.forEach((t) => t.abort()), this.controllers.clear(), this.state.reset();
688
759
  };
689
760
  }
690
- update(e, a) {
761
+ update(e, t) {
691
762
  this.state.set(
692
- this.state.get().map((o) => o.id === e ? { ...o, ...a } : o)
763
+ this.state.get().map((o) => o.id === e ? { ...o, ...t } : o)
693
764
  );
694
765
  }
695
766
  async upload(e) {
696
- const a = new AbortController();
697
- this.controllers.set(e.id, a), this.update(e.id, { status: "uploading" });
767
+ const t = new AbortController();
768
+ this.controllers.set(e.id, t), this.update(e.id, { status: "uploading" });
698
769
  try {
699
770
  const o = await this.api.uploadFile({
700
771
  file: e.file,
701
- abortSignal: a.signal,
772
+ abortSignal: t.signal,
702
773
  onProgress: (r) => this.update(e.id, { progress: r })
703
774
  });
704
775
  this.update(e.id, {
@@ -707,7 +778,7 @@ class ke {
707
778
  progress: 100
708
779
  });
709
780
  } catch (o) {
710
- a.signal.aborted || this.update(e.id, {
781
+ t.signal.aborted || this.update(e.id, {
711
782
  status: "error",
712
783
  progress: 0,
713
784
  error: o instanceof Error ? o.message : "Upload failed"
@@ -718,18 +789,18 @@ class ke {
718
789
  }
719
790
  }
720
791
  function q() {
721
- return N();
792
+ return R();
722
793
  }
723
- class be {
794
+ class ye {
724
795
  constructor({
725
796
  api: e,
726
- sessionCtx: a,
797
+ sessionCtx: t,
727
798
  messageCtx: o
728
799
  }) {
729
800
  this.submitCsat = async (r) => {
730
- var l;
731
- const c = (l = this.sessionCtx.sessionState.get().session) == null ? void 0 : l.id;
732
- if (!c)
801
+ var c;
802
+ const _ = (c = this.sessionCtx.sessionState.get().session) == null ? void 0 : c.id;
803
+ if (!_)
733
804
  return { data: null, error: "No session id found" };
734
805
  const s = q();
735
806
  this.messageCtx.state.setPartial({
@@ -749,16 +820,16 @@ class be {
749
820
  }
750
821
  ]
751
822
  });
752
- const { data: t, error: n } = await this.api.submitCsat({
823
+ const { data: a, error: n } = await this.api.submitCsat({
753
824
  ...r,
754
825
  system_message_uuid: s,
755
- session_id: c
826
+ session_id: _
756
827
  });
757
- return { data: t, error: n };
758
- }, this.api = e, this.sessionCtx = a, this.messageCtx = o;
828
+ return { data: a, error: n };
829
+ }, this.api = e, this.sessionCtx = t, this.messageCtx = o;
759
830
  }
760
831
  }
761
- const ve = [
832
+ const we = [
762
833
  {
763
834
  action: "newparagraph",
764
835
  phrases: {
@@ -833,7 +904,7 @@ const ve = [
833
904
  it: ["invia messaggio"]
834
905
  }
835
906
  }
836
- ], fe = [
907
+ ], je = [
837
908
  "en",
838
909
  "es",
839
910
  "fr",
@@ -841,25 +912,25 @@ const ve = [
841
912
  "pt",
842
913
  "it"
843
914
  ];
844
- function ye(i) {
845
- return fe.includes(i);
915
+ function Se(i) {
916
+ return je.includes(i);
846
917
  }
847
- function we(i) {
918
+ function ze(i) {
848
919
  return i.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
849
920
  }
850
- function je(i) {
851
- const e = ve.flatMap(
921
+ function Ce(i) {
922
+ const e = we.flatMap(
852
923
  (r) => i.flatMap(
853
- (c) => r.phrases[c].map((s) => ({ phrase: s, action: r.action }))
924
+ (_) => r.phrases[_].map((s) => ({ phrase: s, action: r.action }))
854
925
  )
855
- ), a = e.map((r) => we(r.phrase)).sort((r, c) => c.length - r.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
926
+ ), t = e.map((r) => ze(r.phrase)).sort((r, _) => _.length - r.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
856
927
  return {
857
928
  regex: new RegExp(
858
- `${o}(${a})` + String.raw`([.,!?;:])(?=\s|$)`,
929
+ `${o}(${t})` + String.raw`([.,!?;:])(?=\s|$)`,
859
930
  "giu"
860
931
  ),
861
932
  finalRegex: new RegExp(
862
- `${o}(${a})` + String.raw`([.,!?;:]?)(?=\s|$)`,
933
+ `${o}(${t})` + String.raw`([.,!?;:]?)(?=\s|$)`,
863
934
  "giu"
864
935
  ),
865
936
  phraseToAction: new Map(
@@ -870,37 +941,37 @@ function je(i) {
870
941
  }
871
942
  const B = /* @__PURE__ */ new Map();
872
943
  function M(i) {
873
- const e = i && ye(i) && i !== "en" ? i : null, a = e ?? "en";
874
- let o = B.get(a);
875
- return o || (o = je(e ? ["en", e] : ["en"]), B.set(a, o)), o;
944
+ const e = i && Se(i) && i !== "en" ? i : null, t = e ?? "en";
945
+ let o = B.get(t);
946
+ return o || (o = Ce(e ? ["en", e] : ["en"]), B.set(t, o)), o;
876
947
  }
877
- function Se(i) {
948
+ function xe(i) {
878
949
  const e = i.replace(/\s+$/, "");
879
950
  if (!e) return "";
880
- const a = e.replace(/[.!?]+$/, "");
951
+ const t = e.replace(/[.!?]+$/, "");
881
952
  let o = -1;
882
- for (let r = a.length - 1; r >= 0; r--) {
883
- const c = a[r];
884
- if (c === "." || c === "!" || c === "?" || c === `
953
+ for (let r = t.length - 1; r >= 0; r--) {
954
+ const _ = t[r];
955
+ if (_ === "." || _ === "!" || _ === "?" || _ === `
885
956
  `) {
886
957
  o = r + 1;
887
958
  break;
888
959
  }
889
960
  }
890
- return o === -1 ? "" : `${a.slice(0, o)} `.replace(/\n $/, `
961
+ return o === -1 ? "" : `${t.slice(0, o)} `.replace(/\n $/, `
891
962
  `);
892
963
  }
893
- const ze = new RegExp(
964
+ const qe = new RegExp(
894
965
  String.raw`(^- |\n(?:- )?)(\p{Ll})`,
895
966
  "gu"
896
967
  );
897
- function Ce(i) {
968
+ function Ee(i) {
898
969
  return i.replace(
899
- ze,
900
- (e, a, o) => a + o.toUpperCase()
970
+ qe,
971
+ (e, t, o) => t + o.toUpperCase()
901
972
  );
902
973
  }
903
- function xe(i) {
974
+ function Ae(i) {
904
975
  return i.length <= 3 && /^\s*$/.test(i) ? !0 : /[.!?\n]\s{0,3}$/.test(i.slice(-6));
905
976
  }
906
977
  class E {
@@ -909,31 +980,31 @@ class E {
909
980
  * Pure and deterministic: always called with the entire raw string so the
910
981
  * result never depends on delta chunking.
911
982
  */
912
- static process(e, a) {
913
- const o = M(a == null ? void 0 : a.language), r = a != null && a.final ? "" : E.commandPrefixTail(e, a == null ? void 0 : a.language), c = e.slice(0, e.length - r.length), s = a != null && a.final ? o.finalRegex : o.regex;
914
- let t = "", n = null, l = 0;
915
- for (const _ of Array.from(c.matchAll(s))) {
916
- const [, p = ""] = _, u = o.phraseToAction.get(p.toLowerCase());
983
+ static process(e, t) {
984
+ const o = M(t == null ? void 0 : t.language), r = t != null && t.final ? "" : E.commandPrefixTail(e, t == null ? void 0 : t.language), _ = e.slice(0, e.length - r.length), s = t != null && t.final ? o.finalRegex : o.regex;
985
+ let a = "", n = null, c = 0;
986
+ for (const l of Array.from(_.matchAll(s))) {
987
+ const [, p = ""] = l, u = o.phraseToAction.get(p.toLowerCase());
917
988
  if (u)
918
- if (t += c.slice(l, _.index), l = _.index + _[0].length, u === "newline") t = `${t.replace(/[ \t]+$/, "")}
989
+ if (a += _.slice(c, l.index), c = l.index + l[0].length, u === "newline") a = `${a.replace(/[ \t]+$/, "")}
919
990
  `;
920
991
  else if (u === "newparagraph")
921
- t = `${t.replace(/[ \t]+$/, "")}
992
+ a = `${a.replace(/[ \t]+$/, "")}
922
993
 
923
994
  `;
924
995
  else if (u === "bullet") {
925
- const m = t.replace(/[ \t]+$/, "");
926
- t = m === "" || m.endsWith(`
996
+ const m = a.replace(/[ \t]+$/, "");
997
+ a = m === "" || m.endsWith(`
927
998
  `) ? `${m}- ` : `${m}
928
999
  - `;
929
- } else if (u === "scratch") t = Se(t);
1000
+ } else if (u === "scratch") a = xe(a);
930
1001
  else {
931
1002
  n = u === "send" ? "send" : "stop";
932
1003
  break;
933
1004
  }
934
1005
  }
935
- return n === null && (t += c.slice(l)), { text: Ce(
936
- t.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
1006
+ return n === null && (a += _.slice(c)), { text: Ee(
1007
+ a.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
937
1008
  `).replace(/\n[ \t]+/g, `
938
1009
  `).replace(/(^|\n)- +/g, "$1- ").replace(/ {2,}/g, " ").replace(/\n{3,}/g, `
939
1010
 
@@ -949,16 +1020,16 @@ class E {
949
1020
  * control command from an intermediate delta would stop or submit
950
1021
  * mid-sentence.
951
1022
  */
952
- static commandPrefixTail(e, a) {
953
- const o = M(a), r = Math.min(e.length, o.longestPhrase + 2);
954
- for (let c = r; c > 0; c--) {
955
- const s = e.length - c;
956
- if (!xe(e.slice(0, s))) continue;
957
- const t = e.slice(s).toLowerCase(), n = t.replace(/^\s+/, "");
1023
+ static commandPrefixTail(e, t) {
1024
+ const o = M(t), r = Math.min(e.length, o.longestPhrase + 2);
1025
+ for (let _ = r; _ > 0; _--) {
1026
+ const s = e.length - _;
1027
+ if (!Ae(e.slice(0, s))) continue;
1028
+ const a = e.slice(s).toLowerCase(), n = a.replace(/^\s+/, "");
958
1029
  if (n) {
959
- for (const l of Array.from(o.phraseToAction.keys()))
960
- if (l.startsWith(n))
961
- return e.slice(s + (t.length - n.length));
1030
+ for (const c of Array.from(o.phraseToAction.keys()))
1031
+ if (c.startsWith(n))
1032
+ return e.slice(s + (a.length - n.length));
962
1033
  }
963
1034
  }
964
1035
  return "";
@@ -968,12 +1039,12 @@ class E {
968
1039
  * prefix) — i.e. a silence pause would resolve it into a command. Used by
969
1040
  * the manager's silence timer.
970
1041
  */
971
- static pendingTailIsCompletePhrase(e, a) {
972
- const o = E.commandPrefixTail(e, a).trim().toLowerCase();
973
- return o ? M(a).phraseToAction.has(o) : !1;
1042
+ static pendingTailIsCompletePhrase(e, t) {
1043
+ const o = E.commandPrefixTail(e, t).trim().toLowerCase();
1044
+ return o ? M(t).phraseToAction.has(o) : !1;
974
1045
  }
975
1046
  }
976
- const qe = 55, Ee = 90;
1047
+ const Pe = 55, Te = 90;
977
1048
  class V {
978
1049
  /**
979
1050
  * Next paced step toward `processed`: normally one word per tick so text
@@ -983,28 +1054,28 @@ class V {
983
1054
  */
984
1055
  static nextDripText({
985
1056
  displayed: e,
986
- processed: a
1057
+ processed: t
987
1058
  }) {
988
- if (a.length <= e.length) return a;
989
- const o = a.length - e.length;
990
- if (o > Ee)
991
- return a.slice(0, e.length + Math.ceil(o / 3));
1059
+ if (t.length <= e.length) return t;
1060
+ const o = t.length - e.length;
1061
+ if (o > Te)
1062
+ return t.slice(0, e.length + Math.ceil(o / 3));
992
1063
  let r = e.length;
993
- for (; r < a.length && /\s/.test(a.charAt(r)); ) r++;
994
- for (; r < a.length && !/\s/.test(a.charAt(r)); ) r++;
995
- return r - e.length > 12 && (r = e.length + 6), a.slice(0, Math.max(r, e.length + 1));
1064
+ for (; r < t.length && /\s/.test(t.charAt(r)); ) r++;
1065
+ for (; r < t.length && !/\s/.test(t.charAt(r)); ) r++;
1066
+ return r - e.length > 12 && (r = e.length + 6), t.slice(0, Math.max(r, e.length + 1));
996
1067
  }
997
1068
  /** Normalize a BCP-47 browser locale into the hint OpenAI accepts. */
998
1069
  static languageHint(e) {
999
1070
  if (!e) return;
1000
- const a = e.toLowerCase();
1001
- if (/^zh-(cn|tw|hk)$/.test(a)) return a;
1002
- const o = a.split("-")[0];
1071
+ const t = e.toLowerCase();
1072
+ if (/^zh-(cn|tw|hk)$/.test(t)) return t;
1073
+ const o = t.split("-")[0];
1003
1074
  return o && /^[a-z]{2,3}$/.test(o) ? o : void 0;
1004
1075
  }
1005
1076
  }
1006
- const Ae = 2e4;
1007
- class Pe {
1077
+ const Ie = 2e4;
1078
+ class Me {
1008
1079
  constructor() {
1009
1080
  this.cached = null, this.inflight = null;
1010
1081
  }
@@ -1012,15 +1083,15 @@ class Pe {
1012
1083
  get() {
1013
1084
  if (!this.cached) return null;
1014
1085
  const e = Date.parse(this.cached.expiresAt);
1015
- return Number.isNaN(e) || e - Date.now() < Ae ? (this.cached = null, null) : this.cached;
1086
+ return Number.isNaN(e) || e - Date.now() < Ie ? (this.cached = null, null) : this.cached;
1016
1087
  }
1017
1088
  /**
1018
1089
  * Resolve a mint, deduping concurrent requests (hover-prewarm racing a
1019
1090
  * click reuses the same in-flight promise instead of double-minting).
1020
1091
  */
1021
1092
  async resolve(e) {
1022
- const a = this.get();
1023
- return a || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
1093
+ const t = this.get();
1094
+ return t || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
1024
1095
  this.inflight = null;
1025
1096
  })), this.inflight);
1026
1097
  }
@@ -1032,7 +1103,7 @@ class Pe {
1032
1103
  function H(i) {
1033
1104
  return typeof i == "object" && i !== null && !Array.isArray(i);
1034
1105
  }
1035
- function Te(i) {
1106
+ function De(i) {
1036
1107
  if (!H(i) || typeof i.type != "string") return null;
1037
1108
  const e = H(i.error) ? i.error : null;
1038
1109
  return {
@@ -1041,43 +1112,43 @@ function Te(i) {
1041
1112
  errorMessage: e && typeof e.message == "string" ? e.message : void 0
1042
1113
  };
1043
1114
  }
1044
- const Ie = "https://api.openai.com/v1/realtime/calls", Me = 600 * 1e3, De = 15e3, Ne = 5e3;
1115
+ const Re = "https://api.openai.com/v1/realtime/calls", Ne = 600 * 1e3, Ke = 15e3, Le = 5e3;
1045
1116
  class T extends Error {
1046
1117
  }
1047
- class Re {
1118
+ class Oe {
1048
1119
  constructor({
1049
1120
  mintToken: e,
1050
- onDelta: a,
1121
+ onDelta: t,
1051
1122
  onState: o,
1052
1123
  onError: r,
1053
- onLevel: c
1124
+ onLevel: _
1054
1125
  }) {
1055
- 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 = o, this.onError = r, this.onLevel = c;
1126
+ 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 = t, this.onState = o, this.onError = r, this.onLevel = _;
1056
1127
  }
1057
1128
  async start() {
1058
1129
  if (this.state === "idle") {
1059
1130
  this.setState("connecting"), this.timers.push(
1060
1131
  setTimeout(() => {
1061
1132
  this.state === "connecting" && this.fail("unavailable");
1062
- }, De)
1063
- ), this.timers.push(setTimeout(() => this.stop(), Me));
1133
+ }, Ke)
1134
+ ), this.timers.push(setTimeout(() => this.stop(), Ne));
1064
1135
  try {
1065
1136
  const e = this.requestMicrophone();
1066
1137
  e.then((d) => {
1067
- this.isTornDown() || this.stream && this.stream !== d ? d.getTracks().forEach((_) => _.stop()) : this.stream = d;
1138
+ this.isTornDown() || this.stream && this.stream !== d ? d.getTracks().forEach((l) => l.stop()) : this.stream = d;
1068
1139
  }).catch(() => {
1069
1140
  });
1070
- const [a, o] = await Promise.all([e, this.mintToken()]);
1141
+ const [t, o] = await Promise.all([e, this.mintToken()]);
1071
1142
  if (this.isTornDown()) {
1072
- a.getTracks().forEach((d) => d.stop());
1143
+ t.getTracks().forEach((d) => d.stop());
1073
1144
  return;
1074
1145
  }
1075
- this.stream = a, this.startLevelMeter(a);
1146
+ this.stream = t, this.startLevelMeter(t);
1076
1147
  const r = new RTCPeerConnection();
1077
1148
  this.pc = r;
1078
- const [c] = a.getAudioTracks();
1079
- if (!c) throw new T("No audio track");
1080
- r.addTrack(c, a);
1149
+ const [_] = t.getAudioTracks();
1150
+ if (!_) throw new T("No audio track");
1151
+ r.addTrack(_, t);
1081
1152
  const s = r.createDataChannel("oai-events");
1082
1153
  this.dc = s, s.addEventListener(
1083
1154
  "message",
@@ -1092,24 +1163,24 @@ class Re {
1092
1163
  r.connectionState === "disconnected" && this.timers.push(
1093
1164
  setTimeout(() => {
1094
1165
  this.pc === r && r.connectionState !== "connected" && this.fail("unavailable");
1095
- }, Ne)
1166
+ }, Le)
1096
1167
  );
1097
1168
  });
1098
- const t = await r.createOffer();
1099
- if (this.isTornDown() || (await r.setLocalDescription(t), this.isTornDown())) return;
1100
- const n = await fetch(Ie, {
1169
+ const a = await r.createOffer();
1170
+ if (this.isTornDown() || (await r.setLocalDescription(a), this.isTornDown())) return;
1171
+ const n = await fetch(Re, {
1101
1172
  method: "POST",
1102
1173
  headers: {
1103
1174
  Authorization: `Bearer ${o.token}`,
1104
1175
  "Content-Type": "application/sdp"
1105
1176
  },
1106
- body: t.sdp
1177
+ body: a.sdp
1107
1178
  });
1108
1179
  if (!n.ok)
1109
1180
  throw new Error(`Realtime handshake failed (${n.status})`);
1110
- const l = await n.text();
1181
+ const c = await n.text();
1111
1182
  if (this.isTornDown()) return;
1112
- await r.setRemoteDescription({ type: "answer", sdp: l });
1183
+ await r.setRemoteDescription({ type: "answer", sdp: c });
1113
1184
  } catch (e) {
1114
1185
  e instanceof T ? this.fail("microphone") : (k.error("dictation session failed to start", {
1115
1186
  _e: e instanceof Error ? e.message : String(e)
@@ -1132,32 +1203,32 @@ class Re {
1132
1203
  autoGainControl: !0
1133
1204
  }
1134
1205
  });
1135
- } catch (a) {
1206
+ } catch (t) {
1136
1207
  throw new T(
1137
- a instanceof DOMException ? a.name : "Could not access the microphone"
1208
+ t instanceof DOMException ? t.name : "Could not access the microphone"
1138
1209
  );
1139
1210
  }
1140
1211
  }
1141
1212
  handleServerEvent(e) {
1142
1213
  if (typeof e != "string") return;
1143
- let a;
1214
+ let t;
1144
1215
  try {
1145
- a = JSON.parse(e);
1216
+ t = JSON.parse(e);
1146
1217
  } catch {
1147
1218
  this.loggedParseFailure || (this.loggedParseFailure = !0, k.error("dictation server event was not valid JSON", {
1148
1219
  snippet: e.slice(0, 120)
1149
1220
  }));
1150
1221
  return;
1151
1222
  }
1152
- const o = Te(a);
1223
+ const o = De(t);
1153
1224
  if (!o) return;
1154
- const { type: r, delta: c } = o;
1225
+ const { type: r, delta: _ } = o;
1155
1226
  if (r === "session.created" || r === "transcription_session.created") {
1156
1227
  this.setState("listening");
1157
1228
  return;
1158
1229
  }
1159
- if (r === "conversation.item.input_audio_transcription.delta" && c) {
1160
- this.state === "connecting" && this.setState("listening"), this.onDelta(c);
1230
+ if (r === "conversation.item.input_audio_transcription.delta" && _) {
1231
+ this.state === "connecting" && this.setState("listening"), this.onDelta(_);
1161
1232
  return;
1162
1233
  }
1163
1234
  r === "error" && (k.error("dictation server event error", {
@@ -1167,25 +1238,25 @@ class Re {
1167
1238
  startLevelMeter(e) {
1168
1239
  if (this.onLevel)
1169
1240
  try {
1170
- const a = new AudioContext();
1171
- this.audioContext = a;
1172
- const o = a.createMediaStreamSource(e), r = a.createAnalyser();
1241
+ const t = new AudioContext();
1242
+ this.audioContext = t;
1243
+ const o = t.createMediaStreamSource(e), r = t.createAnalyser();
1173
1244
  r.fftSize = 512, o.connect(r);
1174
- const c = new Uint8Array(r.frequencyBinCount), s = () => {
1175
- var l;
1176
- r.getByteTimeDomainData(c);
1177
- let t = 0;
1178
- for (let d = 0; d < c.length; d++) {
1179
- const _ = ((c[d] ?? 128) - 128) / 128;
1180
- t += _ * _;
1245
+ const _ = new Uint8Array(r.frequencyBinCount), s = () => {
1246
+ var c;
1247
+ r.getByteTimeDomainData(_);
1248
+ let a = 0;
1249
+ for (let d = 0; d < _.length; d++) {
1250
+ const l = ((_[d] ?? 128) - 128) / 128;
1251
+ a += l * l;
1181
1252
  }
1182
- const n = Math.sqrt(t / c.length);
1183
- (l = this.onLevel) == null || l.call(this, Math.min(1, n * 4)), this.levelRaf = requestAnimationFrame(s);
1253
+ const n = Math.sqrt(a / _.length);
1254
+ (c = this.onLevel) == null || c.call(this, Math.min(1, n * 4)), this.levelRaf = requestAnimationFrame(s);
1184
1255
  };
1185
1256
  this.levelRaf = requestAnimationFrame(s);
1186
- } catch (a) {
1257
+ } catch (t) {
1187
1258
  k.error("dictation level meter unavailable", {
1188
- _e: a instanceof Error ? a.message : String(a)
1259
+ _e: t instanceof Error ? t.message : String(t)
1189
1260
  });
1190
1261
  }
1191
1262
  }
@@ -1196,10 +1267,10 @@ class Re {
1196
1267
  this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(e));
1197
1268
  }
1198
1269
  teardown() {
1199
- var e, a, o, r;
1200
- this.timers.forEach((c) => clearTimeout(c)), 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, (o = this.stream) == null || o.getTracks().forEach((c) => c.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((c) => {
1270
+ var e, t, o, r;
1271
+ this.timers.forEach((_) => clearTimeout(_)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (t = this.pc) == null || t.close(), this.pc = null, (o = this.stream) == null || o.getTracks().forEach((_) => _.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((_) => {
1201
1272
  k.error("failed to close dictation audio context", {
1202
- _e: String(c)
1273
+ _e: String(_)
1203
1274
  });
1204
1275
  }), this.audioContext = null;
1205
1276
  }
@@ -1207,10 +1278,10 @@ class Re {
1207
1278
  this.state !== e && (this.state = e, this.onState(e));
1208
1279
  }
1209
1280
  }
1210
- const Ke = 1300, Le = { status: "idle", error: null };
1211
- class Oe {
1212
- constructor({ api: e, config: a }) {
1213
- this.state = new S(Le), this.levelRef = { current: 0 }, this.mintCache = new Pe(), 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 = () => {
1281
+ const Fe = 1300, Ue = { status: "idle", error: null };
1282
+ class Be {
1283
+ constructor({ api: e, config: t }) {
1284
+ this.state = new S(Ue), this.levelRef = { current: 0 }, this.mintCache = new Me(), 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 = () => {
1214
1285
  this.mintToken().catch((o) => {
1215
1286
  this.mintCache.clear(), k.error("dictation token prewarm failed", {
1216
1287
  _e: o instanceof Error ? o.message : String(o)
@@ -1220,24 +1291,24 @@ class Oe {
1220
1291
  this.session && this.teardown(), this.target = o, this.language = V.languageHint(
1221
1292
  this.config.language ?? navigator.language
1222
1293
  ), this.prefix = o.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1223
- const r = new Re({
1294
+ const r = new Oe({
1224
1295
  mintToken: this.mintToken,
1225
- onLevel: (c) => {
1226
- this.levelRef.current = c;
1296
+ onLevel: (_) => {
1297
+ this.levelRef.current = _;
1227
1298
  },
1228
- onState: (c) => {
1229
- r === this.session && (c === "connecting" && this.state.set({ status: "connecting", error: null }), c === "listening" && this.state.set({ status: "listening", error: null }), c === "stopped" && this.teardown());
1299
+ onState: (_) => {
1300
+ r === this.session && (_ === "connecting" && this.state.set({ status: "connecting", error: null }), _ === "listening" && this.state.set({ status: "listening", error: null }), _ === "stopped" && this.teardown());
1230
1301
  },
1231
- onError: (c) => {
1232
- r === this.session && (this.mintCache.clear(), this.teardown({ error: c, executeFinalCommand: !1 }));
1302
+ onError: (_) => {
1303
+ r === this.session && (this.mintCache.clear(), this.teardown({ error: _, executeFinalCommand: !1 }));
1233
1304
  },
1234
- onDelta: (c) => {
1305
+ onDelta: (_) => {
1235
1306
  if (r !== this.session || !this.target) return;
1236
1307
  if (!this.isConsistent()) {
1237
1308
  this.teardown();
1238
1309
  return;
1239
1310
  }
1240
- this.raw += c;
1311
+ this.raw += _;
1241
1312
  const s = this.ingest();
1242
1313
  if (s === "stop") {
1243
1314
  this.teardown();
@@ -1253,9 +1324,9 @@ class Oe {
1253
1324
  ) && (this.silenceTimer = setTimeout(() => {
1254
1325
  if (r !== this.session) return;
1255
1326
  this.raw = `${this.raw}.`;
1256
- const t = this.ingest();
1257
- t === "stop" ? this.teardown() : t === "send" && this.teardown({ send: !0 });
1258
- }, Ke));
1327
+ const a = this.ingest();
1328
+ a === "stop" ? this.teardown() : a === "send" && this.teardown({ send: !0 });
1329
+ }, Fe));
1259
1330
  }
1260
1331
  });
1261
1332
  this.session = r, this.state.set({ status: "connecting", error: null }), this.dripTimer = setInterval(() => {
@@ -1271,12 +1342,12 @@ class Oe {
1271
1342
  })
1272
1343
  );
1273
1344
  }
1274
- }, qe), r.start();
1345
+ }, Pe), r.start();
1275
1346
  }, this.stop = (o) => {
1276
1347
  this.session && this.teardown(o);
1277
1348
  }, this.mintToken = async () => this.mintCache.resolve(
1278
1349
  () => this.api.createDictationSession({ language: this.language })
1279
- ), this.api = e, this.config = a;
1350
+ ), this.api = e, this.config = t;
1280
1351
  }
1281
1352
  /** Applied text = prefix + dictated. A mismatch means the visitor edited. */
1282
1353
  isConsistent() {
@@ -1288,28 +1359,28 @@ class Oe {
1288
1359
  /** Process the transcript and apply the outcome. Shared by the delta path,
1289
1360
  * the silence timer, and (with `final`) teardown. Returns the control. */
1290
1361
  ingest(e) {
1291
- const a = E.process(this.raw, {
1362
+ const t = E.process(this.raw, {
1292
1363
  language: this.language,
1293
1364
  final: e == null ? void 0 : e.final
1294
1365
  });
1295
- return this.processed = a.text, a.text.startsWith(this.displayed) || this.applyDisplayed(a.text), a.control;
1366
+ return this.processed = t.text, t.text.startsWith(this.displayed) || this.applyDisplayed(t.text), t.control;
1296
1367
  }
1297
1368
  stopSilenceTimer() {
1298
1369
  this.silenceTimer && clearTimeout(this.silenceTimer), this.silenceTimer = null;
1299
1370
  }
1300
1371
  teardown(e) {
1301
- var c;
1302
- const a = this.session, o = this.target;
1372
+ var _;
1373
+ const t = this.session, o = this.target;
1303
1374
  this.dripTimer && clearInterval(this.dripTimer), this.dripTimer = null, this.stopSilenceTimer();
1304
1375
  let r = (e == null ? void 0 : e.send) ?? !1;
1305
1376
  if (o && this.isConsistent()) {
1306
1377
  const s = this.ingest({ final: !0 });
1307
1378
  (e == null ? void 0 : e.executeFinalCommand) !== !1 && s === "send" && (r = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1308
1379
  }
1309
- 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 }), r && ((c = o == null ? void 0 : o.onSend) == null || c.call(o));
1380
+ this.session = null, this.target = null, t == null || t.stop(), this.levelRef.current = 0, this.state.set({ status: "idle", error: (e == null ? void 0 : e.error) ?? null }), r && ((_ = o == null ? void 0 : o.onSend) == null || _.call(o));
1310
1381
  }
1311
1382
  }
1312
- const Fe = {
1383
+ const Ve = {
1313
1384
  write_a_message_placeholder: "اكتب رسالة...",
1314
1385
  your_issue_has_been_resolved: "تم حل مشكلتك!",
1315
1386
  new_conversation: "محادثة جديدة",
@@ -1346,6 +1417,7 @@ const Fe = {
1346
1417
  companion_active_chats: "{count} جلسات نشطة",
1347
1418
  companion_other_sessions: "الجلسات المفتوحة الأخرى: {count}",
1348
1419
  companion_working_chats: "{count} قيد العمل",
1420
+ unread_sessions: "{count} غير مقروءة",
1349
1421
  companion_history: "سجل المحادثات",
1350
1422
  companion_expand_chat: "توسيع المحادثة",
1351
1423
  companion_sidebar_dock_label: "الإرساء",
@@ -1418,7 +1490,7 @@ const Fe = {
1418
1490
  zoom_out: "تصغير",
1419
1491
  reset_zoom: "إعادة تعيين التكبير",
1420
1492
  support_chat_aria_label: "دردشة الدعم"
1421
- }, Ue = {
1493
+ }, He = {
1422
1494
  write_a_message_placeholder: "একটি বার্তা লিখুন...",
1423
1495
  your_issue_has_been_resolved: "আপনার সমস্যা সমাধান হয়েছে!",
1424
1496
  new_conversation: "নতুন কথোপকথন",
@@ -1515,7 +1587,7 @@ const Fe = {
1515
1587
  zoom_out: "ছোট করুন",
1516
1588
  reset_zoom: "জুম রিসেট করুন",
1517
1589
  support_chat_aria_label: "সাপোর্ট চ্যাট"
1518
- }, Be = {
1590
+ }, Ge = {
1519
1591
  write_a_message_placeholder: "Напишете съобщение...",
1520
1592
  your_issue_has_been_resolved: "Вашият проблем е разрешен!",
1521
1593
  new_conversation: "Нов разговор",
@@ -1612,7 +1684,7 @@ const Fe = {
1612
1684
  zoom_out: "Намаляване",
1613
1685
  reset_zoom: "Нулиране на мащаба",
1614
1686
  support_chat_aria_label: "Чат за поддръжка"
1615
- }, Ve = {
1687
+ }, Ze = {
1616
1688
  write_a_message_placeholder: "Napište zprávu...",
1617
1689
  your_issue_has_been_resolved: "Váš problém byl vyřešen!",
1618
1690
  new_conversation: "Nová konverzace",
@@ -1709,7 +1781,7 @@ const Fe = {
1709
1781
  zoom_out: "Oddálit",
1710
1782
  reset_zoom: "Obnovit přiblížení",
1711
1783
  support_chat_aria_label: "Chat podpory"
1712
- }, He = {
1784
+ }, We = {
1713
1785
  write_a_message_placeholder: "Skriv en besked...",
1714
1786
  your_issue_has_been_resolved: "Dit problem er løst!",
1715
1787
  new_conversation: "Ny samtale",
@@ -1806,7 +1878,7 @@ const Fe = {
1806
1878
  zoom_out: "Zoom ud",
1807
1879
  reset_zoom: "Nulstil zoom",
1808
1880
  support_chat_aria_label: "Supportchat"
1809
- }, Ge = {
1881
+ }, $e = {
1810
1882
  write_a_message_placeholder: "Γράψτε ένα μήνυμα...",
1811
1883
  your_issue_has_been_resolved: "Το πρόβλημά σας επιλύθηκε!",
1812
1884
  new_conversation: "Νέα συνομιλία",
@@ -1903,7 +1975,7 @@ const Fe = {
1903
1975
  zoom_out: "Σμίκρυνση",
1904
1976
  reset_zoom: "Επαναφορά ζουμ",
1905
1977
  support_chat_aria_label: "Συνομιλία υποστήριξης"
1906
- }, Ze = {
1978
+ }, Je = {
1907
1979
  write_a_message_placeholder: "Nachricht schreiben...",
1908
1980
  your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
1909
1981
  new_conversation: "Neue Konversation",
@@ -2037,6 +2109,7 @@ const Fe = {
2037
2109
  companion_active_chats: "{count} active sessions",
2038
2110
  companion_other_sessions: "Other open sessions: {count}",
2039
2111
  companion_working_chats: "{count} working",
2112
+ unread_sessions: "{count} unread",
2040
2113
  companion_history: "Conversation history",
2041
2114
  companion_expand_chat: "Expand chat",
2042
2115
  companion_sidebar_dock_label: "Dock",
@@ -2109,7 +2182,7 @@ const Fe = {
2109
2182
  zoom_out: "Zoom out",
2110
2183
  reset_zoom: "Reset zoom",
2111
2184
  support_chat_aria_label: "Support chat"
2112
- }, We = {
2185
+ }, Ye = {
2113
2186
  write_a_message_placeholder: "Escribe un mensaje...",
2114
2187
  your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
2115
2188
  new_conversation: "Nueva conversación",
@@ -2206,7 +2279,7 @@ const Fe = {
2206
2279
  zoom_out: "Alejar",
2207
2280
  reset_zoom: "Restablecer zoom",
2208
2281
  support_chat_aria_label: "Chat de soporte"
2209
- }, $e = {
2282
+ }, Xe = {
2210
2283
  write_a_message_placeholder: "Magsulat ng mensahe...",
2211
2284
  your_issue_has_been_resolved: "Nalutas na ang iyong isyu!",
2212
2285
  new_conversation: "Bagong usapan",
@@ -2303,7 +2376,7 @@ const Fe = {
2303
2376
  zoom_out: "Paliitin",
2304
2377
  reset_zoom: "I-reset ang zoom",
2305
2378
  support_chat_aria_label: "Chat ng suporta"
2306
- }, Je = {
2379
+ }, Qe = {
2307
2380
  write_a_message_placeholder: "Kirjoita viesti...",
2308
2381
  your_issue_has_been_resolved: "Ongelmasi on ratkaistu!",
2309
2382
  new_conversation: "Uusi keskustelu",
@@ -2400,7 +2473,7 @@ const Fe = {
2400
2473
  zoom_out: "Loitonna",
2401
2474
  reset_zoom: "Palauta zoomaus",
2402
2475
  support_chat_aria_label: "Tukichat"
2403
- }, Ye = {
2476
+ }, ea = {
2404
2477
  write_a_message_placeholder: "Écrivez un message...",
2405
2478
  your_issue_has_been_resolved: "Votre problème a été résolu !",
2406
2479
  new_conversation: "Nouvelle conversation",
@@ -2497,7 +2570,7 @@ const Fe = {
2497
2570
  zoom_out: "Zoom arrière",
2498
2571
  reset_zoom: "Réinitialiser le zoom",
2499
2572
  support_chat_aria_label: "Chat de support"
2500
- }, Xe = {
2573
+ }, aa = {
2501
2574
  write_a_message_placeholder: "एक संदेश लिखें...",
2502
2575
  your_issue_has_been_resolved: "आपकी समस्या हल हो गई है!",
2503
2576
  new_conversation: "नई बातचीत",
@@ -2594,7 +2667,7 @@ const Fe = {
2594
2667
  zoom_out: "ज़ूम आउट",
2595
2668
  reset_zoom: "ज़ूम रीसेट करें",
2596
2669
  support_chat_aria_label: "सहायता चैट"
2597
- }, Qe = {
2670
+ }, ta = {
2598
2671
  write_a_message_placeholder: "Scrivi un messaggio...",
2599
2672
  your_issue_has_been_resolved: "Il tuo problema è stato risolto!",
2600
2673
  new_conversation: "Nuova conversazione",
@@ -2691,7 +2764,7 @@ const Fe = {
2691
2764
  zoom_out: "Riduci",
2692
2765
  reset_zoom: "Reimposta zoom",
2693
2766
  support_chat_aria_label: "Chat di supporto"
2694
- }, ea = {
2767
+ }, sa = {
2695
2768
  write_a_message_placeholder: "メッセージを入力...",
2696
2769
  your_issue_has_been_resolved: "問題が解決しました!",
2697
2770
  new_conversation: "新しい会話",
@@ -2788,7 +2861,7 @@ const Fe = {
2788
2861
  zoom_out: "縮小",
2789
2862
  reset_zoom: "ズームをリセット",
2790
2863
  support_chat_aria_label: "サポートチャット"
2791
- }, aa = {
2864
+ }, oa = {
2792
2865
  write_a_message_placeholder: "메시지를 입력하세요...",
2793
2866
  your_issue_has_been_resolved: "문제가 해결되었습니다!",
2794
2867
  new_conversation: "새 대화",
@@ -2885,7 +2958,7 @@ const Fe = {
2885
2958
  zoom_out: "축소",
2886
2959
  reset_zoom: "확대/축소 초기화",
2887
2960
  support_chat_aria_label: "고객 지원 채팅"
2888
- }, ta = {
2961
+ }, na = {
2889
2962
  write_a_message_placeholder: "Schrijf een bericht...",
2890
2963
  your_issue_has_been_resolved: "Uw probleem is opgelost!",
2891
2964
  new_conversation: "Nieuw gesprek",
@@ -2982,7 +3055,7 @@ const Fe = {
2982
3055
  zoom_out: "Uitzoomen",
2983
3056
  reset_zoom: "Zoom herstellen",
2984
3057
  support_chat_aria_label: "Supportchat"
2985
- }, sa = {
3058
+ }, ia = {
2986
3059
  write_a_message_placeholder: "Skriv en melding...",
2987
3060
  your_issue_has_been_resolved: "Problemet ditt er løst!",
2988
3061
  new_conversation: "Ny samtale",
@@ -3079,7 +3152,7 @@ const Fe = {
3079
3152
  zoom_out: "Zoom ut",
3080
3153
  reset_zoom: "Tilbakestill zoom",
3081
3154
  support_chat_aria_label: "Support-chat"
3082
- }, oa = {
3155
+ }, ra = {
3083
3156
  write_a_message_placeholder: "Napisz wiadomość...",
3084
3157
  your_issue_has_been_resolved: "Twój problem został rozwiązany!",
3085
3158
  new_conversation: "Nowa rozmowa",
@@ -3176,7 +3249,7 @@ const Fe = {
3176
3249
  zoom_out: "Pomniejsz",
3177
3250
  reset_zoom: "Resetuj powiększenie",
3178
3251
  support_chat_aria_label: "Czat pomocy"
3179
- }, na = {
3252
+ }, _a = {
3180
3253
  write_a_message_placeholder: "Escreva uma mensagem...",
3181
3254
  your_issue_has_been_resolved: "Seu problema foi resolvido!",
3182
3255
  new_conversation: "Nova conversa",
@@ -3273,7 +3346,7 @@ const Fe = {
3273
3346
  zoom_out: "Reduzir",
3274
3347
  reset_zoom: "Redefinir zoom",
3275
3348
  support_chat_aria_label: "Chat de suporte"
3276
- }, ia = {
3349
+ }, la = {
3277
3350
  write_a_message_placeholder: "Scrie un mesaj...",
3278
3351
  your_issue_has_been_resolved: "Problema ta a fost rezolvată!",
3279
3352
  new_conversation: "Conversație nouă",
@@ -3370,7 +3443,7 @@ const Fe = {
3370
3443
  zoom_out: "Micșorează",
3371
3444
  reset_zoom: "Resetează zoomul",
3372
3445
  support_chat_aria_label: "Chat de asistență"
3373
- }, ra = {
3446
+ }, ca = {
3374
3447
  write_a_message_placeholder: "Skriv ett meddelande...",
3375
3448
  your_issue_has_been_resolved: "Ditt problem har lösts!",
3376
3449
  new_conversation: "Ny konversation",
@@ -3467,7 +3540,7 @@ const Fe = {
3467
3540
  zoom_out: "Zooma ut",
3468
3541
  reset_zoom: "Återställ zoom",
3469
3542
  support_chat_aria_label: "Supportchatt"
3470
- }, _a = {
3543
+ }, pa = {
3471
3544
  write_a_message_placeholder: "Напишите сообщение...",
3472
3545
  your_issue_has_been_resolved: "Ваша проблема решена!",
3473
3546
  new_conversation: "Новый разговор",
@@ -3564,7 +3637,7 @@ const Fe = {
3564
3637
  zoom_out: "Уменьшить",
3565
3638
  reset_zoom: "Сбросить масштаб",
3566
3639
  support_chat_aria_label: "Чат поддержки"
3567
- }, la = {
3640
+ }, da = {
3568
3641
  write_a_message_placeholder: "เขียนข้อความ...",
3569
3642
  your_issue_has_been_resolved: "ปัญหาของคุณได้รับการแก้ไขแล้ว!",
3570
3643
  new_conversation: "การสนทนาใหม่",
@@ -3661,7 +3734,7 @@ const Fe = {
3661
3734
  zoom_out: "ย่อ",
3662
3735
  reset_zoom: "รีเซ็ตการซูม",
3663
3736
  support_chat_aria_label: "แชทฝ่ายสนับสนุน"
3664
- }, ca = {
3737
+ }, ua = {
3665
3738
  write_a_message_placeholder: "Bir mesaj yazın...",
3666
3739
  your_issue_has_been_resolved: "Sorununuz çözüldü!",
3667
3740
  new_conversation: "Yeni konuşma",
@@ -3758,7 +3831,7 @@ const Fe = {
3758
3831
  zoom_out: "Uzaklaştır",
3759
3832
  reset_zoom: "Yakınlaştırmayı sıfırla",
3760
3833
  support_chat_aria_label: "Destek sohbeti"
3761
- }, pa = {
3834
+ }, ma = {
3762
3835
  write_a_message_placeholder: "پیغام لکھیں...",
3763
3836
  your_issue_has_been_resolved: "آپ کا مسئلہ حل ہو گیا ہے!",
3764
3837
  new_conversation: "نئی گفتگو",
@@ -3855,7 +3928,7 @@ const Fe = {
3855
3928
  zoom_out: "زوم آؤٹ",
3856
3929
  reset_zoom: "زوم دوبارہ ترتیب دیں",
3857
3930
  support_chat_aria_label: "سپورٹ چیٹ"
3858
- }, da = {
3931
+ }, ha = {
3859
3932
  write_a_message_placeholder: "Viết tin nhắn...",
3860
3933
  your_issue_has_been_resolved: "Vấn đề của bạn đã được giải quyết!",
3861
3934
  new_conversation: "Cuộc trò chuyện mới",
@@ -3952,7 +4025,7 @@ const Fe = {
3952
4025
  zoom_out: "Thu nhỏ",
3953
4026
  reset_zoom: "Đặt lại thu phóng",
3954
4027
  support_chat_aria_label: "Trò chuyện hỗ trợ"
3955
- }, ua = {
4028
+ }, ga = {
3956
4029
  write_a_message_placeholder: "写一条消息...",
3957
4030
  your_issue_has_been_resolved: "您的问题已解决!",
3958
4031
  new_conversation: "新对话",
@@ -4049,7 +4122,7 @@ const Fe = {
4049
4122
  zoom_out: "缩小",
4050
4123
  reset_zoom: "重置缩放",
4051
4124
  support_chat_aria_label: "支持对话"
4052
- }, ma = {
4125
+ }, ka = {
4053
4126
  write_a_message_placeholder: "Napišite poruku...",
4054
4127
  your_issue_has_been_resolved: "Vaš problem je riješen!",
4055
4128
  new_conversation: "Novi razgovor",
@@ -4146,7 +4219,7 @@ const Fe = {
4146
4219
  zoom_out: "Udalji",
4147
4220
  reset_zoom: "Poništi zumiranje",
4148
4221
  support_chat_aria_label: "Chat za podršku"
4149
- }, ha = {
4222
+ }, ba = {
4150
4223
  write_a_message_placeholder: "Kirjuta sõnum...",
4151
4224
  your_issue_has_been_resolved: "Teie probleem on lahendatud!",
4152
4225
  new_conversation: "Uus vestlus",
@@ -4243,7 +4316,7 @@ const Fe = {
4243
4316
  zoom_out: "Vähenda",
4244
4317
  reset_zoom: "Lähtesta suurendus",
4245
4318
  support_chat_aria_label: "Tugivestlus"
4246
- }, ga = {
4319
+ }, va = {
4247
4320
  write_a_message_placeholder: "Írjon üzenetet...",
4248
4321
  your_issue_has_been_resolved: "A problémája megoldódott!",
4249
4322
  new_conversation: "Új beszélgetés",
@@ -4340,7 +4413,7 @@ const Fe = {
4340
4413
  zoom_out: "Kicsinyítés",
4341
4414
  reset_zoom: "Nagyítás visszaállítása",
4342
4415
  support_chat_aria_label: "Ügyfélszolgálati chat"
4343
- }, ka = {
4416
+ }, fa = {
4344
4417
  write_a_message_placeholder: "Skrifaðu skilaboð...",
4345
4418
  your_issue_has_been_resolved: "Málið þitt hefur verið leyst!",
4346
4419
  new_conversation: "Nýtt samtal",
@@ -4437,7 +4510,7 @@ const Fe = {
4437
4510
  zoom_out: "Minnka aðdrátt",
4438
4511
  reset_zoom: "Endurstilla aðdrátt",
4439
4512
  support_chat_aria_label: "Þjónustuspjall"
4440
- }, ba = {
4513
+ }, ya = {
4441
4514
  write_a_message_placeholder: "Rakstiet ziņojumu...",
4442
4515
  your_issue_has_been_resolved: "Jūsu problēma ir atrisināta!",
4443
4516
  new_conversation: "Jauna saruna",
@@ -4534,7 +4607,7 @@ const Fe = {
4534
4607
  zoom_out: "Attālināt",
4535
4608
  reset_zoom: "Atiestatīt tālummaiņu",
4536
4609
  support_chat_aria_label: "Atbalsta tērzēšana"
4537
- }, va = {
4610
+ }, wa = {
4538
4611
  write_a_message_placeholder: "Parašykite žinutę...",
4539
4612
  your_issue_has_been_resolved: "Jūsų problema išspręsta!",
4540
4613
  new_conversation: "Naujas pokalbis",
@@ -4631,7 +4704,7 @@ const Fe = {
4631
4704
  zoom_out: "Nutolinti",
4632
4705
  reset_zoom: "Atstatyti mastelį",
4633
4706
  support_chat_aria_label: "Pagalbos pokalbis"
4634
- }, fa = {
4707
+ }, ja = {
4635
4708
  write_a_message_placeholder: "Schreift eng Noriicht...",
4636
4709
  your_issue_has_been_resolved: "Äert Problem gouf geléist!",
4637
4710
  new_conversation: "Nei Konversatioun",
@@ -4728,7 +4801,7 @@ const Fe = {
4728
4801
  zoom_out: "Erauszoomen",
4729
4802
  reset_zoom: "Zoom zrécksetzen",
4730
4803
  support_chat_aria_label: "Support-Chat"
4731
- }, ya = {
4804
+ }, Sa = {
4732
4805
  write_a_message_placeholder: "Ikteb messaġġ...",
4733
4806
  your_issue_has_been_resolved: "Il-problema tiegħek ġiet riżolta!",
4734
4807
  new_conversation: "Konversazzjoni ġdida",
@@ -4825,7 +4898,7 @@ const Fe = {
4825
4898
  zoom_out: "Ċekken",
4826
4899
  reset_zoom: "Irrisettja ż-zoom",
4827
4900
  support_chat_aria_label: "Chat ta’ appoġġ"
4828
- }, wa = {
4901
+ }, za = {
4829
4902
  write_a_message_placeholder: "Skriv en melding...",
4830
4903
  your_issue_has_been_resolved: "Saken din er løst!",
4831
4904
  new_conversation: "Ny samtale",
@@ -4922,7 +4995,7 @@ const Fe = {
4922
4995
  zoom_out: "Zoom ut",
4923
4996
  reset_zoom: "Tilbakestill zoom",
4924
4997
  support_chat_aria_label: "Support-chat"
4925
- }, ja = {
4998
+ }, Ca = {
4926
4999
  write_a_message_placeholder: "Napíšte správu...",
4927
5000
  your_issue_has_been_resolved: "Váš problém bol vyriešený!",
4928
5001
  new_conversation: "Nová konverzácia",
@@ -5020,78 +5093,78 @@ const Fe = {
5020
5093
  reset_zoom: "Obnoviť priblíženie",
5021
5094
  support_chat_aria_label: "Chat podpory"
5022
5095
  }, Y = {
5023
- ar: Fe,
5024
- bn: Ue,
5025
- bg: Be,
5026
- cs: Ve,
5027
- da: He,
5028
- de: Ze,
5029
- el: Ge,
5096
+ ar: Ve,
5097
+ bn: He,
5098
+ bg: Ge,
5099
+ cs: Ze,
5100
+ da: We,
5101
+ de: Je,
5102
+ el: $e,
5030
5103
  en: J,
5031
- es: We,
5032
- et: ha,
5033
- fi: Je,
5034
- fil: $e,
5035
- fr: Ye,
5036
- hi: Xe,
5037
- hr: ma,
5038
- hu: ga,
5039
- is: ka,
5040
- it: Qe,
5041
- ja: ea,
5042
- ko: aa,
5043
- lb: fa,
5044
- lt: va,
5045
- lv: ba,
5046
- mt: ya,
5047
- nb: wa,
5048
- nl: ta,
5049
- no: sa,
5050
- pl: oa,
5051
- pt: na,
5052
- ro: ia,
5053
- ru: _a,
5054
- sk: ja,
5055
- sv: ra,
5056
- th: la,
5057
- tr: ca,
5058
- ur: pa,
5059
- vi: da,
5060
- "zh-cn": ua
5061
- }, Sa = Object.keys(Y);
5062
- function za(i) {
5063
- return Sa.includes(i);
5104
+ es: Ye,
5105
+ et: ba,
5106
+ fi: Qe,
5107
+ fil: Xe,
5108
+ fr: ea,
5109
+ hi: aa,
5110
+ hr: ka,
5111
+ hu: va,
5112
+ is: fa,
5113
+ it: ta,
5114
+ ja: sa,
5115
+ ko: oa,
5116
+ lb: ja,
5117
+ lt: wa,
5118
+ lv: ya,
5119
+ mt: Sa,
5120
+ nb: za,
5121
+ nl: na,
5122
+ no: ia,
5123
+ pl: ra,
5124
+ pt: _a,
5125
+ ro: la,
5126
+ ru: pa,
5127
+ sk: Ca,
5128
+ sv: ca,
5129
+ th: da,
5130
+ tr: ua,
5131
+ ur: ma,
5132
+ vi: ha,
5133
+ "zh-cn": ga
5134
+ }, xa = Object.keys(Y);
5135
+ function qa(i) {
5136
+ return xa.includes(i);
5064
5137
  }
5065
- const Ca = /* @__PURE__ */ new Set(["ar", "ur"]);
5066
- function Ja(i) {
5067
- return Ca.has(i);
5138
+ const Ea = /* @__PURE__ */ new Set(["ar", "ur"]);
5139
+ function Qa(i) {
5140
+ return Ea.has(i);
5068
5141
  }
5069
- function xa(i) {
5070
- return za(i) ? i : "en";
5142
+ function Aa(i) {
5143
+ return qa(i) ? i : "en";
5071
5144
  }
5072
- function qa(i, e, a, o) {
5073
- var c;
5074
- const r = ((c = a == null ? void 0 : a[e]) == null ? void 0 : c[i]) || Y[e][i] || J[i] || i;
5145
+ function Pa(i, e, t, o) {
5146
+ var _;
5147
+ const r = ((_ = t == null ? void 0 : t[e]) == null ? void 0 : _[i]) || Y[e][i] || J[i] || i;
5075
5148
  return o ? r.replace(
5076
5149
  /\{(\w+)\}/g,
5077
- (s, t) => t in o ? String(o[t]) : s
5150
+ (s, a) => a in o ? String(o[a]) : s
5078
5151
  ) : r;
5079
5152
  }
5080
- function Ea(i, e, a) {
5081
- return qa(
5153
+ function Ta(i, e, t) {
5154
+ return Pa(
5082
5155
  e,
5083
- xa(i.language),
5156
+ Aa(i.language),
5084
5157
  i.translationOverrides,
5085
- a
5158
+ t
5086
5159
  );
5087
5160
  }
5088
- class Aa {
5161
+ class Ia {
5089
5162
  constructor({
5090
5163
  config: e,
5091
- api: a,
5164
+ api: t,
5092
5165
  contactCtx: o,
5093
5166
  storageCtx: r,
5094
- sessionsPollingIntervalSeconds: c,
5167
+ sessionsPollingIntervalSeconds: _,
5095
5168
  sharedSessions: s
5096
5169
  }) {
5097
5170
  this.sessionsRefresher = new W(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new S({
@@ -5112,21 +5185,21 @@ class Aa {
5112
5185
  this.persistSession
5113
5186
  ));
5114
5187
  }, this.restoreActiveSessionTracking = () => {
5115
- var t;
5116
- (t = this.stopPersistingSession) == null || t.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5117
- }, this.trackActiveSession = (t) => {
5188
+ var a;
5189
+ (a = this.stopPersistingSession) == null || a.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5190
+ }, this.trackActiveSession = (a) => {
5118
5191
  var n;
5119
- (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = t.sessionState.subscribe(
5192
+ (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = a.sessionState.subscribe(
5120
5193
  this.persistSession
5121
- ), this.persistSession(t.sessionState.get());
5122
- }, this.persistSession = ({ session: t }) => {
5194
+ ), this.persistSession(a.sessionState.get());
5195
+ }, this.persistSession = ({ session: a }) => {
5123
5196
  const n = this.storageCtx;
5124
5197
  if (!n) return;
5125
- const l = t != null && t.isOpened ? t.id : null;
5126
- if (l === this.persistedSessionId || !l && this.persistedSessionId === null) return;
5127
- this.persistedSessionId = l, (l ? n.setActiveSessionId(l) : n.clearActiveSessionId()).catch((_) => {
5198
+ const c = a != null && a.isOpened ? a.id : null;
5199
+ if (c === this.persistedSessionId || !c && this.persistedSessionId === null) return;
5200
+ this.persistedSessionId = c, (c ? n.setActiveSessionId(c) : n.clearActiveSessionId()).catch((l) => {
5128
5201
  k.warn("failed to persist the active session", {
5129
- error: _ instanceof Error ? _.message : String(_)
5202
+ error: l instanceof Error ? l.message : String(l)
5130
5203
  });
5131
5204
  });
5132
5205
  }, this.getLastActiveSessionId = async () => {
@@ -5139,9 +5212,9 @@ class Aa {
5139
5212
  }, this.reset = async () => {
5140
5213
  this.sessionAbortController.abort(), this.sessionAbortController = new AbortController(), this.sessionState.reset();
5141
5214
  }, this.registerSessionsRefresherWrapper = () => {
5142
- var t;
5215
+ var a;
5143
5216
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
5144
- (t = this.contactCtx.state.get().contact) != null && t.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5217
+ (a = this.contactCtx.state.get().contact) != null && a.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5145
5218
  ({ contact: n }) => {
5146
5219
  n != null && n.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
5147
5220
  }
@@ -5150,9 +5223,9 @@ class Aa {
5150
5223
  this.sessionsRefresher.startPolling(async () => {
5151
5224
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
5152
5225
  }, this.sessionsPollingIntervalSeconds * 1e3);
5153
- }, this.dispose = ({ clearActiveSession: t = !1 } = {}) => {
5154
- var n, l;
5155
- if (this.sessionsRefresher.reset(), this.sessionAbortController.abort(), (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = void 0, (l = this.stopWaitingForContact) == null || l.call(this), this.stopWaitingForContact = void 0, this.sessionState.reset(), t && this.storageCtx)
5226
+ }, this.dispose = ({ clearActiveSession: a = !1 } = {}) => {
5227
+ var n, c;
5228
+ if (this.sessionsRefresher.reset(), this.sessionAbortController.abort(), (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = void 0, (c = this.stopWaitingForContact) == null || c.call(this), this.stopWaitingForContact = void 0, this.sessionState.reset(), a && this.storageCtx)
5156
5229
  return this.persistedSessionId = null, this.storageCtx.clearActiveSessionId().catch((d) => {
5157
5230
  k.warn("failed to clear the replaced session", {
5158
5231
  error: d instanceof Error ? d.message : String(d)
@@ -5160,46 +5233,46 @@ class Aa {
5160
5233
  });
5161
5234
  }, this.getParsedCustomData = () => Object.fromEntries(
5162
5235
  Object.entries(this.config.sessionCustomData || {}).map(
5163
- ([t, n]) => {
5164
- var l;
5165
- return typeof n == "string" ? [t, n] : typeof n == "boolean" ? [t, n] : typeof n == "number" ? [t, n] : [t, ((l = $(() => JSON.stringify(n))) == null ? void 0 : l.data) || ""];
5236
+ ([a, n]) => {
5237
+ var c;
5238
+ return typeof n == "string" ? [a, n] : typeof n == "boolean" ? [a, n] : typeof n == "number" ? [a, n] : [a, ((c = $(() => JSON.stringify(n))) == null ? void 0 : c.data) || ""];
5166
5239
  }
5167
5240
  )
5168
5241
  ), this.createSession = async () => {
5169
- const { signal: t } = this.sessionAbortController;
5242
+ const { signal: a } = this.sessionAbortController;
5170
5243
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
5171
5244
  try {
5172
- const n = await this.requestSession(t);
5173
- if (t.aborted) return null;
5245
+ const n = await this.requestSession(a);
5246
+ if (a.aborted) return null;
5174
5247
  if (n.session) return n.session;
5175
5248
  if (n.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
5176
- if (t.aborted) return null;
5177
- const l = await this.requestSession(t);
5178
- return t.aborted ? null : l.session ? l.session : (k.error("failed to create session", l.error), null);
5249
+ if (a.aborted) return null;
5250
+ const c = await this.requestSession(a);
5251
+ return a.aborted ? null : c.session ? c.session : (k.error("failed to create session", c.error), null);
5179
5252
  }
5180
5253
  return k.error("failed to create session", n.error), null;
5181
5254
  } catch (n) {
5182
- return t.aborted || k.error("failed to create session", n), null;
5255
+ return a.aborted || k.error("failed to create session", n), null;
5183
5256
  } finally {
5184
- t.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5257
+ a.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5185
5258
  }
5186
- }, this.requestSession = async (t) => {
5259
+ }, this.requestSession = async (a) => {
5187
5260
  var u, m, g;
5188
- const n = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, l = {
5261
+ const n = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, c = {
5189
5262
  ...this.getParsedCustomData(),
5190
5263
  ...n ? { external_id: n } : {}
5191
5264
  }, {
5192
5265
  data: d,
5193
- error: _,
5266
+ error: l,
5194
5267
  response: p
5195
5268
  } = await this.api.createSession(
5196
5269
  {
5197
- customData: Object.keys(l).length > 0 ? l : void 0
5270
+ customData: Object.keys(c).length > 0 ? c : void 0
5198
5271
  },
5199
- t
5272
+ a
5200
5273
  );
5201
- if (t.aborted || !d)
5202
- return { session: null, status: p == null ? void 0 : p.status, error: _ };
5274
+ if (a.aborted || !d)
5275
+ return { session: null, status: p == null ? void 0 : p.status, error: l };
5203
5276
  this.sessionState.setPartial({ session: d });
5204
5277
  try {
5205
5278
  (g = (m = this.config.hooks) == null ? void 0 : m.onSessionCreated) == null || g.call(m, { session: d });
@@ -5209,83 +5282,83 @@ class Aa {
5209
5282
  return { session: d, status: p.status, error: void 0 };
5210
5283
  }, this.loadMoreSessions = async () => {
5211
5284
  if (this.sessionsState.get().isLastPage) return;
5212
- const { data: t } = await this.getSessions({
5285
+ const { data: a } = await this.getSessions({
5213
5286
  cursor: this.sessionsState.get().cursor
5214
5287
  });
5215
- if (t) {
5216
- const l = [...this.sessionsState.get().data, ...t.items].filter(
5217
- (d, _, p) => _ === p.findIndex((u) => d.id === u.id)
5288
+ if (a) {
5289
+ const c = [...this.sessionsState.get().data, ...a.items].filter(
5290
+ (d, l, p) => l === p.findIndex((u) => d.id === u.id)
5218
5291
  );
5219
5292
  this.sessionsState.setPartial({
5220
- data: l,
5221
- cursor: t.next || void 0,
5222
- isLastPage: t.next === null
5293
+ data: c,
5294
+ cursor: a.next || void 0,
5295
+ isLastPage: a.next === null
5223
5296
  });
5224
5297
  }
5225
- }, this.getSessions = async ({ cursor: t }) => {
5226
- var l, d;
5227
- if (!((l = this.contactCtx.state.get().contact) != null && l.token)) return { data: null };
5298
+ }, this.getSessions = async ({ cursor: a }) => {
5299
+ var c, d;
5300
+ if (!((c = this.contactCtx.state.get().contact) != null && c.token)) return { data: null };
5228
5301
  const n = (d = this.contactCtx.state.get().contact) == null ? void 0 : d.externalId;
5229
5302
  return await this.api.getSessions({
5230
- cursor: t,
5303
+ cursor: a,
5231
5304
  filters: n ? {
5232
5305
  external_id: n
5233
5306
  } : {}
5234
5307
  });
5235
- }, this.setSessions = (t) => {
5236
- const n = [...t, ...this.sessionsState.get().data].filter(
5237
- (l, d, _) => d === _.findIndex((p) => l.id === p.id)
5308
+ }, this.setSessions = (a) => {
5309
+ const n = [...a, ...this.sessionsState.get().data].filter(
5310
+ (c, d, l) => d === l.findIndex((p) => c.id === p.id)
5238
5311
  );
5239
5312
  this.sessionsState.setPartial({ data: n });
5240
5313
  }, this.refreshSessions = async () => {
5241
- const { data: t } = await this.getSessions({ cursor: void 0 });
5242
- t && this.setSessions(t.items);
5314
+ const { data: a } = await this.getSessions({ cursor: void 0 });
5315
+ a && this.setSessions(a.items);
5243
5316
  }, this.resolveSession = async () => {
5244
- const t = this.sessionState.get().session;
5245
- if (!t || !t.isOpened)
5317
+ const a = this.sessionState.get().session;
5318
+ if (!a || !a.isOpened)
5246
5319
  return { success: !1, error: "Session is not opened" };
5247
5320
  this.sessionState.setPartial({ isResolvingSession: !0 });
5248
- const { signal: n } = this.sessionAbortController, l = await this.api.resolveSession({ session_id: t.id }, n).catch((p) => {
5321
+ const { signal: n } = this.sessionAbortController, c = await this.api.resolveSession({ session_id: a.id }, n).catch((p) => {
5249
5322
  if (n.aborted) return null;
5250
5323
  throw p;
5251
5324
  });
5252
- if (!l || n.aborted)
5325
+ if (!c || n.aborted)
5253
5326
  return { success: !1, error: "Session was reset" };
5254
- const { data: d, error: _ } = l;
5255
- return d ? (this.sessionState.setPartial({ session: d, isResolvingSession: !1 }), { success: !0, data: d }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: _ });
5256
- }, this.createStateCheckpoint = async (t) => {
5327
+ const { data: d, error: l } = c;
5328
+ return d ? (this.sessionState.setPartial({ session: d, isResolvingSession: !1 }), { success: !0, data: d }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: l });
5329
+ }, this.createStateCheckpoint = async (a) => {
5257
5330
  var d;
5258
5331
  const n = (d = this.sessionState.get().session) == null ? void 0 : d.id;
5259
5332
  if (!n) return;
5260
- const { data: l } = await this.api.createStateCheckpoint({
5333
+ const { data: c } = await this.api.createStateCheckpoint({
5261
5334
  session_id: n,
5262
- payload: t
5335
+ payload: a
5263
5336
  });
5264
- return l != null && l.success ? { success: !0 } : { success: !1 };
5265
- }, this.config = e, this.api = a, this.contactCtx = o, this.storageCtx = r, this.sessionsPollingIntervalSeconds = c, s ? this.sessionsState = s : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
5337
+ return c != null && c.success ? { success: !0 } : { success: !1 };
5338
+ }, this.config = e, this.api = t, this.contactCtx = o, this.storageCtx = r, this.sessionsPollingIntervalSeconds = _, s ? this.sessionsState = s : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
5266
5339
  }
5267
5340
  }
5268
- const Pa = (i, e, { sendsPageContext: a }) => {
5269
- const o = Ma(i), r = a && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(Ta) } : void 0, c = a && (e.clientContext || r) ? { ...o, ...e.clientContext, ...r } : o, s = e.connectionRequestId ? {
5270
- ...c,
5341
+ const Ma = (i, e, { sendsPageContext: t }) => {
5342
+ const o = Na(i), r = t && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(Da) } : void 0, _ = t && (e.clientContext || r) ? { ...o, ...e.clientContext, ...r } : o, s = e.connectionRequestId ? {
5343
+ ..._,
5271
5344
  opencx__connection_request_id: e.connectionRequestId
5272
- } : c, t = e.withPageEntity === !1 && s && "entity" in s ? Ia(s, "entity") : s;
5345
+ } : _, a = e.withPageEntity === !1 && s && "entity" in s ? Ra(s, "entity") : s;
5273
5346
  return {
5274
- clientContext: e.background ? { ...t, opencx__background: !0 } : t,
5347
+ clientContext: e.background ? { ...a, opencx__background: !0 } : a,
5275
5348
  custom_data: {
5276
5349
  ...i.messageCustomData || {},
5277
5350
  ...e.customData || {}
5278
5351
  }
5279
5352
  };
5280
- }, Ta = ({ type: i, id: e, title: a, meta: o }) => ({
5353
+ }, Da = ({ type: i, id: e, title: t, meta: o }) => ({
5281
5354
  type: i,
5282
5355
  id: e,
5283
- title: a,
5356
+ title: t,
5284
5357
  ...o ? { meta: o } : {}
5285
- }), Ia = (i, e) => {
5286
- const { [e]: a, ...o } = i;
5358
+ }), Ra = (i, e) => {
5359
+ const { [e]: t, ...o } = i;
5287
5360
  return Object.keys(o).length > 0 ? o : void 0;
5288
- }, Ma = (i) => {
5361
+ }, Na = (i) => {
5289
5362
  if (typeof i.context != "function") return i.context;
5290
5363
  try {
5291
5364
  return i.context();
@@ -5293,25 +5366,25 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5293
5366
  k.error("context getter threw; sending without context", e);
5294
5367
  return;
5295
5368
  }
5296
- }, Da = (i) => {
5297
- const e = i.features, a = {
5369
+ }, Ka = (i) => {
5370
+ const e = i.features, t = {
5298
5371
  page_context: (e == null ? void 0 : e.pageContext) === !0,
5299
5372
  client_tools: (e == null ? void 0 : e.pageContext) === !0 && (e == null ? void 0 : e.clientTools) === !0,
5300
5373
  page_actions: (e == null ? void 0 : e.pageContext) === !0 && (e == null ? void 0 : e.clientTools) === !0 && (e == null ? void 0 : e.pageActions) === !0
5301
5374
  };
5302
- return e && (e.preamble !== void 0 && (a.preamble = e.preamble), e.inlineUi !== void 0 && (a.inline_ui = e.inlineUi)), a;
5303
- }, Na = ({
5375
+ return e && (e.preamble !== void 0 && (t.preamble = e.preamble), e.inlineUi !== void 0 && (t.inline_ui = e.inlineUi)), t;
5376
+ }, La = ({
5304
5377
  config: i,
5305
5378
  input: e,
5306
- uuid: a,
5379
+ uuid: t,
5307
5380
  sessionId: o,
5308
5381
  content: r,
5309
- initialMessages: c,
5382
+ initialMessages: _,
5310
5383
  sendsPageContext: s
5311
5384
  }) => {
5312
- var t, n, l, d;
5385
+ var a, n, c, d;
5313
5386
  return {
5314
- uuid: a,
5387
+ uuid: t,
5315
5388
  bot_token: i.token,
5316
5389
  headers: i.headers,
5317
5390
  query_params: i.queryParams,
@@ -5319,14 +5392,14 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5319
5392
  session_id: o,
5320
5393
  content: r,
5321
5394
  attachments: e.attachments,
5322
- ...Pa(i, e, { sendsPageContext: s }),
5395
+ ...Ma(i, e, { sendsPageContext: s }),
5323
5396
  language: i.language,
5324
- features: Da(i),
5397
+ features: Ka(i),
5325
5398
  presentation: i.presentation,
5326
5399
  capabilities: {
5327
- connections: ((t = i.capabilities) == null ? void 0 : t.connections) === !0,
5400
+ connections: ((a = i.capabilities) == null ? void 0 : a.connections) === !0,
5328
5401
  structured_questions: (n = i.capabilities) == null ? void 0 : n.structuredQuestions,
5329
- rich_replies: (l = i.capabilities) == null ? void 0 : l.richReplies,
5402
+ rich_replies: (c = i.capabilities) == null ? void 0 : c.richReplies,
5330
5403
  page_effects: (d = i.capabilities) == null ? void 0 : d.pageEffects
5331
5404
  },
5332
5405
  exit_mode_prompt: e.exitModePrompt,
@@ -5334,19 +5407,19 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5334
5407
  message_id: e.optionReply.messageId,
5335
5408
  option_id: e.optionReply.optionId
5336
5409
  } : void 0,
5337
- initial_messages: c.length > 0 ? c.map((_) => ({ uuid: _.id, content: _.data.message })) : void 0
5410
+ initial_messages: _.length > 0 ? _.map((l) => ({ uuid: l.id, content: l.data.message })) : void 0
5338
5411
  };
5339
5412
  }, x = class x {
5340
5413
  constructor({
5341
5414
  config: e,
5342
- api: a,
5415
+ api: t,
5343
5416
  sessionCtx: o,
5344
5417
  contactCtx: r,
5345
- streaming: c,
5418
+ streaming: _,
5346
5419
  sendsPageContext: s,
5347
- getClientCapabilities: t,
5420
+ getClientCapabilities: a,
5348
5421
  getRequestConfig: n,
5349
- isStreaming: l,
5422
+ isStreaming: c,
5350
5423
  getSendsPageContext: d
5351
5424
  }) {
5352
5425
  this.state = new S({
@@ -5360,29 +5433,29 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5360
5433
  text: "",
5361
5434
  mentions: []
5362
5435
  }), this.agentHandlers = null, this.bufferedAgentSends = [], this.sendMessageAbortController = new AbortController(), this.conversationGeneration = 0, this.captureConversation = () => {
5363
- const _ = this.conversationGeneration;
5364
- return () => _ === this.conversationGeneration;
5436
+ const l = this.conversationGeneration;
5437
+ return () => l === this.conversationGeneration;
5365
5438
  }, this.messageIdsDispatchedToOnMessageReceivedHook = /* @__PURE__ */ new Set(), this.sentTextHistory = [], this.reset = () => {
5366
5439
  this.conversationGeneration++, this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [], this.draftState.reset();
5367
- }, this.rememberSentText = (_) => {
5368
- const p = _.trim();
5440
+ }, this.rememberSentText = (l) => {
5441
+ const p = l.trim();
5369
5442
  !p || this.sentTextHistory.at(-1) === p || (this.sentTextHistory.push(p), this.sentTextHistory.length > x.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
5370
- }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (_) => {
5371
- this.agentHandlers = _;
5443
+ }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (l) => {
5444
+ this.agentHandlers = l;
5372
5445
  const p = this.bufferedAgentSends;
5373
5446
  this.bufferedAgentSends = [], p.forEach((u) => {
5374
- x.dispatchToEngine(_, u);
5447
+ x.dispatchToEngine(l, u);
5375
5448
  });
5376
- }, this.unregisterAgentHandlers = (_) => {
5377
- this.agentHandlers === _ && (this.agentHandlers = null);
5378
- }, this.dispatchToOnMessageReceivedHook = (_) => {
5449
+ }, this.unregisterAgentHandlers = (l) => {
5450
+ this.agentHandlers === l && (this.agentHandlers = null);
5451
+ }, this.dispatchToOnMessageReceivedHook = (l) => {
5379
5452
  var u, m;
5380
- if (_.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(_.id))
5453
+ if (l.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(l.id))
5381
5454
  return;
5382
5455
  const p = this.sessionCtx.sessionState.get().session;
5383
- p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(_.id), (m = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || m.call(u, { message: _, session: p }));
5384
- }, this.markAsDispatchedToOnMessageReceivedHook = (_) => {
5385
- _.forEach(
5456
+ p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(l.id), (m = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || m.call(u, { message: l, session: p }));
5457
+ }, this.markAsDispatchedToOnMessageReceivedHook = (l) => {
5458
+ l.forEach(
5386
5459
  (p) => this.messageIdsDispatchedToOnMessageReceivedHook.add(p)
5387
5460
  );
5388
5461
  }, this.buildPersistentInitialMessages = () => {
@@ -5398,29 +5471,29 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5398
5471
  })
5399
5472
  ) : [];
5400
5473
  }, this.ensureSessionId = async () => {
5401
- var _, p;
5402
- if (!((_ = this.sessionCtx.sessionState.get().session) != null && _.id)) {
5474
+ var l, p;
5475
+ if (!((l = this.sessionCtx.sessionState.get().session) != null && l.id)) {
5403
5476
  if (!await this.sessionCtx.createSession()) return null;
5404
5477
  this.sessionCtx.refreshSessions();
5405
5478
  }
5406
5479
  return ((p = this.sessionCtx.sessionState.get().session) == null ? void 0 : p.id) ?? null;
5407
- }, this.rollbackOptimisticMessages = (_) => {
5408
- if (_.length === 0) return;
5409
- const p = new Set(_), u = this.state.get().messages, m = u.filter((g) => !p.has(g.id));
5480
+ }, this.rollbackOptimisticMessages = (l) => {
5481
+ if (l.length === 0) return;
5482
+ const p = new Set(l), u = this.state.get().messages, m = u.filter((g) => !p.has(g.id));
5410
5483
  m.length !== u.length && this.state.setPartial({ messages: m });
5411
- }, this.notifySendAccepted = (_) => {
5484
+ }, this.notifySendAccepted = (l) => {
5412
5485
  var p;
5413
- _.optionReply && this.setMessageOptionPick(
5414
- _.optionReply.messageId,
5415
- _.optionReply.optionId
5486
+ l.optionReply && this.setMessageOptionPick(
5487
+ l.optionReply.messageId,
5488
+ l.optionReply.optionId
5416
5489
  );
5417
5490
  try {
5418
- (p = _.onAccepted) == null || p.call(_);
5491
+ (p = l.onAccepted) == null || p.call(l);
5419
5492
  } catch (u) {
5420
5493
  k.error("send acceptance callback failed", u);
5421
5494
  }
5422
- }, this.stageUserTurn = async (_, { pending: p }) => {
5423
- const u = this.captureConversation(), m = this.buildUserMessage(_);
5495
+ }, this.stageUserTurn = async (l, { pending: p }) => {
5496
+ const u = this.captureConversation(), m = this.buildUserMessage(l);
5424
5497
  if (!m) return null;
5425
5498
  const g = p ? { ...m, pending: !0 } : m, b = this.buildPersistentInitialMessages(), f = [
5426
5499
  ...b.map((y) => y.id),
@@ -5441,30 +5514,30 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5441
5514
  throw this.rollbackOptimisticMessages(f), y;
5442
5515
  }
5443
5516
  return u() ? v ? { sessionId: v, userMessage: g, initialMessages: b } : (this.rollbackOptimisticMessages(f), null) : null;
5444
- }, this.buildQueuedUserMessage = (_) => {
5517
+ }, this.buildQueuedUserMessage = (l) => {
5445
5518
  var m;
5446
- const p = this.buildUserMessage(_);
5519
+ const p = this.buildUserMessage(l);
5447
5520
  if (!p) return null;
5448
5521
  const u = (m = this.sessionCtx.sessionState.get().session) == null ? void 0 : m.id;
5449
5522
  return u ? { sessionId: u, userMessage: { ...p, pending: !0 } } : null;
5450
- }, this.buildUserMessage = (_) => {
5523
+ }, this.buildUserMessage = (l) => {
5451
5524
  var p;
5452
- return !_.content.trim() && (!_.attachments || _.attachments.length === 0) ? (k.warn("cannot send an empty message of no content or attachments"), null) : {
5525
+ return !l.content.trim() && (!l.attachments || l.attachments.length === 0) ? (k.warn("cannot send an empty message of no content or attachments"), null) : {
5453
5526
  ...this.toUserMessage(
5454
- _.content.trim(),
5455
- _.attachments || void 0,
5456
- this.sendsPageContext ? x.markedElementNames(_.clientContext) : void 0,
5457
- this.sendsPageContext && ((p = _.mentions) != null && p.length) ? _.mentions : void 0
5527
+ l.content.trim(),
5528
+ l.attachments || void 0,
5529
+ this.sendsPageContext ? x.markedElementNames(l.clientContext) : void 0,
5530
+ this.sendsPageContext && ((p = l.mentions) != null && p.length) ? l.mentions : void 0
5458
5531
  ),
5459
- ..._.background ? { background: !0 } : {}
5532
+ ...l.background ? { background: !0 } : {}
5460
5533
  };
5461
- }, this.appendUserMessageIfAbsent = (_) => {
5462
- if (_.background) return;
5534
+ }, this.appendUserMessageIfAbsent = (l) => {
5535
+ if (l.background) return;
5463
5536
  const p = this.state.get().messages;
5464
- p.some((u) => u.id === _.id) || this.state.setPartial({ messages: [...p, _] });
5465
- }, this.markUserMessageDelivered = (_) => {
5537
+ p.some((u) => u.id === l.id) || this.state.setPartial({ messages: [...p, l] });
5538
+ }, this.markUserMessageDelivered = (l) => {
5466
5539
  const p = this.state.get().messages, u = p.findIndex(
5467
- (b) => b.id === _ && b.type === "USER" && b.pending
5540
+ (b) => b.id === l && b.type === "USER" && b.pending
5468
5541
  );
5469
5542
  if (u === -1) return;
5470
5543
  const m = p[u];
@@ -5473,27 +5546,27 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5473
5546
  g[u] = { ...m, pending: !1 }, this.state.setPartial({
5474
5547
  messages: g
5475
5548
  });
5476
- }, this.setMessageOptionPick = (_, p) => {
5477
- const u = this.state.get().messages, m = u.findIndex((f) => f.id === _), g = u[m];
5549
+ }, this.setMessageOptionPick = (l, p) => {
5550
+ const u = this.state.get().messages, m = u.findIndex((f) => f.id === l), g = u[m];
5478
5551
  if (!g || g.type !== "AGENT" || !g.messageOptions || g.messageOptions.pickedOptionId === p) return;
5479
5552
  const b = [...u];
5480
5553
  b[m] = {
5481
5554
  ...g,
5482
5555
  messageOptions: { ...g.messageOptions, pickedOptionId: p }
5483
5556
  }, this.state.setPartial({ messages: b });
5484
- }, this.releaseFailedOptionPick = (_) => {
5557
+ }, this.releaseFailedOptionPick = (l) => {
5485
5558
  var g;
5486
- if (!_.optionReply) return;
5487
- const { messageId: p, optionId: u } = _.optionReply, m = this.state.get().messages.find((b) => b.id === p);
5559
+ if (!l.optionReply) return;
5560
+ const { messageId: p, optionId: u } = l.optionReply, m = this.state.get().messages.find((b) => b.id === p);
5488
5561
  (m == null ? void 0 : m.type) !== "AGENT" || ((g = m.messageOptions) == null ? void 0 : g.pickedOptionId) !== u || this.setMessageOptionPick(p, null);
5489
- }, this.sendMessage = async (_) => {
5562
+ }, this.sendMessage = async (l) => {
5490
5563
  var u, m, g, b, f;
5491
5564
  if (this.streaming) {
5492
5565
  if (!this.agentHandlers) {
5493
- this.bufferedAgentSends.push(_);
5566
+ this.bufferedAgentSends.push(l);
5494
5567
  return;
5495
5568
  }
5496
- await this.agentHandlers.send(_);
5569
+ await this.agentHandlers.send(l);
5497
5570
  return;
5498
5571
  }
5499
5572
  let p;
@@ -5509,17 +5582,17 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5509
5582
  isSendingMessage: !0,
5510
5583
  isSendingMessageToAI: !!z || !v
5511
5584
  });
5512
- const R = await this.stageUserTurn(_, { pending: !1 });
5513
- if (!R) return;
5514
- const { sessionId: ee, userMessage: K, initialMessages: ae } = R;
5515
- this.notifySendAccepted(_);
5585
+ const N = await this.stageUserTurn(l, { pending: !1 });
5586
+ if (!N) return;
5587
+ const { sessionId: ee, userMessage: K, initialMessages: ae } = N;
5588
+ this.notifySendAccepted(l);
5516
5589
  const { data: w } = await this.api.sendMessage(
5517
- Na({
5590
+ La({
5518
5591
  config: {
5519
5592
  ...this.getRequestConfig(),
5520
5593
  capabilities: this.getClientCapabilities()
5521
5594
  },
5522
- input: _,
5595
+ input: l,
5523
5596
  uuid: K.id,
5524
5597
  sessionId: ee,
5525
5598
  content: K.content,
@@ -5547,29 +5620,29 @@ const Pa = (i, e, { sendsPageContext: a }) => {
5547
5620
  }
5548
5621
  w.session && this.sessionCtx.sessionState.setPartial({ session: w.session });
5549
5622
  } else {
5550
- this.releaseFailedOptionPick(_);
5623
+ this.releaseFailedOptionPick(l);
5551
5624
  const C = this.toBotErrorMessage(
5552
- ((f = w == null ? void 0 : w.error) == null ? void 0 : f.message) || Ea(this.config, "turn_failed_message")
5625
+ ((f = w == null ? void 0 : w.error) == null ? void 0 : f.message) || Ta(this.config, "turn_failed_message")
5553
5626
  ), P = this.state.get().messages;
5554
5627
  this.state.setPartial({
5555
5628
  messages: [...P, C]
5556
5629
  });
5557
5630
  }
5558
5631
  } catch (v) {
5559
- p != null && p.signal.aborted || (this.releaseFailedOptionPick(_), k.error("failed to send message", v));
5632
+ p != null && p.signal.aborted || (this.releaseFailedOptionPick(l), k.error("failed to send message", v));
5560
5633
  } finally {
5561
5634
  p != null && p.signal.aborted || this.state.setPartial({
5562
5635
  isSendingMessage: !1,
5563
5636
  isSendingMessageToAI: !1
5564
5637
  });
5565
5638
  }
5566
- }, this.toUserMessage = (_, p, u, m) => {
5639
+ }, this.toUserMessage = (l, p, u, m) => {
5567
5640
  const g = (() => {
5568
5641
  const f = this.contactCtx.state.get().extraCollectedData;
5569
5642
  return this.state.get().messages.length === 0 && f && Object.keys(f).length > 0 ? `${Object.entries(f).filter(([y, z]) => !!z).map(([y, z]) => `${y}: ${z}`).join(`
5570
5643
  `)}
5571
5644
 
5572
- ${_}` : _;
5645
+ ${l}` : l;
5573
5646
  })(), b = (/* @__PURE__ */ new Date()).toISOString();
5574
5647
  return {
5575
5648
  id: q(),
@@ -5581,11 +5654,11 @@ ${_}` : _;
5581
5654
  mentions: m,
5582
5655
  timestamp: b
5583
5656
  };
5584
- }, this.toBotMessage = (_) => {
5657
+ }, this.toBotMessage = (l) => {
5585
5658
  var p;
5586
- return _.success && _.autopilotResponse ? {
5659
+ return l.success && l.autopilotResponse ? {
5587
5660
  type: "AI",
5588
- id: _.autopilotResponse.id || q(),
5661
+ id: l.autopilotResponse.id || q(),
5589
5662
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5590
5663
  component: "bot_message",
5591
5664
  agent: this.config.bot ? {
@@ -5597,24 +5670,24 @@ ${_}` : _;
5597
5670
  id: null
5598
5671
  } : void 0,
5599
5672
  data: {
5600
- message: _.autopilotResponse.value.content,
5601
- action: (p = _.uiResponse) != null && p.value.name ? {
5602
- name: _.uiResponse.value.name,
5603
- data: _.uiResponse.value.request_response
5673
+ message: l.autopilotResponse.value.content,
5674
+ action: (p = l.uiResponse) != null && p.value.name ? {
5675
+ name: l.uiResponse.value.name,
5676
+ data: l.uiResponse.value.request_response
5604
5677
  } : void 0
5605
5678
  }
5606
5679
  } : null;
5607
- }, this.toBotErrorMessage = (_) => ({
5680
+ }, this.toBotErrorMessage = (l) => ({
5608
5681
  type: "AI",
5609
5682
  id: q(),
5610
5683
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5611
5684
  component: "bot_message",
5612
5685
  data: {
5613
- message: _,
5686
+ message: l,
5614
5687
  variant: "error",
5615
5688
  action: void 0
5616
5689
  }
5617
- }), this.config = e, this.getClientCapabilities = t ?? (() => this.getRequestConfig().capabilities), this.api = a, this.sessionCtx = o, this.contactCtx = r, this.isStreaming = l ?? (() => c), this.getRequestConfig = n ?? (() => this.config), this.getSendsPageContext = d ?? (() => s);
5690
+ }), this.config = e, this.getClientCapabilities = a ?? (() => this.getRequestConfig().capabilities), this.api = t, this.sessionCtx = o, this.contactCtx = r, this.isStreaming = c ?? (() => _), this.getRequestConfig = n ?? (() => this.config), this.getSendsPageContext = d ?? (() => s);
5618
5691
  }
5619
5692
  /**
5620
5693
  * Current transport choice. The org or this embed may request polling
@@ -5627,9 +5700,9 @@ ${_}` : _;
5627
5700
  return this.getSendsPageContext();
5628
5701
  }
5629
5702
  /** Hand a send to the streaming engine; its failure can never propagate. */
5630
- static dispatchToEngine(e, a) {
5703
+ static dispatchToEngine(e, t) {
5631
5704
  try {
5632
- Promise.resolve(e.send(a)).catch((o) => {
5705
+ Promise.resolve(e.send(t)).catch((o) => {
5633
5706
  k.error("streaming send failed", o);
5634
5707
  });
5635
5708
  } catch (o) {
@@ -5637,8 +5710,8 @@ ${_}` : _;
5637
5710
  }
5638
5711
  }
5639
5712
  get hasPendingAgentWork() {
5640
- var e, a;
5641
- return this.bufferedAgentSends.length > 0 || (((a = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : a.call(e)) ?? !1);
5713
+ var e, t;
5714
+ return this.bufferedAgentSends.length > 0 || (((t = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : t.call(e)) ?? !1);
5642
5715
  }
5643
5716
  /**
5644
5717
  * Defensive read of `clientContext.page_marks` → the user bubble's context
@@ -5648,18 +5721,18 @@ ${_}` : _;
5648
5721
  * without a usable name are dropped.
5649
5722
  */
5650
5723
  static markedElementNames(e) {
5651
- const a = e == null ? void 0 : e.page_marks;
5652
- if (!Array.isArray(a)) return;
5653
- const o = a.flatMap((r) => {
5724
+ const t = e == null ? void 0 : e.page_marks;
5725
+ if (!Array.isArray(t)) return;
5726
+ const o = t.flatMap((r) => {
5654
5727
  if (typeof r != "object" || r === null) return [];
5655
- const c = r.elements, s = Array.isArray(c) ? c[0] : void 0, t = typeof s == "object" && s !== null && "name" in s ? s.name : void 0;
5656
- if (typeof t != "string" || t.length === 0) return [];
5657
- const n = r.note, l = r.snapshotUrl;
5728
+ const _ = r.elements, s = Array.isArray(_) ? _[0] : void 0, a = typeof s == "object" && s !== null && "name" in s ? s.name : void 0;
5729
+ if (typeof a != "string" || a.length === 0) return [];
5730
+ const n = r.note, c = r.snapshotUrl;
5658
5731
  return [
5659
5732
  {
5660
- name: t,
5733
+ name: a,
5661
5734
  ...typeof n == "string" && n.length > 0 ? { note: n } : {},
5662
- ...typeof l == "string" && l.length > 0 ? { snapshotUrl: l } : {},
5735
+ ...typeof c == "string" && c.length > 0 ? { snapshotUrl: c } : {},
5663
5736
  mark: r
5664
5737
  }
5665
5738
  ];
@@ -5676,9 +5749,9 @@ ${_}` : _;
5676
5749
  };
5677
5750
  x.SENT_TEXT_HISTORY_MAX = 50;
5678
5751
  let D = x;
5679
- class Ra {
5752
+ class Oa {
5680
5753
  constructor(e) {
5681
- var a, o;
5754
+ var t, o;
5682
5755
  this.widget = e, this.subscriptions = [], this.disposed = !1, this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
5683
5756
  if (!this.shouldRestoreLastSession) {
5684
5757
  this.didReadStoredSession = !0;
@@ -5692,9 +5765,9 @@ class Ra {
5692
5765
  }, this.registerRoutingListener = () => {
5693
5766
  this.subscriptions.push(
5694
5767
  this.contactCtx.state.subscribe(({ contact: r }) => {
5695
- var c;
5768
+ var _;
5696
5769
  r != null && r.token && this.state.get().screen === "welcome" && this.state.setPartial({
5697
- screen: (c = this.config.router) != null && c.chatScreenOnly ? "chat" : "sessions"
5770
+ screen: (_ = this.config.router) != null && _.chatScreenOnly ? "chat" : "sessions"
5698
5771
  });
5699
5772
  })
5700
5773
  ), this.subscriptions.push(
@@ -5702,52 +5775,52 @@ class Ra {
5702
5775
  );
5703
5776
  }, this.routeFromSessions = ({
5704
5777
  isInitialFetchLoading: r,
5705
- data: c
5778
+ data: _
5706
5779
  }) => {
5707
- var s, t, n, l, d;
5780
+ var s, a, n, c, d;
5708
5781
  if (!(this.disposed || !this.didReadStoredSession)) {
5709
5782
  if (this.restorableSessionId && !((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
5710
- const _ = c.find(
5783
+ const l = _.find(
5711
5784
  (p) => p.id === this.restorableSessionId && p.isOpened
5712
5785
  );
5713
- if (_) {
5714
- this.restorableSessionId = null, this.toChatScreen(_.id);
5786
+ if (l) {
5787
+ this.restorableSessionId = null, this.toChatScreen(l.id);
5715
5788
  return;
5716
5789
  }
5717
5790
  if (r) return;
5718
5791
  this.restorableSessionId = null;
5719
5792
  }
5720
- if ((t = this.config.router) != null && t.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5793
+ if ((a = this.config.router) != null && a.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5721
5794
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
5722
5795
  !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
5723
- const _ = (l = c.find((p) => p.isOpened)) == null ? void 0 : l.id;
5724
- return _ ? this.toChatScreen(_) : void 0;
5796
+ const l = (c = _.find((p) => p.isOpened)) == null ? void 0 : c.id;
5797
+ return l ? this.toChatScreen(l) : void 0;
5725
5798
  }
5726
- c.length || ((d = this.config.router) == null ? void 0 : d.goToChatIfNoSessions) !== !1 && !r && this.state.get().screen !== "chat" && this.toChatScreen();
5799
+ _.length || ((d = this.config.router) == null ? void 0 : d.goToChatIfNoSessions) !== !1 && !r && this.state.get().screen !== "chat" && this.toChatScreen();
5727
5800
  }
5728
5801
  }, this.dispose = () => {
5729
5802
  this.disposed = !0, this.subscriptions.forEach((r) => r()), this.subscriptions = [], this.navigateConversation = void 0;
5730
5803
  }, this.toSessionsScreen = () => {
5731
5804
  this.navigateConversation || this.resetChat(), this.state.setPartial({ screen: "sessions" });
5732
5805
  }, this.toChatScreen = (r) => {
5733
- var s, t;
5806
+ var s, a;
5734
5807
  if (this.navigateConversation) return this.navigateConversation(r);
5735
5808
  this.resetChat();
5736
- let c;
5809
+ let _;
5737
5810
  if (r) {
5738
- if (c = this.sessionCtx.sessionsState.get().data.find((n) => n.id === r), !c) return;
5739
- this.sessionCtx.sessionState.setPartial({ session: c });
5811
+ if (_ = this.sessionCtx.sessionsState.get().data.find((n) => n.id === r), !_) return;
5812
+ this.sessionCtx.sessionState.setPartial({ session: _ });
5740
5813
  }
5741
- return this.state.setPartial({ screen: "chat" }), (t = (s = this.config.hooks) == null ? void 0 : s.onNavigateToChat) == null || t.call(s, { session: c }), this.widget;
5814
+ return this.state.setPartial({ screen: "chat" }), (a = (s = this.config.hooks) == null ? void 0 : s.onNavigateToChat) == null || a.call(s, { session: _ }), this.widget;
5742
5815
  }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new S({
5743
- screen: this.contactCtx.shouldCollectData() ? "welcome" : (a = this.config.router) != null && a.chatScreenOnly ? "chat" : "sessions"
5816
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : (t = this.config.router) != null && t.chatScreenOnly ? "chat" : "sessions"
5744
5817
  }), this.shouldRestoreLastSession = ((o = this.config.router) == null ? void 0 : o.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5745
5818
  }
5746
5819
  }
5747
- class Ka {
5820
+ class Fa {
5748
5821
  constructor({
5749
5822
  storage: e,
5750
- config: a
5823
+ config: t
5751
5824
  }) {
5752
5825
  this.KEYS = {
5753
5826
  contactToken: (o) => `opencx-widget:org-token-${o}:contact-token`,
@@ -5767,8 +5840,8 @@ class Ka {
5767
5840
  }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.companionKey = (o) => this.KEYS.companionPreference(this.config.token, o), this.getFiniteNumber = async (o) => {
5768
5841
  const r = await this.storage.get(o);
5769
5842
  if (r === null) return null;
5770
- const c = Number(r);
5771
- return Number.isFinite(c) ? c : null;
5843
+ const _ = Number(r);
5844
+ return Number.isFinite(_) ? _ : null;
5772
5845
  }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (o) => {
5773
5846
  Number.isFinite(o) && await this.storage.set(this.companionKey("pill-offset-x"), String(o));
5774
5847
  }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (o) => {
@@ -5788,10 +5861,10 @@ class Ka {
5788
5861
  return o === "docked" || o === "floating" ? o : null;
5789
5862
  }, this.setCompanionSidebarMode = async (o) => {
5790
5863
  await this.storage.set(this.companionKey("sidebar-mode"), o);
5791
- }, this.storage = e, this.config = a;
5864
+ }, this.storage = e, this.config = t;
5792
5865
  }
5793
5866
  }
5794
- function La({
5867
+ function Ua({
5795
5868
  org: i,
5796
5869
  agent: e
5797
5870
  }) {
@@ -5823,37 +5896,37 @@ function La({
5823
5896
  function G(i, e) {
5824
5897
  return i && e !== !1;
5825
5898
  }
5826
- function Oa(i, e) {
5827
- const a = e.features;
5899
+ function Ba(i, e) {
5900
+ const t = e.features;
5828
5901
  return {
5829
- dictation: G(i.features.dictation, a == null ? void 0 : a.dictation),
5902
+ dictation: G(i.features.dictation, t == null ? void 0 : t.dictation),
5830
5903
  attachments: G(
5831
5904
  i.features.attachments,
5832
- a == null ? void 0 : a.attachments
5905
+ t == null ? void 0 : t.attachments
5833
5906
  ),
5834
- pageContext: i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0,
5835
- clientTools: i.features.clientTools && i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0 && (a == null ? void 0 : a.clientTools) === !0,
5836
- pageActions: i.features.pageActions && i.features.clientTools && i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0 && (a == null ? void 0 : a.clientTools) === !0 && (a == null ? void 0 : a.pageActions) === !0
5907
+ pageContext: i.features.pageContext && (t == null ? void 0 : t.pageContext) === !0,
5908
+ clientTools: i.features.clientTools && i.features.pageContext && (t == null ? void 0 : t.pageContext) === !0 && (t == null ? void 0 : t.clientTools) === !0,
5909
+ pageActions: i.features.pageActions && i.features.clientTools && i.features.pageContext && (t == null ? void 0 : t.pageContext) === !0 && (t == null ? void 0 : t.clientTools) === !0 && (t == null ? void 0 : t.pageActions) === !0
5837
5910
  };
5838
5911
  }
5839
- class Fa extends Error {
5840
- constructor(e, a, o) {
5841
- super(a), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5912
+ class Va extends Error {
5913
+ constructor(e, t, o) {
5914
+ super(t), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5842
5915
  }
5843
5916
  }
5844
5917
  const j = class j {
5845
5918
  constructor({
5846
5919
  config: e,
5847
- storage: a,
5920
+ storage: t,
5848
5921
  getClientCapabilities: o,
5849
5922
  getRequestConfig: r,
5850
- modes: c,
5923
+ modes: _,
5851
5924
  org: s,
5852
- agent: t,
5925
+ agent: a,
5853
5926
  parent: n
5854
5927
  }) {
5855
5928
  if (this.modes = [], this.disposed = !1, this.createConversation = () => {
5856
- const l = new j({
5929
+ const c = new j({
5857
5930
  config: {
5858
5931
  ...this.config,
5859
5932
  router: {
@@ -5870,25 +5943,25 @@ const j = class j {
5870
5943
  getRequestConfig: this.getRequestConfig,
5871
5944
  getClientCapabilities: this.getClientCapabilities
5872
5945
  });
5873
- return l.routerCtx.state.setPartial({
5946
+ return c.routerCtx.state.setPartial({
5874
5947
  screen: this.contactCtx.shouldCollectData() ? "welcome" : "chat"
5875
- }), l;
5876
- }, this.releaseConversation = () => this.dispose(), this.dispose = ({ clearActiveSession: l = !1 } = {}) => {
5948
+ }), c;
5949
+ }, this.releaseConversation = () => this.dispose(), this.dispose = ({ clearActiveSession: c = !1 } = {}) => {
5877
5950
  if (this.disposed) return;
5878
- this.disposed = !0, this.routerCtx.dispose(), this.activeSessionPollingCtx.dispose();
5879
- const d = this.sessionCtx.dispose({ clearActiveSession: l });
5951
+ this.disposed = !0, this.routerCtx.dispose(), this.activeSessionPollingCtx.dispose(), this.ownsUnreadCtx && this.unreadCtx.dispose();
5952
+ const d = this.sessionCtx.dispose({ clearActiveSession: c });
5880
5953
  return this.messageCtx.reset(), this.uploadCtx.reset(), this.dictationCtx.stop({ executeFinalCommand: !1 }), d;
5881
5954
  }, this.resetChat = () => {
5882
5955
  this.sessionCtx.reset(), this.messageCtx.reset(), this.uploadCtx.reset();
5883
- }, this.reconcileAfterStream = (l) => this.activeSessionPollingCtx.reconcileAfterStream(l), !j.pollingIntervalsSeconds)
5956
+ }, this.reconcileAfterStream = (c) => this.activeSessionPollingCtx.reconcileAfterStream(c), !j.pollingIntervalsSeconds)
5884
5957
  throw Error(
5885
5958
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
5886
5959
  );
5887
- this.config = e, this.getRequestConfig = r ?? (() => this.config), this.getClientCapabilities = o, this.org = s, this.agent = t, this.api = (n == null ? void 0 : n.api) ?? new U({ config: e }), this.storageCtx = (n == null ? void 0 : n.storageCtx) ?? (a ? new Ka({ storage: a, config: e }) : void 0), this.modes = c, this.contactCtx = (n == null ? void 0 : n.contactCtx) ?? new ge({
5960
+ this.config = e, this.getRequestConfig = r ?? (() => this.config), this.getClientCapabilities = o, this.org = s, this.agent = a, this.api = (n == null ? void 0 : n.api) ?? new U({ config: e }), this.storageCtx = (n == null ? void 0 : n.storageCtx) ?? (t ? new Fa({ storage: t, config: e }) : void 0), this.modes = _, this.contactCtx = (n == null ? void 0 : n.contactCtx) ?? new ve({
5888
5961
  api: this.api,
5889
5962
  config: this.config,
5890
5963
  storageCtx: this.storageCtx
5891
- }), this.sessionCtx = new Aa({
5964
+ }), this.sessionCtx = new Ia({
5892
5965
  config: this.config,
5893
5966
  api: this.api,
5894
5967
  contactCtx: this.contactCtx,
@@ -5896,6 +5969,11 @@ const j = class j {
5896
5969
  storageCtx: n ? void 0 : this.storageCtx,
5897
5970
  sharedSessions: n == null ? void 0 : n.sessionCtx.sessionsState,
5898
5971
  sessionsPollingIntervalSeconds: j.pollingIntervalsSeconds.sessions
5972
+ }), this.ownsUnreadCtx = !n, this.unreadCtx = (n == null ? void 0 : n.unreadCtx) ?? new ie({
5973
+ config: this.config,
5974
+ api: this.api,
5975
+ sessionsState: this.sessionCtx.sessionsState,
5976
+ setSessions: this.sessionCtx.setSessions
5899
5977
  }), this.messageCtx = new D({
5900
5978
  config: this.config,
5901
5979
  api: this.api,
@@ -5909,76 +5987,76 @@ const j = class j {
5909
5987
  getSendsPageContext: () => this.features.pageContext,
5910
5988
  getClientCapabilities: o,
5911
5989
  getRequestConfig: r
5912
- }), this.uploadCtx = new ke(this.api), this.csatCtx = new be({
5990
+ }), this.uploadCtx = new fe(this.api), this.csatCtx = new ye({
5913
5991
  api: this.api,
5914
5992
  sessionCtx: this.sessionCtx,
5915
5993
  messageCtx: this.messageCtx
5916
- }), this.dictationCtx = new Oe({
5994
+ }), this.dictationCtx = new Be({
5917
5995
  api: this.api,
5918
5996
  config: this.config
5919
- }), this.activeSessionPollingCtx = new he({
5997
+ }), this.activeSessionPollingCtx = new be({
5920
5998
  api: this.api,
5921
5999
  config: this.config,
5922
6000
  sessionCtx: this.sessionCtx,
5923
6001
  messageCtx: this.messageCtx,
5924
6002
  sessionPollingIntervalSeconds: j.pollingIntervalsSeconds.session
5925
- }), this.routerCtx = new Ra(this);
6003
+ }), this.routerCtx = new Oa(this);
5926
6004
  }
5927
6005
  get streaming() {
5928
- var e, a;
5929
- return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (a = this.messageCtx) != null && a.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming === !0;
6006
+ var e, t;
6007
+ return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (t = this.messageCtx) != null && t.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming === !0;
5930
6008
  }
5931
6009
  /**
5932
6010
  * The org's features narrowed by this embed's `config.features` — the
5933
6011
  * answers the UI asks for, resolved against the current options.
5934
6012
  */
5935
6013
  get features() {
5936
- return Oa(this.agent, this.getRequestConfig());
6014
+ return Ba(this.agent, this.getRequestConfig());
5937
6015
  }
5938
6016
  };
5939
6017
  j.pollingIntervalsSeconds = null, j.initialize = async ({
5940
6018
  config: e,
5941
- storage: a,
6019
+ storage: t,
5942
6020
  getClientCapabilities: o,
5943
6021
  getRequestConfig: r
5944
6022
  }) => {
5945
- var s, t;
5946
- const c = await new U({
6023
+ var s, a;
6024
+ const _ = await new U({
5947
6025
  config: e
5948
6026
  }).getExternalWidgetConfig();
5949
- if (!c.data)
5950
- throw k.error("widget config fetch failed", c.error), new Fa(
6027
+ if (!_.data)
6028
+ throw k.error("widget config fetch failed", _.error), new Va(
5951
6029
  "config-fetch-failed",
5952
6030
  "Failed to fetch widget config",
5953
- c.error
6031
+ _.error
5954
6032
  );
5955
6033
  return j.pollingIntervalsSeconds = {
5956
- session: ((s = c.data) == null ? void 0 : s.sessionPollingIntervalSeconds) || 10,
5957
- sessions: ((t = c.data) == null ? void 0 : t.sessionsPollingIntervalSeconds) || 60
6034
+ session: ((s = _.data) == null ? void 0 : s.sessionPollingIntervalSeconds) || 10,
6035
+ sessions: ((a = _.data) == null ? void 0 : a.sessionsPollingIntervalSeconds) || 60
5958
6036
  }, new j({
5959
6037
  config: e,
5960
- storage: a,
6038
+ storage: t,
5961
6039
  getClientCapabilities: o,
5962
6040
  getRequestConfig: r,
5963
- modes: c.data.modes || [],
6041
+ modes: _.data.modes || [],
5964
6042
  org: {
5965
- id: c.data.org.id,
5966
- name: c.data.org.name
6043
+ id: _.data.org.id,
6044
+ name: _.data.org.name
5967
6045
  },
5968
- agent: La(c.data)
6046
+ agent: Ua(_.data)
5969
6047
  });
5970
6048
  };
5971
6049
  let Z = j;
5972
- function Ya(i, e) {
6050
+ function et(i, e) {
5973
6051
  return i ? {
5974
6052
  streaming: i.streaming && (e == null ? void 0 : e.streaming) !== !1,
5975
6053
  toolActivity: i.toolActivity === "hidden" || (e == null ? void 0 : e.toolActivity) === "hidden" ? "hidden" : i.toolActivity === "status" || (e == null ? void 0 : e.toolActivity) === "status" ? "status" : "details",
5976
6054
  reasoning: i.reasoning && (e == null ? void 0 : e.reasoning) !== !1
5977
6055
  } : e;
5978
6056
  }
5979
- class Xa {
5980
- constructor({ attack: e, release: a }) {
5981
- this.value = 0, this.attack = e, this.release = a;
6057
+ class at {
6058
+ constructor({ attack: e, release: t }) {
6059
+ this.value = 0, this.attack = e, this.release = t;
5982
6060
  }
5983
6061
  next(e) {
5984
6062
  return this.value += (e - this.value) * (e > this.value ? this.attack : this.release), this.value;
@@ -5991,52 +6069,53 @@ const I = [
5991
6069
  "compact",
5992
6070
  "sidebar",
5993
6071
  "fullscreen"
5994
- ], Ua = new Set(
6072
+ ], Ha = new Set(
5995
6073
  I
5996
6074
  );
5997
6075
  function X(i) {
5998
- return Ua.has(i);
6076
+ return Ha.has(i);
5999
6077
  }
6000
- function Qa(i) {
6078
+ function tt(i) {
6001
6079
  if (!Array.isArray(i)) return I;
6002
- const e = [], a = /* @__PURE__ */ new Set();
6080
+ const e = [], t = /* @__PURE__ */ new Set();
6003
6081
  for (const o of i)
6004
- !X(o) || a.has(o) || (a.add(o), e.push(o));
6082
+ !X(o) || t.has(o) || (t.add(o), e.push(o));
6005
6083
  return e.length > 0 ? e : I;
6006
6084
  }
6007
- function et(i, e) {
6085
+ function st(i, e) {
6008
6086
  return X(i) && e.includes(i) ? i : e[0] ?? I[0];
6009
6087
  }
6010
- function at(i, e) {
6088
+ function ot(i, e) {
6011
6089
  return i === "left" || i === "right" ? i : e === "rtl" ? "left" : "right";
6012
6090
  }
6013
- function tt(i) {
6091
+ function nt(i) {
6014
6092
  return i === "docked" ? "docked" : "floating";
6015
6093
  }
6016
6094
  export {
6017
- pe as ConnectionAttemptUnavailableError,
6018
- ce as ConnectionRequestExpiredError,
6019
- Xa as DictationLevelSmoother,
6095
+ me as ConnectionAttemptUnavailableError,
6096
+ ue as ConnectionRequestExpiredError,
6097
+ at as DictationLevelSmoother,
6020
6098
  S as PrimitiveState,
6099
+ ie as UnreadCtx,
6021
6100
  Z as WidgetCtx,
6022
- Fa as WidgetInitializationError,
6023
- Na as buildSendMessageBody,
6101
+ Va as WidgetInitializationError,
6102
+ La as buildSendMessageBody,
6024
6103
  q as genUuid,
6025
- qa as getTranslation,
6026
- Wa as isAgentStreamKeepalive,
6027
- me as isExhaustive,
6104
+ Pa as getTranslation,
6105
+ Ya as isAgentStreamKeepalive,
6106
+ ke as isExhaustive,
6028
6107
  H as isRecord,
6029
- Ja as isRtlLanguage,
6030
- za as isSupportedLanguage,
6031
- $a as isTurnSteeredPart,
6108
+ Qa as isRtlLanguage,
6109
+ qa as isSupportedLanguage,
6110
+ Xa as isTurnSteeredPart,
6032
6111
  k as log,
6033
- Qa as normalizeCompanionLayouts,
6034
- Ya as resolveClientPresentation,
6035
- et as resolveCompanionDefaultLayout,
6036
- Ma as resolveConfigContext,
6037
- xa as resolveLanguage,
6038
- tt as resolveSidebarMode,
6039
- at as resolveSidebarSide,
6040
- Ea as translate
6112
+ tt as normalizeCompanionLayouts,
6113
+ et as resolveClientPresentation,
6114
+ st as resolveCompanionDefaultLayout,
6115
+ Na as resolveConfigContext,
6116
+ Aa as resolveLanguage,
6117
+ nt as resolveSidebarMode,
6118
+ ot as resolveSidebarSide,
6119
+ Ta as translate
6041
6120
  };
6042
6121
  //# sourceMappingURL=index.js.map