@opencx/widget-core 5.0.0-beta.0 → 5.0.0-beta.10

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 (141) hide show
  1. package/dist/index.cjs +8 -8
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.js +1797 -1078
  4. package/dist/index.js.map +1 -1
  5. package/dist/src/api/api-caller.d.ts +105 -3
  6. package/dist/src/api/api-caller.d.ts.map +1 -1
  7. package/dist/src/api/elicitation.d.ts +60 -0
  8. package/dist/src/api/elicitation.d.ts.map +1 -0
  9. package/dist/src/api/schema.d.ts +603 -44
  10. package/dist/src/api/schema.d.ts.map +1 -1
  11. package/dist/src/context/active-session-polling.ctx.d.ts +11 -1
  12. package/dist/src/context/active-session-polling.ctx.d.ts.map +1 -1
  13. package/dist/src/context/message.ctx.d.ts +28 -6
  14. package/dist/src/context/message.ctx.d.ts.map +1 -1
  15. package/dist/src/context/resolve-client-presentation.d.ts +5 -0
  16. package/dist/src/context/resolve-client-presentation.d.ts.map +1 -0
  17. package/dist/src/context/router.ctx.d.ts +8 -10
  18. package/dist/src/context/router.ctx.d.ts.map +1 -1
  19. package/dist/src/context/session.ctx.d.ts +18 -1
  20. package/dist/src/context/session.ctx.d.ts.map +1 -1
  21. package/dist/src/context/upload.ctx.d.ts +23 -0
  22. package/dist/src/context/upload.ctx.d.ts.map +1 -0
  23. package/dist/src/context/widget-agent.d.ts +4 -4
  24. package/dist/src/context/widget-agent.d.ts.map +1 -1
  25. package/dist/src/context/widget.ctx.d.ts +20 -6
  26. package/dist/src/context/widget.ctx.d.ts.map +1 -1
  27. package/dist/src/index.d.ts +5 -0
  28. package/dist/src/index.d.ts.map +1 -1
  29. package/dist/src/translation/ar.d.ts.map +1 -1
  30. package/dist/src/translation/bg.d.ts.map +1 -1
  31. package/dist/src/translation/bn.d.ts.map +1 -1
  32. package/dist/src/translation/cs.d.ts.map +1 -1
  33. package/dist/src/translation/da.d.ts.map +1 -1
  34. package/dist/src/translation/de.d.ts.map +1 -1
  35. package/dist/src/translation/el.d.ts.map +1 -1
  36. package/dist/src/translation/en.d.ts.map +1 -1
  37. package/dist/src/translation/es.d.ts.map +1 -1
  38. package/dist/src/translation/et.d.ts.map +1 -1
  39. package/dist/src/translation/fi.d.ts.map +1 -1
  40. package/dist/src/translation/fil.d.ts.map +1 -1
  41. package/dist/src/translation/fr.d.ts.map +1 -1
  42. package/dist/src/translation/hi.d.ts.map +1 -1
  43. package/dist/src/translation/hr.d.ts.map +1 -1
  44. package/dist/src/translation/hu.d.ts.map +1 -1
  45. package/dist/src/translation/index.d.ts +24 -0
  46. package/dist/src/translation/index.d.ts.map +1 -1
  47. package/dist/src/translation/is.d.ts.map +1 -1
  48. package/dist/src/translation/it.d.ts.map +1 -1
  49. package/dist/src/translation/ja.d.ts.map +1 -1
  50. package/dist/src/translation/ko.d.ts.map +1 -1
  51. package/dist/src/translation/lb.d.ts.map +1 -1
  52. package/dist/src/translation/lt.d.ts.map +1 -1
  53. package/dist/src/translation/lv.d.ts.map +1 -1
  54. package/dist/src/translation/mt.d.ts.map +1 -1
  55. package/dist/src/translation/nb.d.ts.map +1 -1
  56. package/dist/src/translation/nl.d.ts.map +1 -1
  57. package/dist/src/translation/no.d.ts.map +1 -1
  58. package/dist/src/translation/pl.d.ts.map +1 -1
  59. package/dist/src/translation/pt.d.ts.map +1 -1
  60. package/dist/src/translation/ro.d.ts.map +1 -1
  61. package/dist/src/translation/ru.d.ts.map +1 -1
  62. package/dist/src/translation/sk.d.ts.map +1 -1
  63. package/dist/src/translation/sv.d.ts.map +1 -1
  64. package/dist/src/translation/th.d.ts.map +1 -1
  65. package/dist/src/translation/tr.d.ts.map +1 -1
  66. package/dist/src/translation/ur.d.ts.map +1 -1
  67. package/dist/src/translation/vi.d.ts.map +1 -1
  68. package/dist/src/translation/zh-cn.d.ts.map +1 -1
  69. package/dist/src/types/component-name.d.ts +1 -1
  70. package/dist/src/types/component-name.d.ts.map +1 -1
  71. package/dist/src/types/messages.d.ts +14 -1
  72. package/dist/src/types/messages.d.ts.map +1 -1
  73. package/dist/src/types/widget-config.d.ts +38 -6
  74. package/dist/src/types/widget-config.d.ts.map +1 -1
  75. package/package.json +6 -5
  76. package/dist/src/__tests__/api/agent-stream-parts.spec.d.ts +0 -2
  77. package/dist/src/__tests__/api/agent-stream-parts.spec.d.ts.map +0 -1
  78. package/dist/src/__tests__/api/dictation-mint-cache.spec.d.ts +0 -2
  79. package/dist/src/__tests__/api/dictation-mint-cache.spec.d.ts.map +0 -1
  80. package/dist/src/__tests__/api/widget-api-wire.spec.d.ts +0 -2
  81. package/dist/src/__tests__/api/widget-api-wire.spec.d.ts.map +0 -1
  82. package/dist/src/__tests__/api-caller.mock.d.ts +0 -2
  83. package/dist/src/__tests__/api-caller.mock.d.ts.map +0 -1
  84. package/dist/src/__tests__/context/contact/auth/auto-create-unverified-anonymous.spec.d.ts +0 -1
  85. package/dist/src/__tests__/context/contact/auth/auto-create-unverified-anonymous.spec.d.ts.map +0 -1
  86. package/dist/src/__tests__/context/contact/auth/auto-create-unverified-with-user-data-provided-by-org.spec.d.ts +0 -1
  87. package/dist/src/__tests__/context/contact/auth/auto-create-unverified-with-user-data-provided-by-org.spec.d.ts.map +0 -1
  88. package/dist/src/__tests__/context/contact/auth/manually-create-unverified-with-user-data-provided-by-user.spec.d.ts +0 -1
  89. package/dist/src/__tests__/context/contact/auth/manually-create-unverified-with-user-data-provided-by-user.spec.d.ts.map +0 -1
  90. package/dist/src/__tests__/context/contact/auth/with-secure-token.spec.d.ts +0 -1
  91. package/dist/src/__tests__/context/contact/auth/with-secure-token.spec.d.ts.map +0 -1
  92. package/dist/src/__tests__/context/contact/should-collect-data.spec.d.ts +0 -1
  93. package/dist/src/__tests__/context/contact/should-collect-data.spec.d.ts.map +0 -1
  94. package/dist/src/__tests__/context/contact-ctx.create-failure.spec.d.ts +0 -2
  95. package/dist/src/__tests__/context/contact-ctx.create-failure.spec.d.ts.map +0 -1
  96. package/dist/src/__tests__/context/dictation-ctx.spec.d.ts +0 -1
  97. package/dist/src/__tests__/context/dictation-ctx.spec.d.ts.map +0 -1
  98. package/dist/src/__tests__/context/message/merge-send-context.spec.d.ts +0 -2
  99. package/dist/src/__tests__/context/message/merge-send-context.spec.d.ts.map +0 -1
  100. package/dist/src/__tests__/context/message/on-message-received-hook.spec.d.ts +0 -1
  101. package/dist/src/__tests__/context/message/on-message-received-hook.spec.d.ts.map +0 -1
  102. package/dist/src/__tests__/context/message/pending-user-messages.spec.d.ts +0 -1
  103. package/dist/src/__tests__/context/message/pending-user-messages.spec.d.ts.map +0 -1
  104. package/dist/src/__tests__/context/message/sent-text-history.spec.d.ts +0 -1
  105. package/dist/src/__tests__/context/message/sent-text-history.spec.d.ts.map +0 -1
  106. package/dist/src/__tests__/context/message-ctx.agent-handlers.spec.d.ts +0 -2
  107. package/dist/src/__tests__/context/message-ctx.agent-handlers.spec.d.ts.map +0 -1
  108. package/dist/src/__tests__/context/message-ctx.client-context.spec.d.ts +0 -2
  109. package/dist/src/__tests__/context/message-ctx.client-context.spec.d.ts.map +0 -1
  110. package/dist/src/__tests__/context/message-ctx.mentions.spec.d.ts +0 -2
  111. package/dist/src/__tests__/context/message-ctx.mentions.spec.d.ts.map +0 -1
  112. package/dist/src/__tests__/context/message-ctx.page-mark-chips.spec.d.ts +0 -2
  113. package/dist/src/__tests__/context/message-ctx.page-mark-chips.spec.d.ts.map +0 -1
  114. package/dist/src/__tests__/context/message-ctx.send-acceptance.spec.d.ts +0 -2
  115. package/dist/src/__tests__/context/message-ctx.send-acceptance.spec.d.ts.map +0 -1
  116. package/dist/src/__tests__/context/message-ctx.send-features.spec.d.ts +0 -2
  117. package/dist/src/__tests__/context/message-ctx.send-features.spec.d.ts.map +0 -1
  118. package/dist/src/__tests__/context/reconcile-after-stream.spec.d.ts +0 -1
  119. package/dist/src/__tests__/context/reconcile-after-stream.spec.d.ts.map +0 -1
  120. package/dist/src/__tests__/context/restore-last-session.spec.d.ts +0 -2
  121. package/dist/src/__tests__/context/restore-last-session.spec.d.ts.map +0 -1
  122. package/dist/src/__tests__/context/session-ctx.stale-token-retry.spec.d.ts +0 -2
  123. package/dist/src/__tests__/context/session-ctx.stale-token-retry.spec.d.ts.map +0 -1
  124. package/dist/src/__tests__/context/storage-ctx.spec.d.ts +0 -2
  125. package/dist/src/__tests__/context/storage-ctx.spec.d.ts.map +0 -1
  126. package/dist/src/__tests__/context/streaming-engine.spec.d.ts +0 -1
  127. package/dist/src/__tests__/context/streaming-engine.spec.d.ts.map +0 -1
  128. package/dist/src/__tests__/context/widget-ctx.features.spec.d.ts +0 -1
  129. package/dist/src/__tests__/context/widget-ctx.features.spec.d.ts.map +0 -1
  130. package/dist/src/__tests__/dictation/dictation-commands.utils.spec.d.ts +0 -2
  131. package/dist/src/__tests__/dictation/dictation-commands.utils.spec.d.ts.map +0 -1
  132. package/dist/src/__tests__/test-utils.d.ts +0 -445
  133. package/dist/src/__tests__/test-utils.d.ts.map +0 -1
  134. package/dist/src/__tests__/translation.spec.d.ts +0 -2
  135. package/dist/src/__tests__/translation.spec.d.ts.map +0 -1
  136. package/dist/src/__tests__/utils/Poller.spec.d.ts +0 -2
  137. package/dist/src/__tests__/utils/Poller.spec.d.ts.map +0 -1
  138. package/dist/src/__tests__/utils/PrimitiveState.spec.d.ts +0 -2
  139. package/dist/src/__tests__/utils/PrimitiveState.spec.d.ts.map +0 -1
  140. package/dist/src/__tests__/utils/companion-layout.spec.d.ts +0 -2
  141. package/dist/src/__tests__/utils/companion-layout.spec.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,484 +1,657 @@
