@meandr/chat-sdk 0.0.0-stage → 0.0.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/dist/index.js ADDED
@@ -0,0 +1,1585 @@
1
+ // src/errors.ts
2
+ var RETRYABLE = /* @__PURE__ */ new Set([
3
+ "busy",
4
+ "rate_limited",
5
+ "overloaded",
6
+ "not_connected",
7
+ "interrupted",
8
+ "timeout",
9
+ "unavailable",
10
+ "model_busy",
11
+ "no_answer",
12
+ "network",
13
+ "internal",
14
+ "token_failed"
15
+ ]);
16
+ var ChatError = class extends Error {
17
+ constructor(code, message, init = {}) {
18
+ var _a, _b, _c;
19
+ super(message);
20
+ this.name = "ChatError";
21
+ this.code = code;
22
+ this.status = (_a = init.status) != null ? _a : 0;
23
+ this.retryAfter = (_b = init.retryAfter) != null ? _b : null;
24
+ this.partial = (_c = init.partial) != null ? _c : null;
25
+ if (init.cause !== void 0) this.cause = init.cause;
26
+ }
27
+ // retryable says whether the same message may work if the visitor tries again.
28
+ get retryable() {
29
+ return RETRYABLE.has(this.code);
30
+ }
31
+ };
32
+ function isChatError(e) {
33
+ return e instanceof ChatError || !!e && typeof e === "object" && e.name === "ChatError" && typeof e.code === "string";
34
+ }
35
+
36
+ // src/api.ts
37
+ var LOCAL = /^(localhost|127\.0\.0\.1|\[::1\])$/;
38
+ var ANSWER_MS = 3e4;
39
+ var BODY_CAP = 16 << 20;
40
+ var BODY_MS = 18e4;
41
+ var RATE = 32;
42
+ function apiBase(url) {
43
+ let u;
44
+ try {
45
+ u = new URL(url);
46
+ } catch {
47
+ throw new TypeError("url must be an absolute URL");
48
+ }
49
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && LOCAL.test(u.hostname))) {
50
+ throw new TypeError("url must be an https: URL");
51
+ }
52
+ if (u.username || u.password) throw new TypeError("url must not carry credentials");
53
+ return u.origin + u.pathname.replace(/\/+$/, "") + "/chat/v1";
54
+ }
55
+ function aborted() {
56
+ return new ChatError("aborted", "Cut short by the page.");
57
+ }
58
+ function within(p, signal, ms, late2) {
59
+ return new Promise((resolve, reject) => {
60
+ if (signal && signal.aborted) return reject(aborted());
61
+ const stop = () => {
62
+ clearTimeout(t);
63
+ if (signal) signal.removeEventListener("abort", onAbort);
64
+ };
65
+ const onAbort = () => {
66
+ stop();
67
+ reject(aborted());
68
+ };
69
+ const t = setTimeout(() => {
70
+ stop();
71
+ reject(late2());
72
+ }, ms);
73
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
74
+ p.then(
75
+ (v) => {
76
+ stop();
77
+ resolve(v);
78
+ },
79
+ (e) => {
80
+ stop();
81
+ reject(e);
82
+ }
83
+ );
84
+ });
85
+ }
86
+ async function timed(fetchFn, url, init, signal, ms = ANSWER_MS) {
87
+ if (signal && signal.aborted) throw aborted();
88
+ const ctrl = new AbortController();
89
+ const p = new Promise((resolve, reject) => {
90
+ try {
91
+ fetchFn(url, { ...init, signal: ctrl.signal }).then(resolve, reject);
92
+ } catch (e) {
93
+ reject(e);
94
+ }
95
+ });
96
+ try {
97
+ return await within(p, signal, ms, late);
98
+ } catch (e) {
99
+ ctrl.abort();
100
+ p.then(discard, () => {
101
+ });
102
+ if (isChatError(e)) throw e;
103
+ throw new ChatError("network", "Couldn't connect.");
104
+ }
105
+ }
106
+ function request(fetchFn, base, c) {
107
+ const headers = { Accept: c.stream ? "text/event-stream" : "application/json" };
108
+ if (c.body !== void 0) headers["Content-Type"] = c.type || "application/json";
109
+ if (c.bearer) headers.Authorization = "Bearer " + c.bearer;
110
+ const init = { method: c.method, headers, credentials: "include", cache: "no-store", redirect: "error" };
111
+ if (c.body !== void 0) init.body = c.type ? c.body : JSON.stringify(c.body);
112
+ if (!c.type) return timed(fetchFn, base + c.path, init, c.signal);
113
+ if (c.progress && typeof XMLHttpRequest == "function") return upload(base + c.path, init, c.progress, c.signal);
114
+ return timed(fetchFn, base + c.path, init, c.signal, ANSWER_MS + c.body.size / RATE);
115
+ }
116
+ function upload(url, init, progress, signal) {
117
+ return new Promise((resolve, reject) => {
118
+ if (signal && signal.aborted) return reject(aborted());
119
+ const x = new XMLHttpRequest();
120
+ let t;
121
+ const end = (e) => {
122
+ clearTimeout(t);
123
+ if (signal) signal.removeEventListener("abort", stop);
124
+ if (e) {
125
+ x.abort();
126
+ reject(e);
127
+ }
128
+ };
129
+ const stop = () => end(aborted());
130
+ const alive = () => {
131
+ clearTimeout(t);
132
+ t = setTimeout(() => end(late()), ANSWER_MS);
133
+ };
134
+ x.open(init.method, url);
135
+ x.withCredentials = true;
136
+ const h = init.headers;
137
+ for (const k in h) x.setRequestHeader(k, h[k]);
138
+ x.upload.onprogress = (e) => {
139
+ alive();
140
+ progress(e.loaded);
141
+ };
142
+ x.onprogress = alive;
143
+ x.onerror = () => end(new ChatError("network", "Couldn't connect."));
144
+ x.onload = () => {
145
+ end();
146
+ try {
147
+ resolve(new Response(x.responseText, { status: x.status, headers: { "Retry-After": x.getResponseHeader("Retry-After") || "" } }));
148
+ } catch {
149
+ reject(new ChatError("protocol", "The chat's answer couldn't be read.", { status: x.status }));
150
+ }
151
+ };
152
+ if (signal) signal.addEventListener("abort", stop, { once: true });
153
+ alive();
154
+ x.send(init.body);
155
+ });
156
+ }
157
+ function late() {
158
+ return new ChatError("network", "No answer came in time.");
159
+ }
160
+ function discard(res) {
161
+ if (res.body && !res.body.locked) res.body.cancel().catch(() => {
162
+ });
163
+ }
164
+ async function chunks(res, signal) {
165
+ const stream = res.body;
166
+ if (!stream) {
167
+ let b;
168
+ try {
169
+ b = await within(res.arrayBuffer(), signal, ANSWER_MS, stalled);
170
+ } catch (e) {
171
+ throw isChatError(e) ? e : new ChatError("network", "The answer was cut short.");
172
+ }
173
+ if (b.byteLength > BODY_CAP) throw new ChatError("protocol", "The chat's answer is too large.", { status: res.status });
174
+ return [new Uint8Array(b)];
175
+ }
176
+ const reader = stream.getReader();
177
+ const out = [];
178
+ const began = Date.now();
179
+ let n = 0;
180
+ try {
181
+ for (; ; ) {
182
+ let r;
183
+ try {
184
+ r = await within(reader.read(), signal, Math.max(0, Math.min(ANSWER_MS, began + BODY_MS + n / RATE - Date.now())), stalled);
185
+ } catch (e) {
186
+ throw isChatError(e) ? e : new ChatError("network", "The answer was cut short.");
187
+ }
188
+ if (r.done) return out;
189
+ n += r.value.length;
190
+ if (n > BODY_CAP) throw new ChatError("protocol", "The chat's answer is too large.", { status: res.status });
191
+ out.push(r.value);
192
+ }
193
+ } catch (e) {
194
+ reader.cancel().catch(() => {
195
+ });
196
+ throw e;
197
+ }
198
+ }
199
+ async function body(res, signal) {
200
+ const d = new TextDecoder();
201
+ let text = "";
202
+ for (const c of await chunks(res, signal)) text += d.decode(c, { stream: true });
203
+ text += d.decode();
204
+ try {
205
+ return JSON.parse(text);
206
+ } catch {
207
+ throw new ChatError("protocol", "The chat's answer couldn't be read.", { status: res.status });
208
+ }
209
+ }
210
+ function stalled() {
211
+ return new ChatError("network", "The answer stalled.");
212
+ }
213
+ function readJSON(res, signal) {
214
+ return body(res, signal);
215
+ }
216
+ async function failure(res, signal) {
217
+ let code = "";
218
+ let message = "";
219
+ try {
220
+ const b = await body(res, signal);
221
+ if (b && typeof b.error === "string") code = b.error;
222
+ if (b && typeof b.message === "string") message = b.message;
223
+ } catch {
224
+ if (signal && signal.aborted) return aborted();
225
+ }
226
+ if (!code) code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "internal" : "protocol";
227
+ return new ChatError(code, message || "The chat refused the request (" + res.status + ").", {
228
+ status: res.status,
229
+ retryAfter: retryAfter(res)
230
+ });
231
+ }
232
+ function retryAfter(res) {
233
+ const v = res.headers.get("Retry-After");
234
+ if (!v) return null;
235
+ const s = v.trim();
236
+ if (/^\d+$/.test(s)) return Number(s);
237
+ const at = Date.parse(s);
238
+ if (isNaN(at)) return null;
239
+ return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
240
+ }
241
+ function sleep(ms, signal) {
242
+ return new Promise((resolve, reject) => {
243
+ if (signal.aborted) return reject(aborted());
244
+ const stop = () => {
245
+ clearTimeout(t);
246
+ reject(aborted());
247
+ };
248
+ const t = setTimeout(() => {
249
+ signal.removeEventListener("abort", stop);
250
+ resolve();
251
+ }, ms);
252
+ signal.addEventListener("abort", stop, { once: true });
253
+ });
254
+ }
255
+
256
+ // src/sse.ts
257
+ var SSETooLarge = class extends Error {
258
+ };
259
+ var SSEParser = class {
260
+ constructor(maxEvent_ = 4 << 20) {
261
+ this.ia = maxEvent_;
262
+ this.P = "";
263
+ this.B = "";
264
+ this.Z = "";
265
+ this.C = false;
266
+ this._ = false;
267
+ }
268
+ push(chunk) {
269
+ const out = [];
270
+ let text = chunk;
271
+ if (!this.C && text.length > 0) {
272
+ this.C = true;
273
+ if (text.charCodeAt(0) === 65279) text = text.slice(1);
274
+ }
275
+ let start = 0;
276
+ if (this._ && text.length > 0) {
277
+ this._ = false;
278
+ if (text.charCodeAt(0) === 10) start = 1;
279
+ }
280
+ for (let i = start; i < text.length; i++) {
281
+ const c = text.charCodeAt(i);
282
+ if (c !== 10 && c !== 13) continue;
283
+ this.Ma(this.P + text.slice(start, i), out);
284
+ this.P = "";
285
+ if (c === 13) {
286
+ if (i + 1 === text.length) this._ = true;
287
+ else if (text.charCodeAt(i + 1) === 10) i++;
288
+ }
289
+ start = i + 1;
290
+ }
291
+ this.P += text.slice(start);
292
+ if (this.P.length + this.B.length > this.ia) throw new SSETooLarge("event too large");
293
+ return out;
294
+ }
295
+ Ma(line, out) {
296
+ if (line === "") {
297
+ if (this.B !== "") out.push({ event: this.Z || "message", data: this.B.slice(0, -1) });
298
+ this.B = "";
299
+ this.Z = "";
300
+ return;
301
+ }
302
+ if (line.charCodeAt(0) === 58) return;
303
+ const colon = line.indexOf(":");
304
+ const field = colon < 0 ? line : line.slice(0, colon);
305
+ let value = colon < 0 ? "" : line.slice(colon + 1);
306
+ if (value.charCodeAt(0) === 32) value = value.slice(1);
307
+ if (field === "event") this.Z = value;
308
+ else if (field === "data") {
309
+ this.B += value + "\n";
310
+ if (this.B.length > this.ia) throw new SSETooLarge("event too large");
311
+ }
312
+ }
313
+ };
314
+
315
+ // src/token.ts
316
+ var TOKEN_MS = 3e4;
317
+ function hide(token) {
318
+ return () => token;
319
+ }
320
+ function wayOf(o) {
321
+ for (const k of ["token", "tokenUrl", "getToken"]) {
322
+ if (k in o && o[k] === void 0) throw new TypeError(k + " is undefined: omit it, or null for nobody");
323
+ }
324
+ const given = [o.token, o.tokenUrl, o.getToken].filter((v) => v !== void 0).length;
325
+ if (given > 1) throw new TypeError("at most one of token, tokenUrl, getToken");
326
+ if (o.token !== void 0) return tokenWay(o.token);
327
+ if (o.tokenUrl !== void 0) {
328
+ if (typeof o.tokenUrl !== "string" || o.tokenUrl === "") throw new TypeError("tokenUrl must be an address");
329
+ return { e: "url", url: o.tokenUrl };
330
+ }
331
+ if (o.getToken !== void 0) {
332
+ if (typeof o.getToken !== "function") throw new TypeError("getToken must be a function");
333
+ return { e: "fn", fn: o.getToken };
334
+ }
335
+ return { e: "none" };
336
+ }
337
+ function tokenWay(token) {
338
+ if (token === null) return { e: "token", token: null };
339
+ if (typeof token === "string" && usable(token)) return { e: "token", token: hide(token) };
340
+ throw new TypeError("token must be a token or null");
341
+ }
342
+ function usable(token) {
343
+ if (token === "") return false;
344
+ for (let i = 0; i < token.length; i++) {
345
+ const c = token.charCodeAt(i);
346
+ if (c < 33 || c > 126) return false;
347
+ }
348
+ return true;
349
+ }
350
+ function renews(way) {
351
+ return way.e === "url" || way.e === "fn";
352
+ }
353
+ async function userToken(way, fetchFn, signal, expired) {
354
+ switch (way.e) {
355
+ case "none":
356
+ return void 0;
357
+ case "token":
358
+ return way.token ? way.token() : null;
359
+ case "url":
360
+ return fromURL(way.url, fetchFn, signal);
361
+ case "fn":
362
+ return fromFunction(way.fn, signal, expired);
363
+ }
364
+ }
365
+ async function fromURL(url, fetchFn, signal) {
366
+ let res;
367
+ try {
368
+ const init = { method: "GET", headers: { Accept: "application/json" }, credentials: "include", cache: "no-store" };
369
+ res = await timed(fetchFn, url, init, signal);
370
+ } catch {
371
+ if (signal.aborted) throw aborted();
372
+ throw new ChatError("token_failed", "The token couldn't be fetched.");
373
+ }
374
+ if (res.status === 401 || res.status === 403) return null;
375
+ if (!res.ok) throw new ChatError("token_failed", "tokenUrl answered " + res.status + ".", { status: res.status });
376
+ let v;
377
+ try {
378
+ v = await body(res, signal);
379
+ } catch {
380
+ if (signal.aborted) throw aborted();
381
+ throw new ChatError("token_failed", "tokenUrl didn't answer JSON.", { status: res.status });
382
+ }
383
+ const token = v && typeof v === "object" ? v.token : void 0;
384
+ if (token === null || typeof token === "string" && usable(token)) return token;
385
+ throw new ChatError("token_failed", 'tokenUrl must answer {"token": token or null}.', { status: res.status });
386
+ }
387
+ async function fromFunction(fn, signal, expired) {
388
+ let token;
389
+ try {
390
+ const p = new Promise((resolve) => resolve(fn({ expired, signal })));
391
+ token = await within(p, signal, TOKEN_MS, () => new ChatError("token_failed", "getToken didn't answer in time."));
392
+ } catch (e) {
393
+ if (signal.aborted) throw aborted();
394
+ if (isChatError(e) && e.code === "token_failed") throw e;
395
+ throw new ChatError("token_failed", "getToken failed.", { cause: e });
396
+ }
397
+ if (signal.aborted) throw aborted();
398
+ if (token === null || typeof token === "string" && usable(token)) return token;
399
+ throw new ChatError("token_failed", "getToken must return a token or null.");
400
+ }
401
+ function claimsOf(token) {
402
+ const parts = token.split(".");
403
+ if (parts.length !== 3) return null;
404
+ try {
405
+ const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
406
+ const bin = atob(b64 + "===".slice((b64.length + 3) % 4));
407
+ const bytes = new Uint8Array(bin.length);
408
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
409
+ const c = JSON.parse(new TextDecoder().decode(bytes));
410
+ if (!c || typeof c !== "object" || typeof c.sub !== "string") return null;
411
+ const aud = typeof c.aud === "string" ? [c.aud] : Array.isArray(c.aud) ? c.aud.filter((a) => typeof a === "string") : [];
412
+ const empty = !!c.ext && typeof c.ext === "object" && !Array.isArray(c.ext) && Object.keys(c.ext).length === 0;
413
+ return { aud, j: "user:" + c.sub + "\n" + canonical(c.ext === void 0 || empty ? null : c.ext) };
414
+ } catch {
415
+ return null;
416
+ }
417
+ }
418
+ function canonical(v) {
419
+ var _a;
420
+ if (Array.isArray(v)) return "[" + v.map(canonical).join(",") + "]";
421
+ if (v && typeof v === "object") {
422
+ const o = v;
423
+ return "{" + Object.keys(o).sort().map((k) => JSON.stringify(k) + ":" + canonical(o[k])).join(",") + "}";
424
+ }
425
+ return (_a = JSON.stringify(v)) != null ? _a : "null";
426
+ }
427
+ function originOf(url) {
428
+ try {
429
+ return new URL(url).origin;
430
+ } catch {
431
+ return null;
432
+ }
433
+ }
434
+
435
+ // src/client.ts
436
+ var OPTIONS = ["url", "token", "tokenUrl", "getToken", "fetch", "context"];
437
+ var EVENTS = ["conversation", "message", "delta", "tool", "done", "error"];
438
+ var TRANSIENT = ["network", "internal", "rate_limited", "overloaded", "not_connected", "token_failed"];
439
+ var ANSWER_CAP = 1 << 20;
440
+ var TOOLS_CAP = 100;
441
+ var STALL_MS = 45e3;
442
+ var STREAM_CAP_MS = 65 * 6e4;
443
+ var WAIT_CAP_MS = 6e4;
444
+ var BUSY_CAP_MS = 12e4;
445
+ var BUSY_STEPS_MS = [2e3, 3e3, 5e3, 8e3, 1e4];
446
+ var LOOKUP_STEPS_MS = [1e3, 2e3, 4e3, 8e3, 15e3];
447
+ var POLL_MS = 3e3;
448
+ var POLL_SLOW_MS = 1e4;
449
+ var POLL_CAP_MS = 6e5;
450
+ var POLL_FAILURES = 20;
451
+ var OPEN_STEPS_MS = [1e3, 2e3, 4e3, 8e3, 15e3];
452
+ var OPEN_LATER_MS = 15e3;
453
+ var SIGN_OUT_MS = 3e3;
454
+ var FILE_CAP = 10 << 20;
455
+ var IMAGE = /^image\/(png|jpeg|webp|gif)$/i;
456
+ var CONTEXT_MS = 5e3;
457
+ var KNOWN = { url: 2048, title: 512, timezone: 64 };
458
+ var IDLE = {
459
+ status: "idle",
460
+ anonymous: null,
461
+ conversation: null,
462
+ messages: [],
463
+ outgoing: null,
464
+ answer: null,
465
+ answering: false,
466
+ waiting: null,
467
+ stop: null,
468
+ error: null,
469
+ files: null
470
+ };
471
+ function createChat(options) {
472
+ return new Client(options);
473
+ }
474
+ var Client = class {
475
+ constructor(o) {
476
+ this.a = IDLE;
477
+ this.Q = /* @__PURE__ */ new Set();
478
+ this.g = { e: "cookie" };
479
+ this.j = null;
480
+ // the session's user: a token's sub and ext, "anonymous", or "cookie"
481
+ this.R = false;
482
+ // learned once: this browser doesn't keep the chat's cookie
483
+ this.D = null;
484
+ this.S = new AbortController();
485
+ // aborted by reopen, signOut and destroy
486
+ this.K = new AbortController();
487
+ // aborted with the session, and by newConversation
488
+ this.h = 0;
489
+ this.L = false;
490
+ // newConversation before the session opened
491
+ this.i = null;
492
+ this.r = null;
493
+ this.v = null;
494
+ // a message the chat may have stored: sending it again checks first
495
+ this.E = 0;
496
+ this.ka = /* @__PURE__ */ new Set();
497
+ this.aa = false;
498
+ // a stream's chunk is applied at once: listeners hear it once
499
+ this.ba = false;
500
+ this.m = false;
501
+ this.getState = () => this.a;
502
+ this.subscribe = (listener) => {
503
+ if (typeof listener !== "function") throw new TypeError("subscribe needs a function");
504
+ if (!this.m) this.Q.add(listener);
505
+ this.la(listener);
506
+ return () => {
507
+ this.Q.delete(listener);
508
+ };
509
+ };
510
+ this.open = () => {
511
+ if (this.m || this.a.status === "ready") return Promise.resolve(this.a);
512
+ if (!this.D) {
513
+ const p = this.Na();
514
+ this.D = p;
515
+ const clear = () => {
516
+ if (this.D === p) this.D = null;
517
+ };
518
+ p.then(clear, clear);
519
+ }
520
+ return this.D;
521
+ };
522
+ this.send = (text, options) => {
523
+ if (typeof text !== "string") throw new TypeError("send needs text");
524
+ const files = checked(options, ["files"]).files;
525
+ if (files !== void 0 && !Array.isArray(files)) throw new TypeError("files must be an array");
526
+ return this.Oa(text, files ? files.map(idOf) : []);
527
+ };
528
+ this.attach = (file, options) => {
529
+ var _a, _b;
530
+ if (!(file instanceof Blob)) throw new TypeError("attach needs a Blob");
531
+ const o = checked(options, ["name", "onProgress", "signal"]);
532
+ const on = o.onProgress;
533
+ if (o.name !== void 0 && typeof o.name !== "string") throw new TypeError("name must be a string");
534
+ if (on !== void 0 && typeof on !== "function") throw new TypeError("onProgress must be a function");
535
+ const size = file.size;
536
+ if (size > FILE_CAP) return Promise.resolve({ ok: false, error: new ChatError("too_large", "The file is too large.") });
537
+ const path = "/files?name=" + encodeURIComponent(wellFormed((_b = (_a = o.name) != null ? _a : file.name) != null ? _b : "") || "file");
538
+ return this.ma(o.signal, async (signal) => {
539
+ const l = this.$;
540
+ if (l === null) throw new ChatError("attachments_off", "This chat takes no files.");
541
+ if (l && size > l.maxBytes) throw new ChatError("too_large", "The file is too large.");
542
+ const c = { method: "POST", path, body: file, type: file.type || "application/octet-stream" };
543
+ const res = await this.na(on ? { ...c, progress: (sent) => on(Math.min(sent, size), size) } : c, signal);
544
+ return { ok: true, file: fileOf(await readJSON(res, signal)) };
545
+ });
546
+ };
547
+ this.readFile = (file, options) => {
548
+ const path = "/files/" + encodeURIComponent(idOf(file));
549
+ return this.ma(checked(options, ["signal"]).signal, async (signal) => {
550
+ const res = await this.na({ method: "GET", path }, signal);
551
+ const t = res.headers.get("Content-Type") || "";
552
+ return { ok: true, blob: new Blob(await chunks(res, signal), { type: IMAGE.test(t) ? t : "application/octet-stream" }) };
553
+ });
554
+ };
555
+ this.start = () => this.Pa();
556
+ this.newConversation = () => {
557
+ if (this.m) return;
558
+ if (this.a.status !== "ready") this.L = true;
559
+ this.oa();
560
+ this.c({ conversation: null, messages: [], outgoing: null, answer: null, answering: false, waiting: null, stop: null, error: null });
561
+ };
562
+ this.reopen = (options) => {
563
+ if (options !== void 0 && (!options || typeof options !== "object")) throw new TypeError("reopen takes { token }");
564
+ const o = options || {};
565
+ for (const k of Object.keys(o)) if (k !== "token") throw new TypeError("unknown option " + k);
566
+ if ("token" in o) this.p = tokenWay(o.token);
567
+ else if (this.p.e === "token") throw new TypeError("reopen needs { token }, or { token: null }");
568
+ if (this.m) return Promise.resolve(this.a);
569
+ const idle = this.a.status === "idle";
570
+ this.pa();
571
+ return idle ? Promise.resolve(this.a) : this.open();
572
+ };
573
+ this.signOut = async () => {
574
+ if (this.m) return;
575
+ const auth = this.g;
576
+ if (this.p.e === "token") this.p = { e: "token", token: null };
577
+ this.pa();
578
+ const stop = new AbortController();
579
+ const t = setTimeout(() => stop.abort(), SIGN_OUT_MS);
580
+ try {
581
+ const bearer = auth.e === "session" ? auth.token() : null;
582
+ discard(await request(this.l, this.q, { method: "DELETE", path: "/session", bearer, signal: stop.signal }));
583
+ } catch {
584
+ } finally {
585
+ clearTimeout(t);
586
+ }
587
+ };
588
+ this.destroy = () => {
589
+ if (this.m) return;
590
+ this.qa();
591
+ this.m = true;
592
+ this.Q.clear();
593
+ };
594
+ if (!o || typeof o !== "object") throw new TypeError("createChat needs options");
595
+ for (const k of Object.keys(o)) if (OPTIONS.indexOf(k) < 0) throw new TypeError("unknown option " + k);
596
+ if (typeof o.url !== "string") throw new TypeError("url is required");
597
+ if (o.fetch !== void 0 && typeof o.fetch !== "function") throw new TypeError("fetch must be a function");
598
+ if (o.context !== void 0 && typeof o.context !== "function") throw new TypeError("context must be a function");
599
+ this.ja = o.context;
600
+ this.q = apiBase(o.url);
601
+ this.J = originOf(this.q);
602
+ this.p = wayOf(o);
603
+ const f = o.fetch;
604
+ this.l = f ? (input, init) => f(input, init) : (input, init) => fetch(input, init);
605
+ }
606
+ // --- state
607
+ c(patch) {
608
+ this.a = { ...this.a, ...patch };
609
+ if (this.aa) this.ba = true;
610
+ else this.ca();
611
+ }
612
+ ca() {
613
+ if (this.m) return;
614
+ for (const l of Array.from(this.Q)) this.la(l);
615
+ }
616
+ la(listener) {
617
+ try {
618
+ listener(this.a);
619
+ } catch (e) {
620
+ setTimeout(() => {
621
+ throw e;
622
+ });
623
+ }
624
+ }
625
+ x(messages) {
626
+ for (const m of messages) if (m.id > this.E) this.E = m.id;
627
+ }
628
+ T(id) {
629
+ return this.a.conversation !== null && this.a.conversation.id === id;
630
+ }
631
+ oa() {
632
+ this.K.abort();
633
+ this.K = new AbortController();
634
+ this.h++;
635
+ this.i = null;
636
+ this.r = null;
637
+ this.v = null;
638
+ }
639
+ qa() {
640
+ this.S.abort();
641
+ this.S = new AbortController();
642
+ this.D = null;
643
+ this.oa();
644
+ }
645
+ pa() {
646
+ this.qa();
647
+ this.g = { e: "cookie" };
648
+ this.j = null;
649
+ this.L = false;
650
+ this.E = 0;
651
+ this.$ = this.w = void 0;
652
+ this.a = IDLE;
653
+ this.ca();
654
+ }
655
+ // userChanged wipes what the page shows when a reopened session is someone
656
+ // else's, so nobody sees another's conversation or draft, then shows theirs.
657
+ Qa(o) {
658
+ if (this.r) this.r.abort();
659
+ this.r = null;
660
+ this.h++;
661
+ this.v = null;
662
+ this.L = false;
663
+ this.E = 0;
664
+ this.a = { ...IDLE, status: "ready", files: this.a.files };
665
+ this.ra(o, this.h, false);
666
+ }
667
+ // show applies an opened session; hide keeps its conversation off the page,
668
+ // after newConversation, while still learning its newest message.
669
+ ra(o, version, hide2) {
670
+ this.x(o.messages);
671
+ if (version !== this.h) {
672
+ this.c({ anonymous: o.anonymous });
673
+ return;
674
+ }
675
+ if (hide2) {
676
+ this.c({ anonymous: o.anonymous, conversation: null, messages: [], answering: false });
677
+ return;
678
+ }
679
+ const answering = o.answering && o.conversation !== null;
680
+ this.c({ anonymous: o.anonymous, conversation: o.conversation, messages: merge(this.a.messages, o.messages), answering });
681
+ if (answering && o.conversation) this.Ra(o.conversation.id);
682
+ }
683
+ sa(id) {
684
+ if (this.T(id)) this.c({ conversation: null, messages: [], answer: null, answering: false });
685
+ }
686
+ // --- opening
687
+ async Na() {
688
+ const session = this.S;
689
+ const version = this.h;
690
+ const began = Date.now();
691
+ this.c({ status: "opening", error: null });
692
+ for (let tries = 0; ; tries++) {
693
+ try {
694
+ const o = await this.ta(session.signal);
695
+ if (session.signal.aborted) return this.a;
696
+ const hidden = this.L;
697
+ this.L = false;
698
+ this.ra(o, version, hidden);
699
+ this.c({ status: "ready", waiting: null });
700
+ return this.a;
701
+ } catch (e) {
702
+ if (session.signal.aborted) return this.a;
703
+ const err = asChatError(e);
704
+ if (TRANSIENT.indexOf(err.code) < 0 || err.code === "token_failed") {
705
+ this.c({ status: "error", error: err, waiting: null });
706
+ return this.a;
707
+ }
708
+ const ms = openWait(err, tries, Date.now() - began);
709
+ this.c({ waiting: { code: err.code, until: Date.now() + ms } });
710
+ try {
711
+ await sleep(ms, session.signal);
712
+ } catch {
713
+ return this.a;
714
+ }
715
+ }
716
+ }
717
+ }
718
+ // establish opens or resumes the session for the page's user and settles how
719
+ // requests carry it.
720
+ async ta(signal) {
721
+ const token = await userToken(this.p, this.l, signal, false);
722
+ if (typeof token !== "string") return this.ua(token === null, signal);
723
+ try {
724
+ return await this.va(token, signal);
725
+ } catch (e) {
726
+ if (!isCode(e, "token_expired") || !renews(this.p)) throw e;
727
+ }
728
+ const next = await userToken(this.p, this.l, signal, true);
729
+ if (typeof next !== "string") return this.ua(next === null, signal);
730
+ return this.va(next, signal);
731
+ }
732
+ async va(token, signal) {
733
+ if (!this.wa(token)) throw notForThisChat(this.J);
734
+ const who = whoOf(token);
735
+ if (this.R) {
736
+ const o2 = await this.y({ cookieless: true }, token, signal);
737
+ this.g = { e: "token", token: hide(token) };
738
+ this.j = who;
739
+ return o2;
740
+ }
741
+ const o = await this.y({}, token, signal);
742
+ if (o.C && !await this.xa(signal)) {
743
+ this.R = true;
744
+ this.g = { e: "token", token: hide(token) };
745
+ } else {
746
+ this.g = { e: "cookie" };
747
+ }
748
+ this.j = who;
749
+ return o;
750
+ }
751
+ // openWithout opens with no customer's token. When the page says nobody is
752
+ // signed in, a signed-in session the browser still holds is ended first.
753
+ async ua(nobody, signal) {
754
+ const held = this.g;
755
+ if (held.e === "session") {
756
+ try {
757
+ const o2 = await this.y({}, held.token(), signal);
758
+ this.j = "anonymous";
759
+ return o2;
760
+ } catch (e) {
761
+ if (!isCode(e, "session_expired") && !isCode(e, "unauthorized")) throw e;
762
+ }
763
+ }
764
+ this.g = { e: "cookie" };
765
+ if (this.R) return this.ya(signal);
766
+ if (nobody && await this.Sa(signal)) await this.F(signal);
767
+ const o = await this.y({}, null, signal);
768
+ if (nobody && !o.anonymous) {
769
+ throw new ChatError("protocol", "Signed in, though the page says nobody is.");
770
+ }
771
+ if (o.C && !await this.xa(signal)) {
772
+ this.R = true;
773
+ return this.ya(signal);
774
+ }
775
+ this.j = o.anonymous ? "anonymous" : "cookie";
776
+ return o;
777
+ }
778
+ async ya(signal) {
779
+ const o = await this.y({ cookieless: true }, null, signal);
780
+ if (!o.za) throw new ChatError("protocol", "The chat gave no session token.");
781
+ this.g = { e: "session", token: hide(o.za) };
782
+ this.j = "anonymous";
783
+ return o;
784
+ }
785
+ async y(body2, bearer, signal) {
786
+ const res = await request(this.l, this.q, { method: "POST", path: "/session", body: body2, bearer, signal });
787
+ if (!res.ok) throw await failure(res, signal);
788
+ const o = openedOf(await readJSON(res, signal));
789
+ live(signal);
790
+ this.$ = o.files;
791
+ this.w = o.w;
792
+ const files = o.files || null;
793
+ if (JSON.stringify(files) !== JSON.stringify(this.a.files)) this.c({ files });
794
+ return o;
795
+ }
796
+ // cookieKept asks, with the cookie alone, whether the browser kept the session it was just given.
797
+ async xa(signal) {
798
+ const res = await request(this.l, this.q, { method: "GET", path: "/session", signal });
799
+ if (res.ok || res.status === 401) {
800
+ discard(res);
801
+ live(signal);
802
+ return res.ok;
803
+ }
804
+ throw await failure(res, signal);
805
+ }
806
+ // signedIn asks, with the cookie alone, whether the browser holds a signed-in
807
+ // session, without fetching that user's conversation. One the chat refuses to
808
+ // serve (403) is ended too: it's of no use to anyone.
809
+ async Sa(signal) {
810
+ const res = await request(this.l, this.q, { method: "GET", path: "/session", signal });
811
+ if (res.status === 401 || res.status === 403) {
812
+ discard(res);
813
+ return res.status === 403;
814
+ }
815
+ if (!res.ok) throw await failure(res, signal);
816
+ const v = await readJSON(res, signal);
817
+ return !!v && typeof v === "object" && v.anonymous === false;
818
+ }
819
+ async F(signal) {
820
+ const res = await request(this.l, this.q, { method: "DELETE", path: "/session", signal });
821
+ if (!res.ok) throw await failure(res, signal);
822
+ discard(res);
823
+ }
824
+ // mayCarry: a token goes only to the chat its aud names, or to the page's own
825
+ // server, which forwards the chat.
826
+ wa(token) {
827
+ const page = typeof location === "object" && location ? location.origin : null;
828
+ if (page === this.J) return true;
829
+ const c = claimsOf(token);
830
+ return !!c && c.aud.some((a) => originOf(a) === this.J);
831
+ }
832
+ // --- requests as the session's user
833
+ Aa() {
834
+ return this.g.e === "cookie" ? null : this.g.token();
835
+ }
836
+ // authed makes a request as the session's user; a lapsed token or session is
837
+ // renewed or reopened once, for target's conversation.
838
+ async U(c, signal, target) {
839
+ for (let retried = false; ; retried = true) {
840
+ const res = await request(this.l, this.q, { ...c, bearer: this.Aa(), signal });
841
+ if (res.status !== 401 || retried) return res;
842
+ const err = await failure(res, signal);
843
+ if (!await this.Ta(err, signal, target)) throw err;
844
+ }
845
+ }
846
+ // recoverAuth renews a lapsed token or reopens an ended session. It answers
847
+ // whether to try again, and throws session_expired when the user changed.
848
+ async Ta(err, signal, target) {
849
+ if (this.g.e === "token" && (err.code === "token_expired" || err.code === "unauthorized")) {
850
+ if (!renews(this.p)) return false;
851
+ const token = await userToken(this.p, this.l, signal, err.code === "token_expired");
852
+ if (typeof token === "string" && whoOf(token) === this.j) {
853
+ if (!this.wa(token)) throw notForThisChat(this.J);
854
+ this.g = { e: "token", token: hide(token) };
855
+ return true;
856
+ }
857
+ } else if (err.code !== "session_expired" && err.code !== "unauthorized") {
858
+ return false;
859
+ }
860
+ const o = await this.da(signal);
861
+ this.c({ anonymous: o.anonymous });
862
+ return true;
863
+ }
864
+ // reestablish opens the session again as the page's user, within the flow's
865
+ // signal, so a sign-out meanwhile stops it. Someone else's session wipes the
866
+ // page, and the caller fails with session_expired.
867
+ async da(signal) {
868
+ live(signal);
869
+ const who = this.j;
870
+ const o = await this.ta(signal);
871
+ live(signal);
872
+ if (this.j !== who) {
873
+ this.Qa(o);
874
+ throw new ChatError("session_expired", "Someone else is signed in now.", { status: 401 });
875
+ }
876
+ this.x(o.messages);
877
+ return o;
878
+ }
879
+ // --- files
880
+ // flow runs attach's or readFile's request as the session's user, opening it
881
+ // as send does. The page's signal or the session's end cuts it short.
882
+ async ma(signal, run) {
883
+ if (this.m) return { ok: false, error: aborted() };
884
+ const ctrl = new AbortController();
885
+ const stop = () => ctrl.abort();
886
+ const session = this.S.signal;
887
+ session.addEventListener("abort", stop);
888
+ if (signal) signal.addEventListener("abort", stop);
889
+ if (session.aborted || signal && signal.aborted) stop();
890
+ try {
891
+ live(ctrl.signal);
892
+ if (this.a.status !== "ready") {
893
+ const st = await new Promise((resolve, reject) => {
894
+ ctrl.signal.addEventListener("abort", () => reject(aborted()));
895
+ this.open().then(resolve);
896
+ });
897
+ if (st.status !== "ready") throw st.error || unopened();
898
+ }
899
+ return await run(ctrl.signal);
900
+ } catch (e) {
901
+ return { ok: false, error: ctrl.signal.aborted ? aborted() : asChatError(e) };
902
+ } finally {
903
+ session.removeEventListener("abort", stop);
904
+ if (signal) signal.removeEventListener("abort", stop);
905
+ }
906
+ }
907
+ // retried makes a request that nothing is stored by when it's refused: a 401
908
+ // reopens the session once, and 429 and 503 wait as the chat says, up to a minute.
909
+ async na(c, signal) {
910
+ const until = Date.now() + WAIT_CAP_MS;
911
+ for (; ; ) {
912
+ let err;
913
+ try {
914
+ const res = await this.U(c, signal, null);
915
+ if (res.ok) return res;
916
+ err = await failure(res, signal);
917
+ } catch (e) {
918
+ err = asChatError(e);
919
+ }
920
+ const wait = waitFor(err);
921
+ if (wait === null || Date.now() + wait > until) throw err;
922
+ await sleep(wait, signal);
923
+ }
924
+ }
925
+ // --- page context
926
+ // contextOf is what a message or a start tells of the page: the browser's time zone
927
+ // under what the context option gives. That part is left out, with a warning, when
928
+ // the option fails or the chat would refuse it, so it never costs the message.
929
+ async Ba(signal) {
930
+ let zone;
931
+ try {
932
+ zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
933
+ } catch {
934
+ }
935
+ const base = zone ? { timezone: zone } : {};
936
+ const fn = this.ja;
937
+ if (fn && this.w !== void 0) {
938
+ let page;
939
+ try {
940
+ page = await within(new Promise((resolve) => resolve(fn())), signal, CONTEXT_MS, () => new Error("timeout"));
941
+ } catch (e) {
942
+ if (signal.aborted) throw aborted();
943
+ this.Ca("the option failed or took 5 s", e);
944
+ }
945
+ if (page != null) {
946
+ const v2 = vetted(base, page, this.w);
947
+ if (typeof v2 !== "string") return v2;
948
+ this.Ca(v2);
949
+ }
950
+ }
951
+ const v = vetted(base, {}, this.w);
952
+ return typeof v === "string" ? void 0 : v;
953
+ }
954
+ // warn tells the page's developer, once for each reason, that its context was left out.
955
+ Ca(why, ...cause) {
956
+ if (this.ka.has(why)) return;
957
+ this.ka.add(why);
958
+ console.warn("@meandr/chat-sdk: context left out: " + why, ...cause);
959
+ }
960
+ // --- messages
961
+ async Oa(raw, files) {
962
+ const text = normalize(raw);
963
+ if (this.m) return { ok: false, error: aborted() };
964
+ if (text === "" && !files.length) return { ok: false, error: new ChatError("bad_request", "The message is empty.") };
965
+ if (this.i || this.a.answering) return { ok: false, error: busy() };
966
+ const mine = {};
967
+ this.i = mine;
968
+ const scope = this.K;
969
+ const u = this.v;
970
+ const recheck = u && u.text === text && String(u.files) === String(files) ? u : null;
971
+ this.v = null;
972
+ let began = -1;
973
+ this.c({ outgoing: text, error: null, stop: null });
974
+ try {
975
+ if (this.a.status !== "ready") {
976
+ const st = await this.open();
977
+ if (scope.signal.aborted || this.i !== mine) return { ok: false, error: aborted() };
978
+ if (st.status !== "ready") return this.G(mine, scope, st.error || unopened(), -1);
979
+ if (this.a.answering) return this.G(mine, scope, busy(), -1);
980
+ }
981
+ const context = await this.Ba(scope.signal);
982
+ began = this.h;
983
+ this.c({ answering: true, answer: { text: "", tools: [] } });
984
+ const r = await this.Ua(text, files, context, scope.signal, recheck);
985
+ return { ok: true, message: r.message, stop: r.stop };
986
+ } catch (e) {
987
+ return this.G(mine, scope, asChatError(e), began);
988
+ } finally {
989
+ if (this.i === mine) this.i = null;
990
+ }
991
+ }
992
+ // doStart opens if need be, then has the assistant speak first; the chat
993
+ // supplies the instructions, so the page sends only its context.
994
+ async Pa() {
995
+ if (this.m) return { ok: false, error: aborted() };
996
+ if (this.i || this.a.answering) return { ok: false, error: busy() };
997
+ const mine = {};
998
+ this.i = mine;
999
+ const scope = this.K;
1000
+ let began = -1;
1001
+ this.c({ error: null, stop: null });
1002
+ try {
1003
+ if (this.a.status !== "ready") {
1004
+ const st = await this.open();
1005
+ if (scope.signal.aborted || this.i !== mine) return { ok: false, error: aborted() };
1006
+ if (st.status !== "ready") return this.G(mine, scope, st.error || unopened(), -1);
1007
+ if (this.a.answering) return this.G(mine, scope, busy(), -1);
1008
+ }
1009
+ const context = await this.Ba(scope.signal);
1010
+ began = this.h;
1011
+ this.c({ answering: true, answer: { text: "", tools: [] } });
1012
+ const r = await this.Va(scope.signal, context);
1013
+ return { ok: true, message: r.message, stop: r.stop };
1014
+ } catch (e) {
1015
+ return this.G(mine, scope, asChatError(e), began);
1016
+ } finally {
1017
+ if (this.i === mine) this.i = null;
1018
+ }
1019
+ }
1020
+ // begin asks for the start and reads its answer. Only refusals before the
1021
+ // chat starts are tried again; a start never lands twice. With no
1022
+ // conversation shown, after newConversation say, it asks for a new one.
1023
+ async Va(signal, context) {
1024
+ const sent = { text: "", files: [], o: null, V: this.E };
1025
+ const body2 = this.a.conversation === null ? { new: true, context } : { context };
1026
+ const call = { method: "POST", path: "/start", body: body2, stream: true };
1027
+ const waitUntil = Date.now() + WAIT_CAP_MS;
1028
+ const busyUntil = Date.now() + BUSY_CAP_MS;
1029
+ for (let busyTries = 0; ; ) {
1030
+ const stream = new AbortController();
1031
+ const stop = () => stream.abort();
1032
+ signal.addEventListener("abort", stop);
1033
+ try {
1034
+ let res;
1035
+ try {
1036
+ res = await this.U(call, stream.signal, null);
1037
+ } catch (e) {
1038
+ if (signal.aborted) throw aborted();
1039
+ const reopen = isChatError(e) ? waitFor(e) : null;
1040
+ if (reopen !== null && Date.now() + reopen <= waitUntil) {
1041
+ await this.H(e.code, reopen, signal);
1042
+ continue;
1043
+ }
1044
+ throw e;
1045
+ }
1046
+ if (res.ok) return await this.Da(res, stream, signal, sent);
1047
+ const err = await failure(res, signal);
1048
+ const wait = waitFor(err);
1049
+ if (wait !== null && Date.now() + wait <= waitUntil) {
1050
+ await this.H(err.code, wait, signal);
1051
+ continue;
1052
+ }
1053
+ if (err.code === "busy" && Date.now() < busyUntil) {
1054
+ await this.H("busy", BUSY_STEPS_MS[Math.min(busyTries++, BUSY_STEPS_MS.length - 1)], signal);
1055
+ continue;
1056
+ }
1057
+ throw err;
1058
+ } finally {
1059
+ signal.removeEventListener("abort", stop);
1060
+ }
1061
+ }
1062
+ }
1063
+ // failed shows a failure. A message the page doesn't show as stored stays in
1064
+ // outgoing, so it can be sent again. began is the conversation version this
1065
+ // send set answering in; once the page shows another, answering is not its own.
1066
+ G(mine, scope, err, began) {
1067
+ if (this.i === mine && !scope.signal.aborted && err.code !== "aborted") {
1068
+ if (began < 0) this.c({ error: err });
1069
+ else if (began === this.h) this.c({ answer: null, answering: false, waiting: null, error: err });
1070
+ else this.c({ answer: null, waiting: null, error: err });
1071
+ }
1072
+ return { ok: false, error: err };
1073
+ }
1074
+ // deliver sends the message and reads its answer. Only refusals that come
1075
+ // before the chat stores it are tried again: nothing after a 200 is resent.
1076
+ async Ua(text, files, context, signal, recheck) {
1077
+ if (recheck) {
1078
+ const id = await this.ea(recheck, signal, null);
1079
+ if (id !== null) return this.fa(id, recheck, signal);
1080
+ }
1081
+ const sent = { text, files, o: this.a.conversation ? this.a.conversation.id : null, V: this.E };
1082
+ const path = sent.o === null ? "/conversations" : "/conversations/" + encodeURIComponent(sent.o) + "/messages";
1083
+ const waitUntil = Date.now() + WAIT_CAP_MS;
1084
+ const busyUntil = Date.now() + BUSY_CAP_MS;
1085
+ for (let busyTries = 0; ; ) {
1086
+ const stream = new AbortController();
1087
+ const stop = () => stream.abort();
1088
+ signal.addEventListener("abort", stop);
1089
+ try {
1090
+ let res;
1091
+ try {
1092
+ res = await this.U({ method: "POST", path, body: files.length ? { text, files, context } : { text, context }, stream: true }, stream.signal, sent.o);
1093
+ } catch (e) {
1094
+ if (signal.aborted) throw aborted();
1095
+ if (isCode(e, "network")) return await this.Ea(e, sent, signal);
1096
+ const reopen = isChatError(e) ? waitFor(e) : null;
1097
+ if (reopen !== null && Date.now() + reopen <= waitUntil) {
1098
+ await this.H(e.code, reopen, signal);
1099
+ continue;
1100
+ }
1101
+ throw e;
1102
+ }
1103
+ if (res.ok) return await this.Da(res, stream, signal, sent);
1104
+ const err = await failure(res, signal);
1105
+ if (err.code === "internal") return await this.Ea(err, sent, signal);
1106
+ if (err.code === "not_found" && sent.o !== null) this.sa(sent.o);
1107
+ const wait = waitFor(err);
1108
+ if (wait !== null && Date.now() + wait <= waitUntil) {
1109
+ await this.H(err.code, wait, signal);
1110
+ continue;
1111
+ }
1112
+ if (err.code === "busy" && Date.now() < busyUntil) {
1113
+ await this.H("busy", BUSY_STEPS_MS[Math.min(busyTries++, BUSY_STEPS_MS.length - 1)], signal);
1114
+ continue;
1115
+ }
1116
+ throw err;
1117
+ } finally {
1118
+ signal.removeEventListener("abort", stop);
1119
+ }
1120
+ }
1121
+ }
1122
+ async H(code, ms, signal) {
1123
+ live(signal);
1124
+ this.c({ waiting: { code, until: Date.now() + ms } });
1125
+ try {
1126
+ await sleep(ms, signal);
1127
+ } finally {
1128
+ if (!signal.aborted) this.c({ waiting: null });
1129
+ }
1130
+ }
1131
+ // ifLanded settles a request whose outcome is unknown, a lost connection or a
1132
+ // 500: the message may have been stored, so the conversation decides.
1133
+ async Ea(err, sent, signal) {
1134
+ const id = await this.ea(sent, signal, err);
1135
+ if (id === null) throw err;
1136
+ return this.fa(id, sent, signal);
1137
+ }
1138
+ // landedSoon looks for the message, trying again while the chat can't be
1139
+ // reached. It answers null only when a lookup said the message isn't there;
1140
+ // when none could tell, it throws, and sending the text again checks first.
1141
+ async ea(sent, signal, cause) {
1142
+ const version = this.h;
1143
+ let last = null;
1144
+ for (const ms of LOOKUP_STEPS_MS) {
1145
+ await sleep(ms, signal);
1146
+ try {
1147
+ return await this.Wa(sent, signal);
1148
+ } catch (e) {
1149
+ if (signal.aborted) throw aborted();
1150
+ last = asChatError(e);
1151
+ if (this.h !== version) throw last;
1152
+ if (last.code === "not_found") return null;
1153
+ if (TRANSIENT.indexOf(last.code) < 0) break;
1154
+ }
1155
+ }
1156
+ this.v = sent;
1157
+ if (last && TRANSIENT.indexOf(last.code) < 0) throw last;
1158
+ throw cause || last || new ChatError("network", "The chat couldn't be reached.");
1159
+ }
1160
+ // landed finds the conversation that holds the message sent, if the chat
1161
+ // stored it, and shows it. A new conversation holds nothing older than known.
1162
+ async Wa(sent, signal) {
1163
+ const mine = (m) => isSent(m, sent);
1164
+ let found = null;
1165
+ if (sent.o !== null) {
1166
+ const v = await this.Fa(sent.o, signal);
1167
+ if (v.messages.some(mine)) found = v;
1168
+ } else {
1169
+ const o = await this.Xa(signal);
1170
+ if (o.conversation && o.messages.some(mine) && o.messages.every((m) => m.id > sent.V)) {
1171
+ found = { conversation: o.conversation, messages: o.messages };
1172
+ }
1173
+ }
1174
+ live(signal);
1175
+ if (!found) return null;
1176
+ this.x(found.messages);
1177
+ this.c({ conversation: found.conversation, messages: merge(this.a.messages, found.messages), outgoing: null });
1178
+ return found.conversation.id;
1179
+ }
1180
+ // latest opens the session as it is, for its latest conversation: a live
1181
+ // cookie needs no token, which may have expired meanwhile. A lapsed session is
1182
+ // reopened as the page's user, never swapped for an anonymous one.
1183
+ async Xa(signal) {
1184
+ if (this.g.e === "cookie") {
1185
+ const res = await request(this.l, this.q, { method: "GET", path: "/session", signal });
1186
+ if (res.ok) {
1187
+ discard(res);
1188
+ const o = await this.y({}, null, signal);
1189
+ if (!o.C) return o;
1190
+ } else if (res.status === 401) {
1191
+ discard(res);
1192
+ } else {
1193
+ throw await failure(res, signal);
1194
+ }
1195
+ return this.da(signal);
1196
+ }
1197
+ try {
1198
+ return await this.y(this.g.e === "token" ? { cookieless: true } : {}, this.Aa(), signal);
1199
+ } catch (e) {
1200
+ if (!isCode(e, "token_expired") && !isCode(e, "session_expired") && !isCode(e, "unauthorized")) throw e;
1201
+ return this.da(signal);
1202
+ }
1203
+ }
1204
+ // read applies the stream's events. A stream that ends without done or error
1205
+ // lost the answer, which runs on and is stored, so the conversation is followed.
1206
+ async Da(res, stream, signal, sent) {
1207
+ let conversation = sent.o;
1208
+ let message = false;
1209
+ const reader = res.body ? res.body.getReader() : null;
1210
+ if (reader) {
1211
+ const decoder = new TextDecoder();
1212
+ const parser = new SSEParser();
1213
+ const cancel = () => {
1214
+ reader.cancel().catch(() => {
1215
+ });
1216
+ };
1217
+ stream.signal.addEventListener("abort", cancel, { once: true });
1218
+ if (stream.signal.aborted) cancel();
1219
+ let stall = setTimeout(() => stream.abort(), STALL_MS);
1220
+ const cap = setTimeout(() => stream.abort(), STREAM_CAP_MS);
1221
+ try {
1222
+ for (; ; ) {
1223
+ const { value, done } = await reader.read();
1224
+ if (signal.aborted) throw aborted();
1225
+ if (done) break;
1226
+ clearTimeout(stall);
1227
+ stall = setTimeout(() => stream.abort(), STALL_MS);
1228
+ this.aa = true;
1229
+ try {
1230
+ for (const ev of parser.push(decoder.decode(value, { stream: true }))) {
1231
+ if (signal.aborted) throw aborted();
1232
+ if (ev.event === "message" && message) continue;
1233
+ if (ev.event === "message") message = true;
1234
+ const out = this.Ya(ev.event, ev.data);
1235
+ if (!out) continue;
1236
+ if ("conversation" in out) conversation = out.conversation;
1237
+ else return out;
1238
+ }
1239
+ } finally {
1240
+ this.aa = false;
1241
+ if (this.ba) {
1242
+ this.ba = false;
1243
+ this.ca();
1244
+ }
1245
+ }
1246
+ }
1247
+ } catch (e) {
1248
+ if (signal.aborted) throw aborted();
1249
+ if (isChatError(e) && e.code !== "protocol") throw e;
1250
+ } finally {
1251
+ clearTimeout(stall);
1252
+ clearTimeout(cap);
1253
+ stream.signal.removeEventListener("abort", cancel);
1254
+ cancel();
1255
+ }
1256
+ }
1257
+ if (signal.aborted) throw aborted();
1258
+ return this.fa(conversation, { ...sent, o: conversation }, signal);
1259
+ }
1260
+ // event applies one event: it answers the reply when done, the conversation
1261
+ // when one starts, and throws the answer's error.
1262
+ Ya(name, data) {
1263
+ if (EVENTS.indexOf(name) < 0) return null;
1264
+ let o;
1265
+ try {
1266
+ const v = JSON.parse(data);
1267
+ o = v && typeof v === "object" ? v : {};
1268
+ } catch {
1269
+ throw new ChatError("protocol", "The stream couldn't be read.");
1270
+ }
1271
+ switch (name) {
1272
+ case "conversation": {
1273
+ const c = conversationOf(o);
1274
+ if (this.a.conversation && this.a.conversation.id === c.id) this.c({ conversation: c });
1275
+ else this.c({ conversation: c, messages: [] });
1276
+ return { conversation: c.id };
1277
+ }
1278
+ case "message": {
1279
+ const m = messageOf(o);
1280
+ this.x([m]);
1281
+ this.c({ messages: withMessage(this.a.messages, m), outgoing: null });
1282
+ return null;
1283
+ }
1284
+ case "delta": {
1285
+ const a = this.a.answer || { text: "", tools: [] };
1286
+ if (typeof o.text !== "string" || o.text === "" || a.text.length >= ANSWER_CAP) return null;
1287
+ this.c({ answer: { text: a.text + o.text, tools: a.tools } });
1288
+ return null;
1289
+ }
1290
+ case "tool": {
1291
+ const a = this.a.answer || { text: "", tools: [] };
1292
+ if (typeof o.name !== "string" || typeof o.status !== "string") return null;
1293
+ const tools = withTool(a.tools, o.name, o.status, typeof o.title === "string" ? o.title : "");
1294
+ if (tools !== a.tools) this.c({ answer: { text: a.text, tools } });
1295
+ return null;
1296
+ }
1297
+ case "done": {
1298
+ const m = messageOf(o.message);
1299
+ const stop = typeof o.stop === "string" ? o.stop : null;
1300
+ this.x([m]);
1301
+ this.c({ messages: withMessage(this.a.messages, m), outgoing: null, answer: null, answering: false, waiting: null, stop });
1302
+ return { message: m, stop };
1303
+ }
1304
+ default: {
1305
+ const partial = o.partial ? messageOf(o.partial) : null;
1306
+ if (partial) this.x([partial]);
1307
+ this.c({ messages: partial ? withMessage(this.a.messages, partial) : this.a.messages, outgoing: null, answer: null, answering: false });
1308
+ const code = typeof o.error === "string" && o.error !== "" ? o.error : "unavailable";
1309
+ throw new ChatError(code, typeof o.message === "string" ? o.message : "The answer failed.", { status: 200, partial });
1310
+ }
1311
+ }
1312
+ }
1313
+ // follow waits for an answer whose stream was lost: the conversation, found
1314
+ // through the session when its first event never came, is asked for until
1315
+ // it's answered. The message is stored, so a failure here leaves it unsure.
1316
+ async fa(id, sent, signal) {
1317
+ const start = sent.text === "" && !sent.files.length;
1318
+ if (id === null && start) throw new ChatError("network", "The answer was lost.");
1319
+ const cid = id !== null ? id : await this.ea(sent, signal, null);
1320
+ if (cid === null) {
1321
+ this.v = sent;
1322
+ throw new ChatError("no_answer", "The answer was lost.");
1323
+ }
1324
+ const version = this.h;
1325
+ let v;
1326
+ try {
1327
+ v = await this.Ga(cid, signal);
1328
+ } catch (e) {
1329
+ if (!start && !signal.aborted && !isCode(e, "not_found") && version === this.h) this.v = { ...sent, o: cid };
1330
+ throw e;
1331
+ }
1332
+ live(signal);
1333
+ if (this.T(cid)) this.c({ outgoing: null, answer: null, waiting: null });
1334
+ let reply;
1335
+ if (start) {
1336
+ reply = v.messages.filter((m) => m.role === "assistant" && m.id > sent.V).pop();
1337
+ } else {
1338
+ let i = v.messages.length - 1;
1339
+ while (i >= 0 && !isSent(v.messages[i], sent)) i--;
1340
+ reply = i >= 0 ? v.messages.slice(i + 1).find((m) => m.role === "assistant") : void 0;
1341
+ }
1342
+ if (!reply) throw new ChatError("no_answer", "The assistant didn't answer.");
1343
+ return { message: reply, stop: null };
1344
+ }
1345
+ async Fa(id, signal) {
1346
+ const res = await this.U({ method: "GET", path: "/conversations/" + encodeURIComponent(id) }, signal, id);
1347
+ if (!res.ok) throw await failure(res, signal);
1348
+ return viewOf(await readJSON(res, signal));
1349
+ }
1350
+ // poll asks for the conversation every few seconds until no answer is being
1351
+ // written in it, then shows what was stored.
1352
+ async Ga(id, signal) {
1353
+ const started = Date.now();
1354
+ let failures = 0;
1355
+ for (; ; ) {
1356
+ const elapsed = Date.now() - started;
1357
+ if (elapsed >= POLL_CAP_MS) throw new ChatError("timeout", "The answer took too long.");
1358
+ await sleep(elapsed < 6e4 ? POLL_MS : POLL_SLOW_MS, signal);
1359
+ let v;
1360
+ try {
1361
+ v = await this.Fa(id, signal);
1362
+ } catch (e) {
1363
+ if (signal.aborted) throw aborted();
1364
+ const err = asChatError(e);
1365
+ if (err.code === "not_found") this.sa(id);
1366
+ else if (TRANSIENT.indexOf(err.code) >= 0 && ++failures < POLL_FAILURES) continue;
1367
+ throw err;
1368
+ }
1369
+ failures = 0;
1370
+ live(signal);
1371
+ if (v.answering) continue;
1372
+ if (this.T(id)) {
1373
+ this.x(v.messages);
1374
+ this.c({ conversation: v.conversation, messages: merge(this.a.messages, v.messages), answering: false });
1375
+ }
1376
+ return v;
1377
+ }
1378
+ }
1379
+ // watch follows an answer this page didn't start, such as one a previous
1380
+ // page left running; a newer watch replaces it.
1381
+ Ra(id) {
1382
+ if (this.r) this.r.abort();
1383
+ const w = new AbortController();
1384
+ this.r = w;
1385
+ const scope = this.K.signal;
1386
+ const stop = () => w.abort();
1387
+ scope.addEventListener("abort", stop, { once: true });
1388
+ this.Ga(id, w.signal).then(
1389
+ () => {
1390
+ },
1391
+ () => {
1392
+ if (!w.signal.aborted && this.T(id)) this.c({ answering: false });
1393
+ }
1394
+ ).then(() => {
1395
+ scope.removeEventListener("abort", stop);
1396
+ if (this.r === w) this.r = null;
1397
+ });
1398
+ }
1399
+ };
1400
+ function openWait(err, tries, elapsed) {
1401
+ const said = waitFor(err);
1402
+ if (elapsed < WAIT_CAP_MS) return said != null ? said : OPEN_STEPS_MS[Math.min(tries, OPEN_STEPS_MS.length - 1)];
1403
+ return Math.max(said != null ? said : 0, OPEN_LATER_MS + Math.random() * OPEN_LATER_MS);
1404
+ }
1405
+ function waitFor(err) {
1406
+ if (err.code !== "rate_limited" && err.code !== "overloaded" && err.code !== "not_connected") return null;
1407
+ const secs = err.retryAfter === null ? 5 : Math.min(Math.max(err.retryAfter, 1), 60);
1408
+ return secs * 1e3;
1409
+ }
1410
+ function busy() {
1411
+ return new ChatError("busy", "Still answering.");
1412
+ }
1413
+ function unopened() {
1414
+ return new ChatError("unauthorized", "The chat couldn't be opened.");
1415
+ }
1416
+ function checked(o, keys) {
1417
+ if (o === void 0) return {};
1418
+ if (!o || typeof o !== "object") throw new TypeError("options must be an object");
1419
+ for (const k of Object.keys(o)) if (keys.indexOf(k) < 0) throw new TypeError("unknown option " + k);
1420
+ const s = o.signal;
1421
+ if (s != null && !(s instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal");
1422
+ return o;
1423
+ }
1424
+ function idOf(f) {
1425
+ const id = typeof f === "string" ? f : f && f.id;
1426
+ if (typeof id !== "string" || id === "") throw new TypeError("a file is a ChatFile or its id");
1427
+ return id;
1428
+ }
1429
+ function vetted(base, page, max) {
1430
+ let s;
1431
+ try {
1432
+ if (page && typeof page === "object" && !Array.isArray(page)) s = JSON.stringify({ ...base, ...page });
1433
+ } catch {
1434
+ }
1435
+ if (!s || s[0] !== "{") return "no JSON object";
1436
+ const o = JSON.parse(s);
1437
+ for (const k in KNOWN) {
1438
+ const f = o[k];
1439
+ if (f != null && (typeof f !== "string" || bytesOf(f) > KNOWN[k])) return k + " must be a string of at most " + KNOWN[k] + " bytes";
1440
+ }
1441
+ if (max !== void 0 && bytesOf(s) > max) return "over the chat's " + max + " bytes";
1442
+ return s === "{}" ? void 0 : o;
1443
+ }
1444
+ function bytesOf(s) {
1445
+ return new TextEncoder().encode(s).length;
1446
+ }
1447
+ function isSent(m, sent) {
1448
+ if (m.role !== "user" || m.id <= sent.V) return false;
1449
+ return sent.files.length ? !!m.files && m.files.some((f) => f.id === sent.files[0]) : m.text === sent.text;
1450
+ }
1451
+ function notForThisChat(origin) {
1452
+ return new ChatError("token_failed", "The token's aud isn't " + origin + ".");
1453
+ }
1454
+ function live(signal) {
1455
+ if (signal.aborted) throw aborted();
1456
+ }
1457
+ function isCode(e, code) {
1458
+ return isChatError(e) && e.code === code;
1459
+ }
1460
+ function asChatError(e) {
1461
+ if (isChatError(e)) return e;
1462
+ return new ChatError("protocol", e instanceof Error ? e.message : "Something went wrong.", { cause: e });
1463
+ }
1464
+ function whoOf(token) {
1465
+ const c = claimsOf(token);
1466
+ return c ? c.j : "token";
1467
+ }
1468
+ function wellFormed(s) {
1469
+ let out = "";
1470
+ let from = 0;
1471
+ for (let i = 0; i < s.length; i++) {
1472
+ const c = s.charCodeAt(i);
1473
+ if (c >= 55296 && c <= 56319 && i + 1 < s.length && (s.charCodeAt(i + 1) & 64512) === 56320) {
1474
+ i++;
1475
+ } else if ((c & 63488) === 55296) {
1476
+ out += s.slice(from, i) + String.fromCharCode(65533);
1477
+ from = i + 1;
1478
+ }
1479
+ }
1480
+ return from === 0 ? s : out + s.slice(from);
1481
+ }
1482
+ function normalize(s) {
1483
+ const t = wellFormed(s);
1484
+ let a = 0;
1485
+ let b = t.length;
1486
+ while (a < b && goSpace(t.charCodeAt(a))) a++;
1487
+ while (b > a && goSpace(t.charCodeAt(b - 1))) b--;
1488
+ return t.slice(a, b);
1489
+ }
1490
+ function goSpace(c) {
1491
+ return c >= 9 && c <= 13 || c === 32 || c === 133 || c === 160 || c === 5760 || c >= 8192 && c <= 8202 || c === 8232 || c === 8233 || c === 8239 || c === 8287 || c === 12288;
1492
+ }
1493
+ function merge(old, fresh) {
1494
+ const byId = new Map(old.map((m) => [m.id, m]));
1495
+ return fresh.map((m) => {
1496
+ const o = byId.get(m.id);
1497
+ const same = o && o.text === m.text && o.role === m.role && o.createdAt === m.createdAt && String(o.tools) === String(m.tools);
1498
+ return same && JSON.stringify(o.files) === JSON.stringify(m.files) ? o : m;
1499
+ });
1500
+ }
1501
+ function withMessage(list, m) {
1502
+ return list.some((x) => x.id === m.id) ? list.map((x) => x.id === m.id ? m : x) : list.concat(m);
1503
+ }
1504
+ function withTool(tools, name, status, title) {
1505
+ if (status !== "started") {
1506
+ for (let i = tools.length - 1; i >= 0; i--) {
1507
+ if (tools[i].name === name && tools[i].status === "started") {
1508
+ return tools.slice(0, i).concat({ name, status, title: title || tools[i].title }, tools.slice(i + 1));
1509
+ }
1510
+ }
1511
+ }
1512
+ return tools.length >= TOOLS_CAP ? tools : tools.concat({ name, status, title: title || name });
1513
+ }
1514
+ function bad(what) {
1515
+ return new ChatError("protocol", "Unreadable " + what + " from the chat.");
1516
+ }
1517
+ function conversationOf(v) {
1518
+ var _a, _b;
1519
+ const o = v;
1520
+ if (!o || typeof o !== "object" || typeof o.id !== "string") throw bad("conversation");
1521
+ return { id: o.id, createdAt: String((_a = o.created_at) != null ? _a : ""), updatedAt: String((_b = o.updated_at) != null ? _b : "") };
1522
+ }
1523
+ function messageOf(v) {
1524
+ var _a;
1525
+ const o = v;
1526
+ if (!o || typeof o !== "object" || typeof o.id !== "number" || typeof o.text !== "string" || o.role !== "user" && o.role !== "assistant") {
1527
+ throw bad("message");
1528
+ }
1529
+ const m = { id: o.id, role: o.role, text: o.text, createdAt: String((_a = o.created_at) != null ? _a : "") };
1530
+ if (Array.isArray(o.tools)) {
1531
+ const tools = o.tools.filter((t) => typeof t === "string");
1532
+ const said = o.tool_titles && typeof o.tool_titles === "object" ? o.tool_titles : {};
1533
+ m.tools = tools;
1534
+ m.toolTitles = Object.fromEntries(
1535
+ tools.map((t) => {
1536
+ const title = said[t];
1537
+ return [t, typeof title === "string" && title ? title : t];
1538
+ })
1539
+ );
1540
+ }
1541
+ if (Array.isArray(o.files)) m.files = o.files.filter((f) => f && typeof f.id === "string").map(fileOf);
1542
+ return m;
1543
+ }
1544
+ function fileOf(v) {
1545
+ var _a, _b, _c;
1546
+ const o = v;
1547
+ if (!o || typeof o !== "object" || typeof o.id !== "string") throw bad("file");
1548
+ const size = typeof o.size === "number" ? o.size : 0;
1549
+ return { id: o.id, name: String((_a = o.name) != null ? _a : ""), type: String((_b = o.type) != null ? _b : ""), size, createdAt: String((_c = o.created_at) != null ? _c : "") };
1550
+ }
1551
+ function messagesOf(v) {
1552
+ if (!Array.isArray(v)) return [];
1553
+ return v.filter((m) => m && typeof m === "object" && (m.role === "user" || m.role === "assistant")).map(messageOf);
1554
+ }
1555
+ function openedOf(v) {
1556
+ const o = v;
1557
+ if (!o || typeof o !== "object") throw bad("session");
1558
+ return {
1559
+ anonymous: o.anonymous === true,
1560
+ C: o.started === true,
1561
+ conversation: o.conversation ? conversationOf(o.conversation) : null,
1562
+ messages: messagesOf(o.messages),
1563
+ answering: o.answering === true,
1564
+ za: typeof o.session_token === "string" && o.session_token !== "" ? o.session_token : null,
1565
+ files: limitsOf(o.files),
1566
+ w: typeof o.context_max_bytes === "number" ? o.context_max_bytes : void 0
1567
+ };
1568
+ }
1569
+ function limitsOf(v) {
1570
+ const o = v;
1571
+ if (o === null) return null;
1572
+ if (!o || typeof o !== "object" || !Array.isArray(o.types) || typeof o.max_bytes !== "number" || typeof o.per_message !== "number") return void 0;
1573
+ return { types: o.types.filter((t) => typeof t === "string"), maxBytes: o.max_bytes, perMessage: o.per_message };
1574
+ }
1575
+ function viewOf(v) {
1576
+ const o = v;
1577
+ if (!o || typeof o !== "object") throw bad("conversation");
1578
+ return { conversation: conversationOf(o.conversation), messages: messagesOf(o.messages), answering: o.answering === true };
1579
+ }
1580
+ export {
1581
+ ChatError,
1582
+ createChat,
1583
+ isChatError
1584
+ };
1585
+ //# sourceMappingURL=index.js.map