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