1
- import J from "openapi-fetch";
2
- import Y from "lodash.isequal";
3
- import { v4 as U } from "uuid";
4
- const Da = (i) => i.type === "data-keepalive", Na = (i) => i.type === "data-turn-steered", D = "[opencx]", h = {
5
- warn: (i, ...a) => {
6
- console.warn(`${D} ${i}`, ...a);
1
+ import { z as h } from "zod";
2
+ import se from "openapi-fetch";
3
+ import oe from "lodash.isequal";
4
+ import { v4 as N } from "uuid";
5
+ const Ga = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn-steered", F = h.object({ const: h.string(), title: h.string().optional() }), ne = h.object({
6
+ type: h.enum(["string", "number", "integer", "boolean", "array"]),
7
+ title: h.string().optional(),
8
+ description: h.string().optional(),
9
+ default: h.union([h.string(), h.number(), h.boolean(), h.array(h.string())]).optional(),
10
+ enum: h.array(h.string()).optional(),
11
+ oneOf: h.array(F).optional(),
12
+ items: h.object({
13
+ enum: h.array(h.string()).optional(),
14
+ anyOf: h.array(F).optional()
15
+ }).optional(),
16
+ minItems: h.number().int().nonnegative().optional(),
17
+ maxItems: h.number().int().nonnegative().optional(),
18
+ minimum: h.number().optional(),
19
+ maximum: h.number().optional(),
20
+ minLength: h.number().optional(),
21
+ maxLength: h.number().optional(),
22
+ format: h.string().optional()
23
+ }), ie = h.array(
24
+ h.object({
25
+ id: h.string(),
26
+ serverId: h.string(),
27
+ serverName: h.string(),
28
+ expiresAt: h.number(),
29
+ approvalKey: h.string().optional(),
30
+ form: h.object({
31
+ message: h.string(),
32
+ requestedSchema: h.object({
33
+ properties: h.record(h.string(), ne),
34
+ required: h.array(h.string()).optional()
35
+ })
36
+ })
37
+ })
38
+ ), re = h.array(
39
+ h.object({
40
+ key: h.string(),
41
+ serverId: h.string(),
42
+ serverName: h.string(),
43
+ message: h.string(),
44
+ toolName: h.string()
45
+ })
46
+ ), O = "[opencx]", k = {
47
+ warn: (i, ...e) => {
48
+ console.warn(`${O} ${i}`, ...e);
7
49
  },
8
- error: (i, ...a) => {
9
- console.error(`${D} ${i}`, ...a);
50
+ error: (i, ...e) => {
51
+ console.error(`${O} ${i}`, ...e);
10
52
  }
11
- }, X = (i) => {
12
- h.error("request failed", i.error);
13
- }, Q = (i) => {
14
- const a = J({
53
+ }, _e = (i) => {
54
+ k.error("request failed", i.error);
55
+ }, le = (i) => {
56
+ const e = se({
15
57
  baseUrl: i.baseUrl
16
- }), s = {
58
+ }), t = {
17
59
  onRequest: i.onRequest,
18
60
  onResponse: i.onResponse,
19
- onError: i.onError || X
61
+ onError: i.onError || _e
20
62
  };
21
- return a.use(s), a;
22
- }, ee = "/backend/widget/v5/chat/stream", ae = "/backend/widget/v5/chat/{sessionId}/stream", N = (i, a, s) => `${i.replace(/\/$/, "")}${s ? a.replace("{sessionId}", encodeURIComponent(s)) : a}`;
23
- class R {
24
- constructor({ config: a }) {
63
+ return e.use(t), e;
64
+ };
65
+ class ce extends Error {
66
+ constructor() {
67
+ super("This connection request expired. Preparing a new request."), this.name = "ConnectionRequestExpiredError";
68
+ }
69
+ }
70
+ class pe extends Error {
71
+ constructor() {
72
+ super("This connection attempt is no longer available."), this.name = "ConnectionAttemptUnavailableError";
73
+ }
74
+ }
75
+ const de = "/backend/widget/v5/chat/stream", ue = "/backend/widget/v5/chat/{sessionId}/stream", U = (i, e, t) => `${i.replace(/\/$/, "")}${t ? e.replace("{sessionId}", encodeURIComponent(t)) : e}`;
76
+ class B {
77
+ constructor({ config: e }) {
25
78
  var r, l;
26
- this.userToken = null, this.constructClientOptions = (t) => {
27
- const e = this.config.apiUrl || "https://api.open.cx", o = {
79
+ this.userToken = null, this.constructClientOptions = (s) => {
80
+ const a = this.config.apiUrl || "https://api.open.cx", n = {
28
81
  "X-Bot-Token": this.config.token,
29
82
  "Content-Type": "application/json",
30
83
  Accept: "application/json",
31
- Authorization: t ? `Bearer ${t}` : void 0
84
+ Authorization: s ? `Bearer ${s}` : void 0
32
85
  };
33
- return { baseUrl: e, headers: o };
86
+ return { baseUrl: a, headers: n };
34
87
  }, this.createOpenAPIClient = ({
35
- baseUrl: t,
36
- headers: e
37
- }) => Q({
38
- baseUrl: t,
39
- onRequest: ({ request: o }) => {
40
- Object.entries(e).forEach(([_, c]) => {
41
- c && o.headers.set(_, c);
88
+ baseUrl: s,
89
+ headers: a
90
+ }) => le({
91
+ baseUrl: s,
92
+ onRequest: ({ request: n }) => {
93
+ Object.entries(a).forEach(([c, d]) => {
94
+ d && n.headers.set(c, d);
42
95
  });
43
96
  }
44
- }), this.setAuthToken = (t) => {
45
- this.userToken = t;
46
- const { baseUrl: e, headers: o } = this.constructClientOptions(t);
47
- this.client = this.createOpenAPIClient({ baseUrl: e, headers: o });
97
+ }), this.listApprovalPreferences = async () => {
98
+ const { baseUrl: s, headers: a } = this.getStreamAuthContext(), n = await fetch(
99
+ `${s}/backend/widget/v5/connections/approval-preferences`,
100
+ { headers: a }
101
+ );
102
+ if (!n.ok) throw new Error("Could not load permissions.");
103
+ return re.parse(await n.json());
104
+ }, this.revokeApprovalPreference = async (s, a) => {
105
+ const { baseUrl: n, headers: c } = this.getStreamAuthContext();
106
+ if (!(await fetch(
107
+ `${n}/backend/widget/v5/connections/${encodeURIComponent(s)}/approval-preferences/${encodeURIComponent(a)}`,
108
+ { method: "DELETE", headers: c }
109
+ )).ok) throw new Error("Could not reset permission.");
110
+ }, this.listElicitations = async (s, a) => {
111
+ const { baseUrl: n, headers: c } = this.getStreamAuthContext(), d = await fetch(
112
+ `${n}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}`,
113
+ { headers: c, signal: a }
114
+ );
115
+ if (!d.ok) throw new Error("Could not load the request.");
116
+ return ie.parse(await d.json());
117
+ }, this.answerElicitation = async (s, a, n) => {
118
+ const { baseUrl: c, headers: d } = this.getStreamAuthContext(), _ = await fetch(
119
+ `${c}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}/${encodeURIComponent(a)}`,
120
+ {
121
+ method: "POST",
122
+ headers: { ...d, "Content-Type": "application/json" },
123
+ body: JSON.stringify(n)
124
+ }
125
+ );
126
+ if (!_.ok)
127
+ throw new Error(
128
+ _.status === 400 ? "Check your answers and try again." : "This request has ended. Ask the agent to try again."
129
+ );
130
+ }, this.listConnections = async (s) => {
131
+ const { data: a, error: n } = await this.client.GET(
132
+ "/backend/widget/v5/connections",
133
+ { signal: s }
134
+ );
135
+ if (n || !a)
136
+ throw new Error("Could not load connections. Sign in and try again.");
137
+ return a;
138
+ }, this.startConnection = async (s, a, n) => {
139
+ const { data: c, error: d, response: _ } = await this.client.POST(
140
+ "/backend/widget/v5/connections/{serverId}/start",
141
+ {
142
+ params: { path: { serverId: s } },
143
+ body: { request_id: a },
144
+ signal: n
145
+ }
146
+ );
147
+ if (_.status === 410) throw new ce();
148
+ if (_.status === 404)
149
+ throw new Error("This connection request is no longer available.");
150
+ if (d || !c)
151
+ throw new Error("Could not start this connection. Please try again.");
152
+ return c;
153
+ }, this.getConnectionAttempt = async (s, a, n) => {
154
+ const { data: c, error: d, response: _ } = await this.client.GET(
155
+ "/backend/widget/v5/connections/{serverId}/attempts/{attemptId}",
156
+ {
157
+ params: { path: { serverId: s, attemptId: a } },
158
+ signal: n
159
+ }
160
+ );
161
+ if ([401, 403, 404].includes(_.status))
162
+ throw new pe();
163
+ if (d || !c)
164
+ throw new Error(`Could not check the connection (${_.status}).`);
165
+ return c.status;
166
+ }, this.disconnectConnection = async (s) => {
167
+ const { error: a } = await this.client.DELETE(
168
+ "/backend/widget/v5/connections/{serverId}",
169
+ {
170
+ params: { path: { serverId: s } }
171
+ }
172
+ );
173
+ if (a) throw new Error("Could not disconnect. Please try again.");
174
+ }, this.setAuthToken = (s) => {
175
+ this.userToken = s;
176
+ const { baseUrl: a, headers: n } = this.constructClientOptions(s);
177
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: n });
48
178
  }, this.getStreamAuthContext = () => {
49
- const { baseUrl: t, headers: e } = this.constructClientOptions(this.userToken), o = {};
50
- for (const [_, c] of Object.entries(e))
51
- typeof c == "string" && (["content-type", "accept"].includes(_.toLowerCase()) || (o[_] = c));
52
- return { baseUrl: t, headers: o };
179
+ const { baseUrl: s, headers: a } = this.constructClientOptions(this.userToken), n = {};
180
+ for (const [c, d] of Object.entries(a))
181
+ typeof d == "string" && (["content-type", "accept"].includes(c.toLowerCase()) || (n[c] = d));
182
+ return { baseUrl: s, headers: n };
53
183
  }, this.getStreamTransportOptions = () => {
54
- const { baseUrl: t, headers: e } = this.getStreamAuthContext();
184
+ const { baseUrl: s, headers: a } = this.getStreamAuthContext();
55
185
  return {
56
- api: N(t, ee),
57
- reconnectApi: (o) => N(t, ae, o),
58
- headers: e
186
+ api: U(s, de),
187
+ reconnectApi: (n) => U(s, ue, n),
188
+ headers: a
59
189
  };
60
- }, this.stopStream = async (t) => {
61
- const { response: e } = await this.client.POST(
190
+ }, this.stopStream = async (s) => {
191
+ const { response: a } = await this.client.POST(
62
192
  "/backend/widget/v5/chat/{sessionId}/stop",
63
- { params: { path: { sessionId: t } } }
193
+ { params: { path: { sessionId: s } } }
64
194
  );
65
- if (!e.ok)
66
- throw new Error(`Failed to stop stream: ${e.status}`);
67
- }, this.getAgentTurnMessages = async (t) => {
68
- const { data: e, response: o } = await this.client.GET(
195
+ if (!a.ok)
196
+ throw new Error(`Failed to stop stream: ${a.status}`);
197
+ }, this.sendPageReply = async (s, a) => {
198
+ try {
199
+ await this.client.POST("/backend/widget/v5/chat/{sessionId}/page-reply", {
200
+ params: { path: { sessionId: s } },
201
+ body: a
202
+ });
203
+ } catch {
204
+ }
205
+ }, this.getAgentTurnMessages = async (s, a) => {
206
+ const { data: n, response: c } = await this.client.GET(
69
207
  "/backend/widget/v5/chat/{sessionId}/messages",
70
- { params: { path: { sessionId: t } } }
208
+ {
209
+ params: {
210
+ path: { sessionId: s },
211
+ query: {
212
+ toolActivity: a == null ? void 0 : a.toolActivity,
213
+ reasoning: (a == null ? void 0 : a.reasoning) === void 0 ? void 0 : a.reasoning ? "true" : "false"
214
+ }
215
+ }
216
+ }
71
217
  );
72
- return e || (h.warn("agent turn messages fetch failed", o.status), null);
218
+ return n ? {
219
+ ...n,
220
+ handled_connection_request_ids: n.handled_connection_request_ids ?? []
221
+ } : (k.warn("agent turn messages fetch failed", c.status), null);
73
222
  }, this.createDictationSession = async ({
74
- language: t
223
+ language: s
75
224
  }) => {
76
- const { data: e, response: o } = await this.client.POST(
225
+ const { data: a, response: n } = await this.client.POST(
77
226
  "/backend/widget/v5/dictation/sessions",
78
- { body: t ? { language: t } : {} }
227
+ { body: s ? { language: s } : {} }
79
228
  );
80
- if (!e)
81
- throw new Error(`Failed to start dictation: ${o.status}`);
82
- return e;
229
+ if (!a)
230
+ throw new Error(`Failed to start dictation: ${n.status}`);
231
+ return a;
83
232
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
84
233
  params: {
85
234
  header: { "x-bot-token": this.config.token }
86
235
  }
87
- }), this.sendMessage = async (t, e) => await this.client.POST("/backend/widget/v2/chat/send", {
88
- body: t,
89
- signal: e
90
- }), this.createUnverifiedContact = async (t) => await this.client.POST(
236
+ }), this.sendMessage = async (s, a) => await this.client.POST("/backend/widget/v2/chat/send", {
237
+ body: s,
238
+ signal: a
239
+ }), this.createUnverifiedContact = async (s) => await this.client.POST(
91
240
  "/backend/widget/v2/contact/create-unverified",
92
241
  {
93
242
  params: { header: { "x-bot-token": this.config.token } },
94
- body: t
243
+ body: s
95
244
  }
96
- ), this.createSession = async (t) => await this.client.POST("/backend/widget/v2/create-session", {
97
- body: t
245
+ ), this.createSession = async (s, a) => await this.client.POST("/backend/widget/v2/create-session", {
246
+ body: s,
247
+ signal: a
98
248
  }), this.pollSessionAndHistory = async ({
99
- sessionId: t,
100
- abortSignal: e
249
+ sessionId: s,
250
+ abortSignal: a
101
251
  }) => await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
102
- params: { path: { sessionId: t } },
103
- signal: e
252
+ params: { path: { sessionId: s } },
253
+ signal: a
104
254
  }), this.getSessions = async ({
105
- cursor: t,
106
- filters: e,
107
- abortSignal: o
255
+ cursor: s,
256
+ filters: a,
257
+ abortSignal: n
108
258
  }) => await this.client.GET("/backend/widget/v2/sessions", {
109
259
  params: {
110
260
  query: {
111
- offset: t,
112
- filters: JSON.stringify(e)
261
+ offset: s,
262
+ filters: JSON.stringify(a)
113
263
  }
114
264
  },
115
- signal: o
265
+ signal: n
116
266
  }), this.uploadFile = async ({
117
- file: t,
118
- abortSignal: e,
119
- onProgress: o
120
- }) => new Promise((_, c) => {
121
- var y;
122
- const d = new FormData();
123
- d.append("file", t);
267
+ file: s,
268
+ abortSignal: a,
269
+ onProgress: n
270
+ }) => new Promise((c, d) => {
271
+ var f;
272
+ const _ = new FormData();
273
+ _.append("file", s);
124
274
  const p = new XMLHttpRequest();
125
- if (e && (e.addEventListener("abort", () => {
126
- p.abort(), c(new DOMException("Aborted", "AbortError"));
127
- }), e.aborted)) {
128
- c(new DOMException("Aborted", "AbortError"));
275
+ if (a && (a.addEventListener("abort", () => {
276
+ p.abort(), d(new DOMException("Aborted", "AbortError"));
277
+ }), a.aborted)) {
278
+ d(new DOMException("Aborted", "AbortError"));
129
279
  return;
130
280
  }
131
- p.upload.addEventListener("progress", (k) => {
132
- if (k.lengthComputable && o) {
133
- const f = Math.round(k.loaded / k.total * 100);
134
- o(f);
281
+ p.upload.addEventListener("progress", (b) => {
282
+ if (b.lengthComputable && n) {
283
+ const w = Math.round(b.loaded / b.total * 100);
284
+ n(w);
135
285
  }
136
286
  }), p.addEventListener("load", () => {
137
287
  if (p.status >= 200 && p.status < 300)
138
288
  try {
139
- const k = JSON.parse(p.responseText);
140
- _(k);
141
- } catch (k) {
142
- c(new Error(`Failed to parse response: ${k}`));
289
+ const b = JSON.parse(p.responseText);
290
+ c(b);
291
+ } catch (b) {
292
+ d(new Error(`Failed to parse response: ${b}`));
143
293
  }
144
294
  else
145
- c(new Error(`Upload failed with status: ${p.status}`));
295
+ d(new Error(`Upload failed with status: ${p.status}`));
146
296
  }), p.addEventListener("error", () => {
147
- c(new Error("Network error occurred"));
297
+ d(new Error("Network error occurred"));
148
298
  }), p.addEventListener("timeout", () => {
149
- c(new Error("Upload timed out"));
299
+ d(new Error("Upload timed out"));
150
300
  });
151
301
  const { baseUrl: u } = this.constructClientOptions(this.userToken), g = `${u}/backend/widget/v2/upload`;
152
- p.open("POST", g), p.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((y = this.config.user) == null ? void 0 : y.token) ? p.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : h.error("user token not set"), p.send(d);
153
- }), this.vote = async (t) => await this.client.POST("/backend/widget/v2/chat/vote", { body: t }), this.resolveSession = async (t, e) => await this.client.POST("/backend/widget/v2/session/resolve", {
154
- body: t,
155
- signal: e
156
- }), this.createStateCheckpoint = async (t) => await this.client.POST("/backend/widget/v2/checkpoint", {
157
- body: t
158
- }), this.submitCsat = async (t) => await this.client.POST("/backend/widget/v2/submit-csat", { body: t }), this.config = a, this.userToken = ((r = a.user) == null ? void 0 : r.token) || null;
159
- const { baseUrl: s, headers: n } = this.constructClientOptions(
160
- (l = a.user) == null ? void 0 : l.token
302
+ p.open("POST", g), p.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((f = this.config.user) == null ? void 0 : f.token) ? p.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : k.error("user token not set"), p.send(_);
303
+ }), this.vote = async (s) => await this.client.POST("/backend/widget/v2/chat/vote", { body: s }), this.resolveSession = async (s, a) => await this.client.POST("/backend/widget/v2/session/resolve", {
304
+ body: s,
305
+ signal: a
306
+ }), this.createStateCheckpoint = async (s) => await this.client.POST("/backend/widget/v2/checkpoint", {
307
+ body: s
308
+ }), this.submitCsat = async (s) => await this.client.POST("/backend/widget/v2/submit-csat", { body: s }), this.config = e, this.userToken = ((r = e.user) == null ? void 0 : r.token) || null;
309
+ const { baseUrl: t, headers: o } = this.constructClientOptions(
310
+ (l = e.user) == null ? void 0 : l.token
161
311
  );
162
- this.client = this.createOpenAPIClient({ baseUrl: s, headers: n });
312
+ this.client = this.createOpenAPIClient({ baseUrl: t, headers: o });
163
313
  }
164
314
  }
165
- function te(i, a) {
166
- h.error(`missing case for ${i} in ${a}`);
315
+ function me(i, e) {
316
+ k.error(`missing case for ${i} in ${e}`);
167
317
  }
168
- class w {
169
- constructor(a) {
170
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (s) => {
171
- Y(this.state, s) || (this.state = s, this.notifySubscribers(s));
172
- }, this.setPartial = (s) => {
173
- if (s == null) return;
174
- const n = { ...this.state, ...s };
175
- this.set(n);
318
+ class S {
319
+ constructor(e) {
320
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (t) => {
321
+ oe(this.state, t) || (this.state = t, this.notifySubscribers(t));
322
+ }, this.setPartial = (t) => {
323
+ if (t == null) return;
324
+ const o = { ...this.state, ...t };
325
+ this.set(o);
176
326
  }, this.reset = () => {
177
327
  this.set(this.initialState);
178
- }, this.notifySubscribers = (s) => {
328
+ }, this.notifySubscribers = (t) => {
179
329
  Array.from(this.subscribers).forEach((r) => {
180
330
  try {
181
- r(s);
331
+ r(t);
182
332
  } catch (l) {
183
- h.error("state subscriber threw", l);
333
+ k.error("state subscriber threw", l);
184
334
  }
185
335
  });
186
- }, this.subscribe = (s) => (this.subscribers.add(s), () => {
187
- this.subscribers.delete(s);
188
- }), this.state = a, this.initialState = a;
336
+ }, this.subscribe = (t) => (this.subscribers.add(t), () => {
337
+ this.subscribers.delete(t);
338
+ }), this.state = e, this.initialState = e;
189
339
  }
190
340
  }
191
- class B {
341
+ class G {
192
342
  constructor() {
193
- this.state = new w({
343
+ this.state = new S({
194
344
  isPolling: !1,
195
345
  isError: !1
196
346
  }), this.abortController = new AbortController(), this.reset = () => {
197
- var a;
198
- this.abortController.abort("Resetting poller"), (a = this.stopPolling) == null || a.call(this), this.stopPolling = null;
199
- }, this.stopPolling = null, this.startPolling = (a, s) => {
347
+ var e;
348
+ this.abortController.abort("Resetting poller"), (e = this.stopPolling) == null || e.call(this), this.stopPolling = null;
349
+ }, this.stopPolling = null, this.startPolling = (e, t) => {
200
350
  if (this.stopPolling) return;
201
- const n = [], r = async () => {
351
+ const o = [], r = async () => {
202
352
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
203
353
  try {
204
- await a(this.abortController.signal);
354
+ await e(this.abortController.signal);
205
355
  } catch (l) {
206
356
  if (this.abortController.signal.aborted)
207
357
  return;
208
- h.error("failed to poll", l), this.state.setPartial({ isError: !0 });
358
+ k.error("failed to poll", l), this.state.setPartial({ isError: !0 });
209
359
  } finally {
210
360
  this.state.setPartial({ isPolling: !1 });
211
361
  }
212
- this.abortController.signal.aborted || n.push(setTimeout(r, s));
362
+ this.abortController.signal.aborted || o.push(setTimeout(r, t));
213
363
  };
214
364
  r(), this.stopPolling = () => {
215
- n.forEach(clearTimeout), this.state.reset();
365
+ o.forEach(clearTimeout), this.state.reset();
216
366
  };
217
367
  };
218
368
  }
219
369
  }
220
- function V(i) {
370
+ function $(i) {
221
371
  try {
222
- const a = i();
223
- return a instanceof Promise ? a.then((s) => ({ data: s })).catch((s) => ({ error: s })) : { data: a };
224
- } catch (a) {
225
- return { error: a };
372
+ const e = i();
373
+ return e instanceof Promise ? e.then((t) => ({ data: t })).catch((t) => ({ error: t })) : { data: e };
374
+ } catch (e) {
375
+ return { error: e };
226
376
  }
227
377
  }
228
- class se {
378
+ class he {
229
379
  constructor({
230
- api: a,
231
- config: s,
232
- sessionCtx: n,
380
+ api: e,
381
+ config: t,
382
+ sessionCtx: o,
233
383
  messageCtx: r,
234
384
  sessionPollingIntervalSeconds: l
235
385
  }) {
236
- this.poller = new B(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.reconcilingSessionId = null, this.registerPolling = () => {
237
- this.sessionCtx.sessionState.subscribe(({ session: t }) => {
238
- t != null && t.id ? this.poller.startPolling(async (e) => {
239
- this.fetchSessionAndHistory({ sessionId: t.id, abortSignal: e });
240
- }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
241
- }), this.sessionCtx.sessionState.subscribe(({ session: t }) => {
242
- if (t != null && t.id && !t.isOpened)
243
- try {
244
- this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.fetchSessionAndHistory({
245
- sessionId: t.id,
246
- abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
386
+ this.poller = new G(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.subscriptions = [], this.reconcilingSessionId = null, this.registerPolling = () => {
387
+ this.subscriptions.push(
388
+ this.sessionCtx.sessionState.subscribe(({ session: s }) => {
389
+ s != null && s.id ? this.poller.startPolling(async (a) => {
390
+ this.fetchSessionAndHistory({
391
+ sessionId: s.id,
392
+ abortSignal: a
247
393
  });
248
- } catch (e) {
249
- this.fetchSessionAndFullHistoryAbortController.signal.aborted || h.error("failed to fetch session and full history", e);
250
- }
251
- else
252
- this.fetchSessionAndFullHistoryAbortController.abort();
253
- }), this.sessionCtx.sessionState.subscribe(({ session: t }) => {
254
- this.reconcilingSessionId !== null && (t == null ? void 0 : t.id) !== this.reconcilingSessionId && this.reconcileAbortController.abort();
255
- });
256
- }, this.reconcileAfterStream = async (t) => {
394
+ }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
395
+ })
396
+ ), this.subscriptions.push(
397
+ this.sessionCtx.sessionState.subscribe(({ session: s }) => {
398
+ if (s != null && s.id && !s.isOpened)
399
+ try {
400
+ this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.fetchSessionAndHistory({
401
+ sessionId: s.id,
402
+ abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
403
+ });
404
+ } catch (a) {
405
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || k.error("failed to fetch session and full history", a);
406
+ }
407
+ else
408
+ this.fetchSessionAndFullHistoryAbortController.abort();
409
+ })
410
+ ), this.subscriptions.push(
411
+ this.sessionCtx.sessionState.subscribe(({ session: s }) => {
412
+ this.reconcilingSessionId !== null && (s == null ? void 0 : s.id) !== this.reconcilingSessionId && this.reconcileAbortController.abort();
413
+ })
414
+ );
415
+ }, this.dispose = () => {
416
+ this.poller.reset(), this.fetchSessionAndFullHistoryAbortController.abort(), this.reconcileAbortController.abort(), this.reconcilingSessionId = null, this.subscriptions.forEach((s) => s()), this.subscriptions = [];
417
+ }, this.reconcileAfterStream = async (s) => {
257
418
  this.reconcileAbortController.abort(), this.reconcileAbortController = new AbortController();
258
- const { signal: e } = this.reconcileAbortController;
259
- this.reconcilingSessionId = t;
419
+ const { signal: a } = this.reconcileAbortController;
420
+ this.reconcilingSessionId = s;
260
421
  try {
261
- await this.fetchSessionAndHistory({ sessionId: t, abortSignal: e });
262
- } catch (o) {
263
- if (!e.aborted) throw o;
422
+ await this.fetchSessionAndHistory({ sessionId: s, abortSignal: a });
423
+ } catch (n) {
424
+ if (!a.aborted) throw n;
264
425
  } finally {
265
- this.reconcilingSessionId === t && (this.reconcilingSessionId = null);
426
+ this.reconcilingSessionId === s && (this.reconcilingSessionId = null);
266
427
  }
267
428
  }, this.fetchSessionAndHistory = async ({
268
- sessionId: t,
269
- abortSignal: e
429
+ sessionId: s,
430
+ abortSignal: a
270
431
  }) => {
271
- const o = this.messageCtx.state.get().messages.length === 0;
272
- o && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
273
- const { data: _ } = await this.api.pollSessionAndHistory({
274
- sessionId: t,
275
- abortSignal: e
432
+ const n = this.messageCtx.state.get().messages.length === 0;
433
+ n && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
434
+ const { data: c } = await this.api.pollSessionAndHistory({
435
+ sessionId: s,
436
+ abortSignal: a
276
437
  });
277
- if (_ != null && _.session && (this.sessionCtx.sessionState.setPartial({ session: _.session }), this.sessionCtx.setSessions([_.session])), _ != null && _.history && _.history.length > 0) {
278
- const c = this.messageCtx.state.get().messages, d = _.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
279
- (p) => !c.some((u) => u.id === p.id)
438
+ if (c != null && c.session && (this.sessionCtx.sessionState.setPartial({ session: c.session }), this.sessionCtx.setSessions([c.session])), c != null && c.history && c.history.length > 0) {
439
+ const d = this.messageCtx.state.get().messages, _ = c.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
440
+ (p) => !d.some((u) => u.id === p.id)
280
441
  );
281
- if (d.length > 0)
442
+ if (_.length > 0)
282
443
  if (this.messageCtx.state.setPartial({
283
- messages: [...c, ...d]
284
- }), o)
444
+ messages: [...d, ..._]
445
+ }), n)
285
446
  this.messageCtx.markAsDispatchedToOnMessageReceivedHook(
286
- d.map((p) => p.id)
447
+ _.map((p) => p.id)
287
448
  );
288
449
  else
289
- for (const p of d)
450
+ for (const p of _)
290
451
  this.messageCtx.dispatchToOnMessageReceivedHook(p);
291
452
  }
292
453
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
293
- }, this.mapHistoryToMessage = (t) => {
294
- var o;
295
- const e = {
296
- id: t.publicId,
297
- timestamp: t.sentAt || "",
298
- attachments: t.attachments || void 0
454
+ }, this.mapHistoryToMessage = (s) => {
455
+ var n;
456
+ const a = {
457
+ id: s.publicId,
458
+ timestamp: s.sentAt || "",
459
+ attachments: s.attachments || void 0
299
460
  };
300
- if (t.sender.kind === "user")
461
+ if (s.sender.kind === "user")
301
462
  return {
302
- ...e,
463
+ ...a,
303
464
  type: "USER",
304
- content: t.content.text || "",
465
+ content: s.content.text || "",
305
466
  // Backend field name (schema.ts) → widget vocabulary.
306
- markedElements: t.pickedElements
467
+ markedElements: s.pickedElements
307
468
  };
308
- if (t.sender.kind === "agent")
469
+ if (s.sender.kind === "agent")
309
470
  return {
310
- ...e,
471
+ ...a,
311
472
  type: "AGENT",
312
473
  component: "agent_message",
313
474
  data: {
314
- message: t.content.text || ""
475
+ message: s.content.text || ""
315
476
  },
316
477
  agent: {
317
- name: t.sender.name || "",
478
+ name: s.sender.name || "",
318
479
  // Do not set avatarUrl from config here... let it be taken from the config at render time
319
480
  // Only set avatar url from the backend's response
320
- avatarUrl: t.sender.avatar || null,
321
- avatar: t.sender.avatar || null,
481
+ avatarUrl: s.sender.avatar || null,
482
+ avatar: s.sender.avatar || null,
322
483
  id: null,
323
484
  isAi: !1
324
- }
485
+ },
486
+ ...this.constructReplyTo(s)
325
487
  };
326
- if (t.sender.kind === "ai") {
327
- const _ = t.actionCalls && t.actionCalls.length > 0 ? t.actionCalls[t.actionCalls.length - 1] : void 0;
488
+ if (s.sender.kind === "ai") {
489
+ const c = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
328
490
  return {
329
- ...e,
491
+ ...a,
330
492
  type: "AI",
331
493
  component: "bot_message",
332
494
  agent: {
333
495
  id: null,
334
- name: ((o = this.config.bot) == null ? void 0 : o.name) || "",
496
+ name: ((n = this.config.bot) == null ? void 0 : n.name) || "",
335
497
  isAi: !0,
336
498
  // Do not set avatarUrl from config here... let it be taken from the config at render time
337
499
  avatarUrl: null,
338
500
  avatar: null
339
501
  },
340
502
  data: {
341
- message: t.content.text || "",
342
- action: _ ? {
343
- name: _.actionName,
344
- data: this.extractActionResult(_)
503
+ message: s.content.text || "",
504
+ action: c ? {
505
+ name: c.actionName,
506
+ data: this.extractActionResult(c)
345
507
  } : void 0
346
- }
508
+ },
509
+ ...this.constructReplyTo(s)
347
510
  };
348
511
  }
349
- if (t.sender.kind === "system") {
350
- const _ = this.constructSystemMessage(t);
351
- return _ === null ? null : { ..._ };
512
+ if (s.sender.kind === "system") {
513
+ const c = this.constructSystemMessage(s);
514
+ return c === null ? null : { ...c };
352
515
  }
353
516
  return null;
354
- }, this.constructSystemMessage = (t) => {
355
- if (!t || !t.systemMessagePayload) return null;
356
- switch (t.systemMessagePayload.type) {
517
+ }, this.constructReplyTo = (s) => {
518
+ if (!s.replyTo) return {};
519
+ const { publicId: a, text: n, sender: c } = s.replyTo;
520
+ return {
521
+ replyTo: {
522
+ id: a,
523
+ text: n,
524
+ sender: c
525
+ }
526
+ };
527
+ }, this.constructSystemMessage = (s) => {
528
+ if (!s || !s.systemMessagePayload) return null;
529
+ switch (s.systemMessagePayload.type) {
357
530
  case "state_checkpoint":
358
531
  return {
359
- id: t.publicId,
532
+ id: s.publicId,
360
533
  type: "SYSTEM",
361
534
  subtype: "state_checkpoint",
362
- data: { payload: t.systemMessagePayload.payload },
363
- timestamp: t.sentAt || "",
535
+ data: { payload: s.systemMessagePayload.payload },
536
+ timestamp: s.sentAt || "",
364
537
  attachments: void 0
365
538
  };
366
539
  case "csat_requested":
367
540
  return {
368
- id: t.publicId,
541
+ id: s.publicId,
369
542
  type: "SYSTEM",
370
543
  subtype: "csat_requested",
371
544
  data: { payload: void 0 },
372
- timestamp: t.sentAt || "",
545
+ timestamp: s.sentAt || "",
373
546
  attachments: void 0
374
547
  };
375
548
  case "csat_submitted":
376
549
  return {
377
- id: t.publicId,
550
+ id: s.publicId,
378
551
  type: "SYSTEM",
379
552
  subtype: "csat_submitted",
380
553
  data: {
381
554
  payload: {
382
- score: t.systemMessagePayload.payload.score ?? void 0,
383
- feedback: t.systemMessagePayload.payload.feedback ?? void 0
555
+ score: s.systemMessagePayload.payload.score ?? void 0,
556
+ feedback: s.systemMessagePayload.payload.feedback ?? void 0
384
557
  }
385
558
  },
386
- timestamp: t.sentAt || "",
559
+ timestamp: s.sentAt || "",
387
560
  attachments: void 0
388
561
  };
389
562
  case "none":
390
563
  return null;
391
564
  default:
392
- return te(
393
- t.systemMessagePayload,
565
+ return me(
566
+ s.systemMessagePayload,
394
567
  this.constructSystemMessage.name
395
568
  ), null;
396
569
  }
397
- }, this.extractActionResult = (t) => {
398
- const e = t.result;
399
- if (e === null || typeof e != "object") return e;
400
- if ("responseBodyText" in e && typeof e.responseBodyText == "string") {
401
- const o = e.responseBodyText, _ = V(() => JSON.parse(o)).data;
402
- if (_) return _;
570
+ }, this.extractActionResult = (s) => {
571
+ const a = s.result;
572
+ if (a === null || typeof a != "object") return a;
573
+ if ("responseBodyText" in a && typeof a.responseBodyText == "string") {
574
+ const n = a.responseBodyText, c = $(() => JSON.parse(n)).data;
575
+ if (c) return c;
403
576
  }
404
- return t.result;
405
- }, this.api = a, this.config = s, this.sessionCtx = n, this.messageCtx = r, this.sessionPollingIntervalSeconds = l, this.registerPolling();
577
+ return s.result;
578
+ }, this.api = e, this.config = t, this.sessionCtx = o, this.messageCtx = r, this.sessionPollingIntervalSeconds = l, this.registerPolling();
406
579
  }
407
580
  }
408
- class ne {
581
+ class ge {
409
582
  constructor({
410
- config: a,
411
- api: s,
412
- storageCtx: n
583
+ config: e,
584
+ api: t,
585
+ storageCtx: o
413
586
  }) {
414
587
  var r;
415
588
  this.shouldCollectData = () => {
416
589
  var l;
417
590
  return !!(!((l = this.state.get().contact) != null && l.token) && this.config.collectUserData);
418
591
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
419
- var l, t, e, o, _, c, d, p, u, m, g, j, y, k;
592
+ var l, s, a, n, c, d, _, p, u, m, g, v, f, b;
420
593
  if (!((l = this.config.user) != null && l.token)) {
421
- if (this.config.collectUserData && !((e = (t = this.config.user) == null ? void 0 : t.data) != null && e.email)) {
422
- if ((o = this.config.extraDataCollectionFields) != null && o.length)
594
+ if (this.config.collectUserData && !((a = (s = this.config.user) == null ? void 0 : s.data) != null && a.email)) {
595
+ if ((n = this.config.extraDataCollectionFields) != null && n.length)
423
596
  return;
424
- const f = await ((_ = this.storageCtx) == null ? void 0 : _.getContactToken());
425
- f && await this.setUnverifiedContact(f);
597
+ const w = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
598
+ w && await this.setUnverifiedContact(w);
426
599
  return;
427
600
  }
428
- if (!((d = (c = this.config.user) == null ? void 0 : c.data) != null && d.email)) {
429
- const f = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
430
- if (f) {
431
- await this.setUnverifiedContact(f);
601
+ if (!((_ = (d = this.config.user) == null ? void 0 : d.data) != null && _.email)) {
602
+ const w = await ((p = this.storageCtx) == null ? void 0 : p.getContactToken());
603
+ if (w) {
604
+ await this.setUnverifiedContact(w);
432
605
  return;
433
606
  }
434
607
  }
435
608
  await this.createUnverifiedContact({
436
609
  email: (m = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : m.email,
437
- non_verified_name: (j = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : j.name,
438
- non_verified_custom_data: (k = (y = this.config.user) == null ? void 0 : y.data) == null ? void 0 : k.customData
610
+ non_verified_name: (v = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : v.name,
611
+ non_verified_custom_data: (b = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : b.customData
439
612
  });
440
613
  }
441
- }, this.createUnverifiedContact = async (l, t) => {
442
- this.state.setPartial({ extraCollectedData: t });
614
+ }, this.createUnverifiedContact = async (l, s) => {
615
+ this.state.setPartial({ extraCollectedData: s });
443
616
  try {
444
617
  this.state.setPartial({
445
618
  isCreatingUnverifiedContact: !0,
446
619
  isErrorCreatingUnverifiedContact: !1
447
620
  });
448
- const { data: e } = await this.api.createUnverifiedContact(l);
449
- e != null && e.token ? await this.setUnverifiedContact(e.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
450
- } catch (e) {
451
- this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), h.error("failed to create an unverified contact", {
452
- _e: e instanceof Error ? e.message : String(e)
621
+ const { data: a } = await this.api.createUnverifiedContact(l);
622
+ a != null && a.token ? await this.setUnverifiedContact(a.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
623
+ } catch (a) {
624
+ this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), k.error("failed to create an unverified contact", {
625
+ _e: a instanceof Error ? a.message : String(a)
453
626
  });
454
627
  } finally {
455
628
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
456
629
  }
457
630
  }, this.recoverFromStaleToken = async () => {
458
- var l, t, e, o, _, c, d, p, u, m;
631
+ var l, s, a, n, c, d, _, p, u, m;
459
632
  if ((l = this.config.user) != null && l.token) return !1;
460
633
  this.api.setAuthToken(""), this.state.setPartial({ contact: null });
461
634
  try {
462
- await ((t = this.storageCtx) == null ? void 0 : t.clearContactToken()), await ((e = this.storageCtx) == null ? void 0 : e.clearActiveSessionId());
635
+ await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((a = this.storageCtx) == null ? void 0 : a.clearActiveSessionId());
463
636
  } catch (g) {
464
- h.warn("failed to clear a stale contact token", {
637
+ k.warn("failed to clear a stale contact token", {
465
638
  error: g instanceof Error ? g.message : String(g)
466
639
  });
467
640
  }
468
641
  return await this.createUnverifiedContact({
469
- email: (_ = (o = this.config.user) == null ? void 0 : o.data) == null ? void 0 : _.email,
470
- non_verified_name: (d = (c = this.config.user) == null ? void 0 : c.data) == null ? void 0 : d.name,
642
+ email: (c = (n = this.config.user) == null ? void 0 : n.data) == null ? void 0 : c.email,
643
+ non_verified_name: (_ = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : _.name,
471
644
  non_verified_custom_data: (u = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : u.customData
472
645
  }), !!((m = this.state.get().contact) != null && m.token);
473
646
  }, this.setUnverifiedContact = async (l) => {
474
- var o, _, c, d;
475
- const t = await ((o = this.storageCtx) == null ? void 0 : o.getExternalContactId()), e = ((_ = this.config.user) == null ? void 0 : _.externalId) || t || U();
476
- this.api.setAuthToken(l), await ((c = this.storageCtx) == null ? void 0 : c.setContactToken(l)), await ((d = this.storageCtx) == null ? void 0 : d.setExternalContactId(e)), this.state.setPartial({ contact: { token: l, externalId: e } });
477
- }, this.config = a, this.storageCtx = n, this.api = s, this.state = new w({
478
- contact: (r = a.user) != null && r.token ? {
479
- token: a.user.token,
647
+ var n, c, d, _;
648
+ const s = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), a = ((c = this.config.user) == null ? void 0 : c.externalId) || s || N();
649
+ this.api.setAuthToken(l), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(l)), await ((_ = this.storageCtx) == null ? void 0 : _.setExternalContactId(a)), this.state.setPartial({ contact: { token: l, externalId: a } });
650
+ }, this.config = e, this.storageCtx = o, this.api = t, this.state = new S({
651
+ contact: (r = e.user) != null && r.token ? {
652
+ token: e.user.token,
480
653
  // Set optional externalId from config... not local storage
481
- externalId: a.user.externalId
654
+ externalId: e.user.externalId
482
655
  } : null,
483
656
  extraCollectedData: void 0,
484
657
  isCreatingUnverifiedContact: !1,
@@ -486,26 +659,75 @@ class ne {
486
659
  }), this.autoCreateUnverifiedUserIfNotExists();
487
660
  }
488
661
  }
662
+ class ke {
663
+ constructor(e) {
664
+ this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (t) => {
665
+ const o = t.map(
666
+ (r) => ({
667
+ file: r,
668
+ id: N(),
669
+ status: "pending",
670
+ progress: 0
671
+ })
672
+ );
673
+ this.state.set([...this.state.get(), ...o]), o.forEach((r) => void this.upload(r));
674
+ }, this.cancel = (t) => {
675
+ var o;
676
+ (o = this.controllers.get(t)) == null || o.abort(), this.controllers.delete(t), this.state.set(this.state.get().filter((r) => r.id !== t));
677
+ }, this.reset = () => {
678
+ this.controllers.forEach((t) => t.abort()), this.controllers.clear(), this.state.reset();
679
+ };
680
+ }
681
+ update(e, t) {
682
+ this.state.set(
683
+ this.state.get().map((o) => o.id === e ? { ...o, ...t } : o)
684
+ );
685
+ }
686
+ async upload(e) {
687
+ const t = new AbortController();
688
+ this.controllers.set(e.id, t), this.update(e.id, { status: "uploading" });
689
+ try {
690
+ const o = await this.api.uploadFile({
691
+ file: e.file,
692
+ abortSignal: t.signal,
693
+ onProgress: (r) => this.update(e.id, { progress: r })
694
+ });
695
+ this.update(e.id, {
696
+ status: "success",
697
+ fileUrl: o.fileUrl,
698
+ progress: 100
699
+ });
700
+ } catch (o) {
701
+ t.signal.aborted || this.update(e.id, {
702
+ status: "error",
703
+ progress: 0,
704
+ error: o instanceof Error ? o.message : "Upload failed"
705
+ });
706
+ } finally {
707
+ this.controllers.delete(e.id);
708
+ }
709
+ }
710
+ }
489
711
  function x() {
490
- return U();
712
+ return N();
491
713
  }
492
- class oe {
714
+ class be {
493
715
  constructor({
494
- api: a,
495
- sessionCtx: s,
496
- messageCtx: n
716
+ api: e,
717
+ sessionCtx: t,
718
+ messageCtx: o
497
719
  }) {
498
720
  this.submitCsat = async (r) => {
499
- var _;
500
- const l = (_ = this.sessionCtx.sessionState.get().session) == null ? void 0 : _.id;
721
+ var c;
722
+ const l = (c = this.sessionCtx.sessionState.get().session) == null ? void 0 : c.id;
501
723
  if (!l)
502
724
  return { data: null, error: "No session id found" };
503
- const t = x();
725
+ const s = x();
504
726
  this.messageCtx.state.setPartial({
505
727
  messages: [
506
728
  ...this.messageCtx.state.get().messages,
507
729
  {
508
- id: t,
730
+ id: s,
509
731
  type: "SYSTEM",
510
732
  subtype: "csat_submitted",
511
733
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -518,16 +740,16 @@ class oe {
518
740
  }
519
741
  ]
520
742
  });
521
- const { data: e, error: o } = await this.api.submitCsat({
743
+ const { data: a, error: n } = await this.api.submitCsat({
522
744
  ...r,
523
- system_message_uuid: t,
745
+ system_message_uuid: s,
524
746
  session_id: l
525
747
  });
526
- return { data: e, error: o };
527
- }, this.api = a, this.sessionCtx = s, this.messageCtx = n;
748
+ return { data: a, error: n };
749
+ }, this.api = e, this.sessionCtx = t, this.messageCtx = o;
528
750
  }
529
751
  }
530
- const ie = [
752
+ const ve = [
531
753
  {
532
754
  action: "newparagraph",
533
755
  phrases: {
@@ -602,7 +824,7 @@ const ie = [
602
824
  it: ["invia messaggio"]
603
825
  }
604
826
  }
605
- ], re = [
827
+ ], fe = [
606
828
  "en",
607
829
  "es",
608
830
  "fr",
@@ -610,104 +832,104 @@ const ie = [
610
832
  "pt",
611
833
  "it"
612
834
  ];
613
- function _e(i) {
614
- return re.includes(i);
835
+ function ye(i) {
836
+ return fe.includes(i);
615
837
  }
616
- function le(i) {
838
+ function we(i) {
617
839
  return i.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
618
840
  }
619
- function ce(i) {
620
- const a = ie.flatMap(
841
+ function je(i) {
842
+ const e = ve.flatMap(
621
843
  (r) => i.flatMap(
622
- (l) => r.phrases[l].map((t) => ({ phrase: t, action: r.action }))
844
+ (l) => r.phrases[l].map((s) => ({ phrase: s, action: r.action }))
623
845
  )
624
- ), s = a.map((r) => le(r.phrase)).sort((r, l) => l.length - r.length).join("|"), n = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
846
+ ), t = e.map((r) => we(r.phrase)).sort((r, l) => l.length - r.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
625
847
  return {
626
848
  regex: new RegExp(
627
- `${n}(${s})` + String.raw`([.,!?;:])(?=\s|$)`,
849
+ `${o}(${t})` + String.raw`([.,!?;:])(?=\s|$)`,
628
850
  "giu"
629
851
  ),
630
852
  finalRegex: new RegExp(
631
- `${n}(${s})` + String.raw`([.,!?;:]?)(?=\s|$)`,
853
+ `${o}(${t})` + String.raw`([.,!?;:]?)(?=\s|$)`,
632
854
  "giu"
633
855
  ),
634
856
  phraseToAction: new Map(
635
- a.map((r) => [r.phrase.toLowerCase(), r.action])
857
+ e.map((r) => [r.phrase.toLowerCase(), r.action])
636
858
  ),
637
- longestPhrase: Math.max(...a.map((r) => r.phrase.length))
859
+ longestPhrase: Math.max(...e.map((r) => r.phrase.length))
638
860
  };
639
861
  }
640
- const K = /* @__PURE__ */ new Map();
641
- function T(i) {
642
- const a = i && _e(i) && i !== "en" ? i : null, s = a ?? "en";
643
- let n = K.get(s);
644
- return n || (n = ce(a ? ["en", a] : ["en"]), K.set(s, n)), n;
862
+ const V = /* @__PURE__ */ new Map();
863
+ function I(i) {
864
+ const e = i && ye(i) && i !== "en" ? i : null, t = e ?? "en";
865
+ let o = V.get(t);
866
+ return o || (o = je(e ? ["en", e] : ["en"]), V.set(t, o)), o;
645
867
  }
646
- function pe(i) {
647
- const a = i.replace(/\s+$/, "");
648
- if (!a) return "";
649
- const s = a.replace(/[.!?]+$/, "");
650
- let n = -1;
651
- for (let r = s.length - 1; r >= 0; r--) {
652
- const l = s[r];
868
+ function Se(i) {
869
+ const e = i.replace(/\s+$/, "");
870
+ if (!e) return "";
871
+ const t = e.replace(/[.!?]+$/, "");
872
+ let o = -1;
873
+ for (let r = t.length - 1; r >= 0; r--) {
874
+ const l = t[r];
653
875
  if (l === "." || l === "!" || l === "?" || l === `
654
876
  `) {
655
- n = r + 1;
877
+ o = r + 1;
656
878
  break;
657
879
  }
658
880
  }
659
- return n === -1 ? "" : `${s.slice(0, n)} `.replace(/\n $/, `
881
+ return o === -1 ? "" : `${t.slice(0, o)} `.replace(/\n $/, `
660
882
  `);
661
883
  }
662
- const de = new RegExp(
884
+ const ze = new RegExp(
663
885
  String.raw`(^- |\n(?:- )?)(\p{Ll})`,
664
886
  "gu"
665
887
  );
666
- function me(i) {
888
+ function Ce(i) {
667
889
  return i.replace(
668
- de,
669
- (a, s, n) => s + n.toUpperCase()
890
+ ze,
891
+ (e, t, o) => t + o.toUpperCase()
670
892
  );
671
893
  }
672
- function ue(i) {
894
+ function xe(i) {
673
895
  return i.length <= 3 && /^\s*$/.test(i) ? !0 : /[.!?\n]\s{0,3}$/.test(i.slice(-6));
674
896
  }
675
- class C {
897
+ class q {
676
898
  /**
677
899
  * Process the full raw transcript accumulated so far into insertable text.
678
900
  * Pure and deterministic: always called with the entire raw string so the
679
901
  * result never depends on delta chunking.
680
902
  */
681
- static process(a, s) {
682
- const n = T(s == null ? void 0 : s.language), r = s != null && s.final ? "" : C.commandPrefixTail(a, s == null ? void 0 : s.language), l = a.slice(0, a.length - r.length), t = s != null && s.final ? n.finalRegex : n.regex;
683
- let e = "", o = null, _ = 0;
684
- for (const d of Array.from(l.matchAll(t))) {
685
- const [, p = ""] = d, u = n.phraseToAction.get(p.toLowerCase());
903
+ static process(e, t) {
904
+ const o = I(t == null ? void 0 : t.language), r = t != null && t.final ? "" : q.commandPrefixTail(e, t == null ? void 0 : t.language), l = e.slice(0, e.length - r.length), s = t != null && t.final ? o.finalRegex : o.regex;
905
+ let a = "", n = null, c = 0;
906
+ for (const _ of Array.from(l.matchAll(s))) {
907
+ const [, p = ""] = _, u = o.phraseToAction.get(p.toLowerCase());
686
908
  if (u)
687
- if (e += l.slice(_, d.index), _ = d.index + d[0].length, u === "newline") e = `${e.replace(/[ \t]+$/, "")}
909
+ if (a += l.slice(c, _.index), c = _.index + _[0].length, u === "newline") a = `${a.replace(/[ \t]+$/, "")}
688
910
  `;
689
911
  else if (u === "newparagraph")
690
- e = `${e.replace(/[ \t]+$/, "")}
912
+ a = `${a.replace(/[ \t]+$/, "")}
691
913
 
692
914
  `;
693
915
  else if (u === "bullet") {
694
- const m = e.replace(/[ \t]+$/, "");
695
- e = m === "" || m.endsWith(`
916
+ const m = a.replace(/[ \t]+$/, "");
917
+ a = m === "" || m.endsWith(`
696
918
  `) ? `${m}- ` : `${m}
697
919
  - `;
698
- } else if (u === "scratch") e = pe(e);
920
+ } else if (u === "scratch") a = Se(a);
699
921
  else {
700
- o = u === "send" ? "send" : "stop";
922
+ n = u === "send" ? "send" : "stop";
701
923
  break;
702
924
  }
703
925
  }
704
- return o === null && (e += l.slice(_)), { text: me(
705
- e.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
926
+ return n === null && (a += l.slice(c)), { text: Ce(
927
+ a.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
706
928
  `).replace(/\n[ \t]+/g, `
707
929
  `).replace(/(^|\n)- +/g, "$1- ").replace(/ {2,}/g, " ").replace(/\n{3,}/g, `
708
930
 
709
931
  `)
710
- ), pendingTail: r, control: o };
932
+ ), pendingTail: r, control: n };
711
933
  }
712
934
  /**
713
935
  * Longest suffix of `raw` that could still become a command — a proper
@@ -718,16 +940,16 @@ class C {
718
940
  * control command from an intermediate delta would stop or submit
719
941
  * mid-sentence.
720
942
  */
721
- static commandPrefixTail(a, s) {
722
- const n = T(s), r = Math.min(a.length, n.longestPhrase + 2);
943
+ static commandPrefixTail(e, t) {
944
+ const o = I(t), r = Math.min(e.length, o.longestPhrase + 2);
723
945
  for (let l = r; l > 0; l--) {
724
- const t = a.length - l;
725
- if (!ue(a.slice(0, t))) continue;
726
- const e = a.slice(t).toLowerCase(), o = e.replace(/^\s+/, "");
727
- if (o) {
728
- for (const _ of Array.from(n.phraseToAction.keys()))
729
- if (_.startsWith(o))
730
- return a.slice(t + (e.length - o.length));
946
+ const s = e.length - l;
947
+ if (!xe(e.slice(0, s))) continue;
948
+ const a = e.slice(s).toLowerCase(), n = a.replace(/^\s+/, "");
949
+ if (n) {
950
+ for (const c of Array.from(o.phraseToAction.keys()))
951
+ if (c.startsWith(n))
952
+ return e.slice(s + (a.length - n.length));
731
953
  }
732
954
  }
733
955
  return "";
@@ -737,13 +959,13 @@ class C {
737
959
  * prefix) — i.e. a silence pause would resolve it into a command. Used by
738
960
  * the manager's silence timer.
739
961
  */
740
- static pendingTailIsCompletePhrase(a, s) {
741
- const n = C.commandPrefixTail(a, s).trim().toLowerCase();
742
- return n ? T(s).phraseToAction.has(n) : !1;
962
+ static pendingTailIsCompletePhrase(e, t) {
963
+ const o = q.commandPrefixTail(e, t).trim().toLowerCase();
964
+ return o ? I(t).phraseToAction.has(o) : !1;
743
965
  }
744
966
  }
745
- const he = 55, ge = 90;
746
- class L {
967
+ const qe = 55, Ee = 90;
968
+ class H {
747
969
  /**
748
970
  * Next paced step toward `processed`: normally one word per tick so text
749
971
  * flows evenly instead of landing in bursty chunks; proportionally larger
@@ -751,45 +973,45 @@ class L {
751
973
  * `displayed` (callers reconcile immediately otherwise).
752
974
  */
753
975
  static nextDripText({
754
- displayed: a,
755
- processed: s
976
+ displayed: e,
977
+ processed: t
756
978
  }) {
757
- if (s.length <= a.length) return s;
758
- const n = s.length - a.length;
759
- if (n > ge)
760
- return s.slice(0, a.length + Math.ceil(n / 3));
761
- let r = a.length;
762
- for (; r < s.length && /\s/.test(s.charAt(r)); ) r++;
763
- for (; r < s.length && !/\s/.test(s.charAt(r)); ) r++;
764
- return r - a.length > 12 && (r = a.length + 6), s.slice(0, Math.max(r, a.length + 1));
979
+ if (t.length <= e.length) return t;
980
+ const o = t.length - e.length;
981
+ if (o > Ee)
982
+ return t.slice(0, e.length + Math.ceil(o / 3));
983
+ let r = e.length;
984
+ for (; r < t.length && /\s/.test(t.charAt(r)); ) r++;
985
+ for (; r < t.length && !/\s/.test(t.charAt(r)); ) r++;
986
+ return r - e.length > 12 && (r = e.length + 6), t.slice(0, Math.max(r, e.length + 1));
765
987
  }
766
988
  /** Normalize a BCP-47 browser locale into the hint OpenAI accepts. */
767
- static languageHint(a) {
768
- if (!a) return;
769
- const s = a.toLowerCase();
770
- if (/^zh-(cn|tw|hk)$/.test(s)) return s;
771
- const n = s.split("-")[0];
772
- return n && /^[a-z]{2,3}$/.test(n) ? n : void 0;
989
+ static languageHint(e) {
990
+ if (!e) return;
991
+ const t = e.toLowerCase();
992
+ if (/^zh-(cn|tw|hk)$/.test(t)) return t;
993
+ const o = t.split("-")[0];
994
+ return o && /^[a-z]{2,3}$/.test(o) ? o : void 0;
773
995
  }
774
996
  }
775
- const ke = 2e4;
776
- class be {
997
+ const Ae = 2e4;
998
+ class Pe {
777
999
  constructor() {
778
1000
  this.cached = null, this.inflight = null;
779
1001
  }
780
1002
  /** Valid cached mint, or null. */
781
1003
  get() {
782
1004
  if (!this.cached) return null;
783
- const a = Date.parse(this.cached.expiresAt);
784
- return Number.isNaN(a) || a - Date.now() < ke ? (this.cached = null, null) : this.cached;
1005
+ const e = Date.parse(this.cached.expiresAt);
1006
+ return Number.isNaN(e) || e - Date.now() < Ae ? (this.cached = null, null) : this.cached;
785
1007
  }
786
1008
  /**
787
1009
  * Resolve a mint, deduping concurrent requests (hover-prewarm racing a
788
1010
  * click reuses the same in-flight promise instead of double-minting).
789
1011
  */
790
- async resolve(a) {
791
- const s = this.get();
792
- return s || (this.inflight || (this.inflight = a().then((n) => (this.cached = n, n)).finally(() => {
1012
+ async resolve(e) {
1013
+ const t = this.get();
1014
+ return t || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
793
1015
  this.inflight = null;
794
1016
  })), this.inflight);
795
1017
  }
@@ -798,60 +1020,60 @@ class be {
798
1020
  this.cached = null;
799
1021
  }
800
1022
  }
801
- function F(i) {
1023
+ function Z(i) {
802
1024
  return typeof i == "object" && i !== null && !Array.isArray(i);
803
1025
  }
804
- function fe(i) {
805
- if (!F(i) || typeof i.type != "string") return null;
806
- const a = F(i.error) ? i.error : null;
1026
+ function Te(i) {
1027
+ if (!Z(i) || typeof i.type != "string") return null;
1028
+ const e = Z(i.error) ? i.error : null;
807
1029
  return {
808
1030
  type: i.type,
809
1031
  delta: typeof i.delta == "string" ? i.delta : void 0,
810
- errorMessage: a && typeof a.message == "string" ? a.message : void 0
1032
+ errorMessage: e && typeof e.message == "string" ? e.message : void 0
811
1033
  };
812
1034
  }
813
- const ve = "https://api.openai.com/v1/realtime/calls", ye = 10 * 60 * 1e3, we = 15e3, je = 5e3;
814
- class E extends Error {
1035
+ const Ie = "https://api.openai.com/v1/realtime/calls", Me = 600 * 1e3, De = 15e3, Ne = 5e3;
1036
+ class P extends Error {
815
1037
  }
816
- class Se {
1038
+ class Re {
817
1039
  constructor({
818
- mintToken: a,
819
- onDelta: s,
820
- onState: n,
1040
+ mintToken: e,
1041
+ onDelta: t,
1042
+ onState: o,
821
1043
  onError: r,
822
1044
  onLevel: l
823
1045
  }) {
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 = a, this.onDelta = s, this.onState = n, this.onError = r, this.onLevel = l;
1046
+ this.state = "idle", this.pc = null, this.dc = null, this.stream = null, this.audioContext = null, this.levelRaf = 0, this.timers = [], this.loggedParseFailure = !1, this.mintToken = e, this.onDelta = t, this.onState = o, this.onError = r, this.onLevel = l;
825
1047
  }
826
1048
  async start() {
827
1049
  if (this.state === "idle") {
828
1050
  this.setState("connecting"), this.timers.push(
829
1051
  setTimeout(() => {
830
1052
  this.state === "connecting" && this.fail("unavailable");
831
- }, we)
832
- ), this.timers.push(setTimeout(() => this.stop(), ye));
1053
+ }, De)
1054
+ ), this.timers.push(setTimeout(() => this.stop(), Me));
833
1055
  try {
834
- const a = this.requestMicrophone();
835
- a.then((c) => {
836
- (this.isTornDown() || this.stream && this.stream !== c) && c.getTracks().forEach((d) => d.stop());
1056
+ const e = this.requestMicrophone();
1057
+ e.then((d) => {
1058
+ (this.isTornDown() || this.stream && this.stream !== d) && d.getTracks().forEach((_) => _.stop());
837
1059
  }).catch(() => {
838
1060
  });
839
- const [s, n] = await Promise.all([a, this.mintToken()]);
1061
+ const [t, o] = await Promise.all([e, this.mintToken()]);
840
1062
  if (this.isTornDown()) {
841
- s.getTracks().forEach((c) => c.stop());
1063
+ t.getTracks().forEach((d) => d.stop());
842
1064
  return;
843
1065
  }
844
- this.stream = s, this.startLevelMeter(s);
1066
+ this.stream = t, this.startLevelMeter(t);
845
1067
  const r = new RTCPeerConnection();
846
1068
  this.pc = r;
847
- const [l] = s.getAudioTracks();
848
- if (!l) throw new E("No audio track");
849
- r.addTrack(l, s);
850
- const t = r.createDataChannel("oai-events");
851
- this.dc = t, t.addEventListener(
1069
+ const [l] = t.getAudioTracks();
1070
+ if (!l) throw new P("No audio track");
1071
+ r.addTrack(l, t);
1072
+ const s = r.createDataChannel("oai-events");
1073
+ this.dc = s, s.addEventListener(
852
1074
  "message",
853
- (c) => this.handleServerEvent(c.data)
854
- ), t.addEventListener("open", () => {
1075
+ (d) => this.handleServerEvent(d.data)
1076
+ ), s.addEventListener("open", () => {
855
1077
  this.state === "connecting" && this.setState("listening");
856
1078
  }), r.addEventListener("connectionstatechange", () => {
857
1079
  if (r.connectionState === "failed") {
@@ -861,27 +1083,27 @@ class Se {
861
1083
  r.connectionState === "disconnected" && this.timers.push(
862
1084
  setTimeout(() => {
863
1085
  this.pc === r && r.connectionState !== "connected" && this.fail("unavailable");
864
- }, je)
1086
+ }, Ne)
865
1087
  );
866
1088
  });
867
- const e = await r.createOffer();
868
- await r.setLocalDescription(e);
869
- const o = await fetch(ve, {
1089
+ const a = await r.createOffer();
1090
+ await r.setLocalDescription(a);
1091
+ const n = await fetch(Ie, {
870
1092
  method: "POST",
871
1093
  headers: {
872
- Authorization: `Bearer ${n.token}`,
1094
+ Authorization: `Bearer ${o.token}`,
873
1095
  "Content-Type": "application/sdp"
874
1096
  },
875
- body: e.sdp
1097
+ body: a.sdp
876
1098
  });
877
- if (!o.ok)
878
- throw new Error(`Realtime handshake failed (${o.status})`);
879
- const _ = await o.text();
1099
+ if (!n.ok)
1100
+ throw new Error(`Realtime handshake failed (${n.status})`);
1101
+ const c = await n.text();
880
1102
  if (this.isTornDown()) return;
881
- await r.setRemoteDescription({ type: "answer", sdp: _ });
882
- } catch (a) {
883
- a instanceof E ? this.fail("microphone") : (h.error("dictation session failed to start", {
884
- _e: a instanceof Error ? a.message : String(a)
1103
+ await r.setRemoteDescription({ type: "answer", sdp: c });
1104
+ } catch (e) {
1105
+ e instanceof P ? this.fail("microphone") : (k.error("dictation session failed to start", {
1106
+ _e: e instanceof Error ? e.message : String(e)
885
1107
  }), this.fail("unavailable"));
886
1108
  }
887
1109
  }
@@ -890,9 +1112,9 @@ class Se {
890
1112
  this.state !== "stopped" && (this.teardown(), this.setState("stopped"));
891
1113
  }
892
1114
  async requestMicrophone() {
893
- var a;
894
- if (!((a = navigator.mediaDevices) != null && a.getUserMedia))
895
- throw new E("Microphone is not supported");
1115
+ var e;
1116
+ if (!((e = navigator.mediaDevices) != null && e.getUserMedia))
1117
+ throw new P("Microphone is not supported");
896
1118
  try {
897
1119
  return await navigator.mediaDevices.getUserMedia({
898
1120
  audio: {
@@ -901,26 +1123,26 @@ class Se {
901
1123
  autoGainControl: !0
902
1124
  }
903
1125
  });
904
- } catch (s) {
905
- throw new E(
906
- s instanceof DOMException ? s.name : "Could not access the microphone"
1126
+ } catch (t) {
1127
+ throw new P(
1128
+ t instanceof DOMException ? t.name : "Could not access the microphone"
907
1129
  );
908
1130
  }
909
1131
  }
910
- handleServerEvent(a) {
911
- if (typeof a != "string") return;
912
- let s;
1132
+ handleServerEvent(e) {
1133
+ if (typeof e != "string") return;
1134
+ let t;
913
1135
  try {
914
- s = JSON.parse(a);
1136
+ t = JSON.parse(e);
915
1137
  } catch {
916
- this.loggedParseFailure || (this.loggedParseFailure = !0, h.error("dictation server event was not valid JSON", {
917
- snippet: a.slice(0, 120)
1138
+ this.loggedParseFailure || (this.loggedParseFailure = !0, k.error("dictation server event was not valid JSON", {
1139
+ snippet: e.slice(0, 120)
918
1140
  }));
919
1141
  return;
920
1142
  }
921
- const n = fe(s);
922
- if (!n) return;
923
- const { type: r, delta: l } = n;
1143
+ const o = Te(t);
1144
+ if (!o) return;
1145
+ const { type: r, delta: l } = o;
924
1146
  if (r === "session.created" || r === "transcription_session.created") {
925
1147
  this.setState("listening");
926
1148
  return;
@@ -929,67 +1151,67 @@ class Se {
929
1151
  this.state === "connecting" && this.setState("listening"), this.onDelta(l);
930
1152
  return;
931
1153
  }
932
- r === "error" && (h.error("dictation server event error", {
933
- _e: n.errorMessage ?? "unknown"
1154
+ r === "error" && (k.error("dictation server event error", {
1155
+ _e: o.errorMessage ?? "unknown"
934
1156
  }), this.fail("unavailable"));
935
1157
  }
936
- startLevelMeter(a) {
1158
+ startLevelMeter(e) {
937
1159
  if (this.onLevel)
938
1160
  try {
939
- const s = new AudioContext();
940
- this.audioContext = s;
941
- const n = s.createMediaStreamSource(a), r = s.createAnalyser();
942
- r.fftSize = 512, n.connect(r);
943
- const l = new Uint8Array(r.frequencyBinCount), t = () => {
944
- var _;
1161
+ const t = new AudioContext();
1162
+ this.audioContext = t;
1163
+ const o = t.createMediaStreamSource(e), r = t.createAnalyser();
1164
+ r.fftSize = 512, o.connect(r);
1165
+ const l = new Uint8Array(r.frequencyBinCount), s = () => {
1166
+ var c;
945
1167
  r.getByteTimeDomainData(l);
946
- let e = 0;
947
- for (let c = 0; c < l.length; c++) {
948
- const d = ((l[c] ?? 128) - 128) / 128;
949
- e += d * d;
1168
+ let a = 0;
1169
+ for (let d = 0; d < l.length; d++) {
1170
+ const _ = ((l[d] ?? 128) - 128) / 128;
1171
+ a += _ * _;
950
1172
  }
951
- const o = Math.sqrt(e / l.length);
952
- (_ = this.onLevel) == null || _.call(this, Math.min(1, o * 4)), this.levelRaf = requestAnimationFrame(t);
1173
+ const n = Math.sqrt(a / l.length);
1174
+ (c = this.onLevel) == null || c.call(this, Math.min(1, n * 4)), this.levelRaf = requestAnimationFrame(s);
953
1175
  };
954
- this.levelRaf = requestAnimationFrame(t);
955
- } catch (s) {
956
- h.error("dictation level meter unavailable", {
957
- _e: s instanceof Error ? s.message : String(s)
1176
+ this.levelRaf = requestAnimationFrame(s);
1177
+ } catch (t) {
1178
+ k.error("dictation level meter unavailable", {
1179
+ _e: t instanceof Error ? t.message : String(t)
958
1180
  });
959
1181
  }
960
1182
  }
961
1183
  isTornDown() {
962
1184
  return this.state === "stopped" || this.state === "error";
963
1185
  }
964
- fail(a) {
965
- this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(a));
1186
+ fail(e) {
1187
+ this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(e));
966
1188
  }
967
1189
  teardown() {
968
- var a, s, n, r;
969
- this.timers.forEach((l) => clearTimeout(l)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (a = this.dc) == null || a.close(), this.dc = null, (s = this.pc) == null || s.close(), this.pc = null, (n = this.stream) == null || n.getTracks().forEach((l) => l.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((l) => {
970
- h.error("failed to close dictation audio context", {
1190
+ var e, t, o, r;
1191
+ this.timers.forEach((l) => clearTimeout(l)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (t = this.pc) == null || t.close(), this.pc = null, (o = this.stream) == null || o.getTracks().forEach((l) => l.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((l) => {
1192
+ k.error("failed to close dictation audio context", {
971
1193
  _e: String(l)
972
1194
  });
973
1195
  }), this.audioContext = null;
974
1196
  }
975
- setState(a) {
976
- this.state !== a && (this.state = a, this.onState(a));
1197
+ setState(e) {
1198
+ this.state !== e && (this.state = e, this.onState(e));
977
1199
  }
978
1200
  }
979
- const ze = 1300, xe = { status: "idle", error: null };
980
- class Ce {
981
- constructor({ api: a, config: s }) {
982
- this.state = new w(xe), this.levelRef = { current: 0 }, this.mintCache = new be(), 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((n) => {
984
- this.mintCache.clear(), h.error("dictation token prewarm failed", {
985
- _e: n instanceof Error ? n.message : String(n)
1201
+ const Ke = 1300, Le = { status: "idle", error: null };
1202
+ class Fe {
1203
+ constructor({ api: e, config: t }) {
1204
+ this.state = new S(Le), this.levelRef = { current: 0 }, this.mintCache = new Pe(), this.session = null, this.target = null, this.prefix = "", this.raw = "", this.processed = "", this.displayed = "", this.dripTimer = null, this.silenceTimer = null, this.isActive = () => this.session !== null, this.prewarm = () => {
1205
+ this.mintToken().catch((o) => {
1206
+ this.mintCache.clear(), k.error("dictation token prewarm failed", {
1207
+ _e: o instanceof Error ? o.message : String(o)
986
1208
  });
987
1209
  });
988
- }, this.start = (n) => {
989
- this.session && this.teardown(), this.target = n, this.language = L.languageHint(
1210
+ }, this.start = (o) => {
1211
+ this.session && this.teardown(), this.target = o, this.language = H.languageHint(
990
1212
  this.config.language ?? navigator.language
991
- ), this.prefix = n.getValue(), this.raw = "", this.processed = "", this.displayed = "";
992
- const r = new Se({
1213
+ ), this.prefix = o.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1214
+ const r = new Re({
993
1215
  mintToken: this.mintToken,
994
1216
  onLevel: (l) => {
995
1217
  this.levelRef.current = l;
@@ -1007,24 +1229,24 @@ class Ce {
1007
1229
  return;
1008
1230
  }
1009
1231
  this.raw += l;
1010
- const t = this.ingest();
1011
- if (t === "stop") {
1232
+ const s = this.ingest();
1233
+ if (s === "stop") {
1012
1234
  this.teardown();
1013
1235
  return;
1014
1236
  }
1015
- if (t === "send") {
1237
+ if (s === "send") {
1016
1238
  this.teardown({ send: !0 });
1017
1239
  return;
1018
1240
  }
1019
- this.stopSilenceTimer(), C.pendingTailIsCompletePhrase(
1241
+ this.stopSilenceTimer(), q.pendingTailIsCompletePhrase(
1020
1242
  this.raw,
1021
1243
  this.language
1022
1244
  ) && (this.silenceTimer = setTimeout(() => {
1023
1245
  if (r !== this.session) return;
1024
1246
  this.raw = `${this.raw}.`;
1025
- const e = this.ingest();
1026
- e === "stop" ? this.teardown() : e === "send" && this.teardown({ send: !0 });
1027
- }, ze));
1247
+ const a = this.ingest();
1248
+ a === "stop" ? this.teardown() : a === "send" && this.teardown({ send: !0 });
1249
+ }, Ke));
1028
1250
  }
1029
1251
  });
1030
1252
  this.session = r, this.state.set({ status: "connecting", error: null }), this.dripTimer = setInterval(() => {
@@ -1034,51 +1256,51 @@ class Ce {
1034
1256
  return;
1035
1257
  }
1036
1258
  this.applyDisplayed(
1037
- L.nextDripText({
1259
+ H.nextDripText({
1038
1260
  displayed: this.displayed,
1039
1261
  processed: this.processed
1040
1262
  })
1041
1263
  );
1042
1264
  }
1043
- }, he), r.start();
1265
+ }, qe), r.start();
1044
1266
  }, this.stop = () => {
1045
1267
  this.session && this.teardown();
1046
1268
  }, this.mintToken = async () => this.mintCache.resolve(
1047
1269
  () => this.api.createDictationSession({ language: this.language })
1048
- ), this.api = a, this.config = s;
1270
+ ), this.api = e, this.config = t;
1049
1271
  }
1050
1272
  /** Applied text = prefix + dictated. A mismatch means the visitor edited. */
1051
1273
  isConsistent() {
1052
1274
  return this.target ? this.target.getValue() === this.prefix + this.displayed : !1;
1053
1275
  }
1054
- applyDisplayed(a) {
1055
- this.target && (this.target.setValue(this.prefix + a), this.displayed = a);
1276
+ applyDisplayed(e) {
1277
+ this.target && (this.target.setValue(this.prefix + e), this.displayed = e);
1056
1278
  }
1057
1279
  /** Process the transcript and apply the outcome. Shared by the delta path,
1058
1280
  * the silence timer, and (with `final`) teardown. Returns the control. */
1059
- ingest(a) {
1060
- const s = C.process(this.raw, {
1281
+ ingest(e) {
1282
+ const t = q.process(this.raw, {
1061
1283
  language: this.language,
1062
- final: a == null ? void 0 : a.final
1284
+ final: e == null ? void 0 : e.final
1063
1285
  });
1064
- return this.processed = s.text, s.text.startsWith(this.displayed) || this.applyDisplayed(s.text), s.control;
1286
+ return this.processed = t.text, t.text.startsWith(this.displayed) || this.applyDisplayed(t.text), t.control;
1065
1287
  }
1066
1288
  stopSilenceTimer() {
1067
1289
  this.silenceTimer && clearTimeout(this.silenceTimer), this.silenceTimer = null;
1068
1290
  }
1069
- teardown(a) {
1291
+ teardown(e) {
1070
1292
  var l;
1071
- const s = this.session, n = this.target;
1293
+ const t = this.session, o = this.target;
1072
1294
  this.dripTimer && clearInterval(this.dripTimer), this.dripTimer = null, this.stopSilenceTimer();
1073
- let r = (a == null ? void 0 : a.send) ?? !1;
1074
- if (n && this.isConsistent()) {
1075
- const t = this.ingest({ final: !0 });
1076
- (a == null ? void 0 : a.executeFinalCommand) !== !1 && t === "send" && (r = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1295
+ let r = (e == null ? void 0 : e.send) ?? !1;
1296
+ if (o && this.isConsistent()) {
1297
+ const s = this.ingest({ final: !0 });
1298
+ (e == null ? void 0 : e.executeFinalCommand) !== !1 && s === "send" && (r = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1077
1299
  }
1078
- this.session = null, this.target = null, s == null || s.stop(), this.levelRef.current = 0, this.state.set({ status: "idle", error: (a == null ? void 0 : a.error) ?? null }), r && ((l = n == null ? void 0 : n.onSend) == null || l.call(n));
1300
+ this.session = null, this.target = null, t == null || t.stop(), this.levelRef.current = 0, this.state.set({ status: "idle", error: (e == null ? void 0 : e.error) ?? null }), r && ((l = o == null ? void 0 : o.onSend) == null || l.call(o));
1079
1301
  }
1080
1302
  }
1081
- const qe = {
1303
+ const Oe = {
1082
1304
  write_a_message_placeholder: "اكتب رسالة...",
1083
1305
  your_issue_has_been_resolved: "تم حل مشكلتك!",
1084
1306
  new_conversation: "محادثة جديدة",
@@ -1102,7 +1324,19 @@ const qe = {
1102
1324
  companion_layout_floating: "عائم",
1103
1325
  companion_layout_sidebar: "الشريط الجانبي",
1104
1326
  companion_layout_fullscreen: "ملء الشاشة",
1327
+ companion_close_chat: "إغلاق {title}",
1105
1328
  companion_close: "إغلاق",
1329
+ companion_switch_chat: "تبديل المحادثة",
1330
+ companion_viewing: "تعرض الآن",
1331
+ companion_working: "قيد العمل",
1332
+ companion_open: "مفتوحة",
1333
+ companion_closed: "مغلقة",
1334
+ companion_draft: "مسودة",
1335
+ companion_chats: "الجلسات النشطة",
1336
+ companion_chat_number: "محادثة {count}",
1337
+ companion_active_chats: "{count} جلسات نشطة",
1338
+ companion_other_sessions: "الجلسات المفتوحة الأخرى: {count}",
1339
+ companion_working_chats: "{count} قيد العمل",
1106
1340
  companion_history: "سجل المحادثات",
1107
1341
  companion_expand_chat: "توسيع المحادثة",
1108
1342
  companion_sidebar_dock_label: "الإرساء",
@@ -1165,8 +1399,17 @@ const qe = {
1165
1399
  questions_next: "التالي",
1166
1400
  questions_send: "إرسال",
1167
1401
  questions_type_answer: "سأكتبها بنفسي",
1168
- questions_answer_placeholder: "اكتب إجابتك…"
1169
- }, Ee = {
1402
+ questions_answer_placeholder: "اكتب إجابتك…",
1403
+ close_conversation_title: "إغلاق المحادثة",
1404
+ close_conversation_description: "هل أنت متأكد أنك تريد إغلاق هذه المحادثة؟",
1405
+ close_conversation_cancel: "لا",
1406
+ close_conversation_confirm: "نعم",
1407
+ dialog_close: "إغلاق",
1408
+ zoom_in: "تكبير",
1409
+ zoom_out: "تصغير",
1410
+ reset_zoom: "إعادة تعيين التكبير",
1411
+ support_chat_aria_label: "دردشة الدعم"
1412
+ }, Ue = {
1170
1413
  write_a_message_placeholder: "একটি বার্তা লিখুন...",
1171
1414
  your_issue_has_been_resolved: "আপনার সমস্যা সমাধান হয়েছে!",
1172
1415
  new_conversation: "নতুন কথোপকথন",
@@ -1253,8 +1496,17 @@ const qe = {
1253
1496
  questions_next: "পরবর্তী",
1254
1497
  questions_send: "পাঠান",
1255
1498
  questions_type_answer: "আমি লিখে দিচ্ছি",
1256
- questions_answer_placeholder: "আপনার উত্তর লিখুন…"
1257
- }, Pe = {
1499
+ questions_answer_placeholder: "আপনার উত্তর লিখুন…",
1500
+ close_conversation_title: "কথোপকথন বন্ধ করুন",
1501
+ close_conversation_description: "আপনি কি নিশ্চিত যে আপনি এই কথোপকথনটি বন্ধ করতে চান?",
1502
+ close_conversation_cancel: "না",
1503
+ close_conversation_confirm: "হ্যাঁ",
1504
+ dialog_close: "বন্ধ করুন",
1505
+ zoom_in: "বড় করুন",
1506
+ zoom_out: "ছোট করুন",
1507
+ reset_zoom: "জুম রিসেট করুন",
1508
+ support_chat_aria_label: "সাপোর্ট চ্যাট"
1509
+ }, Be = {
1258
1510
  write_a_message_placeholder: "Напишете съобщение...",
1259
1511
  your_issue_has_been_resolved: "Вашият проблем е разрешен!",
1260
1512
  new_conversation: "Нов разговор",
@@ -1341,8 +1593,17 @@ const qe = {
1341
1593
  questions_next: "Напред",
1342
1594
  questions_send: "Изпрати",
1343
1595
  questions_type_answer: "Ще напиша сам",
1344
- questions_answer_placeholder: "Напишете отговора си…"
1345
- }, Te = {
1596
+ questions_answer_placeholder: "Напишете отговора си…",
1597
+ close_conversation_title: "Затваряне на разговора",
1598
+ close_conversation_description: "Сигурни ли сте, че искате да затворите този разговор?",
1599
+ close_conversation_cancel: "Не",
1600
+ close_conversation_confirm: "Да",
1601
+ dialog_close: "Затваряне",
1602
+ zoom_in: "Увеличаване",
1603
+ zoom_out: "Намаляване",
1604
+ reset_zoom: "Нулиране на мащаба",
1605
+ support_chat_aria_label: "Чат за поддръжка"
1606
+ }, Ve = {
1346
1607
  write_a_message_placeholder: "Napište zprávu...",
1347
1608
  your_issue_has_been_resolved: "Váš problém byl vyřešen!",
1348
1609
  new_conversation: "Nová konverzace",
@@ -1429,8 +1690,17 @@ const qe = {
1429
1690
  questions_next: "Další",
1430
1691
  questions_send: "Odeslat",
1431
1692
  questions_type_answer: "Napíšu to sám",
1432
- questions_answer_placeholder: "Napište svou odpověď…"
1433
- }, Ae = {
1693
+ questions_answer_placeholder: "Napište svou odpověď…",
1694
+ close_conversation_title: "Uzavřít konverzaci",
1695
+ close_conversation_description: "Opravdu chcete tuto konverzaci uzavřít?",
1696
+ close_conversation_cancel: "Ne",
1697
+ close_conversation_confirm: "Ano",
1698
+ dialog_close: "Zavřít",
1699
+ zoom_in: "Přiblížit",
1700
+ zoom_out: "Oddálit",
1701
+ reset_zoom: "Obnovit přiblížení",
1702
+ support_chat_aria_label: "Chat podpory"
1703
+ }, He = {
1434
1704
  write_a_message_placeholder: "Skriv en besked...",
1435
1705
  your_issue_has_been_resolved: "Dit problem er løst!",
1436
1706
  new_conversation: "Ny samtale",
@@ -1517,8 +1787,17 @@ const qe = {
1517
1787
  questions_next: "Næste",
1518
1788
  questions_send: "Send",
1519
1789
  questions_type_answer: "Jeg skriver det selv",
1520
- questions_answer_placeholder: "Skriv dit svar…"
1521
- }, Me = {
1790
+ questions_answer_placeholder: "Skriv dit svar…",
1791
+ close_conversation_title: "Luk samtale",
1792
+ close_conversation_description: "Er du sikker på, at du vil lukke denne samtale?",
1793
+ close_conversation_cancel: "Nej",
1794
+ close_conversation_confirm: "Ja",
1795
+ dialog_close: "Luk",
1796
+ zoom_in: "Zoom ind",
1797
+ zoom_out: "Zoom ud",
1798
+ reset_zoom: "Nulstil zoom",
1799
+ support_chat_aria_label: "Supportchat"
1800
+ }, Ze = {
1522
1801
  write_a_message_placeholder: "Γράψτε ένα μήνυμα...",
1523
1802
  your_issue_has_been_resolved: "Το πρόβλημά σας επιλύθηκε!",
1524
1803
  new_conversation: "Νέα συνομιλία",
@@ -1605,8 +1884,17 @@ const qe = {
1605
1884
  questions_next: "Επόμενο",
1606
1885
  questions_send: "Αποστολή",
1607
1886
  questions_type_answer: "Θα το γράψω",
1608
- questions_answer_placeholder: "Γράψτε την απάντησή σας…"
1609
- }, Ie = {
1887
+ questions_answer_placeholder: "Γράψτε την απάντησή σας…",
1888
+ close_conversation_title: "Κλείσιμο συνομιλίας",
1889
+ close_conversation_description: "Είστε βέβαιοι ότι θέλετε να κλείσετε αυτήν τη συνομιλία;",
1890
+ close_conversation_cancel: "Όχι",
1891
+ close_conversation_confirm: "Ναι",
1892
+ dialog_close: "Κλείσιμο",
1893
+ zoom_in: "Μεγέθυνση",
1894
+ zoom_out: "Σμίκρυνση",
1895
+ reset_zoom: "Επαναφορά ζουμ",
1896
+ support_chat_aria_label: "Συνομιλία υποστήριξης"
1897
+ }, We = {
1610
1898
  write_a_message_placeholder: "Nachricht schreiben...",
1611
1899
  your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
1612
1900
  new_conversation: "Neue Konversation",
@@ -1693,8 +1981,17 @@ const qe = {
1693
1981
  questions_next: "Weiter",
1694
1982
  questions_send: "Senden",
1695
1983
  questions_type_answer: "Ich schreibe es selbst",
1696
- questions_answer_placeholder: "Antwort eingeben…"
1697
- }, De = {
1984
+ questions_answer_placeholder: "Antwort eingeben…",
1985
+ close_conversation_title: "Konversation schließen",
1986
+ close_conversation_description: "Möchten Sie diese Konversation wirklich schließen?",
1987
+ close_conversation_cancel: "Nein",
1988
+ close_conversation_confirm: "Ja",
1989
+ dialog_close: "Schließen",
1990
+ zoom_in: "Vergrößern",
1991
+ zoom_out: "Verkleinern",
1992
+ reset_zoom: "Zoom zurücksetzen",
1993
+ support_chat_aria_label: "Support-Chat"
1994
+ }, J = {
1698
1995
  write_a_message_placeholder: "Write a message...",
1699
1996
  your_issue_has_been_resolved: "Your issue has been resolved!",
1700
1997
  new_conversation: "New conversation",
@@ -1718,7 +2015,19 @@ const qe = {
1718
2015
  companion_layout_floating: "Floating",
1719
2016
  companion_layout_sidebar: "Sidebar",
1720
2017
  companion_layout_fullscreen: "Fullscreen",
2018
+ companion_close_chat: "Close {title}",
1721
2019
  companion_close: "Close",
2020
+ companion_switch_chat: "Switch chat",
2021
+ companion_viewing: "Viewing",
2022
+ companion_working: "Working",
2023
+ companion_open: "Open",
2024
+ companion_closed: "Closed",
2025
+ companion_draft: "Draft",
2026
+ companion_chats: "Active sessions",
2027
+ companion_chat_number: "Chat {count}",
2028
+ companion_active_chats: "{count} active sessions",
2029
+ companion_other_sessions: "Other open sessions: {count}",
2030
+ companion_working_chats: "{count} working",
1722
2031
  companion_history: "Conversation history",
1723
2032
  companion_expand_chat: "Expand chat",
1724
2033
  companion_sidebar_dock_label: "Dock",
@@ -1781,8 +2090,17 @@ const qe = {
1781
2090
  questions_next: "Next",
1782
2091
  questions_send: "Send",
1783
2092
  questions_type_answer: "I'll type it",
1784
- questions_answer_placeholder: "Type your answer…"
1785
- }, Ne = {
2093
+ questions_answer_placeholder: "Type your answer…",
2094
+ close_conversation_title: "Close conversation",
2095
+ close_conversation_description: "Are you sure you want to close this conversation?",
2096
+ close_conversation_cancel: "No",
2097
+ close_conversation_confirm: "Yes",
2098
+ dialog_close: "Close",
2099
+ zoom_in: "Zoom in",
2100
+ zoom_out: "Zoom out",
2101
+ reset_zoom: "Reset zoom",
2102
+ support_chat_aria_label: "Support chat"
2103
+ }, Ge = {
1786
2104
  write_a_message_placeholder: "Escribe un mensaje...",
1787
2105
  your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
1788
2106
  new_conversation: "Nueva conversación",
@@ -1869,8 +2187,17 @@ const qe = {
1869
2187
  questions_next: "Siguiente",
1870
2188
  questions_send: "Enviar",
1871
2189
  questions_type_answer: "Lo escribo yo",
1872
- questions_answer_placeholder: "Escribe tu respuesta…"
1873
- }, Re = {
2190
+ questions_answer_placeholder: "Escribe tu respuesta…",
2191
+ close_conversation_title: "Cerrar conversación",
2192
+ close_conversation_description: "¿Seguro que quieres cerrar esta conversación?",
2193
+ close_conversation_cancel: "No",
2194
+ close_conversation_confirm: "Sí",
2195
+ dialog_close: "Cerrar",
2196
+ zoom_in: "Acercar",
2197
+ zoom_out: "Alejar",
2198
+ reset_zoom: "Restablecer zoom",
2199
+ support_chat_aria_label: "Chat de soporte"
2200
+ }, $e = {
1874
2201
  write_a_message_placeholder: "Magsulat ng mensahe...",
1875
2202
  your_issue_has_been_resolved: "Nalutas na ang iyong isyu!",
1876
2203
  new_conversation: "Bagong usapan",
@@ -1957,8 +2284,17 @@ const qe = {
1957
2284
  questions_next: "Susunod",
1958
2285
  questions_send: "Ipadala",
1959
2286
  questions_type_answer: "Ako na ang magta-type",
1960
- questions_answer_placeholder: "I-type ang iyong sagot…"
1961
- }, Ke = {
2287
+ questions_answer_placeholder: "I-type ang iyong sagot…",
2288
+ close_conversation_title: "Isara ang usapan",
2289
+ close_conversation_description: "Sigurado ka bang gusto mong isara ang usapang ito?",
2290
+ close_conversation_cancel: "Hindi",
2291
+ close_conversation_confirm: "Oo",
2292
+ dialog_close: "Isara",
2293
+ zoom_in: "Palakihin",
2294
+ zoom_out: "Paliitin",
2295
+ reset_zoom: "I-reset ang zoom",
2296
+ support_chat_aria_label: "Chat ng suporta"
2297
+ }, Je = {
1962
2298
  write_a_message_placeholder: "Kirjoita viesti...",
1963
2299
  your_issue_has_been_resolved: "Ongelmasi on ratkaistu!",
1964
2300
  new_conversation: "Uusi keskustelu",
@@ -2045,8 +2381,17 @@ const qe = {
2045
2381
  questions_next: "Seuraava",
2046
2382
  questions_send: "Lähetä",
2047
2383
  questions_type_answer: "Kirjoitan itse",
2048
- questions_answer_placeholder: "Kirjoita vastauksesi…"
2049
- }, Le = {
2384
+ questions_answer_placeholder: "Kirjoita vastauksesi…",
2385
+ close_conversation_title: "Sulje keskustelu",
2386
+ close_conversation_description: "Haluatko varmasti sulkea tämän keskustelun?",
2387
+ close_conversation_cancel: "Ei",
2388
+ close_conversation_confirm: "Kyllä",
2389
+ dialog_close: "Sulje",
2390
+ zoom_in: "Lähennä",
2391
+ zoom_out: "Loitonna",
2392
+ reset_zoom: "Palauta zoomaus",
2393
+ support_chat_aria_label: "Tukichat"
2394
+ }, Ye = {
2050
2395
  write_a_message_placeholder: "Écrivez un message...",
2051
2396
  your_issue_has_been_resolved: "Votre problème a été résolu !",
2052
2397
  new_conversation: "Nouvelle conversation",
@@ -2133,8 +2478,17 @@ const qe = {
2133
2478
  questions_next: "Suivant",
2134
2479
  questions_send: "Envoyer",
2135
2480
  questions_type_answer: "Je préfère écrire",
2136
- questions_answer_placeholder: "Écrivez votre réponse…"
2137
- }, Fe = {
2481
+ questions_answer_placeholder: "Écrivez votre réponse…",
2482
+ close_conversation_title: "Fermer la conversation",
2483
+ close_conversation_description: "Voulez-vous vraiment fermer cette conversation ?",
2484
+ close_conversation_cancel: "Non",
2485
+ close_conversation_confirm: "Oui",
2486
+ dialog_close: "Fermer",
2487
+ zoom_in: "Zoom avant",
2488
+ zoom_out: "Zoom arrière",
2489
+ reset_zoom: "Réinitialiser le zoom",
2490
+ support_chat_aria_label: "Chat de support"
2491
+ }, Qe = {
2138
2492
  write_a_message_placeholder: "एक संदेश लिखें...",
2139
2493
  your_issue_has_been_resolved: "आपकी समस्या हल हो गई है!",
2140
2494
  new_conversation: "नई बातचीत",
@@ -2221,8 +2575,17 @@ const qe = {
2221
2575
  questions_next: "आगे",
2222
2576
  questions_send: "भेजें",
2223
2577
  questions_type_answer: "मैं खुद लिखूंगा",
2224
- questions_answer_placeholder: "अपना उत्तर लिखें…"
2225
- }, Oe = {
2578
+ questions_answer_placeholder: "अपना उत्तर लिखें…",
2579
+ close_conversation_title: "बातचीत बंद करें",
2580
+ close_conversation_description: "क्या आप वाकई इस बातचीत को बंद करना चाहते हैं?",
2581
+ close_conversation_cancel: "नहीं",
2582
+ close_conversation_confirm: "हाँ",
2583
+ dialog_close: "बंद करें",
2584
+ zoom_in: "ज़ूम इन",
2585
+ zoom_out: "ज़ूम आउट",
2586
+ reset_zoom: "ज़ूम रीसेट करें",
2587
+ support_chat_aria_label: "सहायता चैट"
2588
+ }, Xe = {
2226
2589
  write_a_message_placeholder: "Scrivi un messaggio...",
2227
2590
  your_issue_has_been_resolved: "Il tuo problema è stato risolto!",
2228
2591
  new_conversation: "Nuova conversazione",
@@ -2309,8 +2672,17 @@ const qe = {
2309
2672
  questions_next: "Avanti",
2310
2673
  questions_send: "Invia",
2311
2674
  questions_type_answer: "Lo scrivo io",
2312
- questions_answer_placeholder: "Scrivi la tua risposta…"
2313
- }, Ue = {
2675
+ questions_answer_placeholder: "Scrivi la tua risposta…",
2676
+ close_conversation_title: "Chiudi conversazione",
2677
+ close_conversation_description: "Vuoi davvero chiudere questa conversazione?",
2678
+ close_conversation_cancel: "No",
2679
+ close_conversation_confirm: "Sì",
2680
+ dialog_close: "Chiudi",
2681
+ zoom_in: "Ingrandisci",
2682
+ zoom_out: "Riduci",
2683
+ reset_zoom: "Reimposta zoom",
2684
+ support_chat_aria_label: "Chat di supporto"
2685
+ }, ea = {
2314
2686
  write_a_message_placeholder: "メッセージを入力...",
2315
2687
  your_issue_has_been_resolved: "問題が解決しました!",
2316
2688
  new_conversation: "新しい会話",
@@ -2397,8 +2769,17 @@ const qe = {
2397
2769
  questions_next: "次へ",
2398
2770
  questions_send: "送信",
2399
2771
  questions_type_answer: "自分で入力する",
2400
- questions_answer_placeholder: "回答を入力してください…"
2401
- }, Be = {
2772
+ questions_answer_placeholder: "回答を入力してください…",
2773
+ close_conversation_title: "会話を終了",
2774
+ close_conversation_description: "この会話を終了してもよろしいですか?",
2775
+ close_conversation_cancel: "いいえ",
2776
+ close_conversation_confirm: "はい",
2777
+ dialog_close: "閉じる",
2778
+ zoom_in: "拡大",
2779
+ zoom_out: "縮小",
2780
+ reset_zoom: "ズームをリセット",
2781
+ support_chat_aria_label: "サポートチャット"
2782
+ }, aa = {
2402
2783
  write_a_message_placeholder: "메시지를 입력하세요...",
2403
2784
  your_issue_has_been_resolved: "문제가 해결되었습니다!",
2404
2785
  new_conversation: "새 대화",
@@ -2485,8 +2866,17 @@ const qe = {
2485
2866
  questions_next: "다음",
2486
2867
  questions_send: "보내기",
2487
2868
  questions_type_answer: "직접 입력할게요",
2488
- questions_answer_placeholder: "답변을 입력하세요…"
2489
- }, Ve = {
2869
+ questions_answer_placeholder: "답변을 입력하세요…",
2870
+ close_conversation_title: "대화 종료",
2871
+ close_conversation_description: "이 대화를 종료하시겠습니까?",
2872
+ close_conversation_cancel: "아니요",
2873
+ close_conversation_confirm: "예",
2874
+ dialog_close: "닫기",
2875
+ zoom_in: "확대",
2876
+ zoom_out: "축소",
2877
+ reset_zoom: "확대/축소 초기화",
2878
+ support_chat_aria_label: "고객 지원 채팅"
2879
+ }, ta = {
2490
2880
  write_a_message_placeholder: "Schrijf een bericht...",
2491
2881
  your_issue_has_been_resolved: "Uw probleem is opgelost!",
2492
2882
  new_conversation: "Nieuw gesprek",
@@ -2573,8 +2963,17 @@ const qe = {
2573
2963
  questions_next: "Volgende",
2574
2964
  questions_send: "Verzenden",
2575
2965
  questions_type_answer: "Ik typ het zelf",
2576
- questions_answer_placeholder: "Typ je antwoord…"
2577
- }, He = {
2966
+ questions_answer_placeholder: "Typ je antwoord…",
2967
+ close_conversation_title: "Gesprek sluiten",
2968
+ close_conversation_description: "Weet je zeker dat je dit gesprek wilt sluiten?",
2969
+ close_conversation_cancel: "Nee",
2970
+ close_conversation_confirm: "Ja",
2971
+ dialog_close: "Sluiten",
2972
+ zoom_in: "Inzoomen",
2973
+ zoom_out: "Uitzoomen",
2974
+ reset_zoom: "Zoom herstellen",
2975
+ support_chat_aria_label: "Supportchat"
2976
+ }, sa = {
2578
2977
  write_a_message_placeholder: "Skriv en melding...",
2579
2978
  your_issue_has_been_resolved: "Problemet ditt er løst!",
2580
2979
  new_conversation: "Ny samtale",
@@ -2661,8 +3060,17 @@ const qe = {
2661
3060
  questions_next: "Neste",
2662
3061
  questions_send: "Send",
2663
3062
  questions_type_answer: "Jeg skriver det selv",
2664
- questions_answer_placeholder: "Skriv svaret ditt…"
2665
- }, Ge = {
3063
+ questions_answer_placeholder: "Skriv svaret ditt…",
3064
+ close_conversation_title: "Lukk samtale",
3065
+ close_conversation_description: "Er du sikker på at du vil lukke denne samtalen?",
3066
+ close_conversation_cancel: "Nei",
3067
+ close_conversation_confirm: "Ja",
3068
+ dialog_close: "Lukk",
3069
+ zoom_in: "Zoom inn",
3070
+ zoom_out: "Zoom ut",
3071
+ reset_zoom: "Tilbakestill zoom",
3072
+ support_chat_aria_label: "Support-chat"
3073
+ }, oa = {
2666
3074
  write_a_message_placeholder: "Napisz wiadomość...",
2667
3075
  your_issue_has_been_resolved: "Twój problem został rozwiązany!",
2668
3076
  new_conversation: "Nowa rozmowa",
@@ -2749,8 +3157,17 @@ const qe = {
2749
3157
  questions_next: "Dalej",
2750
3158
  questions_send: "Wyślij",
2751
3159
  questions_type_answer: "Napiszę sam",
2752
- questions_answer_placeholder: "Wpisz swoją odpowiedź…"
2753
- }, We = {
3160
+ questions_answer_placeholder: "Wpisz swoją odpowiedź…",
3161
+ close_conversation_title: "Zamknij rozmowę",
3162
+ close_conversation_description: "Czy na pewno chcesz zamknąć tę rozmowę?",
3163
+ close_conversation_cancel: "Nie",
3164
+ close_conversation_confirm: "Tak",
3165
+ dialog_close: "Zamknij",
3166
+ zoom_in: "Powiększ",
3167
+ zoom_out: "Pomniejsz",
3168
+ reset_zoom: "Resetuj powiększenie",
3169
+ support_chat_aria_label: "Czat pomocy"
3170
+ }, na = {
2754
3171
  write_a_message_placeholder: "Escreva uma mensagem...",
2755
3172
  your_issue_has_been_resolved: "Seu problema foi resolvido!",
2756
3173
  new_conversation: "Nova conversa",
@@ -2837,8 +3254,17 @@ const qe = {
2837
3254
  questions_next: "Seguinte",
2838
3255
  questions_send: "Enviar",
2839
3256
  questions_type_answer: "Prefiro escrever",
2840
- questions_answer_placeholder: "Escreva a sua resposta…"
2841
- }, $e = {
3257
+ questions_answer_placeholder: "Escreva a sua resposta…",
3258
+ close_conversation_title: "Encerrar conversa",
3259
+ close_conversation_description: "Tem certeza de que deseja encerrar esta conversa?",
3260
+ close_conversation_cancel: "Não",
3261
+ close_conversation_confirm: "Sim",
3262
+ dialog_close: "Fechar",
3263
+ zoom_in: "Ampliar",
3264
+ zoom_out: "Reduzir",
3265
+ reset_zoom: "Redefinir zoom",
3266
+ support_chat_aria_label: "Chat de suporte"
3267
+ }, ia = {
2842
3268
  write_a_message_placeholder: "Scrie un mesaj...",
2843
3269
  your_issue_has_been_resolved: "Problema ta a fost rezolvată!",
2844
3270
  new_conversation: "Conversație nouă",
@@ -2925,8 +3351,17 @@ const qe = {
2925
3351
  questions_next: "Înainte",
2926
3352
  questions_send: "Trimite",
2927
3353
  questions_type_answer: "Scriu eu",
2928
- questions_answer_placeholder: "Scrieți răspunsul dvs.…"
2929
- }, Ze = {
3354
+ questions_answer_placeholder: "Scrieți răspunsul dvs.…",
3355
+ close_conversation_title: "Închide conversația",
3356
+ close_conversation_description: "Sigur vrei să închizi această conversație?",
3357
+ close_conversation_cancel: "Nu",
3358
+ close_conversation_confirm: "Da",
3359
+ dialog_close: "Închide",
3360
+ zoom_in: "Mărește",
3361
+ zoom_out: "Micșorează",
3362
+ reset_zoom: "Resetează zoomul",
3363
+ support_chat_aria_label: "Chat de asistență"
3364
+ }, ra = {
2930
3365
  write_a_message_placeholder: "Skriv ett meddelande...",
2931
3366
  your_issue_has_been_resolved: "Ditt problem har lösts!",
2932
3367
  new_conversation: "Ny konversation",
@@ -3013,8 +3448,17 @@ const qe = {
3013
3448
  questions_next: "Nästa",
3014
3449
  questions_send: "Skicka",
3015
3450
  questions_type_answer: "Jag skriver själv",
3016
- questions_answer_placeholder: "Skriv ditt svar…"
3017
- }, Je = {
3451
+ questions_answer_placeholder: "Skriv ditt svar…",
3452
+ close_conversation_title: "Avsluta konversation",
3453
+ close_conversation_description: "Är du säker på att du vill avsluta den här konversationen?",
3454
+ close_conversation_cancel: "Nej",
3455
+ close_conversation_confirm: "Ja",
3456
+ dialog_close: "Stäng",
3457
+ zoom_in: "Zooma in",
3458
+ zoom_out: "Zooma ut",
3459
+ reset_zoom: "Återställ zoom",
3460
+ support_chat_aria_label: "Supportchatt"
3461
+ }, _a = {
3018
3462
  write_a_message_placeholder: "Напишите сообщение...",
3019
3463
  your_issue_has_been_resolved: "Ваша проблема решена!",
3020
3464
  new_conversation: "Новый разговор",
@@ -3101,8 +3545,17 @@ const qe = {
3101
3545
  questions_next: "Далее",
3102
3546
  questions_send: "Отправить",
3103
3547
  questions_type_answer: "Напишу сам",
3104
- questions_answer_placeholder: "Напишите ваш ответ…"
3105
- }, Ye = {
3548
+ questions_answer_placeholder: "Напишите ваш ответ…",
3549
+ close_conversation_title: "Закрыть разговор",
3550
+ close_conversation_description: "Вы уверены, что хотите закрыть этот разговор?",
3551
+ close_conversation_cancel: "Нет",
3552
+ close_conversation_confirm: "Да",
3553
+ dialog_close: "Закрыть",
3554
+ zoom_in: "Увеличить",
3555
+ zoom_out: "Уменьшить",
3556
+ reset_zoom: "Сбросить масштаб",
3557
+ support_chat_aria_label: "Чат поддержки"
3558
+ }, la = {
3106
3559
  write_a_message_placeholder: "เขียนข้อความ...",
3107
3560
  your_issue_has_been_resolved: "ปัญหาของคุณได้รับการแก้ไขแล้ว!",
3108
3561
  new_conversation: "การสนทนาใหม่",
@@ -3189,8 +3642,17 @@ const qe = {
3189
3642
  questions_next: "ถัดไป",
3190
3643
  questions_send: "ส่ง",
3191
3644
  questions_type_answer: "ขอพิมพ์เอง",
3192
- questions_answer_placeholder: "พิมพ์คำตอบของคุณ…"
3193
- }, Xe = {
3645
+ questions_answer_placeholder: "พิมพ์คำตอบของคุณ…",
3646
+ close_conversation_title: "ปิดการสนทนา",
3647
+ close_conversation_description: "คุณแน่ใจหรือไม่ว่าต้องการปิดการสนทนานี้?",
3648
+ close_conversation_cancel: "ไม่",
3649
+ close_conversation_confirm: "ใช่",
3650
+ dialog_close: "ปิด",
3651
+ zoom_in: "ขยาย",
3652
+ zoom_out: "ย่อ",
3653
+ reset_zoom: "รีเซ็ตการซูม",
3654
+ support_chat_aria_label: "แชทฝ่ายสนับสนุน"
3655
+ }, ca = {
3194
3656
  write_a_message_placeholder: "Bir mesaj yazın...",
3195
3657
  your_issue_has_been_resolved: "Sorununuz çözüldü!",
3196
3658
  new_conversation: "Yeni konuşma",
@@ -3277,8 +3739,17 @@ const qe = {
3277
3739
  questions_next: "İleri",
3278
3740
  questions_send: "Gönder",
3279
3741
  questions_type_answer: "Kendim yazayım",
3280
- questions_answer_placeholder: "Yanıtınızı yazın…"
3281
- }, Qe = {
3742
+ questions_answer_placeholder: "Yanıtınızı yazın…",
3743
+ close_conversation_title: "Görüşmeyi kapat",
3744
+ close_conversation_description: "Bu görüşmeyi kapatmak istediğinizden emin misiniz?",
3745
+ close_conversation_cancel: "Hayır",
3746
+ close_conversation_confirm: "Evet",
3747
+ dialog_close: "Kapat",
3748
+ zoom_in: "Yakınlaştır",
3749
+ zoom_out: "Uzaklaştır",
3750
+ reset_zoom: "Yakınlaştırmayı sıfırla",
3751
+ support_chat_aria_label: "Destek sohbeti"
3752
+ }, pa = {
3282
3753
  write_a_message_placeholder: "پیغام لکھیں...",
3283
3754
  your_issue_has_been_resolved: "آپ کا مسئلہ حل ہو گیا ہے!",
3284
3755
  new_conversation: "نئی گفتگو",
@@ -3365,8 +3836,17 @@ const qe = {
3365
3836
  questions_next: "اگلا",
3366
3837
  questions_send: "بھیجیں",
3367
3838
  questions_type_answer: "میں خود لکھوں گا",
3368
- questions_answer_placeholder: "اپنا جواب لکھیں…"
3369
- }, ea = {
3839
+ questions_answer_placeholder: "اپنا جواب لکھیں…",
3840
+ close_conversation_title: "گفتگو بند کریں",
3841
+ close_conversation_description: "کیا آپ واقعی یہ گفتگو بند کرنا چاہتے ہیں؟",
3842
+ close_conversation_cancel: "نہیں",
3843
+ close_conversation_confirm: "ہاں",
3844
+ dialog_close: "بند کریں",
3845
+ zoom_in: "زوم اِن",
3846
+ zoom_out: "زوم آؤٹ",
3847
+ reset_zoom: "زوم دوبارہ ترتیب دیں",
3848
+ support_chat_aria_label: "سپورٹ چیٹ"
3849
+ }, da = {
3370
3850
  write_a_message_placeholder: "Viết tin nhắn...",
3371
3851
  your_issue_has_been_resolved: "Vấn đề của bạn đã được giải quyết!",
3372
3852
  new_conversation: "Cuộc trò chuyện mới",
@@ -3453,8 +3933,17 @@ const qe = {
3453
3933
  questions_next: "Tiếp theo",
3454
3934
  questions_send: "Gửi",
3455
3935
  questions_type_answer: "Tôi sẽ tự nhập",
3456
- questions_answer_placeholder: "Nhập câu trả lời của bạn…"
3457
- }, aa = {
3936
+ questions_answer_placeholder: "Nhập câu trả lời của bạn…",
3937
+ close_conversation_title: "Đóng cuộc trò chuyện",
3938
+ close_conversation_description: "Bạn có chắc muốn đóng cuộc trò chuyện này không?",
3939
+ close_conversation_cancel: "Không",
3940
+ close_conversation_confirm: "Có",
3941
+ dialog_close: "Đóng",
3942
+ zoom_in: "Phóng to",
3943
+ zoom_out: "Thu nhỏ",
3944
+ reset_zoom: "Đặt lại thu phóng",
3945
+ support_chat_aria_label: "Trò chuyện hỗ trợ"
3946
+ }, ua = {
3458
3947
  write_a_message_placeholder: "写一条消息...",
3459
3948
  your_issue_has_been_resolved: "您的问题已解决!",
3460
3949
  new_conversation: "新对话",
@@ -3541,8 +4030,17 @@ const qe = {
3541
4030
  questions_next: "下一步",
3542
4031
  questions_send: "发送",
3543
4032
  questions_type_answer: "我自己输入",
3544
- questions_answer_placeholder: "输入你的回答…"
3545
- }, ta = {
4033
+ questions_answer_placeholder: "输入你的回答…",
4034
+ close_conversation_title: "结束对话",
4035
+ close_conversation_description: "确定要结束此对话吗?",
4036
+ close_conversation_cancel: "否",
4037
+ close_conversation_confirm: "是",
4038
+ dialog_close: "关闭",
4039
+ zoom_in: "放大",
4040
+ zoom_out: "缩小",
4041
+ reset_zoom: "重置缩放",
4042
+ support_chat_aria_label: "支持对话"
4043
+ }, ma = {
3546
4044
  write_a_message_placeholder: "Napišite poruku...",
3547
4045
  your_issue_has_been_resolved: "Vaš problem je riješen!",
3548
4046
  new_conversation: "Novi razgovor",
@@ -3629,8 +4127,17 @@ const qe = {
3629
4127
  questions_next: "Dalje",
3630
4128
  questions_send: "Pošalji",
3631
4129
  questions_type_answer: "Napisat ću sam",
3632
- questions_answer_placeholder: "Napišite svoj odgovor…"
3633
- }, sa = {
4130
+ questions_answer_placeholder: "Napišite svoj odgovor…",
4131
+ close_conversation_title: "Zatvori razgovor",
4132
+ close_conversation_description: "Jeste li sigurni da želite zatvoriti ovaj razgovor?",
4133
+ close_conversation_cancel: "Ne",
4134
+ close_conversation_confirm: "Da",
4135
+ dialog_close: "Zatvori",
4136
+ zoom_in: "Približi",
4137
+ zoom_out: "Udalji",
4138
+ reset_zoom: "Poništi zumiranje",
4139
+ support_chat_aria_label: "Chat za podršku"
4140
+ }, ha = {
3634
4141
  write_a_message_placeholder: "Kirjuta sõnum...",
3635
4142
  your_issue_has_been_resolved: "Teie probleem on lahendatud!",
3636
4143
  new_conversation: "Uus vestlus",
@@ -3717,8 +4224,17 @@ const qe = {
3717
4224
  questions_next: "Edasi",
3718
4225
  questions_send: "Saada",
3719
4226
  questions_type_answer: "Kirjutan ise",
3720
- questions_answer_placeholder: "Kirjutage oma vastus…"
3721
- }, na = {
4227
+ questions_answer_placeholder: "Kirjutage oma vastus…",
4228
+ close_conversation_title: "Sulge vestlus",
4229
+ close_conversation_description: "Kas soovite kindlasti selle vestluse sulgeda?",
4230
+ close_conversation_cancel: "Ei",
4231
+ close_conversation_confirm: "Jah",
4232
+ dialog_close: "Sulge",
4233
+ zoom_in: "Suurenda",
4234
+ zoom_out: "Vähenda",
4235
+ reset_zoom: "Lähtesta suurendus",
4236
+ support_chat_aria_label: "Tugivestlus"
4237
+ }, ga = {
3722
4238
  write_a_message_placeholder: "Írjon üzenetet...",
3723
4239
  your_issue_has_been_resolved: "A problémája megoldódott!",
3724
4240
  new_conversation: "Új beszélgetés",
@@ -3805,8 +4321,17 @@ const qe = {
3805
4321
  questions_next: "Tovább",
3806
4322
  questions_send: "Küldés",
3807
4323
  questions_type_answer: "Inkább leírom",
3808
- questions_answer_placeholder: "Írja le a válaszát…"
3809
- }, oa = {
4324
+ questions_answer_placeholder: "Írja le a válaszát…",
4325
+ close_conversation_title: "Beszélgetés lezárása",
4326
+ close_conversation_description: "Biztosan lezárja ezt a beszélgetést?",
4327
+ close_conversation_cancel: "Nem",
4328
+ close_conversation_confirm: "Igen",
4329
+ dialog_close: "Bezárás",
4330
+ zoom_in: "Nagyítás",
4331
+ zoom_out: "Kicsinyítés",
4332
+ reset_zoom: "Nagyítás visszaállítása",
4333
+ support_chat_aria_label: "Ügyfélszolgálati chat"
4334
+ }, ka = {
3810
4335
  write_a_message_placeholder: "Skrifaðu skilaboð...",
3811
4336
  your_issue_has_been_resolved: "Málið þitt hefur verið leyst!",
3812
4337
  new_conversation: "Nýtt samtal",
@@ -3893,8 +4418,17 @@ const qe = {
3893
4418
  questions_next: "Áfram",
3894
4419
  questions_send: "Senda",
3895
4420
  questions_type_answer: "Ég skrifa það",
3896
- questions_answer_placeholder: "Skrifaðu svarið þitt…"
3897
- }, ia = {
4421
+ questions_answer_placeholder: "Skrifaðu svarið þitt…",
4422
+ close_conversation_title: "Loka samtali",
4423
+ close_conversation_description: "Ertu viss um að þú viljir loka þessu samtali?",
4424
+ close_conversation_cancel: "Nei",
4425
+ close_conversation_confirm: "Já",
4426
+ dialog_close: "Loka",
4427
+ zoom_in: "Auka aðdrátt",
4428
+ zoom_out: "Minnka aðdrátt",
4429
+ reset_zoom: "Endurstilla aðdrátt",
4430
+ support_chat_aria_label: "Þjónustuspjall"
4431
+ }, ba = {
3898
4432
  write_a_message_placeholder: "Rakstiet ziņojumu...",
3899
4433
  your_issue_has_been_resolved: "Jūsu problēma ir atrisināta!",
3900
4434
  new_conversation: "Jauna saruna",
@@ -3981,8 +4515,17 @@ const qe = {
3981
4515
  questions_next: "Tālāk",
3982
4516
  questions_send: "Sūtīt",
3983
4517
  questions_type_answer: "Rakstīšu pats",
3984
- questions_answer_placeholder: "Ierakstiet savu atbildi…"
3985
- }, ra = {
4518
+ questions_answer_placeholder: "Ierakstiet savu atbildi…",
4519
+ close_conversation_title: "Aizvērt sarunu",
4520
+ close_conversation_description: "Vai tiešām vēlaties aizvērt šo sarunu?",
4521
+ close_conversation_cancel: "Nē",
4522
+ close_conversation_confirm: "Jā",
4523
+ dialog_close: "Aizvērt",
4524
+ zoom_in: "Pietuvināt",
4525
+ zoom_out: "Attālināt",
4526
+ reset_zoom: "Atiestatīt tālummaiņu",
4527
+ support_chat_aria_label: "Atbalsta tērzēšana"
4528
+ }, va = {
3986
4529
  write_a_message_placeholder: "Parašykite žinutę...",
3987
4530
  your_issue_has_been_resolved: "Jūsų problema išspręsta!",
3988
4531
  new_conversation: "Naujas pokalbis",
@@ -4069,8 +4612,17 @@ const qe = {
4069
4612
  questions_next: "Toliau",
4070
4613
  questions_send: "Siųsti",
4071
4614
  questions_type_answer: "Parašysiu pats",
4072
- questions_answer_placeholder: "Parašykite savo atsakymą…"
4073
- }, _a = {
4615
+ questions_answer_placeholder: "Parašykite savo atsakymą…",
4616
+ close_conversation_title: "Uždaryti pokalbį",
4617
+ close_conversation_description: "Ar tikrai norite uždaryti šį pokalbį?",
4618
+ close_conversation_cancel: "Ne",
4619
+ close_conversation_confirm: "Taip",
4620
+ dialog_close: "Uždaryti",
4621
+ zoom_in: "Priartinti",
4622
+ zoom_out: "Nutolinti",
4623
+ reset_zoom: "Atstatyti mastelį",
4624
+ support_chat_aria_label: "Pagalbos pokalbis"
4625
+ }, fa = {
4074
4626
  write_a_message_placeholder: "Schreift eng Noriicht...",
4075
4627
  your_issue_has_been_resolved: "Äert Problem gouf geléist!",
4076
4628
  new_conversation: "Nei Konversatioun",
@@ -4157,8 +4709,17 @@ const qe = {
4157
4709
  questions_next: "Weider",
4158
4710
  questions_send: "Schécken",
4159
4711
  questions_type_answer: "Ech schreiwen et selwer",
4160
- questions_answer_placeholder: "Schreift Är Äntwert…"
4161
- }, la = {
4712
+ questions_answer_placeholder: "Schreift Är Äntwert…",
4713
+ close_conversation_title: "Konversatioun zoumaachen",
4714
+ close_conversation_description: "Wëllt Dir dës Konversatioun wierklech zoumaachen?",
4715
+ close_conversation_cancel: "Nee",
4716
+ close_conversation_confirm: "Jo",
4717
+ dialog_close: "Zoumaachen",
4718
+ zoom_in: "Erazoomen",
4719
+ zoom_out: "Erauszoomen",
4720
+ reset_zoom: "Zoom zrécksetzen",
4721
+ support_chat_aria_label: "Support-Chat"
4722
+ }, ya = {
4162
4723
  write_a_message_placeholder: "Ikteb messaġġ...",
4163
4724
  your_issue_has_been_resolved: "Il-problema tiegħek ġiet riżolta!",
4164
4725
  new_conversation: "Konversazzjoni ġdida",
@@ -4245,8 +4806,17 @@ const qe = {
4245
4806
  questions_next: "Li jmiss",
4246
4807
  questions_send: "Ibgħat",
4247
4808
  questions_type_answer: "Nikteb jien",
4248
- questions_answer_placeholder: "Ikteb it-tweġiba tiegħek…"
4249
- }, ca = {
4809
+ questions_answer_placeholder: "Ikteb it-tweġiba tiegħek…",
4810
+ close_conversation_title: "Agħlaq il-konversazzjoni",
4811
+ close_conversation_description: "Żgur li trid tagħlaq din il-konversazzjoni?",
4812
+ close_conversation_cancel: "Le",
4813
+ close_conversation_confirm: "Iva",
4814
+ dialog_close: "Agħlaq",
4815
+ zoom_in: "Kabbar",
4816
+ zoom_out: "Ċekken",
4817
+ reset_zoom: "Irrisettja ż-zoom",
4818
+ support_chat_aria_label: "Chat ta’ appoġġ"
4819
+ }, wa = {
4250
4820
  write_a_message_placeholder: "Skriv en melding...",
4251
4821
  your_issue_has_been_resolved: "Saken din er løst!",
4252
4822
  new_conversation: "Ny samtale",
@@ -4333,8 +4903,17 @@ const qe = {
4333
4903
  questions_next: "Neste",
4334
4904
  questions_send: "Send",
4335
4905
  questions_type_answer: "Jeg skriver det selv",
4336
- questions_answer_placeholder: "Skriv svaret ditt…"
4337
- }, pa = {
4906
+ questions_answer_placeholder: "Skriv svaret ditt…",
4907
+ close_conversation_title: "Lukk samtale",
4908
+ close_conversation_description: "Er du sikker på at du vil lukke denne samtalen?",
4909
+ close_conversation_cancel: "Nei",
4910
+ close_conversation_confirm: "Ja",
4911
+ dialog_close: "Lukk",
4912
+ zoom_in: "Zoom inn",
4913
+ zoom_out: "Zoom ut",
4914
+ reset_zoom: "Tilbakestill zoom",
4915
+ support_chat_aria_label: "Support-chat"
4916
+ }, ja = {
4338
4917
  write_a_message_placeholder: "Napíšte správu...",
4339
4918
  your_issue_has_been_resolved: "Váš problém bol vyriešený!",
4340
4919
  new_conversation: "Nová konverzácia",
@@ -4421,86 +5000,96 @@ const qe = {
4421
5000
  questions_next: "Ďalej",
4422
5001
  questions_send: "Odoslať",
4423
5002
  questions_type_answer: "Napíšem to sám",
4424
- questions_answer_placeholder: "Napíšte svoju odpoveď…"
4425
- }, H = {
4426
- ar: qe,
4427
- bn: Ee,
4428
- bg: Pe,
4429
- cs: Te,
4430
- da: Ae,
4431
- de: Ie,
4432
- el: Me,
4433
- en: De,
4434
- es: Ne,
4435
- et: sa,
4436
- fi: Ke,
4437
- fil: Re,
4438
- fr: Le,
4439
- hi: Fe,
4440
- hr: ta,
4441
- hu: na,
4442
- is: oa,
4443
- it: Oe,
4444
- ja: Ue,
4445
- ko: Be,
4446
- lb: _a,
4447
- lt: ra,
4448
- lv: ia,
4449
- mt: la,
4450
- nb: ca,
4451
- nl: Ve,
4452
- no: He,
4453
- pl: Ge,
4454
- pt: We,
4455
- ro: $e,
4456
- ru: Je,
4457
- sk: pa,
4458
- sv: Ze,
4459
- th: Ye,
4460
- tr: Xe,
4461
- ur: Qe,
4462
- vi: ea,
4463
- "zh-cn": aa
4464
- }, da = Object.keys(H);
4465
- function ma(i) {
4466
- return da.includes(i);
5003
+ questions_answer_placeholder: "Napíšte svoju odpoveď…",
5004
+ close_conversation_title: "Uzavrieť konverzáciu",
5005
+ close_conversation_description: "Naozaj chcete túto konverzáciu uzavrieť?",
5006
+ close_conversation_cancel: "Nie",
5007
+ close_conversation_confirm: "Áno",
5008
+ dialog_close: "Zavrieť",
5009
+ zoom_in: "Priblížiť",
5010
+ zoom_out: "Oddialiť",
5011
+ reset_zoom: "Obnoviť priblíženie",
5012
+ support_chat_aria_label: "Chat podpory"
5013
+ }, Y = {
5014
+ ar: Oe,
5015
+ bn: Ue,
5016
+ bg: Be,
5017
+ cs: Ve,
5018
+ da: He,
5019
+ de: We,
5020
+ el: Ze,
5021
+ en: J,
5022
+ es: Ge,
5023
+ et: ha,
5024
+ fi: Je,
5025
+ fil: $e,
5026
+ fr: Ye,
5027
+ hi: Qe,
5028
+ hr: ma,
5029
+ hu: ga,
5030
+ is: ka,
5031
+ it: Xe,
5032
+ ja: ea,
5033
+ ko: aa,
5034
+ lb: fa,
5035
+ lt: va,
5036
+ lv: ba,
5037
+ mt: ya,
5038
+ nb: wa,
5039
+ nl: ta,
5040
+ no: sa,
5041
+ pl: oa,
5042
+ pt: na,
5043
+ ro: ia,
5044
+ ru: _a,
5045
+ sk: ja,
5046
+ sv: ra,
5047
+ th: la,
5048
+ tr: ca,
5049
+ ur: pa,
5050
+ vi: da,
5051
+ "zh-cn": ua
5052
+ }, Sa = Object.keys(Y);
5053
+ function za(i) {
5054
+ return Sa.includes(i);
4467
5055
  }
4468
- const ua = /* @__PURE__ */ new Set(["ar", "ur"]);
4469
- function Ra(i) {
4470
- return ua.has(i);
5056
+ const Ca = /* @__PURE__ */ new Set(["ar", "ur"]);
5057
+ function Ja(i) {
5058
+ return Ca.has(i);
4471
5059
  }
4472
- function ha(i) {
4473
- return ma(i) ? i : "en";
5060
+ function xa(i) {
5061
+ return za(i) ? i : "en";
4474
5062
  }
4475
- function ga(i, a, s, n) {
5063
+ function qa(i, e, t, o) {
4476
5064
  var l;
4477
- const r = ((l = s == null ? void 0 : s[a]) == null ? void 0 : l[i]) || H[a][i];
4478
- return n ? r.replace(
5065
+ const r = ((l = t == null ? void 0 : t[e]) == null ? void 0 : l[i]) || Y[e][i] || J[i] || i;
5066
+ return o ? r.replace(
4479
5067
  /\{(\w+)\}/g,
4480
- (t, e) => e in n ? String(n[e]) : t
5068
+ (s, a) => a in o ? String(o[a]) : s
4481
5069
  ) : r;
4482
5070
  }
4483
- function ka(i, a, s) {
4484
- return ga(
4485
- a,
4486
- ha(i.language),
5071
+ function Ea(i, e, t) {
5072
+ return qa(
5073
+ e,
5074
+ xa(i.language),
4487
5075
  i.translationOverrides,
4488
- s
5076
+ t
4489
5077
  );
4490
5078
  }
4491
- class ba {
5079
+ class Aa {
4492
5080
  constructor({
4493
- config: a,
4494
- api: s,
4495
- contactCtx: n,
5081
+ config: e,
5082
+ api: t,
5083
+ contactCtx: o,
4496
5084
  storageCtx: r,
4497
- sessionsPollingIntervalSeconds: l
5085
+ sessionsPollingIntervalSeconds: l,
5086
+ sharedSessions: s
4498
5087
  }) {
4499
- this.sessionsRefresher = new B(), this.persistedSessionId = null, this.sessionState = new w({
5088
+ this.sessionsRefresher = new G(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new S({
4500
5089
  session: null,
4501
5090
  isCreatingSession: !1,
4502
5091
  isResolvingSession: !1
4503
- }), this.sessionsState = new w({
5092
+ }), this.sessionsState = new S({
4504
5093
  data: [],
4505
5094
  cursor: void 0,
4506
5095
  isLastPage: !1,
@@ -4510,14 +5099,25 @@ class ba {
4510
5099
  */
4511
5100
  isInitialFetchLoading: !0
4512
5101
  }), this.registerActiveSessionPersistence = () => {
4513
- const t = this.storageCtx;
4514
- t && this.sessionState.subscribe(({ session: e }) => {
4515
- const o = e != null && e.isOpened ? e.id : null;
4516
- if (o === this.persistedSessionId || !o && this.persistedSessionId === null) return;
4517
- this.persistedSessionId = o, (o ? t.setActiveSessionId(o) : t.clearActiveSessionId()).catch((c) => {
4518
- h.warn("failed to persist the active session", {
4519
- error: c instanceof Error ? c.message : String(c)
4520
- });
5102
+ this.storageCtx && (this.stopPersistingSession = this.sessionState.subscribe(
5103
+ this.persistSession
5104
+ ));
5105
+ }, this.restoreActiveSessionTracking = () => {
5106
+ var a;
5107
+ (a = this.stopPersistingSession) == null || a.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5108
+ }, this.trackActiveSession = (a) => {
5109
+ var n;
5110
+ (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = a.sessionState.subscribe(
5111
+ this.persistSession
5112
+ ), this.persistSession(a.sessionState.get());
5113
+ }, this.persistSession = ({ session: a }) => {
5114
+ const n = this.storageCtx;
5115
+ if (!n) return;
5116
+ const c = a != null && a.isOpened ? a.id : null;
5117
+ if (c === this.persistedSessionId || !c && this.persistedSessionId === null) return;
5118
+ this.persistedSessionId = c, (c ? n.setActiveSessionId(c) : n.clearActiveSessionId()).catch((_) => {
5119
+ k.warn("failed to persist the active session", {
5120
+ error: _ instanceof Error ? _.message : String(_)
4521
5121
  });
4522
5122
  });
4523
5123
  }, this.getLastActiveSessionId = async () => {
@@ -4528,373 +5128,431 @@ class ba {
4528
5128
  return null;
4529
5129
  }
4530
5130
  }, this.reset = async () => {
4531
- this.sessionState.reset();
5131
+ this.sessionAbortController.abort(), this.sessionAbortController = new AbortController(), this.sessionState.reset();
4532
5132
  }, this.registerSessionsRefresherWrapper = () => {
4533
- var t;
5133
+ var a;
4534
5134
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
4535
- (t = this.contactCtx.state.get().contact) != null && t.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: e }) => {
4536
- e != null && e.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
4537
- });
5135
+ (a = this.contactCtx.state.get().contact) != null && a.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5136
+ ({ contact: n }) => {
5137
+ n != null && n.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
5138
+ }
5139
+ );
4538
5140
  }, this.registerSessionsRefresher = () => {
4539
5141
  this.sessionsRefresher.startPolling(async () => {
4540
5142
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
4541
5143
  }, this.sessionsPollingIntervalSeconds * 1e3);
5144
+ }, this.dispose = ({ clearActiveSession: a = !1 } = {}) => {
5145
+ var n, c;
5146
+ if (this.sessionsRefresher.reset(), this.sessionAbortController.abort(), (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = void 0, (c = this.stopWaitingForContact) == null || c.call(this), this.stopWaitingForContact = void 0, this.sessionState.reset(), a && this.storageCtx)
5147
+ return this.persistedSessionId = null, this.storageCtx.clearActiveSessionId().catch((d) => {
5148
+ k.warn("failed to clear the replaced session", {
5149
+ error: d instanceof Error ? d.message : String(d)
5150
+ });
5151
+ });
4542
5152
  }, this.getParsedCustomData = () => Object.fromEntries(
4543
5153
  Object.entries(this.config.sessionCustomData || {}).map(
4544
- ([t, e]) => {
4545
- var o;
4546
- return typeof e == "string" ? [t, e] : typeof e == "boolean" ? [t, e] : typeof e == "number" ? [t, e] : [t, ((o = V(() => JSON.stringify(e))) == null ? void 0 : o.data) || ""];
5154
+ ([a, n]) => {
5155
+ var c;
5156
+ return typeof n == "string" ? [a, n] : typeof n == "boolean" ? [a, n] : typeof n == "number" ? [a, n] : [a, ((c = $(() => JSON.stringify(n))) == null ? void 0 : c.data) || ""];
4547
5157
  }
4548
5158
  )
4549
5159
  ), this.createSession = async () => {
5160
+ const { signal: a } = this.sessionAbortController;
4550
5161
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
4551
5162
  try {
4552
- const t = await this.requestSession();
4553
- if (t.session) return t.session;
4554
- if (t.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
4555
- const e = await this.requestSession();
4556
- return e.session ? e.session : (h.error("failed to create session", e.error), null);
5163
+ const n = await this.requestSession(a);
5164
+ if (a.aborted) return null;
5165
+ if (n.session) return n.session;
5166
+ if (n.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
5167
+ if (a.aborted) return null;
5168
+ const c = await this.requestSession(a);
5169
+ return a.aborted ? null : c.session ? c.session : (k.error("failed to create session", c.error), null);
4557
5170
  }
4558
- return h.error("failed to create session", t.error), null;
4559
- } catch (t) {
4560
- return h.error("failed to create session", t), null;
5171
+ return k.error("failed to create session", n.error), null;
5172
+ } catch (n) {
5173
+ return a.aborted || k.error("failed to create session", n), null;
4561
5174
  } finally {
4562
- this.sessionState.setPartial({ isCreatingSession: !1 });
5175
+ a.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
4563
5176
  }
4564
- }, this.requestSession = async () => {
4565
- var d, p, u;
4566
- const t = (d = this.contactCtx.state.get().contact) == null ? void 0 : d.externalId, e = {
5177
+ }, this.requestSession = async (a) => {
5178
+ var u, m, g;
5179
+ const n = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, c = {
4567
5180
  ...this.getParsedCustomData(),
4568
- ...t ? { external_id: t } : {}
5181
+ ...n ? { external_id: n } : {}
4569
5182
  }, {
4570
- data: o,
5183
+ data: d,
4571
5184
  error: _,
4572
- response: c
4573
- } = await this.api.createSession({
4574
- customData: Object.keys(e).length > 0 ? e : void 0
4575
- });
4576
- if (!o) return { session: null, status: c == null ? void 0 : c.status, error: _ };
4577
- this.sessionState.setPartial({ session: o });
5185
+ response: p
5186
+ } = await this.api.createSession(
5187
+ {
5188
+ customData: Object.keys(c).length > 0 ? c : void 0
5189
+ },
5190
+ a
5191
+ );
5192
+ if (a.aborted || !d)
5193
+ return { session: null, status: p == null ? void 0 : p.status, error: _ };
5194
+ this.sessionState.setPartial({ session: d });
4578
5195
  try {
4579
- (u = (p = this.config.hooks) == null ? void 0 : p.onSessionCreated) == null || u.call(p, { session: o });
4580
- } catch (m) {
4581
- h.error("onSessionCreated hook failed", m);
5196
+ (g = (m = this.config.hooks) == null ? void 0 : m.onSessionCreated) == null || g.call(m, { session: d });
5197
+ } catch (v) {
5198
+ k.error("onSessionCreated hook failed", v);
4582
5199
  }
4583
- return { session: o, status: c.status, error: void 0 };
5200
+ return { session: d, status: p.status, error: void 0 };
4584
5201
  }, this.loadMoreSessions = async () => {
4585
5202
  if (this.sessionsState.get().isLastPage) return;
4586
- const { data: t } = await this.getSessions({
5203
+ const { data: a } = await this.getSessions({
4587
5204
  cursor: this.sessionsState.get().cursor
4588
5205
  });
4589
- if (t) {
4590
- const o = [...this.sessionsState.get().data, ...t.items].filter(
4591
- (_, c, d) => c === d.findIndex((p) => _.id === p.id)
5206
+ if (a) {
5207
+ const c = [...this.sessionsState.get().data, ...a.items].filter(
5208
+ (d, _, p) => _ === p.findIndex((u) => d.id === u.id)
4592
5209
  );
4593
5210
  this.sessionsState.setPartial({
4594
- data: o,
4595
- cursor: t.next || void 0,
4596
- isLastPage: t.next === null
5211
+ data: c,
5212
+ cursor: a.next || void 0,
5213
+ isLastPage: a.next === null
4597
5214
  });
4598
5215
  }
4599
- }, this.getSessions = async ({ cursor: t }) => {
4600
- var o, _;
4601
- if (!((o = this.contactCtx.state.get().contact) != null && o.token)) return { data: null };
4602
- const e = (_ = this.contactCtx.state.get().contact) == null ? void 0 : _.externalId;
5216
+ }, this.getSessions = async ({ cursor: a }) => {
5217
+ var c, d;
5218
+ if (!((c = this.contactCtx.state.get().contact) != null && c.token)) return { data: null };
5219
+ const n = (d = this.contactCtx.state.get().contact) == null ? void 0 : d.externalId;
4603
5220
  return await this.api.getSessions({
4604
- cursor: t,
4605
- filters: e ? {
4606
- external_id: e
5221
+ cursor: a,
5222
+ filters: n ? {
5223
+ external_id: n
4607
5224
  } : {}
4608
5225
  });
4609
- }, this.setSessions = (t) => {
4610
- const e = [...t, ...this.sessionsState.get().data].filter(
4611
- (o, _, c) => _ === c.findIndex((d) => o.id === d.id)
5226
+ }, this.setSessions = (a) => {
5227
+ const n = [...a, ...this.sessionsState.get().data].filter(
5228
+ (c, d, _) => d === _.findIndex((p) => c.id === p.id)
4612
5229
  );
4613
- this.sessionsState.setPartial({ data: e });
5230
+ this.sessionsState.setPartial({ data: n });
4614
5231
  }, this.refreshSessions = async () => {
4615
- const { data: t } = await this.getSessions({ cursor: void 0 });
4616
- t && this.setSessions(t.items);
5232
+ const { data: a } = await this.getSessions({ cursor: void 0 });
5233
+ a && this.setSessions(a.items);
4617
5234
  }, this.resolveSession = async () => {
4618
- const t = this.sessionState.get().session;
4619
- if (!t || !t.isOpened)
5235
+ const a = this.sessionState.get().session;
5236
+ if (!a || !a.isOpened)
4620
5237
  return { success: !1, error: "Session is not opened" };
4621
5238
  this.sessionState.setPartial({ isResolvingSession: !0 });
4622
- const { data: e, error: o } = await this.api.resolveSession({
4623
- session_id: t.id
5239
+ const { signal: n } = this.sessionAbortController, c = await this.api.resolveSession({ session_id: a.id }, n).catch((p) => {
5240
+ if (n.aborted) return null;
5241
+ throw p;
4624
5242
  });
4625
- return e ? (this.sessionState.setPartial({ session: e, isResolvingSession: !1 }), { success: !0, data: e }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: o });
4626
- }, this.createStateCheckpoint = async (t) => {
4627
- var _;
4628
- const e = (_ = this.sessionState.get().session) == null ? void 0 : _.id;
4629
- if (!e) return;
4630
- const { data: o } = await this.api.createStateCheckpoint({
4631
- session_id: e,
4632
- payload: t
5243
+ if (!c || n.aborted)
5244
+ return { success: !1, error: "Session was reset" };
5245
+ const { data: d, error: _ } = c;
5246
+ return d ? (this.sessionState.setPartial({ session: d, isResolvingSession: !1 }), { success: !0, data: d }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: _ });
5247
+ }, this.createStateCheckpoint = async (a) => {
5248
+ var d;
5249
+ const n = (d = this.sessionState.get().session) == null ? void 0 : d.id;
5250
+ if (!n) return;
5251
+ const { data: c } = await this.api.createStateCheckpoint({
5252
+ session_id: n,
5253
+ payload: a
4633
5254
  });
4634
- return o != null && o.success ? { success: !0 } : { success: !1 };
4635
- }, this.config = a, this.api = s, this.contactCtx = n, this.storageCtx = r, this.sessionsPollingIntervalSeconds = l, this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
5255
+ return c != null && c.success ? { success: !0 } : { success: !1 };
5256
+ }, this.config = e, this.api = t, this.contactCtx = o, this.storageCtx = r, this.sessionsPollingIntervalSeconds = l, s ? this.sessionsState = s : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
4636
5257
  }
4637
5258
  }
4638
- const fa = (i, a, { sendsPageContext: s }) => {
4639
- const n = wa(i), r = s && a.mentions && a.mentions.length > 0 ? { mentions: a.mentions.map(va) } : void 0, l = s && (a.clientContext || r) ? { ...n, ...a.clientContext, ...r } : n;
5259
+ const Pa = (i, e, { sendsPageContext: t }) => {
5260
+ const o = Ma(i), r = t && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(Ta) } : void 0, l = t && (e.clientContext || r) ? { ...o, ...e.clientContext, ...r } : o, s = e.connectionRequestId ? {
5261
+ ...l,
5262
+ opencx__connection_request_id: e.connectionRequestId
5263
+ } : l, a = e.withPageEntity === !1 && s && "entity" in s ? Ia(s, "entity") : s;
4640
5264
  return {
4641
- clientContext: a.withPageEntity === !1 && l && "entity" in l ? ya(l, "entity") : l,
5265
+ clientContext: e.background ? { ...a, opencx__background: !0 } : a,
4642
5266
  custom_data: {
4643
5267
  ...i.messageCustomData || {},
4644
- ...a.customData || {}
5268
+ ...e.customData || {}
4645
5269
  }
4646
5270
  };
4647
- }, va = ({ type: i, id: a, title: s, meta: n }) => ({
5271
+ }, Ta = ({ type: i, id: e, title: t, meta: o }) => ({
4648
5272
  type: i,
4649
- id: a,
4650
- title: s,
4651
- ...n ? { meta: n } : {}
4652
- }), ya = (i, a) => {
4653
- const { [a]: s, ...n } = i;
4654
- return Object.keys(n).length > 0 ? n : void 0;
4655
- }, wa = (i) => {
5273
+ id: e,
5274
+ title: t,
5275
+ ...o ? { meta: o } : {}
5276
+ }), Ia = (i, e) => {
5277
+ const { [e]: t, ...o } = i;
5278
+ return Object.keys(o).length > 0 ? o : void 0;
5279
+ }, Ma = (i) => {
4656
5280
  if (typeof i.context != "function") return i.context;
4657
5281
  try {
4658
5282
  return i.context();
4659
- } catch (a) {
4660
- h.error("context getter threw; sending without context", a);
5283
+ } catch (e) {
5284
+ k.error("context getter threw; sending without context", e);
4661
5285
  return;
4662
5286
  }
4663
- }, ja = (i) => {
4664
- const a = i.features;
4665
- if (!a) return;
4666
- const s = {};
4667
- return a.preamble !== void 0 && (s.preamble = a.preamble), a.inlineUi !== void 0 && (s.inline_ui = a.inlineUi), a.pageContext !== void 0 && (s.page_context = a.pageContext), a.clientTools !== void 0 && (s.client_tools = a.clientTools), Object.keys(s).length > 0 ? s : void 0;
4668
- }, Sa = ({
5287
+ }, Da = (i) => {
5288
+ const e = i.features;
5289
+ if (!e) return;
5290
+ const t = {};
5291
+ 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;
5292
+ }, Na = ({
4669
5293
  config: i,
4670
- input: a,
4671
- uuid: s,
4672
- sessionId: n,
5294
+ input: e,
5295
+ uuid: t,
5296
+ sessionId: o,
4673
5297
  content: r,
4674
5298
  initialMessages: l,
4675
- sendsPageContext: t
4676
- }) => ({
4677
- uuid: s,
4678
- bot_token: i.token,
4679
- headers: i.headers,
4680
- query_params: i.queryParams,
4681
- body_properties: i.bodyProperties,
4682
- session_id: n,
4683
- content: r,
4684
- attachments: a.attachments,
4685
- ...fa(i, a, { sendsPageContext: t }),
4686
- language: i.language,
4687
- features: ja(i),
4688
- exit_mode_prompt: a.exitModePrompt,
4689
- initial_messages: l.length > 0 ? l.map((e) => ({ uuid: e.id, content: e.data.message })) : void 0
4690
- }), z = class z {
5299
+ sendsPageContext: s
5300
+ }) => {
5301
+ var a, n, c, d, _, p, u, m;
5302
+ return {
5303
+ uuid: t,
5304
+ bot_token: i.token,
5305
+ headers: i.headers,
5306
+ query_params: i.queryParams,
5307
+ body_properties: i.bodyProperties,
5308
+ session_id: o,
5309
+ content: r,
5310
+ attachments: e.attachments,
5311
+ ...Pa(i, e, { sendsPageContext: s }),
5312
+ language: i.language,
5313
+ features: Da(i),
5314
+ presentation: i.presentation,
5315
+ capabilities: [
5316
+ (a = i.capabilities) == null ? void 0 : a.connections,
5317
+ (n = i.capabilities) == null ? void 0 : n.structuredQuestions,
5318
+ (c = i.capabilities) == null ? void 0 : c.richReplies,
5319
+ (d = i.capabilities) == null ? void 0 : d.pageEffects
5320
+ ].some((g) => g !== void 0) ? {
5321
+ connections: (_ = i.capabilities) == null ? void 0 : _.connections,
5322
+ structured_questions: (p = i.capabilities) == null ? void 0 : p.structuredQuestions,
5323
+ rich_replies: (u = i.capabilities) == null ? void 0 : u.richReplies,
5324
+ page_effects: (m = i.capabilities) == null ? void 0 : m.pageEffects
5325
+ } : void 0,
5326
+ exit_mode_prompt: e.exitModePrompt,
5327
+ initial_messages: l.length > 0 ? l.map((g) => ({ uuid: g.id, content: g.data.message })) : void 0
5328
+ };
5329
+ }, C = class C {
4691
5330
  constructor({
4692
- config: a,
4693
- api: s,
4694
- sessionCtx: n,
5331
+ config: e,
5332
+ api: t,
5333
+ sessionCtx: o,
4695
5334
  contactCtx: r,
4696
5335
  streaming: l,
4697
- sendsPageContext: t
5336
+ sendsPageContext: s,
5337
+ getClientCapabilities: a,
5338
+ getRequestConfig: n,
5339
+ isStreaming: c,
5340
+ getSendsPageContext: d
4698
5341
  }) {
4699
- this.state = new w({
5342
+ this.state = new S({
4700
5343
  messages: [],
4701
5344
  isSendingMessage: !1,
4702
5345
  isSendingMessageToAI: !1,
5346
+ settledAgentUserMessageId: null,
4703
5347
  lastAIResMightSolveUserIssue: !1,
4704
5348
  isInitialFetchLoading: !1
5349
+ }), this.draftState = new S({
5350
+ text: "",
5351
+ mentions: []
4705
5352
  }), this.agentHandlers = null, this.bufferedAgentSends = [], this.sendMessageAbortController = new AbortController(), this.messageIdsDispatchedToOnMessageReceivedHook = /* @__PURE__ */ new Set(), this.sentTextHistory = [], this.reset = () => {
4706
- this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [];
4707
- }, this.rememberSentText = (e) => {
4708
- const o = e.trim();
4709
- !o || this.sentTextHistory.at(-1) === o || (this.sentTextHistory.push(o), this.sentTextHistory.length > z.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
4710
- }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (e) => {
4711
- this.agentHandlers = e;
4712
- const o = this.bufferedAgentSends;
4713
- this.bufferedAgentSends = [], o.forEach((_) => {
4714
- z.dispatchToEngine(e, _);
5353
+ this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [], this.draftState.reset();
5354
+ }, this.rememberSentText = (_) => {
5355
+ const p = _.trim();
5356
+ !p || this.sentTextHistory.at(-1) === p || (this.sentTextHistory.push(p), this.sentTextHistory.length > C.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
5357
+ }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (_) => {
5358
+ this.agentHandlers = _;
5359
+ const p = this.bufferedAgentSends;
5360
+ this.bufferedAgentSends = [], p.forEach((u) => {
5361
+ C.dispatchToEngine(_, u);
4715
5362
  });
4716
- }, this.unregisterAgentHandlers = (e) => {
4717
- this.agentHandlers === e && (this.agentHandlers = null);
4718
- }, this.dispatchToOnMessageReceivedHook = (e) => {
4719
- var _, c;
4720
- if (e.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(e.id))
5363
+ }, this.unregisterAgentHandlers = (_) => {
5364
+ this.agentHandlers === _ && (this.agentHandlers = null);
5365
+ }, this.dispatchToOnMessageReceivedHook = (_) => {
5366
+ var u, m;
5367
+ if (_.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(_.id))
4721
5368
  return;
4722
- const o = this.sessionCtx.sessionState.get().session;
4723
- o && (this.messageIdsDispatchedToOnMessageReceivedHook.add(e.id), (c = (_ = this.config.hooks) == null ? void 0 : _.onMessageReceived) == null || c.call(_, { message: e, session: o }));
4724
- }, this.markAsDispatchedToOnMessageReceivedHook = (e) => {
4725
- e.forEach(
4726
- (o) => this.messageIdsDispatchedToOnMessageReceivedHook.add(o)
5369
+ const p = this.sessionCtx.sessionState.get().session;
5370
+ p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(_.id), (m = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || m.call(u, { message: _, session: p }));
5371
+ }, this.markAsDispatchedToOnMessageReceivedHook = (_) => {
5372
+ _.forEach(
5373
+ (p) => this.messageIdsDispatchedToOnMessageReceivedHook.add(p)
4727
5374
  );
4728
5375
  }, this.buildPersistentInitialMessages = () => {
4729
- var o, _;
4730
- return !((o = this.sessionCtx.sessionState.get().session) != null && o.id) && this.state.get().messages.length === 0 && ((_ = this.config.advancedInitialMessages) == null ? void 0 : _.some((c) => c.persistent)) ? (this.config.advancedInitialMessages || []).filter((c) => c.persistent).map(
4731
- (c) => ({
5376
+ var p, u;
5377
+ 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(
5378
+ (m) => ({
4732
5379
  id: x(),
4733
5380
  component: "bot_message",
4734
5381
  type: "AI",
4735
5382
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4736
- data: { message: c.message },
5383
+ data: { message: m.message },
4737
5384
  agent: this.config.bot ? { ...this.config.bot, isAi: !0, id: null } : void 0
4738
5385
  })
4739
5386
  ) : [];
4740
5387
  }, this.ensureSessionId = async () => {
4741
- var e, o;
4742
- if (!((e = this.sessionCtx.sessionState.get().session) != null && e.id)) {
5388
+ var _, p;
5389
+ if (!((_ = this.sessionCtx.sessionState.get().session) != null && _.id)) {
4743
5390
  if (!await this.sessionCtx.createSession()) return null;
4744
5391
  this.sessionCtx.refreshSessions();
4745
5392
  }
4746
- return ((o = this.sessionCtx.sessionState.get().session) == null ? void 0 : o.id) ?? null;
4747
- }, this.rollbackOptimisticMessages = (e) => {
4748
- if (e.length === 0) return;
4749
- const o = new Set(e), _ = this.state.get().messages, c = _.filter((d) => !o.has(d.id));
4750
- c.length !== _.length && this.state.setPartial({ messages: c });
4751
- }, this.notifySendAccepted = (e) => {
4752
- var o;
5393
+ return ((p = this.sessionCtx.sessionState.get().session) == null ? void 0 : p.id) ?? null;
5394
+ }, this.rollbackOptimisticMessages = (_) => {
5395
+ if (_.length === 0) return;
5396
+ const p = new Set(_), u = this.state.get().messages, m = u.filter((g) => !p.has(g.id));
5397
+ m.length !== u.length && this.state.setPartial({ messages: m });
5398
+ }, this.notifySendAccepted = (_) => {
5399
+ var p;
4753
5400
  try {
4754
- (o = e.onAccepted) == null || o.call(e);
4755
- } catch (_) {
4756
- h.error("send acceptance callback failed", _);
5401
+ (p = _.onAccepted) == null || p.call(_);
5402
+ } catch (u) {
5403
+ k.error("send acceptance callback failed", u);
4757
5404
  }
4758
- }, this.stageUserTurn = async (e, { pending: o }) => {
4759
- const _ = this.buildUserMessage(e);
4760
- if (!_) return null;
4761
- const c = o ? { ..._, pending: !0 } : _, d = this.buildPersistentInitialMessages(), p = [
4762
- ...d.map((m) => m.id),
4763
- c.id
5405
+ }, this.stageUserTurn = async (_, { pending: p }) => {
5406
+ const u = this.buildUserMessage(_);
5407
+ if (!u) return null;
5408
+ const m = p ? { ...u, pending: !0 } : u, g = this.buildPersistentInitialMessages(), v = [
5409
+ ...g.map((b) => b.id),
5410
+ m.id
4764
5411
  ];
4765
5412
  this.state.setPartial({
4766
- messages: [...d, ...this.state.get().messages, c]
5413
+ messages: [
5414
+ ...g,
5415
+ ...this.state.get().messages,
5416
+ ...m.background ? [] : [m]
5417
+ ]
4767
5418
  });
4768
- let u;
5419
+ let f;
4769
5420
  try {
4770
- u = await this.ensureSessionId();
4771
- } catch (m) {
4772
- throw this.rollbackOptimisticMessages(p), m;
5421
+ f = await this.ensureSessionId();
5422
+ } catch (b) {
5423
+ throw this.rollbackOptimisticMessages(v), b;
4773
5424
  }
4774
- return u ? { sessionId: u, userMessage: c, initialMessages: d } : (this.rollbackOptimisticMessages(p), null);
4775
- }, this.buildQueuedUserMessage = (e) => {
4776
- var c;
4777
- const o = this.buildUserMessage(e);
4778
- if (!o) return null;
4779
- const _ = (c = this.sessionCtx.sessionState.get().session) == null ? void 0 : c.id;
4780
- return _ ? { sessionId: _, userMessage: { ...o, pending: !0 } } : null;
4781
- }, this.buildUserMessage = (e) => {
4782
- var o;
4783
- return !e.content.trim() && (!e.attachments || e.attachments.length === 0) ? (h.warn("cannot send an empty message of no content or attachments"), null) : this.toUserMessage(
4784
- e.content.trim(),
4785
- e.attachments || void 0,
4786
- this.sendsPageContext ? z.markedElementNames(e.clientContext) : void 0,
4787
- this.sendsPageContext && ((o = e.mentions) != null && o.length) ? e.mentions : void 0
4788
- );
4789
- }, this.appendUserMessageIfAbsent = (e) => {
4790
- const o = this.state.get().messages;
4791
- o.some((_) => _.id === e.id) || this.state.setPartial({ messages: [...o, e] });
4792
- }, this.markUserMessageDelivered = (e) => {
4793
- const o = this.state.get().messages, _ = o.findIndex(
4794
- (p) => p.id === e && p.type === "USER" && p.pending
5425
+ return f ? { sessionId: f, userMessage: m, initialMessages: g } : (this.rollbackOptimisticMessages(v), null);
5426
+ }, this.buildQueuedUserMessage = (_) => {
5427
+ var m;
5428
+ const p = this.buildUserMessage(_);
5429
+ if (!p) return null;
5430
+ const u = (m = this.sessionCtx.sessionState.get().session) == null ? void 0 : m.id;
5431
+ return u ? { sessionId: u, userMessage: { ...p, pending: !0 } } : null;
5432
+ }, this.buildUserMessage = (_) => {
5433
+ var p;
5434
+ return !_.content.trim() && (!_.attachments || _.attachments.length === 0) ? (k.warn("cannot send an empty message of no content or attachments"), null) : {
5435
+ ...this.toUserMessage(
5436
+ _.content.trim(),
5437
+ _.attachments || void 0,
5438
+ this.sendsPageContext ? C.markedElementNames(_.clientContext) : void 0,
5439
+ this.sendsPageContext && ((p = _.mentions) != null && p.length) ? _.mentions : void 0
5440
+ ),
5441
+ ..._.background ? { background: !0 } : {}
5442
+ };
5443
+ }, this.appendUserMessageIfAbsent = (_) => {
5444
+ if (_.background) return;
5445
+ const p = this.state.get().messages;
5446
+ p.some((u) => u.id === _.id) || this.state.setPartial({ messages: [...p, _] });
5447
+ }, this.markUserMessageDelivered = (_) => {
5448
+ const p = this.state.get().messages, u = p.findIndex(
5449
+ (v) => v.id === _ && v.type === "USER" && v.pending
4795
5450
  );
4796
- if (_ === -1) return;
4797
- const c = o[_];
4798
- if (!c || c.type !== "USER") return;
4799
- const d = [...o];
4800
- d[_] = { ...c, pending: !1 }, this.state.setPartial({
4801
- messages: d
5451
+ if (u === -1) return;
5452
+ const m = p[u];
5453
+ if (!m || m.type !== "USER") return;
5454
+ const g = [...p];
5455
+ g[u] = { ...m, pending: !1 }, this.state.setPartial({
5456
+ messages: g
4802
5457
  });
4803
- }, this.sendMessage = async (e) => {
4804
- var _, c, d, p, u;
5458
+ }, this.sendMessage = async (_) => {
5459
+ var u, m, g, v, f;
4805
5460
  if (this.streaming) {
4806
5461
  if (!this.agentHandlers) {
4807
- this.bufferedAgentSends.push(e);
5462
+ this.bufferedAgentSends.push(_);
4808
5463
  return;
4809
5464
  }
4810
- await this.agentHandlers.send(e);
5465
+ await this.agentHandlers.send(_);
4811
5466
  return;
4812
5467
  }
4813
- let o;
5468
+ let p;
4814
5469
  try {
4815
- const m = this.sessionCtx.sessionState.get().session, j = (m == null ? void 0 : m.assignee.kind) === "ai", y = this.state.get().isSendingMessageToAI, k = this.state.get().messages.at(-1);
4816
- if (this.blocksSendWhileAwaitingReply && (y || // If last message is from user, then bot response did not arrive yet
4817
- j && (k == null ? void 0 : k.type) === "USER")) {
4818
- h.warn("cannot send messages while awaiting AI response");
5470
+ const b = this.sessionCtx.sessionState.get().session, R = (b == null ? void 0 : b.assignee.kind) === "ai", X = this.state.get().isSendingMessageToAI, E = this.state.get().messages.at(-1);
5471
+ if (this.blocksSendWhileAwaitingReply && (X || // If last message is from user, then bot response did not arrive yet
5472
+ R && (E == null ? void 0 : E.type) === "USER" && E.id !== this.state.get().settledAgentUserMessageId)) {
5473
+ k.warn("cannot send messages while awaiting AI response");
4819
5474
  return;
4820
5475
  }
4821
- this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), o = this.sendMessageAbortController, this.state.setPartial({
5476
+ this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), p = this.sendMessageAbortController, this.state.setPartial({
4822
5477
  lastAIResMightSolveUserIssue: !1,
4823
5478
  isSendingMessage: !0,
4824
- isSendingMessageToAI: !!j || !m
5479
+ isSendingMessageToAI: !!R || !b
4825
5480
  });
4826
- const f = await this.stageUserTurn(e, { pending: !1 });
4827
- if (!f) return;
4828
- const { sessionId: W, userMessage: I, initialMessages: $ } = f;
4829
- this.notifySendAccepted(e);
4830
- const { data: b } = await this.api.sendMessage(
4831
- Sa({
4832
- config: this.config,
4833
- input: e,
4834
- uuid: I.id,
4835
- sessionId: W,
4836
- content: I.content,
4837
- initialMessages: $,
5481
+ const K = await this.stageUserTurn(_, { pending: !1 });
5482
+ if (!K) return;
5483
+ const { sessionId: ee, userMessage: L, initialMessages: ae } = K;
5484
+ this.notifySendAccepted(_);
5485
+ const { data: y } = await this.api.sendMessage(
5486
+ Na({
5487
+ config: {
5488
+ ...this.getRequestConfig(),
5489
+ capabilities: this.getClientCapabilities()
5490
+ },
5491
+ input: _,
5492
+ uuid: L.id,
5493
+ sessionId: ee,
5494
+ content: L.content,
5495
+ initialMessages: ae,
4838
5496
  sendsPageContext: this.sendsPageContext
4839
5497
  }),
4840
- o.signal
5498
+ p.signal
4841
5499
  );
4842
- if (b != null && b.success) {
4843
- const S = this.toBotMessage(b);
4844
- if (S) {
4845
- const q = this.state.get().messages;
4846
- if (!!q.some(
4847
- (Z) => Z.id === S.id
5500
+ if (y != null && y.success) {
5501
+ const z = this.toBotMessage(y);
5502
+ if (z) {
5503
+ const A = this.state.get().messages;
5504
+ if (!!A.some(
5505
+ (te) => te.id === z.id
4848
5506
  )) {
4849
5507
  this.state.setPartial({
4850
- lastAIResMightSolveUserIssue: ((_ = b.autopilotResponse) == null ? void 0 : _.mightSolveUserIssue) || ((c = b.uiResponse) == null ? void 0 : c.mightSolveUserIssue)
5508
+ lastAIResMightSolveUserIssue: ((u = y.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((m = y.uiResponse) == null ? void 0 : m.mightSolveUserIssue)
4851
5509
  });
4852
5510
  return;
4853
5511
  }
4854
5512
  this.state.setPartial({
4855
- messages: [...q, S],
4856
- lastAIResMightSolveUserIssue: ((d = b.autopilotResponse) == null ? void 0 : d.mightSolveUserIssue) || ((p = b.uiResponse) == null ? void 0 : p.mightSolveUserIssue)
4857
- }), this.dispatchToOnMessageReceivedHook(S);
5513
+ messages: [...A, z],
5514
+ lastAIResMightSolveUserIssue: ((g = y.autopilotResponse) == null ? void 0 : g.mightSolveUserIssue) || ((v = y.uiResponse) == null ? void 0 : v.mightSolveUserIssue)
5515
+ }), this.dispatchToOnMessageReceivedHook(z);
4858
5516
  }
4859
- b.session && this.sessionCtx.sessionState.setPartial({ session: b.session });
5517
+ y.session && this.sessionCtx.sessionState.setPartial({ session: y.session });
4860
5518
  } else {
4861
- const S = this.toBotErrorMessage(
4862
- ((u = b == null ? void 0 : b.error) == null ? void 0 : u.message) || ka(this.config, "turn_failed_message")
4863
- ), q = this.state.get().messages;
5519
+ const z = this.toBotErrorMessage(
5520
+ ((f = y == null ? void 0 : y.error) == null ? void 0 : f.message) || Ea(this.config, "turn_failed_message")
5521
+ ), A = this.state.get().messages;
4864
5522
  this.state.setPartial({
4865
- messages: [...q, S]
5523
+ messages: [...A, z]
4866
5524
  });
4867
5525
  }
4868
- } catch (m) {
4869
- o != null && o.signal.aborted || h.error("failed to send message", m);
5526
+ } catch (b) {
5527
+ p != null && p.signal.aborted || k.error("failed to send message", b);
4870
5528
  } finally {
4871
- o != null && o.signal.aborted || this.state.setPartial({
5529
+ p != null && p.signal.aborted || this.state.setPartial({
4872
5530
  isSendingMessage: !1,
4873
5531
  isSendingMessageToAI: !1
4874
5532
  });
4875
5533
  }
4876
- }, this.toUserMessage = (e, o, _, c) => {
4877
- const d = (() => {
4878
- const p = this.contactCtx.state.get().extraCollectedData;
4879
- return this.state.get().messages.length === 0 && p && Object.keys(p).length > 0 ? `${Object.entries(p).filter(([m, g]) => !!g).map(([m, g]) => `${m}: ${g}`).join(`
5534
+ }, this.toUserMessage = (_, p, u, m) => {
5535
+ const g = (() => {
5536
+ const v = this.contactCtx.state.get().extraCollectedData;
5537
+ return this.state.get().messages.length === 0 && v && Object.keys(v).length > 0 ? `${Object.entries(v).filter(([b, w]) => !!w).map(([b, w]) => `${b}: ${w}`).join(`
4880
5538
  `)}
4881
5539
 
4882
- ${e}` : e;
5540
+ ${_}` : _;
4883
5541
  })();
4884
5542
  return {
4885
5543
  id: x(),
4886
5544
  type: "USER",
4887
- content: d,
4888
- attachments: o,
4889
- markedElements: _,
4890
- mentions: c,
5545
+ content: g,
5546
+ attachments: p,
5547
+ markedElements: u,
5548
+ mentions: m,
4891
5549
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
4892
5550
  };
4893
- }, this.toBotMessage = (e) => {
4894
- var o;
4895
- return e.success && e.autopilotResponse ? {
5551
+ }, this.toBotMessage = (_) => {
5552
+ var p;
5553
+ return _.success && _.autopilotResponse ? {
4896
5554
  type: "AI",
4897
- id: e.autopilotResponse.id || x(),
5555
+ id: _.autopilotResponse.id || x(),
4898
5556
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4899
5557
  component: "bot_message",
4900
5558
  agent: this.config.bot ? {
@@ -4906,35 +5564,49 @@ ${e}` : e;
4906
5564
  id: null
4907
5565
  } : void 0,
4908
5566
  data: {
4909
- message: e.autopilotResponse.value.content,
4910
- action: (o = e.uiResponse) != null && o.value.name ? {
4911
- name: e.uiResponse.value.name,
4912
- data: e.uiResponse.value.request_response
5567
+ message: _.autopilotResponse.value.content,
5568
+ action: (p = _.uiResponse) != null && p.value.name ? {
5569
+ name: _.uiResponse.value.name,
5570
+ data: _.uiResponse.value.request_response
4913
5571
  } : void 0
4914
5572
  }
4915
5573
  } : null;
4916
- }, this.toBotErrorMessage = (e) => ({
5574
+ }, this.toBotErrorMessage = (_) => ({
4917
5575
  type: "AI",
4918
5576
  id: x(),
4919
5577
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4920
5578
  component: "bot_message",
4921
5579
  data: {
4922
- message: e,
5580
+ message: _,
4923
5581
  variant: "error",
4924
5582
  action: void 0
4925
5583
  }
4926
- }), this.config = a, this.api = s, this.sessionCtx = n, this.contactCtx = r, this.streaming = l, this.sendsPageContext = t;
5584
+ }), this.config = e, this.getClientCapabilities = a ?? (() => this.getRequestConfig().capabilities), this.api = t, this.sessionCtx = o, this.contactCtx = r, this.isStreaming = c ?? (() => l), this.getRequestConfig = n ?? (() => this.config), this.getSendsPageContext = d ?? (() => s);
5585
+ }
5586
+ /**
5587
+ * Current transport choice. The org or this embed may request polling
5588
+ * independently of the server's agent version.
5589
+ */
5590
+ get streaming() {
5591
+ return this.isStreaming();
5592
+ }
5593
+ get sendsPageContext() {
5594
+ return this.getSendsPageContext();
4927
5595
  }
4928
5596
  /** Hand a send to the streaming engine; its failure can never propagate. */
4929
- static dispatchToEngine(a, s) {
5597
+ static dispatchToEngine(e, t) {
4930
5598
  try {
4931
- Promise.resolve(a.send(s)).catch((n) => {
4932
- h.error("streaming send failed", n);
5599
+ Promise.resolve(e.send(t)).catch((o) => {
5600
+ k.error("streaming send failed", o);
4933
5601
  });
4934
- } catch (n) {
4935
- h.error("streaming send failed", n);
5602
+ } catch (o) {
5603
+ k.error("streaming send failed", o);
4936
5604
  }
4937
5605
  }
5606
+ get hasPendingAgentWork() {
5607
+ var e, t;
5608
+ return this.bufferedAgentSends.length > 0 || (((t = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : t.call(e)) ?? !1);
5609
+ }
4938
5610
  /**
4939
5611
  * Defensive read of `clientContext.page_marks` → the user bubble's context
4940
5612
  * chips: each mark contributes the element it was placed on, the note the
@@ -4942,24 +5614,24 @@ ${e}` : e;
4942
5614
  * the same presentation the composer showed, thumbnail included). Entries
4943
5615
  * without a usable name are dropped.
4944
5616
  */
4945
- static markedElementNames(a) {
4946
- const s = a == null ? void 0 : a.page_marks;
4947
- if (!Array.isArray(s)) return;
4948
- const n = s.flatMap((r) => {
5617
+ static markedElementNames(e) {
5618
+ const t = e == null ? void 0 : e.page_marks;
5619
+ if (!Array.isArray(t)) return;
5620
+ const o = t.flatMap((r) => {
4949
5621
  if (typeof r != "object" || r === null) return [];
4950
- const l = r.elements, t = Array.isArray(l) ? l[0] : void 0, e = typeof t == "object" && t !== null && "name" in t ? t.name : void 0;
4951
- if (typeof e != "string" || e.length === 0) return [];
4952
- const o = r.note, _ = r.snapshotUrl;
5622
+ const l = r.elements, s = Array.isArray(l) ? l[0] : void 0, a = typeof s == "object" && s !== null && "name" in s ? s.name : void 0;
5623
+ if (typeof a != "string" || a.length === 0) return [];
5624
+ const n = r.note, c = r.snapshotUrl;
4953
5625
  return [
4954
5626
  {
4955
- name: e,
4956
- ...typeof o == "string" && o.length > 0 ? { note: o } : {},
4957
- ...typeof _ == "string" && _.length > 0 ? { snapshotUrl: _ } : {},
5627
+ name: a,
5628
+ ...typeof n == "string" && n.length > 0 ? { note: n } : {},
5629
+ ...typeof c == "string" && c.length > 0 ? { snapshotUrl: c } : {},
4958
5630
  mark: r
4959
5631
  }
4960
5632
  ];
4961
5633
  });
4962
- return n.length > 0 ? n : void 0;
5634
+ return o.length > 0 ? o : void 0;
4963
5635
  }
4964
5636
  /**
4965
5637
  * The blocking engine refuses a send while the AI reply is pending unless
@@ -4969,136 +5641,137 @@ ${e}` : e;
4969
5641
  return !this.streaming && this.config.disableSendingWhenAwaitingAIReply !== !1;
4970
5642
  }
4971
5643
  };
4972
- z.SENT_TEXT_HISTORY_MAX = 50;
4973
- let M = z;
4974
- class za {
4975
- constructor({
4976
- config: a,
4977
- contactCtx: s,
4978
- sessionCtx: n,
4979
- resetChat: r
4980
- }) {
4981
- var l, t;
4982
- this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
5644
+ C.SENT_TEXT_HISTORY_MAX = 50;
5645
+ let D = C;
5646
+ class Ra {
5647
+ constructor(e) {
5648
+ var t, o;
5649
+ this.widget = e, this.subscriptions = [], this.disposed = !1, this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
4983
5650
  if (!this.shouldRestoreLastSession) {
4984
5651
  this.didReadStoredSession = !0;
4985
5652
  return;
4986
5653
  }
4987
- this.sessionCtx.getLastActiveSessionId().then((e) => {
4988
- this.restorableSessionId = e;
5654
+ this.sessionCtx.getLastActiveSessionId().then((r) => {
5655
+ this.restorableSessionId = r;
4989
5656
  }).finally(() => {
4990
5657
  this.didReadStoredSession = !0, this.routeFromSessions(this.sessionCtx.sessionsState.get());
4991
5658
  });
4992
5659
  }, this.registerRoutingListener = () => {
4993
- this.contactCtx.state.subscribe(({ contact: e }) => {
4994
- var o;
4995
- e != null && e.token && this.state.get().screen === "welcome" && this.state.setPartial({
4996
- screen: (o = this.config.router) != null && o.chatScreenOnly ? "chat" : "sessions"
4997
- });
4998
- }), this.sessionCtx.sessionsState.subscribe(this.routeFromSessions);
5660
+ this.subscriptions.push(
5661
+ this.contactCtx.state.subscribe(({ contact: r }) => {
5662
+ var l;
5663
+ r != null && r.token && this.state.get().screen === "welcome" && this.state.setPartial({
5664
+ screen: (l = this.config.router) != null && l.chatScreenOnly ? "chat" : "sessions"
5665
+ });
5666
+ })
5667
+ ), this.subscriptions.push(
5668
+ this.sessionCtx.sessionsState.subscribe(this.routeFromSessions)
5669
+ );
4999
5670
  }, this.routeFromSessions = ({
5000
- isInitialFetchLoading: e,
5001
- data: o
5671
+ isInitialFetchLoading: r,
5672
+ data: l
5002
5673
  }) => {
5003
- var _, c, d, p, u;
5004
- if (this.didReadStoredSession) {
5005
- if (this.restorableSessionId && !((_ = this.sessionCtx.sessionState.get().session) != null && _.id)) {
5006
- const m = o.find(
5007
- (g) => g.id === this.restorableSessionId && g.isOpened
5674
+ var s, a, n, c, d;
5675
+ if (!(this.disposed || !this.didReadStoredSession)) {
5676
+ if (this.restorableSessionId && !((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
5677
+ const _ = l.find(
5678
+ (p) => p.id === this.restorableSessionId && p.isOpened
5008
5679
  );
5009
- if (m) {
5010
- this.restorableSessionId = null, this.toChatScreen(m.id);
5680
+ if (_) {
5681
+ this.restorableSessionId = null, this.toChatScreen(_.id);
5011
5682
  return;
5012
5683
  }
5013
- if (e) return;
5684
+ if (r) return;
5014
5685
  this.restorableSessionId = null;
5015
5686
  }
5016
- if ((c = this.config.router) != null && c.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5687
+ if ((a = this.config.router) != null && a.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5017
5688
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
5018
- !((d = this.sessionCtx.sessionState.get().session) != null && d.id)) {
5019
- const m = (p = o.find((g) => g.isOpened)) == null ? void 0 : p.id;
5020
- return m ? this.toChatScreen(m) : void 0;
5689
+ !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
5690
+ const _ = (c = l.find((p) => p.isOpened)) == null ? void 0 : c.id;
5691
+ return _ ? this.toChatScreen(_) : void 0;
5021
5692
  }
5022
- o.length || ((u = this.config.router) == null ? void 0 : u.goToChatIfNoSessions) !== !1 && !e && this.state.get().screen !== "chat" && this.toChatScreen();
5693
+ l.length || ((d = this.config.router) == null ? void 0 : d.goToChatIfNoSessions) !== !1 && !r && this.state.get().screen !== "chat" && this.toChatScreen();
5023
5694
  }
5695
+ }, this.dispose = () => {
5696
+ this.disposed = !0, this.subscriptions.forEach((r) => r()), this.subscriptions = [], this.navigateConversation = void 0;
5024
5697
  }, this.toSessionsScreen = () => {
5025
- this.resetChat(), this.state.setPartial({ screen: "sessions" });
5026
- }, this.toChatScreen = (e) => {
5027
- var _, c;
5698
+ this.navigateConversation || this.resetChat(), this.state.setPartial({ screen: "sessions" });
5699
+ }, this.toChatScreen = (r) => {
5700
+ var s, a;
5701
+ if (this.navigateConversation) return this.navigateConversation(r);
5028
5702
  this.resetChat();
5029
- let o;
5030
- if (e) {
5031
- if (o = this.sessionCtx.sessionsState.get().data.find((d) => d.id === e), !o) return;
5032
- this.sessionCtx.sessionState.setPartial({ session: o });
5703
+ let l;
5704
+ if (r) {
5705
+ if (l = this.sessionCtx.sessionsState.get().data.find((n) => n.id === r), !l) return;
5706
+ this.sessionCtx.sessionState.setPartial({ session: l });
5033
5707
  }
5034
- this.state.setPartial({ screen: "chat" }), (c = (_ = this.config.hooks) == null ? void 0 : _.onNavigateToChat) == null || c.call(_, {
5035
- session: o
5036
- });
5037
- }, this.config = a, this.contactCtx = s, this.sessionCtx = n, this.resetChat = r, this.state = new w({
5038
- screen: this.contactCtx.shouldCollectData() ? "welcome" : (l = this.config.router) != null && l.chatScreenOnly ? "chat" : "sessions"
5039
- }), this.shouldRestoreLastSession = ((t = this.config.router) == null ? void 0 : t.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5708
+ return this.state.setPartial({ screen: "chat" }), (a = (s = this.config.hooks) == null ? void 0 : s.onNavigateToChat) == null || a.call(s, { session: l }), this.widget;
5709
+ }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new S({
5710
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : (t = this.config.router) != null && t.chatScreenOnly ? "chat" : "sessions"
5711
+ }), this.shouldRestoreLastSession = ((o = this.config.router) == null ? void 0 : o.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5040
5712
  }
5041
5713
  }
5042
- class xa {
5714
+ class Ka {
5043
5715
  constructor({
5044
- storage: a,
5045
- config: s
5716
+ storage: e,
5717
+ config: t
5046
5718
  }) {
5047
5719
  this.KEYS = {
5048
- contactToken: (n) => `opencx-widget:org-token-${n}:contact-token`,
5049
- externalContactId: (n) => `opencx-widget:org-token-${n}:external-contact-id`,
5050
- companionPreference: (n, r) => `opencx-widget:org-token-${n}:companion-${r}`,
5051
- activeSession: (n) => `opencx-widget:org-token-${n}:active-session`
5052
- }, this.setContactToken = async (n) => {
5053
- await this.storage.set(this.KEYS.contactToken(this.config.token), n);
5720
+ contactToken: (o) => `opencx-widget:org-token-${o}:contact-token`,
5721
+ externalContactId: (o) => `opencx-widget:org-token-${o}:external-contact-id`,
5722
+ companionPreference: (o, r) => `opencx-widget:org-token-${o}:companion-${r}`,
5723
+ activeSession: (o) => `opencx-widget:org-token-${o}:active-session`
5724
+ }, this.setContactToken = async (o) => {
5725
+ await this.storage.set(this.KEYS.contactToken(this.config.token), o);
5054
5726
  }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken(this.config.token)), this.clearContactToken = async () => {
5055
5727
  await this.storage.remove(this.KEYS.contactToken(this.config.token));
5056
- }, this.activeSessionKey = () => this.KEYS.activeSession(this.config.token), this.getActiveSessionId = async () => this.storage.get(this.activeSessionKey()), this.setActiveSessionId = async (n) => {
5057
- await this.storage.set(this.activeSessionKey(), n);
5728
+ }, this.activeSessionKey = () => this.KEYS.activeSession(this.config.token), this.getActiveSessionId = async () => this.storage.get(this.activeSessionKey()), this.setActiveSessionId = async (o) => {
5729
+ await this.storage.set(this.activeSessionKey(), o);
5058
5730
  }, this.clearActiveSessionId = async () => {
5059
5731
  await this.storage.remove(this.activeSessionKey());
5060
- }, this.setExternalContactId = async (n) => {
5061
- await this.storage.set(this.KEYS.externalContactId(this.config.token), n);
5062
- }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.companionKey = (n) => this.KEYS.companionPreference(this.config.token, n), this.getFiniteNumber = async (n) => {
5063
- const r = await this.storage.get(n);
5732
+ }, this.setExternalContactId = async (o) => {
5733
+ await this.storage.set(this.KEYS.externalContactId(this.config.token), o);
5734
+ }, 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) => {
5735
+ const r = await this.storage.get(o);
5064
5736
  if (r === null) return null;
5065
5737
  const l = Number(r);
5066
5738
  return Number.isFinite(l) ? l : null;
5067
- }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (n) => {
5068
- Number.isFinite(n) && await this.storage.set(this.companionKey("pill-offset-x"), String(n));
5069
- }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (n) => {
5070
- Number.isFinite(n) && await this.storage.set(this.companionKey("sidebar-width"), String(n));
5739
+ }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (o) => {
5740
+ Number.isFinite(o) && await this.storage.set(this.companionKey("pill-offset-x"), String(o));
5741
+ }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (o) => {
5742
+ Number.isFinite(o) && await this.storage.set(this.companionKey("sidebar-width"), String(o));
5071
5743
  }, this.getCompanionSidebarSide = async () => {
5072
- const n = await this.storage.get(this.companionKey("sidebar-side"));
5073
- return n === "left" || n === "right" ? n : null;
5074
- }, this.setCompanionSidebarSide = async (n) => {
5075
- await this.storage.set(this.companionKey("sidebar-side"), n);
5744
+ const o = await this.storage.get(this.companionKey("sidebar-side"));
5745
+ return o === "left" || o === "right" ? o : null;
5746
+ }, this.setCompanionSidebarSide = async (o) => {
5747
+ await this.storage.set(this.companionKey("sidebar-side"), o);
5076
5748
  }, this.getCompanionLayout = async () => {
5077
- const n = await this.storage.get(this.companionKey("layout"));
5078
- return n === "compact" || n === "sidebar" ? n : null;
5079
- }, this.setCompanionLayout = async (n) => {
5080
- await this.storage.set(this.companionKey("layout"), n);
5749
+ const o = await this.storage.get(this.companionKey("layout"));
5750
+ return o === "compact" || o === "sidebar" ? o : null;
5751
+ }, this.setCompanionLayout = async (o) => {
5752
+ await this.storage.set(this.companionKey("layout"), o);
5081
5753
  }, this.getCompanionSidebarMode = async () => {
5082
- const n = await this.storage.get(this.companionKey("sidebar-mode"));
5083
- return n === "docked" || n === "floating" ? n : null;
5084
- }, this.setCompanionSidebarMode = async (n) => {
5085
- await this.storage.set(this.companionKey("sidebar-mode"), n);
5086
- }, this.storage = a, this.config = s;
5754
+ const o = await this.storage.get(this.companionKey("sidebar-mode"));
5755
+ return o === "docked" || o === "floating" ? o : null;
5756
+ }, this.setCompanionSidebarMode = async (o) => {
5757
+ await this.storage.set(this.companionKey("sidebar-mode"), o);
5758
+ }, this.storage = e, this.config = t;
5087
5759
  }
5088
5760
  }
5089
- function Ca({
5761
+ function La({
5090
5762
  org: i,
5091
- agent: a
5763
+ agent: e
5092
5764
  }) {
5093
- return a ? {
5094
- name: a.name,
5095
- avatarUrl: a.avatar_url,
5096
- streaming: a.streaming,
5765
+ return e ? {
5766
+ name: e.name,
5767
+ avatarUrl: e.avatar_url,
5768
+ streaming: e.streaming,
5769
+ ...e.presentation ? { presentation: e.presentation } : {},
5097
5770
  features: {
5098
- dictation: a.features.dictation,
5099
- attachments: a.features.attachments,
5100
- pageContext: a.features.page_context,
5101
- clientTools: a.features.client_tools
5771
+ dictation: e.features.dictation,
5772
+ attachments: e.features.attachments,
5773
+ pageContext: e.features.page_context,
5774
+ clientTools: e.features.client_tools
5102
5775
  }
5103
5776
  } : {
5104
5777
  name: i.name,
@@ -5112,55 +5785,85 @@ function Ca({
5112
5785
  }
5113
5786
  };
5114
5787
  }
5115
- function A(i, a) {
5116
- return i && a !== !1;
5788
+ function M(i, e) {
5789
+ return i && e !== !1;
5117
5790
  }
5118
- function qa(i, a) {
5119
- const s = a.features;
5791
+ function Fa(i, e) {
5792
+ const t = e.features;
5120
5793
  return {
5121
- dictation: A(i.features.dictation, s == null ? void 0 : s.dictation),
5794
+ dictation: M(i.features.dictation, t == null ? void 0 : t.dictation),
5122
5795
  attachments: i.features.attachments,
5123
- pageContext: A(
5796
+ pageContext: M(
5124
5797
  i.features.pageContext,
5125
- s == null ? void 0 : s.pageContext
5798
+ t == null ? void 0 : t.pageContext
5126
5799
  ),
5127
- clientTools: A(
5800
+ clientTools: M(
5128
5801
  i.features.clientTools,
5129
- s == null ? void 0 : s.clientTools
5802
+ t == null ? void 0 : t.clientTools
5130
5803
  )
5131
5804
  };
5132
5805
  }
5133
- class Ea extends Error {
5134
- constructor(a, s, n) {
5135
- super(s), this.name = "WidgetInitializationError", this.code = a, this.details = n;
5806
+ class Oa extends Error {
5807
+ constructor(e, t, o) {
5808
+ super(t), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5136
5809
  }
5137
5810
  }
5138
- const v = class v {
5811
+ const j = class j {
5139
5812
  constructor({
5140
- config: a,
5141
- storage: s,
5142
- modes: n,
5143
- org: r,
5144
- agent: l
5813
+ config: e,
5814
+ storage: t,
5815
+ getClientCapabilities: o,
5816
+ getRequestConfig: r,
5817
+ modes: l,
5818
+ org: s,
5819
+ agent: a,
5820
+ parent: n
5145
5821
  }) {
5146
- if (this.modes = [], this.resetChat = () => {
5147
- this.sessionCtx.reset(), this.messageCtx.reset();
5148
- }, this.reconcileAfterStream = (t) => this.activeSessionPollingCtx.reconcileAfterStream(t), !v.pollingIntervalsSeconds)
5822
+ if (this.modes = [], this.disposed = !1, this.createConversation = () => {
5823
+ const c = new j({
5824
+ config: {
5825
+ ...this.config,
5826
+ router: {
5827
+ ...this.config.router,
5828
+ restoreLastSession: !1,
5829
+ chatScreenOnly: !1,
5830
+ goToChatIfNoSessions: !1
5831
+ }
5832
+ },
5833
+ modes: this.modes,
5834
+ org: this.org,
5835
+ agent: this.agent,
5836
+ parent: this,
5837
+ getRequestConfig: this.getRequestConfig,
5838
+ getClientCapabilities: this.getClientCapabilities
5839
+ });
5840
+ return c.routerCtx.state.setPartial({
5841
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : "chat"
5842
+ }), c;
5843
+ }, this.releaseConversation = () => this.dispose(), this.dispose = ({ clearActiveSession: c = !1 } = {}) => {
5844
+ if (this.disposed) return;
5845
+ this.disposed = !0, this.routerCtx.dispose(), this.activeSessionPollingCtx.dispose();
5846
+ const d = this.sessionCtx.dispose({ clearActiveSession: c });
5847
+ return this.messageCtx.reset(), this.uploadCtx.reset(), this.dictationCtx.stop(), d;
5848
+ }, this.resetChat = () => {
5849
+ this.sessionCtx.reset(), this.messageCtx.reset(), this.uploadCtx.reset();
5850
+ }, this.reconcileAfterStream = (c) => this.activeSessionPollingCtx.reconcileAfterStream(c), !j.pollingIntervalsSeconds)
5149
5851
  throw Error(
5150
5852
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
5151
5853
  );
5152
- this.config = a, this.org = r, this.agent = l, this.features = qa(l, a), this.api = new R({ config: a }), this.storageCtx = s ? new xa({ storage: s, config: a }) : void 0, this.modes = n, this.contactCtx = new ne({
5854
+ this.config = e, this.getRequestConfig = r ?? (() => this.config), this.getClientCapabilities = o, this.org = s, this.agent = a, this.api = (n == null ? void 0 : n.api) ?? new B({ config: e }), this.storageCtx = (n == null ? void 0 : n.storageCtx) ?? (t ? new Ka({ storage: t, config: e }) : void 0), this.modes = l, this.contactCtx = (n == null ? void 0 : n.contactCtx) ?? new ge({
5153
5855
  api: this.api,
5154
5856
  config: this.config,
5155
5857
  storageCtx: this.storageCtx
5156
- }), this.sessionCtx = new ba({
5858
+ }), this.sessionCtx = new Aa({
5157
5859
  config: this.config,
5158
5860
  api: this.api,
5159
5861
  contactCtx: this.contactCtx,
5160
5862
  // Remembers the open conversation so a reload can return to it.
5161
- storageCtx: this.storageCtx,
5162
- sessionsPollingIntervalSeconds: v.pollingIntervalsSeconds.sessions
5163
- }), this.messageCtx = new M({
5863
+ storageCtx: n ? void 0 : this.storageCtx,
5864
+ sharedSessions: n == null ? void 0 : n.sessionCtx.sessionsState,
5865
+ sessionsPollingIntervalSeconds: j.pollingIntervalsSeconds.sessions
5866
+ }), this.messageCtx = new D({
5164
5867
  config: this.config,
5165
5868
  api: this.api,
5166
5869
  sessionCtx: this.sessionCtx,
@@ -5168,123 +5871,139 @@ const v = class v {
5168
5871
  // Streaming orgs send their turns over the AI SDK transport instead of
5169
5872
  // the blocking bot-chat send.
5170
5873
  streaming: this.streaming,
5171
- sendsPageContext: this.features.pageContext
5172
- }), this.csatCtx = new oe({
5874
+ isStreaming: () => this.streaming,
5875
+ sendsPageContext: this.features.pageContext,
5876
+ getSendsPageContext: () => this.features.pageContext,
5877
+ getClientCapabilities: o,
5878
+ getRequestConfig: r
5879
+ }), this.uploadCtx = new ke(this.api), this.csatCtx = new be({
5173
5880
  api: this.api,
5174
5881
  sessionCtx: this.sessionCtx,
5175
5882
  messageCtx: this.messageCtx
5176
- }), this.dictationCtx = new Ce({
5883
+ }), this.dictationCtx = new Fe({
5177
5884
  api: this.api,
5178
5885
  config: this.config
5179
- }), this.activeSessionPollingCtx = new se({
5886
+ }), this.activeSessionPollingCtx = new he({
5180
5887
  api: this.api,
5181
5888
  config: this.config,
5182
5889
  sessionCtx: this.sessionCtx,
5183
5890
  messageCtx: this.messageCtx,
5184
- sessionPollingIntervalSeconds: v.pollingIntervalsSeconds.session
5185
- }), this.routerCtx = new za({
5186
- config: this.config,
5187
- contactCtx: this.contactCtx,
5188
- sessionCtx: this.sessionCtx,
5189
- resetChat: this.resetChat
5190
- });
5891
+ sessionPollingIntervalSeconds: j.pollingIntervalsSeconds.session
5892
+ }), this.routerCtx = new Ra(this);
5893
+ }
5894
+ get streaming() {
5895
+ var e, t;
5896
+ return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (t = this.messageCtx) != null && t.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming !== !1;
5191
5897
  }
5192
5898
  /**
5193
- * Whether turns stream (the v5 agent-chat engine) or use the blocking
5194
- * bot-chat send. Decided by the SERVER per org; the single source for every
5195
- * "which engine?" decision in the widget.
5899
+ * The org's features narrowed by this embed's `config.features` — the
5900
+ * answers the UI asks for, resolved against the current options.
5196
5901
  */
5197
- get streaming() {
5198
- return this.agent.streaming;
5902
+ get features() {
5903
+ return Fa(this.agent, this.getRequestConfig());
5199
5904
  }
5200
5905
  };
5201
- v.pollingIntervalsSeconds = null, v.initialize = async ({
5202
- config: a,
5203
- storage: s
5906
+ j.pollingIntervalsSeconds = null, j.initialize = async ({
5907
+ config: e,
5908
+ storage: t,
5909
+ getClientCapabilities: o,
5910
+ getRequestConfig: r
5204
5911
  }) => {
5205
- var r, l;
5206
- const n = await new R({
5207
- config: a
5912
+ var s, a;
5913
+ const l = await new B({
5914
+ config: e
5208
5915
  }).getExternalWidgetConfig();
5209
- if (!n.data)
5210
- throw h.error("widget config fetch failed", n.error), new Ea(
5916
+ if (!l.data)
5917
+ throw k.error("widget config fetch failed", l.error), new Oa(
5211
5918
  "config-fetch-failed",
5212
5919
  "Failed to fetch widget config",
5213
- n.error
5920
+ l.error
5214
5921
  );
5215
- return v.pollingIntervalsSeconds = {
5216
- session: ((r = n.data) == null ? void 0 : r.sessionPollingIntervalSeconds) || 10,
5217
- sessions: ((l = n.data) == null ? void 0 : l.sessionsPollingIntervalSeconds) || 60
5218
- }, new v({
5219
- config: a,
5220
- storage: s,
5221
- modes: n.data.modes || [],
5922
+ return j.pollingIntervalsSeconds = {
5923
+ session: ((s = l.data) == null ? void 0 : s.sessionPollingIntervalSeconds) || 10,
5924
+ sessions: ((a = l.data) == null ? void 0 : a.sessionsPollingIntervalSeconds) || 60
5925
+ }, new j({
5926
+ config: e,
5927
+ storage: t,
5928
+ getClientCapabilities: o,
5929
+ getRequestConfig: r,
5930
+ modes: l.data.modes || [],
5222
5931
  org: {
5223
- id: n.data.org.id,
5224
- name: n.data.org.name
5932
+ id: l.data.org.id,
5933
+ name: l.data.org.name
5225
5934
  },
5226
- agent: Ca(n.data)
5935
+ agent: La(l.data)
5227
5936
  });
5228
5937
  };
5229
- let O = v;
5230
- class Ka {
5231
- constructor({ attack: a, release: s }) {
5232
- this.value = 0, this.attack = a, this.release = s;
5938
+ let W = j;
5939
+ function Ya(i, e) {
5940
+ return i ? {
5941
+ streaming: i.streaming && (e == null ? void 0 : e.streaming) !== !1,
5942
+ toolActivity: i.toolActivity === "hidden" || (e == null ? void 0 : e.toolActivity) === "hidden" ? "hidden" : i.toolActivity === "status" || (e == null ? void 0 : e.toolActivity) === "status" ? "status" : "details",
5943
+ reasoning: i.reasoning && (e == null ? void 0 : e.reasoning) !== !1
5944
+ } : e;
5945
+ }
5946
+ class Qa {
5947
+ constructor({ attack: e, release: t }) {
5948
+ this.value = 0, this.attack = e, this.release = t;
5233
5949
  }
5234
- next(a) {
5235
- return this.value += (a - this.value) * (a > this.value ? this.attack : this.release), this.value;
5950
+ next(e) {
5951
+ return this.value += (e - this.value) * (e > this.value ? this.attack : this.release), this.value;
5236
5952
  }
5237
5953
  current() {
5238
5954
  return this.value;
5239
5955
  }
5240
5956
  }
5241
- const P = [
5957
+ const T = [
5242
5958
  "compact",
5243
5959
  "sidebar",
5244
5960
  "fullscreen"
5245
- ], Pa = new Set(
5246
- P
5961
+ ], Ua = new Set(
5962
+ T
5247
5963
  );
5248
- function G(i) {
5249
- return Pa.has(i);
5964
+ function Q(i) {
5965
+ return Ua.has(i);
5250
5966
  }
5251
- function La(i) {
5252
- if (!Array.isArray(i)) return P;
5253
- const a = [], s = /* @__PURE__ */ new Set();
5254
- for (const n of i)
5255
- !G(n) || s.has(n) || (s.add(n), a.push(n));
5256
- return a.length > 0 ? a : P;
5967
+ function Xa(i) {
5968
+ if (!Array.isArray(i)) return T;
5969
+ const e = [], t = /* @__PURE__ */ new Set();
5970
+ for (const o of i)
5971
+ !Q(o) || t.has(o) || (t.add(o), e.push(o));
5972
+ return e.length > 0 ? e : T;
5257
5973
  }
5258
- function Fa(i, a) {
5259
- return G(i) && a.includes(i) ? i : a[0] ?? P[0];
5974
+ function et(i, e) {
5975
+ return Q(i) && e.includes(i) ? i : e[0] ?? T[0];
5260
5976
  }
5261
- function Oa(i, a) {
5262
- return i === "left" || i === "right" ? i : a === "rtl" ? "left" : "right";
5977
+ function at(i, e) {
5978
+ return i === "left" || i === "right" ? i : e === "rtl" ? "left" : "right";
5263
5979
  }
5264
- function Ua(i) {
5980
+ function tt(i) {
5265
5981
  return i === "docked" ? "docked" : "floating";
5266
5982
  }
5267
5983
  export {
5268
- Ka as DictationLevelSmoother,
5269
- w as PrimitiveState,
5270
- O as WidgetCtx,
5271
- Ea as WidgetInitializationError,
5272
- Sa as buildSendMessageBody,
5984
+ pe as ConnectionAttemptUnavailableError,
5985
+ ce as ConnectionRequestExpiredError,
5986
+ Qa as DictationLevelSmoother,
5987
+ S as PrimitiveState,
5988
+ W as WidgetCtx,
5989
+ Oa as WidgetInitializationError,
5990
+ Na as buildSendMessageBody,
5273
5991
  x as genUuid,
5274
- ga as getTranslation,
5275
- Da as isAgentStreamKeepalive,
5276
- te as isExhaustive,
5277
- F as isRecord,
5278
- Ra as isRtlLanguage,
5279
- ma as isSupportedLanguage,
5280
- Na as isTurnSteeredPart,
5281
- h as log,
5282
- La as normalizeCompanionLayouts,
5283
- Fa as resolveCompanionDefaultLayout,
5284
- wa as resolveConfigContext,
5285
- ha as resolveLanguage,
5286
- Ua as resolveSidebarMode,
5287
- Oa as resolveSidebarSide,
5288
- ka as translate
5992
+ qa as getTranslation,
5993
+ Ga as isAgentStreamKeepalive,
5994
+ me as isExhaustive,
5995
+ Z as isRecord,
5996
+ Ja as isRtlLanguage,
5997
+ za as isSupportedLanguage,
5998
+ $a as isTurnSteeredPart,
5999
+ k as log,
6000
+ Xa as normalizeCompanionLayouts,
6001
+ Ya as resolveClientPresentation,
6002
+ et as resolveCompanionDefaultLayout,
6003
+ Ma as resolveConfigContext,
6004
+ xa as resolveLanguage,
6005
+ tt as resolveSidebarMode,
6006
+ at as resolveSidebarSide,
6007
+ Ea as translate
5289
6008
  };
5290
6009
  //# sourceMappingURL=index.js.map