@rei-standard/amsg-shared 0.4.0-next.0 → 0.4.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -231,22 +231,6 @@ export function isErrorPush(value: unknown): value is ErrorPush;
231
231
  * @returns {string[]}
232
232
  */
233
233
  export function chunkReasoningByUtf8Bytes(text: string, maxBytes: number): string[];
234
- /**
235
- * Coerce ArrayBuffer | Uint8Array | view → Uint8Array (no copy when possible).
236
- */
237
- export function toUint8(buf: any): Uint8Array<ArrayBufferLike>;
238
- /**
239
- * Decode base64url (with or without padding) → Uint8Array.
240
- * @param {string} input
241
- * @returns {Uint8Array}
242
- */
243
- export function base64UrlToBytes(input: string): Uint8Array;
244
- /**
245
- * Concatenate Uint8Arrays into a single Uint8Array.
246
- * @param {...(Uint8Array | ArrayBuffer | ArrayBufferView)} chunks
247
- * @returns {Uint8Array}
248
- */
249
- export function concatBytes(...chunks: (Uint8Array | ArrayBuffer | ArrayBufferView)[]): Uint8Array;
250
234
  /**
251
235
  * True when `value` parses as an absolute URL.
252
236
  * @param {unknown} value
@@ -316,6 +300,7 @@ export function stripReasoningTags(content: string): string;
316
300
  * @property {Record<string, unknown>} metadata
317
301
  * @property {string} contactName
318
302
  * @property {string} [avatarUrl]
303
+ * @property {Record<string, unknown>} [scratch] - Per-fire host scratch object. Producers that run several hooks within one fire (amsg-server's fire-time loop) pass the same mutable object to every hook of that fire, so hooks can hand context to each other without a module-level Map. The library never reads, writes, logs, or persists it, and never shares it across fires. Absent when the producer does not supply one (amsg-instant).
319
304
  */
320
305
  /**
321
306
  * Build the frozen SessionContext handed to an onLLMOutput hook.
@@ -335,9 +320,10 @@ export function stripReasoningTags(content: string): string;
335
320
  * @param {string} [args.avatarUrl]
336
321
  * @param {string} [args.charId]
337
322
  * @param {Record<string, unknown>} [args.metadata]
323
+ * @param {Record<string, unknown>} [args.scratch]
338
324
  * @returns {SessionContext}
339
325
  */
