@opencx/widget-core 5.0.0-beta.9 → 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,160 +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.sendPageReply = async (s, a) => {
195
+ if (!t.ok)
196
+ throw new Error(`Failed to stop stream: ${t.status}`);
197
+ }, this.sendPageReply = async (s, t) => {
198
198
  try {
199
199
  await this.client.POST("/backend/widget/v5/chat/{sessionId}/page-reply", {
200
200
  params: { path: { sessionId: s } },
201
- body: a
201
+ body: t
202
202
  });
203
203
  } catch {
204
204
  }
205
- }, this.getAgentTurnMessages = async (s, a) => {
206
- const { data: i, response: c } = await this.client.GET(
205
+ }, this.getAgentTurnMessages = async (s, t) => {
206
+ const { data: n, response: c } = await this.client.GET(
207
207
  "/backend/widget/v5/chat/{sessionId}/messages",
208
208
  {
209
209
  params: {
210
210
  path: { sessionId: s },
211
211
  query: {
212
- toolActivity: a == null ? void 0 : a.toolActivity,
213
- 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"
214
214
  }
215
215
  }
216
216
  }
217
217
  );
218
- return i ? {
219
- ...i,
220
- handled_connection_request_ids: i.handled_connection_request_ids ?? []
221
- } : (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);
222
222
  }, this.createDictationSession = async ({
223
223
  language: s
224
224
  }) => {
225
- const { data: a, response: i } = await this.client.POST(
225
+ const { data: t, response: n } = await this.client.POST(
226
226
  "/backend/widget/v5/dictation/sessions",
227
227
  { body: s ? { language: s } : {} }
228
228
  );
229
- if (!a)
230
- throw new Error(`Failed to start dictation: ${i.status}`);
231
- return a;
229
+ if (!t)
230
+ throw new Error(`Failed to start dictation: ${n.status}`);
231
+ return t;
232
232
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
233
233
  params: {
234
234
  header: { "x-bot-token": this.config.token }
235
235
  }
236
- }), 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", {
237
237
  body: s,
238
- signal: a
238
+ signal: t
239
239
  }), this.createUnverifiedContact = async (s) => await this.client.POST(
240
240
  "/backend/widget/v2/contact/create-unverified",
241
241
  {
242
242
  params: { header: { "x-bot-token": this.config.token } },
243
243
  body: s
244
244
  }
245
- ), 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", {
246
246
  body: s,
247
- signal: a
247
+ signal: t
248
248
  }), this.pollSessionAndHistory = async ({
249
249
  sessionId: s,
250
- abortSignal: a
250
+ abortSignal: t
251
251
  }) => await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
252
252
  params: { path: { sessionId: s } },
