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

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