340
- export function buildSessionContext({ sessionId, messages, llmResponse, iteration, contactName, avatarUrl, charId, metadata, }: {
326
+ export function buildSessionContext({ sessionId, messages, llmResponse, iteration, contactName, avatarUrl, charId, metadata, scratch, }: {
341
327
  sessionId: string;
342
328
  messages: ChatMessage[];
343
329
  llmResponse: unknown;
@@ -346,6 +332,7 @@ export function buildSessionContext({ sessionId, messages, llmResponse, iteratio
346
332
  avatarUrl?: string;
347
333
  charId?: string;
348
334
  metadata?: Record<string, unknown>;
335
+ scratch?: Record<string, unknown>;
349
336
  }): SessionContext;
350
337
  /**
351
338
  * Extract the `choices[0].message` whole object — preserving `tool_calls`
@@ -687,6 +674,10 @@ export type SessionContext = {
687
674
  metadata: Record<string, unknown>;
688
675
  contactName: string;
689
676
  avatarUrl?: string;
677
+ /**
678
+ * - Per-fire host scratch object. Producers that run several hooks within one fire (amsg-server's fire-time loop) pass the same mutable object to every hook of that fire, so hooks can hand context to each other without a module-level Map. The library never reads, writes, logs, or persists it, and never shares it across fires. Absent when the producer does not supply one (amsg-instant).
679
+ */
680
+ scratch?: Record<string, unknown>;
690
681
  };
691
682
  /**
692
683
  * What the push carries. Fixed enum — packages must not add values.
@@ -703,3 +694,8 @@ export type MessageType = "instant" | "fixed" | "prompted" | "auto";
703
694
  * add values.
704
695
  */
705
696
  export type PushSource = "instant" | "scheduled";
697
+ export { toUint8, concatBytes, utf8, utf8Decode, bytesToBase64, bytesToBase64Url, base64UrlToBytes, jsonToBase64Url, bytesToHex, hexToBytes, hmacSha256, timingSafeEqualBytes, randomBytes, randomUUID } from "./webcrypto-utils.js";
698
+ export { LLM_MESSAGES_ERROR, validateLlmMessagesShape } from "./llm-messages.js";
699
+ export { callLlm, buildLlmRequestBody, normalizeAiApiUrl } from "./llm-call.js";
700
+ export { sendWebPush, buildVapidJwt, verifyVapidJwt } from "./webpush.js";
701
+ export { MULTIPART_MESSAGE_KIND, MULTIPART_ENCODING, MULTIPART_VERSION, DEFAULT_MULTIPART_TTL_MS, DEFAULT_MULTIPART_MAX_CHUNKS, DEFAULT_MULTIPART_MAX_TOTAL_BYTES, REI_AMSG_POSTMESSAGE_TYPE, REI_SW_EVENT, REI_SW_MESSAGE_TYPE, REI_AMSG_DELIVER_MESSAGE_TYPE } from "./protocol.js";
package/dist/index.mjs CHANGED
@@ -1,3 +1,485 @@
1
+ // src/webcrypto-utils.js
2
+ var TEXT_ENCODER = new TextEncoder();
3
+ var TEXT_DECODER = new TextDecoder("utf-8", { fatal: false });
4
+ function toUint8(buf) {
5
+ if (buf instanceof Uint8Array) return buf;
6
+ if (buf instanceof ArrayBuffer) return new Uint8Array(buf);
7
+ if (ArrayBuffer.isView(buf)) return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
8
+ throw new TypeError("Expected ArrayBuffer / Uint8Array");
9
+ }
10
+ function concatBytes(...chunks) {
11
+ let total = 0;
12
+ for (const c of chunks) total += c.byteLength;
13
+ const out = new Uint8Array(total);
14
+ let offset = 0;
15
+ for (const c of chunks) {
16
+ out.set(c instanceof Uint8Array ? c : new Uint8Array(c.buffer || c), offset);
17
+ offset += c.byteLength;
18
+ }
19
+ return out;
20
+ }
21
+ function utf8(str) {
22
+ return TEXT_ENCODER.encode(String(str));
23
+ }
24
+ function utf8Decode(buf) {
25
+ return TEXT_DECODER.decode(toUint8(buf));
26
+ }
27
+ function bytesToBase64(buf) {
28
+ const bytes = toUint8(buf);
29
+ let bin = "";
30
+ for (let i = 0; i < bytes.length; i++) {
31
+ bin += String.fromCharCode(bytes[i]);
32
+ }
33
+ return typeof btoa === "function" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64");
34
+ }
35
+ function bytesToBase64Url(buf) {
36
+ return bytesToBase64(buf).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
37
+ }
38
+ function base64UrlToBytes(input) {
39
+ const s = String(input).replace(/-/g, "+").replace(/_/g, "/");
40
+ const pad = (4 - s.length % 4) % 4;
41
+ const padded = s + "=".repeat(pad);
42
+ const bin = typeof atob === "function" ? atob(padded) : Buffer.from(padded, "base64").toString("binary");
43
+ const out = new Uint8Array(bin.length);
44
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
45
+ return out;
46
+ }
47
+ function jsonToBase64Url(value) {
48
+ return bytesToBase64Url(utf8(JSON.stringify(value)));
49
+ }
50
+ function bytesToHex(buf) {
51
+ const bytes = toUint8(buf);
52
+ let out = "";
53
+ for (let i = 0; i < bytes.length; i++) {
54
+ out += bytes[i].toString(16).padStart(2, "0");
55
+ }
56
+ return out;
57
+ }
58
+ function hexToBytes(hex) {
59
+ const out = new Uint8Array(hex.length / 2);
60
+ for (let i = 0; i < out.length; i++) {
61
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
62
+ }
63
+ return out;
64
+ }
65
+ async function hmacSha256(keyBytes, data) {
66
+ const key = await globalThis.crypto.subtle.importKey(
67
+ "raw",
68
+ toUint8(keyBytes),
69
+ { name: "HMAC", hash: "SHA-256" },
70
+ false,
71
+ ["sign"]
72
+ );
73
+ const sig = await globalThis.crypto.subtle.sign("HMAC", key, toUint8(data));
74
+ return new Uint8Array(sig);
75
+ }
76
+ function timingSafeEqualBytes(a, b) {
77
+ const x = toUint8(a);
78
+ const y = toUint8(b);
79
+ if (x.length !== y.length) return false;
80
+ let diff = 0;
81
+ for (let i = 0; i < x.length; i++) {
82
+ diff |= x[i] ^ y[i];
83
+ }
84
+ return diff === 0;
85
+ }
86
+ function randomBytes(n) {
87
+ const out = new Uint8Array(n);
88
+ globalThis.crypto.getRandomValues(out);
89
+ return out;
90
+ }
91
+ function randomUUID() {
92
+ return globalThis.crypto.randomUUID();
93
+ }
94
+
95
+ // src/llm-messages.js
96
+ var VALID_LLM_MESSAGE_ROLES = /* @__PURE__ */ new Set(["system", "user", "assistant", "tool"]);
97
+ var LLM_MESSAGES_ERROR = Object.freeze({
98
+ MESSAGES_NOT_ARRAY: "MESSAGES_NOT_ARRAY",
99
+ MESSAGE_NOT_OBJECT: "MESSAGE_NOT_OBJECT",
100
+ INVALID_ROLE: "INVALID_ROLE",
101
+ TOOL_CALL_MALFORMED: "TOOL_CALL_MALFORMED",
102
+ TOOL_CONTENT_INVALID: "TOOL_CONTENT_INVALID",
103
+ TOOL_CALL_ID_MISSING: "TOOL_CALL_ID_MISSING",
104
+ CONTENT_EMPTY_STRING: "CONTENT_EMPTY_STRING",
105
+ CONTENT_EMPTY_ARRAY: "CONTENT_EMPTY_ARRAY",
106
+ CONTENT_INVALID_TYPE: "CONTENT_INVALID_TYPE"
107
+ });
108
+ function validateLlmMessagesShape(messages) {
109
+ if (!Array.isArray(messages) || messages.length === 0) {
110
+ return { code: LLM_MESSAGES_ERROR.MESSAGES_NOT_ARRAY };
111
+ }
112
+ for (let i = 0; i < messages.length; i++) {
113
+ const m = messages[i];
114
+ if (!m || typeof m !== "object" || Array.isArray(m)) {
115
+ return { code: LLM_MESSAGES_ERROR.MESSAGE_NOT_OBJECT, index: i };
116
+ }
117
+ if (!VALID_LLM_MESSAGE_ROLES.has(m.role)) {
118
+ return { code: LLM_MESSAGES_ERROR.INVALID_ROLE, index: i };
119
+ }
120
+ const isAssistantToolCallCarrier = m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0;
121
+ if (isAssistantToolCallCarrier) {
122
+ for (let j = 0; j < m.tool_calls.length; j++) {
123
+ const tc = m.tool_calls[j];
124
+ if (!tc || typeof tc !== "object" || typeof tc.id !== "string" || !tc.function) {
125
+ return { code: LLM_MESSAGES_ERROR.TOOL_CALL_MALFORMED, index: i, toolCallIndex: j };
126
+ }
127
+ }
128
+ continue;
129
+ }
130
+ if (m.role === "tool") {
131
+ if (typeof m.content !== "string" && !Array.isArray(m.content)) {
132
+ return { code: LLM_MESSAGES_ERROR.TOOL_CONTENT_INVALID, index: i };
133
+ }
134
+ if (typeof m.tool_call_id !== "string" || !m.tool_call_id) {
135
+ return { code: LLM_MESSAGES_ERROR.TOOL_CALL_ID_MISSING, index: i };
136
+ }
137
+ continue;
138
+ }
139
+ if (typeof m.content === "string") {
140
+ if (!m.content) {
141
+ return { code: LLM_MESSAGES_ERROR.CONTENT_EMPTY_STRING, index: i };
142
+ }
143
+ } else if (Array.isArray(m.content)) {
144
+ if (m.content.length === 0) {
145
+ return { code: LLM_MESSAGES_ERROR.CONTENT_EMPTY_ARRAY, index: i };
146
+ }
147
+ } else {
148
+ return { code: LLM_MESSAGES_ERROR.CONTENT_INVALID_TYPE, index: i };
149
+ }
150
+ }
151
+ return null;
152
+ }
153
+
154
+ // src/llm-call.js
155
+ async function callLlm(payload, options = {}) {
156
+ const requireContent = options.requireContent !== false;
157
+ const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 3e5;
158
+ const fetchImpl = options.fetch || globalThis.fetch;
159
+ const normalizedApiUrl = normalizeAiApiUrl(payload.apiUrl);
160
+ const requestBody = buildLlmRequestBody(payload, options);
161
+ const aiResponse = await fetchImpl(normalizedApiUrl, {
162
+ method: "POST",
163
+ headers: {
164
+ "Content-Type": "application/json",
165
+ "Authorization": `Bearer ${payload.apiKey}`
166
+ },
167
+ body: JSON.stringify(requestBody),
168
+ signal: AbortSignal.timeout(timeoutMs)
169
+ });
170
+ if (!aiResponse.ok) {
171
+ if (aiResponse.status === 405) {
172
+ throw new Error(
173
+ `AI API error: 405 Method Not Allowed. apiUrl must point to a full chat endpoint (for example: /chat/completions). Received: ${normalizedApiUrl}`
174
+ );
175
+ }
176
+ throw new Error(
177
+ `AI API error: ${aiResponse.status} ${aiResponse.statusText || "Unknown Error"}. Request URL: ${normalizedApiUrl}`
178
+ );
179
+ }
180
+ const aiData = await aiResponse.json();
181
+ const rawContent = aiData?.choices?.[0]?.message?.content;
182
+ if (requireContent && (typeof rawContent !== "string" || !rawContent.trim())) {
183
+ throw new Error("AI API error: response missing choices[0].message.content");
184
+ }
185
+ return { response: aiData, content: typeof rawContent === "string" ? rawContent.trim() : "" };
186
+ }
187
+ function buildLlmRequestBody(payload, options = {}) {
188
+ const llmMessages = Array.isArray(payload.messages) && payload.messages.length > 0 ? payload.messages : [{ role: "user", content: payload.completePrompt }];
189
+ const requestBody = {
190
+ model: payload.primaryModel,
191
+ messages: llmMessages
192
+ };
193
+ if (options.stream !== void 0) {
194
+ requestBody.stream = options.stream;
195
+ }
196
+ if (payload.temperature !== void 0 && payload.temperature !== null) {
197
+ requestBody.temperature = payload.temperature;
198
+ } else if (!Array.isArray(payload.messages)) {
199
+ requestBody.temperature = 0.8;
200
+ }
201
+ if (options.forwardTools !== false && Array.isArray(payload.tools) && payload.tools.length > 0) {
202
+ requestBody.tools = payload.tools;
203
+ if (payload.toolChoice !== void 0 && payload.toolChoice !== null) {
204
+ requestBody.tool_choice = payload.toolChoice;
205
+ }
206
+ }
207
+ if (payload.maxTokens === void 0 || payload.maxTokens === null) {
208
+ return requestBody;
209
+ }
210
+ if (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0) {
211
+ throw new Error("Invalid maxTokens: maxTokens must be a positive integer when provided.");
212
+ }
213
+ requestBody.max_tokens = payload.maxTokens;
214
+ return requestBody;
215
+ }
216
+ function normalizeAiApiUrl(apiUrl) {
217
+ const trimmed = String(apiUrl || "").trim();
218
+ if (!trimmed) {
219
+ throw new Error(
220
+ "Invalid apiUrl: apiUrl is required. Please provide a chat endpoint URL (for example: https://api.openai.com or https://api.openai.com/v1/chat/completions)."
221
+ );
222
+ }
223
+ let parsed;
224
+ try {
225
+ parsed = new URL(trimmed);
226
+ } catch {
227
+ throw new Error(
228
+ `Invalid apiUrl: "${apiUrl}". Please provide a valid absolute URL.`
229
+ );
230
+ }
231
+ let path = parsed.pathname.replace(/\/+$/, "") || "/";
232
+ if (/\/chat\/completions$/.test(path)) {
233
+ } else if (path === "/") {
234
+ path = "/v1/chat/completions";
235
+ } else if (/\/v\d+$/.test(path)) {
236
+ path = `${path}/chat/completions`;
237
+ }
238
+ parsed.pathname = path;
239
+ return parsed.toString();
240
+ }
241
+
242
+ // src/webpush.js
243
+ var KEY_INFO_PREFIX = utf8("WebPush: info\0");
244
+ var CEK_INFO = utf8("Content-Encoding: aes128gcm\0");
245
+ var NONCE_INFO = utf8("Content-Encoding: nonce\0");
246
+ var VAPID_DEFAULT_TTL = 60;
247
+ var VAPID_TOKEN_LIFETIME = 12 * 3600;
248
+ var RECORD_SIZE = 4096;
249
+ async function sendWebPush({ subscription, payload, vapid, ttl, fetch: fetchImpl }) {
250
+ if (!subscription || typeof subscription.endpoint !== "string") {
251
+ throw new Error("sendWebPush: invalid subscription");
252
+ }
253
+ if (typeof payload !== "string") {
254
+ throw new Error("sendWebPush: payload must be a string");
255
+ }
256
+ if (!vapid || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
257
+ throw new Error("VAPID_CONFIG_MISSING");
258
+ }
259
+ const subscriptionKeys = subscription.keys || {};
260
+ if (typeof subscriptionKeys.p256dh !== "string" || typeof subscriptionKeys.auth !== "string") {
261
+ throw new Error("sendWebPush: subscription.keys.p256dh and .auth are required");
262
+ }
263
+ const encryptedBody = await encryptPushPayload({
264
+ plaintext: utf8(payload),
265
+ uaPublicKey: base64UrlToBytes(subscriptionKeys.p256dh),
266
+ authSecret: base64UrlToBytes(subscriptionKeys.auth)
267
+ });
268
+ const jwt = await buildVapidJwt({
269
+ audience: originOf(subscription.endpoint),
270
+ subject: normalizeVapidSubject(vapid.email),
271
+ publicKey: vapid.publicKey,
272
+ privateKey: vapid.privateKey
273
+ });
274
+ const fetchFn = fetchImpl || globalThis.fetch;
275
+ if (typeof fetchFn !== "function") {
276
+ throw new Error("sendWebPush: no fetch implementation available");
277
+ }
278
+ const res = await fetchFn(subscription.endpoint, {
279
+ method: "POST",
280
+ headers: {
281
+ "Content-Type": "application/octet-stream",
282
+ "Content-Encoding": "aes128gcm",
283
+ "TTL": String(Number.isFinite(ttl) ? ttl : VAPID_DEFAULT_TTL),
284
+ "Authorization": `vapid t=${jwt}, k=${vapid.publicKey}`
285
+ },
286
+ body: encryptedBody
287
+ });
288
+ if (!res.ok) {
289
+ const text = await safeReadText(res);
290
+ const err = new Error(
291
+ `Web Push delivery failed: ${res.status} ${res.statusText || ""}${text ? ` \u2014 ${text}` : ""}`
292
+ );
293
+ err.code = "PUSH_SEND_FAILED";
294
+ err.statusCode = res.status;
295
+ throw err;
296
+ }
297
+ return {
298
+ statusCode: res.status,
299
+ body: await safeReadText(res),
300
+ headers: res.headers
301
+ };
302
+ }
303
+ async function encryptPushPayload({ plaintext, uaPublicKey, authSecret }) {
304
+ const asKeyPair = await globalThis.crypto.subtle.generateKey(
305
+ { name: "ECDH", namedCurve: "P-256" },
306
+ true,
307
+ ["deriveBits"]
308
+ );
309
+ const asPublicRaw = new Uint8Array(
310
+ await globalThis.crypto.subtle.exportKey("raw", asKeyPair.publicKey)
311
+ );
312
+ const uaPublicCryptoKey = await globalThis.crypto.subtle.importKey(
313
+ "raw",
314
+ uaPublicKey,
315
+ { name: "ECDH", namedCurve: "P-256" },
316
+ false,
317
+ []
318
+ );
319
+ const ecdhSecret = new Uint8Array(
320
+ await globalThis.crypto.subtle.deriveBits(
321
+ { name: "ECDH", public: uaPublicCryptoKey },
322
+ asKeyPair.privateKey,
323
+ 256
324
+ )
325
+ );
326
+ const keyInfo = concatBytes(KEY_INFO_PREFIX, uaPublicKey, asPublicRaw);
327
+ const ikm = await hkdfSha256(authSecret, ecdhSecret, keyInfo, 32);
328
+ const salt = randomBytes(16);
329
+ const cekBytes = await hkdfSha256(salt, ikm, CEK_INFO, 16);
330
+ const cek = await globalThis.crypto.subtle.importKey(
331
+ "raw",
332
+ cekBytes,
333
+ { name: "AES-GCM" },
334
+ false,
335
+ ["encrypt"]
336
+ );
337
+ const nonce = await hkdfSha256(salt, ikm, NONCE_INFO, 12);
338
+ const padded = concatBytes(plaintext, new Uint8Array([2]));
339
+ const ciphertext = new Uint8Array(
340
+ await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, cek, padded)
341
+ );
342
+ const header = new Uint8Array(16 + 4 + 1 + asPublicRaw.byteLength);
343
+ header.set(salt, 0);
344
+ writeUint32BE(header, 16, RECORD_SIZE);
345
+ header[20] = asPublicRaw.byteLength;
346
+ header.set(asPublicRaw, 21);
347
+ return concatBytes(header, ciphertext);
348
+ }
349
+ async function hkdfSha256(salt, ikm, info, length) {
350
+ const baseKey = await globalThis.crypto.subtle.importKey(
351
+ "raw",
352
+ toUint8(ikm),
353
+ { name: "HKDF" },
354
+ false,
355
+ ["deriveBits"]
356
+ );
357
+ const bits = await globalThis.crypto.subtle.deriveBits(
358
+ {
359
+ name: "HKDF",
360
+ hash: "SHA-256",
361
+ salt: toUint8(salt),
362
+ info: toUint8(info)
363
+ },
364
+ baseKey,
365
+ length * 8
366
+ );
367
+ return new Uint8Array(bits);
368
+ }
369
+ async function buildVapidJwt({ audience, subject, publicKey, privateKey }) {
370
+ const header = jsonToBase64Url({ typ: "JWT", alg: "ES256" });
371
+ const payload = jsonToBase64Url({
372
+ aud: audience,
373
+ exp: Math.floor(Date.now() / 1e3) + VAPID_TOKEN_LIFETIME,
374
+ sub: subject
375
+ });
376
+ const signingInput = utf8(`${header}.${payload}`);
377
+ const pubBytes = base64UrlToBytes(publicKey);
378
+ const privBytes = base64UrlToBytes(privateKey);
379
+ if (pubBytes.length !== 65 || pubBytes[0] !== 4) {
380
+ throw new Error("VAPID publicKey must be a 65-byte uncompressed P-256 point (base64url).");
381
+ }
382
+ if (privBytes.length !== 32) {
383
+ throw new Error("VAPID privateKey must be a 32-byte scalar (base64url).");
384
+ }
385
+ const jwk = {
386
+ kty: "EC",
387
+ crv: "P-256",
388
+ d: bytesToBase64Url(privBytes),
389
+ x: bytesToBase64Url(pubBytes.subarray(1, 33)),
390
+ y: bytesToBase64Url(pubBytes.subarray(33, 65)),
391
+ ext: true
392
+ };
393
+ const key = await globalThis.crypto.subtle.importKey(
394
+ "jwk",
395
+ jwk,
396
+ { name: "ECDSA", namedCurve: "P-256" },
397
+ false,
398
+ ["sign"]
399
+ );
400
+ const sig = await globalThis.crypto.subtle.sign(
401
+ { name: "ECDSA", hash: "SHA-256" },
402
+ key,
403
+ signingInput
404
+ );
405
+ return `${header}.${payload}.${bytesToBase64Url(sig)}`;
406
+ }
407
+ async function verifyVapidJwt(jwt, publicKey) {
408
+ const parts = String(jwt).split(".");
409
+ if (parts.length !== 3) throw new Error("VAPID JWT: malformed (expected three segments)");
410
+ const [h, p, s] = parts;
411
+ const pubBytes = base64UrlToBytes(publicKey);
412
+ if (pubBytes.length !== 65 || pubBytes[0] !== 4) {
413
+ throw new Error("VAPID publicKey must be 65 B uncompressed P-256 (base64url).");
414
+ }
415
+ const jwk = {
416
+ kty: "EC",
417
+ crv: "P-256",
418
+ x: bytesToBase64Url(pubBytes.subarray(1, 33)),
419
+ y: bytesToBase64Url(pubBytes.subarray(33, 65)),
420
+ ext: true
421
+ };
422
+ const key = await globalThis.crypto.subtle.importKey(
423
+ "jwk",
424
+ jwk,
425
+ { name: "ECDSA", namedCurve: "P-256" },
426
+ false,
427
+ ["verify"]
428
+ );
429
+ const ok = await globalThis.crypto.subtle.verify(
430
+ { name: "ECDSA", hash: "SHA-256" },
431
+ key,
432
+ base64UrlToBytes(s),
433
+ utf8(`${h}.${p}`)
434
+ );
435
+ if (!ok) throw new Error("VAPID JWT: signature mismatch");
436
+ const payload = JSON.parse(new TextDecoder().decode(base64UrlToBytes(p)));
437
+ if (!payload.exp || payload.exp <= Math.floor(Date.now() / 1e3)) {
438
+ throw new Error("VAPID JWT: expired");
439
+ }
440
+ return payload;
441
+ }
442
+ function originOf(endpoint) {
443
+ return new URL(endpoint).origin;
444
+ }
445
+ function writeUint32BE(buf, offset, value) {
446
+ buf[offset] = value >>> 24 & 255;
447
+ buf[offset + 1] = value >>> 16 & 255;
448
+ buf[offset + 2] = value >>> 8 & 255;
449
+ buf[offset + 3] = value & 255;
450
+ }
451
+ async function safeReadText(res) {
452
+ try {
453
+ return await res.text();
454
+ } catch {
455
+ return "";
456
+ }
457
+ }
458
+
459
+ // src/protocol.js
460
+ var MULTIPART_MESSAGE_KIND = "_multipart";
461
+ var MULTIPART_ENCODING = "json-utf8-base64url";
462
+ var MULTIPART_VERSION = 1;
463
+ var DEFAULT_MULTIPART_TTL_MS = 6e4;
464
+ var DEFAULT_MULTIPART_MAX_CHUNKS = 128;
465
+ var DEFAULT_MULTIPART_MAX_TOTAL_BYTES = 256e3;
466
+ var REI_AMSG_POSTMESSAGE_TYPE = "REI_AMSG_PUSH";
467
+ var REI_SW_EVENT = Object.freeze({
468
+ CONTENT_RECEIVED: "rei-amsg-content-received",
469
+ REASONING_RECEIVED: "rei-amsg-reasoning-received",
470
+ TOOL_REQUEST_RECEIVED: "rei-amsg-tool-request-received",
471
+ ERROR_RECEIVED: "rei-amsg-error-received",
472
+ MULTIPART_EXPIRED: "rei-amsg-multipart-expired",
473
+ UNKNOWN_RECEIVED: "rei-amsg-unknown-received"
474
+ });
475
+ var REI_SW_MESSAGE_TYPE = Object.freeze({
476
+ ENQUEUE_REQUEST: "REI_ENQUEUE_REQUEST",
477
+ DELIVER: "REI_AMSG_DELIVER",
478
+ FLUSH_QUEUE: "REI_FLUSH_QUEUE",
479
+ QUEUE_RESULT: "REI_QUEUE_RESULT"
480
+ });
481
+ var REI_AMSG_DELIVER_MESSAGE_TYPE = REI_SW_MESSAGE_TYPE.DELIVER;
482
+
1
483
  // src/index.js
2
484
  var MESSAGE_KIND = Object.freeze({
3
485
  CONTENT: "content",
@@ -201,32 +683,6 @@ function chunkReasoningByUtf8Bytes(text, maxBytes) {
201
683
  }
202
684
  return chunks;
203
685
  }
204
- function toUint8(buf) {
205
- if (buf instanceof Uint8Array) return buf;
206
- if (buf instanceof ArrayBuffer) return new Uint8Array(buf);
207
- if (ArrayBuffer.isView(buf)) return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
208
- throw new TypeError("Expected ArrayBuffer / Uint8Array");
209
- }
210
- function base64UrlToBytes(input) {
211
- const s = String(input).replace(/-/g, "+").replace(/_/g, "/");
212
- const pad = (4 - s.length % 4) % 4;
213
- const padded = s + "=".repeat(pad);
214
- const bin = typeof atob === "function" ? atob(padded) : Buffer.from(padded, "base64").toString("binary");
215
- const out = new Uint8Array(bin.length);
216
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
217
- return out;
218
- }
219
- function concatBytes(...chunks) {
220
- let total = 0;
221
- for (const c of chunks) total += c.byteLength;
222
- const out = new Uint8Array(total);
223
- let offset = 0;
224
- for (const c of chunks) {
225
- out.set(c instanceof Uint8Array ? c : new Uint8Array(c.buffer || c), offset);
226
- offset += c.byteLength;
227
- }
228
- return out;
229
- }
230
686
  function isValidUrl(value) {
231
687
  if (typeof value !== "string") return false;
232
688
  try {
@@ -298,7 +754,8 @@ function buildSessionContext({
298
754
  contactName,
299
755
  avatarUrl,
300
756
  charId,
301
- metadata
757
+ metadata,
758
+ scratch
302
759
  }) {
303
760
  const llmOutputText = readLlmOutputText(llmResponse);
304
761
  const ctx = {
@@ -312,6 +769,7 @@ function buildSessionContext({
312
769
  contactName,
313
770
  avatarUrl: avatarUrl || void 0
314
771
  };
772
+ if (scratch !== void 0) ctx.scratch = scratch;
315
773
  return Object.freeze(ctx);
316
774
  }
317
775
  function readLlmOutputText(llmResponse) {
@@ -457,28 +915,57 @@ function stringifyDecisionForError(value) {
457
915
  }
458
916
  export {
459
917
  AVATAR_URL_MAX_LENGTH,
918
+ DEFAULT_MULTIPART_MAX_CHUNKS,
919
+ DEFAULT_MULTIPART_MAX_TOTAL_BYTES,
920
+ DEFAULT_MULTIPART_TTL_MS,
921
+ LLM_MESSAGES_ERROR,
460
922
  MESSAGE_KIND,
461
923
  MESSAGE_TYPE,
924
+ MULTIPART_ENCODING,
925
+ MULTIPART_MESSAGE_KIND,
926
+ MULTIPART_VERSION,
462
927
  PUSH_SOURCE,
928
+ REI_AMSG_DELIVER_MESSAGE_TYPE,
929
+ REI_AMSG_POSTMESSAGE_TYPE,
930
+ REI_SW_EVENT,
931
+ REI_SW_MESSAGE_TYPE,
463
932
  assertValidDecision,
464
933
  base64UrlToBytes,
465
934
  buildContentPush,
466
935
  buildErrorPush,
936
+ buildLlmRequestBody,
467
937
  buildReasoningPush,
468
938
  buildSessionContext,
469
939
  buildToolRequestPush,
940
+ buildVapidJwt,
941
+ bytesToBase64,
942
+ bytesToBase64Url,
943
+ bytesToHex,
944
+ callLlm,
470
945
  chunkReasoningByUtf8Bytes,
471
946
  concatBytes,
472
947
  extractAssistantMessage,
473
948
  extractToolCallsFromDecision,
949
+ hexToBytes,
950
+ hmacSha256,
474
951
  isContentPush,
475
952
  isErrorPush,
476
953
  isReasoningPush,
477
954
  isToolRequestPush,
478
955
  isValidUrl,
956
+ jsonToBase64Url,
957
+ normalizeAiApiUrl,
479
958
  normalizeVapidSubject,
959
+ randomBytes,
960
+ randomUUID,
480
961
  readReasoningContent,
962
+ sendWebPush,
481
963
  stripReasoningTags,
964
+ timingSafeEqualBytes,
482
965
  toUint8,
483
- validateAvatarUrl
966
+ utf8,
967
+ utf8Decode,
968
+ validateAvatarUrl,
969
+ validateLlmMessagesShape,
970
+ verifyVapidJwt
484
971
  };