@aliendesk/chat-sdk 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +54 -2
- package/USAGE.md +269 -0
- package/dist/chat.d.ts +165 -0
- package/dist/chat.js +520 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +11 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/sse.d.ts +2 -0
- package/dist/sse.js +59 -0
- package/dist/tool-token.d.ts +10 -0
- package/dist/tool-token.js +21 -0
- package/dist/types.d.ts +166 -0
- package/dist/types.js +3 -0
- package/package.json +47 -4
package/dist/chat.js
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
// createChat(): a product's own chat screen on Alien Desk. It opens the session,
|
|
2
|
+
// keeps its token, sends messages safely (a retry never sends twice), reads the live events and reconnects, and
|
|
3
|
+
// passes the user's tool token on when the AI needs a fresh one. No UI: the product draws its own.
|
|
4
|
+
import { ChatError } from './errors.js';
|
|
5
|
+
import { readEvents } from './sse.js';
|
|
6
|
+
import { expiryMs, refreshDelay, TOKEN_ASK_MIN_MS } from './tool-token.js';
|
|
7
|
+
/** The Alien Desk app the Chat API lives on. `sdk.js` is built with the address of the app that serves it. */
|
|
8
|
+
export const DEFAULT_API_URL = typeof __ALIENDESK_API_URL__ === 'string' ? __ALIENDESK_API_URL__ : 'https://app.aliendesk.io';
|
|
9
|
+
const DEFAULT_DELAYS = [1000, 2000, 5000, 10000, 30000];
|
|
10
|
+
function memoryStorage() {
|
|
11
|
+
const m = new Map();
|
|
12
|
+
return { get: (k) => m.get(k) ?? null, set: (k, v) => void m.set(k, v), remove: (k) => void m.delete(k) };
|
|
13
|
+
}
|
|
14
|
+
function browserStorage() {
|
|
15
|
+
try {
|
|
16
|
+
const ls = typeof window !== 'undefined' ? window.localStorage : undefined;
|
|
17
|
+
if (!ls)
|
|
18
|
+
return null;
|
|
19
|
+
return {
|
|
20
|
+
get: (k) => {
|
|
21
|
+
try {
|
|
22
|
+
return ls.getItem(k);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
set: (k, v) => {
|
|
29
|
+
try {
|
|
30
|
+
ls.setItem(k, v);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
/* private mode, full storage: the session lasts for this page only */
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
remove: (k) => {
|
|
37
|
+
try {
|
|
38
|
+
ls.removeItem(k);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
/* ignore */
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const newId = () => (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`);
|
|
51
|
+
const sleep = (ms, signal) => new Promise((resolve) => {
|
|
52
|
+
if (signal?.aborted)
|
|
53
|
+
return resolve();
|
|
54
|
+
const t = setTimeout(done, ms);
|
|
55
|
+
function done() {
|
|
56
|
+
clearTimeout(t);
|
|
57
|
+
signal?.removeEventListener('abort', done);
|
|
58
|
+
resolve();
|
|
59
|
+
}
|
|
60
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
61
|
+
});
|
|
62
|
+
const unref = (t) => t.unref?.();
|
|
63
|
+
export function createChat(options) {
|
|
64
|
+
if (!options?.key)
|
|
65
|
+
throw new ChatError(0, 'bad_request', 'createChat() needs the brand\'s public key: { key: "pk_..." }.');
|
|
66
|
+
const apiUrl = (options.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
|
67
|
+
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
68
|
+
const storage = options.storage === null ? memoryStorage() : (options.storage ?? browserStorage() ?? memoryStorage());
|
|
69
|
+
const storageKey = `aliendesk.chat.${options.key}`;
|
|
70
|
+
const delays = options.retryDelaysMs?.length ? options.retryDelaysMs : DEFAULT_DELAYS;
|
|
71
|
+
const delayFor = (attempt) => delays[Math.min(attempt, delays.length - 1)];
|
|
72
|
+
const listeners = new Map();
|
|
73
|
+
let session = null;
|
|
74
|
+
let opening = null;
|
|
75
|
+
/** The proven user, in memory only: a refreshed tool token is accepted only with their signed id. */
|
|
76
|
+
let user = null;
|
|
77
|
+
let pendingHost = {};
|
|
78
|
+
let current = null;
|
|
79
|
+
const deltas = new Map();
|
|
80
|
+
let tokenHandler = null;
|
|
81
|
+
let tokenTimer = null;
|
|
82
|
+
let tokenExpiresAt;
|
|
83
|
+
let lastTokenAsk = 0;
|
|
84
|
+
let streamGen = 0;
|
|
85
|
+
let streamCtl = null;
|
|
86
|
+
let connection = 'closed';
|
|
87
|
+
function emit(type, payload) {
|
|
88
|
+
for (const fn of [...(listeners.get(type) ?? [])]) {
|
|
89
|
+
try {
|
|
90
|
+
fn(payload);
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
// A listener's own bug never stops the chat.
|
|
94
|
+
if (type !== 'error')
|
|
95
|
+
emit('error', new ChatError(0, 'listener_failed', `An "${String(type)}" listener threw: ${String(e?.message ?? e)}`));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function setConnection(state) {
|
|
100
|
+
if (state === connection)
|
|
101
|
+
return;
|
|
102
|
+
connection = state;
|
|
103
|
+
emit('connection', state);
|
|
104
|
+
}
|
|
105
|
+
// ---------------------------------------------------------------------------------------------
|
|
106
|
+
// HTTP
|
|
107
|
+
// ---------------------------------------------------------------------------------------------
|
|
108
|
+
async function request(method, path, body, opts = {}) {
|
|
109
|
+
const useSession = opts.session !== false;
|
|
110
|
+
const s = useSession ? await ready() : null;
|
|
111
|
+
const headers = { accept: 'application/json' };
|
|
112
|
+
if (body !== undefined)
|
|
113
|
+
headers['content-type'] = 'application/json';
|
|
114
|
+
if (s)
|
|
115
|
+
headers.authorization = `Bearer ${s.sessionToken}`;
|
|
116
|
+
let res;
|
|
117
|
+
try {
|
|
118
|
+
res = await doFetch(`${apiUrl}/api/v1/chat${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
119
|
+
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
throw new ChatError(0, 'network', 'No connection to the chat. Check the internet connection and try again.', undefined, e);
|
|
122
|
+
}
|
|
123
|
+
const data = (await res.json().catch(() => null));
|
|
124
|
+
if (!res.ok) {
|
|
125
|
+
// The session ended elsewhere (signed out, removed): open a new one and try once more.
|
|
126
|
+
if (res.status === 401 && s && opts.retry401 !== false) {
|
|
127
|
+
if (session === s)
|
|
128
|
+
forget();
|
|
129
|
+
return request(method, path, body, { ...opts, retry401: false });
|
|
130
|
+
}
|
|
131
|
+
throw new ChatError(res.status, data?.error?.code ?? 'error', data?.error?.message ?? `The chat answered ${res.status}.`, data?.error?.fields);
|
|
132
|
+
}
|
|
133
|
+
return data;
|
|
134
|
+
}
|
|
135
|
+
/** Retries a call that may not have arrived (no connection) or is still running (409), with the same body. */
|
|
136
|
+
async function retrying(run) {
|
|
137
|
+
for (let attempt = 0;; attempt++) {
|
|
138
|
+
try {
|
|
139
|
+
return await run();
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
const err = e;
|
|
143
|
+
const again = err instanceof ChatError && (err.status === 0 || (err.status === 409 && err.code === 'in_progress'));
|
|
144
|
+
if (!again || attempt >= 2)
|
|
145
|
+
throw e;
|
|
146
|
+
await sleep(delayFor(attempt));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// ---------------------------------------------------------------------------------------------
|
|
151
|
+
// Session
|
|
152
|
+
// ---------------------------------------------------------------------------------------------
|
|
153
|
+
function forget() {
|
|
154
|
+
session = null;
|
|
155
|
+
storage.remove(storageKey);
|
|
156
|
+
}
|
|
157
|
+
async function openSession(extra) {
|
|
158
|
+
const host = pendingHost;
|
|
159
|
+
const body = {
|
|
160
|
+
key: options.key,
|
|
161
|
+
...(storage.get(storageKey) ? { sessionToken: storage.get(storageKey) } : {}),
|
|
162
|
+
...(options.locale ? { locale: options.locale } : {}),
|
|
163
|
+
...(user ? { user: { id: user.id, hash: user.hash } } : {}),
|
|
164
|
+
...host,
|
|
165
|
+
...extra,
|
|
166
|
+
};
|
|
167
|
+
const s = await request('POST', '/sessions', body, { session: false });
|
|
168
|
+
pendingHost = {};
|
|
169
|
+
session = s;
|
|
170
|
+
storage.set(storageKey, s.sessionToken);
|
|
171
|
+
emit('session', s);
|
|
172
|
+
if (options.stream !== false)
|
|
173
|
+
startStream(s.stream);
|
|
174
|
+
return s;
|
|
175
|
+
}
|
|
176
|
+
/** The open session, opening (or resuming) one first. */
|
|
177
|
+
function ready() {
|
|
178
|
+
if (session)
|
|
179
|
+
return Promise.resolve(session);
|
|
180
|
+
opening ?? (opening = openSession({}).finally(() => (opening = null)));
|
|
181
|
+
return opening;
|
|
182
|
+
}
|
|
183
|
+
// ---------------------------------------------------------------------------------------------
|
|
184
|
+
// Tool token
|
|
185
|
+
// ---------------------------------------------------------------------------------------------
|
|
186
|
+
function scheduleToken(expiresAt) {
|
|
187
|
+
tokenExpiresAt = expiresAt;
|
|
188
|
+
if (tokenTimer)
|
|
189
|
+
clearTimeout(tokenTimer);
|
|
190
|
+
tokenTimer = null;
|
|
191
|
+
const wait = tokenHandler ? refreshDelay(expiresAt, Date.now()) : null;
|
|
192
|
+
if (wait === null)
|
|
193
|
+
return;
|
|
194
|
+
tokenTimer = setTimeout(() => void askForToken(false), wait);
|
|
195
|
+
unref(tokenTimer);
|
|
196
|
+
}
|
|
197
|
+
async function askForToken(onDemand) {
|
|
198
|
+
if (!tokenHandler || !user)
|
|
199
|
+
return;
|
|
200
|
+
if (onDemand && Date.now() - lastTokenAsk < TOKEN_ASK_MIN_MS)
|
|
201
|
+
return;
|
|
202
|
+
lastTokenAsk = Date.now();
|
|
203
|
+
let answer;
|
|
204
|
+
try {
|
|
205
|
+
answer = await tokenHandler();
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
emit('error', new ChatError(0, 'token_request_failed', `onTokenRequest failed: ${String(e?.message ?? e)}`, undefined, e));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
// The token alone (a string), as the widget's onTokenRequest also takes.
|
|
212
|
+
const next = typeof answer === 'string' ? { toolToken: answer } : answer;
|
|
213
|
+
if (!next?.toolToken)
|
|
214
|
+
return;
|
|
215
|
+
try {
|
|
216
|
+
await setToolToken(next.toolToken, next.toolTokenExpiresAt);
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
emit('error', e instanceof ChatError ? e : new ChatError(0, 'error', String(e)));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
async function setToolToken(toolToken, toolTokenExpiresAt) {
|
|
223
|
+
if (!user)
|
|
224
|
+
throw new ChatError(0, 'not_identified', 'Call identify() with userId and userHash before passing a tool token.');
|
|
225
|
+
const r = await request('POST', '/sessions/current/tool-token', { user, toolToken, ...(toolTokenExpiresAt !== undefined ? { toolTokenExpiresAt } : {}) });
|
|
226
|
+
if (r.stored)
|
|
227
|
+
scheduleToken(toolTokenExpiresAt);
|
|
228
|
+
return r.stored;
|
|
229
|
+
}
|
|
230
|
+
// ---------------------------------------------------------------------------------------------
|
|
231
|
+
// Live events
|
|
232
|
+
// ---------------------------------------------------------------------------------------------
|
|
233
|
+
function stopStream() {
|
|
234
|
+
streamGen++;
|
|
235
|
+
streamCtl?.abort();
|
|
236
|
+
streamCtl = null;
|
|
237
|
+
}
|
|
238
|
+
function startStream(first) {
|
|
239
|
+
stopStream();
|
|
240
|
+
const gen = streamGen;
|
|
241
|
+
const ctl = new AbortController();
|
|
242
|
+
streamCtl = ctl;
|
|
243
|
+
void runStream(gen, ctl, first);
|
|
244
|
+
}
|
|
245
|
+
const live = (gen, ctl) => gen === streamGen && !ctl.signal.aborted;
|
|
246
|
+
async function runStream(gen, ctl, first) {
|
|
247
|
+
let ticket = first;
|
|
248
|
+
let attempt = 0;
|
|
249
|
+
let reconnect = false;
|
|
250
|
+
while (live(gen, ctl)) {
|
|
251
|
+
let expired = false;
|
|
252
|
+
try {
|
|
253
|
+
// A ticket close to its end is replaced first (it lasts an hour).
|
|
254
|
+
if (!ticket || (expiryMs(ticket.expiresAt) ?? 0) - Date.now() < 5000)
|
|
255
|
+
ticket = await request('POST', '/sessions/current/stream-ticket');
|
|
256
|
+
if (!live(gen, ctl))
|
|
257
|
+
return;
|
|
258
|
+
setConnection(reconnect ? 'reconnecting' : 'connecting');
|
|
259
|
+
const res = await doFetch(ticket.url, { headers: { accept: 'text/event-stream', authorization: `Bearer ${ticket.ticket}` }, signal: ctl.signal });
|
|
260
|
+
if (!res.ok || !res.body) {
|
|
261
|
+
const data = (await res.json().catch(() => null));
|
|
262
|
+
const err = new ChatError(res.status, data?.error?.code ?? 'error', data?.error?.message ?? `The event stream answered ${res.status}.`);
|
|
263
|
+
// This site may not read the stream: trying again won't change that.
|
|
264
|
+
if (res.status === 403) {
|
|
265
|
+
emit('error', err);
|
|
266
|
+
setConnection('closed');
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
// An expired ticket, or a signed-out session: a new ticket (and if need be a new session) next time.
|
|
270
|
+
if (res.status === 401)
|
|
271
|
+
ticket = null;
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
await readEvents(res.body, (type, data) => {
|
|
275
|
+
if (!live(gen, ctl))
|
|
276
|
+
return;
|
|
277
|
+
const e = data;
|
|
278
|
+
if (type === 'ready') {
|
|
279
|
+
attempt = 0;
|
|
280
|
+
setConnection('open');
|
|
281
|
+
if (reconnect)
|
|
282
|
+
void resync();
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (type === 'expired') {
|
|
286
|
+
expired = true;
|
|
287
|
+
ticket = null;
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
handle(e);
|
|
291
|
+
}, ctl.signal);
|
|
292
|
+
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
if (!live(gen, ctl))
|
|
295
|
+
return;
|
|
296
|
+
if (e instanceof ChatError && e.status !== 0 && e.status !== 401)
|
|
297
|
+
emit('error', e);
|
|
298
|
+
}
|
|
299
|
+
if (!live(gen, ctl))
|
|
300
|
+
return;
|
|
301
|
+
reconnect = true;
|
|
302
|
+
setConnection('reconnecting');
|
|
303
|
+
// A ticket that ran out is replaced at once; a dropped connection waits a little longer each time.
|
|
304
|
+
if (!expired)
|
|
305
|
+
await sleep(delayFor(attempt++), ctl.signal);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/** After a reconnect, the open chat is read again: events sent while the stream was down are not replayed. */
|
|
309
|
+
async function resync() {
|
|
310
|
+
deltas.clear();
|
|
311
|
+
const id = current;
|
|
312
|
+
if (!id)
|
|
313
|
+
return;
|
|
314
|
+
try {
|
|
315
|
+
const r = await request('GET', `/conversations/${encodeURIComponent(id)}`);
|
|
316
|
+
if (current === id)
|
|
317
|
+
emit('sync', r);
|
|
318
|
+
}
|
|
319
|
+
catch (e) {
|
|
320
|
+
if (e instanceof ChatError)
|
|
321
|
+
emit('error', e);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const awaiting = (m) => m.confirmation?.status === 'awaiting_confirmation';
|
|
325
|
+
function handle(e) {
|
|
326
|
+
emit('event', e);
|
|
327
|
+
switch (e.type) {
|
|
328
|
+
case 'message.created':
|
|
329
|
+
if (e.message.kind === 'ai')
|
|
330
|
+
deltas.delete(e.conversationId);
|
|
331
|
+
emit('message', e.message);
|
|
332
|
+
if (awaiting(e.message))
|
|
333
|
+
emit('confirmation', { conversationId: e.conversationId, message: e.message });
|
|
334
|
+
break;
|
|
335
|
+
case 'message.updated':
|
|
336
|
+
emit('message.updated', e.message);
|
|
337
|
+
break;
|
|
338
|
+
case 'conversation.updated':
|
|
339
|
+
emit('conversation', e.conversation);
|
|
340
|
+
break;
|
|
341
|
+
case 'typing':
|
|
342
|
+
emit('typing', { conversationId: e.conversationId, who: e.who, name: e.name, on: e.on });
|
|
343
|
+
break;
|
|
344
|
+
case 'ai.delta': {
|
|
345
|
+
const text = (e.reset ? '' : (deltas.get(e.conversationId) ?? '')) + e.text;
|
|
346
|
+
deltas.set(e.conversationId, text);
|
|
347
|
+
emit('delta', { conversationId: e.conversationId, text });
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
case 'ai.step':
|
|
351
|
+
emit('step', { conversationId: e.conversationId, title: e.title, status: e.status });
|
|
352
|
+
break;
|
|
353
|
+
case 'ai.action':
|
|
354
|
+
emit('action', { conversationId: e.conversationId, name: e.name, args: e.args ?? {} });
|
|
355
|
+
break;
|
|
356
|
+
case 'ai.token_request':
|
|
357
|
+
void askForToken(true);
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
// ---------------------------------------------------------------------------------------------
|
|
362
|
+
// The chat
|
|
363
|
+
// ---------------------------------------------------------------------------------------------
|
|
364
|
+
const enc = encodeURIComponent;
|
|
365
|
+
const conversationOf = (id) => {
|
|
366
|
+
const c = id ?? current;
|
|
367
|
+
if (!c)
|
|
368
|
+
throw new ChatError(0, 'no_conversation', 'No chat is open: send a message first, or open() one.');
|
|
369
|
+
return c;
|
|
370
|
+
};
|
|
371
|
+
return {
|
|
372
|
+
/** Open (or resume) the session now, and read its events. Every other call opens the session itself when needed. */
|
|
373
|
+
async start() {
|
|
374
|
+
const s = await ready();
|
|
375
|
+
if (options.stream !== false && !streamCtl)
|
|
376
|
+
startStream(null);
|
|
377
|
+
return s;
|
|
378
|
+
},
|
|
379
|
+
/** Sign the user in (their signed id), with their tool token if your product is connected. Call again for another user. */
|
|
380
|
+
async identify(input) {
|
|
381
|
+
if (input?.userId === undefined || input.userId === null || input.userId === '' || !input.userHash)
|
|
382
|
+
throw new ChatError(0, 'bad_request', 'identify() needs userId and userHash.');
|
|
383
|
+
const id = String(input.userId);
|
|
384
|
+
if (user && user.id !== id)
|
|
385
|
+
current = null;
|
|
386
|
+
user = { id, hash: input.userHash };
|
|
387
|
+
if (opening)
|
|
388
|
+
await opening.catch(() => undefined);
|
|
389
|
+
const s = await openSession({
|
|
390
|
+
user: { id, hash: input.userHash, ...(input.emailHash ? { emailHash: input.emailHash } : {}), ...(input.name ? { name: input.name } : {}), ...(input.email ? { email: input.email } : {}), ...(input.phone ? { phone: input.phone } : {}), ...(input.attrs ? { attrs: input.attrs } : {}) },
|
|
391
|
+
...(input.toolToken ? { toolToken: input.toolToken, ...(input.toolTokenExpiresAt !== undefined ? { toolTokenExpiresAt: input.toolTokenExpiresAt } : {}) } : {}),
|
|
392
|
+
});
|
|
393
|
+
if (s.toolTokenStored)
|
|
394
|
+
scheduleToken(input.toolTokenExpiresAt);
|
|
395
|
+
return s;
|
|
396
|
+
},
|
|
397
|
+
/** The user signed out of your product: the session ends, its token is forgotten, the stream closes. */
|
|
398
|
+
async signOut() {
|
|
399
|
+
const s = session;
|
|
400
|
+
stopStream();
|
|
401
|
+
if (tokenTimer)
|
|
402
|
+
clearTimeout(tokenTimer);
|
|
403
|
+
tokenTimer = null;
|
|
404
|
+
if (s)
|
|
405
|
+
await request('DELETE', '/sessions/current', undefined, { retry401: false }).catch((e) => (e instanceof ChatError && e.status === 401 ? undefined : Promise.reject(e)));
|
|
406
|
+
forget();
|
|
407
|
+
user = null;
|
|
408
|
+
current = null;
|
|
409
|
+
deltas.clear();
|
|
410
|
+
setConnection('closed');
|
|
411
|
+
},
|
|
412
|
+
/** A fresh tool token for the AI's actions in your product (the user's own). Usually `onTokenRequest` does this. */
|
|
413
|
+
setToolToken,
|
|
414
|
+
/** Called when the AI needs a fresh tool token, and before the current one expires. Return `{ toolToken, toolTokenExpiresAt }` or the token alone. */
|
|
415
|
+
onTokenRequest(fn) {
|
|
416
|
+
tokenHandler = fn;
|
|
417
|
+
scheduleToken(tokenExpiresAt);
|
|
418
|
+
},
|
|
419
|
+
/** Where the user is in your product (a hint for the AI, never trusted). `null` clears it. */
|
|
420
|
+
async context(value) {
|
|
421
|
+
if (!session) {
|
|
422
|
+
pendingHost.context = value;
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
await request('PUT', '/sessions/current/context', { context: value });
|
|
426
|
+
},
|
|
427
|
+
/** Page actions the AI may trigger; they arrive at `on('action')`. */
|
|
428
|
+
async clientTools(tools) {
|
|
429
|
+
if (!session) {
|
|
430
|
+
pendingHost.clientTools = tools;
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
await request('PUT', '/sessions/current/context', { clientTools: tools });
|
|
434
|
+
},
|
|
435
|
+
/** The user's most recent chats, newest first. */
|
|
436
|
+
async conversations() {
|
|
437
|
+
return (await request('GET', '/conversations')).data;
|
|
438
|
+
},
|
|
439
|
+
/** Load a chat and make it the one `send()` writes to. */
|
|
440
|
+
async open(conversationId) {
|
|
441
|
+
const r = await request('GET', `/conversations/${enc(conversationId)}`);
|
|
442
|
+
current = r.conversation.id;
|
|
443
|
+
deltas.delete(current);
|
|
444
|
+
return r;
|
|
445
|
+
},
|
|
446
|
+
/** The next `send()` starts a new chat. */
|
|
447
|
+
newConversation() {
|
|
448
|
+
current = null;
|
|
449
|
+
},
|
|
450
|
+
/** The chat `send()` writes to, or null before the first message. */
|
|
451
|
+
get conversationId() {
|
|
452
|
+
return current;
|
|
453
|
+
},
|
|
454
|
+
get session() {
|
|
455
|
+
return session;
|
|
456
|
+
},
|
|
457
|
+
get connection() {
|
|
458
|
+
return connection;
|
|
459
|
+
},
|
|
460
|
+
/**
|
|
461
|
+
* Send a message: to the open chat, or a new one. A lost answer is retried with the same id, so the message is
|
|
462
|
+
* never sent twice. The answer arrives as events (`delta`, `step`, then `message`).
|
|
463
|
+
*/
|
|
464
|
+
async send(text, opts = {}) {
|
|
465
|
+
const id = opts.conversationId ?? current;
|
|
466
|
+
const clientMessageId = opts.clientMessageId ?? newId();
|
|
467
|
+
if (id) {
|
|
468
|
+
const r = await retrying(() => request('POST', `/conversations/${enc(id)}/messages`, { text, clientMessageId }));
|
|
469
|
+
current = r.conversation.id;
|
|
470
|
+
return r;
|
|
471
|
+
}
|
|
472
|
+
const r = await retrying(() => request('POST', '/conversations', { text, clientMessageId }));
|
|
473
|
+
current = r.conversation.id;
|
|
474
|
+
const message = r.messages.find((m) => m.kind === 'customer') ?? r.messages[r.messages.length - 1];
|
|
475
|
+
return { conversation: r.conversation, message, newConversation: true };
|
|
476
|
+
},
|
|
477
|
+
/** Yes or No for the change the AI asked about. A second answer does nothing. */
|
|
478
|
+
async confirm(yes, conversationId) {
|
|
479
|
+
await request('POST', `/conversations/${enc(conversationOf(conversationId))}/confirmation`, { confirm: !!yes });
|
|
480
|
+
},
|
|
481
|
+
/** Hand the chat to a person on the team. */
|
|
482
|
+
async askForPerson(conversationId) {
|
|
483
|
+
return request('POST', `/conversations/${enc(conversationOf(conversationId))}/human`, {});
|
|
484
|
+
},
|
|
485
|
+
/** Where replies go when the user leaves; a handover waiting for an email (`awaitingEmail`) goes ahead. */
|
|
486
|
+
async setEmail(email, conversationId) {
|
|
487
|
+
return (await request('POST', `/conversations/${enc(conversationOf(conversationId))}/email`, { email })).conversation;
|
|
488
|
+
},
|
|
489
|
+
async end(conversationId) {
|
|
490
|
+
return (await request('POST', `/conversations/${enc(conversationOf(conversationId))}/end`, {})).conversation;
|
|
491
|
+
},
|
|
492
|
+
async rate(label, comment, conversationId) {
|
|
493
|
+
return (await request('POST', `/conversations/${enc(conversationOf(conversationId))}/rating`, { label, ...(comment ? { comment } : {}) })).conversation;
|
|
494
|
+
},
|
|
495
|
+
/** The user has the chat open on its latest replies (the team sees them as read). */
|
|
496
|
+
async markRead(conversationId) {
|
|
497
|
+
await request('POST', `/conversations/${enc(conversationOf(conversationId))}/read`, {});
|
|
498
|
+
},
|
|
499
|
+
/** Helpful or not, on an answer from the AI. */
|
|
500
|
+
async feedback(messageId, helpful) {
|
|
501
|
+
await request('POST', `/messages/${enc(messageId)}/feedback`, { helpful: !!helpful });
|
|
502
|
+
},
|
|
503
|
+
/** Listen to an event; returns the function that stops listening. */
|
|
504
|
+
on(type, fn) {
|
|
505
|
+
let set = listeners.get(type);
|
|
506
|
+
if (!set)
|
|
507
|
+
listeners.set(type, (set = new Set()));
|
|
508
|
+
set.add(fn);
|
|
509
|
+
return () => void set.delete(fn);
|
|
510
|
+
},
|
|
511
|
+
/** Stop reading events and the token timer. The session stays: `start()` reads events again. */
|
|
512
|
+
close() {
|
|
513
|
+
stopStream();
|
|
514
|
+
if (tokenTimer)
|
|
515
|
+
clearTimeout(tokenTimer);
|
|
516
|
+
tokenTimer = null;
|
|
517
|
+
setConnection('closed');
|
|
518
|
+
},
|
|
519
|
+
};
|
|
520
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A Chat API call that failed. `status` 0: no answer (no connection) or refused before sending. */
|
|
2
|
+
export declare class ChatError extends Error {
|
|
3
|
+
status: number;
|
|
4
|
+
code: string;
|
|
5
|
+
fields?: Record<string, string> | undefined;
|
|
6
|
+
cause?: unknown | undefined;
|
|
7
|
+
constructor(status: number, code: string, message: string, fields?: Record<string, string> | undefined, cause?: unknown | undefined);
|
|
8
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** A Chat API call that failed. `status` 0: no answer (no connection) or refused before sending. */
|
|
2
|
+
export class ChatError extends Error {
|
|
3
|
+
constructor(status, code, message, fields, cause) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.status = status;
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.fields = fields;
|
|
8
|
+
this.cause = cause;
|
|
9
|
+
this.name = 'ChatError';
|
|
10
|
+
}
|
|
11
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createChat, DEFAULT_API_URL } from './chat.js';
|
|
2
|
+
export type { Chat, ChatEventMap, ChatIdentity, ChatOptions, ChatStorage, ClientTool, ConnectionState, SendResult, TokenHandler, ToolTokenAnswer } from './chat.js';
|
|
3
|
+
export { ChatError } from './errors.js';
|
|
4
|
+
export type * from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @aliendesk/chat-sdk: build your own chat on Alien Desk. `createChat({ key })`, then `send()` and `on('message')`.
|
|
2
|
+
// The same module is `sdk.js` on the widget's host, as `window.AlienDeskChat`.
|
|
3
|
+
export { createChat, DEFAULT_API_URL } from './chat.js';
|
|
4
|
+
export { ChatError } from './errors.js';
|
package/dist/sse.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Reads `body` until it ends or `signal` aborts. `data` is parsed as JSON; an event whose data isn't JSON is skipped. */
|
|
2
|
+
export declare function readEvents(body: ReadableStream<Uint8Array>, onEvent: (type: string, data: unknown) => void, signal?: AbortSignal): Promise<void>;
|
package/dist/sse.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Server-Sent Events read from a fetch() body, so the ticket can go in a header (EventSource can't send one) and the
|
|
2
|
+
// same code runs in browsers and Node. Follows the format's rules: `event:` and `data:` fields, `:` comments,
|
|
3
|
+
// a blank line ends an event, CRLF or LF line ends.
|
|
4
|
+
/** Reads `body` until it ends or `signal` aborts. `data` is parsed as JSON; an event whose data isn't JSON is skipped. */
|
|
5
|
+
export async function readEvents(body, onEvent, signal) {
|
|
6
|
+
const reader = body.getReader();
|
|
7
|
+
const decoder = new TextDecoder();
|
|
8
|
+
const stop = () => void reader.cancel().catch(() => undefined);
|
|
9
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
10
|
+
let buffer = '';
|
|
11
|
+
let event = '';
|
|
12
|
+
let data = [];
|
|
13
|
+
const line = (text) => {
|
|
14
|
+
if (text === '') {
|
|
15
|
+
if (data.length) {
|
|
16
|
+
let parsed;
|
|
17
|
+
let ok = true;
|
|
18
|
+
try {
|
|
19
|
+
parsed = JSON.parse(data.join('\n'));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
ok = false;
|
|
23
|
+
}
|
|
24
|
+
if (ok)
|
|
25
|
+
onEvent(event || 'message', parsed);
|
|
26
|
+
}
|
|
27
|
+
event = '';
|
|
28
|
+
data = [];
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (text.startsWith(':'))
|
|
32
|
+
return;
|
|
33
|
+
const colon = text.indexOf(':');
|
|
34
|
+
const field = colon < 0 ? text : text.slice(0, colon);
|
|
35
|
+
let value = colon < 0 ? '' : text.slice(colon + 1);
|
|
36
|
+
if (value.startsWith(' '))
|
|
37
|
+
value = value.slice(1);
|
|
38
|
+
if (field === 'event')
|
|
39
|
+
event = value;
|
|
40
|
+
else if (field === 'data')
|
|
41
|
+
data.push(value);
|
|
42
|
+
};
|
|
43
|
+
try {
|
|
44
|
+
for (;;) {
|
|
45
|
+
const { value, done } = await reader.read();
|
|
46
|
+
if (done)
|
|
47
|
+
break;
|
|
48
|
+
buffer += decoder.decode(value, { stream: true });
|
|
49
|
+
let end;
|
|
50
|
+
while ((end = buffer.indexOf('\n')) >= 0) {
|
|
51
|
+
line(buffer.slice(0, end).replace(/\r$/, ''));
|
|
52
|
+
buffer = buffer.slice(end + 1);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
signal?.removeEventListener('abort', stop);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Ask for the next token this long before the current one expires. */
|
|
2
|
+
export declare const TOKEN_REFRESH_EARLY_MS = 60000;
|
|
3
|
+
/** The timer never asks sooner than this after a token was stored (a short-lived or already expired token would otherwise be asked for every few seconds). */
|
|
4
|
+
export declare const TOKEN_REFRESH_MIN_MS = 60000;
|
|
5
|
+
/** When the server asks for a token (`ai.token_request`), the page is asked at most this often. */
|
|
6
|
+
export declare const TOKEN_ASK_MIN_MS = 5000;
|
|
7
|
+
/** `toolTokenExpiresAt` as the page gives it (an ISO date, or Unix seconds or milliseconds), in milliseconds. */
|
|
8
|
+
export declare function expiryMs(v: unknown): number | null;
|
|
9
|
+
/** How long to wait before asking for the next token. Null: the expiry is not known, so no timer is set. */
|
|
10
|
+
export declare function refreshDelay(expiresAt: unknown, now: number): number | null;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// When to ask the product's page for the user's next tool token. The same rules as the widget
|
|
2
|
+
// (the widget's own tool-token rules); this package can't import from the widget, so they are repeated here.
|
|
3
|
+
/** Ask for the next token this long before the current one expires. */
|
|
4
|
+
export const TOKEN_REFRESH_EARLY_MS = 60000;
|
|
5
|
+
/** The timer never asks sooner than this after a token was stored (a short-lived or already expired token would otherwise be asked for every few seconds). */
|
|
6
|
+
export const TOKEN_REFRESH_MIN_MS = 60000;
|
|
7
|
+
/** When the server asks for a token (`ai.token_request`), the page is asked at most this often. */
|
|
8
|
+
export const TOKEN_ASK_MIN_MS = 5000;
|
|
9
|
+
/** `toolTokenExpiresAt` as the page gives it (an ISO date, or Unix seconds or milliseconds), in milliseconds. */
|
|
10
|
+
export function expiryMs(v) {
|
|
11
|
+
if (v == null || v === '')
|
|
12
|
+
return null;
|
|
13
|
+
const n = typeof v === 'number' ? v : /^\d+(\.\d+)?$/.test(String(v).trim()) ? Number(v) : NaN;
|
|
14
|
+
const t = Number.isFinite(n) ? (n < 1e11 ? n * 1000 : n) : Date.parse(String(v));
|
|
15
|
+
return Number.isFinite(t) ? t : null;
|
|
16
|
+
}
|
|
17
|
+
/** How long to wait before asking for the next token. Null: the expiry is not known, so no timer is set. */
|
|
18
|
+
export function refreshDelay(expiresAt, now) {
|
|
19
|
+
const at = expiryMs(expiresAt);
|
|
20
|
+
return at === null ? null : Math.max(TOKEN_REFRESH_MIN_MS, at - now - TOKEN_REFRESH_EARLY_MS);
|
|
21
|
+
}
|