@rei-standard/amsg-shared 0.4.0-next.1 → 0.4.0-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +98 -12
- package/dist/index.cjs +514 -27
- package/dist/index.d.cts +30 -18
- package/dist/index.d.ts +30 -18
- package/dist/index.mjs +512 -27
- package/dist/llm-call.d.cts +113 -0
- package/dist/llm-call.d.ts +113 -0
- package/dist/llm-messages.d.cts +66 -0
- package/dist/llm-messages.d.ts +66 -0
- package/dist/protocol.d.cts +57 -0
- package/dist/protocol.d.ts +57 -0
- package/dist/webcrypto-utils.d.cts +42 -0
- package/dist/webcrypto-utils.d.ts +42 -0
- package/dist/webpush.d.cts +69 -0
- package/dist/webpush.d.ts +69 -0
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -20,32 +20,545 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
var src_exports = {};
|
|
21
21
|
__export(src_exports, {
|
|
22
22
|
AVATAR_URL_MAX_LENGTH: () => AVATAR_URL_MAX_LENGTH,
|
|
23
|
+
DEFAULT_MULTIPART_MAX_CHUNKS: () => DEFAULT_MULTIPART_MAX_CHUNKS,
|
|
24
|
+
DEFAULT_MULTIPART_MAX_TOTAL_BYTES: () => DEFAULT_MULTIPART_MAX_TOTAL_BYTES,
|
|
25
|
+
DEFAULT_MULTIPART_TTL_MS: () => DEFAULT_MULTIPART_TTL_MS,
|
|
26
|
+
LLM_MESSAGES_ERROR: () => LLM_MESSAGES_ERROR,
|
|
23
27
|
MESSAGE_KIND: () => MESSAGE_KIND,
|
|
24
28
|
MESSAGE_TYPE: () => MESSAGE_TYPE,
|
|
29
|
+
MULTIPART_ENCODING: () => MULTIPART_ENCODING,
|
|
30
|
+
MULTIPART_MESSAGE_KIND: () => MULTIPART_MESSAGE_KIND,
|
|
31
|
+
MULTIPART_VERSION: () => MULTIPART_VERSION,
|
|
25
32
|
PUSH_SOURCE: () => PUSH_SOURCE,
|
|
33
|
+
REI_AMSG_DELIVER_MESSAGE_TYPE: () => REI_AMSG_DELIVER_MESSAGE_TYPE,
|
|
34
|
+
REI_AMSG_POSTMESSAGE_TYPE: () => REI_AMSG_POSTMESSAGE_TYPE,
|
|
35
|
+
REI_SW_EVENT: () => REI_SW_EVENT,
|
|
36
|
+
REI_SW_MESSAGE_TYPE: () => REI_SW_MESSAGE_TYPE,
|
|
26
37
|
assertValidDecision: () => assertValidDecision,
|
|
27
38
|
base64UrlToBytes: () => base64UrlToBytes,
|
|
28
39
|
buildContentPush: () => buildContentPush,
|
|
29
40
|
buildErrorPush: () => buildErrorPush,
|
|
41
|
+
buildLlmRequestBody: () => buildLlmRequestBody,
|
|
30
42
|
buildReasoningPush: () => buildReasoningPush,
|
|
31
43
|
buildSessionContext: () => buildSessionContext,
|
|
32
44
|
buildToolRequestPush: () => buildToolRequestPush,
|
|
45
|
+
buildVapidJwt: () => buildVapidJwt,
|
|
46
|
+
bytesToBase64: () => bytesToBase64,
|
|
47
|
+
bytesToBase64Url: () => bytesToBase64Url,
|
|
48
|
+
bytesToHex: () => bytesToHex,
|
|
49
|
+
callLlm: () => callLlm,
|
|
33
50
|
chunkReasoningByUtf8Bytes: () => chunkReasoningByUtf8Bytes,
|
|
34
51
|
concatBytes: () => concatBytes,
|
|
35
52
|
extractAssistantMessage: () => extractAssistantMessage,
|
|
36
53
|
extractToolCallsFromDecision: () => extractToolCallsFromDecision,
|
|
54
|
+
hexToBytes: () => hexToBytes,
|
|
55
|
+
hmacSha256: () => hmacSha256,
|
|
37
56
|
isContentPush: () => isContentPush,
|
|
38
57
|
isErrorPush: () => isErrorPush,
|
|
39
58
|
isReasoningPush: () => isReasoningPush,
|
|
40
59
|
isToolRequestPush: () => isToolRequestPush,
|
|
41
60
|
isValidUrl: () => isValidUrl,
|
|
61
|
+
jsonToBase64Url: () => jsonToBase64Url,
|
|
62
|
+
normalizeAiApiUrl: () => normalizeAiApiUrl,
|
|
42
63
|
normalizeVapidSubject: () => normalizeVapidSubject,
|
|
64
|
+
randomBytes: () => randomBytes,
|
|
65
|
+
randomUUID: () => randomUUID,
|
|
43
66
|
readReasoningContent: () => readReasoningContent,
|
|
67
|
+
sendWebPush: () => sendWebPush,
|
|
44
68
|
stripReasoningTags: () => stripReasoningTags,
|
|
69
|
+
timingSafeEqualBytes: () => timingSafeEqualBytes,
|
|
45
70
|
toUint8: () => toUint8,
|
|
46
|
-
|
|
71
|
+
utf8: () => utf8,
|
|
72
|
+
utf8Decode: () => utf8Decode,
|
|
73
|
+
validateAvatarUrl: () => validateAvatarUrl,
|
|
74
|
+
validateLlmMessagesShape: () => validateLlmMessagesShape,
|
|
75
|
+
verifyVapidJwt: () => verifyVapidJwt
|
|
47
76
|
});
|
|
48
77
|
module.exports = __toCommonJS(src_exports);
|
|
78
|
+
|
|
79
|
+
// src/webcrypto-utils.js
|
|
80
|
+
var TEXT_ENCODER = new TextEncoder();
|
|
81
|
+
var TEXT_DECODER = new TextDecoder("utf-8", { fatal: false });
|
|
82
|
+
function toUint8(buf) {
|
|
83
|
+
if (buf instanceof Uint8Array) return buf;
|
|
84
|
+
if (buf instanceof ArrayBuffer) return new Uint8Array(buf);
|
|
85
|
+
if (ArrayBuffer.isView(buf)) return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
86
|
+
throw new TypeError("Expected ArrayBuffer / Uint8Array");
|
|
87
|
+
}
|
|
88
|
+
function concatBytes(...chunks) {
|
|
89
|
+
let total = 0;
|
|
90
|
+
for (const c of chunks) total += c.byteLength;
|
|
91
|
+
const out = new Uint8Array(total);
|
|
92
|
+
let offset = 0;
|
|
93
|
+
for (const c of chunks) {
|
|
94
|
+
out.set(c instanceof Uint8Array ? c : new Uint8Array(c.buffer || c), offset);
|
|
95
|
+
offset += c.byteLength;
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
function utf8(str) {
|
|
100
|
+
return TEXT_ENCODER.encode(String(str));
|
|
101
|
+
}
|
|
102
|
+
function utf8Decode(buf) {
|
|
103
|
+
return TEXT_DECODER.decode(toUint8(buf));
|
|
104
|
+
}
|
|
105
|
+
function bytesToBase64(buf) {
|
|
106
|
+
const bytes = toUint8(buf);
|
|
107
|
+
let bin = "";
|
|
108
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
109
|
+
bin += String.fromCharCode(bytes[i]);
|
|
110
|
+
}
|
|
111
|
+
return typeof btoa === "function" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64");
|
|
112
|
+
}
|
|
113
|
+
function bytesToBase64Url(buf) {
|
|
114
|
+
return bytesToBase64(buf).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
115
|
+
}
|
|
116
|
+
function base64UrlToBytes(input) {
|
|
117
|
+
const s = String(input).replace(/-/g, "+").replace(/_/g, "/");
|
|
118
|
+
const pad = (4 - s.length % 4) % 4;
|
|
119
|
+
const padded = s + "=".repeat(pad);
|
|
120
|
+
const bin = typeof atob === "function" ? atob(padded) : Buffer.from(padded, "base64").toString("binary");
|
|
121
|
+
const out = new Uint8Array(bin.length);
|
|
122
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
function jsonToBase64Url(value) {
|
|
126
|
+
return bytesToBase64Url(utf8(JSON.stringify(value)));
|
|
127
|
+
}
|
|
128
|
+
function bytesToHex(buf) {
|
|
129
|
+
const bytes = toUint8(buf);
|
|
130
|
+
let out = "";
|
|
131
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
132
|
+
out += bytes[i].toString(16).padStart(2, "0");
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
function hexToBytes(hex) {
|
|
137
|
+
const out = new Uint8Array(hex.length / 2);
|
|
138
|
+
for (let i = 0; i < out.length; i++) {
|
|
139
|
+
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
async function hmacSha256(keyBytes, data) {
|
|
144
|
+
const key = await globalThis.crypto.subtle.importKey(
|
|
145
|
+
"raw",
|
|
146
|
+
toUint8(keyBytes),
|
|
147
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
148
|
+
false,
|
|
149
|
+
["sign"]
|
|
150
|
+
);
|
|
151
|
+
const sig = await globalThis.crypto.subtle.sign("HMAC", key, toUint8(data));
|
|
152
|
+
return new Uint8Array(sig);
|
|
153
|
+
}
|
|
154
|
+
function timingSafeEqualBytes(a, b) {
|
|
155
|
+
const x = toUint8(a);
|
|
156
|
+
const y = toUint8(b);
|
|
157
|
+
if (x.length !== y.length) return false;
|
|
158
|
+
let diff = 0;
|
|
159
|
+
for (let i = 0; i < x.length; i++) {
|
|
160
|
+
diff |= x[i] ^ y[i];
|
|
161
|
+
}
|
|
162
|
+
return diff === 0;
|
|
163
|
+
}
|
|
164
|
+
function randomBytes(n) {
|
|
165
|
+
const out = new Uint8Array(n);
|
|
166
|
+
globalThis.crypto.getRandomValues(out);
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
function randomUUID() {
|
|
170
|
+
return globalThis.crypto.randomUUID();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/llm-messages.js
|
|
174
|
+
var VALID_LLM_MESSAGE_ROLES = /* @__PURE__ */ new Set(["system", "user", "assistant", "tool"]);
|
|
175
|
+
var LLM_MESSAGES_ERROR = Object.freeze({
|
|
176
|
+
MESSAGES_NOT_ARRAY: "MESSAGES_NOT_ARRAY",
|
|
177
|
+
MESSAGE_NOT_OBJECT: "MESSAGE_NOT_OBJECT",
|
|
178
|
+
INVALID_ROLE: "INVALID_ROLE",
|
|
179
|
+
TOOL_CALL_MALFORMED: "TOOL_CALL_MALFORMED",
|
|
180
|
+
TOOL_CONTENT_INVALID: "TOOL_CONTENT_INVALID",
|
|
181
|
+
TOOL_CALL_ID_MISSING: "TOOL_CALL_ID_MISSING",
|
|
182
|
+
CONTENT_EMPTY_STRING: "CONTENT_EMPTY_STRING",
|
|
183
|
+
CONTENT_EMPTY_ARRAY: "CONTENT_EMPTY_ARRAY",
|
|
184
|
+
CONTENT_INVALID_TYPE: "CONTENT_INVALID_TYPE"
|
|
185
|
+
});
|
|
186
|
+
function validateLlmMessagesShape(messages) {
|
|
187
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
188
|
+
return { code: LLM_MESSAGES_ERROR.MESSAGES_NOT_ARRAY };
|
|
189
|
+
}
|
|
190
|
+
for (let i = 0; i < messages.length; i++) {
|
|
191
|
+
const m = messages[i];
|
|
192
|
+
if (!m || typeof m !== "object" || Array.isArray(m)) {
|
|
193
|
+
return { code: LLM_MESSAGES_ERROR.MESSAGE_NOT_OBJECT, index: i };
|
|
194
|
+
}
|
|
195
|
+
if (!VALID_LLM_MESSAGE_ROLES.has(m.role)) {
|
|
196
|
+
return { code: LLM_MESSAGES_ERROR.INVALID_ROLE, index: i };
|
|
197
|
+
}
|
|
198
|
+
const isAssistantToolCallCarrier = m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0;
|
|
199
|
+
if (isAssistantToolCallCarrier) {
|
|
200
|
+
for (let j = 0; j < m.tool_calls.length; j++) {
|
|
201
|
+
const tc = m.tool_calls[j];
|
|
202
|
+
if (!tc || typeof tc !== "object" || typeof tc.id !== "string" || !tc.function) {
|
|
203
|
+
return { code: LLM_MESSAGES_ERROR.TOOL_CALL_MALFORMED, index: i, toolCallIndex: j };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (m.role === "tool") {
|
|
209
|
+
if (typeof m.content !== "string" && !Array.isArray(m.content)) {
|
|
210
|
+
return { code: LLM_MESSAGES_ERROR.TOOL_CONTENT_INVALID, index: i };
|
|
211
|
+
}
|
|
212
|
+
if (typeof m.tool_call_id !== "string" || !m.tool_call_id) {
|
|
213
|
+
return { code: LLM_MESSAGES_ERROR.TOOL_CALL_ID_MISSING, index: i };
|
|
214
|
+
}
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (typeof m.content === "string") {
|
|
218
|
+
if (!m.content) {
|
|
219
|
+
return { code: LLM_MESSAGES_ERROR.CONTENT_EMPTY_STRING, index: i };
|
|
220
|
+
}
|
|
221
|
+
} else if (Array.isArray(m.content)) {
|
|
222
|
+
if (m.content.length === 0) {
|
|
223
|
+
return { code: LLM_MESSAGES_ERROR.CONTENT_EMPTY_ARRAY, index: i };
|
|
224
|
+
}
|
|
225
|
+
} else {
|
|
226
|
+
return { code: LLM_MESSAGES_ERROR.CONTENT_INVALID_TYPE, index: i };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// src/llm-call.js
|
|
233
|
+
async function callLlm(payload, options = {}) {
|
|
234
|
+
const requireContent = options.requireContent !== false;
|
|
235
|
+
const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 3e5;
|
|
236
|
+
const fetchImpl = options.fetch || globalThis.fetch;
|
|
237
|
+
const normalizedApiUrl = normalizeAiApiUrl(payload.apiUrl);
|
|
238
|
+
const requestBody = buildLlmRequestBody(payload, options);
|
|
239
|
+
const aiResponse = await fetchImpl(normalizedApiUrl, {
|
|
240
|
+
method: "POST",
|
|
241
|
+
headers: {
|
|
242
|
+
"Content-Type": "application/json",
|
|
243
|
+
"Authorization": `Bearer ${payload.apiKey}`
|
|
244
|
+
},
|
|
245
|
+
body: JSON.stringify(requestBody),
|
|
246
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
247
|
+
});
|
|
248
|
+
if (!aiResponse.ok) {
|
|
249
|
+
if (aiResponse.status === 405) {
|
|
250
|
+
throw new Error(
|
|
251
|
+
`AI API error: 405 Method Not Allowed. apiUrl must point to a full chat endpoint (for example: /chat/completions). Received: ${normalizedApiUrl}`
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
throw new Error(
|
|
255
|
+
`AI API error: ${aiResponse.status} ${aiResponse.statusText || "Unknown Error"}. Request URL: ${normalizedApiUrl}`
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const aiData = await aiResponse.json();
|
|
259
|
+
const rawContent = aiData?.choices?.[0]?.message?.content;
|
|
260
|
+
if (requireContent && (typeof rawContent !== "string" || !rawContent.trim())) {
|
|
261
|
+
throw new Error("AI API error: response missing choices[0].message.content");
|
|
262
|
+
}
|
|
263
|
+
return { response: aiData, content: typeof rawContent === "string" ? rawContent.trim() : "" };
|
|
264
|
+
}
|
|
265
|
+
function buildLlmRequestBody(payload, options = {}) {
|
|
266
|
+
const llmMessages = Array.isArray(payload.messages) && payload.messages.length > 0 ? payload.messages : [{ role: "user", content: payload.completePrompt }];
|
|
267
|
+
const requestBody = {
|
|
268
|
+
model: payload.primaryModel,
|
|
269
|
+
messages: llmMessages
|
|
270
|
+
};
|
|
271
|
+
if (options.stream !== void 0) {
|
|
272
|
+
requestBody.stream = options.stream;
|
|
273
|
+
}
|
|
274
|
+
if (payload.temperature !== void 0 && payload.temperature !== null) {
|
|
275
|
+
requestBody.temperature = payload.temperature;
|
|
276
|
+
} else if (!Array.isArray(payload.messages)) {
|
|
277
|
+
requestBody.temperature = 0.8;
|
|
278
|
+
}
|
|
279
|
+
if (options.forwardTools !== false && Array.isArray(payload.tools) && payload.tools.length > 0) {
|
|
280
|
+
requestBody.tools = payload.tools;
|
|
281
|
+
if (payload.toolChoice !== void 0 && payload.toolChoice !== null) {
|
|
282
|
+
requestBody.tool_choice = payload.toolChoice;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (payload.maxTokens === void 0 || payload.maxTokens === null) {
|
|
286
|
+
return requestBody;
|
|
287
|
+
}
|
|
288
|
+
if (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0) {
|
|
289
|
+
throw new Error("Invalid maxTokens: maxTokens must be a positive integer when provided.");
|
|
290
|
+
}
|
|
291
|
+
requestBody.max_tokens = payload.maxTokens;
|
|
292
|
+
return requestBody;
|
|
293
|
+
}
|
|
294
|
+
function normalizeAiApiUrl(apiUrl) {
|
|
295
|
+
const trimmed = String(apiUrl || "").trim();
|
|
296
|
+
if (!trimmed) {
|
|
297
|
+
throw new Error(
|
|
298
|
+
"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)."
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
let parsed;
|
|
302
|
+
try {
|
|
303
|
+
parsed = new URL(trimmed);
|
|
304
|
+
} catch {
|
|
305
|
+
throw new Error(
|
|
306
|
+
`Invalid apiUrl: "${apiUrl}". Please provide a valid absolute URL.`
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
let path = parsed.pathname.replace(/\/+$/, "") || "/";
|
|
310
|
+
if (/\/chat\/completions$/.test(path)) {
|
|
311
|
+
} else if (path === "/") {
|
|
312
|
+
path = "/v1/chat/completions";
|
|
313
|
+
} else if (/\/v\d+$/.test(path)) {
|
|
314
|
+
path = `${path}/chat/completions`;
|
|
315
|
+
}
|
|
316
|
+
parsed.pathname = path;
|
|
317
|
+
return parsed.toString();
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/webpush.js
|
|
321
|
+
var KEY_INFO_PREFIX = utf8("WebPush: info\0");
|
|
322
|
+
var CEK_INFO = utf8("Content-Encoding: aes128gcm\0");
|
|
323
|
+
var NONCE_INFO = utf8("Content-Encoding: nonce\0");
|
|
324
|
+
var VAPID_DEFAULT_TTL = 60;
|
|
325
|
+
var VAPID_TOKEN_LIFETIME = 12 * 3600;
|
|
326
|
+
var RECORD_SIZE = 4096;
|
|
327
|
+
async function sendWebPush({ subscription, payload, vapid, ttl, fetch: fetchImpl }) {
|
|
328
|
+
if (!subscription || typeof subscription.endpoint !== "string") {
|
|
329
|
+
throw new Error("sendWebPush: invalid subscription");
|
|
330
|
+
}
|
|
331
|
+
if (typeof payload !== "string") {
|
|
332
|
+
throw new Error("sendWebPush: payload must be a string");
|
|
333
|
+
}
|
|
334
|
+
if (!vapid || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
|
|
335
|
+
throw new Error("VAPID_CONFIG_MISSING");
|
|
336
|
+
}
|
|
337
|
+
const subscriptionKeys = subscription.keys || {};
|
|
338
|
+
if (typeof subscriptionKeys.p256dh !== "string" || typeof subscriptionKeys.auth !== "string") {
|
|
339
|
+
throw new Error("sendWebPush: subscription.keys.p256dh and .auth are required");
|
|
340
|
+
}
|
|
341
|
+
const encryptedBody = await encryptPushPayload({
|
|
342
|
+
plaintext: utf8(payload),
|
|
343
|
+
uaPublicKey: base64UrlToBytes(subscriptionKeys.p256dh),
|
|
344
|
+
authSecret: base64UrlToBytes(subscriptionKeys.auth)
|
|
345
|
+
});
|
|
346
|
+
const jwt = await buildVapidJwt({
|
|
347
|
+
audience: originOf(subscription.endpoint),
|
|
348
|
+
subject: normalizeVapidSubject(vapid.email),
|
|
349
|
+
publicKey: vapid.publicKey,
|
|
350
|
+
privateKey: vapid.privateKey
|
|
351
|
+
});
|
|
352
|
+
const fetchFn = fetchImpl || globalThis.fetch;
|
|
353
|
+
if (typeof fetchFn !== "function") {
|
|
354
|
+
throw new Error("sendWebPush: no fetch implementation available");
|
|
355
|
+
}
|
|
356
|
+
const res = await fetchFn(subscription.endpoint, {
|
|
357
|
+
method: "POST",
|
|
358
|
+
headers: {
|
|
359
|
+
"Content-Type": "application/octet-stream",
|
|
360
|
+
"Content-Encoding": "aes128gcm",
|
|
361
|
+
"TTL": String(Number.isFinite(ttl) ? ttl : VAPID_DEFAULT_TTL),
|
|
362
|
+
"Authorization": `vapid t=${jwt}, k=${vapid.publicKey}`
|
|
363
|
+
},
|
|
364
|
+
body: encryptedBody
|
|
365
|
+
});
|
|
366
|
+
if (!res.ok) {
|
|
367
|
+
const text = await safeReadText(res);
|
|
368
|
+
const err = new Error(
|
|
369
|
+
`Web Push delivery failed: ${res.status} ${res.statusText || ""}${text ? ` \u2014 ${text}` : ""}`
|
|
370
|
+
);
|
|
371
|
+
err.code = "PUSH_SEND_FAILED";
|
|
372
|
+
err.statusCode = res.status;
|
|
373
|
+
throw err;
|
|
374
|
+
}
|
|
375
|
+
return {
|
|
376
|
+
statusCode: res.status,
|
|
377
|
+
body: await safeReadText(res),
|
|
378
|
+
headers: res.headers
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
async function encryptPushPayload({ plaintext, uaPublicKey, authSecret }) {
|
|
382
|
+
const asKeyPair = await globalThis.crypto.subtle.generateKey(
|
|
383
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
384
|
+
true,
|
|
385
|
+
["deriveBits"]
|
|
386
|
+
);
|
|
387
|
+
const asPublicRaw = new Uint8Array(
|
|
388
|
+
await globalThis.crypto.subtle.exportKey("raw", asKeyPair.publicKey)
|
|
389
|
+
);
|
|
390
|
+
const uaPublicCryptoKey = await globalThis.crypto.subtle.importKey(
|
|
391
|
+
"raw",
|
|
392
|
+
uaPublicKey,
|
|
393
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
394
|
+
false,
|
|
395
|
+
[]
|
|
396
|
+
);
|
|
397
|
+
const ecdhSecret = new Uint8Array(
|
|
398
|
+
await globalThis.crypto.subtle.deriveBits(
|
|
399
|
+
{ name: "ECDH", public: uaPublicCryptoKey },
|
|
400
|
+
asKeyPair.privateKey,
|
|
401
|
+
256
|
|
402
|
+
)
|
|
403
|
+
);
|
|
404
|
+
const keyInfo = concatBytes(KEY_INFO_PREFIX, uaPublicKey, asPublicRaw);
|
|
405
|
+
const ikm = await hkdfSha256(authSecret, ecdhSecret, keyInfo, 32);
|
|
406
|
+
const salt = randomBytes(16);
|
|
407
|
+
const cekBytes = await hkdfSha256(salt, ikm, CEK_INFO, 16);
|
|
408
|
+
const cek = await globalThis.crypto.subtle.importKey(
|
|
409
|
+
"raw",
|
|
410
|
+
cekBytes,
|
|
411
|
+
{ name: "AES-GCM" },
|
|
412
|
+
false,
|
|
413
|
+
["encrypt"]
|
|
414
|
+
);
|
|
415
|
+
const nonce = await hkdfSha256(salt, ikm, NONCE_INFO, 12);
|
|
416
|
+
const padded = concatBytes(plaintext, new Uint8Array([2]));
|
|
417
|
+
const ciphertext = new Uint8Array(
|
|
418
|
+
await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, cek, padded)
|
|
419
|
+
);
|
|
420
|
+
const header = new Uint8Array(16 + 4 + 1 + asPublicRaw.byteLength);
|
|
421
|
+
header.set(salt, 0);
|
|
422
|
+
writeUint32BE(header, 16, RECORD_SIZE);
|
|
423
|
+
header[20] = asPublicRaw.byteLength;
|
|
424
|
+
header.set(asPublicRaw, 21);
|
|
425
|
+
return concatBytes(header, ciphertext);
|
|
426
|
+
}
|
|
427
|
+
async function hkdfSha256(salt, ikm, info, length) {
|
|
428
|
+
const baseKey = await globalThis.crypto.subtle.importKey(
|
|
429
|
+
"raw",
|
|
430
|
+
toUint8(ikm),
|
|
431
|
+
{ name: "HKDF" },
|
|
432
|
+
false,
|
|
433
|
+
["deriveBits"]
|
|
434
|
+
);
|
|
435
|
+
const bits = await globalThis.crypto.subtle.deriveBits(
|
|
436
|
+
{
|
|
437
|
+
name: "HKDF",
|
|
438
|
+
hash: "SHA-256",
|
|
439
|
+
salt: toUint8(salt),
|
|
440
|
+
info: toUint8(info)
|
|
441
|
+
},
|
|
442
|
+
baseKey,
|
|
443
|
+
length * 8
|
|
444
|
+
);
|
|
445
|
+
return new Uint8Array(bits);
|
|
446
|
+
}
|
|
447
|
+
async function buildVapidJwt({ audience, subject, publicKey, privateKey }) {
|
|
448
|
+
const header = jsonToBase64Url({ typ: "JWT", alg: "ES256" });
|
|
449
|
+
const payload = jsonToBase64Url({
|
|
450
|
+
aud: audience,
|
|
451
|
+
exp: Math.floor(Date.now() / 1e3) + VAPID_TOKEN_LIFETIME,
|
|
452
|
+
sub: subject
|
|
453
|
+
});
|
|
454
|
+
const signingInput = utf8(`${header}.${payload}`);
|
|
455
|
+
const pubBytes = base64UrlToBytes(publicKey);
|
|
456
|
+
const privBytes = base64UrlToBytes(privateKey);
|
|
457
|
+
if (pubBytes.length !== 65 || pubBytes[0] !== 4) {
|
|
458
|
+
throw new Error("VAPID publicKey must be a 65-byte uncompressed P-256 point (base64url).");
|
|
459
|
+
}
|
|
460
|
+
if (privBytes.length !== 32) {
|
|
461
|
+
throw new Error("VAPID privateKey must be a 32-byte scalar (base64url).");
|
|
462
|
+
}
|
|
463
|
+
const jwk = {
|
|
464
|
+
kty: "EC",
|
|
465
|
+
crv: "P-256",
|
|
466
|
+
d: bytesToBase64Url(privBytes),
|
|
467
|
+
x: bytesToBase64Url(pubBytes.subarray(1, 33)),
|
|
468
|
+
y: bytesToBase64Url(pubBytes.subarray(33, 65)),
|
|
469
|
+
ext: true
|
|
470
|
+
};
|
|
471
|
+
const key = await globalThis.crypto.subtle.importKey(
|
|
472
|
+
"jwk",
|
|
473
|
+
jwk,
|
|
474
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
475
|
+
false,
|
|
476
|
+
["sign"]
|
|
477
|
+
);
|
|
478
|
+
const sig = await globalThis.crypto.subtle.sign(
|
|
479
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
480
|
+
key,
|
|
481
|
+
signingInput
|
|
482
|
+
);
|
|
483
|
+
return `${header}.${payload}.${bytesToBase64Url(sig)}`;
|
|
484
|
+
}
|
|
485
|
+
async function verifyVapidJwt(jwt, publicKey) {
|
|
486
|
+
const parts = String(jwt).split(".");
|
|
487
|
+
if (parts.length !== 3) throw new Error("VAPID JWT: malformed (expected three segments)");
|
|
488
|
+
const [h, p, s] = parts;
|
|
489
|
+
const pubBytes = base64UrlToBytes(publicKey);
|
|
490
|
+
if (pubBytes.length !== 65 || pubBytes[0] !== 4) {
|
|
491
|
+
throw new Error("VAPID publicKey must be 65 B uncompressed P-256 (base64url).");
|
|
492
|
+
}
|
|
493
|
+
const jwk = {
|
|
494
|
+
kty: "EC",
|
|
495
|
+
crv: "P-256",
|
|
496
|
+
x: bytesToBase64Url(pubBytes.subarray(1, 33)),
|
|
497
|
+
y: bytesToBase64Url(pubBytes.subarray(33, 65)),
|
|
498
|
+
ext: true
|
|
499
|
+
};
|
|
500
|
+
const key = await globalThis.crypto.subtle.importKey(
|
|
501
|
+
"jwk",
|
|
502
|
+
jwk,
|
|
503
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
504
|
+
false,
|
|
505
|
+
["verify"]
|
|
506
|
+
);
|
|
507
|
+
const ok = await globalThis.crypto.subtle.verify(
|
|
508
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
509
|
+
key,
|
|
510
|
+
base64UrlToBytes(s),
|
|
511
|
+
utf8(`${h}.${p}`)
|
|
512
|
+
);
|
|
513
|
+
if (!ok) throw new Error("VAPID JWT: signature mismatch");
|
|
514
|
+
const payload = JSON.parse(new TextDecoder().decode(base64UrlToBytes(p)));
|
|
515
|
+
if (!payload.exp || payload.exp <= Math.floor(Date.now() / 1e3)) {
|
|
516
|
+
throw new Error("VAPID JWT: expired");
|
|
517
|
+
}
|
|
518
|
+
return payload;
|
|
519
|
+
}
|
|
520
|
+
function originOf(endpoint) {
|
|
521
|
+
return new URL(endpoint).origin;
|
|
522
|
+
}
|
|
523
|
+
function writeUint32BE(buf, offset, value) {
|
|
524
|
+
buf[offset] = value >>> 24 & 255;
|
|
525
|
+
buf[offset + 1] = value >>> 16 & 255;
|
|
526
|
+
buf[offset + 2] = value >>> 8 & 255;
|
|
527
|
+
buf[offset + 3] = value & 255;
|
|
528
|
+
}
|
|
529
|
+
async function safeReadText(res) {
|
|
530
|
+
try {
|
|
531
|
+
return await res.text();
|
|
532
|
+
} catch {
|
|
533
|
+
return "";
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/protocol.js
|
|
538
|
+
var MULTIPART_MESSAGE_KIND = "_multipart";
|
|
539
|
+
var MULTIPART_ENCODING = "json-utf8-base64url";
|
|
540
|
+
var MULTIPART_VERSION = 1;
|
|
541
|
+
var DEFAULT_MULTIPART_TTL_MS = 6e4;
|
|
542
|
+
var DEFAULT_MULTIPART_MAX_CHUNKS = 128;
|
|
543
|
+
var DEFAULT_MULTIPART_MAX_TOTAL_BYTES = 256e3;
|
|
544
|
+
var REI_AMSG_POSTMESSAGE_TYPE = "REI_AMSG_PUSH";
|
|
545
|
+
var REI_SW_EVENT = Object.freeze({
|
|
546
|
+
CONTENT_RECEIVED: "rei-amsg-content-received",
|
|
547
|
+
REASONING_RECEIVED: "rei-amsg-reasoning-received",
|
|
548
|
+
TOOL_REQUEST_RECEIVED: "rei-amsg-tool-request-received",
|
|
549
|
+
ERROR_RECEIVED: "rei-amsg-error-received",
|
|
550
|
+
MULTIPART_EXPIRED: "rei-amsg-multipart-expired",
|
|
551
|
+
UNKNOWN_RECEIVED: "rei-amsg-unknown-received"
|
|
552
|
+
});
|
|
553
|
+
var REI_SW_MESSAGE_TYPE = Object.freeze({
|
|
554
|
+
ENQUEUE_REQUEST: "REI_ENQUEUE_REQUEST",
|
|
555
|
+
DELIVER: "REI_AMSG_DELIVER",
|
|
556
|
+
FLUSH_QUEUE: "REI_FLUSH_QUEUE",
|
|
557
|
+
QUEUE_RESULT: "REI_QUEUE_RESULT"
|
|
558
|
+
});
|
|
559
|
+
var REI_AMSG_DELIVER_MESSAGE_TYPE = REI_SW_MESSAGE_TYPE.DELIVER;
|
|
560
|
+
|
|
561
|
+
// src/index.js
|
|
49
562
|
var MESSAGE_KIND = Object.freeze({
|
|
50
563
|
CONTENT: "content",
|
|
51
564
|
REASONING: "reasoning",
|
|
@@ -248,32 +761,6 @@ function chunkReasoningByUtf8Bytes(text, maxBytes) {
|
|
|
248
761
|
}
|
|
249
762
|
return chunks;
|
|
250
763
|
}
|
|
251
|
-
function toUint8(buf) {
|
|
252
|
-
if (buf instanceof Uint8Array) return buf;
|
|
253
|
-
if (buf instanceof ArrayBuffer) return new Uint8Array(buf);
|
|
254
|
-
if (ArrayBuffer.isView(buf)) return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
255
|
-
throw new TypeError("Expected ArrayBuffer / Uint8Array");
|
|
256
|
-
}
|
|
257
|
-
function base64UrlToBytes(input) {
|
|
258
|
-
const s = String(input).replace(/-/g, "+").replace(/_/g, "/");
|
|
259
|
-
const pad = (4 - s.length % 4) % 4;
|
|
260
|
-
const padded = s + "=".repeat(pad);
|
|
261
|
-
const bin = typeof atob === "function" ? atob(padded) : Buffer.from(padded, "base64").toString("binary");
|
|
262
|
-
const out = new Uint8Array(bin.length);
|
|
263
|
-
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
264
|
-
return out;
|
|
265
|
-
}
|
|
266
|
-
function concatBytes(...chunks) {
|
|
267
|
-
let total = 0;
|
|
268
|
-
for (const c of chunks) total += c.byteLength;
|
|
269
|
-
const out = new Uint8Array(total);
|
|
270
|
-
let offset = 0;
|
|
271
|
-
for (const c of chunks) {
|
|
272
|
-
out.set(c instanceof Uint8Array ? c : new Uint8Array(c.buffer || c), offset);
|
|
273
|
-
offset += c.byteLength;
|
|
274
|
-
}
|
|
275
|
-
return out;
|
|
276
|
-
}
|
|
277
764
|
function isValidUrl(value) {
|
|
278
765
|
if (typeof value !== "string") return false;
|
|
279
766
|
try {
|
package/dist/index.d.cts
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
|
|
@@ -476,6 +460,14 @@ export const AVATAR_URL_MAX_LENGTH: 2048;
|
|
|
476
460
|
* `metadata` is a passthrough namespace owned by the caller. Packages
|
|
477
461
|
* are forbidden from writing their own fields into `metadata` — any
|
|
478
462
|
* protocol-level data goes on top-level fields.
|
|
463
|
+
*
|
|
464
|
+
* Scheduling identity (`taskId` / `taskUuid` / `recurrenceType` /
|
|
465
|
+
* `occurrenceMs`) is stamped by `@rei-standard/amsg-server` on every push
|
|
466
|
+
* that came out of a scheduled task row. It tells the client which task
|
|
467
|
+
* this is, whether the task will come back, and which nominal fire time
|
|
468
|
+
* produced this burst — so a task the client never created (one the
|
|
469
|
+
* character scheduled for itself at fire time) still arrives fully
|
|
470
|
+
* identified. Pushes with no task behind them (amsg-instant) omit all four.
|
|
479
471
|
*/
|
|
480
472
|
export type AmsgPushCommon = {
|
|
481
473
|
/**
|
|
@@ -491,7 +483,7 @@ export type AmsgPushCommon = {
|
|
|
491
483
|
*/
|
|
492
484
|
messageId: string;
|
|
493
485
|
/**
|
|
494
|
-
* - Shared across all pushes from one LLM round (reasoning + content) and across iterations of a single agentic-loop request.
|
|
486
|
+
* - Shared across all pushes from one LLM round (reasoning + content) and across iterations of a single agentic-loop request. Opaque id — do not parse it for task identity, read the fields below.
|
|
495
487
|
*/
|
|
496
488
|
sessionId: string;
|
|
497
489
|
/**
|
|
@@ -510,6 +502,22 @@ export type AmsgPushCommon = {
|
|
|
510
502
|
* - SW notification strategy.
|
|
511
503
|
*/
|
|
512
504
|
notification?: NotificationDirective;
|
|
505
|
+
/**
|
|
506
|
+
* - Scheduled task row id.
|
|
507
|
+
*/
|
|
508
|
+
taskId?: number | string | null;
|
|
509
|
+
/**
|
|
510
|
+
* - Scheduled task uuid (the id the scheduling side chose).
|
|
511
|
+
*/
|
|
512
|
+
taskUuid?: string | null;
|
|
513
|
+
/**
|
|
514
|
+
* - Whether that task fires again.
|
|
515
|
+
*/
|
|
516
|
+
recurrenceType?: "none" | "daily" | "weekly";
|
|
517
|
+
/**
|
|
518
|
+
* - Nominal fire time of this occurrence (epoch ms).
|
|
519
|
+
*/
|
|
520
|
+
occurrenceMs?: number | null;
|
|
513
521
|
};
|
|
514
522
|
/**
|
|
515
523
|
* SW-rendering directive. Mirrors the fields that `amsg-sw`'s
|
|
@@ -584,7 +592,6 @@ export type ContentPush = AmsgPushCommon & {
|
|
|
584
592
|
avatarUrl?: string | null;
|
|
585
593
|
messageIndex?: number;
|
|
586
594
|
totalMessages?: number;
|
|
587
|
-
taskId?: string | null;
|
|
588
595
|
};
|
|
589
596
|
/**
|
|
590
597
|
* LLM "meta-thinking" — `choices[0].message.reasoning_content` lifted
|
|
@@ -710,3 +717,8 @@ export type MessageType = "instant" | "fixed" | "prompted" | "auto";
|
|
|
710
717
|
* add values.
|
|
711
718
|
*/
|
|
712
719
|
export type PushSource = "instant" | "scheduled";
|
|
720
|
+
export { toUint8, concatBytes, utf8, utf8Decode, bytesToBase64, bytesToBase64Url, base64UrlToBytes, jsonToBase64Url, bytesToHex, hexToBytes, hmacSha256, timingSafeEqualBytes, randomBytes, randomUUID } from "./webcrypto-utils.js";
|
|
721
|
+
export { LLM_MESSAGES_ERROR, validateLlmMessagesShape } from "./llm-messages.js";
|
|
722
|
+
export { callLlm, buildLlmRequestBody, normalizeAiApiUrl } from "./llm-call.js";
|
|
723
|
+
export { sendWebPush, buildVapidJwt, verifyVapidJwt } from "./webpush.js";
|
|
724
|
+
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";
|