@opencx/widget-core 5.0.0-beta.7 → 5.0.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,126 +1,126 @@
1
- import { z as h } from "zod";
2
- import se from "openapi-fetch";
3
- import oe from "lodash.isequal";
1
+ import { z as m } from "zod";
2
+ import te from "openapi-fetch";
3
+ import se from "lodash.isequal";
4
4
  import { v4 as N } from "uuid";
5
- const Ga = (n) => n.type === "data-keepalive", $a = (n) => n.type === "data-turn-steered", F = h.object({ const: h.string(), title: h.string().optional() }), ne = h.object({
6
- type: h.enum(["string", "number", "integer", "boolean", "array"]),
7
- title: h.string().optional(),
8
- description: h.string().optional(),
9
- default: h.union([h.string(), h.number(), h.boolean(), h.array(h.string())]).optional(),
10
- enum: h.array(h.string()).optional(),
11
- oneOf: h.array(F).optional(),
12
- items: h.object({
13
- enum: h.array(h.string()).optional(),
14
- anyOf: h.array(F).optional()
5
+ const Wa = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn-steered", L = m.object({ const: m.string(), title: m.string().optional() }), oe = m.object({
6
+ type: m.enum(["string", "number", "integer", "boolean", "array"]),
7
+ title: m.string().optional(),
8
+ description: m.string().optional(),
9
+ default: m.union([m.string(), m.number(), m.boolean(), m.array(m.string())]).optional(),
10
+ enum: m.array(m.string()).optional(),
11
+ oneOf: m.array(L).optional(),
12
+ items: m.object({
13
+ enum: m.array(m.string()).optional(),
14
+ anyOf: m.array(L).optional()
15
15
  }).optional(),
16
- minItems: h.number().int().nonnegative().optional(),
17
- maxItems: h.number().int().nonnegative().optional(),
18
- minimum: h.number().optional(),
19
- maximum: h.number().optional(),
20
- minLength: h.number().optional(),
21
- maxLength: h.number().optional(),
22
- format: h.string().optional()
23
- }), ie = h.array(
24
- h.object({
25
- id: h.string(),
26
- serverId: h.string(),
27
- serverName: h.string(),
28
- expiresAt: h.number(),
29
- approvalKey: h.string().optional(),
30
- form: h.object({
31
- message: h.string(),
32
- requestedSchema: h.object({
33
- properties: h.record(h.string(), ne),
34
- required: h.array(h.string()).optional()
16
+ minItems: m.number().int().nonnegative().optional(),
17
+ maxItems: m.number().int().nonnegative().optional(),
18
+ minimum: m.number().optional(),
19
+ maximum: m.number().optional(),
20
+ minLength: m.number().optional(),
21
+ maxLength: m.number().optional(),
22
+ format: m.string().optional()
23
+ }), ne = m.array(
24
+ m.object({
25
+ id: m.string(),
26
+ serverId: m.string(),
27
+ serverName: m.string(),
28
+ expiresAt: m.number(),
29
+ approvalKey: m.string().optional(),
30
+ form: m.object({
31
+ message: m.string(),
32
+ requestedSchema: m.object({
33
+ properties: m.record(m.string(), oe),
34
+ required: m.array(m.string()).optional()
35
35
  })
36
36
  })
37
37
  })
38
- ), re = h.array(
39
- h.object({
40
- key: h.string(),
41
- serverId: h.string(),
42
- serverName: h.string(),
43
- message: h.string(),
44
- toolName: h.string()
38
+ ), ie = m.array(
39
+ m.object({
40
+ key: m.string(),
41
+ serverId: m.string(),
42
+ serverName: m.string(),
43
+ message: m.string(),
44
+ toolName: m.string()
45
45
  })
46
- ), O = "[opencx]", k = {
47
- warn: (n, ...e) => {
48
- console.warn(`${O} ${n}`, ...e);
46
+ ), F = "[opencx]", g = {
47
+ warn: (i, ...e) => {
48
+ console.warn(`${F} ${i}`, ...e);
49
49
  },
50
- error: (n, ...e) => {
51
- console.error(`${O} ${n}`, ...e);
50
+ error: (i, ...e) => {
51
+ console.error(`${F} ${i}`, ...e);
52
52
  }
53
- }, _e = (n) => {
54
- k.error("request failed", n.error);
55
- }, le = (n) => {
56
- const e = se({
57
- baseUrl: n.baseUrl
58
- }), t = {
59
- onRequest: n.onRequest,
60
- onResponse: n.onResponse,
61
- onError: n.onError || _e
53
+ }, re = (i) => {
54
+ g.error("request failed", i.error);
55
+ }, _e = (i) => {
56
+ const e = te({
57
+ baseUrl: i.baseUrl
58
+ }), a = {
59
+ onRequest: i.onRequest,
60
+ onResponse: i.onResponse,
61
+ onError: i.onError || re
62
62
  };
63
- return e.use(t), e;
63
+ return e.use(a), e;
64
64
  };
65
- class ce extends Error {
65
+ class le extends Error {
66
66
  constructor() {
67
67
  super("This connection request expired. Preparing a new request."), this.name = "ConnectionRequestExpiredError";
68
68
  }
69
69
  }
70
- class pe extends Error {
70
+ class ce extends Error {
71
71
  constructor() {
72
72
  super("This connection attempt is no longer available."), this.name = "ConnectionAttemptUnavailableError";
73
73
  }
74
74
  }
75
- const de = "/backend/widget/v5/chat/stream", ue = "/backend/widget/v5/chat/{sessionId}/stream", U = (n, e, t) => `${n.replace(/\/$/, "")}${t ? e.replace("{sessionId}", encodeURIComponent(t)) : e}`;
76
- class B {
75
+ const pe = "/backend/widget/v5/chat/stream", de = "/backend/widget/v5/chat/{sessionId}/stream", O = (i, e, a) => `${i.replace(/\/$/, "")}${a ? e.replace("{sessionId}", encodeURIComponent(a)) : e}`;
76
+ class U {
77
77
  constructor({ config: e }) {
78
78
  var r, l;
79
79
  this.userToken = null, this.constructClientOptions = (s) => {
80
- const a = this.config.apiUrl || "https://api.open.cx", i = {
80
+ const t = this.config.apiUrl || "https://api.open.cx", n = {
81
81
  "X-Bot-Token": this.config.token,
82
82
  "Content-Type": "application/json",
83
83
  Accept: "application/json",
84
84
  Authorization: s ? `Bearer ${s}` : void 0
85
85
  };
86
- return { baseUrl: a, headers: i };
86
+ return { baseUrl: t, headers: n };
87
87
  }, this.createOpenAPIClient = ({
88
88
  baseUrl: s,
89
- headers: a
90
- }) => le({
89
+ headers: t
90
+ }) => _e({
91
91
  baseUrl: s,
92
- onRequest: ({ request: i }) => {
93
- Object.entries(a).forEach(([c, d]) => {
94
- d && i.headers.set(c, d);
92
+ onRequest: ({ request: n }) => {
93
+ Object.entries(t).forEach(([c, d]) => {
94
+ d && n.headers.set(c, d);
95
95
  });
96
96
  }
97
97
  }), this.listApprovalPreferences = async () => {
98
- const { baseUrl: s, headers: a } = this.getStreamAuthContext(), i = await fetch(
98
+ const { baseUrl: s, headers: t } = this.getStreamAuthContext(), n = await fetch(
99
99
  `${s}/backend/widget/v5/connections/approval-preferences`,
100
- { headers: a }
100
+ { headers: t }
101
101
  );
102
- if (!i.ok) throw new Error("Could not load permissions.");
103
- return re.parse(await i.json());
104
- }, this.revokeApprovalPreference = async (s, a) => {
105
- const { baseUrl: i, headers: c } = this.getStreamAuthContext();
102
+ if (!n.ok) throw new Error("Could not load permissions.");
103
+ return ie.parse(await n.json());
104
+ }, this.revokeApprovalPreference = async (s, t) => {
105
+ const { baseUrl: n, headers: c } = this.getStreamAuthContext();
106
106
  if (!(await fetch(
107
- `${i}/backend/widget/v5/connections/${encodeURIComponent(s)}/approval-preferences/${encodeURIComponent(a)}`,
107
+ `${n}/backend/widget/v5/connections/${encodeURIComponent(s)}/approval-preferences/${encodeURIComponent(t)}`,
108
108
  { method: "DELETE", headers: c }
109
109
  )).ok) throw new Error("Could not reset permission.");
110
- }, this.listElicitations = async (s, a) => {
111
- const { baseUrl: i, headers: c } = this.getStreamAuthContext(), d = await fetch(
112
- `${i}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}`,
113
- { headers: c, signal: a }
110
+ }, this.listElicitations = async (s, t) => {
111
+ const { baseUrl: n, headers: c } = this.getStreamAuthContext(), d = await fetch(
112
+ `${n}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}`,
113
+ { headers: c, signal: t }
114
114
  );
115
115
  if (!d.ok) throw new Error("Could not load the request.");
116
- return ie.parse(await d.json());
117
- }, this.answerElicitation = async (s, a, i) => {
116
+ return ne.parse(await d.json());
117
+ }, this.answerElicitation = async (s, t, n) => {
118
118
  const { baseUrl: c, headers: d } = this.getStreamAuthContext(), _ = await fetch(
119
- `${c}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}/${encodeURIComponent(a)}`,
119
+ `${c}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}/${encodeURIComponent(t)}`,
120
120
  {
121
121
  method: "POST",
122
122
  headers: { ...d, "Content-Type": "application/json" },
123
- body: JSON.stringify(i)
123
+ body: JSON.stringify(n)
124
124
  }
125
125
  );
126
126
  if (!_.ok)
@@ -128,152 +128,160 @@ class B {
128
128
  _.status === 400 ? "Check your answers and try again." : "This request has ended. Ask the agent to try again."
129
129
  );
130
130
  }, this.listConnections = async (s) => {
131
- const { data: a, error: i } = await this.client.GET(
131
+ const { data: t, error: n } = await this.client.GET(
132
132
  "/backend/widget/v5/connections",
133
133
  { signal: s }
134
134
  );
135
- if (i || !a)
135
+ if (n || !t)
136
136
  throw new Error("Could not load connections. Sign in and try again.");
137
- return a;
138
- }, this.startConnection = async (s, a, i) => {
137
+ return t;
138
+ }, this.startConnection = async (s, t, n) => {
139
139
  const { data: c, error: d, response: _ } = await this.client.POST(
140
140
  "/backend/widget/v5/connections/{serverId}/start",
141
141
  {
142
142
  params: { path: { serverId: s } },
143
- body: { request_id: a },
144
- signal: i
143
+ body: { request_id: t },
144
+ signal: n
145
145
  }
146
146
  );
147
- if (_.status === 410) throw new ce();
147
+ if (_.status === 410) throw new le();
148
148
  if (_.status === 404)
149
149
  throw new Error("This connection request is no longer available.");
150
150
  if (d || !c)
151
151
  throw new Error("Could not start this connection. Please try again.");
152
152
  return c;
153
- }, this.getConnectionAttempt = async (s, a, i) => {
153
+ }, this.getConnectionAttempt = async (s, t, n) => {
154
154
  const { data: c, error: d, response: _ } = await this.client.GET(
155
155
  "/backend/widget/v5/connections/{serverId}/attempts/{attemptId}",
156
156
  {
157
- params: { path: { serverId: s, attemptId: a } },
158
- signal: i
157
+ params: { path: { serverId: s, attemptId: t } },
158
+ signal: n
159
159
  }
160
160
  );
161
161
  if ([401, 403, 404].includes(_.status))
162
- throw new pe();
162
+ throw new ce();
163
163
  if (d || !c)
164
164
  throw new Error(`Could not check the connection (${_.status}).`);
165
165
  return c.status;
166
166
  }, this.disconnectConnection = async (s) => {
167
- const { error: a } = await this.client.DELETE(
167
+ const { error: t } = await this.client.DELETE(
168
168
  "/backend/widget/v5/connections/{serverId}",
169
169
  {
170
170
  params: { path: { serverId: s } }
171
171
  }
172
172
  );
173
- if (a) throw new Error("Could not disconnect. Please try again.");
173
+ if (t) throw new Error("Could not disconnect. Please try again.");
174
174
  }, this.setAuthToken = (s) => {
175
175
  this.userToken = s;
176
- const { baseUrl: a, headers: i } = this.constructClientOptions(s);
177
- this.client = this.createOpenAPIClient({ baseUrl: a, headers: i });
176
+ const { baseUrl: t, headers: n } = this.constructClientOptions(s);
177
+ this.client = this.createOpenAPIClient({ baseUrl: t, headers: n });
178
178
  }, this.getStreamAuthContext = () => {
179
- const { baseUrl: s, headers: a } = this.constructClientOptions(this.userToken), i = {};
180
- for (const [c, d] of Object.entries(a))
181
- typeof d == "string" && (["content-type", "accept"].includes(c.toLowerCase()) || (i[c] = d));
182
- return { baseUrl: s, headers: i };
179
+ const { baseUrl: s, headers: t } = this.constructClientOptions(this.userToken), n = {};
180
+ for (const [c, d] of Object.entries(t))
181
+ typeof d == "string" && (["content-type", "accept"].includes(c.toLowerCase()) || (n[c] = d));
182
+ return { baseUrl: s, headers: n };
183
183
  }, this.getStreamTransportOptions = () => {
184
- const { baseUrl: s, headers: a } = this.getStreamAuthContext();
184
+ const { baseUrl: s, headers: t } = this.getStreamAuthContext();
185
185
  return {
186
- api: U(s, de),
187
- reconnectApi: (i) => U(s, ue, i),
188
- headers: a
186
+ api: O(s, pe),
187
+ reconnectApi: (n) => O(s, de, n),
188
+ headers: t
189
189
  };
190
190
  }, this.stopStream = async (s) => {
191
- const { response: a } = await this.client.POST(
191
+ const { response: t } = await this.client.POST(
192
192
  "/backend/widget/v5/chat/{sessionId}/stop",
193
193
  { params: { path: { sessionId: s } } }
194
194
  );
195
- if (!a.ok)
196
- throw new Error(`Failed to stop stream: ${a.status}`);
197
- }, this.getAgentTurnMessages = async (s, a) => {
198
- const { data: i, response: c } = await this.client.GET(
195
+ if (!t.ok)
196
+ throw new Error(`Failed to stop stream: ${t.status}`);
197
+ }, this.sendPageReply = async (s, t) => {
198
+ try {
199
+ await this.client.POST("/backend/widget/v5/chat/{sessionId}/page-reply", {
200
+ params: { path: { sessionId: s } },
201
+ body: t
202
+ });
203
+ } catch {
204
+ }
205
+ }, this.getAgentTurnMessages = async (s, t) => {
206
+ const { data: n, response: c } = await this.client.GET(
199
207
  "/backend/widget/v5/chat/{sessionId}/messages",
200
208
  {
201
209
  params: {
202
210
  path: { sessionId: s },
203
211
  query: {
204
- toolActivity: a == null ? void 0 : a.toolActivity,
205
- reasoning: (a == null ? void 0 : a.reasoning) === void 0 ? void 0 : a.reasoning ? "true" : "false"
212
+ toolActivity: t == null ? void 0 : t.toolActivity,
213
+ reasoning: (t == null ? void 0 : t.reasoning) === void 0 ? void 0 : t.reasoning ? "true" : "false"
206
214
  }
207
215
  }
208
216
  }
209
217
  );
210
- return i ? {
211
- ...i,
212
- handled_connection_request_ids: i.handled_connection_request_ids ?? []
213
- } : (k.warn("agent turn messages fetch failed", c.status), null);
218
+ return n ? {
219
+ ...n,
220
+ handled_connection_request_ids: n.handled_connection_request_ids ?? []
221
+ } : (g.warn("agent turn messages fetch failed", c.status), null);
214
222
  }, this.createDictationSession = async ({
215
223
  language: s
216
224
  }) => {
217
- const { data: a, response: i } = await this.client.POST(
225
+ const { data: t, response: n } = await this.client.POST(
218
226
  "/backend/widget/v5/dictation/sessions",
219
227
  { body: s ? { language: s } : {} }
220
228
  );
221
- if (!a)
222
- throw new Error(`Failed to start dictation: ${i.status}`);
223
- return a;
229
+ if (!t)
230
+ throw new Error(`Failed to start dictation: ${n.status}`);
231
+ return t;
224
232
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
225
233
  params: {
226
234
  header: { "x-bot-token": this.config.token }
227
235
  }
228
- }), this.sendMessage = async (s, a) => await this.client.POST("/backend/widget/v2/chat/send", {
236
+ }), this.sendMessage = async (s, t) => await this.client.POST("/backend/widget/v2/chat/send", {
229
237
  body: s,
230
- signal: a
238
+ signal: t
231
239
  }), this.createUnverifiedContact = async (s) => await this.client.POST(
232
240
  "/backend/widget/v2/contact/create-unverified",
233
241
  {
234
242
  params: { header: { "x-bot-token": this.config.token } },
235
243
  body: s
236
244
  }
237
- ), this.createSession = async (s, a) => await this.client.POST("/backend/widget/v2/create-session", {
245
+ ), this.createSession = async (s, t) => await this.client.POST("/backend/widget/v2/create-session", {
238
246
  body: s,
239
- signal: a
247
+ signal: t
240
248
  }), this.pollSessionAndHistory = async ({
241
249
  sessionId: s,
242
- abortSignal: a
250
+ abortSignal: t
243
251
  }) => await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
244
252
  params: { path: { sessionId: s } },
245
- signal: a
253
+ signal: t
246
254
  }), this.getSessions = async ({
247
255
  cursor: s,
248
- filters: a,
249
- abortSignal: i
256
+ filters: t,
257
+ abortSignal: n
250
258
  }) => await this.client.GET("/backend/widget/v2/sessions", {
251
259
  params: {
252
260
  query: {
253
261
  offset: s,
254
- filters: JSON.stringify(a)
262
+ filters: JSON.stringify(t)
255
263
  }
256
264
  },
257
- signal: i
265
+ signal: n
258
266
  }), this.uploadFile = async ({
259
267
  file: s,
260
- abortSignal: a,
261
- onProgress: i
268
+ abortSignal: t,
269
+ onProgress: n
262
270
  }) => new Promise((c, d) => {
263
271
  var f;
264
272
  const _ = new FormData();
265
273
  _.append("file", s);
266
274
  const p = new XMLHttpRequest();
267
- if (a && (a.addEventListener("abort", () => {
275
+ if (t && (t.addEventListener("abort", () => {
268
276
  p.abort(), d(new DOMException("Aborted", "AbortError"));
269
- }), a.aborted)) {
277
+ }), t.aborted)) {
270
278
  d(new DOMException("Aborted", "AbortError"));
271
279
  return;
272
280
  }
273
281
  p.upload.addEventListener("progress", (b) => {
274
- if (b.lengthComputable && i) {
275
- const w = Math.round(b.loaded / b.total * 100);
276
- i(w);
282
+ if (b.lengthComputable && n) {
283
+ const y = Math.round(b.loaded / b.total * 100);
284
+ n(y);
277
285
  }
278
286
  }), p.addEventListener("load", () => {
279
287
  if (p.status >= 200 && p.status < 300)
@@ -290,47 +298,47 @@ class B {
290
298
  }), p.addEventListener("timeout", () => {
291
299
  d(new Error("Upload timed out"));
292
300
  });
293
- const { baseUrl: u } = this.constructClientOptions(this.userToken), g = `${u}/backend/widget/v2/upload`;
294
- 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(_);
295
- }), 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", {
301
+ const { baseUrl: u } = this.constructClientOptions(this.userToken), k = `${u}/backend/widget/v2/upload`;
302
+ p.open("POST", k), 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}`) : g.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", {
296
304
  body: s,
297
- signal: a
305
+ signal: t
298
306
  }), this.createStateCheckpoint = async (s) => await this.client.POST("/backend/widget/v2/checkpoint", {
299
307
  body: s
300
308
  }), 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;
301
- const { baseUrl: t, headers: o } = this.constructClientOptions(
309
+ const { baseUrl: a, headers: o } = this.constructClientOptions(
302
310
  (l = e.user) == null ? void 0 : l.token
303
311
  );
304
- this.client = this.createOpenAPIClient({ baseUrl: t, headers: o });
312
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: o });
305
313
  }
306
314
  }
307
- function me(n, e) {
308
- k.error(`missing case for ${n} in ${e}`);
315
+ function ue(i, e) {
316
+ g.error(`missing case for ${i} in ${e}`);
309
317
  }
310
318
  class S {
311
319
  constructor(e) {
312
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (t) => {
313
- oe(this.state, t) || (this.state = t, this.notifySubscribers(t));
314
- }, this.setPartial = (t) => {
315
- if (t == null) return;
316
- const o = { ...this.state, ...t };
320
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
321
+ se(this.state, a) || (this.state = a, this.notifySubscribers(a));
322
+ }, this.setPartial = (a) => {
323
+ if (a == null) return;
324
+ const o = { ...this.state, ...a };
317
325
  this.set(o);
318
326
  }, this.reset = () => {
319
327
  this.set(this.initialState);
320
- }, this.notifySubscribers = (t) => {
328
+ }, this.notifySubscribers = (a) => {
321
329
  Array.from(this.subscribers).forEach((r) => {
322
330
  try {
323
- r(t);
331
+ r(a);
324
332
  } catch (l) {
325
- k.error("state subscriber threw", l);
333
+ g.error("state subscriber threw", l);
326
334
  }
327
335
  });
328
- }, this.subscribe = (t) => (this.subscribers.add(t), () => {
329
- this.subscribers.delete(t);
336
+ }, this.subscribe = (a) => (this.subscribers.add(a), () => {
337
+ this.subscribers.delete(a);
330
338
  }), this.state = e, this.initialState = e;
331
339
  }
332
340
  }
333
- class G {
341
+ class Z {
334
342
  constructor() {
335
343
  this.state = new S({
336
344
  isPolling: !1,
@@ -338,7 +346,7 @@ class G {
338
346
  }), this.abortController = new AbortController(), this.reset = () => {
339
347
  var e;
340
348
  this.abortController.abort("Resetting poller"), (e = this.stopPolling) == null || e.call(this), this.stopPolling = null;
341
- }, this.stopPolling = null, this.startPolling = (e, t) => {
349
+ }, this.stopPolling = null, this.startPolling = (e, a) => {
342
350
  if (this.stopPolling) return;
343
351
  const o = [], r = async () => {
344
352
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
@@ -347,11 +355,11 @@ class G {
347
355
  } catch (l) {
348
356
  if (this.abortController.signal.aborted)
349
357
  return;
350
- k.error("failed to poll", l), this.state.setPartial({ isError: !0 });
358
+ g.error("failed to poll", l), this.state.setPartial({ isError: !0 });
351
359
  } finally {
352
360
  this.state.setPartial({ isPolling: !1 });
353
361
  }
354
- this.abortController.signal.aborted || o.push(setTimeout(r, t));
362
+ this.abortController.signal.aborted || o.push(setTimeout(r, a));
355
363
  };
356
364
  r(), this.stopPolling = () => {
357
365
  o.forEach(clearTimeout), this.state.reset();
@@ -359,29 +367,29 @@ class G {
359
367
  };
360
368
  }
361
369
  }
362
- function $(n) {
370
+ function W(i) {
363
371
  try {
364
- const e = n();
365
- return e instanceof Promise ? e.then((t) => ({ data: t })).catch((t) => ({ error: t })) : { data: e };
372
+ const e = i();
373
+ return e instanceof Promise ? e.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: e };
366
374
  } catch (e) {
367
375
  return { error: e };
368
376
  }
369
377
  }
370
- class he {
378
+ class me {
371
379
  constructor({
372
380
  api: e,
373
- config: t,
381
+ config: a,
374
382
  sessionCtx: o,
375
383
  messageCtx: r,
376
384
  sessionPollingIntervalSeconds: l
377
385
  }) {
378
- this.poller = new G(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.subscriptions = [], this.reconcilingSessionId = null, this.registerPolling = () => {
386
+ this.poller = new Z(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.subscriptions = [], this.reconcilingSessionId = null, this.registerPolling = () => {
379
387
  this.subscriptions.push(
380
388
  this.sessionCtx.sessionState.subscribe(({ session: s }) => {
381
- s != null && s.id ? this.poller.startPolling(async (a) => {
389
+ s != null && s.id ? this.poller.startPolling(async (t) => {
382
390
  this.fetchSessionAndHistory({
383
391
  sessionId: s.id,
384
- abortSignal: a
392
+ abortSignal: t
385
393
  });
386
394
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
387
395
  })
@@ -393,8 +401,8 @@ class he {
393
401
  sessionId: s.id,
394
402
  abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
395
403
  });
396
- } catch (a) {
397
- this.fetchSessionAndFullHistoryAbortController.signal.aborted || k.error("failed to fetch session and full history", a);
404
+ } catch (t) {
405
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || g.error("failed to fetch session and full history", t);
398
406
  }
399
407
  else
400
408
  this.fetchSessionAndFullHistoryAbortController.abort();
@@ -408,24 +416,24 @@ class he {
408
416
  this.poller.reset(), this.fetchSessionAndFullHistoryAbortController.abort(), this.reconcileAbortController.abort(), this.reconcilingSessionId = null, this.subscriptions.forEach((s) => s()), this.subscriptions = [];
409
417
  }, this.reconcileAfterStream = async (s) => {
410
418
  this.reconcileAbortController.abort(), this.reconcileAbortController = new AbortController();
411
- const { signal: a } = this.reconcileAbortController;
419
+ const { signal: t } = this.reconcileAbortController;
412
420
  this.reconcilingSessionId = s;
413
421
  try {
414
- await this.fetchSessionAndHistory({ sessionId: s, abortSignal: a });
415
- } catch (i) {
416
- if (!a.aborted) throw i;
422
+ await this.fetchSessionAndHistory({ sessionId: s, abortSignal: t });
423
+ } catch (n) {
424
+ if (!t.aborted) throw n;
417
425
  } finally {
418
426
  this.reconcilingSessionId === s && (this.reconcilingSessionId = null);
419
427
  }
420
428
  }, this.fetchSessionAndHistory = async ({
421
429
  sessionId: s,
422
- abortSignal: a
430
+ abortSignal: t
423
431
  }) => {
424
- const i = this.messageCtx.state.get().messages.length === 0;
425
- i && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
432
+ const n = this.messageCtx.state.get().messages.length === 0;
433
+ n && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
426
434
  const { data: c } = await this.api.pollSessionAndHistory({
427
435
  sessionId: s,
428
- abortSignal: a
436
+ abortSignal: t
429
437
  });
430
438
  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) {
431
439
  const d = this.messageCtx.state.get().messages, _ = c.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
@@ -434,7 +442,7 @@ class he {
434
442
  if (_.length > 0)
435
443
  if (this.messageCtx.state.setPartial({
436
444
  messages: [...d, ..._]
437
- }), i)
445
+ }), n)
438
446
  this.messageCtx.markAsDispatchedToOnMessageReceivedHook(
439
447
  _.map((p) => p.id)
440
448
  );
@@ -444,23 +452,24 @@ class he {
444
452
  }
445
453
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
446
454
  }, this.mapHistoryToMessage = (s) => {
447
- var i;
448
- const a = {
455
+ var n;
456
+ const t = {
449
457
  id: s.publicId,
450
458
  timestamp: s.sentAt || "",
451
459
  attachments: s.attachments || void 0
452
460
  };
453
461
  if (s.sender.kind === "user")
454
462
  return {
455
- ...a,
463
+ ...t,
456
464
  type: "USER",
465
+ deliveredAt: t.timestamp,
457
466
  content: s.content.text || "",
458
467
  // Backend field name (schema.ts) → widget vocabulary.
459
468
  markedElements: s.pickedElements
460
469
  };
461
470
  if (s.sender.kind === "agent")
462
471
  return {
463
- ...a,
472
+ ...t,
464
473
  type: "AGENT",
465
474
  component: "agent_message",
466
475
  data: {
@@ -474,17 +483,18 @@ class he {
474
483
  avatar: s.sender.avatar || null,
475
484
  id: null,
476
485
  isAi: !1
477
- }
486
+ },
487
+ ...this.constructReplyTo(s)
478
488
  };
479
489
  if (s.sender.kind === "ai") {
480
490
  const c = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
481
491
  return {
482
- ...a,
492
+ ...t,
483
493
  type: "AI",
484
494
  component: "bot_message",
485
495
  agent: {
486
496
  id: null,
487
- name: ((i = this.config.bot) == null ? void 0 : i.name) || "",
497
+ name: ((n = this.config.bot) == null ? void 0 : n.name) || "",
488
498
  isAi: !0,
489
499
  // Do not set avatarUrl from config here... let it be taken from the config at render time
490
500
  avatarUrl: null,
@@ -496,7 +506,8 @@ class he {
496
506
  name: c.actionName,
497
507
  data: this.extractActionResult(c)
498
508
  } : void 0
499
- }
509
+ },
510
+ ...this.constructReplyTo(s)
500
511
  };
501
512
  }
502
513
  if (s.sender.kind === "system") {
@@ -504,6 +515,16 @@ class he {
504
515
  return c === null ? null : { ...c };
505
516
  }
506
517
  return null;
518
+ }, this.constructReplyTo = (s) => {
519
+ if (!s.replyTo) return {};
520
+ const { publicId: t, text: n, sender: c } = s.replyTo;
521
+ return {
522
+ replyTo: {
523
+ id: t,
524
+ text: n,
525
+ sender: c
526
+ }
527
+ };
507
528
  }, this.constructSystemMessage = (s) => {
508
529
  if (!s || !s.systemMessagePayload) return null;
509
530
  switch (s.systemMessagePayload.type) {
@@ -542,26 +563,26 @@ class he {
542
563
  case "none":
543
564
  return null;
544
565
  default:
545
- return me(
566
+ return ue(
546
567
  s.systemMessagePayload,
547
568
  this.constructSystemMessage.name
548
569
  ), null;
549
570
  }
550
571
  }, this.extractActionResult = (s) => {
551
- const a = s.result;
552
- if (a === null || typeof a != "object") return a;
553
- if ("responseBodyText" in a && typeof a.responseBodyText == "string") {
554
- const i = a.responseBodyText, c = $(() => JSON.parse(i)).data;
572
+ const t = s.result;
573
+ if (t === null || typeof t != "object") return t;
574
+ if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
575
+ const n = t.responseBodyText, c = W(() => JSON.parse(n)).data;
555
576
  if (c) return c;
556
577
  }
557
578
  return s.result;
558
- }, this.api = e, this.config = t, this.sessionCtx = o, this.messageCtx = r, this.sessionPollingIntervalSeconds = l, this.registerPolling();
579
+ }, this.api = e, this.config = a, this.sessionCtx = o, this.messageCtx = r, this.sessionPollingIntervalSeconds = l, this.registerPolling();
559
580
  }
560
581
  }
561
- class ge {
582
+ class he {
562
583
  constructor({
563
584
  config: e,
564
- api: t,
585
+ api: a,
565
586
  storageCtx: o
566
587
  }) {
567
588
  var r;
@@ -569,25 +590,25 @@ class ge {
569
590
  var l;
570
591
  return !!(!((l = this.state.get().contact) != null && l.token) && this.config.collectUserData);
571
592
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
572
- var l, s, a, i, c, d, _, p, u, m, g, v, f, b;
593
+ var l, s, t, n, c, d, _, p, u, h, k, v, f, b;
573
594
  if (!((l = this.config.user) != null && l.token)) {
574
- if (this.config.collectUserData && !((a = (s = this.config.user) == null ? void 0 : s.data) != null && a.email)) {
575
- if ((i = this.config.extraDataCollectionFields) != null && i.length)
595
+ if (this.config.collectUserData && !((t = (s = this.config.user) == null ? void 0 : s.data) != null && t.email)) {
596
+ if ((n = this.config.extraDataCollectionFields) != null && n.length)
576
597
  return;
577
- const w = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
578
- w && await this.setUnverifiedContact(w);
598
+ const y = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
599
+ y && await this.setUnverifiedContact(y);
579
600
  return;
580
601
  }
581
602
  if (!((_ = (d = this.config.user) == null ? void 0 : d.data) != null && _.email)) {
582
- const w = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
583
- if (w) {
584
- await this.setUnverifiedContact(w);
603
+ const y = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
604
+ if (y) {
605
+ await this.setUnverifiedContact(y);
585
606
  return;
586
607
  }
587
608
  }
588
609
  await this.createUnverifiedContact({
589
- email: (m = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : m.email,
590
- non_verified_name: (v = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : v.name,
610
+ email: (h = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : h.email,
611
+ non_verified_name: (v = (k = this.config.user) == null ? void 0 : k.data) == null ? void 0 : v.name,
591
612
  non_verified_custom_data: (b = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : b.customData
592
613
  });
593
614
  }
@@ -598,36 +619,36 @@ class ge {
598
619
  isCreatingUnverifiedContact: !0,
599
620
  isErrorCreatingUnverifiedContact: !1
600
621
  });
601
- const { data: a } = await this.api.createUnverifiedContact(l);
602
- a != null && a.token ? await this.setUnverifiedContact(a.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
603
- } catch (a) {
604
- this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), k.error("failed to create an unverified contact", {
605
- _e: a instanceof Error ? a.message : String(a)
622
+ const { data: t } = await this.api.createUnverifiedContact(l);
623
+ t != null && t.token ? await this.setUnverifiedContact(t.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
624
+ } catch (t) {
625
+ this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), g.error("failed to create an unverified contact", {
626
+ _e: t instanceof Error ? t.message : String(t)
606
627
  });
607
628
  } finally {
608
629
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
609
630
  }
610
631
  }, this.recoverFromStaleToken = async () => {
611
- var l, s, a, i, c, d, _, p, u, m;
632
+ var l, s, t, n, c, d, _, p, u, h;
612
633
  if ((l = this.config.user) != null && l.token) return !1;
613
634
  this.api.setAuthToken(""), this.state.setPartial({ contact: null });
614
635
  try {
615
- await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((a = this.storageCtx) == null ? void 0 : a.clearActiveSessionId());
616
- } catch (g) {
617
- k.warn("failed to clear a stale contact token", {
618
- error: g instanceof Error ? g.message : String(g)
636
+ await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((t = this.storageCtx) == null ? void 0 : t.clearActiveSessionId());
637
+ } catch (k) {
638
+ g.warn("failed to clear a stale contact token", {
639
+ error: k instanceof Error ? k.message : String(k)
619
640
  });
620
641
  }
621
642
  return await this.createUnverifiedContact({
622
- email: (c = (i = this.config.user) == null ? void 0 : i.data) == null ? void 0 : c.email,
643
+ email: (c = (n = this.config.user) == null ? void 0 : n.data) == null ? void 0 : c.email,
623
644
  non_verified_name: (_ = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : _.name,
624
645
  non_verified_custom_data: (u = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : u.customData
625
- }), !!((m = this.state.get().contact) != null && m.token);
646
+ }), !!((h = this.state.get().contact) != null && h.token);
626
647
  }, this.setUnverifiedContact = async (l) => {
627
- var i, c, d, _;
628
- const s = await ((i = this.storageCtx) == null ? void 0 : i.getExternalContactId()), a = ((c = this.config.user) == null ? void 0 : c.externalId) || s || N();
629
- this.api.setAuthToken(l), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(l)), await ((_ = this.storageCtx) == null ? void 0 : _.setExternalContactId(a)), this.state.setPartial({ contact: { token: l, externalId: a } });
630
- }, this.config = e, this.storageCtx = o, this.api = t, this.state = new S({
648
+ var n, c, d, _;
649
+ const s = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), t = ((c = this.config.user) == null ? void 0 : c.externalId) || s || N();
650
+ this.api.setAuthToken(l), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(l)), await ((_ = this.storageCtx) == null ? void 0 : _.setExternalContactId(t)), this.state.setPartial({ contact: { token: l, externalId: t } });
651
+ }, this.config = e, this.storageCtx = o, this.api = a, this.state = new S({
631
652
  contact: (r = e.user) != null && r.token ? {
632
653
  token: e.user.token,
633
654
  // Set optional externalId from config... not local storage
@@ -639,10 +660,10 @@ class ge {
639
660
  }), this.autoCreateUnverifiedUserIfNotExists();
640
661
  }
641
662
  }
642
- class ke {
663
+ class ge {
643
664
  constructor(e) {
644
- this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (t) => {
645
- const o = t.map(
665
+ this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (a) => {
666
+ const o = a.map(
646
667
  (r) => ({
647
668
  file: r,
648
669
  id: N(),
@@ -651,25 +672,25 @@ class ke {
651
672
  })
652
673
  );
653
674
  this.state.set([...this.state.get(), ...o]), o.forEach((r) => void this.upload(r));
654
- }, this.cancel = (t) => {
675
+ }, this.cancel = (a) => {
655
676
  var o;
656
- (o = this.controllers.get(t)) == null || o.abort(), this.controllers.delete(t), this.state.set(this.state.get().filter((r) => r.id !== t));
677
+ (o = this.controllers.get(a)) == null || o.abort(), this.controllers.delete(a), this.state.set(this.state.get().filter((r) => r.id !== a));
657
678
  }, this.reset = () => {
658
- this.controllers.forEach((t) => t.abort()), this.controllers.clear(), this.state.reset();
679
+ this.controllers.forEach((a) => a.abort()), this.controllers.clear(), this.state.reset();
659
680
  };
660
681
  }
661
- update(e, t) {
682
+ update(e, a) {
662
683
  this.state.set(
663
- this.state.get().map((o) => o.id === e ? { ...o, ...t } : o)
684
+ this.state.get().map((o) => o.id === e ? { ...o, ...a } : o)
664
685
  );
665
686
  }
666
687
  async upload(e) {
667
- const t = new AbortController();
668
- this.controllers.set(e.id, t), this.update(e.id, { status: "uploading" });
688
+ const a = new AbortController();
689
+ this.controllers.set(e.id, a), this.update(e.id, { status: "uploading" });
669
690
  try {
670
691
  const o = await this.api.uploadFile({
671
692
  file: e.file,
672
- abortSignal: t.signal,
693
+ abortSignal: a.signal,
673
694
  onProgress: (r) => this.update(e.id, { progress: r })
674
695
  });
675
696
  this.update(e.id, {
@@ -678,7 +699,7 @@ class ke {
678
699
  progress: 100
679
700
  });
680
701
  } catch (o) {
681
- t.signal.aborted || this.update(e.id, {
702
+ a.signal.aborted || this.update(e.id, {
682
703
  status: "error",
683
704
  progress: 0,
684
705
  error: o instanceof Error ? o.message : "Upload failed"
@@ -688,13 +709,13 @@ class ke {
688
709
  }
689
710
  }
690
711
  }
691
- function x() {
712
+ function q() {
692
713
  return N();
693
714
  }
694
- class be {
715
+ class ke {
695
716
  constructor({
696
717
  api: e,
697
- sessionCtx: t,
718
+ sessionCtx: a,
698
719
  messageCtx: o
699
720
  }) {
700
721
  this.submitCsat = async (r) => {
@@ -702,7 +723,7 @@ class be {
702
723
  const l = (c = this.sessionCtx.sessionState.get().session) == null ? void 0 : c.id;
703
724
  if (!l)
704
725
  return { data: null, error: "No session id found" };
705
- const s = x();
726
+ const s = q();
706
727
  this.messageCtx.state.setPartial({
707
728
  messages: [
708
729
  ...this.messageCtx.state.get().messages,
@@ -720,16 +741,16 @@ class be {
720
741
  }
721
742
  ]
722
743
  });
723
- const { data: a, error: i } = await this.api.submitCsat({
744
+ const { data: t, error: n } = await this.api.submitCsat({
724
745
  ...r,
725
746
  system_message_uuid: s,
726
747
  session_id: l
727
748
  });
728
- return { data: a, error: i };
729
- }, this.api = e, this.sessionCtx = t, this.messageCtx = o;
749
+ return { data: t, error: n };
750
+ }, this.api = e, this.sessionCtx = a, this.messageCtx = o;
730
751
  }
731
752
  }
732
- const ve = [
753
+ const be = [
733
754
  {
734
755
  action: "newparagraph",
735
756
  phrases: {
@@ -804,7 +825,7 @@ const ve = [
804
825
  it: ["invia messaggio"]
805
826
  }
806
827
  }
807
- ], fe = [
828
+ ], ve = [
808
829
  "en",
809
830
  "es",
810
831
  "fr",
@@ -812,25 +833,25 @@ const ve = [
812
833
  "pt",
813
834
  "it"
814
835
  ];
815
- function ye(n) {
816
- return fe.includes(n);
836
+ function fe(i) {
837
+ return ve.includes(i);
817
838
  }
818
- function we(n) {
819
- return n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
839
+ function ye(i) {
840
+ return i.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
820
841
  }
821
- function je(n) {
822
- const e = ve.flatMap(
823
- (r) => n.flatMap(
842
+ function we(i) {
843
+ const e = be.flatMap(
844
+ (r) => i.flatMap(
824
845
  (l) => r.phrases[l].map((s) => ({ phrase: s, action: r.action }))
825
846
  )
826
- ), t = e.map((r) => we(r.phrase)).sort((r, l) => l.length - r.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
847
+ ), a = e.map((r) => ye(r.phrase)).sort((r, l) => l.length - r.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
827
848
  return {
828
849
  regex: new RegExp(
829
- `${o}(${t})` + String.raw`([.,!?;:])(?=\s|$)`,
850
+ `${o}(${a})` + String.raw`([.,!?;:])(?=\s|$)`,
830
851
  "giu"
831
852
  ),
832
853
  finalRegex: new RegExp(
833
- `${o}(${t})` + String.raw`([.,!?;:]?)(?=\s|$)`,
854
+ `${o}(${a})` + String.raw`([.,!?;:]?)(?=\s|$)`,
834
855
  "giu"
835
856
  ),
836
857
  phraseToAction: new Map(
@@ -839,77 +860,77 @@ function je(n) {
839
860
  longestPhrase: Math.max(...e.map((r) => r.phrase.length))
840
861
  };
841
862
  }
842
- const V = /* @__PURE__ */ new Map();
843
- function I(n) {
844
- const e = n && ye(n) && n !== "en" ? n : null, t = e ?? "en";
845
- let o = V.get(t);
846
- return o || (o = je(e ? ["en", e] : ["en"]), V.set(t, o)), o;
863
+ const B = /* @__PURE__ */ new Map();
864
+ function M(i) {
865
+ const e = i && fe(i) && i !== "en" ? i : null, a = e ?? "en";
866
+ let o = B.get(a);
867
+ return o || (o = we(e ? ["en", e] : ["en"]), B.set(a, o)), o;
847
868
  }
848
- function Se(n) {
849
- const e = n.replace(/\s+$/, "");
869
+ function je(i) {
870
+ const e = i.replace(/\s+$/, "");
850
871
  if (!e) return "";
851
- const t = e.replace(/[.!?]+$/, "");
872
+ const a = e.replace(/[.!?]+$/, "");
852
873
  let o = -1;
853
- for (let r = t.length - 1; r >= 0; r--) {
854
- const l = t[r];
874
+ for (let r = a.length - 1; r >= 0; r--) {
875
+ const l = a[r];
855
876
  if (l === "." || l === "!" || l === "?" || l === `
856
877
  `) {
857
878
  o = r + 1;
858
879
  break;
859
880
  }
860
881
  }
861
- return o === -1 ? "" : `${t.slice(0, o)} `.replace(/\n $/, `
882
+ return o === -1 ? "" : `${a.slice(0, o)} `.replace(/\n $/, `
862
883
  `);
863
884
  }
864
- const ze = new RegExp(
885
+ const Se = new RegExp(
865
886
  String.raw`(^- |\n(?:- )?)(\p{Ll})`,
866
887
  "gu"
867
888
  );
868
- function Ce(n) {
869
- return n.replace(
870
- ze,
871
- (e, t, o) => t + o.toUpperCase()
889
+ function ze(i) {
890
+ return i.replace(
891
+ Se,
892
+ (e, a, o) => a + o.toUpperCase()
872
893
  );
873
894
  }
874
- function xe(n) {
875
- return n.length <= 3 && /^\s*$/.test(n) ? !0 : /[.!?\n]\s{0,3}$/.test(n.slice(-6));
895
+ function Ce(i) {
896
+ return i.length <= 3 && /^\s*$/.test(i) ? !0 : /[.!?\n]\s{0,3}$/.test(i.slice(-6));
876
897
  }
877
- class q {
898
+ class E {
878
899
  /**
879
900
  * Process the full raw transcript accumulated so far into insertable text.
880
901
  * Pure and deterministic: always called with the entire raw string so the
881
902
  * result never depends on delta chunking.
882
903
  */
883
- static process(e, t) {
884
- const o = I(t == null ? void 0 : t.language), r = t != null && t.final ? "" : q.commandPrefixTail(e, t == null ? void 0 : t.language), l = e.slice(0, e.length - r.length), s = t != null && t.final ? o.finalRegex : o.regex;
885
- let a = "", i = null, c = 0;
904
+ static process(e, a) {
905
+ const o = M(a == null ? void 0 : a.language), r = a != null && a.final ? "" : E.commandPrefixTail(e, a == null ? void 0 : a.language), l = e.slice(0, e.length - r.length), s = a != null && a.final ? o.finalRegex : o.regex;
906
+ let t = "", n = null, c = 0;
886
907
  for (const _ of Array.from(l.matchAll(s))) {
887
908
  const [, p = ""] = _, u = o.phraseToAction.get(p.toLowerCase());
888
909
  if (u)
889
- if (a += l.slice(c, _.index), c = _.index + _[0].length, u === "newline") a = `${a.replace(/[ \t]+$/, "")}
910
+ if (t += l.slice(c, _.index), c = _.index + _[0].length, u === "newline") t = `${t.replace(/[ \t]+$/, "")}
890
911
  `;
891
912
  else if (u === "newparagraph")
892
- a = `${a.replace(/[ \t]+$/, "")}
913
+ t = `${t.replace(/[ \t]+$/, "")}
893
914
 
894
915
  `;
895
916
  else if (u === "bullet") {
896
- const m = a.replace(/[ \t]+$/, "");
897
- a = m === "" || m.endsWith(`
898
- `) ? `${m}- ` : `${m}
917
+ const h = t.replace(/[ \t]+$/, "");
918
+ t = h === "" || h.endsWith(`
919
+ `) ? `${h}- ` : `${h}
899
920
  - `;
900
- } else if (u === "scratch") a = Se(a);
921
+ } else if (u === "scratch") t = je(t);
901
922
  else {
902
- i = u === "send" ? "send" : "stop";
923
+ n = u === "send" ? "send" : "stop";
903
924
  break;
904
925
  }
905
926
  }
906
- return i === null && (a += l.slice(c)), { text: Ce(
907
- a.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
927
+ return n === null && (t += l.slice(c)), { text: ze(
928
+ t.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
908
929
  `).replace(/\n[ \t]+/g, `
909
930
  `).replace(/(^|\n)- +/g, "$1- ").replace(/ {2,}/g, " ").replace(/\n{3,}/g, `
910
931
 
911
932
  `)
912
- ), pendingTail: r, control: i };
933
+ ), pendingTail: r, control: n };
913
934
  }
914
935
  /**
915
936
  * Longest suffix of `raw` that could still become a command — a proper
@@ -920,16 +941,16 @@ class q {
920
941
  * control command from an intermediate delta would stop or submit
921
942
  * mid-sentence.
922
943
  */
923
- static commandPrefixTail(e, t) {
924
- const o = I(t), r = Math.min(e.length, o.longestPhrase + 2);
944
+ static commandPrefixTail(e, a) {
945
+ const o = M(a), r = Math.min(e.length, o.longestPhrase + 2);
925
946
  for (let l = r; l > 0; l--) {
926
947
  const s = e.length - l;
927
- if (!xe(e.slice(0, s))) continue;
928
- const a = e.slice(s).toLowerCase(), i = a.replace(/^\s+/, "");
929
- if (i) {
948
+ if (!Ce(e.slice(0, s))) continue;
949
+ const t = e.slice(s).toLowerCase(), n = t.replace(/^\s+/, "");
950
+ if (n) {
930
951
  for (const c of Array.from(o.phraseToAction.keys()))
931
- if (c.startsWith(i))
932
- return e.slice(s + (a.length - i.length));
952
+ if (c.startsWith(n))
953
+ return e.slice(s + (t.length - n.length));
933
954
  }
934
955
  }
935
956
  return "";
@@ -939,13 +960,13 @@ class q {
939
960
  * prefix) — i.e. a silence pause would resolve it into a command. Used by
940
961
  * the manager's silence timer.
941
962
  */
942
- static pendingTailIsCompletePhrase(e, t) {
943
- const o = q.commandPrefixTail(e, t).trim().toLowerCase();
944
- return o ? I(t).phraseToAction.has(o) : !1;
963
+ static pendingTailIsCompletePhrase(e, a) {
964
+ const o = E.commandPrefixTail(e, a).trim().toLowerCase();
965
+ return o ? M(a).phraseToAction.has(o) : !1;
945
966
  }
946
967
  }
947
- const qe = 55, Ee = 90;
948
- class H {
968
+ const xe = 55, qe = 90;
969
+ class V {
949
970
  /**
950
971
  * Next paced step toward `processed`: normally one word per tick so text
951
972
  * flows evenly instead of landing in bursty chunks; proportionally larger
@@ -954,28 +975,28 @@ class H {
954
975
  */
955
976
  static nextDripText({
956
977
  displayed: e,
957
- processed: t
978
+ processed: a
958
979
  }) {
959
- if (t.length <= e.length) return t;
960
- const o = t.length - e.length;
961
- if (o > Ee)
962
- return t.slice(0, e.length + Math.ceil(o / 3));
980
+ if (a.length <= e.length) return a;
981
+ const o = a.length - e.length;
982
+ if (o > qe)
983
+ return a.slice(0, e.length + Math.ceil(o / 3));
963
984
  let r = e.length;
964
- for (; r < t.length && /\s/.test(t.charAt(r)); ) r++;
965
- for (; r < t.length && !/\s/.test(t.charAt(r)); ) r++;
966
- return r - e.length > 12 && (r = e.length + 6), t.slice(0, Math.max(r, e.length + 1));
985
+ for (; r < a.length && /\s/.test(a.charAt(r)); ) r++;
986
+ for (; r < a.length && !/\s/.test(a.charAt(r)); ) r++;
987
+ return r - e.length > 12 && (r = e.length + 6), a.slice(0, Math.max(r, e.length + 1));
967
988
  }
968
989
  /** Normalize a BCP-47 browser locale into the hint OpenAI accepts. */
969
990
  static languageHint(e) {
970
991
  if (!e) return;
971
- const t = e.toLowerCase();
972
- if (/^zh-(cn|tw|hk)$/.test(t)) return t;
973
- const o = t.split("-")[0];
992
+ const a = e.toLowerCase();
993
+ if (/^zh-(cn|tw|hk)$/.test(a)) return a;
994
+ const o = a.split("-")[0];
974
995
  return o && /^[a-z]{2,3}$/.test(o) ? o : void 0;
975
996
  }
976
997
  }
977
- const Ae = 2e4;
978
- class Pe {
998
+ const Ee = 2e4;
999
+ class Ae {
979
1000
  constructor() {
980
1001
  this.cached = null, this.inflight = null;
981
1002
  }
@@ -983,15 +1004,15 @@ class Pe {
983
1004
  get() {
984
1005
  if (!this.cached) return null;
985
1006
  const e = Date.parse(this.cached.expiresAt);
986
- return Number.isNaN(e) || e - Date.now() < Ae ? (this.cached = null, null) : this.cached;
1007
+ return Number.isNaN(e) || e - Date.now() < Ee ? (this.cached = null, null) : this.cached;
987
1008
  }
988
1009
  /**
989
1010
  * Resolve a mint, deduping concurrent requests (hover-prewarm racing a
990
1011
  * click reuses the same in-flight promise instead of double-minting).
991
1012
  */
992
1013
  async resolve(e) {
993
- const t = this.get();
994
- return t || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
1014
+ const a = this.get();
1015
+ return a || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
995
1016
  this.inflight = null;
996
1017
  })), this.inflight);
997
1018
  }
@@ -1000,55 +1021,55 @@ class Pe {
1000
1021
  this.cached = null;
1001
1022
  }
1002
1023
  }
1003
- function Z(n) {
1004
- return typeof n == "object" && n !== null && !Array.isArray(n);
1024
+ function H(i) {
1025
+ return typeof i == "object" && i !== null && !Array.isArray(i);
1005
1026
  }
1006
- function Te(n) {
1007
- if (!Z(n) || typeof n.type != "string") return null;
1008
- const e = Z(n.error) ? n.error : null;
1027
+ function Pe(i) {
1028
+ if (!H(i) || typeof i.type != "string") return null;
1029
+ const e = H(i.error) ? i.error : null;
1009
1030
  return {
1010
- type: n.type,
1011
- delta: typeof n.delta == "string" ? n.delta : void 0,
1031
+ type: i.type,
1032
+ delta: typeof i.delta == "string" ? i.delta : void 0,
1012
1033
  errorMessage: e && typeof e.message == "string" ? e.message : void 0
1013
1034
  };
1014
1035
  }
1015
- const Ie = "https://api.openai.com/v1/realtime/calls", Me = 600 * 1e3, De = 15e3, Ne = 5e3;
1016
- class P extends Error {
1036
+ const Te = "https://api.openai.com/v1/realtime/calls", Ie = 600 * 1e3, Me = 15e3, De = 5e3;
1037
+ class T extends Error {
1017
1038
  }
1018
- class Re {
1039
+ class Ne {
1019
1040
  constructor({
1020
1041
  mintToken: e,
1021
- onDelta: t,
1042
+ onDelta: a,
1022
1043
  onState: o,
1023
1044
  onError: r,
1024
1045
  onLevel: l
1025
1046
  }) {
1026
- 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 = l;
1047
+ 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 = l;
1027
1048
  }
1028
1049
  async start() {
1029
1050
  if (this.state === "idle") {
1030
1051
  this.setState("connecting"), this.timers.push(
1031
1052
  setTimeout(() => {
1032
1053
  this.state === "connecting" && this.fail("unavailable");
1033
- }, De)
1034
- ), this.timers.push(setTimeout(() => this.stop(), Me));
1054
+ }, Me)
1055
+ ), this.timers.push(setTimeout(() => this.stop(), Ie));
1035
1056
  try {
1036
1057
  const e = this.requestMicrophone();
1037
1058
  e.then((d) => {
1038
- (this.isTornDown() || this.stream && this.stream !== d) && d.getTracks().forEach((_) => _.stop());
1059
+ this.isTornDown() || this.stream && this.stream !== d ? d.getTracks().forEach((_) => _.stop()) : this.stream = d;
1039
1060
  }).catch(() => {
1040
1061
  });
1041
- const [t, o] = await Promise.all([e, this.mintToken()]);
1062
+ const [a, o] = await Promise.all([e, this.mintToken()]);
1042
1063
  if (this.isTornDown()) {
1043
- t.getTracks().forEach((d) => d.stop());
1064
+ a.getTracks().forEach((d) => d.stop());
1044
1065
  return;
1045
1066
  }
1046
- this.stream = t, this.startLevelMeter(t);
1067
+ this.stream = a, this.startLevelMeter(a);
1047
1068
  const r = new RTCPeerConnection();
1048
1069
  this.pc = r;
1049
- const [l] = t.getAudioTracks();
1050
- if (!l) throw new P("No audio track");
1051
- r.addTrack(l, t);
1070
+ const [l] = a.getAudioTracks();
1071
+ if (!l) throw new T("No audio track");
1072
+ r.addTrack(l, a);
1052
1073
  const s = r.createDataChannel("oai-events");
1053
1074
  this.dc = s, s.addEventListener(
1054
1075
  "message",
@@ -1063,26 +1084,26 @@ class Re {
1063
1084
  r.connectionState === "disconnected" && this.timers.push(
1064
1085
  setTimeout(() => {
1065
1086
  this.pc === r && r.connectionState !== "connected" && this.fail("unavailable");
1066
- }, Ne)
1087
+ }, De)
1067
1088
  );
1068
1089
  });
1069
- const a = await r.createOffer();
1070
- await r.setLocalDescription(a);
1071
- const i = await fetch(Ie, {
1090
+ const t = await r.createOffer();
1091
+ if (this.isTornDown() || (await r.setLocalDescription(t), this.isTornDown())) return;
1092
+ const n = await fetch(Te, {
1072
1093
  method: "POST",
1073
1094
  headers: {
1074
1095
  Authorization: `Bearer ${o.token}`,
1075
1096
  "Content-Type": "application/sdp"
1076
1097
  },
1077
- body: a.sdp
1098
+ body: t.sdp
1078
1099
  });
1079
- if (!i.ok)
1080
- throw new Error(`Realtime handshake failed (${i.status})`);
1081
- const c = await i.text();
1100
+ if (!n.ok)
1101
+ throw new Error(`Realtime handshake failed (${n.status})`);
1102
+ const c = await n.text();
1082
1103
  if (this.isTornDown()) return;
1083
1104
  await r.setRemoteDescription({ type: "answer", sdp: c });
1084
1105
  } catch (e) {
1085
- e instanceof P ? this.fail("microphone") : (k.error("dictation session failed to start", {
1106
+ e instanceof T ? this.fail("microphone") : (g.error("dictation session failed to start", {
1086
1107
  _e: e instanceof Error ? e.message : String(e)
1087
1108
  }), this.fail("unavailable"));
1088
1109
  }
@@ -1094,7 +1115,7 @@ class Re {
1094
1115
  async requestMicrophone() {
1095
1116
  var e;
1096
1117
  if (!((e = navigator.mediaDevices) != null && e.getUserMedia))
1097
- throw new P("Microphone is not supported");
1118
+ throw new T("Microphone is not supported");
1098
1119
  try {
1099
1120
  return await navigator.mediaDevices.getUserMedia({
1100
1121
  audio: {
@@ -1103,24 +1124,24 @@ class Re {
1103
1124
  autoGainControl: !0
1104
1125
  }
1105
1126
  });
1106
- } catch (t) {
1107
- throw new P(
1108
- t instanceof DOMException ? t.name : "Could not access the microphone"
1127
+ } catch (a) {
1128
+ throw new T(
1129
+ a instanceof DOMException ? a.name : "Could not access the microphone"
1109
1130
  );
1110
1131
  }
1111
1132
  }
1112
1133
  handleServerEvent(e) {
1113
1134
  if (typeof e != "string") return;
1114
- let t;
1135
+ let a;
1115
1136
  try {
1116
- t = JSON.parse(e);
1137
+ a = JSON.parse(e);
1117
1138
  } catch {
1118
- this.loggedParseFailure || (this.loggedParseFailure = !0, k.error("dictation server event was not valid JSON", {
1139
+ this.loggedParseFailure || (this.loggedParseFailure = !0, g.error("dictation server event was not valid JSON", {
1119
1140
  snippet: e.slice(0, 120)
1120
1141
  }));
1121
1142
  return;
1122
1143
  }
1123
- const o = Te(t);
1144
+ const o = Pe(a);
1124
1145
  if (!o) return;
1125
1146
  const { type: r, delta: l } = o;
1126
1147
  if (r === "session.created" || r === "transcription_session.created") {
@@ -1131,32 +1152,32 @@ class Re {
1131
1152
  this.state === "connecting" && this.setState("listening"), this.onDelta(l);
1132
1153
  return;
1133
1154
  }
1134
- r === "error" && (k.error("dictation server event error", {
1155
+ r === "error" && (g.error("dictation server event error", {
1135
1156
  _e: o.errorMessage ?? "unknown"
1136
1157
  }), this.fail("unavailable"));
1137
1158
  }
1138
1159
  startLevelMeter(e) {
1139
1160
  if (this.onLevel)
1140
1161
  try {
1141
- const t = new AudioContext();
1142
- this.audioContext = t;
1143
- const o = t.createMediaStreamSource(e), r = t.createAnalyser();
1162
+ const a = new AudioContext();
1163
+ this.audioContext = a;
1164
+ const o = a.createMediaStreamSource(e), r = a.createAnalyser();
1144
1165
  r.fftSize = 512, o.connect(r);
1145
1166
  const l = new Uint8Array(r.frequencyBinCount), s = () => {
1146
1167
  var c;
1147
1168
  r.getByteTimeDomainData(l);
1148
- let a = 0;
1169
+ let t = 0;
1149
1170
  for (let d = 0; d < l.length; d++) {
1150
1171
  const _ = ((l[d] ?? 128) - 128) / 128;
1151
- a += _ * _;
1172
+ t += _ * _;
1152
1173
  }
1153
- const i = Math.sqrt(a / l.length);
1154
- (c = this.onLevel) == null || c.call(this, Math.min(1, i * 4)), this.levelRaf = requestAnimationFrame(s);
1174
+ const n = Math.sqrt(t / l.length);
1175
+ (c = this.onLevel) == null || c.call(this, Math.min(1, n * 4)), this.levelRaf = requestAnimationFrame(s);
1155
1176
  };
1156
1177
  this.levelRaf = requestAnimationFrame(s);
1157
- } catch (t) {
1158
- k.error("dictation level meter unavailable", {
1159
- _e: t instanceof Error ? t.message : String(t)
1178
+ } catch (a) {
1179
+ g.error("dictation level meter unavailable", {
1180
+ _e: a instanceof Error ? a.message : String(a)
1160
1181
  });
1161
1182
  }
1162
1183
  }
@@ -1167,9 +1188,9 @@ class Re {
1167
1188
  this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(e));
1168
1189
  }
1169
1190
  teardown() {
1170
- var e, t, o, r;
1171
- this.timers.forEach((l) => clearTimeout(l)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (t = this.pc) == null || t.close(), this.pc = null, (o = this.stream) == null || o.getTracks().forEach((l) => l.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((l) => {
1172
- k.error("failed to close dictation audio context", {
1191
+ var e, a, o, r;
1192
+ this.timers.forEach((l) => clearTimeout(l)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (a = this.pc) == null || a.close(), this.pc = null, (o = this.stream) == null || o.getTracks().forEach((l) => l.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((l) => {
1193
+ g.error("failed to close dictation audio context", {
1173
1194
  _e: String(l)
1174
1195
  });
1175
1196
  }), this.audioContext = null;
@@ -1178,20 +1199,20 @@ class Re {
1178
1199
  this.state !== e && (this.state = e, this.onState(e));
1179
1200
  }
1180
1201
  }
1181
- const Ke = 1300, Le = { status: "idle", error: null };
1182
- class Fe {
1183
- constructor({ api: e, config: t }) {
1184
- 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 = () => {
1202
+ const Re = 1300, Ke = { status: "idle", error: null };
1203
+ class Le {
1204
+ constructor({ api: e, config: a }) {
1205
+ this.state = new S(Ke), this.levelRef = { current: 0 }, this.mintCache = new Ae(), 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 = () => {
1185
1206
  this.mintToken().catch((o) => {
1186
- this.mintCache.clear(), k.error("dictation token prewarm failed", {
1207
+ this.mintCache.clear(), g.error("dictation token prewarm failed", {
1187
1208
  _e: o instanceof Error ? o.message : String(o)
1188
1209
  });
1189
1210
  });
1190
1211
  }, this.start = (o) => {
1191
- this.session && this.teardown(), this.target = o, this.language = H.languageHint(
1212
+ this.session && this.teardown(), this.target = o, this.language = V.languageHint(
1192
1213
  this.config.language ?? navigator.language
1193
1214
  ), this.prefix = o.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1194
- const r = new Re({
1215
+ const r = new Ne({
1195
1216
  mintToken: this.mintToken,
1196
1217
  onLevel: (l) => {
1197
1218
  this.levelRef.current = l;
@@ -1218,15 +1239,15 @@ class Fe {
1218
1239
  this.teardown({ send: !0 });
1219
1240
  return;
1220
1241
  }
1221
- this.stopSilenceTimer(), q.pendingTailIsCompletePhrase(
1242
+ this.stopSilenceTimer(), E.pendingTailIsCompletePhrase(
1222
1243
  this.raw,
1223
1244
  this.language
1224
1245
  ) && (this.silenceTimer = setTimeout(() => {
1225
1246
  if (r !== this.session) return;
1226
1247
  this.raw = `${this.raw}.`;
1227
- const a = this.ingest();
1228
- a === "stop" ? this.teardown() : a === "send" && this.teardown({ send: !0 });
1229
- }, Ke));
1248
+ const t = this.ingest();
1249
+ t === "stop" ? this.teardown() : t === "send" && this.teardown({ send: !0 });
1250
+ }, Re));
1230
1251
  }
1231
1252
  });
1232
1253
  this.session = r, this.state.set({ status: "connecting", error: null }), this.dripTimer = setInterval(() => {
@@ -1236,18 +1257,18 @@ class Fe {
1236
1257
  return;
1237
1258
  }
1238
1259
  this.applyDisplayed(
1239
- H.nextDripText({
1260
+ V.nextDripText({
1240
1261
  displayed: this.displayed,
1241
1262
  processed: this.processed
1242
1263
  })
1243
1264
  );
1244
1265
  }
1245
- }, qe), r.start();
1246
- }, this.stop = () => {
1247
- this.session && this.teardown();
1266
+ }, xe), r.start();
1267
+ }, this.stop = (o) => {
1268
+ this.session && this.teardown(o);
1248
1269
  }, this.mintToken = async () => this.mintCache.resolve(
1249
1270
  () => this.api.createDictationSession({ language: this.language })
1250
- ), this.api = e, this.config = t;
1271
+ ), this.api = e, this.config = a;
1251
1272
  }
1252
1273
  /** Applied text = prefix + dictated. A mismatch means the visitor edited. */
1253
1274
  isConsistent() {
@@ -1259,28 +1280,28 @@ class Fe {
1259
1280
  /** Process the transcript and apply the outcome. Shared by the delta path,
1260
1281
  * the silence timer, and (with `final`) teardown. Returns the control. */
1261
1282
  ingest(e) {
1262
- const t = q.process(this.raw, {
1283
+ const a = E.process(this.raw, {
1263
1284
  language: this.language,
1264
1285
  final: e == null ? void 0 : e.final
1265
1286
  });
1266
- return this.processed = t.text, t.text.startsWith(this.displayed) || this.applyDisplayed(t.text), t.control;
1287
+ return this.processed = a.text, a.text.startsWith(this.displayed) || this.applyDisplayed(a.text), a.control;
1267
1288
  }
1268
1289
  stopSilenceTimer() {
1269
1290
  this.silenceTimer && clearTimeout(this.silenceTimer), this.silenceTimer = null;
1270
1291
  }
1271
1292
  teardown(e) {
1272
1293
  var l;
1273
- const t = this.session, o = this.target;
1294
+ const a = this.session, o = this.target;
1274
1295
  this.dripTimer && clearInterval(this.dripTimer), this.dripTimer = null, this.stopSilenceTimer();
1275
1296
  let r = (e == null ? void 0 : e.send) ?? !1;
1276
1297
  if (o && this.isConsistent()) {
1277
1298
  const s = this.ingest({ final: !0 });
1278
1299
  (e == null ? void 0 : e.executeFinalCommand) !== !1 && s === "send" && (r = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1279
1300
  }
1280
- 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 && ((l = o == null ? void 0 : o.onSend) == null || l.call(o));
1301
+ 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 && ((l = o == null ? void 0 : o.onSend) == null || l.call(o));
1281
1302
  }
1282
1303
  }
1283
- const Oe = {
1304
+ const Fe = {
1284
1305
  write_a_message_placeholder: "اكتب رسالة...",
1285
1306
  your_issue_has_been_resolved: "تم حل مشكلتك!",
1286
1307
  new_conversation: "محادثة جديدة",
@@ -1389,7 +1410,7 @@ const Oe = {
1389
1410
  zoom_out: "تصغير",
1390
1411
  reset_zoom: "إعادة تعيين التكبير",
1391
1412
  support_chat_aria_label: "دردشة الدعم"
1392
- }, Ue = {
1413
+ }, Oe = {
1393
1414
  write_a_message_placeholder: "একটি বার্তা লিখুন...",
1394
1415
  your_issue_has_been_resolved: "আপনার সমস্যা সমাধান হয়েছে!",
1395
1416
  new_conversation: "নতুন কথোপকথন",
@@ -1486,7 +1507,7 @@ const Oe = {
1486
1507
  zoom_out: "ছোট করুন",
1487
1508
  reset_zoom: "জুম রিসেট করুন",
1488
1509
  support_chat_aria_label: "সাপোর্ট চ্যাট"
1489
- }, Be = {
1510
+ }, Ue = {
1490
1511
  write_a_message_placeholder: "Напишете съобщение...",
1491
1512
  your_issue_has_been_resolved: "Вашият проблем е разрешен!",
1492
1513
  new_conversation: "Нов разговор",
@@ -1583,7 +1604,7 @@ const Oe = {
1583
1604
  zoom_out: "Намаляване",
1584
1605
  reset_zoom: "Нулиране на мащаба",
1585
1606
  support_chat_aria_label: "Чат за поддръжка"
1586
- }, Ve = {
1607
+ }, Be = {
1587
1608
  write_a_message_placeholder: "Napište zprávu...",
1588
1609
  your_issue_has_been_resolved: "Váš problém byl vyřešen!",
1589
1610
  new_conversation: "Nová konverzace",
@@ -1680,7 +1701,7 @@ const Oe = {
1680
1701
  zoom_out: "Oddálit",
1681
1702
  reset_zoom: "Obnovit přiblížení",
1682
1703
  support_chat_aria_label: "Chat podpory"
1683
- }, He = {
1704
+ }, Ve = {
1684
1705
  write_a_message_placeholder: "Skriv en besked...",
1685
1706
  your_issue_has_been_resolved: "Dit problem er løst!",
1686
1707
  new_conversation: "Ny samtale",
@@ -1777,7 +1798,7 @@ const Oe = {
1777
1798
  zoom_out: "Zoom ud",
1778
1799
  reset_zoom: "Nulstil zoom",
1779
1800
  support_chat_aria_label: "Supportchat"
1780
- }, Ze = {
1801
+ }, He = {
1781
1802
  write_a_message_placeholder: "Γράψτε ένα μήνυμα...",
1782
1803
  your_issue_has_been_resolved: "Το πρόβλημά σας επιλύθηκε!",
1783
1804
  new_conversation: "Νέα συνομιλία",
@@ -1874,7 +1895,7 @@ const Oe = {
1874
1895
  zoom_out: "Σμίκρυνση",
1875
1896
  reset_zoom: "Επαναφορά ζουμ",
1876
1897
  support_chat_aria_label: "Συνομιλία υποστήριξης"
1877
- }, We = {
1898
+ }, Ge = {
1878
1899
  write_a_message_placeholder: "Nachricht schreiben...",
1879
1900
  your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
1880
1901
  new_conversation: "Neue Konversation",
@@ -1971,7 +1992,7 @@ const Oe = {
1971
1992
  zoom_out: "Verkleinern",
1972
1993
  reset_zoom: "Zoom zurücksetzen",
1973
1994
  support_chat_aria_label: "Support-Chat"
1974
- }, J = {
1995
+ }, $ = {
1975
1996
  write_a_message_placeholder: "Write a message...",
1976
1997
  your_issue_has_been_resolved: "Your issue has been resolved!",
1977
1998
  new_conversation: "New conversation",
@@ -2080,7 +2101,7 @@ const Oe = {
2080
2101
  zoom_out: "Zoom out",
2081
2102
  reset_zoom: "Reset zoom",
2082
2103
  support_chat_aria_label: "Support chat"
2083
- }, Ge = {
2104
+ }, Ze = {
2084
2105
  write_a_message_placeholder: "Escribe un mensaje...",
2085
2106
  your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
2086
2107
  new_conversation: "Nueva conversación",
@@ -2177,7 +2198,7 @@ const Oe = {
2177
2198
  zoom_out: "Alejar",
2178
2199
  reset_zoom: "Restablecer zoom",
2179
2200
  support_chat_aria_label: "Chat de soporte"
2180
- }, $e = {
2201
+ }, We = {
2181
2202
  write_a_message_placeholder: "Magsulat ng mensahe...",
2182
2203
  your_issue_has_been_resolved: "Nalutas na ang iyong isyu!",
2183
2204
  new_conversation: "Bagong usapan",
@@ -2274,7 +2295,7 @@ const Oe = {
2274
2295
  zoom_out: "Paliitin",
2275
2296
  reset_zoom: "I-reset ang zoom",
2276
2297
  support_chat_aria_label: "Chat ng suporta"
2277
- }, Je = {
2298
+ }, $e = {
2278
2299
  write_a_message_placeholder: "Kirjoita viesti...",
2279
2300
  your_issue_has_been_resolved: "Ongelmasi on ratkaistu!",
2280
2301
  new_conversation: "Uusi keskustelu",
@@ -2371,7 +2392,7 @@ const Oe = {
2371
2392
  zoom_out: "Loitonna",
2372
2393
  reset_zoom: "Palauta zoomaus",
2373
2394
  support_chat_aria_label: "Tukichat"
2374
- }, Ye = {
2395
+ }, Je = {
2375
2396
  write_a_message_placeholder: "Écrivez un message...",
2376
2397
  your_issue_has_been_resolved: "Votre problème a été résolu !",
2377
2398
  new_conversation: "Nouvelle conversation",
@@ -2468,7 +2489,7 @@ const Oe = {
2468
2489
  zoom_out: "Zoom arrière",
2469
2490
  reset_zoom: "Réinitialiser le zoom",
2470
2491
  support_chat_aria_label: "Chat de support"
2471
- }, Qe = {
2492
+ }, Ye = {
2472
2493
  write_a_message_placeholder: "एक संदेश लिखें...",
2473
2494
  your_issue_has_been_resolved: "आपकी समस्या हल हो गई है!",
2474
2495
  new_conversation: "नई बातचीत",
@@ -2662,7 +2683,7 @@ const Oe = {
2662
2683
  zoom_out: "Riduci",
2663
2684
  reset_zoom: "Reimposta zoom",
2664
2685
  support_chat_aria_label: "Chat di supporto"
2665
- }, ea = {
2686
+ }, Qe = {
2666
2687
  write_a_message_placeholder: "メッセージを入力...",
2667
2688
  your_issue_has_been_resolved: "問題が解決しました!",
2668
2689
  new_conversation: "新しい会話",
@@ -2759,7 +2780,7 @@ const Oe = {
2759
2780
  zoom_out: "縮小",
2760
2781
  reset_zoom: "ズームをリセット",
2761
2782
  support_chat_aria_label: "サポートチャット"
2762
- }, aa = {
2783
+ }, ea = {
2763
2784
  write_a_message_placeholder: "메시지를 입력하세요...",
2764
2785
  your_issue_has_been_resolved: "문제가 해결되었습니다!",
2765
2786
  new_conversation: "새 대화",
@@ -2856,7 +2877,7 @@ const Oe = {
2856
2877
  zoom_out: "축소",
2857
2878
  reset_zoom: "확대/축소 초기화",
2858
2879
  support_chat_aria_label: "고객 지원 채팅"
2859
- }, ta = {
2880
+ }, aa = {
2860
2881
  write_a_message_placeholder: "Schrijf een bericht...",
2861
2882
  your_issue_has_been_resolved: "Uw probleem is opgelost!",
2862
2883
  new_conversation: "Nieuw gesprek",
@@ -2953,7 +2974,7 @@ const Oe = {
2953
2974
  zoom_out: "Uitzoomen",
2954
2975
  reset_zoom: "Zoom herstellen",
2955
2976
  support_chat_aria_label: "Supportchat"
2956
- }, sa = {
2977
+ }, ta = {
2957
2978
  write_a_message_placeholder: "Skriv en melding...",
2958
2979
  your_issue_has_been_resolved: "Problemet ditt er løst!",
2959
2980
  new_conversation: "Ny samtale",
@@ -3050,7 +3071,7 @@ const Oe = {
3050
3071
  zoom_out: "Zoom ut",
3051
3072
  reset_zoom: "Tilbakestill zoom",
3052
3073
  support_chat_aria_label: "Support-chat"
3053
- }, oa = {
3074
+ }, sa = {
3054
3075
  write_a_message_placeholder: "Napisz wiadomość...",
3055
3076
  your_issue_has_been_resolved: "Twój problem został rozwiązany!",
3056
3077
  new_conversation: "Nowa rozmowa",
@@ -3147,7 +3168,7 @@ const Oe = {
3147
3168
  zoom_out: "Pomniejsz",
3148
3169
  reset_zoom: "Resetuj powiększenie",
3149
3170
  support_chat_aria_label: "Czat pomocy"
3150
- }, na = {
3171
+ }, oa = {
3151
3172
  write_a_message_placeholder: "Escreva uma mensagem...",
3152
3173
  your_issue_has_been_resolved: "Seu problema foi resolvido!",
3153
3174
  new_conversation: "Nova conversa",
@@ -3244,7 +3265,7 @@ const Oe = {
3244
3265
  zoom_out: "Reduzir",
3245
3266
  reset_zoom: "Redefinir zoom",
3246
3267
  support_chat_aria_label: "Chat de suporte"
3247
- }, ia = {
3268
+ }, na = {
3248
3269
  write_a_message_placeholder: "Scrie un mesaj...",
3249
3270
  your_issue_has_been_resolved: "Problema ta a fost rezolvată!",
3250
3271
  new_conversation: "Conversație nouă",
@@ -3341,7 +3362,7 @@ const Oe = {
3341
3362
  zoom_out: "Micșorează",
3342
3363
  reset_zoom: "Resetează zoomul",
3343
3364
  support_chat_aria_label: "Chat de asistență"
3344
- }, ra = {
3365
+ }, ia = {
3345
3366
  write_a_message_placeholder: "Skriv ett meddelande...",
3346
3367
  your_issue_has_been_resolved: "Ditt problem har lösts!",
3347
3368
  new_conversation: "Ny konversation",
@@ -3438,7 +3459,7 @@ const Oe = {
3438
3459
  zoom_out: "Zooma ut",
3439
3460
  reset_zoom: "Återställ zoom",
3440
3461
  support_chat_aria_label: "Supportchatt"
3441
- }, _a = {
3462
+ }, ra = {
3442
3463
  write_a_message_placeholder: "Напишите сообщение...",
3443
3464
  your_issue_has_been_resolved: "Ваша проблема решена!",
3444
3465
  new_conversation: "Новый разговор",
@@ -3535,7 +3556,7 @@ const Oe = {
3535
3556
  zoom_out: "Уменьшить",
3536
3557
  reset_zoom: "Сбросить масштаб",
3537
3558
  support_chat_aria_label: "Чат поддержки"
3538
- }, la = {
3559
+ }, _a = {
3539
3560
  write_a_message_placeholder: "เขียนข้อความ...",
3540
3561
  your_issue_has_been_resolved: "ปัญหาของคุณได้รับการแก้ไขแล้ว!",
3541
3562
  new_conversation: "การสนทนาใหม่",
@@ -3632,7 +3653,7 @@ const Oe = {
3632
3653
  zoom_out: "ย่อ",
3633
3654
  reset_zoom: "รีเซ็ตการซูม",
3634
3655
  support_chat_aria_label: "แชทฝ่ายสนับสนุน"
3635
- }, ca = {
3656
+ }, la = {
3636
3657
  write_a_message_placeholder: "Bir mesaj yazın...",
3637
3658
  your_issue_has_been_resolved: "Sorununuz çözüldü!",
3638
3659
  new_conversation: "Yeni konuşma",
@@ -3729,7 +3750,7 @@ const Oe = {
3729
3750
  zoom_out: "Uzaklaştır",
3730
3751
  reset_zoom: "Yakınlaştırmayı sıfırla",
3731
3752
  support_chat_aria_label: "Destek sohbeti"
3732
- }, pa = {
3753
+ }, ca = {
3733
3754
  write_a_message_placeholder: "پیغام لکھیں...",
3734
3755
  your_issue_has_been_resolved: "آپ کا مسئلہ حل ہو گیا ہے!",
3735
3756
  new_conversation: "نئی گفتگو",
@@ -3826,7 +3847,7 @@ const Oe = {
3826
3847
  zoom_out: "زوم آؤٹ",
3827
3848
  reset_zoom: "زوم دوبارہ ترتیب دیں",
3828
3849
  support_chat_aria_label: "سپورٹ چیٹ"
3829
- }, da = {
3850
+ }, pa = {
3830
3851
  write_a_message_placeholder: "Viết tin nhắn...",
3831
3852
  your_issue_has_been_resolved: "Vấn đề của bạn đã được giải quyết!",
3832
3853
  new_conversation: "Cuộc trò chuyện mới",
@@ -3923,7 +3944,7 @@ const Oe = {
3923
3944
  zoom_out: "Thu nhỏ",
3924
3945
  reset_zoom: "Đặt lại thu phóng",
3925
3946
  support_chat_aria_label: "Trò chuyện hỗ trợ"
3926
- }, ua = {
3947
+ }, da = {
3927
3948
  write_a_message_placeholder: "写一条消息...",
3928
3949
  your_issue_has_been_resolved: "您的问题已解决!",
3929
3950
  new_conversation: "新对话",
@@ -4020,7 +4041,7 @@ const Oe = {
4020
4041
  zoom_out: "缩小",
4021
4042
  reset_zoom: "重置缩放",
4022
4043
  support_chat_aria_label: "支持对话"
4023
- }, ma = {
4044
+ }, ua = {
4024
4045
  write_a_message_placeholder: "Napišite poruku...",
4025
4046
  your_issue_has_been_resolved: "Vaš problem je riješen!",
4026
4047
  new_conversation: "Novi razgovor",
@@ -4117,7 +4138,7 @@ const Oe = {
4117
4138
  zoom_out: "Udalji",
4118
4139
  reset_zoom: "Poništi zumiranje",
4119
4140
  support_chat_aria_label: "Chat za podršku"
4120
- }, ha = {
4141
+ }, ma = {
4121
4142
  write_a_message_placeholder: "Kirjuta sõnum...",
4122
4143
  your_issue_has_been_resolved: "Teie probleem on lahendatud!",
4123
4144
  new_conversation: "Uus vestlus",
@@ -4214,7 +4235,7 @@ const Oe = {
4214
4235
  zoom_out: "Vähenda",
4215
4236
  reset_zoom: "Lähtesta suurendus",
4216
4237
  support_chat_aria_label: "Tugivestlus"
4217
- }, ga = {
4238
+ }, ha = {
4218
4239
  write_a_message_placeholder: "Írjon üzenetet...",
4219
4240
  your_issue_has_been_resolved: "A problémája megoldódott!",
4220
4241
  new_conversation: "Új beszélgetés",
@@ -4311,7 +4332,7 @@ const Oe = {
4311
4332
  zoom_out: "Kicsinyítés",
4312
4333
  reset_zoom: "Nagyítás visszaállítása",
4313
4334
  support_chat_aria_label: "Ügyfélszolgálati chat"
4314
- }, ka = {
4335
+ }, ga = {
4315
4336
  write_a_message_placeholder: "Skrifaðu skilaboð...",
4316
4337
  your_issue_has_been_resolved: "Málið þitt hefur verið leyst!",
4317
4338
  new_conversation: "Nýtt samtal",
@@ -4408,7 +4429,7 @@ const Oe = {
4408
4429
  zoom_out: "Minnka aðdrátt",
4409
4430
  reset_zoom: "Endurstilla aðdrátt",
4410
4431
  support_chat_aria_label: "Þjónustuspjall"
4411
- }, ba = {
4432
+ }, ka = {
4412
4433
  write_a_message_placeholder: "Rakstiet ziņojumu...",
4413
4434
  your_issue_has_been_resolved: "Jūsu problēma ir atrisināta!",
4414
4435
  new_conversation: "Jauna saruna",
@@ -4505,7 +4526,7 @@ const Oe = {
4505
4526
  zoom_out: "Attālināt",
4506
4527
  reset_zoom: "Atiestatīt tālummaiņu",
4507
4528
  support_chat_aria_label: "Atbalsta tērzēšana"
4508
- }, va = {
4529
+ }, ba = {
4509
4530
  write_a_message_placeholder: "Parašykite žinutę...",
4510
4531
  your_issue_has_been_resolved: "Jūsų problema išspręsta!",
4511
4532
  new_conversation: "Naujas pokalbis",
@@ -4602,7 +4623,7 @@ const Oe = {
4602
4623
  zoom_out: "Nutolinti",
4603
4624
  reset_zoom: "Atstatyti mastelį",
4604
4625
  support_chat_aria_label: "Pagalbos pokalbis"
4605
- }, fa = {
4626
+ }, va = {
4606
4627
  write_a_message_placeholder: "Schreift eng Noriicht...",
4607
4628
  your_issue_has_been_resolved: "Äert Problem gouf geléist!",
4608
4629
  new_conversation: "Nei Konversatioun",
@@ -4699,7 +4720,7 @@ const Oe = {
4699
4720
  zoom_out: "Erauszoomen",
4700
4721
  reset_zoom: "Zoom zrécksetzen",
4701
4722
  support_chat_aria_label: "Support-Chat"
4702
- }, ya = {
4723
+ }, fa = {
4703
4724
  write_a_message_placeholder: "Ikteb messaġġ...",
4704
4725
  your_issue_has_been_resolved: "Il-problema tiegħek ġiet riżolta!",
4705
4726
  new_conversation: "Konversazzjoni ġdida",
@@ -4796,7 +4817,7 @@ const Oe = {
4796
4817
  zoom_out: "Ċekken",
4797
4818
  reset_zoom: "Irrisettja ż-zoom",
4798
4819
  support_chat_aria_label: "Chat ta’ appoġġ"
4799
- }, wa = {
4820
+ }, ya = {
4800
4821
  write_a_message_placeholder: "Skriv en melding...",
4801
4822
  your_issue_has_been_resolved: "Saken din er løst!",
4802
4823
  new_conversation: "Ny samtale",
@@ -4893,7 +4914,7 @@ const Oe = {
4893
4914
  zoom_out: "Zoom ut",
4894
4915
  reset_zoom: "Tilbakestill zoom",
4895
4916
  support_chat_aria_label: "Support-chat"
4896
- }, ja = {
4917
+ }, wa = {
4897
4918
  write_a_message_placeholder: "Napíšte správu...",
4898
4919
  your_issue_has_been_resolved: "Váš problém bol vyriešený!",
4899
4920
  new_conversation: "Nová konverzácia",
@@ -4990,82 +5011,82 @@ const Oe = {
4990
5011
  zoom_out: "Oddialiť",
4991
5012
  reset_zoom: "Obnoviť priblíženie",
4992
5013
  support_chat_aria_label: "Chat podpory"
4993
- }, Y = {
4994
- ar: Oe,
4995
- bn: Ue,
4996
- bg: Be,
4997
- cs: Ve,
4998
- da: He,
4999
- de: We,
5000
- el: Ze,
5001
- en: J,
5002
- es: Ge,
5003
- et: ha,
5004
- fi: Je,
5005
- fil: $e,
5006
- fr: Ye,
5007
- hi: Qe,
5008
- hr: ma,
5009
- hu: ga,
5010
- is: ka,
5014
+ }, J = {
5015
+ ar: Fe,
5016
+ bn: Oe,
5017
+ bg: Ue,
5018
+ cs: Be,
5019
+ da: Ve,
5020
+ de: Ge,
5021
+ el: He,
5022
+ en: $,
5023
+ es: Ze,
5024
+ et: ma,
5025
+ fi: $e,
5026
+ fil: We,
5027
+ fr: Je,
5028
+ hi: Ye,
5029
+ hr: ua,
5030
+ hu: ha,
5031
+ is: ga,
5011
5032
  it: Xe,
5012
- ja: ea,
5013
- ko: aa,
5014
- lb: fa,
5015
- lt: va,
5016
- lv: ba,
5017
- mt: ya,
5018
- nb: wa,
5019
- nl: ta,
5020
- no: sa,
5021
- pl: oa,
5022
- pt: na,
5023
- ro: ia,
5024
- ru: _a,
5025
- sk: ja,
5026
- sv: ra,
5027
- th: la,
5028
- tr: ca,
5029
- ur: pa,
5030
- vi: da,
5031
- "zh-cn": ua
5032
- }, Sa = Object.keys(Y);
5033
- function za(n) {
5034
- return Sa.includes(n);
5033
+ ja: Qe,
5034
+ ko: ea,
5035
+ lb: va,
5036
+ lt: ba,
5037
+ lv: ka,
5038
+ mt: fa,
5039
+ nb: ya,
5040
+ nl: aa,
5041
+ no: ta,
5042
+ pl: sa,
5043
+ pt: oa,
5044
+ ro: na,
5045
+ ru: ra,
5046
+ sk: wa,
5047
+ sv: ia,
5048
+ th: _a,
5049
+ tr: la,
5050
+ ur: ca,
5051
+ vi: pa,
5052
+ "zh-cn": da
5053
+ }, ja = Object.keys(J);
5054
+ function Sa(i) {
5055
+ return ja.includes(i);
5035
5056
  }
5036
- const Ca = /* @__PURE__ */ new Set(["ar", "ur"]);
5037
- function Ja(n) {
5038
- return Ca.has(n);
5057
+ const za = /* @__PURE__ */ new Set(["ar", "ur"]);
5058
+ function Ja(i) {
5059
+ return za.has(i);
5039
5060
  }
5040
- function xa(n) {
5041
- return za(n) ? n : "en";
5061
+ function Ca(i) {
5062
+ return Sa(i) ? i : "en";
5042
5063
  }
5043
- function qa(n, e, t, o) {
5064
+ function xa(i, e, a, o) {
5044
5065
  var l;
5045
- const r = ((l = t == null ? void 0 : t[e]) == null ? void 0 : l[n]) || Y[e][n] || J[n] || n;
5066
+ const r = ((l = a == null ? void 0 : a[e]) == null ? void 0 : l[i]) || J[e][i] || $[i] || i;
5046
5067
  return o ? r.replace(
5047
5068
  /\{(\w+)\}/g,
5048
- (s, a) => a in o ? String(o[a]) : s
5069
+ (s, t) => t in o ? String(o[t]) : s
5049
5070
  ) : r;
5050
5071
  }
5051
- function Ea(n, e, t) {
5052
- return qa(
5072
+ function qa(i, e, a) {
5073
+ return xa(
5053
5074
  e,
5054
- xa(n.language),
5055
- n.translationOverrides,
5056
- t
5075
+ Ca(i.language),
5076
+ i.translationOverrides,
5077
+ a
5057
5078
  );
5058
5079
  }
5059
- class Aa {
5080
+ class Ea {
5060
5081
  constructor({
5061
5082
  config: e,
5062
- api: t,
5083
+ api: a,
5063
5084
  contactCtx: o,
5064
5085
  storageCtx: r,
5065
5086
  sessionsPollingIntervalSeconds: l,
5066
5087
  sharedSessions: s
5067
5088
  }) {
5068
- this.sessionsRefresher = new G(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new S({
5089
+ this.sessionsRefresher = new Z(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new S({
5069
5090
  session: null,
5070
5091
  isCreatingSession: !1,
5071
5092
  isResolvingSession: !1
@@ -5083,20 +5104,20 @@ class Aa {
5083
5104
  this.persistSession
5084
5105
  ));
5085
5106
  }, this.restoreActiveSessionTracking = () => {
5086
- var a;
5087
- (a = this.stopPersistingSession) == null || a.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5088
- }, this.trackActiveSession = (a) => {
5089
- var i;
5090
- (i = this.stopPersistingSession) == null || i.call(this), this.stopPersistingSession = a.sessionState.subscribe(
5107
+ var t;
5108
+ (t = this.stopPersistingSession) == null || t.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5109
+ }, this.trackActiveSession = (t) => {
5110
+ var n;
5111
+ (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = t.sessionState.subscribe(
5091
5112
  this.persistSession
5092
- ), this.persistSession(a.sessionState.get());
5093
- }, this.persistSession = ({ session: a }) => {
5094
- const i = this.storageCtx;
5095
- if (!i) return;
5096
- const c = a != null && a.isOpened ? a.id : null;
5113
+ ), this.persistSession(t.sessionState.get());
5114
+ }, this.persistSession = ({ session: t }) => {
5115
+ const n = this.storageCtx;
5116
+ if (!n) return;
5117
+ const c = t != null && t.isOpened ? t.id : null;
5097
5118
  if (c === this.persistedSessionId || !c && this.persistedSessionId === null) return;
5098
- this.persistedSessionId = c, (c ? i.setActiveSessionId(c) : i.clearActiveSessionId()).catch((_) => {
5099
- k.warn("failed to persist the active session", {
5119
+ this.persistedSessionId = c, (c ? n.setActiveSessionId(c) : n.clearActiveSessionId()).catch((_) => {
5120
+ g.warn("failed to persist the active session", {
5100
5121
  error: _ instanceof Error ? _.message : String(_)
5101
5122
  });
5102
5123
  });
@@ -5110,55 +5131,55 @@ class Aa {
5110
5131
  }, this.reset = async () => {
5111
5132
  this.sessionAbortController.abort(), this.sessionAbortController = new AbortController(), this.sessionState.reset();
5112
5133
  }, this.registerSessionsRefresherWrapper = () => {
5113
- var a;
5134
+ var t;
5114
5135
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
5115
- (a = this.contactCtx.state.get().contact) != null && a.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5116
- ({ contact: i }) => {
5117
- i != null && i.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
5136
+ (t = this.contactCtx.state.get().contact) != null && t.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5137
+ ({ contact: n }) => {
5138
+ n != null && n.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
5118
5139
  }
5119
5140
  );
5120
5141
  }, this.registerSessionsRefresher = () => {
5121
5142
  this.sessionsRefresher.startPolling(async () => {
5122
5143
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
5123
5144
  }, this.sessionsPollingIntervalSeconds * 1e3);
5124
- }, this.dispose = ({ clearActiveSession: a = !1 } = {}) => {
5125
- var i, c;
5126
- if (this.sessionsRefresher.reset(), this.sessionAbortController.abort(), (i = this.stopPersistingSession) == null || i.call(this), this.stopPersistingSession = void 0, (c = this.stopWaitingForContact) == null || c.call(this), this.stopWaitingForContact = void 0, this.sessionState.reset(), a && this.storageCtx)
5145
+ }, this.dispose = ({ clearActiveSession: t = !1 } = {}) => {
5146
+ var n, c;
5147
+ 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(), t && this.storageCtx)
5127
5148
  return this.persistedSessionId = null, this.storageCtx.clearActiveSessionId().catch((d) => {
5128
- k.warn("failed to clear the replaced session", {
5149
+ g.warn("failed to clear the replaced session", {
5129
5150
  error: d instanceof Error ? d.message : String(d)
5130
5151
  });
5131
5152
  });
5132
5153
  }, this.getParsedCustomData = () => Object.fromEntries(
5133
5154
  Object.entries(this.config.sessionCustomData || {}).map(
5134
- ([a, i]) => {
5155
+ ([t, n]) => {
5135
5156
  var c;
5136
- return typeof i == "string" ? [a, i] : typeof i == "boolean" ? [a, i] : typeof i == "number" ? [a, i] : [a, ((c = $(() => JSON.stringify(i))) == null ? void 0 : c.data) || ""];
5157
+ return typeof n == "string" ? [t, n] : typeof n == "boolean" ? [t, n] : typeof n == "number" ? [t, n] : [t, ((c = W(() => JSON.stringify(n))) == null ? void 0 : c.data) || ""];
5137
5158
  }
5138
5159
  )
5139
5160
  ), this.createSession = async () => {
5140
- const { signal: a } = this.sessionAbortController;
5161
+ const { signal: t } = this.sessionAbortController;
5141
5162
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
5142
5163
  try {
5143
- const i = await this.requestSession(a);
5144
- if (a.aborted) return null;
5145
- if (i.session) return i.session;
5146
- if (i.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
5147
- if (a.aborted) return null;
5148
- const c = await this.requestSession(a);
5149
- return a.aborted ? null : c.session ? c.session : (k.error("failed to create session", c.error), null);
5164
+ const n = await this.requestSession(t);
5165
+ if (t.aborted) return null;
5166
+ if (n.session) return n.session;
5167
+ if (n.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
5168
+ if (t.aborted) return null;
5169
+ const c = await this.requestSession(t);
5170
+ return t.aborted ? null : c.session ? c.session : (g.error("failed to create session", c.error), null);
5150
5171
  }
5151
- return k.error("failed to create session", i.error), null;
5152
- } catch (i) {
5153
- return a.aborted || k.error("failed to create session", i), null;
5172
+ return g.error("failed to create session", n.error), null;
5173
+ } catch (n) {
5174
+ return t.aborted || g.error("failed to create session", n), null;
5154
5175
  } finally {
5155
- a.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5176
+ t.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5156
5177
  }
5157
- }, this.requestSession = async (a) => {
5158
- var u, m, g;
5159
- const i = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, c = {
5178
+ }, this.requestSession = async (t) => {
5179
+ var u, h, k;
5180
+ const n = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, c = {
5160
5181
  ...this.getParsedCustomData(),
5161
- ...i ? { external_id: i } : {}
5182
+ ...n ? { external_id: n } : {}
5162
5183
  }, {
5163
5184
  data: d,
5164
5185
  error: _,
@@ -5167,155 +5188,152 @@ class Aa {
5167
5188
  {
5168
5189
  customData: Object.keys(c).length > 0 ? c : void 0
5169
5190
  },
5170
- a
5191
+ t
5171
5192
  );
5172
- if (a.aborted || !d)
5193
+ if (t.aborted || !d)
5173
5194
  return { session: null, status: p == null ? void 0 : p.status, error: _ };
5174
5195
  this.sessionState.setPartial({ session: d });
5175
5196
  try {
5176
- (g = (m = this.config.hooks) == null ? void 0 : m.onSessionCreated) == null || g.call(m, { session: d });
5197
+ (k = (h = this.config.hooks) == null ? void 0 : h.onSessionCreated) == null || k.call(h, { session: d });
5177
5198
  } catch (v) {
5178
- k.error("onSessionCreated hook failed", v);
5199
+ g.error("onSessionCreated hook failed", v);
5179
5200
  }
5180
5201
  return { session: d, status: p.status, error: void 0 };
5181
5202
  }, this.loadMoreSessions = async () => {
5182
5203
  if (this.sessionsState.get().isLastPage) return;
5183
- const { data: a } = await this.getSessions({
5204
+ const { data: t } = await this.getSessions({
5184
5205
  cursor: this.sessionsState.get().cursor
5185
5206
  });
5186
- if (a) {
5187
- const c = [...this.sessionsState.get().data, ...a.items].filter(
5207
+ if (t) {
5208
+ const c = [...this.sessionsState.get().data, ...t.items].filter(
5188
5209
  (d, _, p) => _ === p.findIndex((u) => d.id === u.id)
5189
5210
  );
5190
5211
  this.sessionsState.setPartial({
5191
5212
  data: c,
5192
- cursor: a.next || void 0,
5193
- isLastPage: a.next === null
5213
+ cursor: t.next || void 0,
5214
+ isLastPage: t.next === null
5194
5215
  });
5195
5216
  }
5196
- }, this.getSessions = async ({ cursor: a }) => {
5217
+ }, this.getSessions = async ({ cursor: t }) => {
5197
5218
  var c, d;
5198
5219
  if (!((c = this.contactCtx.state.get().contact) != null && c.token)) return { data: null };
5199
- const i = (d = this.contactCtx.state.get().contact) == null ? void 0 : d.externalId;
5220
+ const n = (d = this.contactCtx.state.get().contact) == null ? void 0 : d.externalId;
5200
5221
  return await this.api.getSessions({
5201
- cursor: a,
5202
- filters: i ? {
5203
- external_id: i
5222
+ cursor: t,
5223
+ filters: n ? {
5224
+ external_id: n
5204
5225
  } : {}
5205
5226
  });
5206
- }, this.setSessions = (a) => {
5207
- const i = [...a, ...this.sessionsState.get().data].filter(
5227
+ }, this.setSessions = (t) => {
5228
+ const n = [...t, ...this.sessionsState.get().data].filter(
5208
5229
  (c, d, _) => d === _.findIndex((p) => c.id === p.id)
5209
5230
  );
5210
- this.sessionsState.setPartial({ data: i });
5231
+ this.sessionsState.setPartial({ data: n });
5211
5232
  }, this.refreshSessions = async () => {
5212
- const { data: a } = await this.getSessions({ cursor: void 0 });
5213
- a && this.setSessions(a.items);
5233
+ const { data: t } = await this.getSessions({ cursor: void 0 });
5234
+ t && this.setSessions(t.items);
5214
5235
  }, this.resolveSession = async () => {
5215
- const a = this.sessionState.get().session;
5216
- if (!a || !a.isOpened)
5236
+ const t = this.sessionState.get().session;
5237
+ if (!t || !t.isOpened)
5217
5238
  return { success: !1, error: "Session is not opened" };
5218
5239
  this.sessionState.setPartial({ isResolvingSession: !0 });
5219
- const { signal: i } = this.sessionAbortController, c = await this.api.resolveSession({ session_id: a.id }, i).catch((p) => {
5220
- if (i.aborted) return null;
5240
+ const { signal: n } = this.sessionAbortController, c = await this.api.resolveSession({ session_id: t.id }, n).catch((p) => {
5241
+ if (n.aborted) return null;
5221
5242
  throw p;
5222
5243
  });
5223
- if (!c || i.aborted)
5244
+ if (!c || n.aborted)
5224
5245
  return { success: !1, error: "Session was reset" };
5225
5246
  const { data: d, error: _ } = c;
5226
5247
  return d ? (this.sessionState.setPartial({ session: d, isResolvingSession: !1 }), { success: !0, data: d }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: _ });
5227
- }, this.createStateCheckpoint = async (a) => {
5248
+ }, this.createStateCheckpoint = async (t) => {
5228
5249
  var d;
5229
- const i = (d = this.sessionState.get().session) == null ? void 0 : d.id;
5230
- if (!i) return;
5250
+ const n = (d = this.sessionState.get().session) == null ? void 0 : d.id;
5251
+ if (!n) return;
5231
5252
  const { data: c } = await this.api.createStateCheckpoint({
5232
- session_id: i,
5233
- payload: a
5253
+ session_id: n,
5254
+ payload: t
5234
5255
  });
5235
5256
  return c != null && c.success ? { success: !0 } : { success: !1 };
5236
- }, this.config = e, this.api = t, this.contactCtx = o, this.storageCtx = r, this.sessionsPollingIntervalSeconds = l, s ? this.sessionsState = s : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
5257
+ }, this.config = e, this.api = a, this.contactCtx = o, this.storageCtx = r, this.sessionsPollingIntervalSeconds = l, s ? this.sessionsState = s : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
5237
5258
  }
5238
5259
  }
5239
- const Pa = (n, e, { sendsPageContext: t }) => {
5240
- const o = Ma(n), r = t && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(Ta) } : void 0, l = t && (e.clientContext || r) ? { ...o, ...e.clientContext, ...r } : o, s = e.connectionRequestId ? {
5260
+ const Aa = (i, e, { sendsPageContext: a }) => {
5261
+ const o = Ia(i), r = a && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(Pa) } : void 0, l = a && (e.clientContext || r) ? { ...o, ...e.clientContext, ...r } : o, s = e.connectionRequestId ? {
5241
5262
  ...l,
5242
5263
  opencx__connection_request_id: e.connectionRequestId
5243
- } : l, a = e.withPageEntity === !1 && s && "entity" in s ? Ia(s, "entity") : s;
5264
+ } : l, t = e.withPageEntity === !1 && s && "entity" in s ? Ta(s, "entity") : s;
5244
5265
  return {
5245
- clientContext: e.background ? { ...a, opencx__background: !0 } : a,
5266
+ clientContext: e.background ? { ...t, opencx__background: !0 } : t,
5246
5267
  custom_data: {
5247
- ...n.messageCustomData || {},
5268
+ ...i.messageCustomData || {},
5248
5269
  ...e.customData || {}
5249
5270
  }
5250
5271
  };
5251
- }, Ta = ({ type: n, id: e, title: t, meta: o }) => ({
5252
- type: n,
5272
+ }, Pa = ({ type: i, id: e, title: a, meta: o }) => ({
5273
+ type: i,
5253
5274
  id: e,
5254
- title: t,
5275
+ title: a,
5255
5276
  ...o ? { meta: o } : {}
5256
- }), Ia = (n, e) => {
5257
- const { [e]: t, ...o } = n;
5277
+ }), Ta = (i, e) => {
5278
+ const { [e]: a, ...o } = i;
5258
5279
  return Object.keys(o).length > 0 ? o : void 0;
5259
- }, Ma = (n) => {
5260
- if (typeof n.context != "function") return n.context;
5280
+ }, Ia = (i) => {
5281
+ if (typeof i.context != "function") return i.context;
5261
5282
  try {
5262
- return n.context();
5283
+ return i.context();
5263
5284
  } catch (e) {
5264
- k.error("context getter threw; sending without context", e);
5285
+ g.error("context getter threw; sending without context", e);
5265
5286
  return;
5266
5287
  }
5267
- }, Da = (n) => {
5268
- const e = n.features;
5269
- if (!e) return;
5270
- const t = {};
5271
- return e.preamble !== void 0 && (t.preamble = e.preamble), e.inlineUi !== void 0 && (t.inline_ui = e.inlineUi), e.pageContext !== void 0 && (t.page_context = e.pageContext), e.clientTools !== void 0 && (t.client_tools = e.clientTools), Object.keys(t).length > 0 ? t : void 0;
5272
- }, Na = ({
5273
- config: n,
5288
+ }, Ma = (i) => {
5289
+ const e = i.features, a = {
5290
+ page_context: (e == null ? void 0 : e.pageContext) === !0,
5291
+ client_tools: (e == null ? void 0 : e.pageContext) === !0 && (e == null ? void 0 : e.clientTools) === !0,
5292
+ page_actions: (e == null ? void 0 : e.pageContext) === !0 && (e == null ? void 0 : e.clientTools) === !0 && (e == null ? void 0 : e.pageActions) === !0
5293
+ };
5294
+ return e && (e.preamble !== void 0 && (a.preamble = e.preamble), e.inlineUi !== void 0 && (a.inline_ui = e.inlineUi)), a;
5295
+ }, Da = ({
5296
+ config: i,
5274
5297
  input: e,
5275
- uuid: t,
5298
+ uuid: a,
5276
5299
  sessionId: o,
5277
5300
  content: r,
5278
5301
  initialMessages: l,
5279
5302
  sendsPageContext: s
5280
5303
  }) => {
5281
- var a, i, c, d, _, p, u, m;
5304
+ var t, n, c, d;
5282
5305
  return {
5283
- uuid: t,
5284
- bot_token: n.token,
5285
- headers: n.headers,
5286
- query_params: n.queryParams,
5287
- body_properties: n.bodyProperties,
5306
+ uuid: a,
5307
+ bot_token: i.token,
5308
+ headers: i.headers,
5309
+ query_params: i.queryParams,
5310
+ body_properties: i.bodyProperties,
5288
5311
  session_id: o,
5289
5312
  content: r,
5290
5313
  attachments: e.attachments,
5291
- ...Pa(n, e, { sendsPageContext: s }),
5292
- language: n.language,
5293
- features: Da(n),
5294
- presentation: n.presentation,
5295
- capabilities: [
5296
- (a = n.capabilities) == null ? void 0 : a.connections,
5297
- (i = n.capabilities) == null ? void 0 : i.structuredQuestions,
5298
- (c = n.capabilities) == null ? void 0 : c.richReplies,
5299
- (d = n.capabilities) == null ? void 0 : d.pageEffects
5300
- ].some((g) => g !== void 0) ? {
5301
- connections: (_ = n.capabilities) == null ? void 0 : _.connections,
5302
- structured_questions: (p = n.capabilities) == null ? void 0 : p.structuredQuestions,
5303
- rich_replies: (u = n.capabilities) == null ? void 0 : u.richReplies,
5304
- page_effects: (m = n.capabilities) == null ? void 0 : m.pageEffects
5305
- } : void 0,
5314
+ ...Aa(i, e, { sendsPageContext: s }),
5315
+ language: i.language,
5316
+ features: Ma(i),
5317
+ presentation: i.presentation,
5318
+ capabilities: {
5319
+ connections: ((t = i.capabilities) == null ? void 0 : t.connections) === !0,
5320
+ structured_questions: (n = i.capabilities) == null ? void 0 : n.structuredQuestions,
5321
+ rich_replies: (c = i.capabilities) == null ? void 0 : c.richReplies,
5322
+ page_effects: (d = i.capabilities) == null ? void 0 : d.pageEffects
5323
+ },
5306
5324
  exit_mode_prompt: e.exitModePrompt,
5307
- initial_messages: l.length > 0 ? l.map((g) => ({ uuid: g.id, content: g.data.message })) : void 0
5325
+ initial_messages: l.length > 0 ? l.map((_) => ({ uuid: _.id, content: _.data.message })) : void 0
5308
5326
  };
5309
- }, C = class C {
5327
+ }, x = class x {
5310
5328
  constructor({
5311
5329
  config: e,
5312
- api: t,
5330
+ api: a,
5313
5331
  sessionCtx: o,
5314
5332
  contactCtx: r,
5315
5333
  streaming: l,
5316
5334
  sendsPageContext: s,
5317
- getClientCapabilities: a,
5318
- getRequestConfig: i,
5335
+ getClientCapabilities: t,
5336
+ getRequestConfig: n,
5319
5337
  isStreaming: c,
5320
5338
  getSendsPageContext: d
5321
5339
  }) {
@@ -5329,38 +5347,41 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5329
5347
  }), this.draftState = new S({
5330
5348
  text: "",
5331
5349
  mentions: []
5332
- }), this.agentHandlers = null, this.bufferedAgentSends = [], this.sendMessageAbortController = new AbortController(), this.messageIdsDispatchedToOnMessageReceivedHook = /* @__PURE__ */ new Set(), this.sentTextHistory = [], this.reset = () => {
5333
- this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [], this.draftState.reset();
5350
+ }), this.agentHandlers = null, this.bufferedAgentSends = [], this.sendMessageAbortController = new AbortController(), this.conversationGeneration = 0, this.captureConversation = () => {
5351
+ const _ = this.conversationGeneration;
5352
+ return () => _ === this.conversationGeneration;
5353
+ }, this.messageIdsDispatchedToOnMessageReceivedHook = /* @__PURE__ */ new Set(), this.sentTextHistory = [], this.reset = () => {
5354
+ this.conversationGeneration++, this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [], this.draftState.reset();
5334
5355
  }, this.rememberSentText = (_) => {
5335
5356
  const p = _.trim();
5336
- !p || this.sentTextHistory.at(-1) === p || (this.sentTextHistory.push(p), this.sentTextHistory.length > C.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
5357
+ !p || this.sentTextHistory.at(-1) === p || (this.sentTextHistory.push(p), this.sentTextHistory.length > x.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
5337
5358
  }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (_) => {
5338
5359
  this.agentHandlers = _;
5339
5360
  const p = this.bufferedAgentSends;
5340
5361
  this.bufferedAgentSends = [], p.forEach((u) => {
5341
- C.dispatchToEngine(_, u);
5362
+ x.dispatchToEngine(_, u);
5342
5363
  });
5343
5364
  }, this.unregisterAgentHandlers = (_) => {
5344
5365
  this.agentHandlers === _ && (this.agentHandlers = null);
5345
5366
  }, this.dispatchToOnMessageReceivedHook = (_) => {
5346
- var u, m;
5367
+ var u, h;
5347
5368
  if (_.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(_.id))
5348
5369
  return;
5349
5370
  const p = this.sessionCtx.sessionState.get().session;
5350
- p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(_.id), (m = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || m.call(u, { message: _, session: p }));
5371
+ p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(_.id), (h = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || h.call(u, { message: _, session: p }));
5351
5372
  }, this.markAsDispatchedToOnMessageReceivedHook = (_) => {
5352
5373
  _.forEach(
5353
5374
  (p) => this.messageIdsDispatchedToOnMessageReceivedHook.add(p)
5354
5375
  );
5355
5376
  }, this.buildPersistentInitialMessages = () => {
5356
5377
  var p, u;
5357
- return !((p = this.sessionCtx.sessionState.get().session) != null && p.id) && this.state.get().messages.length === 0 && ((u = this.config.advancedInitialMessages) == null ? void 0 : u.some((m) => m.persistent)) ? (this.config.advancedInitialMessages || []).filter((m) => m.persistent).map(
5358
- (m) => ({
5359
- id: x(),
5378
+ return !((p = this.sessionCtx.sessionState.get().session) != null && p.id) && this.state.get().messages.length === 0 && ((u = this.config.advancedInitialMessages) == null ? void 0 : u.some((h) => h.persistent)) ? (this.config.advancedInitialMessages || []).filter((h) => h.persistent).map(
5379
+ (h) => ({
5380
+ id: q(),
5360
5381
  component: "bot_message",
5361
5382
  type: "AI",
5362
5383
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5363
- data: { message: m.message },
5384
+ data: { message: h.message },
5364
5385
  agent: this.config.bot ? { ...this.config.bot, isAi: !0, id: null } : void 0
5365
5386
  })
5366
5387
  ) : [];
@@ -5373,49 +5394,50 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5373
5394
  return ((p = this.sessionCtx.sessionState.get().session) == null ? void 0 : p.id) ?? null;
5374
5395
  }, this.rollbackOptimisticMessages = (_) => {
5375
5396
  if (_.length === 0) return;
5376
- const p = new Set(_), u = this.state.get().messages, m = u.filter((g) => !p.has(g.id));
5377
- m.length !== u.length && this.state.setPartial({ messages: m });
5397
+ const p = new Set(_), u = this.state.get().messages, h = u.filter((k) => !p.has(k.id));
5398
+ h.length !== u.length && this.state.setPartial({ messages: h });
5378
5399
  }, this.notifySendAccepted = (_) => {
5379
5400
  var p;
5380
5401
  try {
5381
5402
  (p = _.onAccepted) == null || p.call(_);
5382
5403
  } catch (u) {
5383
- k.error("send acceptance callback failed", u);
5404
+ g.error("send acceptance callback failed", u);
5384
5405
  }
5385
5406
  }, this.stageUserTurn = async (_, { pending: p }) => {
5386
- const u = this.buildUserMessage(_);
5387
- if (!u) return null;
5388
- const m = p ? { ...u, pending: !0 } : u, g = this.buildPersistentInitialMessages(), v = [
5389
- ...g.map((b) => b.id),
5390
- m.id
5407
+ const u = this.captureConversation(), h = this.buildUserMessage(_);
5408
+ if (!h) return null;
5409
+ const k = p ? { ...h, pending: !0 } : h, v = this.buildPersistentInitialMessages(), f = [
5410
+ ...v.map((y) => y.id),
5411
+ k.id
5391
5412
  ];
5392
5413
  this.state.setPartial({
5393
5414
  messages: [
5394
- ...g,
5415
+ ...v,
5395
5416
  ...this.state.get().messages,
5396
- ...m.background ? [] : [m]
5417
+ ...k.background ? [] : [k]
5397
5418
  ]
5398
5419
  });
5399
- let f;
5420
+ let b;
5400
5421
  try {
5401
- f = await this.ensureSessionId();
5402
- } catch (b) {
5403
- throw this.rollbackOptimisticMessages(v), b;
5422
+ b = await this.ensureSessionId();
5423
+ } catch (y) {
5424
+ if (!u()) return null;
5425
+ throw this.rollbackOptimisticMessages(f), y;
5404
5426
  }
5405
- return f ? { sessionId: f, userMessage: m, initialMessages: g } : (this.rollbackOptimisticMessages(v), null);
5427
+ return u() ? b ? { sessionId: b, userMessage: k, initialMessages: v } : (this.rollbackOptimisticMessages(f), null) : null;
5406
5428
  }, this.buildQueuedUserMessage = (_) => {
5407
- var m;
5429
+ var h;
5408
5430
  const p = this.buildUserMessage(_);
5409
5431
  if (!p) return null;
5410
- const u = (m = this.sessionCtx.sessionState.get().session) == null ? void 0 : m.id;
5432
+ const u = (h = this.sessionCtx.sessionState.get().session) == null ? void 0 : h.id;
5411
5433
  return u ? { sessionId: u, userMessage: { ...p, pending: !0 } } : null;
5412
5434
  }, this.buildUserMessage = (_) => {
5413
5435
  var p;
5414
- return !_.content.trim() && (!_.attachments || _.attachments.length === 0) ? (k.warn("cannot send an empty message of no content or attachments"), null) : {
5436
+ return !_.content.trim() && (!_.attachments || _.attachments.length === 0) ? (g.warn("cannot send an empty message of no content or attachments"), null) : {
5415
5437
  ...this.toUserMessage(
5416
5438
  _.content.trim(),
5417
5439
  _.attachments || void 0,
5418
- this.sendsPageContext ? C.markedElementNames(_.clientContext) : void 0,
5440
+ this.sendsPageContext ? x.markedElementNames(_.clientContext) : void 0,
5419
5441
  this.sendsPageContext && ((p = _.mentions) != null && p.length) ? _.mentions : void 0
5420
5442
  ),
5421
5443
  ..._.background ? { background: !0 } : {}
@@ -5429,14 +5451,14 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5429
5451
  (v) => v.id === _ && v.type === "USER" && v.pending
5430
5452
  );
5431
5453
  if (u === -1) return;
5432
- const m = p[u];
5433
- if (!m || m.type !== "USER") return;
5434
- const g = [...p];
5435
- g[u] = { ...m, pending: !1 }, this.state.setPartial({
5436
- messages: g
5454
+ const h = p[u];
5455
+ if (!h || h.type !== "USER") return;
5456
+ const k = [...p];
5457
+ k[u] = { ...h, pending: !1 }, this.state.setPartial({
5458
+ messages: k
5437
5459
  });
5438
5460
  }, this.sendMessage = async (_) => {
5439
- var u, m, g, v, f;
5461
+ var u, h, k, v, f;
5440
5462
  if (this.streaming) {
5441
5463
  if (!this.agentHandlers) {
5442
5464
  this.bufferedAgentSends.push(_);
@@ -5447,92 +5469,93 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5447
5469
  }
5448
5470
  let p;
5449
5471
  try {
5450
- const b = this.sessionCtx.sessionState.get().session, R = (b == null ? void 0 : b.assignee.kind) === "ai", X = this.state.get().isSendingMessageToAI, E = this.state.get().messages.at(-1);
5472
+ const b = this.sessionCtx.sessionState.get().session, z = (b == null ? void 0 : b.assignee.kind) === "ai", X = this.state.get().isSendingMessageToAI, A = this.state.get().messages.at(-1);
5451
5473
  if (this.blocksSendWhileAwaitingReply && (X || // If last message is from user, then bot response did not arrive yet
5452
- R && (E == null ? void 0 : E.type) === "USER" && E.id !== this.state.get().settledAgentUserMessageId)) {
5453
- k.warn("cannot send messages while awaiting AI response");
5474
+ z && (A == null ? void 0 : A.type) === "USER" && A.id !== this.state.get().settledAgentUserMessageId)) {
5475
+ g.warn("cannot send messages while awaiting AI response");
5454
5476
  return;
5455
5477
  }
5456
5478
  this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), p = this.sendMessageAbortController, this.state.setPartial({
5457
5479
  lastAIResMightSolveUserIssue: !1,
5458
5480
  isSendingMessage: !0,
5459
- isSendingMessageToAI: !!R || !b
5481
+ isSendingMessageToAI: !!z || !b
5460
5482
  });
5461
- const K = await this.stageUserTurn(_, { pending: !1 });
5462
- if (!K) return;
5463
- const { sessionId: ee, userMessage: L, initialMessages: ae } = K;
5483
+ const R = await this.stageUserTurn(_, { pending: !1 });
5484
+ if (!R) return;
5485
+ const { sessionId: Q, userMessage: K, initialMessages: ee } = R;
5464
5486
  this.notifySendAccepted(_);
5465
- const { data: y } = await this.api.sendMessage(
5466
- Na({
5487
+ const { data: w } = await this.api.sendMessage(
5488
+ Da({
5467
5489
  config: {
5468
5490
  ...this.getRequestConfig(),
5469
5491
  capabilities: this.getClientCapabilities()
5470
5492
  },
5471
5493
  input: _,
5472
- uuid: L.id,
5473
- sessionId: ee,
5474
- content: L.content,
5475
- initialMessages: ae,
5494
+ uuid: K.id,
5495
+ sessionId: Q,
5496
+ content: K.content,
5497
+ initialMessages: ee,
5476
5498
  sendsPageContext: this.sendsPageContext
5477
5499
  }),
5478
5500
  p.signal
5479
5501
  );
5480
- if (y != null && y.success) {
5481
- const z = this.toBotMessage(y);
5482
- if (z) {
5483
- const A = this.state.get().messages;
5484
- if (!!A.some(
5485
- (te) => te.id === z.id
5502
+ if (w != null && w.success) {
5503
+ const C = this.toBotMessage(w);
5504
+ if (C) {
5505
+ const P = this.state.get().messages;
5506
+ if (!!P.some(
5507
+ (ae) => ae.id === C.id
5486
5508
  )) {
5487
5509
  this.state.setPartial({
5488
- lastAIResMightSolveUserIssue: ((u = y.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((m = y.uiResponse) == null ? void 0 : m.mightSolveUserIssue)
5510
+ lastAIResMightSolveUserIssue: ((u = w.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((h = w.uiResponse) == null ? void 0 : h.mightSolveUserIssue)
5489
5511
  });
5490
5512
  return;
5491
5513
  }
5492
5514
  this.state.setPartial({
5493
- messages: [...A, z],
5494
- lastAIResMightSolveUserIssue: ((g = y.autopilotResponse) == null ? void 0 : g.mightSolveUserIssue) || ((v = y.uiResponse) == null ? void 0 : v.mightSolveUserIssue)
5495
- }), this.dispatchToOnMessageReceivedHook(z);
5515
+ messages: [...P, C],
5516
+ lastAIResMightSolveUserIssue: ((k = w.autopilotResponse) == null ? void 0 : k.mightSolveUserIssue) || ((v = w.uiResponse) == null ? void 0 : v.mightSolveUserIssue)
5517
+ }), this.dispatchToOnMessageReceivedHook(C);
5496
5518
  }
5497
- y.session && this.sessionCtx.sessionState.setPartial({ session: y.session });
5519
+ w.session && this.sessionCtx.sessionState.setPartial({ session: w.session });
5498
5520
  } else {
5499
- const z = this.toBotErrorMessage(
5500
- ((f = y == null ? void 0 : y.error) == null ? void 0 : f.message) || Ea(this.config, "turn_failed_message")
5501
- ), A = this.state.get().messages;
5521
+ const C = this.toBotErrorMessage(
5522
+ ((f = w == null ? void 0 : w.error) == null ? void 0 : f.message) || qa(this.config, "turn_failed_message")
5523
+ ), P = this.state.get().messages;
5502
5524
  this.state.setPartial({
5503
- messages: [...A, z]
5525
+ messages: [...P, C]
5504
5526
  });
5505
5527
  }
5506
5528
  } catch (b) {
5507
- p != null && p.signal.aborted || k.error("failed to send message", b);
5529
+ p != null && p.signal.aborted || g.error("failed to send message", b);
5508
5530
  } finally {
5509
5531
  p != null && p.signal.aborted || this.state.setPartial({
5510
5532
  isSendingMessage: !1,
5511
5533
  isSendingMessageToAI: !1
5512
5534
  });
5513
5535
  }
5514
- }, this.toUserMessage = (_, p, u, m) => {
5515
- const g = (() => {
5516
- const v = this.contactCtx.state.get().extraCollectedData;
5517
- return this.state.get().messages.length === 0 && v && Object.keys(v).length > 0 ? `${Object.entries(v).filter(([b, w]) => !!w).map(([b, w]) => `${b}: ${w}`).join(`
5536
+ }, this.toUserMessage = (_, p, u, h) => {
5537
+ const k = (() => {
5538
+ const f = this.contactCtx.state.get().extraCollectedData;
5539
+ 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(`
5518
5540
  `)}
5519
5541
 
5520
5542
  ${_}` : _;
5521
- })();
5543
+ })(), v = (/* @__PURE__ */ new Date()).toISOString();
5522
5544
  return {
5523
- id: x(),
5545
+ id: q(),
5524
5546
  type: "USER",
5525
- content: g,
5547
+ deliveredAt: v,
5548
+ content: k,
5526
5549
  attachments: p,
5527
5550
  markedElements: u,
5528
- mentions: m,
5529
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
5551
+ mentions: h,
5552
+ timestamp: v
5530
5553
  };
5531
5554
  }, this.toBotMessage = (_) => {
5532
5555
  var p;
5533
5556
  return _.success && _.autopilotResponse ? {
5534
5557
  type: "AI",
5535
- id: _.autopilotResponse.id || x(),
5558
+ id: _.autopilotResponse.id || q(),
5536
5559
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5537
5560
  component: "bot_message",
5538
5561
  agent: this.config.bot ? {
@@ -5553,7 +5576,7 @@ ${_}` : _;
5553
5576
  } : null;
5554
5577
  }, this.toBotErrorMessage = (_) => ({
5555
5578
  type: "AI",
5556
- id: x(),
5579
+ id: q(),
5557
5580
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5558
5581
  component: "bot_message",
5559
5582
  data: {
@@ -5561,7 +5584,7 @@ ${_}` : _;
5561
5584
  variant: "error",
5562
5585
  action: void 0
5563
5586
  }
5564
- }), this.config = e, this.getClientCapabilities = a ?? (() => this.getRequestConfig().capabilities), this.api = t, this.sessionCtx = o, this.contactCtx = r, this.isStreaming = c ?? (() => l), this.getRequestConfig = i ?? (() => this.config), this.getSendsPageContext = d ?? (() => s);
5587
+ }), this.config = e, this.getClientCapabilities = t ?? (() => this.getRequestConfig().capabilities), this.api = a, this.sessionCtx = o, this.contactCtx = r, this.isStreaming = c ?? (() => l), this.getRequestConfig = n ?? (() => this.config), this.getSendsPageContext = d ?? (() => s);
5565
5588
  }
5566
5589
  /**
5567
5590
  * Current transport choice. The org or this embed may request polling
@@ -5574,18 +5597,18 @@ ${_}` : _;
5574
5597
  return this.getSendsPageContext();
5575
5598
  }
5576
5599
  /** Hand a send to the streaming engine; its failure can never propagate. */
5577
- static dispatchToEngine(e, t) {
5600
+ static dispatchToEngine(e, a) {
5578
5601
  try {
5579
- Promise.resolve(e.send(t)).catch((o) => {
5580
- k.error("streaming send failed", o);
5602
+ Promise.resolve(e.send(a)).catch((o) => {
5603
+ g.error("streaming send failed", o);
5581
5604
  });
5582
5605
  } catch (o) {
5583
- k.error("streaming send failed", o);
5606
+ g.error("streaming send failed", o);
5584
5607
  }
5585
5608
  }
5586
5609
  get hasPendingAgentWork() {
5587
- var e, t;
5588
- return this.bufferedAgentSends.length > 0 || (((t = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : t.call(e)) ?? !1);
5610
+ var e, a;
5611
+ return this.bufferedAgentSends.length > 0 || (((a = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : a.call(e)) ?? !1);
5589
5612
  }
5590
5613
  /**
5591
5614
  * Defensive read of `clientContext.page_marks` → the user bubble's context
@@ -5595,17 +5618,17 @@ ${_}` : _;
5595
5618
  * without a usable name are dropped.
5596
5619
  */
5597
5620
  static markedElementNames(e) {
5598
- const t = e == null ? void 0 : e.page_marks;
5599
- if (!Array.isArray(t)) return;
5600
- const o = t.flatMap((r) => {
5621
+ const a = e == null ? void 0 : e.page_marks;
5622
+ if (!Array.isArray(a)) return;
5623
+ const o = a.flatMap((r) => {
5601
5624
  if (typeof r != "object" || r === null) return [];
5602
- const l = r.elements, s = Array.isArray(l) ? l[0] : void 0, a = typeof s == "object" && s !== null && "name" in s ? s.name : void 0;
5603
- if (typeof a != "string" || a.length === 0) return [];
5604
- const i = r.note, c = r.snapshotUrl;
5625
+ const l = r.elements, s = Array.isArray(l) ? l[0] : void 0, t = typeof s == "object" && s !== null && "name" in s ? s.name : void 0;
5626
+ if (typeof t != "string" || t.length === 0) return [];
5627
+ const n = r.note, c = r.snapshotUrl;
5605
5628
  return [
5606
5629
  {
5607
- name: a,
5608
- ...typeof i == "string" && i.length > 0 ? { note: i } : {},
5630
+ name: t,
5631
+ ...typeof n == "string" && n.length > 0 ? { note: n } : {},
5609
5632
  ...typeof c == "string" && c.length > 0 ? { snapshotUrl: c } : {},
5610
5633
  mark: r
5611
5634
  }
@@ -5621,11 +5644,11 @@ ${_}` : _;
5621
5644
  return !this.streaming && this.config.disableSendingWhenAwaitingAIReply !== !1;
5622
5645
  }
5623
5646
  };
5624
- C.SENT_TEXT_HISTORY_MAX = 50;
5625
- let D = C;
5626
- class Ra {
5647
+ x.SENT_TEXT_HISTORY_MAX = 50;
5648
+ let D = x;
5649
+ class Na {
5627
5650
  constructor(e) {
5628
- var t, o;
5651
+ var a, o;
5629
5652
  this.widget = e, this.subscriptions = [], this.disposed = !1, this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
5630
5653
  if (!this.shouldRestoreLastSession) {
5631
5654
  this.didReadStoredSession = !0;
@@ -5651,7 +5674,7 @@ class Ra {
5651
5674
  isInitialFetchLoading: r,
5652
5675
  data: l
5653
5676
  }) => {
5654
- var s, a, i, c, d;
5677
+ var s, t, n, c, d;
5655
5678
  if (!(this.disposed || !this.didReadStoredSession)) {
5656
5679
  if (this.restorableSessionId && !((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
5657
5680
  const _ = l.find(
@@ -5664,9 +5687,9 @@ class Ra {
5664
5687
  if (r) return;
5665
5688
  this.restorableSessionId = null;
5666
5689
  }
5667
- if ((a = this.config.router) != null && a.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5690
+ if ((t = this.config.router) != null && t.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5668
5691
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
5669
- !((i = this.sessionCtx.sessionState.get().session) != null && i.id)) {
5692
+ !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
5670
5693
  const _ = (c = l.find((p) => p.isOpened)) == null ? void 0 : c.id;
5671
5694
  return _ ? this.toChatScreen(_) : void 0;
5672
5695
  }
@@ -5677,24 +5700,24 @@ class Ra {
5677
5700
  }, this.toSessionsScreen = () => {
5678
5701
  this.navigateConversation || this.resetChat(), this.state.setPartial({ screen: "sessions" });
5679
5702
  }, this.toChatScreen = (r) => {
5680
- var s, a;
5703
+ var s, t;
5681
5704
  if (this.navigateConversation) return this.navigateConversation(r);
5682
5705
  this.resetChat();
5683
5706
  let l;
5684
5707
  if (r) {
5685
- if (l = this.sessionCtx.sessionsState.get().data.find((i) => i.id === r), !l) return;
5708
+ if (l = this.sessionCtx.sessionsState.get().data.find((n) => n.id === r), !l) return;
5686
5709
  this.sessionCtx.sessionState.setPartial({ session: l });
5687
5710
  }
5688
- return this.state.setPartial({ screen: "chat" }), (a = (s = this.config.hooks) == null ? void 0 : s.onNavigateToChat) == null || a.call(s, { session: l }), this.widget;
5711
+ return this.state.setPartial({ screen: "chat" }), (t = (s = this.config.hooks) == null ? void 0 : s.onNavigateToChat) == null || t.call(s, { session: l }), this.widget;
5689
5712
  }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new S({
5690
- screen: this.contactCtx.shouldCollectData() ? "welcome" : (t = this.config.router) != null && t.chatScreenOnly ? "chat" : "sessions"
5713
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : (a = this.config.router) != null && a.chatScreenOnly ? "chat" : "sessions"
5691
5714
  }), this.shouldRestoreLastSession = ((o = this.config.router) == null ? void 0 : o.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5692
5715
  }
5693
5716
  }
5694
- class Ka {
5717
+ class Ra {
5695
5718
  constructor({
5696
5719
  storage: e,
5697
- config: t
5720
+ config: a
5698
5721
  }) {
5699
5722
  this.KEYS = {
5700
5723
  contactToken: (o) => `opencx-widget:org-token-${o}:contact-token`,
@@ -5735,11 +5758,11 @@ class Ka {
5735
5758
  return o === "docked" || o === "floating" ? o : null;
5736
5759
  }, this.setCompanionSidebarMode = async (o) => {
5737
5760
  await this.storage.set(this.companionKey("sidebar-mode"), o);
5738
- }, this.storage = e, this.config = t;
5761
+ }, this.storage = e, this.config = a;
5739
5762
  }
5740
5763
  }
5741
- function La({
5742
- org: n,
5764
+ function Ka({
5765
+ org: i,
5743
5766
  agent: e
5744
5767
  }) {
5745
5768
  return e ? {
@@ -5751,53 +5774,50 @@ function La({
5751
5774
  dictation: e.features.dictation,
5752
5775
  attachments: e.features.attachments,
5753
5776
  pageContext: e.features.page_context,
5754
- clientTools: e.features.client_tools
5777
+ clientTools: e.features.client_tools,
5778
+ pageActions: e.features.page_actions === !0
5755
5779
  }
5756
5780
  } : {
5757
- name: n.name,
5781
+ name: i.name,
5758
5782
  avatarUrl: null,
5759
5783
  streaming: !1,
5760
5784
  features: {
5761
5785
  dictation: !1,
5762
5786
  attachments: !0,
5763
5787
  pageContext: !1,
5764
- clientTools: !1
5788
+ clientTools: !1,
5789
+ pageActions: !1
5765
5790
  }
5766
5791
  };
5767
5792
  }
5768
- function M(n, e) {
5769
- return n && e !== !1;
5793
+ function La(i, e) {
5794
+ return i && e !== !1;
5770
5795
  }
5771
- function Fa(n, e) {
5772
- const t = e.features;
5796
+ function Fa(i, e) {
5797
+ const a = e.features;
5773
5798
  return {
5774
- dictation: M(n.features.dictation, t == null ? void 0 : t.dictation),
5775
- attachments: n.features.attachments,
5776
- pageContext: M(
5777
- n.features.pageContext,
5778
- t == null ? void 0 : t.pageContext
5779
- ),
5780
- clientTools: M(
5781
- n.features.clientTools,
5782
- t == null ? void 0 : t.clientTools
5783
- )
5799
+ dictation: La(i.features.dictation, a == null ? void 0 : a.dictation),
5800
+ attachments: i.features.attachments,
5801
+ pageContext: i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0,
5802
+ clientTools: i.features.clientTools && i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0 && (a == null ? void 0 : a.clientTools) === !0,
5803
+ 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
5784
5804
  };
5785
5805
  }
5786
5806
  class Oa extends Error {
5787
- constructor(e, t, o) {
5788
- super(t), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5807
+ constructor(e, a, o) {
5808
+ super(a), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5789
5809
  }
5790
5810
  }
5791
5811
  const j = class j {
5792
5812
  constructor({
5793
5813
  config: e,
5794
- storage: t,
5814
+ storage: a,
5795
5815
  getClientCapabilities: o,
5796
5816
  getRequestConfig: r,
5797
5817
  modes: l,
5798
5818
  org: s,
5799
- agent: a,
5800
- parent: i
5819
+ agent: t,
5820
+ parent: n
5801
5821
  }) {
5802
5822
  if (this.modes = [], this.disposed = !1, this.createConversation = () => {
5803
5823
  const c = new j({
@@ -5824,24 +5844,24 @@ const j = class j {
5824
5844
  if (this.disposed) return;
5825
5845
  this.disposed = !0, this.routerCtx.dispose(), this.activeSessionPollingCtx.dispose();
5826
5846
  const d = this.sessionCtx.dispose({ clearActiveSession: c });
5827
- return this.messageCtx.reset(), this.uploadCtx.reset(), this.dictationCtx.stop(), d;
5847
+ return this.messageCtx.reset(), this.uploadCtx.reset(), this.dictationCtx.stop({ executeFinalCommand: !1 }), d;
5828
5848
  }, this.resetChat = () => {
5829
5849
  this.sessionCtx.reset(), this.messageCtx.reset(), this.uploadCtx.reset();
5830
5850
  }, this.reconcileAfterStream = (c) => this.activeSessionPollingCtx.reconcileAfterStream(c), !j.pollingIntervalsSeconds)
5831
5851
  throw Error(
5832
5852
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
5833
5853
  );
5834
- this.config = e, this.getRequestConfig = r ?? (() => this.config), this.getClientCapabilities = o, this.org = s, this.agent = a, this.api = (i == null ? void 0 : i.api) ?? new B({ config: e }), this.storageCtx = (i == null ? void 0 : i.storageCtx) ?? (t ? new Ka({ storage: t, config: e }) : void 0), this.modes = l, this.contactCtx = (i == null ? void 0 : i.contactCtx) ?? new ge({
5854
+ 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 Ra({ storage: a, config: e }) : void 0), this.modes = l, this.contactCtx = (n == null ? void 0 : n.contactCtx) ?? new he({
5835
5855
  api: this.api,
5836
5856
  config: this.config,
5837
5857
  storageCtx: this.storageCtx
5838
- }), this.sessionCtx = new Aa({
5858
+ }), this.sessionCtx = new Ea({
5839
5859
  config: this.config,
5840
5860
  api: this.api,
5841
5861
  contactCtx: this.contactCtx,
5842
5862
  // Remembers the open conversation so a reload can return to it.
5843
- storageCtx: i ? void 0 : this.storageCtx,
5844
- sharedSessions: i == null ? void 0 : i.sessionCtx.sessionsState,
5863
+ storageCtx: n ? void 0 : this.storageCtx,
5864
+ sharedSessions: n == null ? void 0 : n.sessionCtx.sessionsState,
5845
5865
  sessionsPollingIntervalSeconds: j.pollingIntervalsSeconds.sessions
5846
5866
  }), this.messageCtx = new D({
5847
5867
  config: this.config,
@@ -5856,24 +5876,24 @@ const j = class j {
5856
5876
  getSendsPageContext: () => this.features.pageContext,
5857
5877
  getClientCapabilities: o,
5858
5878
  getRequestConfig: r
5859
- }), this.uploadCtx = new ke(this.api), this.csatCtx = new be({
5879
+ }), this.uploadCtx = new ge(this.api), this.csatCtx = new ke({
5860
5880
  api: this.api,
5861
5881
  sessionCtx: this.sessionCtx,
5862
5882
  messageCtx: this.messageCtx
5863
- }), this.dictationCtx = new Fe({
5883
+ }), this.dictationCtx = new Le({
5864
5884
  api: this.api,
5865
5885
  config: this.config
5866
- }), this.activeSessionPollingCtx = new he({
5886
+ }), this.activeSessionPollingCtx = new me({
5867
5887
  api: this.api,
5868
5888
  config: this.config,
5869
5889
  sessionCtx: this.sessionCtx,
5870
5890
  messageCtx: this.messageCtx,
5871
5891
  sessionPollingIntervalSeconds: j.pollingIntervalsSeconds.session
5872
- }), this.routerCtx = new Ra(this);
5892
+ }), this.routerCtx = new Na(this);
5873
5893
  }
5874
5894
  get streaming() {
5875
- var e, t;
5876
- return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (t = this.messageCtx) != null && t.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming !== !1;
5895
+ var e, a;
5896
+ return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (a = this.messageCtx) != null && a.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming === !0;
5877
5897
  }
5878
5898
  /**
5879
5899
  * The org's features narrowed by this embed's `config.features` — the
@@ -5885,26 +5905,26 @@ const j = class j {
5885
5905
  };
5886
5906
  j.pollingIntervalsSeconds = null, j.initialize = async ({
5887
5907
  config: e,
5888
- storage: t,
5908
+ storage: a,
5889
5909
  getClientCapabilities: o,
5890
5910
  getRequestConfig: r
5891
5911
  }) => {
5892
- var s, a;
5893
- const l = await new B({
5912
+ var s, t;
5913
+ const l = await new U({
5894
5914
  config: e
5895
5915
  }).getExternalWidgetConfig();
5896
5916
  if (!l.data)
5897
- throw k.error("widget config fetch failed", l.error), new Oa(
5917
+ throw g.error("widget config fetch failed", l.error), new Oa(
5898
5918
  "config-fetch-failed",
5899
5919
  "Failed to fetch widget config",
5900
5920
  l.error
5901
5921
  );
5902
5922
  return j.pollingIntervalsSeconds = {
5903
5923
  session: ((s = l.data) == null ? void 0 : s.sessionPollingIntervalSeconds) || 10,
5904
- sessions: ((a = l.data) == null ? void 0 : a.sessionsPollingIntervalSeconds) || 60
5924
+ sessions: ((t = l.data) == null ? void 0 : t.sessionsPollingIntervalSeconds) || 60
5905
5925
  }, new j({
5906
5926
  config: e,
5907
- storage: t,
5927
+ storage: a,
5908
5928
  getClientCapabilities: o,
5909
5929
  getRequestConfig: r,
5910
5930
  modes: l.data.modes || [],
@@ -5912,20 +5932,20 @@ j.pollingIntervalsSeconds = null, j.initialize = async ({
5912
5932
  id: l.data.org.id,
5913
5933
  name: l.data.org.name
5914
5934
  },
5915
- agent: La(l.data)
5935
+ agent: Ka(l.data)
5916
5936
  });
5917
5937
  };
5918
- let W = j;
5919
- function Ya(n, e) {
5920
- return n ? {
5921
- streaming: n.streaming && (e == null ? void 0 : e.streaming) !== !1,
5922
- toolActivity: n.toolActivity === "hidden" || (e == null ? void 0 : e.toolActivity) === "hidden" ? "hidden" : n.toolActivity === "status" || (e == null ? void 0 : e.toolActivity) === "status" ? "status" : "details",
5923
- reasoning: n.reasoning && (e == null ? void 0 : e.reasoning) !== !1
5938
+ let G = j;
5939
+ function Ya(i, e) {
5940
+ return i ? {
5941
+ streaming: i.streaming && (e == null ? void 0 : e.streaming) !== !1,
5942
+ toolActivity: i.toolActivity === "hidden" || (e == null ? void 0 : e.toolActivity) === "hidden" ? "hidden" : i.toolActivity === "status" || (e == null ? void 0 : e.toolActivity) === "status" ? "status" : "details",
5943
+ reasoning: i.reasoning && (e == null ? void 0 : e.reasoning) !== !1
5924
5944
  } : e;
5925
5945
  }
5926
- class Qa {
5927
- constructor({ attack: e, release: t }) {
5928
- this.value = 0, this.attack = e, this.release = t;
5946
+ class Xa {
5947
+ constructor({ attack: e, release: a }) {
5948
+ this.value = 0, this.attack = e, this.release = a;
5929
5949
  }
5930
5950
  next(e) {
5931
5951
  return this.value += (e - this.value) * (e > this.value ? this.attack : this.release), this.value;
@@ -5934,56 +5954,56 @@ class Qa {
5934
5954
  return this.value;
5935
5955
  }
5936
5956
  }
5937
- const T = [
5957
+ const I = [
5938
5958
  "compact",
5939
5959
  "sidebar",
5940
5960
  "fullscreen"
5941
5961
  ], Ua = new Set(
5942
- T
5962
+ I
5943
5963
  );
5944
- function Q(n) {
5945
- return Ua.has(n);
5964
+ function Y(i) {
5965
+ return Ua.has(i);
5946
5966
  }
5947
- function Xa(n) {
5948
- if (!Array.isArray(n)) return T;
5949
- const e = [], t = /* @__PURE__ */ new Set();
5950
- for (const o of n)
5951
- !Q(o) || t.has(o) || (t.add(o), e.push(o));
5952
- return e.length > 0 ? e : T;
5967
+ function Qa(i) {
5968
+ if (!Array.isArray(i)) return I;
5969
+ const e = [], a = /* @__PURE__ */ new Set();
5970
+ for (const o of i)
5971
+ !Y(o) || a.has(o) || (a.add(o), e.push(o));
5972
+ return e.length > 0 ? e : I;
5953
5973
  }
5954
- function et(n, e) {
5955
- return Q(n) && e.includes(n) ? n : e[0] ?? T[0];
5974
+ function et(i, e) {
5975
+ return Y(i) && e.includes(i) ? i : e[0] ?? I[0];
5956
5976
  }
5957
- function at(n, e) {
5958
- return n === "left" || n === "right" ? n : e === "rtl" ? "left" : "right";
5977
+ function at(i, e) {
5978
+ return i === "left" || i === "right" ? i : e === "rtl" ? "left" : "right";
5959
5979
  }
5960
- function tt(n) {
5961
- return n === "docked" ? "docked" : "floating";
5980
+ function tt(i) {
5981
+ return i === "docked" ? "docked" : "floating";
5962
5982
  }
5963
5983
  export {
5964
- pe as ConnectionAttemptUnavailableError,
5965
- ce as ConnectionRequestExpiredError,
5966
- Qa as DictationLevelSmoother,
5984
+ ce as ConnectionAttemptUnavailableError,
5985
+ le as ConnectionRequestExpiredError,
5986
+ Xa as DictationLevelSmoother,
5967
5987
  S as PrimitiveState,
5968
- W as WidgetCtx,
5988
+ G as WidgetCtx,
5969
5989
  Oa as WidgetInitializationError,
5970
- Na as buildSendMessageBody,
5971
- x as genUuid,
5972
- qa as getTranslation,
5973
- Ga as isAgentStreamKeepalive,
5974
- me as isExhaustive,
5975
- Z as isRecord,
5990
+ Da as buildSendMessageBody,
5991
+ q as genUuid,
5992
+ xa as getTranslation,
5993
+ Wa as isAgentStreamKeepalive,
5994
+ ue as isExhaustive,
5995
+ H as isRecord,
5976
5996
  Ja as isRtlLanguage,
5977
- za as isSupportedLanguage,
5997
+ Sa as isSupportedLanguage,
5978
5998
  $a as isTurnSteeredPart,
5979
- k as log,
5980
- Xa as normalizeCompanionLayouts,
5999
+ g as log,
6000
+ Qa as normalizeCompanionLayouts,
5981
6001
  Ya as resolveClientPresentation,
5982
6002
  et as resolveCompanionDefaultLayout,
5983
- Ma as resolveConfigContext,
5984
- xa as resolveLanguage,
6003
+ Ia as resolveConfigContext,
6004
+ Ca as resolveLanguage,
5985
6005
  tt as resolveSidebarMode,
5986
6006
  at as resolveSidebarSide,
5987
- Ea as translate
6007
+ qa as translate
5988
6008
  };
5989
6009
  //# sourceMappingURL=index.js.map