@rei-standard/amsg-shared 0.4.0-next.1 → 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/LICENSE +21 -0
- package/dist/index.cjs +514 -27
- package/dist/index.d.cts +5 -16
- package/dist/index.d.ts +5 -16
- 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.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 {
|
|
@@ -459,28 +915,57 @@ function stringifyDecisionForError(value) {
|
|
|
459
915
|
}
|
|
460
916
|
export {
|
|
461
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,
|
|
462
922
|
MESSAGE_KIND,
|
|
463
923
|
MESSAGE_TYPE,
|
|
924
|
+
MULTIPART_ENCODING,
|
|
925
|
+
MULTIPART_MESSAGE_KIND,
|
|
926
|
+
MULTIPART_VERSION,
|
|
464
927
|
PUSH_SOURCE,
|
|
928
|
+
REI_AMSG_DELIVER_MESSAGE_TYPE,
|
|
929
|
+
REI_AMSG_POSTMESSAGE_TYPE,
|
|
930
|
+
REI_SW_EVENT,
|
|
931
|
+
REI_SW_MESSAGE_TYPE,
|
|
465
932
|
assertValidDecision,
|
|
466
933
|
base64UrlToBytes,
|
|
467
934
|
buildContentPush,
|
|
468
935
|
buildErrorPush,
|
|
936
|
+
buildLlmRequestBody,
|
|
469
937
|
buildReasoningPush,
|
|
470
938
|
buildSessionContext,
|
|
471
939
|
buildToolRequestPush,
|
|
940
|
+
buildVapidJwt,
|
|
941
|
+
bytesToBase64,
|
|
942
|
+
bytesToBase64Url,
|
|
943
|
+
bytesToHex,
|
|
944
|
+
callLlm,
|
|
472
945
|
chunkReasoningByUtf8Bytes,
|
|
473
946
|
concatBytes,
|
|
474
947
|
extractAssistantMessage,
|
|
475
948
|
extractToolCallsFromDecision,
|
|
949
|
+
hexToBytes,
|
|
950
|
+
hmacSha256,
|
|
476
951
|
isContentPush,
|
|
477
952
|
isErrorPush,
|
|
478
953
|
isReasoningPush,
|
|
479
954
|
isToolRequestPush,
|
|
480
955
|
isValidUrl,
|
|
956
|
+
jsonToBase64Url,
|
|
957
|
+
normalizeAiApiUrl,
|
|
481
958
|
normalizeVapidSubject,
|
|
959
|
+
randomBytes,
|
|
960
|
+
randomUUID,
|
|
482
961
|
readReasoningContent,
|
|
962
|
+
sendWebPush,
|
|
483
963
|
stripReasoningTags,
|
|
964
|
+
timingSafeEqualBytes,
|
|
484
965
|
toUint8,
|
|
485
|
-
|
|
966
|
+
utf8,
|
|
967
|
+
utf8Decode,
|
|
968
|
+
validateAvatarUrl,
|
|
969
|
+
validateLlmMessagesShape,
|
|
970
|
+
verifyVapidJwt
|
|
486
971
|
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-compatible LLM HTTP 调用核心 — 单一事实来源。
|
|
3
|
+
*
|
|
4
|
+
* `@rei-standard/amsg-instant`(message-processor 的 callLlmRaw)与
|
|
5
|
+
* `@rei-standard/amsg-server`(lib/llm.js 的 callLlm)此前各写一份
|
|
6
|
+
* 「构造请求体 + fetch + 超时 + 解析响应 + trim」,并已出现漂移
|
|
7
|
+
* (stream 字段、messages 模式探测、超时可配性)。现在公共核心收敛到
|
|
8
|
+
* 这里,两侧差异通过 options 参数化,各包保留自己的导出名与错误码
|
|
9
|
+
* 包装:
|
|
10
|
+
*
|
|
11
|
+
* - `stream` — instant 传 `false`(一次性、非流式契约,字段显式
|
|
12
|
+
* 出现在请求体里);server 不传(字段缺省,行为与
|
|
13
|
+
* 之前逐字节一致)。
|
|
14
|
+
* - `forwardTools` — server 转发 payload.tools / payload.toolChoice
|
|
15
|
+
* (v2.6.0 起);instant 传 `false` 维持既有
|
|
16
|
+
* 「忽略 tools」行为。
|
|
17
|
+
* - `timeoutMs` — server 的 agentic 循环传剩余墙钟预算;instant 传
|
|
18
|
+
* 300000 维持现状。默认 300000。
|
|
19
|
+
*
|
|
20
|
+
* messages 模式探测统一为 `Array.isArray(payload.messages) &&
|
|
21
|
+
* payload.messages.length > 0`(server 语义):`messages: []` 回退
|
|
22
|
+
* completePrompt 模式,而不是把空数组原样发给上游。
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Call an OpenAI-compatible API.
|
|
26
|
+
*
|
|
27
|
+
* Returns the full response object alongside the extracted (trimmed)
|
|
28
|
+
* `content` string. Callers that only need the text can ignore
|
|
29
|
+
* `response`; callers that want `reasoning_content` / `tool_calls`
|
|
30
|
+
* read from `response.choices[0].message`.
|
|
31
|
+
*
|
|
32
|
+
* @param {Object} payload
|
|
33
|
+
* @param {{
|
|
34
|
+
* requireContent?: boolean,
|
|
35
|
+
* timeoutMs?: number,
|
|
36
|
+
* fetch?: typeof globalThis.fetch,
|
|
37
|
+
* stream?: boolean,
|
|
38
|
+
* forwardTools?: boolean,
|
|
39
|
+
* }} [options]
|
|
40
|
+
* requireContent defaults to true (legacy single-shot behavior:
|
|
41
|
+
* throw when the response carries no content). Tool rounds legitimately
|
|
42
|
+
* return no content (pure tool_calls), so agentic loops pass
|
|
43
|
+
* `{ requireContent: false }`.
|
|
44
|
+
* timeoutMs defaults to 300000 (the legacy per-call ceiling).
|
|
45
|
+
* fetch defaults to `globalThis.fetch` (resolved at call time so test
|
|
46
|
+
* stubs on the global still take effect).
|
|
47
|
+
* stream / forwardTools are forwarded to {@link buildLlmRequestBody}.
|
|
48
|
+
* @returns {Promise<{ response: unknown, content: string }>}
|
|
49
|
+
*/
|
|
50
|
+
export function callLlm(payload: any, options?: {
|
|
51
|
+
requireContent?: boolean;
|
|
52
|
+
timeoutMs?: number;
|
|
53
|
+
fetch?: typeof globalThis.fetch;
|
|
54
|
+
stream?: boolean;
|
|
55
|
+
forwardTools?: boolean;
|
|
56
|
+
}): Promise<{
|
|
57
|
+
response: unknown;
|
|
58
|
+
content: string;
|
|
59
|
+
}>;
|
|
60
|
+
/**
|
|
61
|
+
* Build OpenAI-compatible request body.
|
|
62
|
+
*
|
|
63
|
+
* messages mode: forward the caller's OpenAI-style array verbatim — no
|
|
64
|
+
* auto role injection, no concatenation back to a single user message.
|
|
65
|
+
* Lets the upstream app preserve system / multi-turn context
|
|
66
|
+
* byte-for-byte. A missing / empty `payload.messages` falls back to
|
|
67
|
+
* wrapping `payload.completePrompt` into a single user message.
|
|
68
|
+
*
|
|
69
|
+
* `temperature`: only inject the 0.8 default for the legacy
|
|
70
|
+
* completePrompt path; messages mode forwards whatever the upstream app
|
|
71
|
+
* set (or nothing) so behavior matches their main chat path.
|
|
72
|
+
*
|
|
73
|
+
* `max_tokens` is optional:
|
|
74
|
+
* - include it only when payload.maxTokens is provided
|
|
75
|
+
* - omit it when payload.maxTokens is undefined / null
|
|
76
|
+
*
|
|
77
|
+
* `tools` / `tool_choice` are optional as well: forwarded only when
|
|
78
|
+
* `options.forwardTools` is not `false` and the caller passes a
|
|
79
|
+
* non-empty payload.tools. An empty array is treated as "no tools"
|
|
80
|
+
* because some OpenAI-compatible relays reject `tools: []`.
|
|
81
|
+
*
|
|
82
|
+
* @param {Object} payload
|
|
83
|
+
* @param {{ stream?: boolean, forwardTools?: boolean }} [options]
|
|
84
|
+
* stream — set to include an explicit `stream` field in the body
|
|
85
|
+
* (instant passes `false`: one-shot, non-streaming by contract);
|
|
86
|
+
* omit to leave the field out entirely (server behavior).
|
|
87
|
+
* @returns {Object}
|
|
88
|
+
*/
|
|
89
|
+
export function buildLlmRequestBody(payload: any, options?: {
|
|
90
|
+
stream?: boolean;
|
|
91
|
+
forwardTools?: boolean;
|
|
92
|
+
}): any;
|
|
93
|
+
/**
|
|
94
|
+
* Normalize the AI API URL for OpenAI-compatible chat endpoints.
|
|
95
|
+
*
|
|
96
|
+
* Rules (idempotent — running it twice is the same as running it once):
|
|
97
|
+
* - Already ends with `/chat/completions` → leave as-is.
|
|
98
|
+
* - Bare host (no path or just `/`) → append `/v1/chat/completions`.
|
|
99
|
+
* - Path ends with a version segment like `/v1`,
|
|
100
|
+
* `/v2`, … (with or without trailing slash) → append only `/chat/completions`
|
|
101
|
+
* (never doubles `/v1` for callers who already
|
|
102
|
+
* include it).
|
|
103
|
+
* - Anything else (custom path that doesn't match
|
|
104
|
+
* the OpenAI shape, e.g. `/v1/messages` for
|
|
105
|
+
* Anthropic-style proxies, or `/openai/api/foo`) → leave as-is. We don't
|
|
106
|
+
* guess — the caller knows their own routing.
|
|
107
|
+
*
|
|
108
|
+
* The query string is preserved verbatim.
|
|
109
|
+
*
|
|
110
|
+
* @param {string} apiUrl
|
|
111
|
+
* @returns {string}
|
|
112
|
+
*/
|
|
113
|
+
export function normalizeAiApiUrl(apiUrl: string): string;
|