@argentic/chest-sdk 0.1.1 → 0.3.0

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.
Files changed (57) hide show
  1. package/README.md +573 -37
  2. package/client/index.ts +12 -5
  3. package/client/src/ai.ts +374 -0
  4. package/client/src/api.ts +85 -0
  5. package/client/src/chest.ts +80 -0
  6. package/client/src/errors.ts +58 -3
  7. package/client/src/events.ts +228 -0
  8. package/client/src/files.ts +93 -88
  9. package/client/src/member.ts +61 -17
  10. package/client/src/members.ts +167 -0
  11. package/client/src/notifications.ts +148 -0
  12. package/client/src/testing.ts +564 -0
  13. package/dist/index.d.ts +5 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +12 -5
  16. package/dist/index.js.map +1 -1
  17. package/dist/src/ai.d.ts +131 -0
  18. package/dist/src/ai.d.ts.map +1 -0
  19. package/dist/src/ai.js +290 -0
  20. package/dist/src/ai.js.map +1 -0
  21. package/dist/src/api.d.ts +11 -0
  22. package/dist/src/api.d.ts.map +1 -0
  23. package/dist/src/api.js +93 -0
  24. package/dist/src/api.js.map +1 -0
  25. package/dist/src/chest.d.ts +10 -0
  26. package/dist/src/chest.d.ts.map +1 -0
  27. package/dist/src/chest.js +49 -0
  28. package/dist/src/chest.js.map +1 -0
  29. package/dist/src/errors.d.ts +19 -0
  30. package/dist/src/errors.d.ts.map +1 -1
  31. package/dist/src/errors.js +49 -3
  32. package/dist/src/errors.js.map +1 -1
  33. package/dist/src/events.d.ts +56 -0
  34. package/dist/src/events.d.ts.map +1 -0
  35. package/dist/src/events.js +193 -0
  36. package/dist/src/events.js.map +1 -0
  37. package/dist/src/files.d.ts +17 -1
  38. package/dist/src/files.d.ts.map +1 -1
  39. package/dist/src/files.js +95 -92
  40. package/dist/src/files.js.map +1 -1
  41. package/dist/src/member.d.ts +10 -3
  42. package/dist/src/member.d.ts.map +1 -1
  43. package/dist/src/member.js +34 -11
  44. package/dist/src/member.js.map +1 -1
  45. package/dist/src/members.d.ts +34 -0
  46. package/dist/src/members.d.ts.map +1 -0
  47. package/dist/src/members.js +146 -0
  48. package/dist/src/members.js.map +1 -0
  49. package/dist/src/notifications.d.ts +25 -0
  50. package/dist/src/notifications.d.ts.map +1 -0
  51. package/dist/src/notifications.js +121 -0
  52. package/dist/src/notifications.js.map +1 -0
  53. package/dist/src/testing.d.ts +101 -0
  54. package/dist/src/testing.d.ts.map +1 -0
  55. package/dist/src/testing.js +552 -0
  56. package/dist/src/testing.js.map +1 -0
  57. package/package.json +40 -4