253
- signal: a
253
+ signal: t
254
254
  }), this.getSessions = async ({
255
255
  cursor: s,
256
- filters: a,
257
- abortSignal: i
256
+ filters: t,
257
+ abortSignal: n
258
258
  }) => await this.client.GET("/backend/widget/v2/sessions", {
259
259
  params: {
260
260
  query: {
261
261
  offset: s,
262
- filters: JSON.stringify(a)
262
+ filters: JSON.stringify(t)
263
263
  }
264
264
  },
265
- signal: i
265
+ signal: n
266
266
  }), this.uploadFile = async ({
267
267
  file: s,
268
- abortSignal: a,
269
- onProgress: i
268
+ abortSignal: t,
269
+ onProgress: n
270
270
  }) => new Promise((c, d) => {
271
271
  var f;
272
272
  const _ = new FormData();
273
273
  _.append("file", s);
274
274
  const p = new XMLHttpRequest();
275
- if (a && (a.addEventListener("abort", () => {
275
+ if (t && (t.addEventListener("abort", () => {
276
276
  p.abort(), d(new DOMException("Aborted", "AbortError"));
277
- }), a.aborted)) {
277
+ }), t.aborted)) {
278
278
  d(new DOMException("Aborted", "AbortError"));
279
279
  return;
280
280
  }
281
281
  p.upload.addEventListener("progress", (b) => {
282
- if (b.lengthComputable && i) {
283
- const w = Math.round(b.loaded / b.total * 100);
284
- i(w);
282
+ if (b.lengthComputable && n) {
283
+ const y = Math.round(b.loaded / b.total * 100);
284
+ n(y);
285
285
  }
286
286
  }), p.addEventListener("load", () => {
287
287
  if (p.status >= 200 && p.status < 300)
@@ -298,47 +298,47 @@ class B {
298
298
  }), p.addEventListener("timeout", () => {
299
299
  d(new Error("Upload timed out"));
300
300
  });
301
- const { baseUrl: u } = this.constructClientOptions(this.userToken), g = `${u}/backend/widget/v2/upload`;
302
- p.open("POST", g), p.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((f = this.config.user) == null ? void 0 : f.token) ? p.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : k.error("user token not set"), p.send(_);
303
- }), this.vote = async (s) => await this.client.POST("/backend/widget/v2/chat/vote", { body: s }), this.resolveSession = async (s, 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", {
304
304
  body: s,
305
- signal: a
305
+ signal: t
306
306
  }), this.createStateCheckpoint = async (s) => await this.client.POST("/backend/widget/v2/checkpoint", {
307
307
  body: s
308
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;
309
- const { baseUrl: t, headers: o } = this.constructClientOptions(
309
+ const { baseUrl: a, headers: o } = this.constructClientOptions(
310
310
  (l = e.user) == null ? void 0 : l.token
311
311
  );
312
- this.client = this.createOpenAPIClient({ baseUrl: t, headers: o });
312
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: o });
313
313
  }
314
314
  }
315
- function me(n, e) {
316
- k.error(`missing case for ${n} in ${e}`);
315
+ function ue(i, e) {
316
+ g.error(`missing case for ${i} in ${e}`);
317
317
  }
318
318
  class S {
319
319
  constructor(e) {
320
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (t) => {
321
- oe(this.state, t) || (this.state = t, this.notifySubscribers(t));
322
- }, this.setPartial = (t) => {
323
- if (t == null) return;
324
- 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 };
325
325
  this.set(o);
326
326
  }, this.reset = () => {
327
327
  this.set(this.initialState);
328
- }, this.notifySubscribers = (t) => {
328
+ }, this.notifySubscribers = (a) => {
329
329
  Array.from(this.subscribers).forEach((r) => {
330
330
  try {
331
- r(t);
331
+ r(a);
332
332
  } catch (l) {
333
- k.error("state subscriber threw", l);
333
+ g.error("state subscriber threw", l);
334
334
  }
335
335
  });
336
- }, this.subscribe = (t) => (this.subscribers.add(t), () => {
337
- this.subscribers.delete(t);
336
+ }, this.subscribe = (a) => (this.subscribers.add(a), () => {
337
+ this.subscribers.delete(a);
338
338
  }), this.state = e, this.initialState = e;
339
339
  }
340
340
  }
341
- class G {
341
+ class Z {
342
342
  constructor() {
343
343
  this.state = new S({
344
344
  isPolling: !1,
@@ -346,7 +346,7 @@ class G {
346
346
  }), this.abortController = new AbortController(), this.reset = () => {
347
347
  var e;
348
348
  this.abortController.abort("Resetting poller"), (e = this.stopPolling) == null || e.call(this), this.stopPolling = null;
349
- }, this.stopPolling = null, this.startPolling = (e, t) => {
349
+ }, this.stopPolling = null, this.startPolling = (e, a) => {
350
350
  if (this.stopPolling) return;
351
351
  const o = [], r = async () => {
352
352
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
@@ -355,11 +355,11 @@ class G {
355
355
  } catch (l) {
356
356
  if (this.abortController.signal.aborted)
357
357
  return;
358
- k.error("failed to poll", l), this.state.setPartial({ isError: !0 });
358
+ g.error("failed to poll", l), this.state.setPartial({ isError: !0 });
359
359
  } finally {
360
360
  this.state.setPartial({ isPolling: !1 });
361
361
  }
362
- this.abortController.signal.aborted || o.push(setTimeout(r, t));
362
+ this.abortController.signal.aborted || o.push(setTimeout(r, a));
363
363
  };
364
364
  r(), this.stopPolling = () => {
365
365
  o.forEach(clearTimeout), this.state.reset();
@@ -367,29 +367,29 @@ class G {
367
367
  };
368
368
  }
369
369
  }
370
- function $(n) {
370
+ function W(i) {
371
371
  try {
372
- const e = n();
373
- 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 };
374
374
  } catch (e) {
375
375
  return { error: e };
376
376
  }
377
377
  }
378
- class he {
378
+ class me {
379
379
  constructor({
380
380
  api: e,
381
- config: t,
381
+ config: a,
382
382
  sessionCtx: o,
383
383
  messageCtx: r,
384
384
  sessionPollingIntervalSeconds: l
385
385
  }) {
386
- 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 = () => {
387
387
  this.subscriptions.push(
388
388
  this.sessionCtx.sessionState.subscribe(({ session: s }) => {
389
- s != null && s.id ? this.poller.startPolling(async (a) => {
389
+ s != null && s.id ? this.poller.startPolling(async (t) => {
390
390
  this.fetchSessionAndHistory({
391
391
  sessionId: s.id,
392
- abortSignal: a
392
+ abortSignal: t
393
393
  });
394
394
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
395
395
  })
@@ -401,8 +401,8 @@ class he {
401
401
  sessionId: s.id,
402
402
  abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
403
403
  });
404
- } catch (a) {
405
- 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);
406
406
  }
407
407
  else
408
408
  this.fetchSessionAndFullHistoryAbortController.abort();
@@ -416,24 +416,24 @@ class he {
416
416
  this.poller.reset(), this.fetchSessionAndFullHistoryAbortController.abort(), this.reconcileAbortController.abort(), this.reconcilingSessionId = null, this.subscriptions.forEach((s) => s()), this.subscriptions = [];
417
417
  }, this.reconcileAfterStream = async (s) => {
418
418
  this.reconcileAbortController.abort(), this.reconcileAbortController = new AbortController();
419
- const { signal: a } = this.reconcileAbortController;
419
+ const { signal: t } = this.reconcileAbortController;
420
420
  this.reconcilingSessionId = s;
421
421
  try {
422
- await this.fetchSessionAndHistory({ sessionId: s, abortSignal: a });
423
- } catch (i) {
424
- if (!a.aborted) throw i;
422
+ await this.fetchSessionAndHistory({ sessionId: s, abortSignal: t });
423
+ } catch (n) {
424
+ if (!t.aborted) throw n;
425
425
  } finally {
426
426
  this.reconcilingSessionId === s && (this.reconcilingSessionId = null);
427
427
  }
428
428
  }, this.fetchSessionAndHistory = async ({
429
429
  sessionId: s,
430
- abortSignal: a
430
+ abortSignal: t
431
431
  }) => {
432
- const i = this.messageCtx.state.get().messages.length === 0;
433
- 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 });
434
434
  const { data: c } = await this.api.pollSessionAndHistory({
435
435
  sessionId: s,
436
- abortSignal: a
436
+ abortSignal: t
437
437
  });
438
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) {
439
439
  const d = this.messageCtx.state.get().messages, _ = c.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
@@ -442,7 +442,7 @@ class he {
442
442
  if (_.length > 0)
443
443
  if (this.messageCtx.state.setPartial({
444
444
  messages: [...d, ..._]
445
- }), i)
445
+ }), n)
446
446
  this.messageCtx.markAsDispatchedToOnMessageReceivedHook(
447
447
  _.map((p) => p.id)
448
448
  );
@@ -452,23 +452,24 @@ class he {
452
452
  }
453
453
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
454
454
  }, this.mapHistoryToMessage = (s) => {
455
- var i;
456
- const a = {
455
+ var n;
456
+ const t = {
457
457
  id: s.publicId,
458
458
  timestamp: s.sentAt || "",
459
459
  attachments: s.attachments || void 0
460
460
  };
461
461
  if (s.sender.kind === "user")
462
462
  return {
463
- ...a,
463
+ ...t,
464
464
  type: "USER",
465
+ deliveredAt: t.timestamp,
465
466
  content: s.content.text || "",
466
467
  // Backend field name (schema.ts) → widget vocabulary.
467
468
  markedElements: s.pickedElements
468
469
  };
469
470
  if (s.sender.kind === "agent")
470
471
  return {
471
- ...a,
472
+ ...t,
472
473
  type: "AGENT",
473
474
  component: "agent_message",
474
475
  data: {
@@ -482,17 +483,18 @@ class he {
482
483
  avatar: s.sender.avatar || null,
483
484
  id: null,
484
485
  isAi: !1
485
- }
486
+ },
487
+ ...this.constructReplyTo(s)
486
488
  };
487
489
  if (s.sender.kind === "ai") {
488
490
  const c = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
489
491
  return {
490
- ...a,
492
+ ...t,
491
493
  type: "AI",
492
494
  component: "bot_message",
493
495
  agent: {
494
496
  id: null,
495
- name: ((i = this.config.bot) == null ? void 0 : i.name) || "",
497
+ name: ((n = this.config.bot) == null ? void 0 : n.name) || "",
496
498
  isAi: !0,
497
499
  // Do not set avatarUrl from config here... let it be taken from the config at render time
498
500
  avatarUrl: null,
@@ -504,7 +506,8 @@ class he {
504
506
  name: c.actionName,
505
507
  data: this.extractActionResult(c)
506
508
  } : void 0
507
- }
509
+ },
510
+ ...this.constructReplyTo(s)
508
511
  };
509
512
  }
510
513
  if (s.sender.kind === "system") {
@@ -512,6 +515,16 @@ class he {
512
515
  return c === null ? null : { ...c };
513
516
  }
514
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
+ };
515
528
  }, this.constructSystemMessage = (s) => {
516
529
  if (!s || !s.systemMessagePayload) return null;
517
530
  switch (s.systemMessagePayload.type) {
@@ -550,26 +563,26 @@ class he {
550
563
  case "none":
551
564
  return null;
552
565
  default:
553
- return me(
566
+ return ue(
554
567
  s.systemMessagePayload,
555
568
  this.constructSystemMessage.name
556
569
  ), null;
557
570
  }
558
571
  }, this.extractActionResult = (s) => {
559
- const a = s.result;
560
- if (a === null || typeof a != "object") return a;
561
- if ("responseBodyText" in a && typeof a.responseBodyText == "string") {
562
- 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;
563
576
  if (c) return c;
564
577
  }
565
578
  return s.result;
566
- }, 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();
567
580
  }
568
581
  }
569
- class ge {
582
+ class he {
570
583
  constructor({
571
584
  config: e,
572
- api: t,
585
+ api: a,
573
586
  storageCtx: o
574
587
  }) {
575
588
  var r;
@@ -577,25 +590,25 @@ class ge {
577
590
  var l;
578
591
  return !!(!((l = this.state.get().contact) != null && l.token) && this.config.collectUserData);
579
592
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
580
- 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;
581
594
  if (!((l = this.config.user) != null && l.token)) {
582
- if (this.config.collectUserData && !((a = (s = this.config.user) == null ? void 0 : s.data) != null && a.email)) {
583
- 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)
584
597
  return;
585
- const w = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
586
- w && await this.setUnverifiedContact(w);
598
+ const y = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
599
+ y && await this.setUnverifiedContact(y);
587
600
  return;
588
601
  }
589
602
  if (!((_ = (d = this.config.user) == null ? void 0 : d.data) != null && _.email)) {
590
- const w = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
591
- if (w) {
592
- await this.setUnverifiedContact(w);
603
+ const y = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
604
+ if (y) {
605
+ await this.setUnverifiedContact(y);
593
606
  return;
594
607
  }
595
608
  }
596
609
  await this.createUnverifiedContact({
597
- email: (m = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : m.email,
598
- 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,
599
612
  non_verified_custom_data: (b = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : b.customData
600
613
  });
601
614
  }
@@ -606,36 +619,36 @@ class ge {
606
619
  isCreatingUnverifiedContact: !0,
607
620
  isErrorCreatingUnverifiedContact: !1
608
621
  });
609
- const { data: a } = await this.api.createUnverifiedContact(l);
610
- a != null && a.token ? await this.setUnverifiedContact(a.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
611
- } catch (a) {
612
- this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), k.error("failed to create an unverified contact", {
613
- _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)
614
627
  });
615
628
  } finally {
616
629
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
617
630
  }
618
631
  }, this.recoverFromStaleToken = async () => {
619
- var l, s, a, i, c, d, _, p, u, m;
632
+ var l, s, t, n, c, d, _, p, u, h;
620
633
  if ((l = this.config.user) != null && l.token) return !1;
621
634
  this.api.setAuthToken(""), this.state.setPartial({ contact: null });
622
635
  try {
623
- await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((a = this.storageCtx) == null ? void 0 : a.clearActiveSessionId());
624
- } catch (g) {
625
- k.warn("failed to clear a stale contact token", {
626
- 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)
627
640
  });
628
641
  }
629
642
  return await this.createUnverifiedContact({
630
- 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,
631
644
  non_verified_name: (_ = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : _.name,
632
645
  non_verified_custom_data: (u = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : u.customData
633
- }), !!((m = this.state.get().contact) != null && m.token);
646
+ }), !!((h = this.state.get().contact) != null && h.token);
634
647
  }, this.setUnverifiedContact = async (l) => {
635
- var i, c, d, _;
636
- const s = await ((i = this.storageCtx) == null ? void 0 : i.getExternalContactId()), a = ((c = this.config.user) == null ? void 0 : c.externalId) || s || N();
637
- 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 } });
638
- }, 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({
639
652
  contact: (r = e.user) != null && r.token ? {
640
653
  token: e.user.token,
641
654
  // Set optional externalId from config... not local storage
@@ -647,10 +660,10 @@ class ge {
647
660
  }), this.autoCreateUnverifiedUserIfNotExists();
648
661
  }
649
662
  }
650
- class ke {
663
+ class ge {
651
664
  constructor(e) {
652
- this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (t) => {
653
- 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(
654
667
  (r) => ({
655
668
  file: r,
656
669
  id: N(),
@@ -659,25 +672,25 @@ class ke {
659
672
  })
660
673
  );
661
674
  this.state.set([...this.state.get(), ...o]), o.forEach((r) => void this.upload(r));
662
- }, this.cancel = (t) => {
675
+ }, this.cancel = (a) => {
663
676
  var o;
664
- (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));
665
678
  }, this.reset = () => {
666
- 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();
667
680
  };
668
681
  }
669
- update(e, t) {
682
+ update(e, a) {
670
683
  this.state.set(
671
- this.state.get().map((o) => o.id === e ? { ...o, ...t } : o)
684
+ this.state.get().map((o) => o.id === e ? { ...o, ...a } : o)
672
685
  );
673
686
  }
674
687
  async upload(e) {
675
- const t = new AbortController();
676
- 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" });
677
690
  try {
678
691
  const o = await this.api.uploadFile({
679
692
  file: e.file,
680
- abortSignal: t.signal,
693
+ abortSignal: a.signal,
681
694
  onProgress: (r) => this.update(e.id, { progress: r })
682
695
  });
683
696
  this.update(e.id, {
@@ -686,7 +699,7 @@ class ke {
686
699
  progress: 100
687
700
  });
688
701
  } catch (o) {
689
- t.signal.aborted || this.update(e.id, {
702
+ a.signal.aborted || this.update(e.id, {
690
703
  status: "error",
691
704
  progress: 0,
692
705
  error: o instanceof Error ? o.message : "Upload failed"
@@ -696,13 +709,13 @@ class ke {
696
709
  }
697
710
  }
698
711
  }
699
- function x() {
712
+ function q() {
700
713
  return N();
701
714
  }
702
- class be {
715
+ class ke {
703
716
  constructor({
704
717
  api: e,
705
- sessionCtx: t,
718
+ sessionCtx: a,
706
719
  messageCtx: o
707
720
  }) {
708
721
  this.submitCsat = async (r) => {
@@ -710,7 +723,7 @@ class be {
710
723
  const l = (c = this.sessionCtx.sessionState.get().session) == null ? void 0 : c.id;
711
724
  if (!l)
712
725
  return { data: null, error: "No session id found" };
713
- const s = x();
726
+ const s = q();
714
727
  this.messageCtx.state.setPartial({
715
728
  messages: [
716
729
  ...this.messageCtx.state.get().messages,
@@ -728,16 +741,16 @@ class be {
728
741
  }
729
742
  ]
730
743
  });
731
- const { data: a, error: i } = await this.api.submitCsat({
744
+ const { data: t, error: n } = await this.api.submitCsat({
732
745
  ...r,
733
746
  system_message_uuid: s,
734
747
  session_id: l
735
748
  });
736
- return { data: a, error: i };
737
- }, 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;
738
751
  }
739
752
  }
740
- const ve = [
753
+ const be = [
741
754
  {
742
755
  action: "newparagraph",
743
756
  phrases: {
@@ -812,7 +825,7 @@ const ve = [
812
825
  it: ["invia messaggio"]
813
826
  }
814
827
  }
815
- ], fe = [
828
+ ], ve = [
816
829
  "en",
817
830
  "es",
818
831
  "fr",
@@ -820,25 +833,25 @@ const ve = [
820
833
  "pt",
821
834
  "it"
822
835
  ];
823
- function ye(n) {
824
- return fe.includes(n);
836
+ function fe(i) {
837
+ return ve.includes(i);
825
838
  }
826
- function we(n) {
827
- return n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
839
+ function ye(i) {
840
+ return i.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
828
841
  }
829
- function je(n) {
830
- const e = ve.flatMap(
831
- (r) => n.flatMap(
842
+ function we(i) {
843
+ const e = be.flatMap(
844
+ (r) => i.flatMap(
832
845
  (l) => r.phrases[l].map((s) => ({ phrase: s, action: r.action }))
833
846
  )
834
- ), 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})`;
835
848
  return {
836
849
  regex: new RegExp(
837
- `${o}(${t})` + String.raw`([.,!?;:])(?=\s|$)`,
850
+ `${o}(${a})` + String.raw`([.,!?;:])(?=\s|$)`,
838
851
  "giu"
839
852
  ),
840
853
  finalRegex: new RegExp(
841
- `${o}(${t})` + String.raw`([.,!?;:]?)(?=\s|$)`,
854
+ `${o}(${a})` + String.raw`([.,!?;:]?)(?=\s|$)`,
842
855
  "giu"
843
856
  ),
844
857
  phraseToAction: new Map(
@@ -847,77 +860,77 @@ function je(n) {
847
860
  longestPhrase: Math.max(...e.map((r) => r.phrase.length))
848
861
  };
849
862
  }
850
- const V = /* @__PURE__ */ new Map();
851
- function I(n) {
852
- const e = n && ye(n) && n !== "en" ? n : null, t = e ?? "en";
853
- let o = V.get(t);
854
- 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;
855
868
  }
856
- function Se(n) {
857
- const e = n.replace(/\s+$/, "");
869
+ function je(i) {
870
+ const e = i.replace(/\s+$/, "");
858
871
  if (!e) return "";
859
- const t = e.replace(/[.!?]+$/, "");
872
+ const a = e.replace(/[.!?]+$/, "");
860
873
  let o = -1;
861
- for (let r = t.length - 1; r >= 0; r--) {
862
- const l = t[r];
874
+ for (let r = a.length - 1; r >= 0; r--) {
875
+ const l = a[r];
863
876
  if (l === "." || l === "!" || l === "?" || l === `
864
877
  `) {
865
878
  o = r + 1;
866
879
  break;
867
880
  }
868
881
  }
869
- return o === -1 ? "" : `${t.slice(0, o)} `.replace(/\n $/, `
882
+ return o === -1 ? "" : `${a.slice(0, o)} `.replace(/\n $/, `
870
883
  `);
871
884
  }
872
- const ze = new RegExp(
885
+ const Se = new RegExp(
873
886
  String.raw`(^- |\n(?:- )?)(\p{Ll})`,
874
887
  "gu"
875
888
  );
876
- function Ce(n) {
877
- return n.replace(
878
- ze,
879
- (e, t, o) => t + o.toUpperCase()
889
+ function ze(i) {
890
+ return i.replace(
891
+ Se,
892
+ (e, a, o) => a + o.toUpperCase()
880
893
  );
881
894
  }
882
- function xe(n) {
883
- 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));
884
897
  }
885
- class q {
898
+ class E {
886
899
  /**
887
900
  * Process the full raw transcript accumulated so far into insertable text.
888
901
  * Pure and deterministic: always called with the entire raw string so the
889
902
  * result never depends on delta chunking.
890
903
  */
891
- static process(e, t) {
892
- 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;
893
- 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;
894
907
  for (const _ of Array.from(l.matchAll(s))) {
895
908
  const [, p = ""] = _, u = o.phraseToAction.get(p.toLowerCase());
896
909
  if (u)
897
- 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]+$/, "")}
898
911
  `;
899
912
  else if (u === "newparagraph")
900
- a = `${a.replace(/[ \t]+$/, "")}
913
+ t = `${t.replace(/[ \t]+$/, "")}
901
914
 
902
915
  `;
903
916
  else if (u === "bullet") {
904
- const m = a.replace(/[ \t]+$/, "");
905
- a = m === "" || m.endsWith(`
906
- `) ? `${m}- ` : `${m}
917
+ const h = t.replace(/[ \t]+$/, "");
918
+ t = h === "" || h.endsWith(`
919
+ `) ? `${h}- ` : `${h}
907
920
  - `;
908
- } else if (u === "scratch") a = Se(a);
921
+ } else if (u === "scratch") t = je(t);
909
922
  else {
910
- i = u === "send" ? "send" : "stop";
923
+ n = u === "send" ? "send" : "stop";
911
924
  break;
912
925
  }
913
926
  }
914
- return i === null && (a += l.slice(c)), { text: Ce(
915
- 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, `
916
929
  `).replace(/\n[ \t]+/g, `
917
930
  `).replace(/(^|\n)- +/g, "$1- ").replace(/ {2,}/g, " ").replace(/\n{3,}/g, `
918
931
 
919
932
  `)
920
- ), pendingTail: r, control: i };
933
+ ), pendingTail: r, control: n };
921
934
  }
922
935
  /**
923
936
  * Longest suffix of `raw` that could still become a command — a proper
@@ -928,16 +941,16 @@ class q {
928
941
  * control command from an intermediate delta would stop or submit
929
942
  * mid-sentence.
930
943
  */
931
- static commandPrefixTail(e, t) {
932
- 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);
933
946
  for (let l = r; l > 0; l--) {
934
947
  const s = e.length - l;
935
- if (!xe(e.slice(0, s))) continue;
936
- const a = e.slice(s).toLowerCase(), i = a.replace(/^\s+/, "");
937
- if (i) {
948
+ if (!Ce(e.slice(0, s))) continue;
949
+ const t = e.slice(s).toLowerCase(), n = t.replace(/^\s+/, "");
950
+ if (n) {
938
951
  for (const c of Array.from(o.phraseToAction.keys()))
939
- if (c.startsWith(i))
940
- return e.slice(s + (a.length - i.length));
952
+ if (c.startsWith(n))
953
+ return e.slice(s + (t.length - n.length));
941
954
  }
942
955
  }
943
956
  return "";
@@ -947,13 +960,13 @@ class q {
947
960
  * prefix) — i.e. a silence pause would resolve it into a command. Used by
948
961
  * the manager's silence timer.
949
962
  */
950
- static pendingTailIsCompletePhrase(e, t) {
951
- const o = q.commandPrefixTail(e, t).trim().toLowerCase();
952
- 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;
953
966
  }
954
967
  }
955
- const qe = 55, Ee = 90;
956
- class H {
968
+ const xe = 55, qe = 90;
969
+ class V {
957
970
  /**
958
971
  * Next paced step toward `processed`: normally one word per tick so text
959
972
  * flows evenly instead of landing in bursty chunks; proportionally larger
@@ -962,28 +975,28 @@ class H {
962
975
  */
963
976
  static nextDripText({
964
977
  displayed: e,
965
- processed: t
978
+ processed: a
966
979
  }) {
967
- if (t.length <= e.length) return t;
968
- const o = t.length - e.length;
969
- if (o > Ee)
970
- 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));
971
984
  let r = e.length;
972
- for (; r < t.length && /\s/.test(t.charAt(r)); ) r++;
973
- for (; r < t.length && !/\s/.test(t.charAt(r)); ) r++;
974
- 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));
975
988
  }
976
989
  /** Normalize a BCP-47 browser locale into the hint OpenAI accepts. */
977
990
  static languageHint(e) {
978
991
  if (!e) return;
979
- const t = e.toLowerCase();
980
- if (/^zh-(cn|tw|hk)$/.test(t)) return t;
981
- 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];
982
995
  return o && /^[a-z]{2,3}$/.test(o) ? o : void 0;
983
996
  }
984
997
  }
985
- const Ae = 2e4;
986
- class Pe {
998
+ const Ee = 2e4;
999
+ class Ae {
987
1000
  constructor() {
988
1001
  this.cached = null, this.inflight = null;
989
1002
  }
@@ -991,15 +1004,15 @@ class Pe {
991
1004
  get() {
992
1005
  if (!this.cached) return null;
993
1006
  const e = Date.parse(this.cached.expiresAt);
994
- 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;
995
1008
  }
996
1009
  /**
997
1010
  * Resolve a mint, deduping concurrent requests (hover-prewarm racing a
998
1011
  * click reuses the same in-flight promise instead of double-minting).
999
1012
  */
1000
1013
  async resolve(e) {
1001
- const t = this.get();
1002
- 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(() => {
1003
1016
  this.inflight = null;
1004
1017
  })), this.inflight);
1005
1018
  }
@@ -1008,55 +1021,55 @@ class Pe {
1008
1021
  this.cached = null;
1009
1022
  }
1010
1023
  }
1011
- function Z(n) {
1012
- return typeof n == "object" && n !== null && !Array.isArray(n);
1024
+ function H(i) {
1025
+ return typeof i == "object" && i !== null && !Array.isArray(i);
1013
1026
  }
1014
- function Te(n) {
1015
- if (!Z(n) || typeof n.type != "string") return null;
1016
- 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;
1017
1030
  return {
1018
- type: n.type,
1019
- delta: typeof n.delta == "string" ? n.delta : void 0,
1031
+ type: i.type,
1032
+ delta: typeof i.delta == "string" ? i.delta : void 0,
1020
1033
  errorMessage: e && typeof e.message == "string" ? e.message : void 0
1021
1034
  };
1022
1035
  }
1023
- const Ie = "https://api.openai.com/v1/realtime/calls", Me = 600 * 1e3, De = 15e3, Ne = 5e3;
1024
- 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 {
1025
1038
  }
1026
- class Re {
1039
+ class Ne {
1027
1040
  constructor({
1028
1041
  mintToken: e,
1029
- onDelta: t,
1042
+ onDelta: a,
1030
1043
  onState: o,
1031
1044
  onError: r,
1032
1045
  onLevel: l
1033
1046
  }) {
1034
- 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;
1035
1048
  }
1036
1049
  async start() {
1037
1050
  if (this.state === "idle") {
1038
1051
  this.setState("connecting"), this.timers.push(
1039
1052
  setTimeout(() => {
1040
1053
  this.state === "connecting" && this.fail("unavailable");
1041
- }, De)
1042
- ), this.timers.push(setTimeout(() => this.stop(), Me));
1054
+ }, Me)
1055
+ ), this.timers.push(setTimeout(() => this.stop(), Ie));
1043
1056
  try {
1044
1057
  const e = this.requestMicrophone();
1045
1058
  e.then((d) => {
1046
- (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;
1047
1060
  }).catch(() => {
1048
1061
  });
1049
- const [t, o] = await Promise.all([e, this.mintToken()]);
1062
+ const [a, o] = await Promise.all([e, this.mintToken()]);
1050
1063
  if (this.isTornDown()) {
1051
- t.getTracks().forEach((d) => d.stop());
1064
+ a.getTracks().forEach((d) => d.stop());
1052
1065
  return;
1053
1066
  }
1054
- this.stream = t, this.startLevelMeter(t);
1067
+ this.stream = a, this.startLevelMeter(a);
1055
1068
  const r = new RTCPeerConnection();
1056
1069
  this.pc = r;
1057
- const [l] = t.getAudioTracks();
1058
- if (!l) throw new P("No audio track");
1059
- r.addTrack(l, t);
1070
+ const [l] = a.getAudioTracks();
1071
+ if (!l) throw new T("No audio track");
1072
+ r.addTrack(l, a);
1060
1073
  const s = r.createDataChannel("oai-events");
1061
1074
  this.dc = s, s.addEventListener(
1062
1075
  "message",
@@ -1071,26 +1084,26 @@ class Re {
1071
1084
  r.connectionState === "disconnected" && this.timers.push(
1072
1085
  setTimeout(() => {
1073
1086
  this.pc === r && r.connectionState !== "connected" && this.fail("unavailable");
1074
- }, Ne)
1087
+ }, De)
1075
1088
  );
1076
1089
  });
1077
- const a = await r.createOffer();
1078
- await r.setLocalDescription(a);
1079
- 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, {
1080
1093
  method: "POST",
1081
1094
  headers: {
1082
1095
  Authorization: `Bearer ${o.token}`,
1083
1096
  "Content-Type": "application/sdp"
1084
1097
  },
1085
- body: a.sdp
1098
+ body: t.sdp
1086
1099
  });
1087
- if (!i.ok)
1088
- throw new Error(`Realtime handshake failed (${i.status})`);
1089
- const c = await i.text();
1100
+ if (!n.ok)
1101
+ throw new Error(`Realtime handshake failed (${n.status})`);
1102
+ const c = await n.text();
1090
1103
  if (this.isTornDown()) return;
1091
1104
  await r.setRemoteDescription({ type: "answer", sdp: c });
1092
1105
  } catch (e) {
1093
- 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", {
1094
1107
  _e: e instanceof Error ? e.message : String(e)
1095
1108
  }), this.fail("unavailable"));
1096
1109
  }
@@ -1102,7 +1115,7 @@ class Re {
1102
1115
  async requestMicrophone() {
1103
1116
  var e;
1104
1117
  if (!((e = navigator.mediaDevices) != null && e.getUserMedia))
1105
- throw new P("Microphone is not supported");
1118
+ throw new T("Microphone is not supported");
1106
1119
  try {
1107
1120
  return await navigator.mediaDevices.getUserMedia({
1108
1121
  audio: {
@@ -1111,24 +1124,24 @@ class Re {
1111
1124
  autoGainControl: !0
1112
1125
  }
1113
1126
  });
1114
- } catch (t) {
1115
- throw new P(
1116
- 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"
1117
1130
  );
1118
1131
  }
1119
1132
  }
1120
1133
  handleServerEvent(e) {
1121
1134
  if (typeof e != "string") return;
1122
- let t;
1135
+ let a;
1123
1136
  try {
1124
- t = JSON.parse(e);
1137
+ a = JSON.parse(e);
1125
1138
  } catch {
1126
- 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", {
1127
1140
  snippet: e.slice(0, 120)
1128
1141
  }));
1129
1142
  return;
1130
1143
  }
1131
- const o = Te(t);
1144
+ const o = Pe(a);
1132
1145
  if (!o) return;
1133
1146
  const { type: r, delta: l } = o;
1134
1147
  if (r === "session.created" || r === "transcription_session.created") {
@@ -1139,32 +1152,32 @@ class Re {
1139
1152
  this.state === "connecting" && this.setState("listening"), this.onDelta(l);
1140
1153
  return;
1141
1154
  }
1142
- r === "error" && (k.error("dictation server event error", {
1155
+ r === "error" && (g.error("dictation server event error", {
1143
1156
  _e: o.errorMessage ?? "unknown"
1144
1157
  }), this.fail("unavailable"));
1145
1158
  }
1146
1159
  startLevelMeter(e) {
1147
1160
  if (this.onLevel)
1148
1161
  try {
1149
- const t = new AudioContext();
1150
- this.audioContext = t;
1151
- 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();
1152
1165
  r.fftSize = 512, o.connect(r);
1153
1166
  const l = new Uint8Array(r.frequencyBinCount), s = () => {
1154
1167
  var c;
1155
1168
  r.getByteTimeDomainData(l);
1156
- let a = 0;
1169
+ let t = 0;
1157
1170
  for (let d = 0; d < l.length; d++) {
1158
1171
  const _ = ((l[d] ?? 128) - 128) / 128;
1159
- a += _ * _;
1172
+ t += _ * _;
1160
1173
  }
1161
- const i = Math.sqrt(a / l.length);
1162
- (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);
1163
1176
  };
1164
1177
  this.levelRaf = requestAnimationFrame(s);
1165
- } catch (t) {
1166
- k.error("dictation level meter unavailable", {
1167
- _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)
1168
1181
  });
1169
1182
  }
1170
1183
  }
@@ -1175,9 +1188,9 @@ class Re {
1175
1188
  this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(e));
1176
1189
  }
1177
1190
  teardown() {
1178
- var e, t, o, r;
1179
- 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) => {
1180
- 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", {
1181
1194
  _e: String(l)
1182
1195
  });
1183
1196
  }), this.audioContext = null;
@@ -1186,20 +1199,20 @@ class Re {
1186
1199
  this.state !== e && (this.state = e, this.onState(e));
1187
1200
  }
1188
1201
  }
1189
- const Ke = 1300, Le = { status: "idle", error: null };
1190
- class Fe {
1191
- constructor({ api: e, config: t }) {
1192
- 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 = () => {
1193
1206
  this.mintToken().catch((o) => {
1194
- this.mintCache.clear(), k.error("dictation token prewarm failed", {
1207
+ this.mintCache.clear(), g.error("dictation token prewarm failed", {
1195
1208
  _e: o instanceof Error ? o.message : String(o)
1196
1209
  });
1197
1210
  });
1198
1211
  }, this.start = (o) => {
1199
- this.session && this.teardown(), this.target = o, this.language = H.languageHint(
1212
+ this.session && this.teardown(), this.target = o, this.language = V.languageHint(
1200
1213
  this.config.language ?? navigator.language
1201
1214
  ), this.prefix = o.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1202
- const r = new Re({
1215
+ const r = new Ne({
1203
1216
  mintToken: this.mintToken,
1204
1217
  onLevel: (l) => {
1205
1218
  this.levelRef.current = l;
@@ -1226,15 +1239,15 @@ class Fe {
1226
1239
  this.teardown({ send: !0 });
1227
1240
  return;
1228
1241
  }
1229
- this.stopSilenceTimer(), q.pendingTailIsCompletePhrase(
1242
+ this.stopSilenceTimer(), E.pendingTailIsCompletePhrase(
1230
1243
  this.raw,
1231
1244
  this.language
1232
1245
  ) && (this.silenceTimer = setTimeout(() => {
1233
1246
  if (r !== this.session) return;
1234
1247
  this.raw = `${this.raw}.`;
1235
- const a = this.ingest();
1236
- a === "stop" ? this.teardown() : a === "send" && this.teardown({ send: !0 });
1237
- }, Ke));
1248
+ const t = this.ingest();
1249
+ t === "stop" ? this.teardown() : t === "send" && this.teardown({ send: !0 });
1250
+ }, Re));
1238
1251
  }
1239
1252
  });
1240
1253
  this.session = r, this.state.set({ status: "connecting", error: null }), this.dripTimer = setInterval(() => {
@@ -1244,18 +1257,18 @@ class Fe {
1244
1257
  return;
1245
1258
  }
1246
1259
  this.applyDisplayed(
1247
- H.nextDripText({
1260
+ V.nextDripText({
1248
1261
  displayed: this.displayed,
1249
1262
  processed: this.processed
1250
1263
  })
1251
1264
  );
1252
1265
  }
1253
- }, qe), r.start();
1254
- }, this.stop = () => {
1255
- this.session && this.teardown();
1266
+ }, xe), r.start();
1267
+ }, this.stop = (o) => {
1268
+ this.session && this.teardown(o);
1256
1269
  }, this.mintToken = async () => this.mintCache.resolve(
1257
1270
  () => this.api.createDictationSession({ language: this.language })
1258
- ), this.api = e, this.config = t;
1271
+ ), this.api = e, this.config = a;
1259
1272
  }
1260
1273
  /** Applied text = prefix + dictated. A mismatch means the visitor edited. */
1261
1274
  isConsistent() {
@@ -1267,28 +1280,28 @@ class Fe {
1267
1280
  /** Process the transcript and apply the outcome. Shared by the delta path,
1268
1281
  * the silence timer, and (with `final`) teardown. Returns the control. */
1269
1282
  ingest(e) {
1270
- const t = q.process(this.raw, {
1283
+ const a = E.process(this.raw, {
1271
1284
  language: this.language,
1272
1285
  final: e == null ? void 0 : e.final
1273
1286
  });
1274
- 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;
1275
1288
  }
1276
1289
  stopSilenceTimer() {
1277
1290
  this.silenceTimer && clearTimeout(this.silenceTimer), this.silenceTimer = null;
1278
1291
  }
1279
1292
  teardown(e) {
1280
1293
  var l;
1281
- const t = this.session, o = this.target;
1294
+ const a = this.session, o = this.target;
1282
1295
  this.dripTimer && clearInterval(this.dripTimer), this.dripTimer = null, this.stopSilenceTimer();
1283
1296
  let r = (e == null ? void 0 : e.send) ?? !1;
1284
1297
  if (o && this.isConsistent()) {
1285
1298
  const s = this.ingest({ final: !0 });
1286
1299
  (e == null ? void 0 : e.executeFinalCommand) !== !1 && s === "send" && (r = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1287
1300
  }
1288
- 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));
1289
1302
  }
1290
1303
  }
1291
- const Oe = {
1304
+ const Fe = {
1292
1305
  write_a_message_placeholder: "اكتب رسالة...",
1293
1306
  your_issue_has_been_resolved: "تم حل مشكلتك!",
1294
1307
  new_conversation: "محادثة جديدة",
@@ -1397,7 +1410,7 @@ const Oe = {
1397
1410
  zoom_out: "تصغير",
1398
1411
  reset_zoom: "إعادة تعيين التكبير",
1399
1412
  support_chat_aria_label: "دردشة الدعم"
1400
- }, Ue = {
1413
+ }, Oe = {
1401
1414
  write_a_message_placeholder: "একটি বার্তা লিখুন...",
1402
1415
  your_issue_has_been_resolved: "আপনার সমস্যা সমাধান হয়েছে!",
1403
1416
  new_conversation: "নতুন কথোপকথন",
@@ -1494,7 +1507,7 @@ const Oe = {
1494
1507
  zoom_out: "ছোট করুন",
1495
1508
  reset_zoom: "জুম রিসেট করুন",
1496
1509
  support_chat_aria_label: "সাপোর্ট চ্যাট"
1497
- }, Be = {
1510
+ }, Ue = {
1498
1511
  write_a_message_placeholder: "Напишете съобщение...",
1499
1512
  your_issue_has_been_resolved: "Вашият проблем е разрешен!",
1500
1513
  new_conversation: "Нов разговор",
@@ -1591,7 +1604,7 @@ const Oe = {
1591
1604
  zoom_out: "Намаляване",
1592
1605
  reset_zoom: "Нулиране на мащаба",
1593
1606
  support_chat_aria_label: "Чат за поддръжка"
1594
- }, Ve = {
1607
+ }, Be = {
1595
1608
  write_a_message_placeholder: "Napište zprávu...",
1596
1609
  your_issue_has_been_resolved: "Váš problém byl vyřešen!",
1597
1610
  new_conversation: "Nová konverzace",
@@ -1688,7 +1701,7 @@ const Oe = {
1688
1701
  zoom_out: "Oddálit",
1689
1702
  reset_zoom: "Obnovit přiblížení",
1690
1703
  support_chat_aria_label: "Chat podpory"
1691
- }, He = {
1704
+ }, Ve = {
1692
1705
  write_a_message_placeholder: "Skriv en besked...",
1693
1706
  your_issue_has_been_resolved: "Dit problem er løst!",
1694
1707
  new_conversation: "Ny samtale",
@@ -1785,7 +1798,7 @@ const Oe = {
1785
1798
  zoom_out: "Zoom ud",
1786
1799
  reset_zoom: "Nulstil zoom",
1787
1800
  support_chat_aria_label: "Supportchat"
1788
- }, Ze = {
1801
+ }, He = {
1789
1802
  write_a_message_placeholder: "Γράψτε ένα μήνυμα...",
1790
1803
  your_issue_has_been_resolved: "Το πρόβλημά σας επιλύθηκε!",
1791
1804
  new_conversation: "Νέα συνομιλία",
@@ -1882,7 +1895,7 @@ const Oe = {
1882
1895
  zoom_out: "Σμίκρυνση",
1883
1896
  reset_zoom: "Επαναφορά ζουμ",
1884
1897
  support_chat_aria_label: "Συνομιλία υποστήριξης"
1885
- }, We = {
1898
+ }, Ge = {
1886
1899
  write_a_message_placeholder: "Nachricht schreiben...",
1887
1900
  your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
1888
1901
  new_conversation: "Neue Konversation",
@@ -1979,7 +1992,7 @@ const Oe = {
1979
1992
  zoom_out: "Verkleinern",
1980
1993
  reset_zoom: "Zoom zurücksetzen",
1981
1994
  support_chat_aria_label: "Support-Chat"
1982
- }, J = {
1995
+ }, $ = {
1983
1996
  write_a_message_placeholder: "Write a message...",
1984
1997
  your_issue_has_been_resolved: "Your issue has been resolved!",
1985
1998
  new_conversation: "New conversation",
@@ -2088,7 +2101,7 @@ const Oe = {
2088
2101
  zoom_out: "Zoom out",
2089
2102
  reset_zoom: "Reset zoom",
2090
2103
  support_chat_aria_label: "Support chat"
2091
- }, Ge = {
2104
+ }, Ze = {
2092
2105
  write_a_message_placeholder: "Escribe un mensaje...",
2093
2106
  your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
2094
2107
  new_conversation: "Nueva conversación",
@@ -2185,7 +2198,7 @@ const Oe = {
2185
2198
  zoom_out: "Alejar",
2186
2199
  reset_zoom: "Restablecer zoom",
2187
2200
  support_chat_aria_label: "Chat de soporte"
2188
- }, $e = {
2201
+ }, We = {
2189
2202
  write_a_message_placeholder: "Magsulat ng mensahe...",
2190
2203
  your_issue_has_been_resolved: "Nalutas na ang iyong isyu!",
2191
2204
  new_conversation: "Bagong usapan",
@@ -2282,7 +2295,7 @@ const Oe = {
2282
2295
  zoom_out: "Paliitin",
2283
2296
  reset_zoom: "I-reset ang zoom",
2284
2297
  support_chat_aria_label: "Chat ng suporta"
2285
- }, Je = {
2298
+ }, $e = {
2286
2299
  write_a_message_placeholder: "Kirjoita viesti...",
2287
2300
  your_issue_has_been_resolved: "Ongelmasi on ratkaistu!",
2288
2301
  new_conversation: "Uusi keskustelu",
@@ -2379,7 +2392,7 @@ const Oe = {
2379
2392
  zoom_out: "Loitonna",
2380
2393
  reset_zoom: "Palauta zoomaus",
2381
2394
  support_chat_aria_label: "Tukichat"
2382
- }, Ye = {
2395
+ }, Je = {
2383
2396
  write_a_message_placeholder: "Écrivez un message...",
2384
2397
  your_issue_has_been_resolved: "Votre problème a été résolu !",
2385
2398
  new_conversation: "Nouvelle conversation",
@@ -2476,7 +2489,7 @@ const Oe = {
2476
2489
  zoom_out: "Zoom arrière",
2477
2490
  reset_zoom: "Réinitialiser le zoom",
2478
2491
  support_chat_aria_label: "Chat de support"
2479
- }, Qe = {
2492
+ }, Ye = {
2480
2493
  write_a_message_placeholder: "एक संदेश लिखें...",
2481
2494
  your_issue_has_been_resolved: "आपकी समस्या हल हो गई है!",
2482
2495
  new_conversation: "नई बातचीत",
@@ -2670,7 +2683,7 @@ const Oe = {
2670
2683
  zoom_out: "Riduci",
2671
2684
  reset_zoom: "Reimposta zoom",
2672
2685
  support_chat_aria_label: "Chat di supporto"
2673
- }, ea = {
2686
+ }, Qe = {
2674
2687
  write_a_message_placeholder: "メッセージを入力...",
2675
2688
  your_issue_has_been_resolved: "問題が解決しました!",
2676
2689
  new_conversation: "新しい会話",
@@ -2767,7 +2780,7 @@ const Oe = {
2767
2780
  zoom_out: "縮小",
2768
2781
  reset_zoom: "ズームをリセット",
2769
2782
  support_chat_aria_label: "サポートチャット"
2770
- }, aa = {
2783
+ }, ea = {
2771
2784
  write_a_message_placeholder: "메시지를 입력하세요...",
2772
2785
  your_issue_has_been_resolved: "문제가 해결되었습니다!",
2773
2786
  new_conversation: "새 대화",
@@ -2864,7 +2877,7 @@ const Oe = {
2864
2877
  zoom_out: "축소",
2865
2878
  reset_zoom: "확대/축소 초기화",
2866
2879
  support_chat_aria_label: "고객 지원 채팅"
2867
- }, ta = {
2880
+ }, aa = {
2868
2881
  write_a_message_placeholder: "Schrijf een bericht...",
2869
2882
  your_issue_has_been_resolved: "Uw probleem is opgelost!",
2870
2883
  new_conversation: "Nieuw gesprek",
@@ -2961,7 +2974,7 @@ const Oe = {
2961
2974
  zoom_out: "Uitzoomen",
2962
2975
  reset_zoom: "Zoom herstellen",
2963
2976
  support_chat_aria_label: "Supportchat"
2964
- }, sa = {
2977
+ }, ta = {
2965
2978
  write_a_message_placeholder: "Skriv en melding...",
2966
2979
  your_issue_has_been_resolved: "Problemet ditt er løst!",
2967
2980
  new_conversation: "Ny samtale",
@@ -3058,7 +3071,7 @@ const Oe = {
3058
3071
  zoom_out: "Zoom ut",
3059
3072
  reset_zoom: "Tilbakestill zoom",
3060
3073
  support_chat_aria_label: "Support-chat"
3061
- }, oa = {
3074
+ }, sa = {
3062
3075
  write_a_message_placeholder: "Napisz wiadomość...",
3063
3076
  your_issue_has_been_resolved: "Twój problem został rozwiązany!",
3064
3077
  new_conversation: "Nowa rozmowa",
@@ -3155,7 +3168,7 @@ const Oe = {
3155
3168
  zoom_out: "Pomniejsz",
3156
3169
  reset_zoom: "Resetuj powiększenie",
3157
3170
  support_chat_aria_label: "Czat pomocy"
3158
- }, na = {
3171
+ }, oa = {
3159
3172
  write_a_message_placeholder: "Escreva uma mensagem...",
3160
3173
  your_issue_has_been_resolved: "Seu problema foi resolvido!",
3161
3174
  new_conversation: "Nova conversa",
@@ -3252,7 +3265,7 @@ const Oe = {
3252
3265
  zoom_out: "Reduzir",
3253
3266
  reset_zoom: "Redefinir zoom",
3254
3267
  support_chat_aria_label: "Chat de suporte"
3255
- }, ia = {
3268
+ }, na = {
3256
3269
  write_a_message_placeholder: "Scrie un mesaj...",
3257
3270
  your_issue_has_been_resolved: "Problema ta a fost rezolvată!",
3258
3271
  new_conversation: "Conversație nouă",
@@ -3349,7 +3362,7 @@ const Oe = {
3349
3362
  zoom_out: "Micșorează",
3350
3363
  reset_zoom: "Resetează zoomul",
3351
3364
  support_chat_aria_label: "Chat de asistență"
3352
- }, ra = {
3365
+ }, ia = {
3353
3366
  write_a_message_placeholder: "Skriv ett meddelande...",
3354
3367
  your_issue_has_been_resolved: "Ditt problem har lösts!",
3355
3368
  new_conversation: "Ny konversation",
@@ -3446,7 +3459,7 @@ const Oe = {
3446
3459
  zoom_out: "Zooma ut",
3447
3460
  reset_zoom: "Återställ zoom",
3448
3461
  support_chat_aria_label: "Supportchatt"
3449
- }, _a = {
3462
+ }, ra = {
3450
3463
  write_a_message_placeholder: "Напишите сообщение...",
3451
3464
  your_issue_has_been_resolved: "Ваша проблема решена!",
3452
3465
  new_conversation: "Новый разговор",
@@ -3543,7 +3556,7 @@ const Oe = {
3543
3556
  zoom_out: "Уменьшить",
3544
3557
  reset_zoom: "Сбросить масштаб",
3545
3558
  support_chat_aria_label: "Чат поддержки"
3546
- }, la = {
3559
+ }, _a = {
3547
3560
  write_a_message_placeholder: "เขียนข้อความ...",
3548
3561
  your_issue_has_been_resolved: "ปัญหาของคุณได้รับการแก้ไขแล้ว!",
3549
3562
  new_conversation: "การสนทนาใหม่",
@@ -3640,7 +3653,7 @@ const Oe = {
3640
3653
  zoom_out: "ย่อ",
3641
3654
  reset_zoom: "รีเซ็ตการซูม",
3642
3655
  support_chat_aria_label: "แชทฝ่ายสนับสนุน"
3643
- }, ca = {
3656
+ }, la = {
3644
3657
  write_a_message_placeholder: "Bir mesaj yazın...",
3645
3658
  your_issue_has_been_resolved: "Sorununuz çözüldü!",
3646
3659
  new_conversation: "Yeni konuşma",
@@ -3737,7 +3750,7 @@ const Oe = {
3737
3750
  zoom_out: "Uzaklaştır",
3738
3751
  reset_zoom: "Yakınlaştırmayı sıfırla",
3739
3752
  support_chat_aria_label: "Destek sohbeti"
3740
- }, pa = {
3753
+ }, ca = {
3741
3754
  write_a_message_placeholder: "پیغام لکھیں...",
3742
3755
  your_issue_has_been_resolved: "آپ کا مسئلہ حل ہو گیا ہے!",
3743
3756
  new_conversation: "نئی گفتگو",
@@ -3834,7 +3847,7 @@ const Oe = {
3834
3847
  zoom_out: "زوم آؤٹ",
3835
3848
  reset_zoom: "زوم دوبارہ ترتیب دیں",
3836
3849
  support_chat_aria_label: "سپورٹ چیٹ"
3837
- }, da = {
3850
+ }, pa = {
3838
3851
  write_a_message_placeholder: "Viết tin nhắn...",
3839
3852
  your_issue_has_been_resolved: "Vấn đề của bạn đã được giải quyết!",
3840
3853
  new_conversation: "Cuộc trò chuyện mới",
@@ -3931,7 +3944,7 @@ const Oe = {
3931
3944
  zoom_out: "Thu nhỏ",
3932
3945
  reset_zoom: "Đặt lại thu phóng",
3933
3946
  support_chat_aria_label: "Trò chuyện hỗ trợ"
3934
- }, ua = {
3947
+ }, da = {
3935
3948
  write_a_message_placeholder: "写一条消息...",
3936
3949
  your_issue_has_been_resolved: "您的问题已解决!",
3937
3950
  new_conversation: "新对话",
@@ -4028,7 +4041,7 @@ const Oe = {
4028
4041
  zoom_out: "缩小",
4029
4042
  reset_zoom: "重置缩放",
4030
4043
  support_chat_aria_label: "支持对话"
4031
- }, ma = {
4044
+ }, ua = {
4032
4045
  write_a_message_placeholder: "Napišite poruku...",
4033
4046
  your_issue_has_been_resolved: "Vaš problem je riješen!",
4034
4047
  new_conversation: "Novi razgovor",
@@ -4125,7 +4138,7 @@ const Oe = {
4125
4138
  zoom_out: "Udalji",
4126
4139
  reset_zoom: "Poništi zumiranje",
4127
4140
  support_chat_aria_label: "Chat za podršku"
4128
- }, ha = {
4141
+ }, ma = {
4129
4142
  write_a_message_placeholder: "Kirjuta sõnum...",
4130
4143
  your_issue_has_been_resolved: "Teie probleem on lahendatud!",
4131
4144
  new_conversation: "Uus vestlus",
@@ -4222,7 +4235,7 @@ const Oe = {
4222
4235
  zoom_out: "Vähenda",
4223
4236
  reset_zoom: "Lähtesta suurendus",
4224
4237
  support_chat_aria_label: "Tugivestlus"
4225
- }, ga = {
4238
+ }, ha = {
4226
4239
  write_a_message_placeholder: "Írjon üzenetet...",
4227
4240
  your_issue_has_been_resolved: "A problémája megoldódott!",
4228
4241
  new_conversation: "Új beszélgetés",
@@ -4319,7 +4332,7 @@ const Oe = {
4319
4332
  zoom_out: "Kicsinyítés",
4320
4333
  reset_zoom: "Nagyítás visszaállítása",
4321
4334
  support_chat_aria_label: "Ügyfélszolgálati chat"
4322
- }, ka = {
4335
+ }, ga = {
4323
4336
  write_a_message_placeholder: "Skrifaðu skilaboð...",
4324
4337
  your_issue_has_been_resolved: "Málið þitt hefur verið leyst!",
4325
4338
  new_conversation: "Nýtt samtal",
@@ -4416,7 +4429,7 @@ const Oe = {
4416
4429
  zoom_out: "Minnka aðdrátt",
4417
4430
  reset_zoom: "Endurstilla aðdrátt",
4418
4431
  support_chat_aria_label: "Þjónustuspjall"
4419
- }, ba = {
4432
+ }, ka = {
4420
4433
  write_a_message_placeholder: "Rakstiet ziņojumu...",
4421
4434
  your_issue_has_been_resolved: "Jūsu problēma ir atrisināta!",
4422
4435
  new_conversation: "Jauna saruna",
@@ -4513,7 +4526,7 @@ const Oe = {
4513
4526
  zoom_out: "Attālināt",
4514
4527
  reset_zoom: "Atiestatīt tālummaiņu",
4515
4528
  support_chat_aria_label: "Atbalsta tērzēšana"
4516
- }, va = {
4529
+ }, ba = {
4517
4530
  write_a_message_placeholder: "Parašykite žinutę...",
4518
4531
  your_issue_has_been_resolved: "Jūsų problema išspręsta!",
4519
4532
  new_conversation: "Naujas pokalbis",
@@ -4610,7 +4623,7 @@ const Oe = {
4610
4623
  zoom_out: "Nutolinti",
4611
4624
  reset_zoom: "Atstatyti mastelį",
4612
4625
  support_chat_aria_label: "Pagalbos pokalbis"
4613
- }, fa = {
4626
+ }, va = {
4614
4627
  write_a_message_placeholder: "Schreift eng Noriicht...",
4615
4628
  your_issue_has_been_resolved: "Äert Problem gouf geléist!",
4616
4629
  new_conversation: "Nei Konversatioun",
@@ -4707,7 +4720,7 @@ const Oe = {
4707
4720
  zoom_out: "Erauszoomen",
4708
4721
  reset_zoom: "Zoom zrécksetzen",
4709
4722
  support_chat_aria_label: "Support-Chat"
4710
- }, ya = {
4723
+ }, fa = {
4711
4724
  write_a_message_placeholder: "Ikteb messaġġ...",
4712
4725
  your_issue_has_been_resolved: "Il-problema tiegħek ġiet riżolta!",
4713
4726
  new_conversation: "Konversazzjoni ġdida",
@@ -4804,7 +4817,7 @@ const Oe = {
4804
4817
  zoom_out: "Ċekken",
4805
4818
  reset_zoom: "Irrisettja ż-zoom",
4806
4819
  support_chat_aria_label: "Chat ta’ appoġġ"
4807
- }, wa = {
4820
+ }, ya = {
4808
4821
  write_a_message_placeholder: "Skriv en melding...",
4809
4822
  your_issue_has_been_resolved: "Saken din er løst!",
4810
4823
  new_conversation: "Ny samtale",
@@ -4901,7 +4914,7 @@ const Oe = {
4901
4914
  zoom_out: "Zoom ut",
4902
4915
  reset_zoom: "Tilbakestill zoom",
4903
4916
  support_chat_aria_label: "Support-chat"
4904
- }, ja = {
4917
+ }, wa = {
4905
4918
  write_a_message_placeholder: "Napíšte správu...",
4906
4919
  your_issue_has_been_resolved: "Váš problém bol vyriešený!",
4907
4920
  new_conversation: "Nová konverzácia",
@@ -4998,82 +5011,82 @@ const Oe = {
4998
5011
  zoom_out: "Oddialiť",
4999
5012
  reset_zoom: "Obnoviť priblíženie",
5000
5013
  support_chat_aria_label: "Chat podpory"
5001
- }, Y = {
5002
- ar: Oe,
5003
- bn: Ue,
5004
- bg: Be,
5005
- cs: Ve,
5006
- da: He,
5007
- de: We,
5008
- el: Ze,
5009
- en: J,
5010
- es: Ge,
5011
- et: ha,
5012
- fi: Je,
5013
- fil: $e,
5014
- fr: Ye,
5015
- hi: Qe,
5016
- hr: ma,
5017
- hu: ga,
5018
- 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,
5019
5032
  it: Xe,
5020
- ja: ea,
5021
- ko: aa,
5022
- lb: fa,
5023
- lt: va,
5024
- lv: ba,
5025
- mt: ya,
5026
- nb: wa,
5027
- nl: ta,
5028
- no: sa,
5029
- pl: oa,
5030
- pt: na,
5031
- ro: ia,
5032
- ru: _a,
5033
- sk: ja,
5034
- sv: ra,
5035
- th: la,
5036
- tr: ca,
5037
- ur: pa,
5038
- vi: da,
5039
- "zh-cn": ua
5040
- }, Sa = Object.keys(Y);
5041
- function za(n) {
5042
- 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);
5043
5056
  }
5044
- const Ca = /* @__PURE__ */ new Set(["ar", "ur"]);
5045
- function Ja(n) {
5046
- return Ca.has(n);
5057
+ const za = /* @__PURE__ */ new Set(["ar", "ur"]);
5058
+ function Ja(i) {
5059
+ return za.has(i);
5047
5060
  }
5048
- function xa(n) {
5049
- return za(n) ? n : "en";
5061
+ function Ca(i) {
5062
+ return Sa(i) ? i : "en";
5050
5063
  }
5051
- function qa(n, e, t, o) {
5064
+ function xa(i, e, a, o) {
5052
5065
  var l;
5053
- 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;
5054
5067
  return o ? r.replace(
5055
5068
  /\{(\w+)\}/g,
5056
- (s, a) => a in o ? String(o[a]) : s
5069
+ (s, t) => t in o ? String(o[t]) : s
5057
5070
  ) : r;
5058
5071
  }
5059
- function Ea(n, e, t) {
5060
- return qa(
5072
+ function qa(i, e, a) {
5073
+ return xa(
5061
5074
  e,
5062
- xa(n.language),
5063
- n.translationOverrides,
5064
- t
5075
+ Ca(i.language),
5076
+ i.translationOverrides,
5077
+ a
5065
5078
  );
5066
5079
  }
5067
- class Aa {
5080
+ class Ea {
5068
5081
  constructor({
5069
5082
  config: e,
5070
- api: t,
5083
+ api: a,
5071
5084
  contactCtx: o,
5072
5085
  storageCtx: r,
5073
5086
  sessionsPollingIntervalSeconds: l,
5074
5087
  sharedSessions: s
5075
5088
  }) {
5076
- 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({
5077
5090
  session: null,
5078
5091
  isCreatingSession: !1,
5079
5092
  isResolvingSession: !1
@@ -5091,20 +5104,20 @@ class Aa {
5091
5104
  this.persistSession
5092
5105
  ));
5093
5106
  }, this.restoreActiveSessionTracking = () => {
5094
- var a;
5095
- (a = this.stopPersistingSession) == null || a.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5096
- }, this.trackActiveSession = (a) => {
5097
- var i;
5098
- (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(
5099
5112
  this.persistSession
5100
- ), this.persistSession(a.sessionState.get());
5101
- }, this.persistSession = ({ session: a }) => {
5102
- const i = this.storageCtx;
5103
- if (!i) return;
5104
- 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;
5105
5118
  if (c === this.persistedSessionId || !c && this.persistedSessionId === null) return;
5106
- this.persistedSessionId = c, (c ? i.setActiveSessionId(c) : i.clearActiveSessionId()).catch((_) => {
5107
- 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", {
5108
5121
  error: _ instanceof Error ? _.message : String(_)
5109
5122
  });
5110
5123
  });
@@ -5118,55 +5131,55 @@ class Aa {
5118
5131
  }, this.reset = async () => {
5119
5132
  this.sessionAbortController.abort(), this.sessionAbortController = new AbortController(), this.sessionState.reset();
5120
5133
  }, this.registerSessionsRefresherWrapper = () => {
5121
- var a;
5134
+ var t;
5122
5135
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
5123
- (a = this.contactCtx.state.get().contact) != null && a.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5124
- ({ contact: i }) => {
5125
- 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();
5126
5139
  }
5127
5140
  );
5128
5141
  }, this.registerSessionsRefresher = () => {
5129
5142
  this.sessionsRefresher.startPolling(async () => {
5130
5143
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
5131
5144
  }, this.sessionsPollingIntervalSeconds * 1e3);
5132
- }, this.dispose = ({ clearActiveSession: a = !1 } = {}) => {
5133
- var i, c;
5134
- 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)
5135
5148
  return this.persistedSessionId = null, this.storageCtx.clearActiveSessionId().catch((d) => {
5136
- k.warn("failed to clear the replaced session", {
5149
+ g.warn("failed to clear the replaced session", {
5137
5150
  error: d instanceof Error ? d.message : String(d)
5138
5151
  });
5139
5152
  });
5140
5153
  }, this.getParsedCustomData = () => Object.fromEntries(
5141
5154
  Object.entries(this.config.sessionCustomData || {}).map(
5142
- ([a, i]) => {
5155
+ ([t, n]) => {
5143
5156
  var c;
5144
- 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) || ""];
5145
5158
  }
5146
5159
  )
5147
5160
  ), this.createSession = async () => {
5148
- const { signal: a } = this.sessionAbortController;
5161
+ const { signal: t } = this.sessionAbortController;
5149
5162
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
5150
5163
  try {
5151
- const i = await this.requestSession(a);
5152
- if (a.aborted) return null;
5153
- if (i.session) return i.session;
5154
- if (i.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
5155
- if (a.aborted) return null;
5156
- const c = await this.requestSession(a);
5157
- 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);
5158
5171
  }
5159
- return k.error("failed to create session", i.error), null;
5160
- } catch (i) {
5161
- 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;
5162
5175
  } finally {
5163
- a.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5176
+ t.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5164
5177
  }
5165
- }, this.requestSession = async (a) => {
5166
- var u, m, g;
5167
- 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 = {
5168
5181
  ...this.getParsedCustomData(),
5169
- ...i ? { external_id: i } : {}
5182
+ ...n ? { external_id: n } : {}
5170
5183
  }, {
5171
5184
  data: d,
5172
5185
  error: _,
@@ -5175,155 +5188,152 @@ class Aa {
5175
5188
  {
5176
5189
  customData: Object.keys(c).length > 0 ? c : void 0
5177
5190
  },
5178
- a
5191
+ t
5179
5192
  );
5180
- if (a.aborted || !d)
5193
+ if (t.aborted || !d)
5181
5194
  return { session: null, status: p == null ? void 0 : p.status, error: _ };
5182
5195
  this.sessionState.setPartial({ session: d });
5183
5196
  try {
5184
- (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 });
5185
5198
  } catch (v) {
5186
- k.error("onSessionCreated hook failed", v);
5199
+ g.error("onSessionCreated hook failed", v);
5187
5200
  }
5188
5201
  return { session: d, status: p.status, error: void 0 };
5189
5202
  }, this.loadMoreSessions = async () => {
5190
5203
  if (this.sessionsState.get().isLastPage) return;
5191
- const { data: a } = await this.getSessions({
5204
+ const { data: t } = await this.getSessions({
5192
5205
  cursor: this.sessionsState.get().cursor
5193
5206
  });
5194
- if (a) {
5195
- const c = [...this.sessionsState.get().data, ...a.items].filter(
5207
+ if (t) {
5208
+ const c = [...this.sessionsState.get().data, ...t.items].filter(
5196
5209
  (d, _, p) => _ === p.findIndex((u) => d.id === u.id)
5197
5210
  );
5198
5211
  this.sessionsState.setPartial({
5199
5212
  data: c,
5200
- cursor: a.next || void 0,
5201
- isLastPage: a.next === null
5213
+ cursor: t.next || void 0,
5214
+ isLastPage: t.next === null
5202
5215
  });
5203
5216
  }
5204
- }, this.getSessions = async ({ cursor: a }) => {
5217
+ }, this.getSessions = async ({ cursor: t }) => {
5205
5218
  var c, d;
5206
5219
  if (!((c = this.contactCtx.state.get().contact) != null && c.token)) return { data: null };
5207
- 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;
5208
5221
  return await this.api.getSessions({
5209
- cursor: a,
5210
- filters: i ? {
5211
- external_id: i
5222
+ cursor: t,
5223
+ filters: n ? {
5224
+ external_id: n
5212
5225
  } : {}
5213
5226
  });
5214
- }, this.setSessions = (a) => {
5215
- const i = [...a, ...this.sessionsState.get().data].filter(
5227
+ }, this.setSessions = (t) => {
5228
+ const n = [...t, ...this.sessionsState.get().data].filter(
5216
5229
  (c, d, _) => d === _.findIndex((p) => c.id === p.id)
5217
5230
  );
5218
- this.sessionsState.setPartial({ data: i });
5231
+ this.sessionsState.setPartial({ data: n });
5219
5232
  }, this.refreshSessions = async () => {
5220
- const { data: a } = await this.getSessions({ cursor: void 0 });
5221
- a && this.setSessions(a.items);
5233
+ const { data: t } = await this.getSessions({ cursor: void 0 });
5234
+ t && this.setSessions(t.items);
5222
5235
  }, this.resolveSession = async () => {
5223
- const a = this.sessionState.get().session;
5224
- if (!a || !a.isOpened)
5236
+ const t = this.sessionState.get().session;
5237
+ if (!t || !t.isOpened)
5225
5238
  return { success: !1, error: "Session is not opened" };
5226
5239
  this.sessionState.setPartial({ isResolvingSession: !0 });
5227
- const { signal: i } = this.sessionAbortController, c = await this.api.resolveSession({ session_id: a.id }, i).catch((p) => {
5228
- 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;
5229
5242
  throw p;
5230
5243
  });
5231
- if (!c || i.aborted)
5244
+ if (!c || n.aborted)
5232
5245
  return { success: !1, error: "Session was reset" };
5233
5246
  const { data: d, error: _ } = c;
5234
5247
  return d ? (this.sessionState.setPartial({ session: d, isResolvingSession: !1 }), { success: !0, data: d }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: _ });
5235
- }, this.createStateCheckpoint = async (a) => {
5248
+ }, this.createStateCheckpoint = async (t) => {
5236
5249
  var d;
5237
- const i = (d = this.sessionState.get().session) == null ? void 0 : d.id;
5238
- if (!i) return;
5250
+ const n = (d = this.sessionState.get().session) == null ? void 0 : d.id;
5251
+ if (!n) return;
5239
5252
  const { data: c } = await this.api.createStateCheckpoint({
5240
- session_id: i,
5241
- payload: a
5253
+ session_id: n,
5254
+ payload: t
5242
5255
  });
5243
5256
  return c != null && c.success ? { success: !0 } : { success: !1 };
5244
- }, 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();
5245
5258
  }
5246
5259
  }
5247
- const Pa = (n, e, { sendsPageContext: t }) => {
5248
- 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 ? {
5249
5262
  ...l,
5250
5263
  opencx__connection_request_id: e.connectionRequestId
5251
- } : 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;
5252
5265
  return {
5253
- clientContext: e.background ? { ...a, opencx__background: !0 } : a,
5266
+ clientContext: e.background ? { ...t, opencx__background: !0 } : t,
5254
5267
  custom_data: {
5255
- ...n.messageCustomData || {},
5268
+ ...i.messageCustomData || {},
5256
5269
  ...e.customData || {}
5257
5270
  }
5258
5271
  };
5259
- }, Ta = ({ type: n, id: e, title: t, meta: o }) => ({
5260
- type: n,
5272
+ }, Pa = ({ type: i, id: e, title: a, meta: o }) => ({
5273
+ type: i,
5261
5274
  id: e,
5262
- title: t,
5275
+ title: a,
5263
5276
  ...o ? { meta: o } : {}
5264
- }), Ia = (n, e) => {
5265
- const { [e]: t, ...o } = n;
5277
+ }), Ta = (i, e) => {
5278
+ const { [e]: a, ...o } = i;
5266
5279
  return Object.keys(o).length > 0 ? o : void 0;
5267
- }, Ma = (n) => {
5268
- if (typeof n.context != "function") return n.context;
5280
+ }, Ia = (i) => {
5281
+ if (typeof i.context != "function") return i.context;
5269
5282
  try {
5270
- return n.context();
5283
+ return i.context();
5271
5284
  } catch (e) {
5272
- k.error("context getter threw; sending without context", e);
5285
+ g.error("context getter threw; sending without context", e);
5273
5286
  return;
5274
5287
  }
5275
- }, Da = (n) => {
5276
- const e = n.features;
5277
- if (!e) return;
5278
- const t = {};
5279
- 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;
5280
- }, Na = ({
5281
- 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,
5282
5297
  input: e,
5283
- uuid: t,
5298
+ uuid: a,
5284
5299
  sessionId: o,
5285
5300
  content: r,
5286
5301
  initialMessages: l,
5287
5302
  sendsPageContext: s
5288
5303
  }) => {
5289
- var a, i, c, d, _, p, u, m;
5304
+ var t, n, c, d;
5290
5305
  return {
5291
- uuid: t,
5292
- bot_token: n.token,
5293
- headers: n.headers,
5294
- query_params: n.queryParams,
5295
- 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,
5296
5311
  session_id: o,
5297
5312
  content: r,
5298
5313
  attachments: e.attachments,
5299
- ...Pa(n, e, { sendsPageContext: s }),
5300
- language: n.language,
5301
- features: Da(n),
5302
- presentation: n.presentation,
5303
- capabilities: [
5304
- (a = n.capabilities) == null ? void 0 : a.connections,
5305
- (i = n.capabilities) == null ? void 0 : i.structuredQuestions,
5306
- (c = n.capabilities) == null ? void 0 : c.richReplies,
5307
- (d = n.capabilities) == null ? void 0 : d.pageEffects
5308
- ].some((g) => g !== void 0) ? {
5309
- connections: (_ = n.capabilities) == null ? void 0 : _.connections,
5310
- structured_questions: (p = n.capabilities) == null ? void 0 : p.structuredQuestions,
5311
- rich_replies: (u = n.capabilities) == null ? void 0 : u.richReplies,
5312
- page_effects: (m = n.capabilities) == null ? void 0 : m.pageEffects
5313
- } : 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
+ },
5314
5324
  exit_mode_prompt: e.exitModePrompt,
5315
- 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
5316
5326
  };
5317
- }, C = class C {
5327
+ }, x = class x {
5318
5328
  constructor({
5319
5329
  config: e,
5320
- api: t,
5330
+ api: a,
5321
5331
  sessionCtx: o,
5322
5332
  contactCtx: r,
5323
5333
  streaming: l,
5324
5334
  sendsPageContext: s,
5325
- getClientCapabilities: a,
5326
- getRequestConfig: i,
5335
+ getClientCapabilities: t,
5336
+ getRequestConfig: n,
5327
5337
  isStreaming: c,
5328
5338
  getSendsPageContext: d
5329
5339
  }) {
@@ -5337,38 +5347,41 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5337
5347
  }), this.draftState = new S({
5338
5348
  text: "",
5339
5349
  mentions: []
5340
- }), this.agentHandlers = null, this.bufferedAgentSends = [], this.sendMessageAbortController = new AbortController(), this.messageIdsDispatchedToOnMessageReceivedHook = /* @__PURE__ */ new Set(), this.sentTextHistory = [], this.reset = () => {
5341
- 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();
5342
5355
  }, this.rememberSentText = (_) => {
5343
5356
  const p = _.trim();
5344
- !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());
5345
5358
  }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (_) => {
5346
5359
  this.agentHandlers = _;
5347
5360
  const p = this.bufferedAgentSends;
5348
5361
  this.bufferedAgentSends = [], p.forEach((u) => {
5349
- C.dispatchToEngine(_, u);
5362
+ x.dispatchToEngine(_, u);
5350
5363
  });
5351
5364
  }, this.unregisterAgentHandlers = (_) => {
5352
5365
  this.agentHandlers === _ && (this.agentHandlers = null);
5353
5366
  }, this.dispatchToOnMessageReceivedHook = (_) => {
5354
- var u, m;
5367
+ var u, h;
5355
5368
  if (_.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(_.id))
5356
5369
  return;
5357
5370
  const p = this.sessionCtx.sessionState.get().session;
5358
- 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 }));
5359
5372
  }, this.markAsDispatchedToOnMessageReceivedHook = (_) => {
5360
5373
  _.forEach(
5361
5374
  (p) => this.messageIdsDispatchedToOnMessageReceivedHook.add(p)
5362
5375
  );
5363
5376
  }, this.buildPersistentInitialMessages = () => {
5364
5377
  var p, u;
5365
- 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(
5366
- (m) => ({
5367
- 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(),
5368
5381
  component: "bot_message",
5369
5382
  type: "AI",
5370
5383
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5371
- data: { message: m.message },
5384
+ data: { message: h.message },
5372
5385
  agent: this.config.bot ? { ...this.config.bot, isAi: !0, id: null } : void 0
5373
5386
  })
5374
5387
  ) : [];
@@ -5381,49 +5394,50 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5381
5394
  return ((p = this.sessionCtx.sessionState.get().session) == null ? void 0 : p.id) ?? null;
5382
5395
  }, this.rollbackOptimisticMessages = (_) => {
5383
5396
  if (_.length === 0) return;
5384
- const p = new Set(_), u = this.state.get().messages, m = u.filter((g) => !p.has(g.id));
5385
- 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 });
5386
5399
  }, this.notifySendAccepted = (_) => {
5387
5400
  var p;
5388
5401
  try {
5389
5402
  (p = _.onAccepted) == null || p.call(_);
5390
5403
  } catch (u) {
5391
- k.error("send acceptance callback failed", u);
5404
+ g.error("send acceptance callback failed", u);
5392
5405
  }
5393
5406
  }, this.stageUserTurn = async (_, { pending: p }) => {
5394
- const u = this.buildUserMessage(_);
5395
- if (!u) return null;
5396
- const m = p ? { ...u, pending: !0 } : u, g = this.buildPersistentInitialMessages(), v = [
5397
- ...g.map((b) => b.id),
5398
- 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
5399
5412
  ];
5400
5413
  this.state.setPartial({
5401
5414
  messages: [
5402
- ...g,
5415
+ ...v,
5403
5416
  ...this.state.get().messages,
5404
- ...m.background ? [] : [m]
5417
+ ...k.background ? [] : [k]
5405
5418
  ]
5406
5419
  });
5407
- let f;
5420
+ let b;
5408
5421
  try {
5409
- f = await this.ensureSessionId();
5410
- } catch (b) {
5411
- throw this.rollbackOptimisticMessages(v), b;
5422
+ b = await this.ensureSessionId();
5423
+ } catch (y) {
5424
+ if (!u()) return null;
5425
+ throw this.rollbackOptimisticMessages(f), y;
5412
5426
  }
5413
- 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;
5414
5428
  }, this.buildQueuedUserMessage = (_) => {
5415
- var m;
5429
+ var h;
5416
5430
  const p = this.buildUserMessage(_);
5417
5431
  if (!p) return null;
5418
- 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;
5419
5433
  return u ? { sessionId: u, userMessage: { ...p, pending: !0 } } : null;
5420
5434
  }, this.buildUserMessage = (_) => {
5421
5435
  var p;
5422
- 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) : {
5423
5437
  ...this.toUserMessage(
5424
5438
  _.content.trim(),
5425
5439
  _.attachments || void 0,
5426
- this.sendsPageContext ? C.markedElementNames(_.clientContext) : void 0,
5440
+ this.sendsPageContext ? x.markedElementNames(_.clientContext) : void 0,
5427
5441
  this.sendsPageContext && ((p = _.mentions) != null && p.length) ? _.mentions : void 0
5428
5442
  ),
5429
5443
  ..._.background ? { background: !0 } : {}
@@ -5437,14 +5451,14 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5437
5451
  (v) => v.id === _ && v.type === "USER" && v.pending
5438
5452
  );
5439
5453
  if (u === -1) return;
5440
- const m = p[u];
5441
- if (!m || m.type !== "USER") return;
5442
- const g = [...p];
5443
- g[u] = { ...m, pending: !1 }, this.state.setPartial({
5444
- 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
5445
5459
  });
5446
5460
  }, this.sendMessage = async (_) => {
5447
- var u, m, g, v, f;
5461
+ var u, h, k, v, f;
5448
5462
  if (this.streaming) {
5449
5463
  if (!this.agentHandlers) {
5450
5464
  this.bufferedAgentSends.push(_);
@@ -5455,92 +5469,93 @@ const Pa = (n, e, { sendsPageContext: t }) => {
5455
5469
  }
5456
5470
  let p;
5457
5471
  try {
5458
- 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);
5459
5473
  if (this.blocksSendWhileAwaitingReply && (X || // If last message is from user, then bot response did not arrive yet
5460
- R && (E == null ? void 0 : E.type) === "USER" && E.id !== this.state.get().settledAgentUserMessageId)) {
5461
- 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");
5462
5476
  return;
5463
5477
  }
5464
5478
  this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), p = this.sendMessageAbortController, this.state.setPartial({
5465
5479
  lastAIResMightSolveUserIssue: !1,
5466
5480
  isSendingMessage: !0,
5467
- isSendingMessageToAI: !!R || !b
5481
+ isSendingMessageToAI: !!z || !b
5468
5482
  });
5469
- const K = await this.stageUserTurn(_, { pending: !1 });
5470
- if (!K) return;
5471
- 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;
5472
5486
  this.notifySendAccepted(_);
5473
- const { data: y } = await this.api.sendMessage(
5474
- Na({
5487
+ const { data: w } = await this.api.sendMessage(
5488
+ Da({
5475
5489
  config: {
5476
5490
  ...this.getRequestConfig(),
5477
5491
  capabilities: this.getClientCapabilities()
5478
5492
  },
5479
5493
  input: _,
5480
- uuid: L.id,
5481
- sessionId: ee,
5482
- content: L.content,
5483
- initialMessages: ae,
5494
+ uuid: K.id,
5495
+ sessionId: Q,
5496
+ content: K.content,
5497
+ initialMessages: ee,
5484
5498
  sendsPageContext: this.sendsPageContext
5485
5499
  }),
5486
5500
  p.signal
5487
5501
  );
5488
- if (y != null && y.success) {
5489
- const z = this.toBotMessage(y);
5490
- if (z) {
5491
- const A = this.state.get().messages;
5492
- if (!!A.some(
5493
- (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
5494
5508
  )) {
5495
5509
  this.state.setPartial({
5496
- 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)
5497
5511
  });
5498
5512
  return;
5499
5513
  }
5500
5514
  this.state.setPartial({
5501
- messages: [...A, z],
5502
- lastAIResMightSolveUserIssue: ((g = y.autopilotResponse) == null ? void 0 : g.mightSolveUserIssue) || ((v = y.uiResponse) == null ? void 0 : v.mightSolveUserIssue)
5503
- }), 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);
5504
5518
  }
5505
- y.session && this.sessionCtx.sessionState.setPartial({ session: y.session });
5519
+ w.session && this.sessionCtx.sessionState.setPartial({ session: w.session });
5506
5520
  } else {
5507
- const z = this.toBotErrorMessage(
5508
- ((f = y == null ? void 0 : y.error) == null ? void 0 : f.message) || Ea(this.config, "turn_failed_message")
5509
- ), 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;
5510
5524
  this.state.setPartial({
5511
- messages: [...A, z]
5525
+ messages: [...P, C]
5512
5526
  });
5513
5527
  }
5514
5528
  } catch (b) {
5515
- 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);
5516
5530
  } finally {
5517
5531
  p != null && p.signal.aborted || this.state.setPartial({
5518
5532
  isSendingMessage: !1,
5519
5533
  isSendingMessageToAI: !1
5520
5534
  });
5521
5535
  }
5522
- }, this.toUserMessage = (_, p, u, m) => {
5523
- const g = (() => {
5524
- const v = this.contactCtx.state.get().extraCollectedData;
5525
- 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(`
5526
5540
  `)}
5527
5541
 
5528
5542
  ${_}` : _;
5529
- })();
5543
+ })(), v = (/* @__PURE__ */ new Date()).toISOString();
5530
5544
  return {
5531
- id: x(),
5545
+ id: q(),
5532
5546
  type: "USER",
5533
- content: g,
5547
+ deliveredAt: v,
5548
+ content: k,
5534
5549
  attachments: p,
5535
5550
  markedElements: u,
5536
- mentions: m,
5537
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
5551
+ mentions: h,
5552
+ timestamp: v
5538
5553
  };
5539
5554
  }, this.toBotMessage = (_) => {
5540
5555
  var p;
5541
5556
  return _.success && _.autopilotResponse ? {
5542
5557
  type: "AI",
5543
- id: _.autopilotResponse.id || x(),
5558
+ id: _.autopilotResponse.id || q(),
5544
5559
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5545
5560
  component: "bot_message",
5546
5561
  agent: this.config.bot ? {
@@ -5561,7 +5576,7 @@ ${_}` : _;
5561
5576
  } : null;
5562
5577
  }, this.toBotErrorMessage = (_) => ({
5563
5578
  type: "AI",
5564
- id: x(),
5579
+ id: q(),
5565
5580
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5566
5581
  component: "bot_message",
5567
5582
  data: {
@@ -5569,7 +5584,7 @@ ${_}` : _;
5569
5584
  variant: "error",
5570
5585
  action: void 0
5571
5586
  }
5572
- }), 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);
5573
5588
  }
5574
5589
  /**
5575
5590
  * Current transport choice. The org or this embed may request polling
@@ -5582,18 +5597,18 @@ ${_}` : _;
5582
5597
  return this.getSendsPageContext();
5583
5598
  }
5584
5599
  /** Hand a send to the streaming engine; its failure can never propagate. */
5585
- static dispatchToEngine(e, t) {
5600
+ static dispatchToEngine(e, a) {
5586
5601
  try {
5587
- Promise.resolve(e.send(t)).catch((o) => {
5588
- k.error("streaming send failed", o);
5602
+ Promise.resolve(e.send(a)).catch((o) => {
5603
+ g.error("streaming send failed", o);
5589
5604
  });
5590
5605
  } catch (o) {
5591
- k.error("streaming send failed", o);
5606
+ g.error("streaming send failed", o);
5592
5607
  }
5593
5608
  }
5594
5609
  get hasPendingAgentWork() {
5595
- var e, t;
5596
- 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);
5597
5612
  }
5598
5613
  /**
5599
5614
  * Defensive read of `clientContext.page_marks` → the user bubble's context
@@ -5603,17 +5618,17 @@ ${_}` : _;
5603
5618
  * without a usable name are dropped.
5604
5619
  */
5605
5620
  static markedElementNames(e) {
5606
- const t = e == null ? void 0 : e.page_marks;
5607
- if (!Array.isArray(t)) return;
5608
- 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) => {
5609
5624
  if (typeof r != "object" || r === null) return [];
5610
- 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;
5611
- if (typeof a != "string" || a.length === 0) return [];
5612
- 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;
5613
5628
  return [
5614
5629
  {
5615
- name: a,
5616
- ...typeof i == "string" && i.length > 0 ? { note: i } : {},
5630
+ name: t,
5631
+ ...typeof n == "string" && n.length > 0 ? { note: n } : {},
5617
5632
  ...typeof c == "string" && c.length > 0 ? { snapshotUrl: c } : {},
5618
5633
  mark: r
5619
5634
  }
@@ -5629,11 +5644,11 @@ ${_}` : _;
5629
5644
  return !this.streaming && this.config.disableSendingWhenAwaitingAIReply !== !1;
5630
5645
  }
5631
5646
  };
5632
- C.SENT_TEXT_HISTORY_MAX = 50;
5633
- let D = C;
5634
- class Ra {
5647
+ x.SENT_TEXT_HISTORY_MAX = 50;
5648
+ let D = x;
5649
+ class Na {
5635
5650
  constructor(e) {
5636
- var t, o;
5651
+ var a, o;
5637
5652
  this.widget = e, this.subscriptions = [], this.disposed = !1, this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
5638
5653
  if (!this.shouldRestoreLastSession) {
5639
5654
  this.didReadStoredSession = !0;
@@ -5659,7 +5674,7 @@ class Ra {
5659
5674
  isInitialFetchLoading: r,
5660
5675
  data: l
5661
5676
  }) => {
5662
- var s, a, i, c, d;
5677
+ var s, t, n, c, d;
5663
5678
  if (!(this.disposed || !this.didReadStoredSession)) {
5664
5679
  if (this.restorableSessionId && !((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
5665
5680
  const _ = l.find(
@@ -5672,9 +5687,9 @@ class Ra {
5672
5687
  if (r) return;
5673
5688
  this.restorableSessionId = null;
5674
5689
  }
5675
- 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
5676
5691
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
5677
- !((i = this.sessionCtx.sessionState.get().session) != null && i.id)) {
5692
+ !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
5678
5693
  const _ = (c = l.find((p) => p.isOpened)) == null ? void 0 : c.id;
5679
5694
  return _ ? this.toChatScreen(_) : void 0;
5680
5695
  }
@@ -5685,24 +5700,24 @@ class Ra {
5685
5700
  }, this.toSessionsScreen = () => {
5686
5701
  this.navigateConversation || this.resetChat(), this.state.setPartial({ screen: "sessions" });
5687
5702
  }, this.toChatScreen = (r) => {
5688
- var s, a;
5703
+ var s, t;
5689
5704
  if (this.navigateConversation) return this.navigateConversation(r);
5690
5705
  this.resetChat();
5691
5706
  let l;
5692
5707
  if (r) {
5693
- 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;
5694
5709
  this.sessionCtx.sessionState.setPartial({ session: l });
5695
5710
  }
5696
- 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;
5697
5712
  }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new S({
5698
- 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"
5699
5714
  }), this.shouldRestoreLastSession = ((o = this.config.router) == null ? void 0 : o.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5700
5715
  }
5701
5716
  }
5702
- class Ka {
5717
+ class Ra {
5703
5718
  constructor({
5704
5719
  storage: e,
5705
- config: t
5720
+ config: a
5706
5721
  }) {
5707
5722
  this.KEYS = {
5708
5723
  contactToken: (o) => `opencx-widget:org-token-${o}:contact-token`,
@@ -5743,11 +5758,11 @@ class Ka {
5743
5758
  return o === "docked" || o === "floating" ? o : null;
5744
5759
  }, this.setCompanionSidebarMode = async (o) => {
5745
5760
  await this.storage.set(this.companionKey("sidebar-mode"), o);
5746
- }, this.storage = e, this.config = t;
5761
+ }, this.storage = e, this.config = a;
5747
5762
  }
5748
5763
  }
5749
- function La({
5750
- org: n,
5764
+ function Ka({
5765
+ org: i,
5751
5766
  agent: e
5752
5767
  }) {
5753
5768
  return e ? {
@@ -5759,53 +5774,50 @@ function La({
5759
5774
  dictation: e.features.dictation,
5760
5775
  attachments: e.features.attachments,
5761
5776
  pageContext: e.features.page_context,
5762
- clientTools: e.features.client_tools
5777
+ clientTools: e.features.client_tools,
5778
+ pageActions: e.features.page_actions === !0
5763
5779
  }
5764
5780
  } : {
5765
- name: n.name,
5781
+ name: i.name,
5766
5782
  avatarUrl: null,
5767
5783
  streaming: !1,
5768
5784
  features: {
5769
5785
  dictation: !1,
5770
5786
  attachments: !0,
5771
5787
  pageContext: !1,
5772
- clientTools: !1
5788
+ clientTools: !1,
5789
+ pageActions: !1
5773
5790
  }
5774
5791
  };
5775
5792
  }
5776
- function M(n, e) {
5777
- return n && e !== !1;
5793
+ function La(i, e) {
5794
+ return i && e !== !1;
5778
5795
  }
5779
- function Fa(n, e) {
5780
- const t = e.features;
5796
+ function Fa(i, e) {
5797
+ const a = e.features;
5781
5798
  return {
5782
- dictation: M(n.features.dictation, t == null ? void 0 : t.dictation),
5783
- attachments: n.features.attachments,
5784
- pageContext: M(
5785
- n.features.pageContext,
5786
- t == null ? void 0 : t.pageContext
5787
- ),
5788
- clientTools: M(
5789
- n.features.clientTools,
5790
- t == null ? void 0 : t.clientTools
5791
- )
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
5792
5804
  };
5793
5805
  }
5794
5806
  class Oa extends Error {
5795
- constructor(e, t, o) {
5796
- 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;
5797
5809
  }
5798
5810
  }
5799
5811
  const j = class j {
5800
5812
  constructor({
5801
5813
  config: e,
5802
- storage: t,
5814
+ storage: a,
5803
5815
  getClientCapabilities: o,
5804
5816
  getRequestConfig: r,
5805
5817
  modes: l,
5806
5818
  org: s,
5807
- agent: a,
5808
- parent: i
5819
+ agent: t,
5820
+ parent: n
5809
5821
  }) {
5810
5822
  if (this.modes = [], this.disposed = !1, this.createConversation = () => {
5811
5823
  const c = new j({
@@ -5832,24 +5844,24 @@ const j = class j {
5832
5844
  if (this.disposed) return;
5833
5845
  this.disposed = !0, this.routerCtx.dispose(), this.activeSessionPollingCtx.dispose();
5834
5846
  const d = this.sessionCtx.dispose({ clearActiveSession: c });
5835
- 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;
5836
5848
  }, this.resetChat = () => {
5837
5849
  this.sessionCtx.reset(), this.messageCtx.reset(), this.uploadCtx.reset();
5838
5850
  }, this.reconcileAfterStream = (c) => this.activeSessionPollingCtx.reconcileAfterStream(c), !j.pollingIntervalsSeconds)
5839
5851
  throw Error(
5840
5852
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
5841
5853
  );
5842
- 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({
5843
5855
  api: this.api,
5844
5856
  config: this.config,
5845
5857
  storageCtx: this.storageCtx
5846
- }), this.sessionCtx = new Aa({
5858
+ }), this.sessionCtx = new Ea({
5847
5859
  config: this.config,
5848
5860
  api: this.api,
5849
5861
  contactCtx: this.contactCtx,
5850
5862
  // Remembers the open conversation so a reload can return to it.
5851
- storageCtx: i ? void 0 : this.storageCtx,
5852
- sharedSessions: i == null ? void 0 : i.sessionCtx.sessionsState,
5863
+ storageCtx: n ? void 0 : this.storageCtx,
5864
+ sharedSessions: n == null ? void 0 : n.sessionCtx.sessionsState,
5853
5865
  sessionsPollingIntervalSeconds: j.pollingIntervalsSeconds.sessions
5854
5866
  }), this.messageCtx = new D({
5855
5867
  config: this.config,
@@ -5864,24 +5876,24 @@ const j = class j {
5864
5876
  getSendsPageContext: () => this.features.pageContext,
5865
5877
  getClientCapabilities: o,
5866
5878
  getRequestConfig: r
5867
- }), this.uploadCtx = new ke(this.api), this.csatCtx = new be({
5879
+ }), this.uploadCtx = new ge(this.api), this.csatCtx = new ke({
5868
5880
  api: this.api,
5869
5881
  sessionCtx: this.sessionCtx,
5870
5882
  messageCtx: this.messageCtx
5871
- }), this.dictationCtx = new Fe({
5883
+ }), this.dictationCtx = new Le({
5872
5884
  api: this.api,
5873
5885
  config: this.config
5874
- }), this.activeSessionPollingCtx = new he({
5886
+ }), this.activeSessionPollingCtx = new me({
5875
5887
  api: this.api,
5876
5888
  config: this.config,
5877
5889
  sessionCtx: this.sessionCtx,
5878
5890
  messageCtx: this.messageCtx,
5879
5891
  sessionPollingIntervalSeconds: j.pollingIntervalsSeconds.session
5880
- }), this.routerCtx = new Ra(this);
5892
+ }), this.routerCtx = new Na(this);
5881
5893
  }
5882
5894
  get streaming() {
5883
- var e, t;
5884
- 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;
5885
5897
  }
5886
5898
  /**
5887
5899
  * The org's features narrowed by this embed's `config.features` — the
@@ -5893,26 +5905,26 @@ const j = class j {
5893
5905
  };
5894
5906
  j.pollingIntervalsSeconds = null, j.initialize = async ({
5895
5907
  config: e,
5896
- storage: t,
5908
+ storage: a,
5897
5909
  getClientCapabilities: o,
5898
5910
  getRequestConfig: r
5899
5911
  }) => {
5900
- var s, a;
5901
- const l = await new B({
5912
+ var s, t;
5913
+ const l = await new U({
5902
5914
  config: e
5903
5915
  }).getExternalWidgetConfig();
5904
5916
  if (!l.data)
5905
- throw k.error("widget config fetch failed", l.error), new Oa(
5917
+ throw g.error("widget config fetch failed", l.error), new Oa(
5906
5918
  "config-fetch-failed",
5907
5919
  "Failed to fetch widget config",
5908
5920
  l.error
5909
5921
  );
5910
5922
  return j.pollingIntervalsSeconds = {
5911
5923
  session: ((s = l.data) == null ? void 0 : s.sessionPollingIntervalSeconds) || 10,
5912
- sessions: ((a = l.data) == null ? void 0 : a.sessionsPollingIntervalSeconds) || 60
5924
+ sessions: ((t = l.data) == null ? void 0 : t.sessionsPollingIntervalSeconds) || 60
5913
5925
  }, new j({
5914
5926
  config: e,
5915
- storage: t,
5927
+ storage: a,
5916
5928
  getClientCapabilities: o,
5917
5929
  getRequestConfig: r,
5918
5930
  modes: l.data.modes || [],
@@ -5920,20 +5932,20 @@ j.pollingIntervalsSeconds = null, j.initialize = async ({
5920
5932
  id: l.data.org.id,
5921
5933
  name: l.data.org.name
5922
5934
  },
5923
- agent: La(l.data)
5935
+ agent: Ka(l.data)
5924
5936
  });
5925
5937
  };
5926
- let W = j;
5927
- function Ya(n, e) {
5928
- return n ? {
5929
- streaming: n.streaming && (e == null ? void 0 : e.streaming) !== !1,
5930
- toolActivity: n.toolActivity === "hidden" || (e == null ? void 0 : e.toolActivity) === "hidden" ? "hidden" : n.toolActivity === "status" || (e == null ? void 0 : e.toolActivity) === "status" ? "status" : "details",
5931
- 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
5932
5944
  } : e;
5933
5945
  }
5934
- class Qa {
5935
- constructor({ attack: e, release: t }) {
5936
- 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;
5937
5949
  }
5938
5950
  next(e) {
5939
5951
  return this.value += (e - this.value) * (e > this.value ? this.attack : this.release), this.value;
@@ -5942,56 +5954,56 @@ class Qa {
5942
5954
  return this.value;
5943
5955
  }
5944
5956
  }
5945
- const T = [
5957
+ const I = [
5946
5958
  "compact",
5947
5959
  "sidebar",
5948
5960
  "fullscreen"
5949
5961
  ], Ua = new Set(
5950
- T
5962
+ I
5951
5963
  );
5952
- function Q(n) {
5953
- return Ua.has(n);
5964
+ function Y(i) {
5965
+ return Ua.has(i);
5954
5966
  }
5955
- function Xa(n) {
5956
- if (!Array.isArray(n)) return T;
5957
- const e = [], t = /* @__PURE__ */ new Set();
5958
- for (const o of n)
5959
- !Q(o) || t.has(o) || (t.add(o), e.push(o));
5960
- 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;
5961
5973
  }
5962
- function et(n, e) {
5963
- 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];
5964
5976
  }
5965
- function at(n, e) {
5966
- 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";
5967
5979
  }
5968
- function tt(n) {
5969
- return n === "docked" ? "docked" : "floating";
5980
+ function tt(i) {
5981
+ return i === "docked" ? "docked" : "floating";
5970
5982
  }
5971
5983
  export {
5972
- pe as ConnectionAttemptUnavailableError,
5973
- ce as ConnectionRequestExpiredError,
5974
- Qa as DictationLevelSmoother,
5984
+ ce as ConnectionAttemptUnavailableError,
5985
+ le as ConnectionRequestExpiredError,
5986
+ Xa as DictationLevelSmoother,
5975
5987
  S as PrimitiveState,
5976
- W as WidgetCtx,
5988
+ G as WidgetCtx,
5977
5989
  Oa as WidgetInitializationError,
5978
- Na as buildSendMessageBody,
5979
- x as genUuid,
5980
- qa as getTranslation,
5981
- Ga as isAgentStreamKeepalive,
5982
- me as isExhaustive,
5983
- 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,
5984
5996
  Ja as isRtlLanguage,
5985
- za as isSupportedLanguage,
5997
+ Sa as isSupportedLanguage,
5986
5998
  $a as isTurnSteeredPart,
5987
- k as log,
5988
- Xa as normalizeCompanionLayouts,
5999
+ g as log,
6000
+ Qa as normalizeCompanionLayouts,
5989
6001
  Ya as resolveClientPresentation,
5990
6002
  et as resolveCompanionDefaultLayout,
5991
- Ma as resolveConfigContext,
5992
- xa as resolveLanguage,
6003
+ Ia as resolveConfigContext,
6004
+ Ca as resolveLanguage,
5993
6005
  tt as resolveSidebarMode,
5994
6006
  at as resolveSidebarSide,
5995
- Ea as translate
6007
+ qa as translate
5996
6008
  };
5997
6009
  //# sourceMappingURL=index.js.map