@meandr/chat-sdk 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +252 -2
- package/dist/api.d.ts +21 -0
- package/dist/client.d.ts +2 -0
- package/dist/errors.d.ts +18 -0
- package/dist/global.d.ts +3 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1347 -0
- package/dist/index.js.map +7 -0
- package/dist/markdown.d.ts +17 -0
- package/dist/markdown.js +927 -0
- package/dist/markdown.js.map +7 -0
- package/dist/meandr-chat.js +11 -0
- package/dist/meandr-chat.js.map +7 -0
- package/dist/sse.d.ts +17 -0
- package/dist/token.d.ts +26 -0
- package/dist/types.d.ts +75 -0
- package/package.json +53 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1347 @@
|
|
|
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
|
+
function apiBase(url) {
|
|
42
|
+
let u;
|
|
43
|
+
try {
|
|
44
|
+
u = new URL(url);
|
|
45
|
+
} catch {
|
|
46
|
+
throw new TypeError("url must be an absolute URL, such as https://calm-otter.meandr.io");
|
|
47
|
+
}
|
|
48
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && LOCAL.test(u.hostname))) {
|
|
49
|
+
throw new TypeError("url must be an https: URL");
|
|
50
|
+
}
|
|
51
|
+
if (u.username || u.password) throw new TypeError("url must not carry credentials");
|
|
52
|
+
return u.origin + u.pathname.replace(/\/+$/, "") + "/chat/v1";
|
|
53
|
+
}
|
|
54
|
+
function aborted() {
|
|
55
|
+
return new ChatError("aborted", "Cut short by the page.");
|
|
56
|
+
}
|
|
57
|
+
function within(p, signal, ms, late) {
|
|
58
|
+
return new Promise((resolve, reject) => {
|
|
59
|
+
if (signal && signal.aborted) return reject(aborted());
|
|
60
|
+
const stop = () => {
|
|
61
|
+
clearTimeout(t);
|
|
62
|
+
if (signal) signal.removeEventListener("abort", onAbort);
|
|
63
|
+
};
|
|
64
|
+
const onAbort = () => {
|
|
65
|
+
stop();
|
|
66
|
+
reject(aborted());
|
|
67
|
+
};
|
|
68
|
+
const t = setTimeout(() => {
|
|
69
|
+
stop();
|
|
70
|
+
reject(late());
|
|
71
|
+
}, ms);
|
|
72
|
+
if (signal) signal.addEventListener("abort", onAbort, { once: true });
|
|
73
|
+
p.then(
|
|
74
|
+
(v) => {
|
|
75
|
+
stop();
|
|
76
|
+
resolve(v);
|
|
77
|
+
},
|
|
78
|
+
(e) => {
|
|
79
|
+
stop();
|
|
80
|
+
reject(e);
|
|
81
|
+
}
|
|
82
|
+
);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
async function timed(fetchFn, url, init, signal) {
|
|
86
|
+
if (signal && signal.aborted) throw aborted();
|
|
87
|
+
const ctrl = new AbortController();
|
|
88
|
+
const p = new Promise((resolve, reject) => {
|
|
89
|
+
try {
|
|
90
|
+
fetchFn(url, { ...init, signal: ctrl.signal }).then(resolve, reject);
|
|
91
|
+
} catch (e) {
|
|
92
|
+
reject(e);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
try {
|
|
96
|
+
return await within(p, signal, ANSWER_MS, () => new ChatError("network", "No answer came in time."));
|
|
97
|
+
} catch (e) {
|
|
98
|
+
ctrl.abort();
|
|
99
|
+
p.then(discard, () => {
|
|
100
|
+
});
|
|
101
|
+
if (isChatError(e)) throw e;
|
|
102
|
+
throw new ChatError("network", "Couldn't connect.");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function request(fetchFn, base, c) {
|
|
106
|
+
const headers = { Accept: c.stream ? "text/event-stream" : "application/json" };
|
|
107
|
+
if (c.body !== void 0) headers["Content-Type"] = "application/json";
|
|
108
|
+
if (c.bearer) headers.Authorization = "Bearer " + c.bearer;
|
|
109
|
+
const init = { method: c.method, headers, credentials: "include", cache: "no-store", redirect: "error" };
|
|
110
|
+
if (c.body !== void 0) init.body = JSON.stringify(c.body);
|
|
111
|
+
return timed(fetchFn, base + c.path, init, c.signal);
|
|
112
|
+
}
|
|
113
|
+
function discard(res) {
|
|
114
|
+
if (res.body && !res.body.locked) res.body.cancel().catch(() => {
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
async function body(res, signal) {
|
|
118
|
+
const stream = res.body;
|
|
119
|
+
if (!stream) {
|
|
120
|
+
let text;
|
|
121
|
+
try {
|
|
122
|
+
text = await within(res.text(), signal, ANSWER_MS, stalled);
|
|
123
|
+
} catch (e) {
|
|
124
|
+
throw isChatError(e) ? e : new ChatError("network", "The answer was cut short.");
|
|
125
|
+
}
|
|
126
|
+
return parse(text, res.status);
|
|
127
|
+
}
|
|
128
|
+
const reader = stream.getReader();
|
|
129
|
+
const chunks = [];
|
|
130
|
+
const until = Date.now() + BODY_MS;
|
|
131
|
+
let n = 0;
|
|
132
|
+
try {
|
|
133
|
+
for (; ; ) {
|
|
134
|
+
let r;
|
|
135
|
+
try {
|
|
136
|
+
r = await within(reader.read(), signal, Math.max(0, Math.min(ANSWER_MS, until - Date.now())), stalled);
|
|
137
|
+
} catch (e) {
|
|
138
|
+
throw isChatError(e) ? e : new ChatError("network", "The answer was cut short.");
|
|
139
|
+
}
|
|
140
|
+
if (r.done) break;
|
|
141
|
+
n += r.value.length;
|
|
142
|
+
if (n > BODY_CAP) throw new ChatError("protocol", "The chat's answer is too large.", { status: res.status });
|
|
143
|
+
chunks.push(r.value);
|
|
144
|
+
}
|
|
145
|
+
} catch (e) {
|
|
146
|
+
reader.cancel().catch(() => {
|
|
147
|
+
});
|
|
148
|
+
throw e;
|
|
149
|
+
}
|
|
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
|
+
}
|
|
161
|
+
function parse(text, status) {
|
|
162
|
+
if (text.length > BODY_CAP) throw new ChatError("protocol", "The chat's answer is too large.", { status });
|
|
163
|
+
try {
|
|
164
|
+
return JSON.parse(text);
|
|
165
|
+
} catch {
|
|
166
|
+
throw new ChatError("protocol", "The chat's answer couldn't be read.", { status });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function readJSON(res, signal) {
|
|
170
|
+
return body(res, signal);
|
|
171
|
+
}
|
|
172
|
+
async function failure(res, signal) {
|
|
173
|
+
let code = "";
|
|
174
|
+
let message = "";
|
|
175
|
+
try {
|
|
176
|
+
const b = await body(res, signal);
|
|
177
|
+
if (b && typeof b.error === "string") code = b.error;
|
|
178
|
+
if (b && typeof b.message === "string") message = b.message;
|
|
179
|
+
} catch {
|
|
180
|
+
if (signal && signal.aborted) return aborted();
|
|
181
|
+
}
|
|
182
|
+
if (!code) code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "internal" : "protocol";
|
|
183
|
+
return new ChatError(code, message || "The chat refused the request (" + res.status + ").", {
|
|
184
|
+
status: res.status,
|
|
185
|
+
retryAfter: retryAfter(res)
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
function retryAfter(res) {
|
|
189
|
+
const v = res.headers.get("Retry-After");
|
|
190
|
+
if (!v) return null;
|
|
191
|
+
const s = v.trim();
|
|
192
|
+
if (/^\d+$/.test(s)) return Number(s);
|
|
193
|
+
const at = Date.parse(s);
|
|
194
|
+
if (isNaN(at)) return null;
|
|
195
|
+
return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
|
|
196
|
+
}
|
|
197
|
+
function sleep(ms, signal) {
|
|
198
|
+
return new Promise((resolve, reject) => {
|
|
199
|
+
if (signal.aborted) return reject(aborted());
|
|
200
|
+
const stop = () => {
|
|
201
|
+
clearTimeout(t);
|
|
202
|
+
reject(aborted());
|
|
203
|
+
};
|
|
204
|
+
const t = setTimeout(() => {
|
|
205
|
+
signal.removeEventListener("abort", stop);
|
|
206
|
+
resolve();
|
|
207
|
+
}, ms);
|
|
208
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/sse.ts
|
|
213
|
+
var SSETooLarge = class extends Error {
|
|
214
|
+
};
|
|
215
|
+
var SSEParser = class {
|
|
216
|
+
constructor(maxEvent = 4 << 20) {
|
|
217
|
+
this.maxEvent = maxEvent;
|
|
218
|
+
this.buf = "";
|
|
219
|
+
this.data = "";
|
|
220
|
+
this.type = "";
|
|
221
|
+
this.started = false;
|
|
222
|
+
this.skipLF = false;
|
|
223
|
+
}
|
|
224
|
+
push(chunk) {
|
|
225
|
+
const out = [];
|
|
226
|
+
let text = chunk;
|
|
227
|
+
if (!this.started && text.length > 0) {
|
|
228
|
+
this.started = true;
|
|
229
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
230
|
+
}
|
|
231
|
+
let start = 0;
|
|
232
|
+
if (this.skipLF && text.length > 0) {
|
|
233
|
+
this.skipLF = false;
|
|
234
|
+
if (text.charCodeAt(0) === 10) start = 1;
|
|
235
|
+
}
|
|
236
|
+
for (let i = start; i < text.length; i++) {
|
|
237
|
+
const c = text.charCodeAt(i);
|
|
238
|
+
if (c !== 10 && c !== 13) continue;
|
|
239
|
+
this.line(this.buf + text.slice(start, i), out);
|
|
240
|
+
this.buf = "";
|
|
241
|
+
if (c === 13) {
|
|
242
|
+
if (i + 1 === text.length) this.skipLF = true;
|
|
243
|
+
else if (text.charCodeAt(i + 1) === 10) i++;
|
|
244
|
+
}
|
|
245
|
+
start = i + 1;
|
|
246
|
+
}
|
|
247
|
+
this.buf += text.slice(start);
|
|
248
|
+
if (this.buf.length + this.data.length > this.maxEvent) throw new SSETooLarge("event too large");
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
line(line, out) {
|
|
252
|
+
if (line === "") {
|
|
253
|
+
if (this.data !== "") out.push({ event: this.type || "message", data: this.data.slice(0, -1) });
|
|
254
|
+
this.data = "";
|
|
255
|
+
this.type = "";
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (line.charCodeAt(0) === 58) return;
|
|
259
|
+
const colon = line.indexOf(":");
|
|
260
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
261
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
262
|
+
if (value.charCodeAt(0) === 32) value = value.slice(1);
|
|
263
|
+
if (field === "event") this.type = value;
|
|
264
|
+
else if (field === "data") {
|
|
265
|
+
this.data += value + "\n";
|
|
266
|
+
if (this.data.length > this.maxEvent) throw new SSETooLarge("event too large");
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// src/token.ts
|
|
272
|
+
var TOKEN_MS = 3e4;
|
|
273
|
+
function hide(token) {
|
|
274
|
+
return () => token;
|
|
275
|
+
}
|
|
276
|
+
function wayOf(o) {
|
|
277
|
+
for (const k of ["token", "tokenUrl", "getToken"]) {
|
|
278
|
+
if (k in o && o[k] === void 0) throw new TypeError(k + " is undefined: leave it out, or pass null for nobody signed in");
|
|
279
|
+
}
|
|
280
|
+
const given = [o.token, o.tokenUrl, o.getToken].filter((v) => v !== void 0).length;
|
|
281
|
+
if (given > 1) throw new TypeError("give at most one of token, tokenUrl and getToken");
|
|
282
|
+
if (o.token !== void 0) return tokenWay(o.token);
|
|
283
|
+
if (o.tokenUrl !== void 0) {
|
|
284
|
+
if (typeof o.tokenUrl !== "string" || o.tokenUrl === "") throw new TypeError("tokenUrl must be an address");
|
|
285
|
+
return { kind: "url", url: o.tokenUrl };
|
|
286
|
+
}
|
|
287
|
+
if (o.getToken !== void 0) {
|
|
288
|
+
if (typeof o.getToken !== "function") throw new TypeError("getToken must be a function");
|
|
289
|
+
return { kind: "fn", fn: o.getToken };
|
|
290
|
+
}
|
|
291
|
+
return { kind: "none" };
|
|
292
|
+
}
|
|
293
|
+
function tokenWay(token) {
|
|
294
|
+
if (token === null) return { kind: "token", token: null };
|
|
295
|
+
if (typeof token === "string" && usable(token)) return { kind: "token", token: hide(token) };
|
|
296
|
+
throw new TypeError("token must be a token, or null when nobody is signed in");
|
|
297
|
+
}
|
|
298
|
+
function usable(token) {
|
|
299
|
+
if (token === "") return false;
|
|
300
|
+
for (let i = 0; i < token.length; i++) {
|
|
301
|
+
const c = token.charCodeAt(i);
|
|
302
|
+
if (c < 33 || c > 126) return false;
|
|
303
|
+
}
|
|
304
|
+
return true;
|
|
305
|
+
}
|
|
306
|
+
function renews(way) {
|
|
307
|
+
return way.kind === "url" || way.kind === "fn";
|
|
308
|
+
}
|
|
309
|
+
async function userToken(way, fetchFn, signal, expired) {
|
|
310
|
+
switch (way.kind) {
|
|
311
|
+
case "none":
|
|
312
|
+
return void 0;
|
|
313
|
+
case "token":
|
|
314
|
+
return way.token ? way.token() : null;
|
|
315
|
+
case "url":
|
|
316
|
+
return fromURL(way.url, fetchFn, signal);
|
|
317
|
+
case "fn":
|
|
318
|
+
return fromFunction(way.fn, signal, expired);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
async function fromURL(url, fetchFn, signal) {
|
|
322
|
+
let res;
|
|
323
|
+
try {
|
|
324
|
+
const init = { method: "GET", headers: { Accept: "application/json" }, credentials: "include", cache: "no-store" };
|
|
325
|
+
res = await timed(fetchFn, url, init, signal);
|
|
326
|
+
} catch {
|
|
327
|
+
if (signal.aborted) throw aborted();
|
|
328
|
+
throw new ChatError("token_failed", "The token couldn't be fetched.");
|
|
329
|
+
}
|
|
330
|
+
if (res.status === 401 || res.status === 403) return null;
|
|
331
|
+
if (!res.ok) throw new ChatError("token_failed", "The token address answered " + res.status + ".", { status: res.status });
|
|
332
|
+
let v;
|
|
333
|
+
try {
|
|
334
|
+
v = await body(res, signal);
|
|
335
|
+
} catch {
|
|
336
|
+
if (signal.aborted) throw aborted();
|
|
337
|
+
throw new ChatError("token_failed", "The token address didn't answer JSON.", { status: res.status });
|
|
338
|
+
}
|
|
339
|
+
const token = v && typeof v === "object" ? v.token : void 0;
|
|
340
|
+
if (token === null || typeof token === "string" && usable(token)) return token;
|
|
341
|
+
throw new ChatError("token_failed", 'The token address must answer {"token": "\u2026"} or {"token": null}.', { status: res.status });
|
|
342
|
+
}
|
|
343
|
+
async function fromFunction(fn, signal, expired) {
|
|
344
|
+
let token;
|
|
345
|
+
try {
|
|
346
|
+
const p = new Promise((resolve) => resolve(fn({ expired, signal })));
|
|
347
|
+
token = await within(p, signal, TOKEN_MS, () => new ChatError("token_failed", "getToken didn't answer in time."));
|
|
348
|
+
} catch (e) {
|
|
349
|
+
if (signal.aborted) throw aborted();
|
|
350
|
+
if (isChatError(e) && e.code === "token_failed") throw e;
|
|
351
|
+
throw new ChatError("token_failed", "getToken failed.", { cause: e });
|
|
352
|
+
}
|
|
353
|
+
if (signal.aborted) throw aborted();
|
|
354
|
+
if (token === null || typeof token === "string" && usable(token)) return token;
|
|
355
|
+
throw new ChatError("token_failed", "getToken must return a token, or null when nobody is signed in.");
|
|
356
|
+
}
|
|
357
|
+
function claimsOf(token) {
|
|
358
|
+
const parts = token.split(".");
|
|
359
|
+
if (parts.length !== 3) return null;
|
|
360
|
+
try {
|
|
361
|
+
const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
362
|
+
const bin = atob(b64 + "===".slice((b64.length + 3) % 4));
|
|
363
|
+
const bytes = new Uint8Array(bin.length);
|
|
364
|
+
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
365
|
+
const c = JSON.parse(new TextDecoder().decode(bytes));
|
|
366
|
+
if (!c || typeof c !== "object" || typeof c.sub !== "string") return null;
|
|
367
|
+
const aud = typeof c.aud === "string" ? [c.aud] : Array.isArray(c.aud) ? c.aud.filter((a) => typeof a === "string") : [];
|
|
368
|
+
const empty = !!c.ext && typeof c.ext === "object" && !Array.isArray(c.ext) && Object.keys(c.ext).length === 0;
|
|
369
|
+
return { aud, who: "user:" + c.sub + "\n" + canonical(c.ext === void 0 || empty ? null : c.ext) };
|
|
370
|
+
} catch {
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function canonical(v) {
|
|
375
|
+
var _a;
|
|
376
|
+
if (Array.isArray(v)) return "[" + v.map(canonical).join(",") + "]";
|
|
377
|
+
if (v && typeof v === "object") {
|
|
378
|
+
const o = v;
|
|
379
|
+
return "{" + Object.keys(o).sort().map((k) => JSON.stringify(k) + ":" + canonical(o[k])).join(",") + "}";
|
|
380
|
+
}
|
|
381
|
+
return (_a = JSON.stringify(v)) != null ? _a : "null";
|
|
382
|
+
}
|
|
383
|
+
function originOf(url) {
|
|
384
|
+
try {
|
|
385
|
+
return new URL(url).origin;
|
|
386
|
+
} catch {
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// src/client.ts
|
|
392
|
+
var OPTIONS = ["url", "token", "tokenUrl", "getToken", "fetch"];
|
|
393
|
+
var EVENTS = ["conversation", "message", "delta", "tool", "done", "error"];
|
|
394
|
+
var TRANSIENT = ["network", "internal", "rate_limited", "overloaded", "not_connected", "token_failed"];
|
|
395
|
+
var ANSWER_CAP = 1 << 20;
|
|
396
|
+
var TOOLS_CAP = 100;
|
|
397
|
+
var STALL_MS = 45e3;
|
|
398
|
+
var STREAM_CAP_MS = 65 * 6e4;
|
|
399
|
+
var WAIT_CAP_MS = 6e4;
|
|
400
|
+
var BUSY_CAP_MS = 12e4;
|
|
401
|
+
var BUSY_STEPS_MS = [2e3, 3e3, 5e3, 8e3, 1e4];
|
|
402
|
+
var LOOKUP_STEPS_MS = [1e3, 2e3, 4e3, 8e3, 15e3];
|
|
403
|
+
var POLL_MS = 3e3;
|
|
404
|
+
var POLL_SLOW_MS = 1e4;
|
|
405
|
+
var POLL_CAP_MS = 6e5;
|
|
406
|
+
var POLL_FAILURES = 20;
|
|
407
|
+
var OPEN_STEPS_MS = [1e3, 2e3, 4e3, 8e3, 15e3];
|
|
408
|
+
var OPEN_LATER_MS = 15e3;
|
|
409
|
+
var SIGN_OUT_MS = 3e3;
|
|
410
|
+
var IDLE = {
|
|
411
|
+
status: "idle",
|
|
412
|
+
anonymous: null,
|
|
413
|
+
conversation: null,
|
|
414
|
+
messages: [],
|
|
415
|
+
outgoing: null,
|
|
416
|
+
answer: null,
|
|
417
|
+
answering: false,
|
|
418
|
+
waiting: null,
|
|
419
|
+
stop: null,
|
|
420
|
+
error: null
|
|
421
|
+
};
|
|
422
|
+
function createChat(options) {
|
|
423
|
+
return new Client(options);
|
|
424
|
+
}
|
|
425
|
+
var Client = class {
|
|
426
|
+
constructor(o) {
|
|
427
|
+
this.s = IDLE;
|
|
428
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
429
|
+
this.auth = { kind: "cookie" };
|
|
430
|
+
this.who = null;
|
|
431
|
+
// the session's user: a token's sub and ext, "anonymous", or "cookie"
|
|
432
|
+
this.cookieless = false;
|
|
433
|
+
// learned once: this browser doesn't keep the chat's cookie
|
|
434
|
+
this.opening = null;
|
|
435
|
+
this.session = new AbortController();
|
|
436
|
+
// aborted by reopen, signOut and destroy
|
|
437
|
+
this.conv = new AbortController();
|
|
438
|
+
// aborted with the session, and by newConversation
|
|
439
|
+
this.convVersion = 0;
|
|
440
|
+
this.wantNew = false;
|
|
441
|
+
// newConversation before the session opened
|
|
442
|
+
this.sending = null;
|
|
443
|
+
this.watcher = null;
|
|
444
|
+
this.unsure = null;
|
|
445
|
+
// a message the chat may have stored: sending it again checks first
|
|
446
|
+
this.maxSeen = 0;
|
|
447
|
+
// message ids rise, so a newer message has a larger one
|
|
448
|
+
this.batching = false;
|
|
449
|
+
// a stream's chunk is applied at once: listeners hear it once
|
|
450
|
+
this.dirty = false;
|
|
451
|
+
this.dead = false;
|
|
452
|
+
this.getState = () => this.s;
|
|
453
|
+
this.subscribe = (listener) => {
|
|
454
|
+
if (typeof listener !== "function") throw new TypeError("subscribe needs a function");
|
|
455
|
+
if (!this.dead) this.listeners.add(listener);
|
|
456
|
+
this.call(listener);
|
|
457
|
+
return () => {
|
|
458
|
+
this.listeners.delete(listener);
|
|
459
|
+
};
|
|
460
|
+
};
|
|
461
|
+
this.open = () => {
|
|
462
|
+
if (this.dead || this.s.status === "ready") return Promise.resolve(this.s);
|
|
463
|
+
if (!this.opening) {
|
|
464
|
+
const p = this.doOpen();
|
|
465
|
+
this.opening = p;
|
|
466
|
+
const clear = () => {
|
|
467
|
+
if (this.opening === p) this.opening = null;
|
|
468
|
+
};
|
|
469
|
+
p.then(clear, clear);
|
|
470
|
+
}
|
|
471
|
+
return this.opening;
|
|
472
|
+
};
|
|
473
|
+
this.send = (text) => {
|
|
474
|
+
if (typeof text !== "string") throw new TypeError("send needs the message's text");
|
|
475
|
+
return this.doSend(text);
|
|
476
|
+
};
|
|
477
|
+
this.start = () => this.doStart();
|
|
478
|
+
this.newConversation = () => {
|
|
479
|
+
if (this.dead) return;
|
|
480
|
+
if (this.s.status !== "ready") this.wantNew = true;
|
|
481
|
+
this.dropConversation();
|
|
482
|
+
this.set({ conversation: null, messages: [], outgoing: null, answer: null, answering: false, waiting: null, stop: null, error: null });
|
|
483
|
+
};
|
|
484
|
+
this.reopen = (options) => {
|
|
485
|
+
if (options !== void 0 && (!options || typeof options !== "object")) throw new TypeError("reopen takes { token }");
|
|
486
|
+
const o = options || {};
|
|
487
|
+
for (const k of Object.keys(o)) if (k !== "token") throw new TypeError("unknown option " + k);
|
|
488
|
+
if ("token" in o) this.way = tokenWay(o.token);
|
|
489
|
+
else if (this.way.kind === "token") throw new TypeError("this client was given token: pass reopen({ token }), null when nobody is signed in");
|
|
490
|
+
if (this.dead) return Promise.resolve(this.s);
|
|
491
|
+
const idle = this.s.status === "idle";
|
|
492
|
+
this.forgetUser();
|
|
493
|
+
return idle ? Promise.resolve(this.s) : this.open();
|
|
494
|
+
};
|
|
495
|
+
this.signOut = async () => {
|
|
496
|
+
if (this.dead) return;
|
|
497
|
+
const auth = this.auth;
|
|
498
|
+
if (this.way.kind === "token") this.way = { kind: "token", token: null };
|
|
499
|
+
this.forgetUser();
|
|
500
|
+
const stop = new AbortController();
|
|
501
|
+
const t = setTimeout(() => stop.abort(), SIGN_OUT_MS);
|
|
502
|
+
try {
|
|
503
|
+
const bearer = auth.kind === "session" ? auth.token() : null;
|
|
504
|
+
discard(await request(this.fetchFn, this.base, { method: "DELETE", path: "/session", bearer, signal: stop.signal }));
|
|
505
|
+
} catch {
|
|
506
|
+
} finally {
|
|
507
|
+
clearTimeout(t);
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
this.destroy = () => {
|
|
511
|
+
if (this.dead) return;
|
|
512
|
+
this.dropSession();
|
|
513
|
+
this.dead = true;
|
|
514
|
+
this.listeners.clear();
|
|
515
|
+
};
|
|
516
|
+
if (!o || typeof o !== "object") throw new TypeError("createChat needs options");
|
|
517
|
+
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: your workspace's URL");
|
|
519
|
+
if (o.fetch !== void 0 && typeof o.fetch !== "function") throw new TypeError("fetch must be a function");
|
|
520
|
+
this.base = apiBase(o.url);
|
|
521
|
+
this.origin = originOf(this.base);
|
|
522
|
+
this.way = wayOf(o);
|
|
523
|
+
const f = o.fetch;
|
|
524
|
+
this.fetchFn = f ? (input, init) => f(input, init) : (input, init) => fetch(input, init);
|
|
525
|
+
}
|
|
526
|
+
// --- state
|
|
527
|
+
set(patch) {
|
|
528
|
+
this.s = { ...this.s, ...patch };
|
|
529
|
+
if (this.batching) this.dirty = true;
|
|
530
|
+
else this.emit();
|
|
531
|
+
}
|
|
532
|
+
emit() {
|
|
533
|
+
if (this.dead) return;
|
|
534
|
+
for (const l of Array.from(this.listeners)) this.call(l);
|
|
535
|
+
}
|
|
536
|
+
call(listener) {
|
|
537
|
+
try {
|
|
538
|
+
listener(this.s);
|
|
539
|
+
} catch (e) {
|
|
540
|
+
setTimeout(() => {
|
|
541
|
+
throw e;
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
seen(messages) {
|
|
546
|
+
for (const m of messages) if (m.id > this.maxSeen) this.maxSeen = m.id;
|
|
547
|
+
}
|
|
548
|
+
current(id) {
|
|
549
|
+
return this.s.conversation !== null && this.s.conversation.id === id;
|
|
550
|
+
}
|
|
551
|
+
dropConversation() {
|
|
552
|
+
this.conv.abort();
|
|
553
|
+
this.conv = new AbortController();
|
|
554
|
+
this.convVersion++;
|
|
555
|
+
this.sending = null;
|
|
556
|
+
this.watcher = null;
|
|
557
|
+
this.unsure = null;
|
|
558
|
+
}
|
|
559
|
+
dropSession() {
|
|
560
|
+
this.session.abort();
|
|
561
|
+
this.session = new AbortController();
|
|
562
|
+
this.opening = null;
|
|
563
|
+
this.dropConversation();
|
|
564
|
+
}
|
|
565
|
+
forgetUser() {
|
|
566
|
+
this.dropSession();
|
|
567
|
+
this.auth = { kind: "cookie" };
|
|
568
|
+
this.who = null;
|
|
569
|
+
this.wantNew = false;
|
|
570
|
+
this.maxSeen = 0;
|
|
571
|
+
this.s = IDLE;
|
|
572
|
+
this.emit();
|
|
573
|
+
}
|
|
574
|
+
// userChanged wipes what the page shows when a reopened session is someone
|
|
575
|
+
// else's, so nobody sees another's conversation or draft, then shows theirs.
|
|
576
|
+
userChanged(o) {
|
|
577
|
+
if (this.watcher) this.watcher.abort();
|
|
578
|
+
this.watcher = null;
|
|
579
|
+
this.convVersion++;
|
|
580
|
+
this.unsure = null;
|
|
581
|
+
this.wantNew = false;
|
|
582
|
+
this.maxSeen = 0;
|
|
583
|
+
this.s = { ...IDLE, status: "ready" };
|
|
584
|
+
this.show(o, this.convVersion, false);
|
|
585
|
+
}
|
|
586
|
+
// show applies an opened session; hide keeps its conversation off the page,
|
|
587
|
+
// after newConversation, while still learning its newest message.
|
|
588
|
+
show(o, version, hide2) {
|
|
589
|
+
this.seen(o.messages);
|
|
590
|
+
if (version !== this.convVersion) {
|
|
591
|
+
this.set({ anonymous: o.anonymous });
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
if (hide2) {
|
|
595
|
+
this.set({ anonymous: o.anonymous, conversation: null, messages: [], answering: false });
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
const answering = o.answering && o.conversation !== null;
|
|
599
|
+
this.set({ anonymous: o.anonymous, conversation: o.conversation, messages: merge(this.s.messages, o.messages), answering });
|
|
600
|
+
if (answering && o.conversation) this.watch(o.conversation.id);
|
|
601
|
+
}
|
|
602
|
+
forget(id) {
|
|
603
|
+
if (this.current(id)) this.set({ conversation: null, messages: [], answer: null, answering: false });
|
|
604
|
+
}
|
|
605
|
+
// --- opening
|
|
606
|
+
async doOpen() {
|
|
607
|
+
const session = this.session;
|
|
608
|
+
const version = this.convVersion;
|
|
609
|
+
const began = Date.now();
|
|
610
|
+
this.set({ status: "opening", error: null });
|
|
611
|
+
for (let tries = 0; ; tries++) {
|
|
612
|
+
try {
|
|
613
|
+
const o = await this.establish(session.signal);
|
|
614
|
+
if (session.signal.aborted) return this.s;
|
|
615
|
+
const hidden = this.wantNew;
|
|
616
|
+
this.wantNew = false;
|
|
617
|
+
this.show(o, version, hidden);
|
|
618
|
+
this.set({ status: "ready", waiting: null });
|
|
619
|
+
return this.s;
|
|
620
|
+
} catch (e) {
|
|
621
|
+
if (session.signal.aborted) return this.s;
|
|
622
|
+
const err = asChatError(e);
|
|
623
|
+
if (TRANSIENT.indexOf(err.code) < 0 || err.code === "token_failed") {
|
|
624
|
+
this.set({ status: "error", error: err, waiting: null });
|
|
625
|
+
return this.s;
|
|
626
|
+
}
|
|
627
|
+
const ms = openWait(err, tries, Date.now() - began);
|
|
628
|
+
this.set({ waiting: { code: err.code, until: Date.now() + ms } });
|
|
629
|
+
try {
|
|
630
|
+
await sleep(ms, session.signal);
|
|
631
|
+
} catch {
|
|
632
|
+
return this.s;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
// establish opens or resumes the session for the page's user and settles how
|
|
638
|
+
// requests carry it.
|
|
639
|
+
async establish(signal) {
|
|
640
|
+
const token = await userToken(this.way, this.fetchFn, signal, false);
|
|
641
|
+
if (typeof token !== "string") return this.openWithout(token === null, signal);
|
|
642
|
+
try {
|
|
643
|
+
return await this.openAs(token, signal);
|
|
644
|
+
} catch (e) {
|
|
645
|
+
if (!isCode(e, "token_expired") || !renews(this.way)) throw e;
|
|
646
|
+
}
|
|
647
|
+
const next = await userToken(this.way, this.fetchFn, signal, true);
|
|
648
|
+
if (typeof next !== "string") return this.openWithout(next === null, signal);
|
|
649
|
+
return this.openAs(next, signal);
|
|
650
|
+
}
|
|
651
|
+
async openAs(token, signal) {
|
|
652
|
+
if (!this.mayCarry(token)) throw notForThisChat(this.origin);
|
|
653
|
+
const who = whoOf(token);
|
|
654
|
+
if (this.cookieless) {
|
|
655
|
+
const o2 = await this.post({ cookieless: true }, token, signal);
|
|
656
|
+
this.auth = { kind: "token", token: hide(token) };
|
|
657
|
+
this.who = who;
|
|
658
|
+
return o2;
|
|
659
|
+
}
|
|
660
|
+
const o = await this.post({}, token, signal);
|
|
661
|
+
if (o.started && !await this.cookieKept(signal)) {
|
|
662
|
+
this.cookieless = true;
|
|
663
|
+
this.auth = { kind: "token", token: hide(token) };
|
|
664
|
+
} else {
|
|
665
|
+
this.auth = { kind: "cookie" };
|
|
666
|
+
}
|
|
667
|
+
this.who = who;
|
|
668
|
+
return o;
|
|
669
|
+
}
|
|
670
|
+
// openWithout opens with no customer's token. When the page says nobody is
|
|
671
|
+
// signed in, a signed-in session the browser still holds is ended first.
|
|
672
|
+
async openWithout(nobody, signal) {
|
|
673
|
+
const held = this.auth;
|
|
674
|
+
if (held.kind === "session") {
|
|
675
|
+
try {
|
|
676
|
+
const o2 = await this.post({}, held.token(), signal);
|
|
677
|
+
this.who = "anonymous";
|
|
678
|
+
return o2;
|
|
679
|
+
} catch (e) {
|
|
680
|
+
if (!isCode(e, "session_expired") && !isCode(e, "unauthorized")) throw e;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
this.auth = { kind: "cookie" };
|
|
684
|
+
if (this.cookieless) return this.openCookieless(signal);
|
|
685
|
+
if (nobody && await this.signedIn(signal)) await this.end(signal);
|
|
686
|
+
const o = await this.post({}, null, signal);
|
|
687
|
+
if (nobody && !o.anonymous) {
|
|
688
|
+
throw new ChatError("protocol", "The chat answered for a signed-in user on a page that says nobody is signed in.");
|
|
689
|
+
}
|
|
690
|
+
if (o.started && !await this.cookieKept(signal)) {
|
|
691
|
+
this.cookieless = true;
|
|
692
|
+
return this.openCookieless(signal);
|
|
693
|
+
}
|
|
694
|
+
this.who = o.anonymous ? "anonymous" : "cookie";
|
|
695
|
+
return o;
|
|
696
|
+
}
|
|
697
|
+
async openCookieless(signal) {
|
|
698
|
+
const o = await this.post({ cookieless: true }, null, signal);
|
|
699
|
+
if (!o.sessionToken) throw new ChatError("protocol", "The chat gave no session token.");
|
|
700
|
+
this.auth = { kind: "session", token: hide(o.sessionToken) };
|
|
701
|
+
this.who = "anonymous";
|
|
702
|
+
return o;
|
|
703
|
+
}
|
|
704
|
+
async post(body2, bearer, signal) {
|
|
705
|
+
const res = await request(this.fetchFn, this.base, { method: "POST", path: "/session", body: body2, bearer, signal });
|
|
706
|
+
if (!res.ok) throw await failure(res, signal);
|
|
707
|
+
const o = openedOf(await readJSON(res, signal));
|
|
708
|
+
live(signal);
|
|
709
|
+
return o;
|
|
710
|
+
}
|
|
711
|
+
// cookieKept asks, with the cookie alone, whether the browser kept the session it was just given.
|
|
712
|
+
async cookieKept(signal) {
|
|
713
|
+
const res = await request(this.fetchFn, this.base, { method: "GET", path: "/session", signal });
|
|
714
|
+
if (res.ok || res.status === 401) {
|
|
715
|
+
discard(res);
|
|
716
|
+
live(signal);
|
|
717
|
+
return res.ok;
|
|
718
|
+
}
|
|
719
|
+
throw await failure(res, signal);
|
|
720
|
+
}
|
|
721
|
+
// signedIn asks, with the cookie alone, whether the browser holds a signed-in
|
|
722
|
+
// session, without fetching that user's conversation. One the chat refuses to
|
|
723
|
+
// serve (403) is ended too: it's of no use to anyone.
|
|
724
|
+
async signedIn(signal) {
|
|
725
|
+
const res = await request(this.fetchFn, this.base, { method: "GET", path: "/session", signal });
|
|
726
|
+
if (res.status === 401 || res.status === 403) {
|
|
727
|
+
discard(res);
|
|
728
|
+
return res.status === 403;
|
|
729
|
+
}
|
|
730
|
+
if (!res.ok) throw await failure(res, signal);
|
|
731
|
+
const v = await readJSON(res, signal);
|
|
732
|
+
return !!v && typeof v === "object" && v.anonymous === false;
|
|
733
|
+
}
|
|
734
|
+
async end(signal) {
|
|
735
|
+
const res = await request(this.fetchFn, this.base, { method: "DELETE", path: "/session", signal });
|
|
736
|
+
if (!res.ok) throw await failure(res, signal);
|
|
737
|
+
discard(res);
|
|
738
|
+
}
|
|
739
|
+
// mayCarry: a token goes only to the chat its aud names, or to the page's own
|
|
740
|
+
// server, which forwards the chat.
|
|
741
|
+
mayCarry(token) {
|
|
742
|
+
const page = typeof location === "object" && location ? location.origin : null;
|
|
743
|
+
if (page === this.origin) return true;
|
|
744
|
+
const c = claimsOf(token);
|
|
745
|
+
return !!c && c.aud.some((a) => originOf(a) === this.origin);
|
|
746
|
+
}
|
|
747
|
+
// --- requests as the session's user
|
|
748
|
+
bearer() {
|
|
749
|
+
return this.auth.kind === "cookie" ? null : this.auth.token();
|
|
750
|
+
}
|
|
751
|
+
// authed makes a request as the session's user; a lapsed token or session is
|
|
752
|
+
// renewed or reopened once, for target's conversation.
|
|
753
|
+
async authed(c, signal, target) {
|
|
754
|
+
for (let retried = false; ; retried = true) {
|
|
755
|
+
const res = await request(this.fetchFn, this.base, { ...c, bearer: this.bearer(), signal });
|
|
756
|
+
if (res.status !== 401 || retried) return res;
|
|
757
|
+
const err = await failure(res, signal);
|
|
758
|
+
if (!await this.recoverAuth(err, signal, target)) throw err;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
// recoverAuth renews a lapsed token or reopens an ended session. It answers
|
|
762
|
+
// whether to try again, and throws session_expired when the user changed.
|
|
763
|
+
async recoverAuth(err, signal, target) {
|
|
764
|
+
if (this.auth.kind === "token" && (err.code === "token_expired" || err.code === "unauthorized")) {
|
|
765
|
+
if (!renews(this.way)) return false;
|
|
766
|
+
const token = await userToken(this.way, this.fetchFn, signal, err.code === "token_expired");
|
|
767
|
+
if (typeof token === "string" && whoOf(token) === this.who) {
|
|
768
|
+
if (!this.mayCarry(token)) throw notForThisChat(this.origin);
|
|
769
|
+
this.auth = { kind: "token", token: hide(token) };
|
|
770
|
+
return true;
|
|
771
|
+
}
|
|
772
|
+
} else if (err.code !== "session_expired" && err.code !== "unauthorized") {
|
|
773
|
+
return false;
|
|
774
|
+
}
|
|
775
|
+
const o = await this.reestablish(signal);
|
|
776
|
+
this.set({ anonymous: o.anonymous });
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
// reestablish opens the session again as the page's user, within the flow's
|
|
780
|
+
// signal, so a sign-out meanwhile stops it. Someone else's session wipes the
|
|
781
|
+
// page, and the caller fails with session_expired.
|
|
782
|
+
async reestablish(signal) {
|
|
783
|
+
live(signal);
|
|
784
|
+
const who = this.who;
|
|
785
|
+
const o = await this.establish(signal);
|
|
786
|
+
live(signal);
|
|
787
|
+
if (this.who !== who) {
|
|
788
|
+
this.userChanged(o);
|
|
789
|
+
throw new ChatError("session_expired", "Someone else is signed in now.", { status: 401 });
|
|
790
|
+
}
|
|
791
|
+
this.seen(o.messages);
|
|
792
|
+
return o;
|
|
793
|
+
}
|
|
794
|
+
// --- messages
|
|
795
|
+
async doSend(raw) {
|
|
796
|
+
const text = normalize(raw);
|
|
797
|
+
if (this.dead) return { ok: false, error: aborted() };
|
|
798
|
+
if (text === "") return { ok: false, error: new ChatError("bad_request", "The message is empty.") };
|
|
799
|
+
if (this.sending || this.s.answering) return { ok: false, error: busy() };
|
|
800
|
+
const mine = {};
|
|
801
|
+
this.sending = mine;
|
|
802
|
+
const scope = this.conv;
|
|
803
|
+
const recheck = this.unsure && this.unsure.text === text ? this.unsure : null;
|
|
804
|
+
this.unsure = null;
|
|
805
|
+
let began = -1;
|
|
806
|
+
this.set({ outgoing: text, error: null, stop: null });
|
|
807
|
+
try {
|
|
808
|
+
if (this.s.status !== "ready") {
|
|
809
|
+
const st = await this.open();
|
|
810
|
+
if (scope.signal.aborted || this.sending !== mine) return { ok: false, error: aborted() };
|
|
811
|
+
if (st.status !== "ready") return this.failed(mine, scope, st.error || new ChatError("unauthorized", "The chat couldn't be opened."), -1);
|
|
812
|
+
if (this.s.answering) return this.failed(mine, scope, busy(), -1);
|
|
813
|
+
}
|
|
814
|
+
began = this.convVersion;
|
|
815
|
+
this.set({ answering: true, answer: { text: "", tools: [] } });
|
|
816
|
+
const r = await this.deliver(text, scope.signal, recheck);
|
|
817
|
+
return { ok: true, message: r.message, stop: r.stop };
|
|
818
|
+
} catch (e) {
|
|
819
|
+
return this.failed(mine, scope, asChatError(e), began);
|
|
820
|
+
} finally {
|
|
821
|
+
if (this.sending === mine) this.sending = null;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
// doStart opens if need be, then has the assistant speak first; the chat
|
|
825
|
+
// supplies the instructions, so nothing of the page's is sent.
|
|
826
|
+
async doStart() {
|
|
827
|
+
if (this.dead) return { ok: false, error: aborted() };
|
|
828
|
+
if (this.sending || this.s.answering) return { ok: false, error: busy() };
|
|
829
|
+
const mine = {};
|
|
830
|
+
this.sending = mine;
|
|
831
|
+
const scope = this.conv;
|
|
832
|
+
let began = -1;
|
|
833
|
+
this.set({ error: null, stop: null });
|
|
834
|
+
try {
|
|
835
|
+
if (this.s.status !== "ready") {
|
|
836
|
+
const st = await this.open();
|
|
837
|
+
if (scope.signal.aborted || this.sending !== mine) return { ok: false, error: aborted() };
|
|
838
|
+
if (st.status !== "ready") return this.failed(mine, scope, st.error || new ChatError("unauthorized", "The chat couldn't be opened."), -1);
|
|
839
|
+
if (this.s.answering) return this.failed(mine, scope, busy(), -1);
|
|
840
|
+
}
|
|
841
|
+
began = this.convVersion;
|
|
842
|
+
this.set({ answering: true, answer: { text: "", tools: [] } });
|
|
843
|
+
const r = await this.begin(scope.signal);
|
|
844
|
+
return { ok: true, message: r.message, stop: r.stop };
|
|
845
|
+
} catch (e) {
|
|
846
|
+
return this.failed(mine, scope, asChatError(e), began);
|
|
847
|
+
} finally {
|
|
848
|
+
if (this.sending === mine) this.sending = null;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
// begin asks for the start and reads its answer. Only refusals before the
|
|
852
|
+
// chat starts are tried again; a start never lands twice. With no
|
|
853
|
+
// conversation shown, after newConversation say, it asks for a new one.
|
|
854
|
+
async begin(signal) {
|
|
855
|
+
const sent = { text: "", target: null, known: this.maxSeen };
|
|
856
|
+
const call = this.s.conversation === null ? { method: "POST", path: "/start", body: { new: true }, stream: true } : { method: "POST", path: "/start", stream: true };
|
|
857
|
+
const waitUntil = Date.now() + WAIT_CAP_MS;
|
|
858
|
+
const busyUntil = Date.now() + BUSY_CAP_MS;
|
|
859
|
+
for (let busyTries = 0; ; ) {
|
|
860
|
+
const stream = new AbortController();
|
|
861
|
+
const stop = () => stream.abort();
|
|
862
|
+
signal.addEventListener("abort", stop);
|
|
863
|
+
try {
|
|
864
|
+
let res;
|
|
865
|
+
try {
|
|
866
|
+
res = await this.authed(call, stream.signal, null);
|
|
867
|
+
} catch (e) {
|
|
868
|
+
if (signal.aborted) throw aborted();
|
|
869
|
+
const reopen = isChatError(e) ? waitFor(e) : null;
|
|
870
|
+
if (reopen !== null && Date.now() + reopen <= waitUntil) {
|
|
871
|
+
await this.pause(e.code, reopen, signal);
|
|
872
|
+
continue;
|
|
873
|
+
}
|
|
874
|
+
throw e;
|
|
875
|
+
}
|
|
876
|
+
if (res.ok) return await this.read(res, stream, signal, sent);
|
|
877
|
+
const err = await failure(res, signal);
|
|
878
|
+
const wait = waitFor(err);
|
|
879
|
+
if (wait !== null && Date.now() + wait <= waitUntil) {
|
|
880
|
+
await this.pause(err.code, wait, signal);
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
883
|
+
if (err.code === "busy" && Date.now() < busyUntil) {
|
|
884
|
+
await this.pause("busy", BUSY_STEPS_MS[Math.min(busyTries++, BUSY_STEPS_MS.length - 1)], signal);
|
|
885
|
+
continue;
|
|
886
|
+
}
|
|
887
|
+
throw err;
|
|
888
|
+
} finally {
|
|
889
|
+
signal.removeEventListener("abort", stop);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
// failed shows a failure. A message the page doesn't show as stored stays in
|
|
894
|
+
// outgoing, so it can be sent again. began is the conversation version this
|
|
895
|
+
// send set answering in; once the page shows another, answering is not its own.
|
|
896
|
+
failed(mine, scope, err, began) {
|
|
897
|
+
if (this.sending === mine && !scope.signal.aborted && err.code !== "aborted") {
|
|
898
|
+
if (began < 0) this.set({ error: err });
|
|
899
|
+
else if (began === this.convVersion) this.set({ answer: null, answering: false, waiting: null, error: err });
|
|
900
|
+
else this.set({ answer: null, waiting: null, error: err });
|
|
901
|
+
}
|
|
902
|
+
return { ok: false, error: err };
|
|
903
|
+
}
|
|
904
|
+
// deliver sends the message and reads its answer. Only refusals that come
|
|
905
|
+
// before the chat stores it are tried again: nothing after a 200 is resent.
|
|
906
|
+
async deliver(text, signal, recheck) {
|
|
907
|
+
if (recheck) {
|
|
908
|
+
const id = await this.landedSoon(recheck, signal, null);
|
|
909
|
+
if (id !== null) return this.follow(id, recheck, signal);
|
|
910
|
+
}
|
|
911
|
+
const sent = { text, target: this.s.conversation ? this.s.conversation.id : null, known: this.maxSeen };
|
|
912
|
+
const path = sent.target === null ? "/conversations" : "/conversations/" + encodeURIComponent(sent.target) + "/messages";
|
|
913
|
+
const waitUntil = Date.now() + WAIT_CAP_MS;
|
|
914
|
+
const busyUntil = Date.now() + BUSY_CAP_MS;
|
|
915
|
+
for (let busyTries = 0; ; ) {
|
|
916
|
+
const stream = new AbortController();
|
|
917
|
+
const stop = () => stream.abort();
|
|
918
|
+
signal.addEventListener("abort", stop);
|
|
919
|
+
try {
|
|
920
|
+
let res;
|
|
921
|
+
try {
|
|
922
|
+
res = await this.authed({ method: "POST", path, body: { text }, stream: true }, stream.signal, sent.target);
|
|
923
|
+
} catch (e) {
|
|
924
|
+
if (signal.aborted) throw aborted();
|
|
925
|
+
if (isCode(e, "network")) return await this.ifLanded(e, sent, signal);
|
|
926
|
+
const reopen = isChatError(e) ? waitFor(e) : null;
|
|
927
|
+
if (reopen !== null && Date.now() + reopen <= waitUntil) {
|
|
928
|
+
await this.pause(e.code, reopen, signal);
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
931
|
+
throw e;
|
|
932
|
+
}
|
|
933
|
+
if (res.ok) return await this.read(res, stream, signal, sent);
|
|
934
|
+
const err = await failure(res, signal);
|
|
935
|
+
if (err.code === "internal") return await this.ifLanded(err, sent, signal);
|
|
936
|
+
if (err.code === "not_found" && sent.target !== null) this.forget(sent.target);
|
|
937
|
+
const wait = waitFor(err);
|
|
938
|
+
if (wait !== null && Date.now() + wait <= waitUntil) {
|
|
939
|
+
await this.pause(err.code, wait, signal);
|
|
940
|
+
continue;
|
|
941
|
+
}
|
|
942
|
+
if (err.code === "busy" && Date.now() < busyUntil) {
|
|
943
|
+
await this.pause("busy", BUSY_STEPS_MS[Math.min(busyTries++, BUSY_STEPS_MS.length - 1)], signal);
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
throw err;
|
|
947
|
+
} finally {
|
|
948
|
+
signal.removeEventListener("abort", stop);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
async pause(code, ms, signal) {
|
|
953
|
+
live(signal);
|
|
954
|
+
this.set({ waiting: { code, until: Date.now() + ms } });
|
|
955
|
+
try {
|
|
956
|
+
await sleep(ms, signal);
|
|
957
|
+
} finally {
|
|
958
|
+
if (!signal.aborted) this.set({ waiting: null });
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
// ifLanded settles a request whose outcome is unknown, a lost connection or a
|
|
962
|
+
// 500: the message may have been stored, so the conversation decides.
|
|
963
|
+
async ifLanded(err, sent, signal) {
|
|
964
|
+
const id = await this.landedSoon(sent, signal, err);
|
|
965
|
+
if (id === null) throw err;
|
|
966
|
+
return this.follow(id, sent, signal);
|
|
967
|
+
}
|
|
968
|
+
// landedSoon looks for the message, trying again while the chat can't be
|
|
969
|
+
// reached. It answers null only when a lookup said the message isn't there;
|
|
970
|
+
// when none could tell, it throws, and sending the text again checks first.
|
|
971
|
+
async landedSoon(sent, signal, cause) {
|
|
972
|
+
const version = this.convVersion;
|
|
973
|
+
let last = null;
|
|
974
|
+
for (const ms of LOOKUP_STEPS_MS) {
|
|
975
|
+
await sleep(ms, signal);
|
|
976
|
+
try {
|
|
977
|
+
return await this.landed(sent, signal);
|
|
978
|
+
} catch (e) {
|
|
979
|
+
if (signal.aborted) throw aborted();
|
|
980
|
+
last = asChatError(e);
|
|
981
|
+
if (this.convVersion !== version) throw last;
|
|
982
|
+
if (last.code === "not_found") return null;
|
|
983
|
+
if (TRANSIENT.indexOf(last.code) < 0) break;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
this.unsure = sent;
|
|
987
|
+
if (last && TRANSIENT.indexOf(last.code) < 0) throw last;
|
|
988
|
+
throw cause || last || new ChatError("network", "The chat couldn't be reached.");
|
|
989
|
+
}
|
|
990
|
+
// landed finds the conversation that holds the message sent, if the chat
|
|
991
|
+
// stored it, and shows it. A new conversation holds nothing older than known.
|
|
992
|
+
async landed(sent, signal) {
|
|
993
|
+
const mine = (m) => m.role === "user" && m.id > sent.known && m.text === sent.text;
|
|
994
|
+
let found = null;
|
|
995
|
+
if (sent.target !== null) {
|
|
996
|
+
const v = await this.view(sent.target, signal);
|
|
997
|
+
if (v.messages.some(mine)) found = v;
|
|
998
|
+
} else {
|
|
999
|
+
const o = await this.latest(signal);
|
|
1000
|
+
if (o.conversation && o.messages.some(mine) && o.messages.every((m) => m.id > sent.known)) {
|
|
1001
|
+
found = { conversation: o.conversation, messages: o.messages };
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
live(signal);
|
|
1005
|
+
if (!found) return null;
|
|
1006
|
+
this.seen(found.messages);
|
|
1007
|
+
this.set({ conversation: found.conversation, messages: merge(this.s.messages, found.messages), outgoing: null });
|
|
1008
|
+
return found.conversation.id;
|
|
1009
|
+
}
|
|
1010
|
+
// latest opens the session as it is, for its latest conversation: a live
|
|
1011
|
+
// cookie needs no token, which may have expired meanwhile. A lapsed session is
|
|
1012
|
+
// reopened as the page's user, never swapped for an anonymous one.
|
|
1013
|
+
async latest(signal) {
|
|
1014
|
+
if (this.auth.kind === "cookie") {
|
|
1015
|
+
const res = await request(this.fetchFn, this.base, { method: "GET", path: "/session", signal });
|
|
1016
|
+
if (res.ok) {
|
|
1017
|
+
discard(res);
|
|
1018
|
+
const o = await this.post({}, null, signal);
|
|
1019
|
+
if (!o.started) return o;
|
|
1020
|
+
} else if (res.status === 401) {
|
|
1021
|
+
discard(res);
|
|
1022
|
+
} else {
|
|
1023
|
+
throw await failure(res, signal);
|
|
1024
|
+
}
|
|
1025
|
+
return this.reestablish(signal);
|
|
1026
|
+
}
|
|
1027
|
+
try {
|
|
1028
|
+
return await this.post(this.auth.kind === "token" ? { cookieless: true } : {}, this.bearer(), signal);
|
|
1029
|
+
} catch (e) {
|
|
1030
|
+
if (!isCode(e, "token_expired") && !isCode(e, "session_expired") && !isCode(e, "unauthorized")) throw e;
|
|
1031
|
+
return this.reestablish(signal);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
// read applies the stream's events. A stream that ends without done or error
|
|
1035
|
+
// lost the answer, which runs on and is stored, so the conversation is followed.
|
|
1036
|
+
async read(res, stream, signal, sent) {
|
|
1037
|
+
let conversation = sent.target;
|
|
1038
|
+
let message = false;
|
|
1039
|
+
const reader = res.body ? res.body.getReader() : null;
|
|
1040
|
+
if (reader) {
|
|
1041
|
+
const decoder = new TextDecoder();
|
|
1042
|
+
const parser = new SSEParser();
|
|
1043
|
+
const cancel = () => {
|
|
1044
|
+
reader.cancel().catch(() => {
|
|
1045
|
+
});
|
|
1046
|
+
};
|
|
1047
|
+
stream.signal.addEventListener("abort", cancel, { once: true });
|
|
1048
|
+
if (stream.signal.aborted) cancel();
|
|
1049
|
+
let stall = setTimeout(() => stream.abort(), STALL_MS);
|
|
1050
|
+
const cap = setTimeout(() => stream.abort(), STREAM_CAP_MS);
|
|
1051
|
+
try {
|
|
1052
|
+
for (; ; ) {
|
|
1053
|
+
const { value, done } = await reader.read();
|
|
1054
|
+
if (signal.aborted) throw aborted();
|
|
1055
|
+
if (done) break;
|
|
1056
|
+
clearTimeout(stall);
|
|
1057
|
+
stall = setTimeout(() => stream.abort(), STALL_MS);
|
|
1058
|
+
this.batching = true;
|
|
1059
|
+
try {
|
|
1060
|
+
for (const ev of parser.push(decoder.decode(value, { stream: true }))) {
|
|
1061
|
+
if (signal.aborted) throw aborted();
|
|
1062
|
+
if (ev.event === "message" && message) continue;
|
|
1063
|
+
if (ev.event === "message") message = true;
|
|
1064
|
+
const out = this.event(ev.event, ev.data);
|
|
1065
|
+
if (!out) continue;
|
|
1066
|
+
if ("conversation" in out) conversation = out.conversation;
|
|
1067
|
+
else return out;
|
|
1068
|
+
}
|
|
1069
|
+
} finally {
|
|
1070
|
+
this.batching = false;
|
|
1071
|
+
if (this.dirty) {
|
|
1072
|
+
this.dirty = false;
|
|
1073
|
+
this.emit();
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
} catch (e) {
|
|
1078
|
+
if (signal.aborted) throw aborted();
|
|
1079
|
+
if (isChatError(e) && e.code !== "protocol") throw e;
|
|
1080
|
+
} finally {
|
|
1081
|
+
clearTimeout(stall);
|
|
1082
|
+
clearTimeout(cap);
|
|
1083
|
+
stream.signal.removeEventListener("abort", cancel);
|
|
1084
|
+
cancel();
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
if (signal.aborted) throw aborted();
|
|
1088
|
+
return this.follow(conversation, { ...sent, target: conversation }, signal);
|
|
1089
|
+
}
|
|
1090
|
+
// event applies one event: it answers the reply when done, the conversation
|
|
1091
|
+
// when one starts, and throws the answer's error.
|
|
1092
|
+
event(name, data) {
|
|
1093
|
+
if (EVENTS.indexOf(name) < 0) return null;
|
|
1094
|
+
let o;
|
|
1095
|
+
try {
|
|
1096
|
+
const v = JSON.parse(data);
|
|
1097
|
+
o = v && typeof v === "object" ? v : {};
|
|
1098
|
+
} catch {
|
|
1099
|
+
throw new ChatError("protocol", "The chat's stream couldn't be read.");
|
|
1100
|
+
}
|
|
1101
|
+
switch (name) {
|
|
1102
|
+
case "conversation": {
|
|
1103
|
+
const c = conversationOf(o);
|
|
1104
|
+
if (this.s.conversation && this.s.conversation.id === c.id) this.set({ conversation: c });
|
|
1105
|
+
else this.set({ conversation: c, messages: [] });
|
|
1106
|
+
return { conversation: c.id };
|
|
1107
|
+
}
|
|
1108
|
+
case "message": {
|
|
1109
|
+
const m = messageOf(o);
|
|
1110
|
+
this.seen([m]);
|
|
1111
|
+
this.set({ messages: withMessage(this.s.messages, m), outgoing: null });
|
|
1112
|
+
return null;
|
|
1113
|
+
}
|
|
1114
|
+
case "delta": {
|
|
1115
|
+
const a = this.s.answer || { text: "", tools: [] };
|
|
1116
|
+
if (typeof o.text !== "string" || o.text === "" || a.text.length >= ANSWER_CAP) return null;
|
|
1117
|
+
this.set({ answer: { text: a.text + o.text, tools: a.tools } });
|
|
1118
|
+
return null;
|
|
1119
|
+
}
|
|
1120
|
+
case "tool": {
|
|
1121
|
+
const a = this.s.answer || { text: "", tools: [] };
|
|
1122
|
+
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.set({ answer: { text: a.text, tools } });
|
|
1125
|
+
return null;
|
|
1126
|
+
}
|
|
1127
|
+
case "done": {
|
|
1128
|
+
const m = messageOf(o.message);
|
|
1129
|
+
const stop = typeof o.stop === "string" ? o.stop : null;
|
|
1130
|
+
this.seen([m]);
|
|
1131
|
+
this.set({ messages: withMessage(this.s.messages, m), outgoing: null, answer: null, answering: false, waiting: null, stop });
|
|
1132
|
+
return { message: m, stop };
|
|
1133
|
+
}
|
|
1134
|
+
default: {
|
|
1135
|
+
const partial = o.partial ? messageOf(o.partial) : null;
|
|
1136
|
+
if (partial) this.seen([partial]);
|
|
1137
|
+
this.set({ messages: partial ? withMessage(this.s.messages, partial) : this.s.messages, outgoing: null, answer: null, answering: false });
|
|
1138
|
+
const code = typeof o.error === "string" && o.error !== "" ? o.error : "unavailable";
|
|
1139
|
+
throw new ChatError(code, typeof o.message === "string" ? o.message : "The answer failed.", { status: 200, partial });
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
// follow waits for an answer whose stream was lost: the conversation, found
|
|
1144
|
+
// through the session when its first event never came, is asked for until
|
|
1145
|
+
// it's answered. The message is stored, so a failure here leaves it unsure.
|
|
1146
|
+
async follow(id, sent, signal) {
|
|
1147
|
+
const start = sent.text === "";
|
|
1148
|
+
if (id === null && start) throw new ChatError("network", "The answer was lost.");
|
|
1149
|
+
const cid = id !== null ? id : await this.landedSoon(sent, signal, null);
|
|
1150
|
+
if (cid === null) {
|
|
1151
|
+
this.unsure = sent;
|
|
1152
|
+
throw new ChatError("no_answer", "The answer was lost.");
|
|
1153
|
+
}
|
|
1154
|
+
const version = this.convVersion;
|
|
1155
|
+
let v;
|
|
1156
|
+
try {
|
|
1157
|
+
v = await this.poll(cid, signal);
|
|
1158
|
+
} catch (e) {
|
|
1159
|
+
if (!start && !signal.aborted && !isCode(e, "not_found") && version === this.convVersion) this.unsure = { ...sent, target: cid };
|
|
1160
|
+
throw e;
|
|
1161
|
+
}
|
|
1162
|
+
live(signal);
|
|
1163
|
+
if (this.current(cid)) this.set({ outgoing: null, answer: null, waiting: null });
|
|
1164
|
+
let reply;
|
|
1165
|
+
if (start) {
|
|
1166
|
+
reply = v.messages.filter((m) => m.role === "assistant" && m.id > sent.known).pop();
|
|
1167
|
+
} else {
|
|
1168
|
+
let i = v.messages.length - 1;
|
|
1169
|
+
while (i >= 0 && !(v.messages[i].role === "user" && v.messages[i].id > sent.known && v.messages[i].text === sent.text)) i--;
|
|
1170
|
+
reply = i >= 0 ? v.messages.slice(i + 1).find((m) => m.role === "assistant") : void 0;
|
|
1171
|
+
}
|
|
1172
|
+
if (!reply) throw new ChatError("no_answer", "The assistant didn't answer.");
|
|
1173
|
+
return { message: reply, stop: null };
|
|
1174
|
+
}
|
|
1175
|
+
async view(id, signal) {
|
|
1176
|
+
const res = await this.authed({ method: "GET", path: "/conversations/" + encodeURIComponent(id) }, signal, id);
|
|
1177
|
+
if (!res.ok) throw await failure(res, signal);
|
|
1178
|
+
return viewOf(await readJSON(res, signal));
|
|
1179
|
+
}
|
|
1180
|
+
// poll asks for the conversation every few seconds until no answer is being
|
|
1181
|
+
// written in it, then shows what was stored.
|
|
1182
|
+
async poll(id, signal) {
|
|
1183
|
+
const started = Date.now();
|
|
1184
|
+
let failures = 0;
|
|
1185
|
+
for (; ; ) {
|
|
1186
|
+
const elapsed = Date.now() - started;
|
|
1187
|
+
if (elapsed >= POLL_CAP_MS) throw new ChatError("timeout", "The answer took too long.");
|
|
1188
|
+
await sleep(elapsed < 6e4 ? POLL_MS : POLL_SLOW_MS, signal);
|
|
1189
|
+
let v;
|
|
1190
|
+
try {
|
|
1191
|
+
v = await this.view(id, signal);
|
|
1192
|
+
} catch (e) {
|
|
1193
|
+
if (signal.aborted) throw aborted();
|
|
1194
|
+
const err = asChatError(e);
|
|
1195
|
+
if (err.code === "not_found") this.forget(id);
|
|
1196
|
+
else if (TRANSIENT.indexOf(err.code) >= 0 && ++failures < POLL_FAILURES) continue;
|
|
1197
|
+
throw err;
|
|
1198
|
+
}
|
|
1199
|
+
failures = 0;
|
|
1200
|
+
live(signal);
|
|
1201
|
+
if (v.answering) continue;
|
|
1202
|
+
if (this.current(id)) {
|
|
1203
|
+
this.seen(v.messages);
|
|
1204
|
+
this.set({ conversation: v.conversation, messages: merge(this.s.messages, v.messages), answering: false });
|
|
1205
|
+
}
|
|
1206
|
+
return v;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
// watch follows an answer this page didn't start, such as one a previous
|
|
1210
|
+
// page left running; a newer watch replaces it.
|
|
1211
|
+
watch(id) {
|
|
1212
|
+
if (this.watcher) this.watcher.abort();
|
|
1213
|
+
const w = new AbortController();
|
|
1214
|
+
this.watcher = w;
|
|
1215
|
+
const scope = this.conv.signal;
|
|
1216
|
+
const stop = () => w.abort();
|
|
1217
|
+
scope.addEventListener("abort", stop, { once: true });
|
|
1218
|
+
this.poll(id, w.signal).then(
|
|
1219
|
+
() => {
|
|
1220
|
+
},
|
|
1221
|
+
() => {
|
|
1222
|
+
if (!w.signal.aborted && this.current(id)) this.set({ answering: false });
|
|
1223
|
+
}
|
|
1224
|
+
).then(() => {
|
|
1225
|
+
scope.removeEventListener("abort", stop);
|
|
1226
|
+
if (this.watcher === w) this.watcher = null;
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
};
|
|
1230
|
+
function openWait(err, tries, elapsed) {
|
|
1231
|
+
const said = waitFor(err);
|
|
1232
|
+
if (elapsed < WAIT_CAP_MS) return said != null ? said : OPEN_STEPS_MS[Math.min(tries, OPEN_STEPS_MS.length - 1)];
|
|
1233
|
+
return Math.max(said != null ? said : 0, OPEN_LATER_MS + Math.random() * OPEN_LATER_MS);
|
|
1234
|
+
}
|
|
1235
|
+
function waitFor(err) {
|
|
1236
|
+
if (err.code !== "rate_limited" && err.code !== "overloaded" && err.code !== "not_connected") return null;
|
|
1237
|
+
const secs = err.retryAfter === null ? 5 : Math.min(Math.max(err.retryAfter, 1), 60);
|
|
1238
|
+
return secs * 1e3;
|
|
1239
|
+
}
|
|
1240
|
+
function busy() {
|
|
1241
|
+
return new ChatError("busy", "Still answering the previous message.");
|
|
1242
|
+
}
|
|
1243
|
+
function notForThisChat(origin) {
|
|
1244
|
+
return new ChatError("token_failed", "The token is for another chat: its aud must be " + origin + ".");
|
|
1245
|
+
}
|
|
1246
|
+
function live(signal) {
|
|
1247
|
+
if (signal.aborted) throw aborted();
|
|
1248
|
+
}
|
|
1249
|
+
function isCode(e, code) {
|
|
1250
|
+
return isChatError(e) && e.code === code;
|
|
1251
|
+
}
|
|
1252
|
+
function asChatError(e) {
|
|
1253
|
+
if (isChatError(e)) return e;
|
|
1254
|
+
return new ChatError("protocol", e instanceof Error ? e.message : "Something went wrong.", { cause: e });
|
|
1255
|
+
}
|
|
1256
|
+
function whoOf(token) {
|
|
1257
|
+
const c = claimsOf(token);
|
|
1258
|
+
return c ? c.who : "token";
|
|
1259
|
+
}
|
|
1260
|
+
function normalize(s) {
|
|
1261
|
+
let out = "";
|
|
1262
|
+
let from = 0;
|
|
1263
|
+
for (let i = 0; i < s.length; i++) {
|
|
1264
|
+
const c = s.charCodeAt(i);
|
|
1265
|
+
if (c >= 55296 && c <= 56319 && i + 1 < s.length && (s.charCodeAt(i + 1) & 64512) === 56320) {
|
|
1266
|
+
i++;
|
|
1267
|
+
} else if ((c & 63488) === 55296) {
|
|
1268
|
+
out += s.slice(from, i) + String.fromCharCode(65533);
|
|
1269
|
+
from = i + 1;
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
const t = from === 0 ? s : out + s.slice(from);
|
|
1273
|
+
let a = 0;
|
|
1274
|
+
let b = t.length;
|
|
1275
|
+
while (a < b && goSpace(t.charCodeAt(a))) a++;
|
|
1276
|
+
while (b > a && goSpace(t.charCodeAt(b - 1))) b--;
|
|
1277
|
+
return t.slice(a, b);
|
|
1278
|
+
}
|
|
1279
|
+
function goSpace(c) {
|
|
1280
|
+
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;
|
|
1281
|
+
}
|
|
1282
|
+
function merge(old, fresh) {
|
|
1283
|
+
const byId = new Map(old.map((m) => [m.id, m]));
|
|
1284
|
+
return fresh.map((m) => {
|
|
1285
|
+
const o = byId.get(m.id);
|
|
1286
|
+
return o && o.text === m.text && o.role === m.role && o.createdAt === m.createdAt && String(o.tools) === String(m.tools) ? o : m;
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
function withMessage(list, m) {
|
|
1290
|
+
return list.some((x) => x.id === m.id) ? list.map((x) => x.id === m.id ? m : x) : list.concat(m);
|
|
1291
|
+
}
|
|
1292
|
+
function withTool(tools, name, status) {
|
|
1293
|
+
if (status !== "started") {
|
|
1294
|
+
for (let i = tools.length - 1; i >= 0; i--) {
|
|
1295
|
+
if (tools[i].name === name && tools[i].status === "started") {
|
|
1296
|
+
return tools.slice(0, i).concat({ name, status }, tools.slice(i + 1));
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
return tools.length >= TOOLS_CAP ? tools : tools.concat({ name, status });
|
|
1301
|
+
}
|
|
1302
|
+
function bad(what) {
|
|
1303
|
+
return new ChatError("protocol", "The chat sent " + what + " the client can't read.");
|
|
1304
|
+
}
|
|
1305
|
+
function conversationOf(v) {
|
|
1306
|
+
var _a, _b;
|
|
1307
|
+
const o = v;
|
|
1308
|
+
if (!o || typeof o !== "object" || typeof o.id !== "string") throw bad("a conversation");
|
|
1309
|
+
return { id: o.id, createdAt: String((_a = o.created_at) != null ? _a : ""), updatedAt: String((_b = o.updated_at) != null ? _b : "") };
|
|
1310
|
+
}
|
|
1311
|
+
function messageOf(v) {
|
|
1312
|
+
var _a;
|
|
1313
|
+
const o = v;
|
|
1314
|
+
if (!o || typeof o !== "object" || typeof o.id !== "number" || typeof o.text !== "string" || o.role !== "user" && o.role !== "assistant") {
|
|
1315
|
+
throw bad("a message");
|
|
1316
|
+
}
|
|
1317
|
+
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)) m.tools = o.tools.filter((t) => typeof t === "string");
|
|
1319
|
+
return m;
|
|
1320
|
+
}
|
|
1321
|
+
function messagesOf(v) {
|
|
1322
|
+
if (!Array.isArray(v)) return [];
|
|
1323
|
+
return v.filter((m) => m && typeof m === "object" && (m.role === "user" || m.role === "assistant")).map(messageOf);
|
|
1324
|
+
}
|
|
1325
|
+
function openedOf(v) {
|
|
1326
|
+
const o = v;
|
|
1327
|
+
if (!o || typeof o !== "object") throw bad("a session");
|
|
1328
|
+
return {
|
|
1329
|
+
anonymous: o.anonymous === true,
|
|
1330
|
+
started: o.started === true,
|
|
1331
|
+
conversation: o.conversation ? conversationOf(o.conversation) : null,
|
|
1332
|
+
messages: messagesOf(o.messages),
|
|
1333
|
+
answering: o.answering === true,
|
|
1334
|
+
sessionToken: typeof o.session_token === "string" && o.session_token !== "" ? o.session_token : null
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
function viewOf(v) {
|
|
1338
|
+
const o = v;
|
|
1339
|
+
if (!o || typeof o !== "object") throw bad("a conversation");
|
|
1340
|
+
return { conversation: conversationOf(o.conversation), messages: messagesOf(o.messages), answering: o.answering === true };
|
|
1341
|
+
}
|
|
1342
|
+
export {
|
|
1343
|
+
ChatError,
|
|
1344
|
+
createChat,
|
|
1345
|
+
isChatError
|
|
1346
|
+
};
|
|
1347
|
+
//# sourceMappingURL=index.js.map
|