@vettvangur/ai-sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -187,6 +187,24 @@ chat.on('end', ({ reason }) => track('chat_end', reason))
187
187
  await chat.handover({ context: { aiShipment: 'L26000008' }, prefill: { Email: email } })
188
188
  ```
189
189
 
190
+ `@vettvangur/ai-sdk/live-chat/livechat` exports `createLiveChatProvider({ organizationId, clientId,
191
+ groupId })` over LiveChat (livechat.com). `clientId` is a "Web app" client from the LiveChat
192
+ Developer Console with the `customers:own` scope, and chats go to `groupId`, or LiveChat's default
193
+ group without one. It needs the optional peer dependency `@livechat/customer-sdk` and connects only
194
+ when the provider is first used. It reports `no-agents` while LiveChat says the group is offline,
195
+ asks the group's pre-chat form (a header becomes a note, a group chooser routes the chat) and hands
196
+ the answers to the agent as a filled form, sets the visitor's name and email from the form's name
197
+ and email fields (prefill them as `name` and `email`), and gives the agent the handover context as
198
+ session fields. Agents see what the visitor types through `draft`. LiveChat allows a visitor one
199
+ chat, so a second handover starts a new thread in it; the resume token is the chat id. A form with
200
+ any field the window cannot ask, such as a rating, is refused rather than shortened.
201
+
202
+ ```ts
203
+ import { createLiveChatProvider } from '@vettvangur/ai-sdk/live-chat/livechat'
204
+
205
+ const liveChat = createLiveChatProvider({ organizationId, clientId })
206
+ ```
207
+
190
208
  `@vettvangur/ai-sdk/live-chat/aichat` exports `createAiChatLiveProvider({ endpoint, headers })` for
191
209
  sites without a contact centre: agents answer from the Live view of the Vettvangur.AiChat backoffice
192
210
  section. `endpoint` is the prefix the site maps with `MapAiChat`, and `headers` go with every
package/dist/index.js CHANGED
@@ -1497,7 +1497,10 @@ function bindChat(root, options = {}) {
1497
1497
  } catch (caught) {
1498
1498
  const error = caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover failed");
1499
1499
  options.onError?.(error);
1500
- if (started) disconnect();
1500
+ if (started) {
1501
+ disconnect();
1502
+ provider.end().catch(() => void 0);
1503
+ }
1501
1504
  if (!stale()) {
1502
1505
  notify(labels.liveChatFailed, "failed");
1503
1506
  setMode("ai");
@@ -0,0 +1,18 @@
1
+ import { a as AiLiveChatProvider } from "../provider.js";
2
+ //#region src/live-chat/livechat.d.ts
3
+ type AiLiveChatConfig = {
4
+ organizationId: string;
5
+ /** A "Web app" client from the LiveChat Developer Console with the `customers:own` scope. */
6
+ clientId: string;
7
+ /** The group chats go to; LiveChat's default group when not given. */
8
+ groupId?: number;
9
+ };
10
+ /**
11
+ * A live chat provider over LiveChat (livechat.com), through `@livechat/customer-sdk`. The SDK is
12
+ * imported and connected the first time the provider is asked anything, so a page pays for it only
13
+ * when a visitor asks for a person. LiveChat keeps the visitor's identity in the browser and allows
14
+ * them one chat, which a later handover starts a new thread in.
15
+ */
16
+ declare function createLiveChatProvider(config: AiLiveChatConfig): AiLiveChatProvider;
17
+ //#endregion
18
+ export { AiLiveChatConfig, createLiveChatProvider };
@@ -0,0 +1,376 @@
1
+ //#region src/live-chat/livechat.ts
2
+ function on(sdk, method, type, handler) {
3
+ sdk[method](type, handler);
4
+ }
5
+ function chosenOptions(options, answer) {
6
+ if (typeof answer !== "string" || !answer) return [];
7
+ const ids = answer.split(",");
8
+ return options.filter((option) => ids.includes(option.id));
9
+ }
10
+ function surveyField(field) {
11
+ switch (field.type) {
12
+ case "header": return field.label.trim() ? {
13
+ kind: "note",
14
+ text: field.label
15
+ } : null;
16
+ case "name":
17
+ case "email": return {
18
+ kind: "text",
19
+ id: field.id,
20
+ name: field.type,
21
+ label: field.label,
22
+ required: field.required,
23
+ inputType: field.type === "email" ? "email" : "text",
24
+ multiline: false,
25
+ maxLength: null,
26
+ placeholder: null
27
+ };
28
+ case "question":
29
+ case "subject":
30
+ case "textarea": return {
31
+ kind: "text",
32
+ id: field.id,
33
+ name: field.id,
34
+ label: field.label,
35
+ required: field.required,
36
+ inputType: "text",
37
+ multiline: field.type === "textarea",
38
+ maxLength: null,
39
+ placeholder: null
40
+ };
41
+ case "radio":
42
+ case "select":
43
+ case "checkbox":
44
+ case "group_chooser": return {
45
+ kind: "choice",
46
+ id: field.id,
47
+ name: field.id,
48
+ label: field.label,
49
+ required: field.required,
50
+ multiple: field.type === "checkbox",
51
+ choices: field.options.map((option) => ({
52
+ label: option.label,
53
+ value: option.id
54
+ }))
55
+ };
56
+ case "checkbox_for_email": return {
57
+ kind: "toggle",
58
+ id: field.id,
59
+ name: field.id,
60
+ label: field.label,
61
+ required: field.required
62
+ };
63
+ default: throw new Error(`LiveChat pre-chat form has a ${field.type} field the window cannot ask`);
64
+ }
65
+ }
66
+ /** The pre-chat form's fields as the window asks them; a header becomes a note. */
67
+ function surveyFieldsFromForm(form) {
68
+ return form.fields.map(surveyField).filter((field) => field !== null);
69
+ }
70
+ /** The answers as the `filled_form` event LiveChat shows the agent at the top of the chat. */
71
+ function filledFormFields(form, answers) {
72
+ const filled = [];
73
+ for (const field of form.fields) {
74
+ const answer = answers[field.id];
75
+ switch (field.type) {
76
+ case "name":
77
+ case "email":
78
+ case "question":
79
+ case "subject":
80
+ case "textarea":
81
+ if (typeof answer === "string" && answer.trim()) filled.push({
82
+ type: field.type,
83
+ id: field.id,
84
+ label: field.label,
85
+ answer: answer.trim()
86
+ });
87
+ break;
88
+ case "radio":
89
+ case "select": {
90
+ const [option] = chosenOptions(field.options, answer);
91
+ if (option) filled.push({
92
+ type: field.type,
93
+ id: field.id,
94
+ label: field.label,
95
+ answer: {
96
+ id: option.id,
97
+ label: option.label
98
+ }
99
+ });
100
+ break;
101
+ }
102
+ case "checkbox": {
103
+ const options = chosenOptions(field.options, answer);
104
+ if (options.length) filled.push({
105
+ type: "checkbox",
106
+ id: field.id,
107
+ label: field.label,
108
+ answers: options.map((option) => ({
109
+ id: option.id,
110
+ label: option.label
111
+ }))
112
+ });
113
+ break;
114
+ }
115
+ case "group_chooser": {
116
+ const [option] = chosenOptions(field.options, answer);
117
+ if (option) filled.push({
118
+ type: "group_chooser",
119
+ id: field.id,
120
+ label: field.label,
121
+ answer: {
122
+ id: option.id,
123
+ label: option.label,
124
+ groupId: option.groupId
125
+ }
126
+ });
127
+ break;
128
+ }
129
+ case "checkbox_for_email": filled.push({
130
+ type: "checkbox_for_email",
131
+ id: field.id,
132
+ label: field.label,
133
+ answer: answer === true
134
+ });
135
+ }
136
+ }
137
+ return filled;
138
+ }
139
+ function errorCode(caught) {
140
+ return caught && typeof caught === "object" && "code" in caught ? String(caught.code) : null;
141
+ }
142
+ /**
143
+ * A live chat provider over LiveChat (livechat.com), through `@livechat/customer-sdk`. The SDK is
144
+ * imported and connected the first time the provider is asked anything, so a page pays for it only
145
+ * when a visitor asks for a person. LiveChat keeps the visitor's identity in the browser and allows
146
+ * them one chat, which a later handover starts a new thread in.
147
+ */
148
+ function createLiveChatProvider(config) {
149
+ const messageListeners = /* @__PURE__ */ new Set();
150
+ const typingListeners = /* @__PURE__ */ new Set();
151
+ const endedListeners = /* @__PURE__ */ new Set();
152
+ const agentListeners = /* @__PURE__ */ new Set();
153
+ const agentNames = /* @__PURE__ */ new Map();
154
+ let connection = null;
155
+ let customerId = null;
156
+ let online = false;
157
+ let form = null;
158
+ let current = null;
159
+ function agentJoined(user) {
160
+ if (user.type !== "agent") return;
161
+ agentNames.set(user.id, user.name);
162
+ for (const listener of agentListeners) listener({ name: user.name.trim() || null });
163
+ }
164
+ function receive(event) {
165
+ if (!event || event.authorId === customerId || event.type !== "message" && event.type !== "system_message") return;
166
+ const text = event.text.trim();
167
+ if (!text) return;
168
+ const system = event.type === "system_message";
169
+ const item = {
170
+ id: event.id,
171
+ text,
172
+ sender: system ? "system" : "agent",
173
+ name: system ? null : agentNames.get(event.authorId)?.trim() || null
174
+ };
175
+ for (const listener of messageListeners) listener(item);
176
+ }
177
+ function listen(sdk) {
178
+ on(sdk, "on", "availability_updated", ({ availability }) => {
179
+ online = availability === "online";
180
+ });
181
+ on(sdk, "on", "incoming_event", ({ chatId, event }) => {
182
+ if (chatId === current?.chatId) receive(event);
183
+ });
184
+ on(sdk, "on", "incoming_typing_indicator", ({ chatId, typingIndicator }) => {
185
+ if (chatId !== current?.chatId || !typingIndicator.isTyping || typingIndicator.authorId === customerId) return;
186
+ for (const listener of typingListeners) listener();
187
+ });
188
+ on(sdk, "on", "user_added_to_chat", ({ chatId, user }) => {
189
+ if (chatId === current?.chatId) agentJoined(user);
190
+ });
191
+ on(sdk, "on", "chat_deactivated", ({ chatId }) => {
192
+ if (chatId !== current?.chatId) return;
193
+ current = null;
194
+ for (const listener of endedListeners) listener();
195
+ });
196
+ }
197
+ function load() {
198
+ if (connection) return connection;
199
+ const pending = (async () => {
200
+ const sdk = (await import("@livechat/customer-sdk")).init({
201
+ organizationId: config.organizationId,
202
+ clientId: config.clientId,
203
+ ...config.groupId === void 0 ? {} : { groupId: config.groupId }
204
+ });
205
+ try {
206
+ await new Promise((resolve, reject) => {
207
+ on(sdk, "once", "connected", ({ customer, availability }) => {
208
+ customerId = customer.id;
209
+ online = availability === "online";
210
+ resolve();
211
+ });
212
+ on(sdk, "once", "disconnected", ({ reason }) => {
213
+ reject(/* @__PURE__ */ new Error(`LiveChat could not connect: ${reason}`));
214
+ });
215
+ });
216
+ } catch (caught) {
217
+ sdk.destroy();
218
+ throw caught;
219
+ }
220
+ listen(sdk);
221
+ return sdk;
222
+ })();
223
+ pending.catch(() => {
224
+ if (connection === pending) connection = null;
225
+ });
226
+ connection = pending;
227
+ return pending;
228
+ }
229
+ function adopt(chatId, thread, users, replay) {
230
+ current = {
231
+ chatId,
232
+ threadId: thread.id
233
+ };
234
+ for (const user of users) if (user.type === "agent" && user.present) agentJoined(user);
235
+ if (replay) for (const event of thread.events) receive(event);
236
+ }
237
+ return {
238
+ async availability() {
239
+ await load();
240
+ return online ? { status: "open" } : {
241
+ status: "closed",
242
+ reason: "no-agents"
243
+ };
244
+ },
245
+ async survey() {
246
+ const response = await (await load()).getForm({
247
+ groupId: config.groupId ?? 0,
248
+ type: "prechat"
249
+ });
250
+ form = response.enabled ? response.form : null;
251
+ return form ? surveyFieldsFromForm(form) : null;
252
+ },
253
+ async start(options) {
254
+ const sdk = await load();
255
+ if (options.resume) {
256
+ const chat = await sdk.getChat({ chatId: options.resume });
257
+ if (!chat.thread?.active) throw new Error("LiveChat chat has ended");
258
+ adopt(chat.id, chat.thread, chat.users, true);
259
+ return;
260
+ }
261
+ const answers = options.answers ?? {};
262
+ const filled = form ? filledFormFields(form, answers) : [];
263
+ const name = filled.find((field) => field.type === "name");
264
+ const email = filled.find((field) => field.type === "email");
265
+ const group = filled.find((field) => field.type === "group_chooser");
266
+ if (name?.answer || email?.answer) await sdk.updateCustomer({
267
+ ...name?.answer ? { name: name.answer } : {},
268
+ ...email?.answer ? { email: email.answer } : {}
269
+ });
270
+ if (options.context && Object.keys(options.context).length) await sdk.setCustomerSessionFields({ sessionFields: options.context });
271
+ const events = [];
272
+ if (form && filled.length) events.push({
273
+ type: "filled_form",
274
+ formId: form.id,
275
+ formType: "prechat",
276
+ properties: {},
277
+ fields: filled
278
+ });
279
+ if (options.openingMessage) events.push({
280
+ type: "message",
281
+ text: options.openingMessage,
282
+ properties: {}
283
+ });
284
+ const chat = {
285
+ ...group?.answer ? { access: { groupIds: [group.answer.groupId] } } : {},
286
+ thread: { events }
287
+ };
288
+ try {
289
+ const started = await sdk.startChat({ chat });
290
+ adopt(started.id, started.thread, started.users, false);
291
+ } catch (caught) {
292
+ if (errorCode(caught) !== "CHAT_LIMIT_REACHED") throw caught;
293
+ const { chatsSummary } = await sdk.listChats({ limit: 1 });
294
+ const earlier = chatsSummary[0];
295
+ if (!earlier) throw caught;
296
+ const resumed = await sdk.resumeChat({ chat: {
297
+ id: earlier.id,
298
+ ...chat
299
+ } });
300
+ adopt(resumed.id, resumed.thread, resumed.users, false);
301
+ }
302
+ },
303
+ async send(text) {
304
+ const sdk = await load();
305
+ if (!current) throw new Error("LiveChat has no chat to send to");
306
+ await sdk.sendEvent({
307
+ chatId: current.chatId,
308
+ event: {
309
+ type: "message",
310
+ text,
311
+ properties: {}
312
+ }
313
+ });
314
+ },
315
+ async typing() {},
316
+ async draft(text) {
317
+ const sdk = await load();
318
+ if (current) sdk.setSneakPeek({
319
+ chatId: current.chatId,
320
+ sneakPeekText: text
321
+ });
322
+ },
323
+ async end() {
324
+ if (!connection || !current) return;
325
+ const sdk = await connection;
326
+ const { chatId } = current;
327
+ current = null;
328
+ await sdk.deactivateChat({ id: chatId });
329
+ },
330
+ onMessage(listener) {
331
+ messageListeners.add(listener);
332
+ return () => messageListeners.delete(listener);
333
+ },
334
+ onTyping(listener) {
335
+ typingListeners.add(listener);
336
+ return () => typingListeners.delete(listener);
337
+ },
338
+ onEnded(listener) {
339
+ endedListeners.add(listener);
340
+ return () => endedListeners.delete(listener);
341
+ },
342
+ onAgent(listener) {
343
+ agentListeners.add(listener);
344
+ return () => agentListeners.delete(listener);
345
+ },
346
+ async resumeToken() {
347
+ return current?.chatId ?? null;
348
+ },
349
+ async emailTranscript({ email }) {
350
+ const sdk = await load();
351
+ if (!current) throw new Error("LiveChat has no chat to send a transcript of");
352
+ await sdk.updateThreadProperties({
353
+ chatId: current.chatId,
354
+ threadId: current.threadId,
355
+ properties: { routing: { transcript_email: email } }
356
+ });
357
+ },
358
+ async upload(file) {
359
+ const sdk = await load();
360
+ if (!current) throw new Error("LiveChat has no chat to upload to");
361
+ const { chatId } = current;
362
+ const { url } = await sdk.uploadFile({ file }).promise;
363
+ await sdk.sendEvent({
364
+ chatId,
365
+ event: {
366
+ type: "file",
367
+ url,
368
+ alternativeText: file.name,
369
+ properties: {}
370
+ }
371
+ });
372
+ }
373
+ };
374
+ }
375
+ //#endregion
376
+ export { createLiveChatProvider };
@@ -38,16 +38,30 @@ function question(id) {
38
38
  const parsed = JSON.parse(id);
39
39
  if (isPlainObject(parsed)) return {
40
40
  name: text(parsed.Name),
41
- text: text(parsed.QuestionText)
41
+ text: text(parsed.QuestionText),
42
+ required: parsed.IsRequired === true
42
43
  };
43
44
  } catch {}
44
45
  return {
45
46
  name: null,
46
- text: null
47
+ text: null,
48
+ required: false
47
49
  };
48
50
  }
51
+ function decode(value) {
52
+ return value.replace(/&#(x[0-9a-f]+|\d+);/gi, (entity, code) => {
53
+ const point = code[0] === "x" || code[0] === "X" ? Number.parseInt(code.slice(1), 16) : Number(code);
54
+ return point > 0 && point <= 1114111 ? String.fromCodePoint(point) : entity;
55
+ });
56
+ }
49
57
  function markdown(value) {
50
- return value.replace(/\]\(\s+/g, "](");
58
+ return decode(value).replace(/\]\(\s+/g, "](");
59
+ }
60
+ function label(value) {
61
+ return markdown(value).replace(/^\*\s+/, "");
62
+ }
63
+ function isPlaceholderChoice(title) {
64
+ return /^[-\u2013\u2014]+$/.test(title);
51
65
  }
52
66
  /**
53
67
  * The pre-chat survey Omnichannel keeps as an Adaptive Card, as the field list the chat window
@@ -77,14 +91,13 @@ function surveyFieldsFromAdaptiveCard(card) {
77
91
  const asked = question(id);
78
92
  const own = text(element.label) ?? (type === "Input.Toggle" ? text(element.title) : null);
79
93
  if (own) flush();
80
- const label = markdown(own ?? pending ?? asked.text ?? id);
81
- pending = null;
82
94
  const base = {
83
95
  id,
84
96
  name: asked.name ?? id,
85
- label,
86
- required: element.isRequired === true
97
+ label: label(own ?? pending ?? asked.text ?? id),
98
+ required: element.isRequired === true || asked.required
87
99
  };
100
+ pending = null;
88
101
  if (type === "Input.Text") {
89
102
  const style = String(element.style ?? "");
90
103
  fields.push({
@@ -101,8 +114,11 @@ function surveyFieldsFromAdaptiveCard(card) {
101
114
  ...base,
102
115
  kind: "choice",
103
116
  multiple: element.isMultiSelect === true,
104
- choices: choices.filter((choice) => text(choice.title) && typeof choice.value === "string").map((choice) => ({
105
- label: String(choice.title).trim(),
117
+ choices: choices.filter((choice) => {
118
+ const title = text(choice.title);
119
+ return title !== null && !isPlaceholderChoice(title) && typeof choice.value === "string";
120
+ }).map((choice) => ({
121
+ label: decode(String(choice.title).trim()),
106
122
  value: String(choice.value)
107
123
  }))
108
124
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Framework-agnostic AI chat client for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",
@@ -26,6 +26,10 @@
26
26
  "types": "./dist/live-chat/omnichannel.d.ts",
27
27
  "import": "./dist/live-chat/omnichannel.js"
28
28
  },
29
+ "./live-chat/livechat": {
30
+ "types": "./dist/live-chat/livechat.d.ts",
31
+ "import": "./dist/live-chat/livechat.js"
32
+ },
29
33
  "./live-chat/aichat": {
30
34
  "types": "./dist/live-chat/aichat.d.ts",
31
35
  "import": "./dist/live-chat/aichat.js"
@@ -39,18 +43,23 @@
39
43
  "types": "./dist/index.d.ts",
40
44
  "peerDependencies": {
41
45
  "@bgunnarsson/binmx": "^0.1.0",
46
+ "@livechat/customer-sdk": "^5.1.1",
42
47
  "@microsoft/omnichannel-chat-sdk": "^2.0.2"
43
48
  },
44
49
  "peerDependenciesMeta": {
45
50
  "@bgunnarsson/binmx": {
46
51
  "optional": true
47
52
  },
53
+ "@livechat/customer-sdk": {
54
+ "optional": true
55
+ },
48
56
  "@microsoft/omnichannel-chat-sdk": {
49
57
  "optional": true
50
58
  }
51
59
  },
52
60
  "devDependencies": {
53
61
  "@bgunnarsson/binmx": "0.1.0",
62
+ "@livechat/customer-sdk": "5.1.1",
54
63
  "@microsoft/omnichannel-chat-sdk": "2.0.2",
55
64
  "rimraf": "6.1.3",
56
65
  "tsdown": "0.22.14",