@@ -0,0 +1,552 @@
1
+ import { createHash, createHmac, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { groupIdPattern, memberIdPattern } from "./member.js";
4
+ import { forget } from "./members.js";
5
+ const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
6
+ // signAssertion is the Chest-Member value the Chest's front would send for
7
+ // that member: HS256 under the key of the token, for the tool, valid 60
8
+ // seconds from when it is issued.
9
+ export function signAssertion(member, options = {}) {
10
+ const token = options.token ?? process.env["CHEST_TOKEN"];
11
+ const tool = options.tool ?? process.env["CHEST_TOOL"];
12
+ if (!token || !tool)
13
+ throw new Error("signAssertion needs a token and a tool: start a fakeChest, or name them");
14
+ if (!memberIdPattern.test(member.id) || !member.groups.every(g => groupIdPattern.test(g)))
15
+ throw new Error("signAssertion needs identifiers of the Chest's shape (mbr_…, grp_…)");
16
+ const iat = Math.floor((options.now ?? new Date()).getTime() / 1000);
17
+ const body = encode({ alg: "HS256", typ: "JWT" }) + "." + encode({
18
+ iss: `https://${tool}-chest.chest.test`, aud: tool, iat, exp: iat + 60, sub: member.id,
19
+ given_name: member.firstName, family_name: member.lastName, name: member.name, picture: member.photo ?? "", role: member.role ?? "",
20
+ admin: member.isAdmin, builder: member.isBuilder, groups: member.groups, time_zone: member.timeZone, ...(member.email === undefined ? {} : { email: member.email }),
21
+ language: member.language,
22
+ });
23
+ // The key as the Chest derives it, and member() reads it: HMAC-SHA256 of
24
+ // the label of the assertion's shape under the text of the token.
25
+ const key = createHmac("sha256", Buffer.from(token, "utf8")).update("Chest-Member v2").digest();
26
+ return body + "." + createHmac("sha256", key).update(body).digest("base64url");
27
+ }
28
+ // signEvent is the Chest-Event value the Chest would send with that body:
29
+ // HS256 under the key the token derives for events, for the tool, naming the
30
+ // event and the digest of the body, valid 60 seconds.
31
+ function signEvent(id, body, options) {
32
+ const iat = Math.floor(Date.now() / 1000);
33
+ const signed = encode({ alg: "HS256", typ: "JWT" }) + "." + encode({ aud: options.tool, iat, exp: iat + 60, jti: id, digest: createHash("sha256").update(body).digest("base64url") });
34
+ const key = createHmac("sha256", Buffer.from(options.token, "utf8")).update("Chest-Event v1").digest();
35
+ return signed + "." + createHmac("sha256", key).update(signed).digest("base64url");
36
+ }
37
+ // withMember is the request carrying that member's assertion, signed with
38
+ // the options of signAssertion: a new Web Request, or the same Node request
39
+ // with its header set.
40
+ export function withMember(request, member, options = {}) {
41
+ const assertion = signAssertion(member, options);
42
+ if (request instanceof Request) {
43
+ const headers = new Headers(request.headers);
44
+ headers.set("Chest-Member", assertion);
45
+ return new Request(request, { headers });
46
+ }
47
+ request.headers["chest-member"] = assertion;
48
+ return request;
49
+ }
50
+ // The bounds of a Chest (chest/toolmembers, chest/toolfiles).
51
+ const maxLimit = 500, defaultLimit = 100, maxLookup = 200, callsPerMinute = 600;
52
+ const maxObject = 32 << 20, maxObjects = 10000, maxTotal = 1 << 30;
53
+ const namePattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}(\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}){0,7}$/u;
54
+ // Its notifications: recipients and badges a call, text, quotas.
55
+ const maxRecipients = 500, maxTitle = 80, maxText = 280, maxPath = 512, maxCount = 9999;
56
+ const recipientsPerHour = 1000, itemsPerDay = 100, badgesPerMinute = 600;
57
+ const keyPattern = /^[a-z0-9._:-]{1,64}$/u;
58
+ const reordering = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
59
+ const cleanTitle = (s) => s.replace(/[\t\r\n]/gu, " ").replace(/\p{Cc}/gu, "").replace(reordering, "").trim();
60
+ const cleanText = (s) => s.replace(/\r\n?/gu, "\n").replace(/\t/gu, " ").replace(/[^\P{Cc}\n]/gu, "").replace(reordering, "").trim();
61
+ const isPath = (p) => typeof p === "string" && p.length <= maxPath && /^\/chest([/?#][\x21-\x5b\x5d-\x7e]*)?$/u.test(p) && !p.includes("//") && !p.split(/[?#]/u)[0].split("/").some(x => /^(\.|%2e){1,2}$/iu.test(x));
62
+ // Its AI: aliases in order, bounds of a request, requests a minute.
63
+ const aliasOrder = ["default", "fast", "smart", "embedding"];
64
+ const chatKeys = ["model", "messages", "max_tokens", "stream", "temperature", "top_p", "stop", "tools", "tool_choice", "response_format", "parallel_tool_calls", "seed", "reasoning_effort", "member"];
65
+ const maxAiBody = 10 << 20, maxAiOutput = 128000, maxInputs = 256, aiPerMinute = 60, fakeDimensions = 8;
66
+ // A fake count of tokens: one per 4 characters.
67
+ const tokensOf = (text) => Math.ceil(text.length / 4);
68
+ // A vector of a text, the same for the same text: unit length.
69
+ function vectorOf(text, dimensions) {
70
+ const values = [];
71
+ for (let block = 0; values.length < dimensions; block++) {
72
+ for (const b of createHash("sha256").update(block + ":" + text).digest())
73
+ values.push(b / 127.5 - 1);
74
+ }
75
+ const kept = values.slice(0, dimensions), norm = Math.hypot(...kept) || 1;
76
+ return kept.map(x => x / norm);
77
+ }
78
+ const fold = (s) => s.normalize("NFD").replace(/\p{Mn}/gu, "").toLowerCase();
79
+ function send(response, status, value, headers = {}) {
80
+ if (value === undefined)
81
+ return void response.writeHead(status, headers).end();
82
+ const raw = JSON.stringify(value);
83
+ response.writeHead(status, { ...headers, "Content-Type": "application/json", "Content-Length": String(Buffer.byteLength(raw)) }).end(raw);
84
+ }
85
+ async function body(request, limit) {
86
+ const chunks = [];
87
+ let size = 0;
88
+ for await (const chunk of request) {
89
+ size += chunk.length;
90
+ if (size > limit)
91
+ return null;
92
+ chunks.push(chunk);
93
+ }
94
+ return Buffer.concat(chunks);
95
+ }
96
+ // fakeChest starts a Chest's API on 127.0.0.1 and points the environment at
97
+ // it: CHEST_API, CHEST_TOKEN (a new one) and CHEST_TOOL ("tool" unless the
98
+ // environment names one), and what the Chest is (CHEST_ORGANIZATION,
99
+ // CHEST_TIME_ZONE, CHEST_LANGUAGE, as options.chest says). What member(),
100
+ // chest and the modules of the SDK read is then this Chest's.
101
+ export async function fakeChest(options = {}) {
102
+ const capabilities = new Set(options.capabilities ?? ["members", "files", "notifications", "ai"]);
103
+ const email = capabilities.has("members.email");
104
+ const tool = process.env["CHEST_TOOL"] || "tool";
105
+ const token = randomBytes(32).toString("base64url");
106
+ const files = new Map();
107
+ for (const [name, file] of Object.entries(options.files ?? {})) {
108
+ files.set(name, { data: typeof file.data === "string" ? new TextEncoder().encode(file.data) : file.data, type: file.type ?? "application/octet-stream", updated: new Date().toISOString() });
109
+ }
110
+ const receives = options.receives ?? ["member.*"];
111
+ // The erasures the tool was told of, by emit: those it may acknowledge.
112
+ const erasures = new Set();
113
+ const chest = { api: "", token, tool, members: [...(options.members ?? [])], groups: [...(options.groups ?? [])], files, notifications: [], badges: new Map(), acknowledged: [], ai: [], emit: async () => 0, close: async () => { } };
114
+ const former = [...(options.former ?? [])];
115
+ let window = 0, calls = 0;
116
+ const shown = (m) => ({ id: m.id, first_name: m.firstName, last_name: m.lastName, name: m.name, photo: m.photo, role: m.role, admin: m.isAdmin, builder: m.isBuilder, groups: m.groups, language: m.language, time_zone: m.timeZone, ...(email && m.email !== undefined ? { email: m.email } : {}) });
117
+ const key = (m) => fold(m.name) + "\u0000" + m.id;
118
+ const described = (name, f) => ({ name, type: f.type, size: f.data.byteLength, updated: f.updated });
119
+ async function members(request, response, url) {
120
+ if (!capabilities.has("members"))
121
+ return send(response, 403, { error: "capability_not_granted" });
122
+ const now = Date.now();
123
+ if (now - window >= 60_000)
124
+ [window, calls] = [now, 0];
125
+ if (++calls > callsPerMinute)
126
+ return send(response, 429, { error: "rate_limited" }, { "Retry-After": "60" });
127
+ if (request.method === "GET" && url.pathname === "/members") {
128
+ const q = url.searchParams, keys = [...q.keys()];
129
+ const limit = q.has("limit") ? Number(q.get("limit")) : defaultLimit;
130
+ const after = q.has("after") ? Buffer.from(q.get("after"), "base64url").toString() : "";
131
+ if (q.has("after") && !memberIdPattern.test(after.split("\u0000")[1] ?? ""))
132
+ return send(response, 400, { error: "invalid_query" });
133
+ const group = q.get("group"), role = q.get("role"), search = fold(q.get("q") ?? "");
134
+ if (keys.some(k => !["after", "limit", "q", "role", "group"].includes(k) || q.getAll(k).length !== 1) || !Number.isInteger(limit) || limit < 1 || limit > maxLimit || String(limit) !== (q.get("limit") ?? String(defaultLimit)) || (group !== null && !groupIdPattern.test(group)) || search.length > 64)
135
+ return send(response, 400, { error: "invalid_query" });
136
+ const shownList = chest.members
137
+ .filter(m => (role === null || m.role === role) && (group === null || m.groups.includes(group)) && (search === "" || [m.firstName, m.lastName, m.name, ...(email && m.email ? [m.email] : [])].some(n => fold(n).startsWith(search))))
138
+ .filter(m => after === "" || key(m) > after)
139
+ .sort((a, b) => key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0);
140
+ const page = shownList.slice(0, limit);
141
+ return send(response, 200, { members: page.map(shown), next: shownList.length > limit ? Buffer.from(key(page.at(-1))).toString("base64url") : null });
142
+ }
143
+ if (request.method === "POST" && url.pathname === "/members/lookup") {
144
+ const raw = await body(request, 64 << 10);
145
+ let ids;
146
+ try {
147
+ ids = JSON.parse(raw?.toString() ?? "").ids;
148
+ }
149
+ catch {
150
+ ids = undefined;
151
+ }
152
+ if (!Array.isArray(ids) || ids.length > maxLookup)
153
+ return send(response, 400, { error: "invalid_body" });
154
+ if (!ids.every(id => typeof id === "string" && memberIdPattern.test(id)))
155
+ return send(response, 400, { error: "invalid_id" });
156
+ const answer = { members: [], former: [], unknown: [] };
157
+ for (const id of new Set(ids)) {
158
+ const m = chest.members.find(x => x.id === id), f = former.find(x => x.id === id);
159
+ if (m)
160
+ answer.members.push(shown(m));
161
+ else if (f?.erased)
162
+ answer.former.push({ id, status: "erased" });
163
+ else if (f)
164
+ answer.former.push({ id, ...(f.name ? { name: f.name } : {}), status: "former" });
165
+ else
166
+ answer.unknown.push(id);
167
+ }
168
+ return send(response, 200, answer);
169
+ }
170
+ if (request.method === "GET" && url.pathname.startsWith("/members/")) {
171
+ const id = url.pathname.slice("/members/".length);
172
+ if (!memberIdPattern.test(id))
173
+ return send(response, 400, { error: "invalid_id" });
174
+ const m = chest.members.find(x => x.id === id);
175
+ return m ? send(response, 200, shown(m)) : send(response, 404, { error: "member_not_found" });
176
+ }
177
+ if (request.method === "GET" && url.pathname === "/groups")
178
+ return send(response, 200, { groups: chest.groups });
179
+ send(response, 404, { error: "not_found" });
180
+ }
181
+ async function filesRoute(request, response, url) {
182
+ if (!capabilities.has("files"))
183
+ return send(response, 403, { error: "capability_not_granted" });
184
+ if (request.method === "GET" && url.pathname === "/files") {
185
+ const prefix = url.searchParams.get("prefix") ?? "", after = url.searchParams.get("after") ?? "";
186
+ const names = [...files.keys()].filter(n => n.startsWith(prefix) && n > after).sort();
187
+ return send(response, 200, { files: names.slice(0, 1000).map(n => described(n, files.get(n))), next: names.length > 1000 ? names[999] : null });
188
+ }
189
+ if (request.method === "POST" && url.pathname === "/files/url") {
190
+ const raw = await body(request, 4096);
191
+ let name;
192
+ try {
193
+ name = JSON.parse(raw?.toString() ?? "").name;
194
+ }
195
+ catch {
196
+ name = undefined;
197
+ }
198
+ if (typeof name !== "string")
199
+ return send(response, 400, { error: "invalid_body" });
200
+ if (!files.has(name))
201
+ return send(response, 404, { error: "not_found" });
202
+ return send(response, 200, { url: `https://${tool}-chest.chest.test/_chest/files/${Buffer.from(name).toString("base64url")}.fake`, expires_in: 900 });
203
+ }
204
+ if (request.method === "POST" && (url.pathname === "/files/move" || url.pathname === "/files/upload-url")) {
205
+ const raw = await body(request, 4096);
206
+ let command = {};
207
+ try {
208
+ command = JSON.parse(raw?.toString() ?? "");
209
+ }
210
+ catch {
211
+ command = {};
212
+ }
213
+ if (url.pathname === "/files/upload-url") {
214
+ // The upload itself goes from a member's browser to the team host,
215
+ // which a fake Chest does not play: it only authorises it.
216
+ if (typeof command["name"] !== "string")
217
+ return send(response, 400, { error: "invalid_body" });
218
+ return send(response, 200, { url: `https://${tool}-chest.chest.test/_chest/files/upload/${Buffer.from(command["name"]).toString("base64url")}.fake`, method: "PUT", expires_in: typeof command["expires_in"] === "number" ? command["expires_in"] : 900 });
219
+ }
220
+ const from = command["from"], to = command["to"];
221
+ if (typeof from !== "string" || typeof to !== "string" || !namePattern.test(from) || !namePattern.test(to))
222
+ return send(response, 400, { error: "invalid_name" });
223
+ const moving = files.get(from);
224
+ if (!moving)
225
+ return send(response, 404, { error: "not_found" });
226
+ files.delete(from);
227
+ files.set(to, moving);
228
+ return send(response, 200, described(to, moving));
229
+ }
230
+ const name = decodeURIComponent(url.pathname.slice("/files/".length));
231
+ if (!namePattern.test(name))
232
+ return send(response, 400, { error: "invalid_name" });
233
+ const object = files.get(name);
234
+ if (request.method === "PUT") {
235
+ const data = await body(request, maxObject);
236
+ if (data === null)
237
+ return send(response, 413, { error: "too_large" });
238
+ const total = [...files.entries()].reduce((sum, [n, f]) => n === name ? sum : sum + f.data.byteLength, 0);
239
+ if (total + data.length > maxTotal || (!object && files.size >= maxObjects))
240
+ return send(response, 429, { error: "quota_exceeded" });
241
+ const kept = { data: new Uint8Array(data), type: request.headers["content-type"] ?? "application/octet-stream", updated: new Date().toISOString() };
242
+ files.set(name, kept);
243
+ return send(response, 201, described(name, kept));
244
+ }
245
+ if (!object)
246
+ return send(response, 404, { error: "not_found" });
247
+ if (request.method === "GET" && url.searchParams.has("stat"))
248
+ return send(response, 200, described(name, object));
249
+ if (request.method === "GET")
250
+ return void response.writeHead(200, { "Content-Type": object.type, "Content-Length": String(object.data.byteLength) }).end(object.data);
251
+ if (request.method === "DELETE") {
252
+ files.delete(name);
253
+ return send(response, 204);
254
+ }
255
+ send(response, 404, { error: "not_found" });
256
+ }
257
+ const hour = { start: 0, count: 0 }, minute = { start: 0, count: 0 }, days = new Map();
258
+ const live = (w, span, now) => w !== undefined && w.count > 0 && now - w.start < span;
259
+ const wait = (w, span, now) => ({ "Retry-After": String(Math.max(1, Math.ceil((w.start + span - now) / 1000))) });
260
+ const count = (w, span, now, n) => {
261
+ if (!live(w, span, now))
262
+ [w.start, w.count] = [now, 0];
263
+ w.count += n;
264
+ };
265
+ const access = (id) => chest.members.some(m => m.id === id);
266
+ // drop removes kept notifications in place: a test may hold the list.
267
+ const drop = (gone) => {
268
+ for (let i = chest.notifications.length - 1; i >= 0; i--)
269
+ if (gone(chest.notifications[i]))
270
+ chest.notifications.splice(i, 1);
271
+ };
272
+ // recipients reads 1 to 500 member identifiers, each once.
273
+ function recipients(value) {
274
+ if (!Array.isArray(value) || value.length < 1 || value.length > maxRecipients)
275
+ return { error: "invalid_body" };
276
+ if (!value.every(v => typeof v === "string" && memberIdPattern.test(v)))
277
+ return { error: "invalid_id" };
278
+ return [...new Set(value)];
279
+ }
280
+ async function notificationsRoute(request, response, url) {
281
+ if (!capabilities.has("notifications"))
282
+ return send(response, 403, { error: "capability_not_granted" });
283
+ const badge = request.method === "PUT" && url.pathname.startsWith("/badges/");
284
+ if (!badge && !(request.method === "PUT" && url.pathname === "/badges") && !(request.method === "POST" && (url.pathname === "/notifications" || url.pathname === "/notifications/withdraw")))
285
+ return send(response, 404, { error: "not_found" });
286
+ const raw = await body(request, 64 << 10);
287
+ let command = null;
288
+ try {
289
+ const value = JSON.parse(raw?.toString() ?? "");
290
+ if (value !== null && typeof value === "object" && !Array.isArray(value))
291
+ command = value;
292
+ }
293
+ catch {
294
+ command = null;
295
+ }
296
+ const keys = (...allowed) => command !== null && Object.keys(command).every(k => allowed.includes(k));
297
+ const now = Date.now();
298
+ if (badge || url.pathname === "/badges") {
299
+ let writes;
300
+ if (badge) {
301
+ const id = url.pathname.slice("/badges/".length);
302
+ if (!memberIdPattern.test(id))
303
+ return send(response, 400, { error: "invalid_id" });
304
+ if (!keys("count") || !("count" in command))
305
+ return send(response, 400, { error: "invalid_body" });
306
+ writes = [{ member: id, count: command["count"] }];
307
+ }
308
+ else {
309
+ const list = command?.["badges"];
310
+ if (!keys("badges") || !Array.isArray(list) || list.length < 1 || list.length > maxRecipients || !list.every(b => b !== null && typeof b === "object" && !Array.isArray(b) && Object.keys(b).every(k => k === "member" || k === "count")))
311
+ return send(response, 400, { error: "invalid_body" });
312
+ writes = list;
313
+ if (!writes.every(b => typeof b.member === "string" && memberIdPattern.test(b.member)))
314
+ return send(response, 400, { error: "invalid_id" });
315
+ }
316
+ if (!writes.every(b => typeof b.count === "number" && Number.isInteger(b.count) && b.count >= 0 && b.count <= maxCount))
317
+ return send(response, 400, { error: "invalid_count" });
318
+ if (new Set(writes.map(b => b.member)).size !== writes.length)
319
+ return send(response, 400, { error: "invalid_body" });
320
+ if (live(minute, 60_000, now) && minute.count + writes.length > badgesPerMinute)
321
+ return send(response, 429, { error: "quota_exceeded" }, wait(minute, 60_000, now));
322
+ count(minute, 60_000, now, writes.length);
323
+ const answer = { set: [], skipped: [] };
324
+ for (const b of writes) {
325
+ if (!access(b.member)) {
326
+ answer.skipped.push(b.member);
327
+ continue;
328
+ }
329
+ if (b.count === 0)
330
+ chest.badges.delete(b.member);
331
+ else
332
+ chest.badges.set(b.member, b.count);
333
+ answer.set.push(b.member);
334
+ }
335
+ return send(response, 200, answer);
336
+ }
337
+ if (url.pathname === "/notifications/withdraw") {
338
+ if (!keys("key", "members"))
339
+ return send(response, 400, { error: "invalid_body" });
340
+ const key = command["key"];
341
+ if (typeof key !== "string" || !keyPattern.test(key))
342
+ return send(response, 400, { error: "invalid_key" });
343
+ const named = command["members"] === undefined ? null : recipients(command["members"]);
344
+ if (named !== null && !Array.isArray(named))
345
+ return send(response, 400, named);
346
+ drop(n => n.key === key && (named === null || named.includes(n.member)));
347
+ return send(response, 204);
348
+ }
349
+ if (!keys("members", "title", "body", "path", "key"))
350
+ return send(response, 400, { error: "invalid_body" });
351
+ const { title, body: text, path, key } = command;
352
+ const ids = recipients(command["members"]);
353
+ if (!Array.isArray(ids))
354
+ return send(response, 400, ids);
355
+ if (typeof title !== "string" || [...title].length < 1 || [...title].length > maxTitle || cleanTitle(title) === "")
356
+ return send(response, 400, { error: "invalid_title" });
357
+ if (text !== undefined && (typeof text !== "string" || [...text].length > maxText))
358
+ return send(response, 400, { error: "invalid_text" });
359
+ if (path !== undefined && !isPath(path))
360
+ return send(response, 400, { error: "invalid_path" });
361
+ if (key !== undefined && (typeof key !== "string" || !keyPattern.test(key)))
362
+ return send(response, 400, { error: "invalid_key" });
363
+ const kept = ids.filter(access);
364
+ if (live(hour, 3_600_000, now) && hour.count + kept.length > recipientsPerHour)
365
+ return send(response, 429, { error: "quota_exceeded" }, wait(hour, 3_600_000, now));
366
+ const full = kept.map(id => days.get(id)).filter((w) => live(w, 86_400_000, now) && w.count >= itemsPerDay);
367
+ if (full.length > 0)
368
+ return send(response, 429, { error: "quota_exceeded" }, wait(full.reduce((a, b) => a.start > b.start ? a : b), 86_400_000, now));
369
+ count(hour, 3_600_000, now, kept.length);
370
+ const cleaned = typeof text === "string" ? cleanText(text) : "";
371
+ for (const id of kept) {
372
+ if (!days.has(id))
373
+ days.set(id, { start: 0, count: 0 });
374
+ count(days.get(id), 86_400_000, now, 1);
375
+ if (key !== undefined)
376
+ drop(n => n.member === id && n.key === key);
377
+ chest.notifications.push({ member: id, title: cleanTitle(title), ...(cleaned ? { body: cleaned } : {}), path: path ?? "/chest", ...(key !== undefined ? { key: key } : {}) });
378
+ }
379
+ send(response, 200, { delivered: kept, skipped: ids.filter(id => !access(id)) });
380
+ }
381
+ // Its AI: the declared aliases, the spending this month, the requests this
382
+ // minute.
383
+ const mapped = (options.ai?.models ?? aliasOrder.map((alias) => ({ alias, model: "fake-" + alias }))).map(m => ({ alias: m.alias, model: m.model, provider: m.provider ?? "openrouter", input: m.input ?? 1, output: m.output ?? 2 }));
384
+ const cap = options.ai?.cap ?? 5;
385
+ const aiMinute = { start: 0, count: 0 };
386
+ let spent = 0;
387
+ const month = () => new Date().toISOString().slice(0, 7);
388
+ const resets = () => {
389
+ const now = new Date();
390
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)).toISOString().replace(".000Z", "Z");
391
+ };
392
+ const spend = (m, input, output) => {
393
+ const cost = Math.round((input * m.input + output * m.output) / 1e6 * 1e6) / 1e6;
394
+ spent = Math.round((spent + cost) * 1e6) / 1e6;
395
+ return cost;
396
+ };
397
+ // echo is the text of the last user message: its text, or its text parts.
398
+ const echo = (request) => {
399
+ const last = [...request["messages"]].reverse().find(m => m?.role === "user")?.content;
400
+ return typeof last === "string" ? last : Array.isArray(last) ? last.map(p => p?.text).filter(t => typeof t === "string").join("") : "";
401
+ };
402
+ async function aiRoute(request, response, url) {
403
+ const raw = request.method === "POST" ? await body(request, maxAiBody) : null;
404
+ let command = null;
405
+ try {
406
+ const value = JSON.parse(raw?.toString() ?? "");
407
+ if (value !== null && typeof value === "object" && !Array.isArray(value))
408
+ command = value;
409
+ }
410
+ catch {
411
+ command = null;
412
+ }
413
+ chest.ai.push({ path: url.pathname, body: command });
414
+ if (!capabilities.has("ai"))
415
+ return send(response, 403, { error: "capability_not_granted" });
416
+ if (request.method === "GET" && url.pathname === "/ai/models")
417
+ return send(response, 200, { models: [...mapped].sort((a, b) => aliasOrder.indexOf(a.alias) - aliasOrder.indexOf(b.alias)) });
418
+ if (request.method === "GET" && url.pathname === "/ai/usage")
419
+ return send(response, 200, { month: month(), spent, cap, resets: resets() });
420
+ if (request.method !== "POST" || (url.pathname !== "/ai/chat" && url.pathname !== "/ai/embeddings"))
421
+ return send(response, 404, { error: "not_found" });
422
+ if (raw === null)
423
+ return send(response, 413, { error: "too_large" });
424
+ const chat = url.pathname === "/ai/chat";
425
+ if (!command || !Object.keys(command).every(k => chat ? chatKeys.includes(k) : ["model", "input", "dimensions", "member"].includes(k)))
426
+ return send(response, 400, { error: "invalid_body" });
427
+ const model = mapped.find(m => m.alias === command["model"]);
428
+ if (!model)
429
+ return send(response, 403, { error: "model_not_allowed" });
430
+ const member = command["member"];
431
+ if (member !== undefined && (typeof member !== "string" || !memberIdPattern.test(member)))
432
+ return send(response, 400, { error: "invalid_body" });
433
+ const now = Date.now();
434
+ // refused says the refusal of a valid request, if any: the rate, the
435
+ // provider, the cap.
436
+ const refused = () => {
437
+ const busy = live(aiMinute, 60_000, now) && aiMinute.count >= aiPerMinute;
438
+ if (busy)
439
+ send(response, 429, { error: "rate_limited" }, wait(aiMinute, 60_000, now));
440
+ else {
441
+ count(aiMinute, 60_000, now, 1);
442
+ if (options.ai?.unavailable)
443
+ send(response, options.ai.unavailable === "provider_key_invalid" ? 502 : 503, { error: options.ai.unavailable });
444
+ else if (spent >= cap)
445
+ send(response, 402, { error: "cap_reached", scope: "tool", resets: resets() });
446
+ }
447
+ return response.headersSent;
448
+ };
449
+ if (!chat) {
450
+ const input = command["input"], texts = typeof input === "string" ? [input] : input, dimensions = command["dimensions"] ?? fakeDimensions;
451
+ if (!Array.isArray(texts) || texts.length < 1 || texts.length > maxInputs || !texts.every(t => typeof t === "string") || typeof dimensions !== "number" || !Number.isInteger(dimensions) || dimensions < 1 || dimensions > 4096)
452
+ return send(response, 400, { error: "invalid_body" });
453
+ if (refused())
454
+ return;
455
+ const used = texts.reduce((sum, t) => sum + tokensOf(t), 0);
456
+ const cost = spend(model, used, 0);
457
+ return send(response, 200, { object: "list", data: texts.map((t, index) => ({ object: "embedding", index, embedding: vectorOf(t, dimensions) })), model: model.model, usage: { prompt_tokens: used, total_tokens: used, cost } });
458
+ }
459
+ const messages = command["messages"], limit = command["max_tokens"] ?? 4096;
460
+ if (!Array.isArray(messages) || messages.length < 1 || !messages.every(m => m !== null && typeof m === "object" && typeof m.role === "string") || typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > maxAiOutput || !(command["stream"] === undefined || typeof command["stream"] === "boolean"))
461
+ return send(response, 400, { error: "invalid_body" });
462
+ if (refused())
463
+ return;
464
+ const given = options.ai?.reply ? options.ai.reply(command) : echo(command);
465
+ const text = typeof given === "string" ? given : given.text ?? "";
466
+ const calls = (typeof given === "string" ? [] : given.toolCalls ?? []).map((c, i) => ({ id: c.id ?? `call_${i + 1}`, type: "function", function: { name: c.name, arguments: c.arguments } }));
467
+ const input = tokensOf(JSON.stringify(messages)), output = tokensOf(text + calls.map(c => c.function.name + c.function.arguments).join(""));
468
+ const usage = { prompt_tokens: input, completion_tokens: output, total_tokens: input + output, prompt_tokens_details: { cached_tokens: 0 }, cost: spend(model, input, output) };
469
+ const finish = calls.length ? "tool_calls" : "stop";
470
+ const head = { id: "chatcmpl-fake", created: Math.floor(now / 1000), model: model.model };
471
+ if (command["stream"] !== true) {
472
+ return send(response, 200, { ...head, object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: calls.length && !text ? null : text, ...(calls.length ? { tool_calls: calls } : {}) }, finish_reason: finish }], usage });
473
+ }
474
+ // Streamed: the role, the text word by word, each call's name then its
475
+ // arguments in two halves, the finish reason, the usage, [DONE].
476
+ const chunk = (choices, extra = {}) => `data: ${JSON.stringify({ ...head, object: "chat.completion.chunk", choices, ...extra })}\n\n`;
477
+ const delta = (d, finishReason = null) => chunk([{ index: 0, delta: d, finish_reason: finishReason }]);
478
+ const parts = [delta({ role: "assistant", content: "" })];
479
+ for (const word of text.match(/\S+\s*|\s+/gu) ?? [])
480
+ parts.push(delta({ content: word }));
481
+ calls.forEach((c, index) => {
482
+ const half = Math.ceil(c.function.arguments.length / 2);
483
+ parts.push(delta({ tool_calls: [{ index, id: c.id, type: "function", function: { name: c.function.name, arguments: "" } }] }));
484
+ for (const piece of [c.function.arguments.slice(0, half), c.function.arguments.slice(half)])
485
+ if (piece)
486
+ parts.push(delta({ tool_calls: [{ index, function: { arguments: piece } }] }));
487
+ });
488
+ parts.push(delta({}, finish), chunk([], { usage }), "data: [DONE]\n\n");
489
+ response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
490
+ for (const part of parts)
491
+ response.write(part);
492
+ response.end();
493
+ }
494
+ // The acknowledgment of an erasure the tool was told of (emit).
495
+ async function erasuresRoute(request, response, url) {
496
+ if (!receives.includes("member.*"))
497
+ return send(response, 403, { error: "capability_not_granted" });
498
+ const done = /^\/erasures\/([^/]+)\/done$/u.exec(url.pathname);
499
+ if (request.method !== "POST" || !done || url.search)
500
+ return send(response, 404, { error: "not_found" });
501
+ const id = done[1];
502
+ if (!/^era_[a-z2-7]{26}$/u.test(id))
503
+ return send(response, 400, { error: "invalid_id" });
504
+ if (!erasures.has(id))
505
+ return send(response, 404, { error: "erasure_not_found" });
506
+ if (!chest.acknowledged.includes(id))
507
+ chest.acknowledged.push(id);
508
+ send(response, 204);
509
+ }
510
+ const server = createServer((request, response) => {
511
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
512
+ const route = url.pathname.startsWith("/erasures/") ? erasuresRoute
513
+ : url.pathname.startsWith("/ai/") ? aiRoute
514
+ : url.pathname === "/members" || url.pathname.startsWith("/members/") || url.pathname === "/groups" ? members
515
+ : url.pathname === "/files" || url.pathname.startsWith("/files/") ? filesRoute
516
+ : url.pathname === "/badges" || url.pathname.startsWith("/badges/") || url.pathname.startsWith("/notifications") ? notificationsRoute : null;
517
+ if (!route)
518
+ return send(response, 404, { error: "not_found" });
519
+ route(request, response, url).catch(() => { if (!response.headersSent)
520
+ send(response, 503, { error: "unavailable" });
521
+ else
522
+ response.destroy(); });
523
+ });
524
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
525
+ const saved = Object.fromEntries(["CHEST_API", "CHEST_TOKEN", "CHEST_TOOL", "CHEST_ORGANIZATION", "CHEST_TIME_ZONE", "CHEST_LANGUAGE"].map(name => [name, process.env[name]]));
526
+ chest.api = "http://127.0.0.1:" + server.address().port;
527
+ Object.assign(process.env, { CHEST_API: chest.api, CHEST_TOKEN: token, CHEST_TOOL: tool, CHEST_ORGANIZATION: options.chest?.organization ?? "Test organization", CHEST_TIME_ZONE: options.chest?.timeZone ?? "UTC", CHEST_LANGUAGE: options.chest?.language ?? "en" });
528
+ forget();
529
+ chest.emit = async (event, to) => {
530
+ const id = event.id ?? "evt_" + Array.from(randomBytes(26), b => "abcdefghijklmnopqrstuvwxyz234567"[b & 31]).join("");
531
+ const body = JSON.stringify({ id, type: event.type, occurredAt: event.occurredAt ?? new Date().toISOString(), data: event.data });
532
+ if (event.type === "member.erased")
533
+ erasures.add(event.data.erasure);
534
+ const request = new Request(typeof to === "string" ? to.replace(/\/$/u, "") + "/chest-events" : "http://tool.test/chest-events", { method: "POST", headers: { "Content-Type": "application/json", "Chest-Event": signEvent(id, body, { token, tool }) }, body });
535
+ const answer = typeof to === "string" ? await fetch(request, { redirect: "manual" }) : await to(request);
536
+ await answer.body?.cancel();
537
+ return answer.status;
538
+ };
539
+ chest.close = async () => {
540
+ server.closeAllConnections();
541
+ await new Promise(resolve => server.close(() => resolve()));
542
+ for (const [name, value] of Object.entries(saved)) {
543
+ if (value === undefined)
544
+ delete process.env[name];
545
+ else
546
+ process.env[name] = value;
547
+ }
548
+ forget();
549
+ };
550
+ return chest;
551
+ }
552
+ //# sourceMappingURL=testing.js.map