@rei-standard/amsg-server 2.6.0-next.8 → 3.0.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.
- package/LICENSE +21 -0
- package/README.md +861 -35
- package/dist/adapters/d1.d.ts +693 -0
- package/dist/adapters/factory.d.ts +39 -0
- package/dist/adapters/interface.d.ts +384 -0
- package/dist/adapters/neon.d.ts +105 -0
- package/dist/adapters/pg-shared.d.ts +194 -0
- package/dist/adapters/pg.d.ts +101 -0
- package/dist/adapters/schema.d.ts +57 -0
- package/dist/adapters/schema.sqlite.d.ts +80 -0
- package/dist/chunk-7NMQFTDJ.cjs +148 -0
- package/dist/{chunk-GOBCWCJP.mjs → chunk-GN44PST5.mjs} +68 -1
- package/dist/chunk-RL7V7VSS.mjs +8784 -0
- package/dist/chunk-TKDISKCF.cjs +163 -0
- package/dist/chunk-XKUWMYVF.mjs +163 -0
- package/dist/chunk-YBDQJVFQ.cjs +8784 -0
- package/dist/cloudflare/single-user-worker.d.ts +39 -0
- package/dist/cloudflare.cjs +35 -2
- package/dist/cloudflare.d.ts +11 -2
- package/dist/cloudflare.mjs +36 -3
- package/dist/handlers/cancel-message.d.ts +3 -0
- package/dist/handlers/capabilities.d.ts +4 -0
- package/dist/handlers/client-state-namespaces.d.ts +5 -0
- package/dist/handlers/client-state.d.ts +7 -0
- package/dist/handlers/cloud-data.d.ts +4 -0
- package/dist/handlers/get-message.d.ts +3 -0
- package/dist/handlers/get-user-key.d.ts +3 -0
- package/dist/handlers/init-tenant.d.ts +23 -0
- package/dist/handlers/llm-credentials.d.ts +5 -0
- package/dist/handlers/messages.d.ts +3 -0
- package/dist/handlers/outbox.d.ts +9 -0
- package/dist/handlers/push-subscription.d.ts +5 -0
- package/dist/handlers/schedule-message.d.ts +3 -0
- package/dist/handlers/send-notifications.d.ts +3 -0
- package/dist/handlers/single-user-init.d.ts +13 -0
- package/dist/handlers/update-message.d.ts +3 -0
- package/dist/handlers/vapid-public-key.d.ts +19 -0
- package/dist/index.cjs +133 -44
- package/dist/index.d.cts +145 -766
- package/dist/index.d.ts +145 -766
- package/dist/index.mjs +125 -36
- package/dist/lib/agentic-fire.d.ts +177 -0
- package/dist/lib/client-state-store.d.ts +88 -0
- package/dist/lib/cloud-data-cleanup.d.ts +36 -0
- package/dist/lib/cloud-data-guard.d.ts +14 -0
- package/dist/lib/cloud-data-inventory.d.ts +15 -0
- package/dist/lib/constant-time.d.ts +14 -0
- package/dist/lib/db-errors.d.ts +10 -0
- package/dist/lib/encryption.d.ts +48 -0
- package/dist/lib/errors.d.ts +273 -0
- package/dist/lib/llm-credentials-store.d.ts +147 -0
- package/dist/lib/llm.d.ts +12 -0
- package/dist/lib/message-processor.d.ts +82 -0
- package/dist/lib/outbox-store.d.ts +162 -0
- package/dist/lib/push-policy.d.ts +11 -0
- package/dist/lib/push-subscription-store.d.ts +94 -0
- package/dist/lib/recurrence.d.ts +51 -0
- package/dist/lib/request.d.ts +182 -0
- package/dist/lib/result-emitter.d.ts +60 -0
- package/dist/lib/retry-policy.d.ts +11 -0
- package/dist/lib/run-tick.d.ts +121 -0
- package/dist/lib/schema-version.d.ts +50 -0
- package/dist/lib/state-accessors.d.ts +70 -0
- package/dist/lib/state-chunks.d.ts +65 -0
- package/dist/lib/task-projection.d.ts +92 -0
- package/dist/lib/validation.d.ts +97 -0
- package/dist/lib/version.d.ts +7 -0
- package/dist/lib/webcrypto-utils.d.ts +1 -0
- package/dist/lib/webpush-webcrypto.d.ts +78 -0
- package/dist/{neon-QJ7KYHEX.mjs → neon-GKLT4UY3.mjs} +116 -44
- package/dist/{neon-V4VOH55N.cjs → neon-XHPJZESV.cjs} +121 -49
- package/dist/{pg-6X74HKMX.cjs → pg-FHXQ6BJP.cjs} +109 -48
- package/dist/{pg-DFJSFOJQ.mjs → pg-J4YXRQP5.mjs} +104 -43
- package/dist/single-user.d.ts +106 -0
- package/dist/tenant/blob-store.d.ts +30 -0
- package/dist/tenant/context.d.ts +47 -0
- package/dist/tenant/single-user-context.d.ts +29 -0
- package/dist/tenant/token.d.ts +26 -0
- package/package.json +3 -3
- package/dist/chunk-DCKCAGFV.cjs +0 -81
- package/dist/chunk-HQHRXSQA.cjs +0 -2710
- package/dist/chunk-LEE5KQ7Y.mjs +0 -2710
- package/dist/cloudflare-CH3dBl5b.d.cts +0 -4235
- package/dist/cloudflare-CH3dBl5b.d.ts +0 -4235
- package/dist/cloudflare.d.cts +0 -2
- package/dist/neon-D8Z2Nn97.d.cts +0 -295
- package/dist/neon-PqNFJIz2.d.ts +0 -295
- package/dist/pg-C48FwCWW.d.cts +0 -289
- package/dist/pg-C5gtWUfU.d.ts +0 -289
- package/dist/schema-BHuyH_6Z.d.cts +0 -88
- package/dist/schema-BHuyH_6Z.d.ts +0 -88
package/dist/chunk-HQHRXSQA.cjs
DELETED
|
@@ -1,2710 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/server/lib/validation.js
|
|
2
|
-
var _amsgshared = require('@rei-standard/amsg-shared');
|
|
3
|
-
function isValidISO8601(dateString) {
|
|
4
|
-
const date = new Date(dateString);
|
|
5
|
-
return date instanceof Date && !isNaN(date.getTime());
|
|
6
|
-
}
|
|
7
|
-
function isValidUrl(urlString) {
|
|
8
|
-
try {
|
|
9
|
-
new URL(urlString);
|
|
10
|
-
return true;
|
|
11
|
-
} catch (e) {
|
|
12
|
-
return false;
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
function isValidUUID(uuid) {
|
|
16
|
-
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
17
|
-
return uuidRegex.test(uuid);
|
|
18
|
-
}
|
|
19
|
-
function isValidUUIDv4(uuid) {
|
|
20
|
-
const uuidV4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
21
|
-
return uuidV4Regex.test(uuid);
|
|
22
|
-
}
|
|
23
|
-
var VALID_LLM_MESSAGE_ROLES = /* @__PURE__ */ new Set(["system", "user", "assistant", "tool"]);
|
|
24
|
-
var SPLIT_PATTERN_MAX_LENGTH = 200;
|
|
25
|
-
var SPLIT_PATTERN_MAX_ITEMS = 10;
|
|
26
|
-
function validateSplitPattern(value) {
|
|
27
|
-
if (value === void 0 || value === null) return null;
|
|
28
|
-
const isArray = Array.isArray(value);
|
|
29
|
-
const items = isArray ? value : [value];
|
|
30
|
-
if (isArray && items.length === 0) return null;
|
|
31
|
-
if (items.length > SPLIT_PATTERN_MAX_ITEMS) {
|
|
32
|
-
return `splitPattern \u6570\u7EC4\u6700\u591A ${SPLIT_PATTERN_MAX_ITEMS} \u9879`;
|
|
33
|
-
}
|
|
34
|
-
for (let i = 0; i < items.length; i++) {
|
|
35
|
-
const s = items[i];
|
|
36
|
-
const label = isArray ? `splitPattern[${i}]` : "splitPattern";
|
|
37
|
-
if (typeof s !== "string") return `${label} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`;
|
|
38
|
-
if (s.length > SPLIT_PATTERN_MAX_LENGTH) {
|
|
39
|
-
return `${label} \u4E0D\u80FD\u8D85\u8FC7 ${SPLIT_PATTERN_MAX_LENGTH} \u5B57\u7B26`;
|
|
40
|
-
}
|
|
41
|
-
try {
|
|
42
|
-
new RegExp(s);
|
|
43
|
-
} catch (_) {
|
|
44
|
-
return `${label} \u4E0D\u662F\u6709\u6548\u6B63\u5219\u8868\u8FBE\u5F0F`;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
49
|
-
function validateLlmMessagesArray(messages) {
|
|
50
|
-
if (!Array.isArray(messages) || messages.length === 0) {
|
|
51
|
-
return "messages must be a non-empty array";
|
|
52
|
-
}
|
|
53
|
-
for (let i = 0; i < messages.length; i++) {
|
|
54
|
-
const m = messages[i];
|
|
55
|
-
if (!m || typeof m !== "object" || Array.isArray(m)) {
|
|
56
|
-
return `messages[${i}] must be an object`;
|
|
57
|
-
}
|
|
58
|
-
if (!VALID_LLM_MESSAGE_ROLES.has(m.role)) {
|
|
59
|
-
return `messages[${i}].role must be one of system / user / assistant / tool`;
|
|
60
|
-
}
|
|
61
|
-
if (typeof m.content === "string") {
|
|
62
|
-
if (!m.content) return `messages[${i}].content must be a non-empty string`;
|
|
63
|
-
} else if (Array.isArray(m.content)) {
|
|
64
|
-
if (m.content.length === 0) return `messages[${i}].content array must be non-empty`;
|
|
65
|
-
} else {
|
|
66
|
-
return `messages[${i}].content must be a non-empty string or a non-empty array`;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return null;
|
|
70
|
-
}
|
|
71
|
-
function validateScheduleMessagePayload(payload) {
|
|
72
|
-
if (!payload.contactName || typeof payload.contactName !== "string") {
|
|
73
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: ["contactName"] } };
|
|
74
|
-
}
|
|
75
|
-
if (!payload.messageType || !["fixed", "prompted", "auto", "instant"].includes(payload.messageType)) {
|
|
76
|
-
return { valid: false, errorCode: "INVALID_MESSAGE_TYPE", errorMessage: "\u6D88\u606F\u7C7B\u578B\u65E0\u6548", details: { providedType: payload.messageType, allowedTypes: ["fixed", "prompted", "auto", "instant"] } };
|
|
77
|
-
}
|
|
78
|
-
if (!payload.firstSendTime || !isValidISO8601(payload.firstSendTime)) {
|
|
79
|
-
return { valid: false, errorCode: "INVALID_TIMESTAMP", errorMessage: "\u65F6\u95F4\u683C\u5F0F\u65E0\u6548", details: { field: "firstSendTime" } };
|
|
80
|
-
}
|
|
81
|
-
if (payload.firstSendTime && new Date(payload.firstSendTime) <= /* @__PURE__ */ new Date()) {
|
|
82
|
-
return { valid: false, errorCode: "INVALID_TIMESTAMP", errorMessage: "\u65F6\u95F4\u5FC5\u987B\u5728\u672A\u6765", details: { field: "firstSendTime", reason: "must be in the future" } };
|
|
83
|
-
}
|
|
84
|
-
if (!payload.pushSubscription || typeof payload.pushSubscription !== "object") {
|
|
85
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: ["pushSubscription"] } };
|
|
86
|
-
}
|
|
87
|
-
if (payload.recurrenceType && !["none", "daily", "weekly"].includes(payload.recurrenceType)) {
|
|
88
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["recurrenceType"] } };
|
|
89
|
-
}
|
|
90
|
-
if (payload.maxTokens !== void 0 && payload.maxTokens !== null && (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0)) {
|
|
91
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["maxTokens"] } };
|
|
92
|
-
}
|
|
93
|
-
if (payload.messageType === "fixed") {
|
|
94
|
-
if (!payload.userMessage) {
|
|
95
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: ["userMessage (required for fixed type)"] } };
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
const promptCheck = (() => {
|
|
99
|
-
const hasCompletePrompt = payload.completePrompt !== void 0 && payload.completePrompt !== null && payload.completePrompt !== "";
|
|
100
|
-
const hasMessages = payload.messages !== void 0 && payload.messages !== null;
|
|
101
|
-
if (hasCompletePrompt && hasMessages) {
|
|
102
|
-
return {
|
|
103
|
-
error: { code: "INVALID_PARAMETERS", message: "exactly one of `completePrompt` or `messages` must be provided\uFF08\u4E24\u8005\u4E0D\u80FD\u540C\u65F6\u51FA\u73B0\uFF09", details: { invalidFields: ["completePrompt", "messages"] } },
|
|
104
|
-
hasCompletePrompt: true,
|
|
105
|
-
hasMessages: true
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
if (hasMessages) {
|
|
109
|
-
const err2 = validateLlmMessagesArray(payload.messages);
|
|
110
|
-
if (err2) {
|
|
111
|
-
return {
|
|
112
|
-
error: { code: "INVALID_PARAMETERS", message: err2, details: { invalidFields: ["messages"] } },
|
|
113
|
-
hasCompletePrompt: false,
|
|
114
|
-
hasMessages: true
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
return { error: null, hasCompletePrompt, hasMessages };
|
|
119
|
-
})();
|
|
120
|
-
if (promptCheck.error) {
|
|
121
|
-
return { valid: false, errorCode: promptCheck.error.code, errorMessage: promptCheck.error.message, details: promptCheck.error.details };
|
|
122
|
-
}
|
|
123
|
-
const hasPrompt = promptCheck.hasCompletePrompt || promptCheck.hasMessages;
|
|
124
|
-
if (payload.messageType === "prompted" || payload.messageType === "auto") {
|
|
125
|
-
const missingAiFields = [];
|
|
126
|
-
if (!hasPrompt) missingAiFields.push("completePrompt or messages");
|
|
127
|
-
if (!payload.apiUrl) missingAiFields.push("apiUrl");
|
|
128
|
-
if (!payload.apiKey) missingAiFields.push("apiKey");
|
|
129
|
-
if (!payload.primaryModel) missingAiFields.push("primaryModel");
|
|
130
|
-
if (missingAiFields.length > 0) {
|
|
131
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { missingFields: missingAiFields } };
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
if (payload.messageType === "instant") {
|
|
135
|
-
if (payload.recurrenceType && payload.recurrenceType !== "none") {
|
|
136
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "instant \u7C7B\u578B\u7684 recurrenceType \u5FC5\u987B\u4E3A none", details: { invalidFields: ['recurrenceType (must be "none" for instant type)'] } };
|
|
137
|
-
}
|
|
138
|
-
const hasAiConfig = hasPrompt && payload.apiUrl && payload.apiKey && payload.primaryModel;
|
|
139
|
-
const hasUserMessage = payload.userMessage;
|
|
140
|
-
if (!hasAiConfig && !hasUserMessage) {
|
|
141
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "instant \u7C7B\u578B\u5FC5\u987B\u63D0\u4F9B userMessage \u6216\u5B8C\u6574\u7684 AI \u914D\u7F6E", details: { missingFields: ["userMessage or ((completePrompt | messages) + apiUrl + apiKey + primaryModel)"] } };
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
if (payload.temperature !== void 0 && payload.temperature !== null && (typeof payload.temperature !== "number" || !Number.isFinite(payload.temperature))) {
|
|
145
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["temperature (must be a finite number)"] } };
|
|
146
|
-
}
|
|
147
|
-
const avatarErr = _amsgshared.validateAvatarUrl.call(void 0, payload.avatarUrl);
|
|
148
|
-
if (avatarErr) {
|
|
149
|
-
console.warn("[amsg-server] avatarUrl \u4E0D\u5408\u6CD5\uFF0C\u5DF2\u7F6E\u7A7A\uFF1A", avatarErr);
|
|
150
|
-
payload.avatarUrl = null;
|
|
151
|
-
}
|
|
152
|
-
if (payload.uuid && !isValidUUID(payload.uuid)) {
|
|
153
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["uuid (invalid UUID format)"] } };
|
|
154
|
-
}
|
|
155
|
-
if (payload.messageSubtype !== void 0 && payload.messageSubtype !== null && typeof payload.messageSubtype !== "string") {
|
|
156
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: "\u7F3A\u5C11\u5FC5\u9700\u53C2\u6570\u6216\u53C2\u6570\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["messageSubtype"] } };
|
|
157
|
-
}
|
|
158
|
-
const splitErr = validateSplitPattern(payload.splitPattern);
|
|
159
|
-
if (splitErr) {
|
|
160
|
-
return { valid: false, errorCode: "INVALID_PARAMETERS", errorMessage: splitErr, details: { invalidFields: ["splitPattern"] } };
|
|
161
|
-
}
|
|
162
|
-
return { valid: true };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// src/server/lib/webcrypto-utils.js
|
|
166
|
-
|
|
167
|
-
var TEXT_ENCODER = new TextEncoder();
|
|
168
|
-
var TEXT_DECODER = new TextDecoder("utf-8", { fatal: false });
|
|
169
|
-
function utf8(str) {
|
|
170
|
-
return TEXT_ENCODER.encode(String(str));
|
|
171
|
-
}
|
|
172
|
-
function utf8Decode(buf) {
|
|
173
|
-
return TEXT_DECODER.decode(_amsgshared.toUint8.call(void 0, buf));
|
|
174
|
-
}
|
|
175
|
-
function bytesToBase64(buf) {
|
|
176
|
-
const bytes = _amsgshared.toUint8.call(void 0, buf);
|
|
177
|
-
let bin = "";
|
|
178
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
179
|
-
bin += String.fromCharCode(bytes[i]);
|
|
180
|
-
}
|
|
181
|
-
return typeof btoa === "function" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64");
|
|
182
|
-
}
|
|
183
|
-
function bytesToBase64Url(buf) {
|
|
184
|
-
return bytesToBase64(buf).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
185
|
-
}
|
|
186
|
-
function bytesToHex(buf) {
|
|
187
|
-
const bytes = _amsgshared.toUint8.call(void 0, buf);
|
|
188
|
-
let out = "";
|
|
189
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
190
|
-
out += bytes[i].toString(16).padStart(2, "0");
|
|
191
|
-
}
|
|
192
|
-
return out;
|
|
193
|
-
}
|
|
194
|
-
function hexToBytes(hex) {
|
|
195
|
-
const out = new Uint8Array(hex.length / 2);
|
|
196
|
-
for (let i = 0; i < out.length; i++) {
|
|
197
|
-
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
198
|
-
}
|
|
199
|
-
return out;
|
|
200
|
-
}
|
|
201
|
-
function jsonToBase64Url(value) {
|
|
202
|
-
return bytesToBase64Url(utf8(JSON.stringify(value)));
|
|
203
|
-
}
|
|
204
|
-
function randomUUID() {
|
|
205
|
-
return globalThis.crypto.randomUUID();
|
|
206
|
-
}
|
|
207
|
-
function randomBytes(n) {
|
|
208
|
-
const out = new Uint8Array(n);
|
|
209
|
-
globalThis.crypto.getRandomValues(out);
|
|
210
|
-
return out;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// src/server/lib/encryption.js
|
|
214
|
-
var base64ToBytes = _amsgshared.base64UrlToBytes;
|
|
215
|
-
var TAG_LENGTH_BYTES = 16;
|
|
216
|
-
function importAesKey(hexKey, usage) {
|
|
217
|
-
return globalThis.crypto.subtle.importKey(
|
|
218
|
-
"raw",
|
|
219
|
-
hexToBytes(hexKey),
|
|
220
|
-
{ name: "AES-GCM" },
|
|
221
|
-
false,
|
|
222
|
-
[usage]
|
|
223
|
-
);
|
|
224
|
-
}
|
|
225
|
-
async function aesGcmSeal(hexKey, iv, plaintextBytes) {
|
|
226
|
-
const key = await importAesKey(hexKey, "encrypt");
|
|
227
|
-
const sealed = new Uint8Array(await globalThis.crypto.subtle.encrypt(
|
|
228
|
-
{ name: "AES-GCM", iv, tagLength: TAG_LENGTH_BYTES * 8 },
|
|
229
|
-
key,
|
|
230
|
-
plaintextBytes
|
|
231
|
-
));
|
|
232
|
-
return {
|
|
233
|
-
ciphertext: sealed.slice(0, sealed.length - TAG_LENGTH_BYTES),
|
|
234
|
-
authTag: sealed.slice(sealed.length - TAG_LENGTH_BYTES)
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
async function aesGcmOpen(hexKey, iv, ciphertext, authTag) {
|
|
238
|
-
const key = await importAesKey(hexKey, "decrypt");
|
|
239
|
-
const tagBits = authTag.length * 8;
|
|
240
|
-
const tagLength = tagBits >= 96 && tagBits <= 128 ? tagBits : 128;
|
|
241
|
-
const plain = await globalThis.crypto.subtle.decrypt(
|
|
242
|
-
{ name: "AES-GCM", iv, tagLength },
|
|
243
|
-
key,
|
|
244
|
-
_amsgshared.concatBytes.call(void 0, ciphertext, authTag)
|
|
245
|
-
);
|
|
246
|
-
return new Uint8Array(plain);
|
|
247
|
-
}
|
|
248
|
-
async function deriveUserEncryptionKey(userId, masterKey) {
|
|
249
|
-
const digest = await globalThis.crypto.subtle.digest("SHA-256", utf8(masterKey + userId));
|
|
250
|
-
return bytesToHex(new Uint8Array(digest)).slice(0, 64);
|
|
251
|
-
}
|
|
252
|
-
async function decryptPayload(encryptedPayload, encryptionKey) {
|
|
253
|
-
const { iv, authTag, encryptedData } = encryptedPayload;
|
|
254
|
-
const plain = await aesGcmOpen(
|
|
255
|
-
encryptionKey,
|
|
256
|
-
base64ToBytes(iv),
|
|
257
|
-
base64ToBytes(encryptedData),
|
|
258
|
-
base64ToBytes(authTag)
|
|
259
|
-
);
|
|
260
|
-
return JSON.parse(utf8Decode(plain));
|
|
261
|
-
}
|
|
262
|
-
async function encryptPayload(payload, encryptionKey) {
|
|
263
|
-
const plaintext = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
264
|
-
const iv = randomBytes(12);
|
|
265
|
-
const { ciphertext, authTag } = await aesGcmSeal(encryptionKey, iv, utf8(plaintext));
|
|
266
|
-
return {
|
|
267
|
-
iv: bytesToBase64(iv),
|
|
268
|
-
authTag: bytesToBase64(authTag),
|
|
269
|
-
encryptedData: bytesToBase64(ciphertext)
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
async function encryptForStorage(text, encryptionKey) {
|
|
273
|
-
const iv = randomBytes(16);
|
|
274
|
-
const { ciphertext, authTag } = await aesGcmSeal(encryptionKey, iv, utf8(text));
|
|
275
|
-
return `${bytesToHex(iv)}:${bytesToHex(authTag)}:${bytesToHex(ciphertext)}`;
|
|
276
|
-
}
|
|
277
|
-
async function decryptFromStorage(encryptedText, encryptionKey) {
|
|
278
|
-
const [ivHex, authTagHex, encryptedDataHex] = encryptedText.split(":");
|
|
279
|
-
const plain = await aesGcmOpen(
|
|
280
|
-
encryptionKey,
|
|
281
|
-
hexToBytes(ivHex),
|
|
282
|
-
hexToBytes(encryptedDataHex),
|
|
283
|
-
hexToBytes(authTagHex)
|
|
284
|
-
);
|
|
285
|
-
return utf8Decode(plain);
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
// src/server/lib/request.js
|
|
289
|
-
var REQUEST_ERRORS = {
|
|
290
|
-
INVALID_JSON: { code: "INVALID_JSON", message: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u6709\u6548\u7684 JSON" },
|
|
291
|
-
INVALID_REQUEST_BODY: { code: "INVALID_REQUEST_BODY", message: "\u8BF7\u6C42\u4F53\u683C\u5F0F\u65E0\u6548" },
|
|
292
|
-
INVALID_ENCRYPTED_PAYLOAD: { code: "INVALID_ENCRYPTED_PAYLOAD", message: "\u52A0\u5BC6\u6570\u636E\u683C\u5F0F\u9519\u8BEF" }
|
|
293
|
-
};
|
|
294
|
-
function parseBodyAsObject(body, options = {}) {
|
|
295
|
-
const invalidJson = options.invalidJson || REQUEST_ERRORS.INVALID_JSON;
|
|
296
|
-
const invalidType = options.invalidType || REQUEST_ERRORS.INVALID_REQUEST_BODY;
|
|
297
|
-
let parsed = body;
|
|
298
|
-
if (typeof parsed === "string") {
|
|
299
|
-
try {
|
|
300
|
-
parsed = JSON.parse(parsed);
|
|
301
|
-
} catch (e2) {
|
|
302
|
-
return { ok: false, error: invalidJson };
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
if (!isPlainObject(parsed)) {
|
|
306
|
-
return { ok: false, error: invalidType };
|
|
307
|
-
}
|
|
308
|
-
return { ok: true, data: parsed };
|
|
309
|
-
}
|
|
310
|
-
function parseJsonBody(body) {
|
|
311
|
-
return parseBodyAsObject(body, {
|
|
312
|
-
invalidJson: REQUEST_ERRORS.INVALID_JSON,
|
|
313
|
-
invalidType: REQUEST_ERRORS.INVALID_REQUEST_BODY
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
function isPlainObject(value) {
|
|
317
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
318
|
-
}
|
|
319
|
-
function isEncryptedEnvelope(payload) {
|
|
320
|
-
if (!isPlainObject(payload)) return false;
|
|
321
|
-
return typeof payload.iv === "string" && typeof payload.authTag === "string" && typeof payload.encryptedData === "string";
|
|
322
|
-
}
|
|
323
|
-
function parseEncryptedBody(body) {
|
|
324
|
-
const parsedBody = parseBodyAsObject(body, {
|
|
325
|
-
invalidJson: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD,
|
|
326
|
-
invalidType: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD
|
|
327
|
-
});
|
|
328
|
-
if (!parsedBody.ok) {
|
|
329
|
-
return parsedBody;
|
|
330
|
-
}
|
|
331
|
-
if (!isEncryptedEnvelope(parsedBody.data)) {
|
|
332
|
-
return { ok: false, error: REQUEST_ERRORS.INVALID_ENCRYPTED_PAYLOAD };
|
|
333
|
-
}
|
|
334
|
-
return parsedBody;
|
|
335
|
-
}
|
|
336
|
-
function getHeader(headers = {}, name) {
|
|
337
|
-
if (!headers || typeof headers !== "object") {
|
|
338
|
-
return "";
|
|
339
|
-
}
|
|
340
|
-
const lowerName = String(name || "").toLowerCase();
|
|
341
|
-
if (!lowerName) return "";
|
|
342
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
343
|
-
if (String(key).toLowerCase() === lowerName) {
|
|
344
|
-
return String(value || "").trim();
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
return "";
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
// src/server/handlers/get-user-key.js
|
|
351
|
-
function createGetUserKeyHandler(ctx) {
|
|
352
|
-
async function GET(url, headers) {
|
|
353
|
-
const effectiveHeaders = headers || url || {};
|
|
354
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
|
|
355
|
-
if (!tenantResult.ok) {
|
|
356
|
-
return tenantResult.error;
|
|
357
|
-
}
|
|
358
|
-
const { masterKey } = tenantResult.context;
|
|
359
|
-
const userId = getHeader(effectiveHeaders, "x-user-id");
|
|
360
|
-
if (!userId) {
|
|
361
|
-
return {
|
|
362
|
-
status: 400,
|
|
363
|
-
body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } }
|
|
364
|
-
};
|
|
365
|
-
}
|
|
366
|
-
if (!isValidUUIDv4(userId)) {
|
|
367
|
-
return {
|
|
368
|
-
status: 400,
|
|
369
|
-
body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } }
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
return {
|
|
373
|
-
status: 200,
|
|
374
|
-
body: {
|
|
375
|
-
success: true,
|
|
376
|
-
data: {
|
|
377
|
-
userKey: await deriveUserEncryptionKey(userId, masterKey),
|
|
378
|
-
version: 1
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
return { GET };
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// src/server/lib/db-errors.js
|
|
387
|
-
function isUniqueViolation(error) {
|
|
388
|
-
if (!error || typeof error !== "object") return false;
|
|
389
|
-
const code = error.code;
|
|
390
|
-
if (code === "23505") return true;
|
|
391
|
-
const message = typeof error.message === "string" ? error.message.toLowerCase() : "";
|
|
392
|
-
return message.includes("duplicate key") || message.includes("unique constraint");
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
// src/server/lib/message-processor.js
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
// src/server/lib/llm.js
|
|
404
|
-
async function callLlm(payload, options = {}) {
|
|
405
|
-
const requireContent = options.requireContent !== false;
|
|
406
|
-
const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 3e5;
|
|
407
|
-
const normalizedApiUrl = normalizeAiApiUrl(payload.apiUrl);
|
|
408
|
-
const requestBody = buildAiRequestBody(payload);
|
|
409
|
-
const aiResponse = await fetch(normalizedApiUrl, {
|
|
410
|
-
method: "POST",
|
|
411
|
-
headers: {
|
|
412
|
-
"Content-Type": "application/json",
|
|
413
|
-
"Authorization": `Bearer ${payload.apiKey}`
|
|
414
|
-
},
|
|
415
|
-
body: JSON.stringify(requestBody),
|
|
416
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
417
|
-
});
|
|
418
|
-
if (!aiResponse.ok) {
|
|
419
|
-
if (aiResponse.status === 405) {
|
|
420
|
-
throw new Error(
|
|
421
|
-
`AI API error: 405 Method Not Allowed. apiUrl must point to a full chat endpoint (for example: /chat/completions). Received: ${normalizedApiUrl}`
|
|
422
|
-
);
|
|
423
|
-
}
|
|
424
|
-
throw new Error(
|
|
425
|
-
`AI API error: ${aiResponse.status} ${aiResponse.statusText || "Unknown Error"}. Request URL: ${normalizedApiUrl}`
|
|
426
|
-
);
|
|
427
|
-
}
|
|
428
|
-
const aiData = await aiResponse.json();
|
|
429
|
-
const rawContent = _optionalChain([aiData, 'optionalAccess', _2 => _2.choices, 'optionalAccess', _3 => _3[0], 'optionalAccess', _4 => _4.message, 'optionalAccess', _5 => _5.content]);
|
|
430
|
-
if (requireContent && (typeof rawContent !== "string" || !rawContent.trim())) {
|
|
431
|
-
throw new Error("AI API error: response missing choices[0].message.content");
|
|
432
|
-
}
|
|
433
|
-
return { response: aiData, content: typeof rawContent === "string" ? rawContent.trim() : "" };
|
|
434
|
-
}
|
|
435
|
-
function buildAiRequestBody(payload) {
|
|
436
|
-
const llmMessages = Array.isArray(payload.messages) && payload.messages.length > 0 ? payload.messages : [{ role: "user", content: payload.completePrompt }];
|
|
437
|
-
const requestBody = {
|
|
438
|
-
model: payload.primaryModel,
|
|
439
|
-
messages: llmMessages
|
|
440
|
-
};
|
|
441
|
-
if (payload.temperature !== void 0 && payload.temperature !== null) {
|
|
442
|
-
requestBody.temperature = payload.temperature;
|
|
443
|
-
} else if (!Array.isArray(payload.messages)) {
|
|
444
|
-
requestBody.temperature = 0.8;
|
|
445
|
-
}
|
|
446
|
-
if (Array.isArray(payload.tools) && payload.tools.length > 0) {
|
|
447
|
-
requestBody.tools = payload.tools;
|
|
448
|
-
if (payload.toolChoice !== void 0 && payload.toolChoice !== null) {
|
|
449
|
-
requestBody.tool_choice = payload.toolChoice;
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
if (payload.maxTokens === void 0 || payload.maxTokens === null) {
|
|
453
|
-
return requestBody;
|
|
454
|
-
}
|
|
455
|
-
if (!Number.isInteger(payload.maxTokens) || payload.maxTokens <= 0) {
|
|
456
|
-
throw new Error("Invalid maxTokens: maxTokens must be a positive integer when provided.");
|
|
457
|
-
}
|
|
458
|
-
requestBody.max_tokens = payload.maxTokens;
|
|
459
|
-
return requestBody;
|
|
460
|
-
}
|
|
461
|
-
function normalizeAiApiUrl(apiUrl) {
|
|
462
|
-
if (typeof apiUrl !== "string" || !apiUrl.trim()) {
|
|
463
|
-
throw new Error(
|
|
464
|
-
"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)."
|
|
465
|
-
);
|
|
466
|
-
}
|
|
467
|
-
const trimmedApiUrl = apiUrl.trim();
|
|
468
|
-
let parsedUrl;
|
|
469
|
-
try {
|
|
470
|
-
parsedUrl = new URL(trimmedApiUrl);
|
|
471
|
-
} catch (e3) {
|
|
472
|
-
throw new Error(
|
|
473
|
-
`Invalid apiUrl: "${apiUrl}". Please provide a valid absolute URL.`
|
|
474
|
-
);
|
|
475
|
-
}
|
|
476
|
-
let path = parsedUrl.pathname.replace(/\/+$/, "") || "/";
|
|
477
|
-
if (/\/chat\/completions$/.test(path)) {
|
|
478
|
-
} else if (path === "/") {
|
|
479
|
-
path = "/v1/chat/completions";
|
|
480
|
-
} else if (/\/v\d+$/.test(path)) {
|
|
481
|
-
path = `${path}/chat/completions`;
|
|
482
|
-
}
|
|
483
|
-
parsedUrl.pathname = path;
|
|
484
|
-
return parsedUrl.toString();
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
// src/server/lib/agentic-fire.js
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
// src/server/lib/state-chunks.js
|
|
496
|
-
|
|
497
|
-
var STATE_CHUNK_SLICE_BYTES = 200 * 1024;
|
|
498
|
-
var DEFAULT_MAX_STATE_VALUE_BYTES = 5 * 1024 * 1024;
|
|
499
|
-
var INTERNAL_STATE_CHAR_RE = /[\u0000-\u001f]/;
|
|
500
|
-
var SEP = "";
|
|
501
|
-
var CHUNK_NS_PREFIX = `${SEP}amsg-chunks${SEP}`;
|
|
502
|
-
var ROOT_MARKER_PREFIX = `${SEP}amsg-chunked${SEP}v1${SEP}`;
|
|
503
|
-
function chunkNamespaceFor(namespace) {
|
|
504
|
-
return CHUNK_NS_PREFIX + namespace;
|
|
505
|
-
}
|
|
506
|
-
function chunkKeyFor(key, index) {
|
|
507
|
-
return `${key}${SEP}${index}`;
|
|
508
|
-
}
|
|
509
|
-
function chunkKeyPrefixFor(key) {
|
|
510
|
-
return `${key}${SEP}`;
|
|
511
|
-
}
|
|
512
|
-
function buildChunkedRootValue(chunkCount) {
|
|
513
|
-
return `${ROOT_MARKER_PREFIX}${chunkCount}`;
|
|
514
|
-
}
|
|
515
|
-
function parseChunkedRootCount(value) {
|
|
516
|
-
if (typeof value !== "string" || !value.startsWith(ROOT_MARKER_PREFIX)) return null;
|
|
517
|
-
const raw = value.slice(ROOT_MARKER_PREFIX.length);
|
|
518
|
-
if (!/^[1-9][0-9]*$/.test(raw)) return null;
|
|
519
|
-
return Number(raw);
|
|
520
|
-
}
|
|
521
|
-
function splitStateValue(value) {
|
|
522
|
-
return _amsgshared.chunkReasoningByUtf8Bytes.call(void 0, value, STATE_CHUNK_SLICE_BYTES);
|
|
523
|
-
}
|
|
524
|
-
async function resolveClientStateEntries(rows, fetchChunkRows, decryptValue) {
|
|
525
|
-
let chunkMap = null;
|
|
526
|
-
const loadChunks = async () => {
|
|
527
|
-
if (chunkMap === null) {
|
|
528
|
-
const chunkRows = await fetchChunkRows();
|
|
529
|
-
chunkMap = new Map(chunkRows.map((row) => [row.key, row]));
|
|
530
|
-
}
|
|
531
|
-
return chunkMap;
|
|
532
|
-
};
|
|
533
|
-
const entries = [];
|
|
534
|
-
for (const row of rows) {
|
|
535
|
-
const count = parseChunkedRootCount(row.value);
|
|
536
|
-
if (count === null) {
|
|
537
|
-
entries.push({
|
|
538
|
-
namespace: row.namespace,
|
|
539
|
-
key: row.key,
|
|
540
|
-
value: await decryptValue(row.value),
|
|
541
|
-
updatedAt: row.updated_at
|
|
542
|
-
});
|
|
543
|
-
continue;
|
|
544
|
-
}
|
|
545
|
-
const map = await loadChunks();
|
|
546
|
-
const chunkRows = [];
|
|
547
|
-
let intact = true;
|
|
548
|
-
for (let i = 0; i < count; i++) {
|
|
549
|
-
const chunk = map.get(chunkKeyFor(row.key, i));
|
|
550
|
-
if (!chunk || chunk.updated_at !== row.updated_at) {
|
|
551
|
-
intact = false;
|
|
552
|
-
break;
|
|
553
|
-
}
|
|
554
|
-
chunkRows.push(chunk);
|
|
555
|
-
}
|
|
556
|
-
if (!intact) continue;
|
|
557
|
-
const parts = await Promise.all(chunkRows.map((chunk) => decryptValue(chunk.value)));
|
|
558
|
-
entries.push({
|
|
559
|
-
namespace: row.namespace,
|
|
560
|
-
key: row.key,
|
|
561
|
-
value: parts.join(""),
|
|
562
|
-
updatedAt: row.updated_at
|
|
563
|
-
});
|
|
564
|
-
}
|
|
565
|
-
return entries;
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
// src/server/lib/client-state-store.js
|
|
569
|
-
var utf82 = new TextEncoder();
|
|
570
|
-
var MAX_STATE_ENTRIES_PER_BATCH = 200;
|
|
571
|
-
var MAX_NAMESPACE_CHARS = 128;
|
|
572
|
-
var MAX_KEY_CHARS = 256;
|
|
573
|
-
function stateValueBytes(value) {
|
|
574
|
-
return utf82.encode(value).length;
|
|
575
|
-
}
|
|
576
|
-
async function writeClientStateEntries({ db, userId, userKey, entries }) {
|
|
577
|
-
const physicalRows = [];
|
|
578
|
-
const cleanups = [];
|
|
579
|
-
const rootRowIndexes = [];
|
|
580
|
-
let deleted = 0;
|
|
581
|
-
for (const entry of entries) {
|
|
582
|
-
cleanups.push({
|
|
583
|
-
namespace: chunkNamespaceFor(entry.namespace),
|
|
584
|
-
keyPrefix: chunkKeyPrefixFor(entry.key),
|
|
585
|
-
updatedAt: entry.updatedAt
|
|
586
|
-
});
|
|
587
|
-
if (entry.value === null) {
|
|
588
|
-
cleanups.push({
|
|
589
|
-
namespace: entry.namespace,
|
|
590
|
-
key: entry.key,
|
|
591
|
-
updatedAt: entry.updatedAt
|
|
592
|
-
});
|
|
593
|
-
deleted++;
|
|
594
|
-
continue;
|
|
595
|
-
}
|
|
596
|
-
rootRowIndexes.push(physicalRows.length);
|
|
597
|
-
if (stateValueBytes(entry.value) <= STATE_CHUNK_SLICE_BYTES) {
|
|
598
|
-
physicalRows.push({
|
|
599
|
-
namespace: entry.namespace,
|
|
600
|
-
key: entry.key,
|
|
601
|
-
value: await encryptForStorage(entry.value, userKey),
|
|
602
|
-
updatedAt: entry.updatedAt
|
|
603
|
-
});
|
|
604
|
-
} else {
|
|
605
|
-
const slices = splitStateValue(entry.value);
|
|
606
|
-
physicalRows.push({
|
|
607
|
-
namespace: entry.namespace,
|
|
608
|
-
key: entry.key,
|
|
609
|
-
value: buildChunkedRootValue(slices.length),
|
|
610
|
-
updatedAt: entry.updatedAt
|
|
611
|
-
});
|
|
612
|
-
const encryptedSlices = await Promise.all(slices.map((slice) => encryptForStorage(slice, userKey)));
|
|
613
|
-
for (let c = 0; c < encryptedSlices.length; c++) {
|
|
614
|
-
physicalRows.push({
|
|
615
|
-
namespace: chunkNamespaceFor(entry.namespace),
|
|
616
|
-
key: chunkKeyFor(entry.key, c),
|
|
617
|
-
value: encryptedSlices[c],
|
|
618
|
-
updatedAt: entry.updatedAt
|
|
619
|
-
});
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
if (physicalRows.length === 0 && cleanups.length === 0) {
|
|
624
|
-
return { upserted: 0, skipped: 0, deleted: 0 };
|
|
625
|
-
}
|
|
626
|
-
const result = await db.upsertClientState(userId, physicalRows, cleanups);
|
|
627
|
-
let upserted = 0;
|
|
628
|
-
let skipped = 0;
|
|
629
|
-
if (Array.isArray(result.outcomes) && result.outcomes.length === physicalRows.length) {
|
|
630
|
-
for (const rootIndex of rootRowIndexes) {
|
|
631
|
-
if (result.outcomes[rootIndex]) upserted++;
|
|
632
|
-
else skipped++;
|
|
633
|
-
}
|
|
634
|
-
} else {
|
|
635
|
-
upserted = result.upserted;
|
|
636
|
-
skipped = result.skipped;
|
|
637
|
-
}
|
|
638
|
-
return { upserted, skipped, deleted };
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
// src/server/lib/agentic-fire.js
|
|
642
|
-
var DEFAULT_MAX_TOOL_ITERATIONS = 5;
|
|
643
|
-
var DEFAULT_TOTAL_TIMEOUT_MS = 24e4;
|
|
644
|
-
var SLEEP_BETWEEN_MESSAGES_MS = 1500;
|
|
645
|
-
var CREDENTIAL_PAYLOAD_KEYS = /* @__PURE__ */ new Set(["apiKey", "pushSubscription"]);
|
|
646
|
-
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
647
|
-
function taskNeedsLlm(decryptedPayload) {
|
|
648
|
-
const type = decryptedPayload.messageType;
|
|
649
|
-
if (type === "prompted" || type === "auto") return true;
|
|
650
|
-
if (type === "instant") {
|
|
651
|
-
return !!(decryptedPayload.apiUrl && decryptedPayload.apiKey && decryptedPayload.primaryModel);
|
|
652
|
-
}
|
|
653
|
-
return false;
|
|
654
|
-
}
|
|
655
|
-
function buildHookTask(task, decryptedPayload) {
|
|
656
|
-
const safe = {};
|
|
657
|
-
for (const [key, value] of Object.entries(decryptedPayload)) {
|
|
658
|
-
if (!CREDENTIAL_PAYLOAD_KEYS.has(key)) safe[key] = value;
|
|
659
|
-
}
|
|
660
|
-
return Object.freeze({
|
|
661
|
-
...safe,
|
|
662
|
-
id: _nullishCoalesce(task.id, () => ( null)),
|
|
663
|
-
uuid: _nullishCoalesce(task.uuid, () => ( null)),
|
|
664
|
-
nextSendAt: _nullishCoalesce(task.next_send_at, () => ( null)),
|
|
665
|
-
retryCount: _nullishCoalesce(task.retry_count, () => ( 0))
|
|
666
|
-
});
|
|
667
|
-
}
|
|
668
|
-
function normalizeBeforeFireResult(result) {
|
|
669
|
-
if (Array.isArray(result)) {
|
|
670
|
-
return { messages: result };
|
|
671
|
-
}
|
|
672
|
-
if (result && typeof result === "object" && Array.isArray(result.messages)) {
|
|
673
|
-
return {
|
|
674
|
-
messages: result.messages,
|
|
675
|
-
maxToolIterations: result.maxToolIterations,
|
|
676
|
-
totalTimeoutMs: result.totalTimeoutMs,
|
|
677
|
-
tools: Array.isArray(result.tools) && result.tools.length > 0 ? result.tools : void 0,
|
|
678
|
-
toolChoice: result.toolChoice
|
|
679
|
-
};
|
|
680
|
-
}
|
|
681
|
-
throw new TypeError(
|
|
682
|
-
"AGENTIC_BAD_BEFORE_FIRE: onBeforeFire must return ChatMessage[] | { messages, maxToolIterations?, totalTimeoutMs?, tools?, toolChoice? } | { skip: true } | null"
|
|
683
|
-
);
|
|
684
|
-
}
|
|
685
|
-
function firstPositiveInt(values, fallback) {
|
|
686
|
-
for (const v of values) {
|
|
687
|
-
if (Number.isInteger(v) && v > 0) return v;
|
|
688
|
-
}
|
|
689
|
-
return fallback;
|
|
690
|
-
}
|
|
691
|
-
function firstPositiveNumber(values, fallback) {
|
|
692
|
-
for (const v of values) {
|
|
693
|
-
if (typeof v === "number" && Number.isFinite(v) && v > 0) return v;
|
|
694
|
-
}
|
|
695
|
-
return fallback;
|
|
696
|
-
}
|
|
697
|
-
async function runAgenticFire({ task, decryptedPayload, userKey, ctx }) {
|
|
698
|
-
const hooks = ctx.hooks;
|
|
699
|
-
if (typeof hooks.onLLMOutput !== "function") {
|
|
700
|
-
throw new Error("AGENTIC_CONFIG_ERROR: hooks.onBeforeFire requires hooks.onLLMOutput to classify LLM rounds");
|
|
701
|
-
}
|
|
702
|
-
const nowFn = typeof ctx._agenticNow === "function" ? ctx._agenticNow : Date.now;
|
|
703
|
-
const sleep = typeof ctx._agenticSleep === "function" ? ctx._agenticSleep : defaultSleep;
|
|
704
|
-
const readState = async (namespace) => {
|
|
705
|
-
if (typeof namespace !== "string" || !namespace.trim()) {
|
|
706
|
-
throw new TypeError("readState(namespace) requires a non-empty string");
|
|
707
|
-
}
|
|
708
|
-
if (!ctx.db || typeof ctx.db.getClientState !== "function") return [];
|
|
709
|
-
const rows = await ctx.db.getClientState(task.user_id, namespace);
|
|
710
|
-
return resolveClientStateEntries(
|
|
711
|
-
rows,
|
|
712
|
-
() => ctx.db.getClientState(task.user_id, chunkNamespaceFor(namespace)),
|
|
713
|
-
(value) => decryptFromStorage(value, userKey)
|
|
714
|
-
);
|
|
715
|
-
};
|
|
716
|
-
const maxStateValueBytes = Number.isInteger(ctx.maxStateValueBytes) && ctx.maxStateValueBytes > 0 ? ctx.maxStateValueBytes : DEFAULT_MAX_STATE_VALUE_BYTES;
|
|
717
|
-
const writeState = async (namespace, entries) => {
|
|
718
|
-
if (typeof namespace !== "string" || !namespace.trim()) {
|
|
719
|
-
throw new TypeError("writeState(namespace, entries) requires a non-empty string namespace");
|
|
720
|
-
}
|
|
721
|
-
if (namespace.length > MAX_NAMESPACE_CHARS || INTERNAL_STATE_CHAR_RE.test(namespace)) {
|
|
722
|
-
throw new TypeError(
|
|
723
|
-
`writeState: namespace \u5FC5\u987B\u662F 1-${MAX_NAMESPACE_CHARS} \u5B57\u7B26\u4E14\u4E0D\u542B\u63A7\u5236\u5B57\u7B26\uFF08\\u0000-\\u001f \u4E3A\u5E93\u5185\u90E8\u4FDD\u7559\uFF09`
|
|
724
|
-
);
|
|
725
|
-
}
|
|
726
|
-
if (!Array.isArray(entries)) {
|
|
727
|
-
throw new TypeError("writeState(namespace, entries) requires an array of { key, value }");
|
|
728
|
-
}
|
|
729
|
-
if (entries.length === 0) return { upserted: 0, skipped: 0, deleted: 0 };
|
|
730
|
-
if (entries.length > MAX_STATE_ENTRIES_PER_BATCH) {
|
|
731
|
-
throw new RangeError(`writeState: \u5355\u6B21\u6700\u591A ${MAX_STATE_ENTRIES_PER_BATCH} \u6761\uFF0C\u6536\u5230 ${entries.length} \u6761`);
|
|
732
|
-
}
|
|
733
|
-
if (!ctx.db || typeof ctx.db.upsertClientState !== "function") {
|
|
734
|
-
throw new Error("AGENTIC_STATE_WRITE_UNSUPPORTED: \u5F53\u524D\u6570\u636E\u5E93\u9002\u914D\u5668\u4E0D\u652F\u6301 client_state \u5199\u5165");
|
|
735
|
-
}
|
|
736
|
-
const now = nowFn();
|
|
737
|
-
const normalized2 = entries.map((entry, index) => {
|
|
738
|
-
if (!entry || typeof entry !== "object") {
|
|
739
|
-
throw new TypeError(`writeState: entries[${index}] \u5FC5\u987B\u662F\u5BF9\u8C61`);
|
|
740
|
-
}
|
|
741
|
-
if (typeof entry.key !== "string" || !entry.key.trim() || entry.key.length > MAX_KEY_CHARS) {
|
|
742
|
-
throw new TypeError(`writeState: entries[${index}].key \u5FC5\u987B\u662F 1-${MAX_KEY_CHARS} \u5B57\u7B26\u7684\u5B57\u7B26\u4E32`);
|
|
743
|
-
}
|
|
744
|
-
if (INTERNAL_STATE_CHAR_RE.test(entry.key)) {
|
|
745
|
-
throw new TypeError(`writeState: entries[${index}].key \u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26\uFF08\\u0000-\\u001f \u4E3A\u5E93\u5185\u90E8\u4FDD\u7559\uFF09`);
|
|
746
|
-
}
|
|
747
|
-
if (entry.value !== null && typeof entry.value !== "string") {
|
|
748
|
-
throw new TypeError(`writeState: entries[${index}].value \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\uFF08\u5BBF\u4E3B\u81EA\u884C\u5E8F\u5217\u5316\uFF09\uFF0C\u6216 null \u8868\u793A\u5220\u9664`);
|
|
749
|
-
}
|
|
750
|
-
if (typeof entry.value === "string") {
|
|
751
|
-
const bytes = stateValueBytes(entry.value);
|
|
752
|
-
if (bytes > maxStateValueBytes) {
|
|
753
|
-
throw new RangeError(`writeState: entries[${index}].value \u4E3A ${bytes} \u5B57\u8282\uFF0C\u8D85\u8FC7\u5355\u6761\u4E0A\u9650 ${maxStateValueBytes} \u5B57\u8282`);
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
if (entry.updatedAt !== void 0 && (!Number.isInteger(entry.updatedAt) || entry.updatedAt <= 0)) {
|
|
757
|
-
throw new TypeError(`writeState: entries[${index}].updatedAt \u5FC5\u987B\u662F\u6B63\u6574\u6570\uFF08epoch \u6BEB\u79D2\uFF09`);
|
|
758
|
-
}
|
|
759
|
-
return {
|
|
760
|
-
namespace,
|
|
761
|
-
key: entry.key,
|
|
762
|
-
value: entry.value,
|
|
763
|
-
updatedAt: _nullishCoalesce(entry.updatedAt, () => ( now))
|
|
764
|
-
};
|
|
765
|
-
});
|
|
766
|
-
return writeClientStateEntries({ db: ctx.db, userId: task.user_id, userKey, entries: normalized2 });
|
|
767
|
-
};
|
|
768
|
-
const scratch = {};
|
|
769
|
-
const fireCtx = Object.freeze({
|
|
770
|
-
task: buildHookTask(task, decryptedPayload),
|
|
771
|
-
userId: task.user_id,
|
|
772
|
-
readState,
|
|
773
|
-
writeState,
|
|
774
|
-
now: new Date(nowFn()),
|
|
775
|
-
scratch
|
|
776
|
-
});
|
|
777
|
-
const before = await hooks.onBeforeFire(fireCtx);
|
|
778
|
-
if (before == null) return { handled: false };
|
|
779
|
-
if (typeof before === "object" && before.skip === true) {
|
|
780
|
-
return { handled: true, result: { success: true, messagesSent: 0, status: "skipped", iterations: 0 } };
|
|
781
|
-
}
|
|
782
|
-
const normalized = normalizeBeforeFireResult(before);
|
|
783
|
-
const maxToolIterations = firstPositiveInt(
|
|
784
|
-
[normalized.maxToolIterations, ctx.maxToolIterations],
|
|
785
|
-
DEFAULT_MAX_TOOL_ITERATIONS
|
|
786
|
-
);
|
|
787
|
-
const totalTimeoutMs = firstPositiveNumber(
|
|
788
|
-
[normalized.totalTimeoutMs, ctx.totalTimeoutMs],
|
|
789
|
-
DEFAULT_TOTAL_TIMEOUT_MS
|
|
790
|
-
);
|
|
791
|
-
const deadline = nowFn() + totalTimeoutMs;
|
|
792
|
-
const sessionId = task.id != null ? `sess_task_${task.id}` : `sess_${randomUUID()}`;
|
|
793
|
-
let messages = normalized.messages.slice();
|
|
794
|
-
for (let iteration = 0; iteration < maxToolIterations; iteration++) {
|
|
795
|
-
if (nowFn() >= deadline) {
|
|
796
|
-
throw new Error(`AGENTIC_TOTAL_TIMEOUT: fire chain exceeded ${totalTimeoutMs}ms after ${iteration} LLM round(s)`);
|
|
797
|
-
}
|
|
798
|
-
const roundTimeoutMs = Math.max(1, Math.min(3e5, deadline - nowFn()));
|
|
799
|
-
const { response: llmResponse } = await callLlm(
|
|
800
|
-
{
|
|
801
|
-
...decryptedPayload,
|
|
802
|
-
messages,
|
|
803
|
-
...normalized.tools ? { tools: normalized.tools, toolChoice: normalized.toolChoice } : {}
|
|
804
|
-
},
|
|
805
|
-
{ requireContent: false, timeoutMs: roundTimeoutMs }
|
|
806
|
-
);
|
|
807
|
-
const assistantMessage = _amsgshared.extractAssistantMessage.call(void 0, llmResponse);
|
|
808
|
-
messages = [...messages, assistantMessage];
|
|
809
|
-
const sessionCtx = Object.freeze({
|
|
810
|
-
..._amsgshared.buildSessionContext.call(void 0, {
|
|
811
|
-
sessionId,
|
|
812
|
-
messages,
|
|
813
|
-
llmResponse,
|
|
814
|
-
iteration,
|
|
815
|
-
contactName: decryptedPayload.contactName,
|
|
816
|
-
avatarUrl: decryptedPayload.avatarUrl || void 0,
|
|
817
|
-
charId: decryptedPayload.charId,
|
|
818
|
-
metadata: decryptedPayload.metadata,
|
|
819
|
-
scratch
|
|
820
|
-
}),
|
|
821
|
-
readState,
|
|
822
|
-
writeState
|
|
823
|
-
});
|
|
824
|
-
const decision = await hooks.onLLMOutput(sessionCtx);
|
|
825
|
-
_amsgshared.assertValidDecision.call(void 0, decision, { inlineToolCalls: true });
|
|
826
|
-
if (decision.decision === "continue") {
|
|
827
|
-
messages = decision.nextHistory.slice();
|
|
828
|
-
continue;
|
|
829
|
-
}
|
|
830
|
-
if (decision.decision === "skip-push") {
|
|
831
|
-
return { handled: true, result: { success: true, messagesSent: 0, status: "skipped", iterations: iteration + 1 } };
|
|
832
|
-
}
|
|
833
|
-
if (decision.decision === "finish") {
|
|
834
|
-
const messagesSent = await sendHookPushPayloads(decision.pushPayloads, decryptedPayload, ctx, sessionId, task, sleep);
|
|
835
|
-
return { handled: true, result: { success: true, messagesSent, status: "finished", iterations: iteration + 1 } };
|
|
836
|
-
}
|
|
837
|
-
const toolCalls = _amsgshared.extractToolCallsFromDecision.call(void 0, decision);
|
|
838
|
-
if (toolCalls.length === 0) {
|
|
839
|
-
throw new Error("AGENTIC_EMPTY_TOOL_REQUEST: tool-request decision carried no toolCalls (neither decision.toolCalls nor pushPayloads[].toolCalls)");
|
|
840
|
-
}
|
|
841
|
-
if (typeof hooks.executeToolCalls !== "function") {
|
|
842
|
-
throw new Error("AGENTIC_CONFIG_ERROR: onLLMOutput returned tool-request but hooks.executeToolCalls is not configured");
|
|
843
|
-
}
|
|
844
|
-
if (iteration === maxToolIterations - 1) {
|
|
845
|
-
break;
|
|
846
|
-
}
|
|
847
|
-
let toolResults;
|
|
848
|
-
try {
|
|
849
|
-
toolResults = await hooks.executeToolCalls(toolCalls, sessionCtx);
|
|
850
|
-
if (!Array.isArray(toolResults)) {
|
|
851
|
-
throw new TypeError('executeToolCalls must resolve to an array of { tool_call_id, role: "tool", content }');
|
|
852
|
-
}
|
|
853
|
-
} catch (error) {
|
|
854
|
-
toolResults = toolCalls.map((toolCall) => ({
|
|
855
|
-
tool_call_id: toolCall && typeof toolCall === "object" && typeof toolCall.id === "string" ? toolCall.id : "",
|
|
856
|
-
role: "tool",
|
|
857
|
-
content: `Tool execution failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _6 => _6.message]), () => ( String(error)))}`
|
|
858
|
-
}));
|
|
859
|
-
}
|
|
860
|
-
const nativeCalls = Array.isArray(assistantMessage.tool_calls) ? assistantMessage.tool_calls : [];
|
|
861
|
-
const nativeIds = new Set(nativeCalls.map((tc) => tc && tc.id));
|
|
862
|
-
const synthesized = toolCalls.filter((tc) => !nativeIds.has(tc && tc.id));
|
|
863
|
-
const assistantWithTools = synthesized.length === 0 ? assistantMessage : { ...assistantMessage, tool_calls: [...nativeCalls, ...synthesized] };
|
|
864
|
-
messages = [...messages.slice(0, -1), assistantWithTools, ...toolResults];
|
|
865
|
-
}
|
|
866
|
-
throw new Error(`AGENTIC_LOOP_EXCEEDED: no finish/skip-push decision within ${maxToolIterations} LLM round(s)`);
|
|
867
|
-
}
|
|
868
|
-
async function sendHookPushPayloads(pushPayloads, decryptedPayload, ctx, sessionId, task, sleep) {
|
|
869
|
-
if (!ctx.vapid || !ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
|
|
870
|
-
throw new Error("VAPID configuration missing - push notifications cannot be sent");
|
|
871
|
-
}
|
|
872
|
-
const pushSubscription = decryptedPayload.pushSubscription;
|
|
873
|
-
const total = pushPayloads.length;
|
|
874
|
-
const messageIdBase = task.id != null ? `msg_task_${task.id}` : `msg_${randomUUID()}`;
|
|
875
|
-
for (let i = 0; i < total; i++) {
|
|
876
|
-
const push = { ...pushPayloads[i] };
|
|
877
|
-
if (typeof push.messageId !== "string" || !push.messageId) push.messageId = `${messageIdBase}_hook_${i}`;
|
|
878
|
-
if (typeof push.sessionId !== "string" || !push.sessionId) push.sessionId = sessionId;
|
|
879
|
-
if (typeof push.timestamp !== "string" || !push.timestamp) push.timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
880
|
-
push.messageIndex = i + 1;
|
|
881
|
-
push.totalMessages = total;
|
|
882
|
-
await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(push));
|
|
883
|
-
if (i < total - 1) await sleep(SLEEP_BETWEEN_MESSAGES_MS);
|
|
884
|
-
}
|
|
885
|
-
return total;
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
// src/server/lib/message-processor.js
|
|
889
|
-
var DEFAULT_SPLIT_REGEX = /([。!?!?]+)/;
|
|
890
|
-
var SLEEP_BETWEEN_MESSAGES_MS2 = 1500;
|
|
891
|
-
function splitOnceByRegex(chunk, regex) {
|
|
892
|
-
const out = chunk.split(regex).reduce((acc, part, i, arr) => {
|
|
893
|
-
if (i % 2 === 0 && part.trim()) {
|
|
894
|
-
const punctuation = arr[i + 1] || "";
|
|
895
|
-
acc.push(part.trim() + punctuation);
|
|
896
|
-
}
|
|
897
|
-
return acc;
|
|
898
|
-
}, []).filter((s) => s.length > 0);
|
|
899
|
-
return out.length > 0 ? out : [chunk];
|
|
900
|
-
}
|
|
901
|
-
function splitMessageIntoSentences(messageContent, splitPattern = null) {
|
|
902
|
-
const sources = splitPattern == null ? null : Array.isArray(splitPattern) ? splitPattern : [splitPattern];
|
|
903
|
-
const regexes = sources && sources.length > 0 ? sources.map((s) => new RegExp(s)) : [DEFAULT_SPLIT_REGEX];
|
|
904
|
-
let chunks = [messageContent];
|
|
905
|
-
for (const regex of regexes) {
|
|
906
|
-
chunks = chunks.flatMap((c) => splitOnceByRegex(c, regex));
|
|
907
|
-
}
|
|
908
|
-
return chunks.length > 0 ? chunks : [messageContent];
|
|
909
|
-
}
|
|
910
|
-
async function processSingleMessage(task, ctx, providedMasterKey) {
|
|
911
|
-
try {
|
|
912
|
-
const masterKey = providedMasterKey || ctx.masterKey;
|
|
913
|
-
if (!masterKey) {
|
|
914
|
-
return { success: false, messagesSent: 0, error: "TENANT_MASTER_KEY_MISSING" };
|
|
915
|
-
}
|
|
916
|
-
const userKey = await deriveUserEncryptionKey(task.user_id, masterKey);
|
|
917
|
-
const decryptedPayload = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
|
|
918
|
-
if (ctx.hooks && typeof ctx.hooks.onBeforeFire === "function" && taskNeedsLlm(decryptedPayload)) {
|
|
919
|
-
const agentic = await runAgenticFire({ task, decryptedPayload, userKey, ctx });
|
|
920
|
-
if (agentic.handled) return agentic.result;
|
|
921
|
-
}
|
|
922
|
-
let messageContent;
|
|
923
|
-
let llmResponse = null;
|
|
924
|
-
if (decryptedPayload.messageType === "fixed") {
|
|
925
|
-
messageContent = decryptedPayload.userMessage;
|
|
926
|
-
} else if (decryptedPayload.messageType === "instant") {
|
|
927
|
-
const hasPrompt = !!decryptedPayload.completePrompt || Array.isArray(decryptedPayload.messages) && decryptedPayload.messages.length > 0;
|
|
928
|
-
if (hasPrompt && decryptedPayload.apiUrl && decryptedPayload.apiKey && decryptedPayload.primaryModel) {
|
|
929
|
-
const aiResult = await callLlm(decryptedPayload);
|
|
930
|
-
messageContent = aiResult.content;
|
|
931
|
-
llmResponse = aiResult.response;
|
|
932
|
-
} else if (decryptedPayload.userMessage) {
|
|
933
|
-
messageContent = decryptedPayload.userMessage;
|
|
934
|
-
} else {
|
|
935
|
-
throw new Error("Invalid instant message: no content source available");
|
|
936
|
-
}
|
|
937
|
-
} else if (decryptedPayload.messageType === "prompted" || decryptedPayload.messageType === "auto") {
|
|
938
|
-
const aiResult = await callLlm(decryptedPayload);
|
|
939
|
-
messageContent = aiResult.content;
|
|
940
|
-
llmResponse = aiResult.response;
|
|
941
|
-
} else {
|
|
942
|
-
throw new Error("Invalid message configuration: no content source available");
|
|
943
|
-
}
|
|
944
|
-
const reasoning = _amsgshared.readReasoningContent.call(void 0, llmResponse);
|
|
945
|
-
if (reasoning) {
|
|
946
|
-
messageContent = _amsgshared.stripReasoningTags.call(void 0, messageContent);
|
|
947
|
-
}
|
|
948
|
-
const messages = splitMessageIntoSentences(messageContent, _nullishCoalesce(decryptedPayload.splitPattern, () => ( null)));
|
|
949
|
-
if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
|
|
950
|
-
throw new Error("VAPID configuration missing - push notifications cannot be sent");
|
|
951
|
-
}
|
|
952
|
-
const pushSubscription = decryptedPayload.pushSubscription;
|
|
953
|
-
const sessionId = task.id != null ? `sess_task_${task.id}` : `sess_${randomUUID()}`;
|
|
954
|
-
const source = decryptedPayload.messageType === "instant" ? "instant" : "scheduled";
|
|
955
|
-
const messageSubtype = decryptedPayload.messageSubtype || "chat";
|
|
956
|
-
const avatarUrl = decryptedPayload.avatarUrl || null;
|
|
957
|
-
const metadata = decryptedPayload.metadata || {};
|
|
958
|
-
const messageIdBase = task.id != null ? `msg_task_${task.id}` : `msg_${randomUUID()}_instant`;
|
|
959
|
-
if (reasoning) {
|
|
960
|
-
const reasoningPush = _amsgshared.buildReasoningPush.call(void 0, {
|
|
961
|
-
messageType: decryptedPayload.messageType,
|
|
962
|
-
source,
|
|
963
|
-
messageId: `${messageIdBase}_reasoning`,
|
|
964
|
-
sessionId,
|
|
965
|
-
reasoningContent: reasoning,
|
|
966
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
967
|
-
title: `\u6765\u81EA ${decryptedPayload.contactName}`,
|
|
968
|
-
contactName: decryptedPayload.contactName,
|
|
969
|
-
avatarUrl,
|
|
970
|
-
messageSubtype,
|
|
971
|
-
metadata
|
|
972
|
-
});
|
|
973
|
-
await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(reasoningPush));
|
|
974
|
-
await new Promise((resolve) => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS2));
|
|
975
|
-
}
|
|
976
|
-
for (let i = 0; i < messages.length; i++) {
|
|
977
|
-
const contentPush = _amsgshared.buildContentPush.call(void 0, {
|
|
978
|
-
messageType: decryptedPayload.messageType,
|
|
979
|
-
source,
|
|
980
|
-
messageId: `${messageIdBase}_${i}`,
|
|
981
|
-
sessionId,
|
|
982
|
-
message: messages[i],
|
|
983
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
984
|
-
title: `\u6765\u81EA ${decryptedPayload.contactName}`,
|
|
985
|
-
contactName: decryptedPayload.contactName,
|
|
986
|
-
avatarUrl,
|
|
987
|
-
messageSubtype,
|
|
988
|
-
messageIndex: i + 1,
|
|
989
|
-
totalMessages: messages.length,
|
|
990
|
-
taskId: task.id || null,
|
|
991
|
-
metadata
|
|
992
|
-
});
|
|
993
|
-
await ctx.webpush.sendNotification(pushSubscription, JSON.stringify(contentPush));
|
|
994
|
-
if (i < messages.length - 1) {
|
|
995
|
-
await new Promise((resolve) => setTimeout(resolve, SLEEP_BETWEEN_MESSAGES_MS2));
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
return { success: true, messagesSent: messages.length };
|
|
999
|
-
} catch (error) {
|
|
1000
|
-
return { success: false, messagesSent: 0, error: error.message };
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
async function processMessagesByUuid(uuid, ctx, maxRetries = 2, userId, providedMasterKey) {
|
|
1004
|
-
let retryCount = 0;
|
|
1005
|
-
const masterKey = providedMasterKey || ctx.masterKey;
|
|
1006
|
-
if (!masterKey) {
|
|
1007
|
-
return {
|
|
1008
|
-
success: false,
|
|
1009
|
-
error: { code: "TENANT_MASTER_KEY_MISSING", message: "\u79DF\u6237\u4E3B\u5BC6\u94A5\u4E0D\u5B58\u5728\u6216\u914D\u7F6E\u5F02\u5E38" }
|
|
1010
|
-
};
|
|
1011
|
-
}
|
|
1012
|
-
while (retryCount <= maxRetries) {
|
|
1013
|
-
let task;
|
|
1014
|
-
try {
|
|
1015
|
-
task = userId ? await ctx.db.getTaskByUuid(uuid, userId) : await ctx.db.getTaskByUuidOnly(uuid);
|
|
1016
|
-
} catch (error) {
|
|
1017
|
-
if (retryCount < maxRetries) {
|
|
1018
|
-
retryCount++;
|
|
1019
|
-
await new Promise((resolve) => setTimeout(resolve, 1e3 * retryCount));
|
|
1020
|
-
continue;
|
|
1021
|
-
}
|
|
1022
|
-
return {
|
|
1023
|
-
success: false,
|
|
1024
|
-
error: { code: "INTERNAL_ERROR", message: error.message, retriesAttempted: retryCount }
|
|
1025
|
-
};
|
|
1026
|
-
}
|
|
1027
|
-
if (!task) {
|
|
1028
|
-
return { success: false, error: { code: "TASK_NOT_FOUND", message: "\u4EFB\u52A1\u4E0D\u5B58\u5728\u6216\u5DF2\u5904\u7406" } };
|
|
1029
|
-
}
|
|
1030
|
-
const result = await processSingleMessage(task, ctx, masterKey);
|
|
1031
|
-
if (!result.success) {
|
|
1032
|
-
if (retryCount < maxRetries) {
|
|
1033
|
-
retryCount++;
|
|
1034
|
-
await new Promise((resolve) => setTimeout(resolve, 1e3 * retryCount));
|
|
1035
|
-
continue;
|
|
1036
|
-
}
|
|
1037
|
-
try {
|
|
1038
|
-
await ctx.db.updateTaskById(task.id, { status: "failed", retry_count: retryCount });
|
|
1039
|
-
} catch (_updateError) {
|
|
1040
|
-
}
|
|
1041
|
-
return {
|
|
1042
|
-
success: false,
|
|
1043
|
-
error: { code: "PROCESSING_ERROR", message: result.error, retriesAttempted: retryCount }
|
|
1044
|
-
};
|
|
1045
|
-
}
|
|
1046
|
-
try {
|
|
1047
|
-
await ctx.db.deleteTaskById(task.id);
|
|
1048
|
-
} catch (error) {
|
|
1049
|
-
try {
|
|
1050
|
-
await ctx.db.updateTaskById(task.id, { status: "sent", retry_count: 0 });
|
|
1051
|
-
} catch (_markSentError) {
|
|
1052
|
-
}
|
|
1053
|
-
return {
|
|
1054
|
-
success: false,
|
|
1055
|
-
error: {
|
|
1056
|
-
code: "POST_SEND_CLEANUP_FAILED",
|
|
1057
|
-
message: "\u6D88\u606F\u5DF2\u53D1\u9001\uFF0C\u4F46\u4EFB\u52A1\u6E05\u7406\u5931\u8D25",
|
|
1058
|
-
details: { error: error.message }
|
|
1059
|
-
}
|
|
1060
|
-
};
|
|
1061
|
-
}
|
|
1062
|
-
return { success: true, messagesSent: result.messagesSent, retriesUsed: retryCount };
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
// src/server/handlers/schedule-message.js
|
|
1067
|
-
function createScheduleMessageHandler(ctx) {
|
|
1068
|
-
async function POST(headers, body) {
|
|
1069
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers);
|
|
1070
|
-
if (!tenantResult.ok) {
|
|
1071
|
-
return tenantResult.error;
|
|
1072
|
-
}
|
|
1073
|
-
const tenantCtx = tenantResult.context;
|
|
1074
|
-
const db = tenantCtx.db;
|
|
1075
|
-
const masterKey = tenantCtx.masterKey;
|
|
1076
|
-
const isEncrypted = getHeader(headers, "x-payload-encrypted") === "true";
|
|
1077
|
-
const encryptionVersion = getHeader(headers, "x-encryption-version");
|
|
1078
|
-
const userId = getHeader(headers, "x-user-id");
|
|
1079
|
-
if (!isEncrypted) {
|
|
1080
|
-
return { status: 400, body: { success: false, error: { code: "ENCRYPTION_REQUIRED", message: "\u8BF7\u6C42\u4F53\u5FC5\u987B\u52A0\u5BC6" } } };
|
|
1081
|
-
}
|
|
1082
|
-
if (!userId) {
|
|
1083
|
-
return { status: 400, body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } } };
|
|
1084
|
-
}
|
|
1085
|
-
if (!isValidUUIDv4(userId)) {
|
|
1086
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } } };
|
|
1087
|
-
}
|
|
1088
|
-
if (encryptionVersion !== "1") {
|
|
1089
|
-
return { status: 400, body: { success: false, error: { code: "UNSUPPORTED_ENCRYPTION_VERSION", message: "\u52A0\u5BC6\u7248\u672C\u4E0D\u652F\u6301" } } };
|
|
1090
|
-
}
|
|
1091
|
-
const parsedBody = parseEncryptedBody(body);
|
|
1092
|
-
if (!parsedBody.ok) {
|
|
1093
|
-
return { status: 400, body: { success: false, error: parsedBody.error } };
|
|
1094
|
-
}
|
|
1095
|
-
const encryptedBody = parsedBody.data;
|
|
1096
|
-
const userKey = await deriveUserEncryptionKey(userId, masterKey);
|
|
1097
|
-
let payload;
|
|
1098
|
-
try {
|
|
1099
|
-
payload = await decryptPayload(encryptedBody, userKey);
|
|
1100
|
-
} catch (error) {
|
|
1101
|
-
if (error instanceof SyntaxError) {
|
|
1102
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_PAYLOAD_FORMAT", message: "\u89E3\u5BC6\u540E\u7684\u6570\u636E\u4E0D\u662F\u6709\u6548 JSON" } } };
|
|
1103
|
-
}
|
|
1104
|
-
const message = typeof error.message === "string" ? error.message : "";
|
|
1105
|
-
if (message.includes("auth") || message.includes("Unsupported state")) {
|
|
1106
|
-
return { status: 400, body: { success: false, error: { code: "DECRYPTION_FAILED", message: "\u8BF7\u6C42\u4F53\u89E3\u5BC6\u5931\u8D25" } } };
|
|
1107
|
-
}
|
|
1108
|
-
return { status: 400, body: { success: false, error: { code: "DECRYPTION_FAILED", message: "\u8BF7\u6C42\u4F53\u89E3\u5BC6\u5931\u8D25" } } };
|
|
1109
|
-
}
|
|
1110
|
-
if (!isPlainObject(payload)) {
|
|
1111
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_PAYLOAD_FORMAT", message: "\u89E3\u5BC6\u540E\u7684\u6570\u636E\u5FC5\u987B\u662F JSON \u5BF9\u8C61" } } };
|
|
1112
|
-
}
|
|
1113
|
-
const validationResult = validateScheduleMessagePayload(payload);
|
|
1114
|
-
if (!validationResult.valid) {
|
|
1115
|
-
return { status: 400, body: { success: false, error: { code: validationResult.errorCode, message: validationResult.errorMessage, details: validationResult.details } } };
|
|
1116
|
-
}
|
|
1117
|
-
const taskUuid = payload.uuid || randomUUID();
|
|
1118
|
-
const fullTaskData = {
|
|
1119
|
-
contactName: payload.contactName,
|
|
1120
|
-
avatarUrl: payload.avatarUrl || null,
|
|
1121
|
-
messageType: payload.messageType,
|
|
1122
|
-
messageSubtype: payload.messageSubtype || "chat",
|
|
1123
|
-
userMessage: payload.userMessage || null,
|
|
1124
|
-
firstSendTime: payload.firstSendTime,
|
|
1125
|
-
recurrenceType: payload.recurrenceType || "none",
|
|
1126
|
-
apiUrl: payload.apiUrl || null,
|
|
1127
|
-
apiKey: payload.apiKey || null,
|
|
1128
|
-
primaryModel: payload.primaryModel || null,
|
|
1129
|
-
// Prompt is one-of: legacy completePrompt (string) OR messages (OpenAI-
|
|
1130
|
-
// style array). Validation has already enforced exactly-one-of, so
|
|
1131
|
-
// exactly one of these will be non-null when an AI config is provided.
|
|
1132
|
-
completePrompt: payload.completePrompt || null,
|
|
1133
|
-
messages: Array.isArray(payload.messages) ? payload.messages : null,
|
|
1134
|
-
maxTokens: _nullishCoalesce(payload.maxTokens, () => ( null)),
|
|
1135
|
-
temperature: _nullishCoalesce(payload.temperature, () => ( null)),
|
|
1136
|
-
// 0.6.0+: optional caller-provided regex (string or string[]) used by
|
|
1137
|
-
// the message processor to chunk LLM output into individual pushes.
|
|
1138
|
-
// null → processor falls back to the default /([。!?!?]+)/ regex.
|
|
1139
|
-
splitPattern: _nullishCoalesce(payload.splitPattern, () => ( null)),
|
|
1140
|
-
pushSubscription: payload.pushSubscription,
|
|
1141
|
-
metadata: payload.metadata || {}
|
|
1142
|
-
};
|
|
1143
|
-
const encryptedPayload = await encryptForStorage(JSON.stringify(fullTaskData), userKey);
|
|
1144
|
-
if (payload.messageType === "instant") {
|
|
1145
|
-
if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
|
|
1146
|
-
return {
|
|
1147
|
-
status: 500,
|
|
1148
|
-
body: {
|
|
1149
|
-
success: false,
|
|
1150
|
-
error: {
|
|
1151
|
-
code: "VAPID_CONFIG_ERROR",
|
|
1152
|
-
message: "VAPID \u914D\u7F6E\u7F3A\u5931\uFF0C\u65E0\u6CD5\u53D1\u9001\u5373\u65F6\u6D88\u606F",
|
|
1153
|
-
details: {
|
|
1154
|
-
missingKeys: [
|
|
1155
|
-
!ctx.vapid.email && "VAPID_EMAIL",
|
|
1156
|
-
!ctx.vapid.publicKey && "NEXT_PUBLIC_VAPID_PUBLIC_KEY",
|
|
1157
|
-
!ctx.vapid.privateKey && "VAPID_PRIVATE_KEY"
|
|
1158
|
-
].filter(Boolean)
|
|
1159
|
-
}
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
};
|
|
1163
|
-
}
|
|
1164
|
-
}
|
|
1165
|
-
let dbResult;
|
|
1166
|
-
try {
|
|
1167
|
-
dbResult = await db.createTask({
|
|
1168
|
-
user_id: userId,
|
|
1169
|
-
uuid: taskUuid,
|
|
1170
|
-
encrypted_payload: encryptedPayload,
|
|
1171
|
-
next_send_at: payload.firstSendTime,
|
|
1172
|
-
message_type: payload.messageType
|
|
1173
|
-
});
|
|
1174
|
-
} catch (error) {
|
|
1175
|
-
if (isUniqueViolation(error)) {
|
|
1176
|
-
return {
|
|
1177
|
-
status: 409,
|
|
1178
|
-
body: {
|
|
1179
|
-
success: false,
|
|
1180
|
-
error: {
|
|
1181
|
-
code: "TASK_UUID_CONFLICT",
|
|
1182
|
-
message: "\u4EFB\u52A1 UUID \u5DF2\u5B58\u5728\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7684 uuid \u91CD\u65B0\u63D0\u4EA4"
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
};
|
|
1186
|
-
}
|
|
1187
|
-
throw error;
|
|
1188
|
-
}
|
|
1189
|
-
if (!dbResult) {
|
|
1190
|
-
return { status: 500, body: { success: false, error: { code: "TASK_CREATE_FAILED", message: "\u521B\u5EFA\u4EFB\u52A1\u5931\u8D25" } } };
|
|
1191
|
-
}
|
|
1192
|
-
if (payload.messageType === "instant") {
|
|
1193
|
-
try {
|
|
1194
|
-
const sendResult = await processMessagesByUuid(taskUuid, {
|
|
1195
|
-
...ctx,
|
|
1196
|
-
db,
|
|
1197
|
-
masterKey
|
|
1198
|
-
}, 2, userId, masterKey);
|
|
1199
|
-
if (!sendResult.success) {
|
|
1200
|
-
return { status: 500, body: { success: false, error: { code: "MESSAGE_SEND_FAILED", message: "\u6D88\u606F\u53D1\u9001\u5931\u8D25", details: sendResult.error } } };
|
|
1201
|
-
}
|
|
1202
|
-
return {
|
|
1203
|
-
status: 200,
|
|
1204
|
-
body: {
|
|
1205
|
-
success: true,
|
|
1206
|
-
data: {
|
|
1207
|
-
uuid: taskUuid,
|
|
1208
|
-
contactName: payload.contactName,
|
|
1209
|
-
messagesSent: sendResult.messagesSent,
|
|
1210
|
-
sentAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1211
|
-
status: "sent",
|
|
1212
|
-
retriesUsed: sendResult.retriesUsed || 0
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
};
|
|
1216
|
-
} catch (error) {
|
|
1217
|
-
return { status: 500, body: { success: false, error: { code: "MESSAGE_SEND_FAILED", message: "\u6D88\u606F\u53D1\u9001\u5931\u8D25", details: { error: error.message } } } };
|
|
1218
|
-
}
|
|
1219
|
-
}
|
|
1220
|
-
return {
|
|
1221
|
-
status: 201,
|
|
1222
|
-
body: {
|
|
1223
|
-
success: true,
|
|
1224
|
-
data: {
|
|
1225
|
-
id: dbResult.id,
|
|
1226
|
-
uuid: dbResult.uuid,
|
|
1227
|
-
contactName: payload.contactName,
|
|
1228
|
-
nextSendAt: dbResult.next_send_at,
|
|
1229
|
-
status: dbResult.status,
|
|
1230
|
-
createdAt: dbResult.created_at
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
};
|
|
1234
|
-
}
|
|
1235
|
-
return { POST };
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
// src/server/lib/run-tick.js
|
|
1239
|
-
var DEFAULT_CLAIM_LEASE_MS = 10 * 60 * 1e3;
|
|
1240
|
-
var CLAIM_LEASE_MARGIN_MS = 2 * 60 * 1e3;
|
|
1241
|
-
function positiveNumber(value) {
|
|
1242
|
-
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
|
|
1243
|
-
}
|
|
1244
|
-
function resolveClaimLeaseMs(ctx) {
|
|
1245
|
-
return positiveNumber(ctx.claimLeaseMs) || Math.max(DEFAULT_CLAIM_LEASE_MS, positiveNumber(ctx.totalTimeoutMs) + CLAIM_LEASE_MARGIN_MS);
|
|
1246
|
-
}
|
|
1247
|
-
async function runScheduledTick(ctx) {
|
|
1248
|
-
const db = ctx.db;
|
|
1249
|
-
const masterKey = ctx.masterKey;
|
|
1250
|
-
const claimLeaseMs = resolveClaimLeaseMs(ctx);
|
|
1251
|
-
const startTime = Date.now();
|
|
1252
|
-
const tasks = await db.getPendingTasks(50);
|
|
1253
|
-
const MAX_CONCURRENT = 8;
|
|
1254
|
-
const results = {
|
|
1255
|
-
totalTasks: tasks.length,
|
|
1256
|
-
successCount: 0,
|
|
1257
|
-
failedCount: 0,
|
|
1258
|
-
claimSkippedTasks: 0,
|
|
1259
|
-
deletedOnceOffTasks: 0,
|
|
1260
|
-
updatedRecurringTasks: 0,
|
|
1261
|
-
failedTasks: []
|
|
1262
|
-
};
|
|
1263
|
-
const supportsClaim = typeof db.claimTask === "function";
|
|
1264
|
-
async function claimForThisTick(task) {
|
|
1265
|
-
if (!supportsClaim) return true;
|
|
1266
|
-
const leaseUntil = new Date(Date.now() + claimLeaseMs).toISOString();
|
|
1267
|
-
return !!await db.claimTask(task.id, task.next_send_at, leaseUntil);
|
|
1268
|
-
}
|
|
1269
|
-
async function updateAndRelease(taskId, fields) {
|
|
1270
|
-
return db.updateTaskById(taskId, supportsClaim ? { ...fields, lease_until: null } : fields);
|
|
1271
|
-
}
|
|
1272
|
-
async function handleDeliveryFailure(task, reason) {
|
|
1273
|
-
results.failedCount++;
|
|
1274
|
-
try {
|
|
1275
|
-
if (task.retry_count >= 3) {
|
|
1276
|
-
await updateAndRelease(task.id, { status: "failed" });
|
|
1277
|
-
results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count, status: "permanently_failed" });
|
|
1278
|
-
} else {
|
|
1279
|
-
const nextRetryTime = new Date(Date.now() + (task.retry_count + 1) * 2 * 60 * 1e3);
|
|
1280
|
-
await updateAndRelease(task.id, { next_send_at: nextRetryTime.toISOString(), retry_count: task.retry_count + 1 });
|
|
1281
|
-
results.failedTasks.push({ taskId: task.id, reason, retryCount: task.retry_count + 1, nextRetryAt: nextRetryTime.toISOString() });
|
|
1282
|
-
}
|
|
1283
|
-
} catch (updateError) {
|
|
1284
|
-
results.failedTasks.push({ taskId: task.id, reason, status: "retry_update_failed", updateError: updateError.message });
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
async function handlePostSendPersistenceFailure(task, reason) {
|
|
1288
|
-
results.failedCount++;
|
|
1289
|
-
let markedSent = false;
|
|
1290
|
-
try {
|
|
1291
|
-
await updateAndRelease(task.id, { status: "sent", retry_count: 0 });
|
|
1292
|
-
markedSent = true;
|
|
1293
|
-
} catch (_markSentError) {
|
|
1294
|
-
markedSent = false;
|
|
1295
|
-
}
|
|
1296
|
-
results.failedTasks.push({
|
|
1297
|
-
taskId: task.id,
|
|
1298
|
-
reason,
|
|
1299
|
-
status: markedSent ? "post_send_cleanup_failed_marked_sent" : "post_send_cleanup_failed",
|
|
1300
|
-
messageDelivered: true
|
|
1301
|
-
});
|
|
1302
|
-
}
|
|
1303
|
-
async function processTask(task) {
|
|
1304
|
-
let claimed;
|
|
1305
|
-
try {
|
|
1306
|
-
claimed = await claimForThisTick(task);
|
|
1307
|
-
} catch (error) {
|
|
1308
|
-
results.failedCount++;
|
|
1309
|
-
results.failedTasks.push({ taskId: task.id, reason: error.message || "\u4EFB\u52A1\u5360\u4F4D\u5931\u8D25", status: "claim_failed" });
|
|
1310
|
-
return;
|
|
1311
|
-
}
|
|
1312
|
-
if (!claimed) {
|
|
1313
|
-
results.claimSkippedTasks++;
|
|
1314
|
-
return;
|
|
1315
|
-
}
|
|
1316
|
-
let sendResult;
|
|
1317
|
-
try {
|
|
1318
|
-
sendResult = await processSingleMessage(task, { ...ctx, db, masterKey }, masterKey);
|
|
1319
|
-
} catch (error) {
|
|
1320
|
-
await handleDeliveryFailure(task, error.message || "\u6D88\u606F\u53D1\u9001\u5931\u8D25");
|
|
1321
|
-
return;
|
|
1322
|
-
}
|
|
1323
|
-
if (!sendResult.success) {
|
|
1324
|
-
await handleDeliveryFailure(task, sendResult.error || "\u6D88\u606F\u53D1\u9001\u5931\u8D25");
|
|
1325
|
-
return;
|
|
1326
|
-
}
|
|
1327
|
-
try {
|
|
1328
|
-
const userKey = await deriveUserEncryptionKey(task.user_id, masterKey);
|
|
1329
|
-
const decryptedPayload = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
|
|
1330
|
-
if (decryptedPayload.recurrenceType === "none") {
|
|
1331
|
-
await db.deleteTaskById(task.id);
|
|
1332
|
-
results.deletedOnceOffTasks++;
|
|
1333
|
-
} else {
|
|
1334
|
-
let nextSendAt;
|
|
1335
|
-
const currentSendAt = new Date(task.next_send_at);
|
|
1336
|
-
if (decryptedPayload.recurrenceType === "daily") {
|
|
1337
|
-
nextSendAt = new Date(currentSendAt.getTime() + 24 * 60 * 60 * 1e3);
|
|
1338
|
-
} else if (decryptedPayload.recurrenceType === "weekly") {
|
|
1339
|
-
nextSendAt = new Date(currentSendAt.getTime() + 7 * 24 * 60 * 60 * 1e3);
|
|
1340
|
-
}
|
|
1341
|
-
await updateAndRelease(task.id, { next_send_at: nextSendAt.toISOString(), retry_count: 0 });
|
|
1342
|
-
results.updatedRecurringTasks++;
|
|
1343
|
-
}
|
|
1344
|
-
results.successCount++;
|
|
1345
|
-
} catch (error) {
|
|
1346
|
-
await handlePostSendPersistenceFailure(task, error.message || "\u53D1\u9001\u540E\u72B6\u6001\u66F4\u65B0\u5931\u8D25");
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
const taskQueue = [...tasks];
|
|
1350
|
-
const processing = [];
|
|
1351
|
-
while (taskQueue.length > 0 || processing.length > 0) {
|
|
1352
|
-
while (processing.length < MAX_CONCURRENT && taskQueue.length > 0) {
|
|
1353
|
-
const task = taskQueue.shift();
|
|
1354
|
-
const promise = processTask(task);
|
|
1355
|
-
processing.push(promise);
|
|
1356
|
-
promise.finally(() => {
|
|
1357
|
-
const index = processing.indexOf(promise);
|
|
1358
|
-
if (index > -1) processing.splice(index, 1);
|
|
1359
|
-
});
|
|
1360
|
-
}
|
|
1361
|
-
if (processing.length > 0) {
|
|
1362
|
-
await Promise.race(processing);
|
|
1363
|
-
}
|
|
1364
|
-
}
|
|
1365
|
-
await db.cleanupOldTasks(7);
|
|
1366
|
-
const executionTime = Date.now() - startTime;
|
|
1367
|
-
return {
|
|
1368
|
-
totalTasks: results.totalTasks,
|
|
1369
|
-
successCount: results.successCount,
|
|
1370
|
-
failedCount: results.failedCount,
|
|
1371
|
-
processedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1372
|
-
executionTime,
|
|
1373
|
-
details: {
|
|
1374
|
-
claimSkippedTasks: results.claimSkippedTasks,
|
|
1375
|
-
deletedOnceOffTasks: results.deletedOnceOffTasks,
|
|
1376
|
-
updatedRecurringTasks: results.updatedRecurringTasks,
|
|
1377
|
-
failedTasks: results.failedTasks
|
|
1378
|
-
}
|
|
1379
|
-
};
|
|
1380
|
-
}
|
|
1381
|
-
|
|
1382
|
-
// src/server/handlers/update-message.js
|
|
1383
|
-
function createUpdateMessageHandler(ctx) {
|
|
1384
|
-
async function PUT(url, headers, body) {
|
|
1385
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
|
|
1386
|
-
if (!tenantResult.ok) {
|
|
1387
|
-
return tenantResult.error;
|
|
1388
|
-
}
|
|
1389
|
-
const tenantCtx = tenantResult.context;
|
|
1390
|
-
const db = tenantCtx.db;
|
|
1391
|
-
const masterKey = tenantCtx.masterKey;
|
|
1392
|
-
const u = new URL(url, "https://dummy");
|
|
1393
|
-
const taskUuid = u.searchParams.get("id");
|
|
1394
|
-
if (!taskUuid) {
|
|
1395
|
-
return { status: 400, body: { success: false, error: { code: "TASK_ID_REQUIRED", message: "\u7F3A\u5C11\u4EFB\u52A1ID" } } };
|
|
1396
|
-
}
|
|
1397
|
-
const userId = getHeader(headers, "x-user-id");
|
|
1398
|
-
if (!userId) {
|
|
1399
|
-
return { status: 400, body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } } };
|
|
1400
|
-
}
|
|
1401
|
-
if (!isValidUUIDv4(userId)) {
|
|
1402
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } } };
|
|
1403
|
-
}
|
|
1404
|
-
const isEncrypted = getHeader(headers, "x-payload-encrypted") === "true";
|
|
1405
|
-
const encryptionVersion = getHeader(headers, "x-encryption-version");
|
|
1406
|
-
if (!isEncrypted) {
|
|
1407
|
-
return { status: 400, body: { success: false, error: { code: "ENCRYPTION_REQUIRED", message: "\u8BF7\u6C42\u4F53\u5FC5\u987B\u52A0\u5BC6" } } };
|
|
1408
|
-
}
|
|
1409
|
-
if (encryptionVersion !== "1") {
|
|
1410
|
-
return { status: 400, body: { success: false, error: { code: "UNSUPPORTED_ENCRYPTION_VERSION", message: "\u52A0\u5BC6\u7248\u672C\u4E0D\u652F\u6301" } } };
|
|
1411
|
-
}
|
|
1412
|
-
const parsedBody = parseEncryptedBody(body);
|
|
1413
|
-
if (!parsedBody.ok) {
|
|
1414
|
-
return { status: 400, body: { success: false, error: parsedBody.error } };
|
|
1415
|
-
}
|
|
1416
|
-
const encryptedBody = parsedBody.data;
|
|
1417
|
-
const userKey = await deriveUserEncryptionKey(userId, masterKey);
|
|
1418
|
-
let updates;
|
|
1419
|
-
try {
|
|
1420
|
-
updates = await decryptPayload(encryptedBody, userKey);
|
|
1421
|
-
} catch (_error) {
|
|
1422
|
-
return { status: 400, body: { success: false, error: { code: "DECRYPTION_FAILED", message: "\u8BF7\u6C42\u4F53\u89E3\u5BC6\u5931\u8D25" } } };
|
|
1423
|
-
}
|
|
1424
|
-
if (!isPlainObject(updates)) {
|
|
1425
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF" } } };
|
|
1426
|
-
}
|
|
1427
|
-
if (updates.nextSendAt && !isValidISO8601(updates.nextSendAt)) {
|
|
1428
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["nextSendAt"] } } } };
|
|
1429
|
-
}
|
|
1430
|
-
if (updates.recurrenceType && !["none", "daily", "weekly"].includes(updates.recurrenceType)) {
|
|
1431
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["recurrenceType"] } } } };
|
|
1432
|
-
}
|
|
1433
|
-
if (Object.prototype.hasOwnProperty.call(updates, "maxTokens") && updates.maxTokens !== null && (!Number.isInteger(updates.maxTokens) || updates.maxTokens <= 0)) {
|
|
1434
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["maxTokens"] } } } };
|
|
1435
|
-
}
|
|
1436
|
-
if (updates.completePrompt && updates.messages !== void 0 && updates.messages !== null) {
|
|
1437
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "completePrompt \u4E0E messages \u4E0D\u80FD\u540C\u65F6\u66F4\u65B0\uFF08\u4E8C\u9009\u4E00\uFF09", details: { invalidFields: ["completePrompt", "messages"] } } } };
|
|
1438
|
-
}
|
|
1439
|
-
if (updates.messages !== void 0 && updates.messages !== null) {
|
|
1440
|
-
const msgErr = validateLlmMessagesArray(updates.messages);
|
|
1441
|
-
if (msgErr) {
|
|
1442
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: msgErr, details: { invalidFields: ["messages"] } } } };
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
if (Object.prototype.hasOwnProperty.call(updates, "temperature") && updates.temperature !== null && (typeof updates.temperature !== "number" || !Number.isFinite(updates.temperature))) {
|
|
1446
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: "\u66F4\u65B0\u6570\u636E\u683C\u5F0F\u9519\u8BEF", details: { invalidFields: ["temperature"] } } } };
|
|
1447
|
-
}
|
|
1448
|
-
if (Object.prototype.hasOwnProperty.call(updates, "splitPattern")) {
|
|
1449
|
-
const splitErr = validateSplitPattern(updates.splitPattern);
|
|
1450
|
-
if (splitErr) {
|
|
1451
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_UPDATE_DATA", message: splitErr, details: { invalidFields: ["splitPattern"] } } } };
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
if (Object.prototype.hasOwnProperty.call(updates, "avatarUrl")) {
|
|
1455
|
-
const avatarErr = _amsgshared.validateAvatarUrl.call(void 0, updates.avatarUrl);
|
|
1456
|
-
if (avatarErr) {
|
|
1457
|
-
console.warn("[amsg-server] update-message avatarUrl \u4E0D\u5408\u6CD5\uFF0C\u5DF2\u5FFD\u7565\uFF1A", avatarErr);
|
|
1458
|
-
delete updates.avatarUrl;
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
const existingTask = await db.getTaskByUuid(taskUuid, userId);
|
|
1462
|
-
if (!existingTask) {
|
|
1463
|
-
const taskStatus = await db.getTaskStatus(taskUuid, userId);
|
|
1464
|
-
if (!taskStatus) {
|
|
1465
|
-
return { status: 404, body: { success: false, error: { code: "TASK_NOT_FOUND", message: "\u6307\u5B9A\u7684\u4EFB\u52A1\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664" } } };
|
|
1466
|
-
}
|
|
1467
|
-
return { status: 409, body: { success: false, error: { code: "TASK_ALREADY_COMPLETED", message: "\u4EFB\u52A1\u5DF2\u5B8C\u6210\u6216\u5DF2\u5931\u8D25\uFF0C\u65E0\u6CD5\u66F4\u65B0" } } };
|
|
1468
|
-
}
|
|
1469
|
-
const existingData = JSON.parse(await decryptFromStorage(existingTask.encrypted_payload, userKey));
|
|
1470
|
-
const promptUpdates = {};
|
|
1471
|
-
if (updates.completePrompt) {
|
|
1472
|
-
promptUpdates.completePrompt = updates.completePrompt;
|
|
1473
|
-
promptUpdates.messages = null;
|
|
1474
|
-
} else if (updates.messages !== void 0 && updates.messages !== null) {
|
|
1475
|
-
promptUpdates.messages = updates.messages;
|
|
1476
|
-
promptUpdates.completePrompt = null;
|
|
1477
|
-
}
|
|
1478
|
-
const updatedData = {
|
|
1479
|
-
...existingData,
|
|
1480
|
-
...promptUpdates,
|
|
1481
|
-
...updates.userMessage && { userMessage: updates.userMessage },
|
|
1482
|
-
...updates.recurrenceType && { recurrenceType: updates.recurrenceType },
|
|
1483
|
-
...updates.avatarUrl && { avatarUrl: updates.avatarUrl },
|
|
1484
|
-
...updates.metadata && { metadata: updates.metadata },
|
|
1485
|
-
...Object.prototype.hasOwnProperty.call(updates, "maxTokens") && { maxTokens: _nullishCoalesce(updates.maxTokens, () => ( null)) },
|
|
1486
|
-
...Object.prototype.hasOwnProperty.call(updates, "temperature") && { temperature: _nullishCoalesce(updates.temperature, () => ( null)) },
|
|
1487
|
-
// splitPattern: hasOwnProperty so that explicit `null` (= revert to
|
|
1488
|
-
// default) doesn't get swallowed by truthy-spread the way the optional
|
|
1489
|
-
// string fields above are.
|
|
1490
|
-
...Object.prototype.hasOwnProperty.call(updates, "splitPattern") && { splitPattern: _nullishCoalesce(updates.splitPattern, () => ( null)) }
|
|
1491
|
-
};
|
|
1492
|
-
const encryptedPayload = await encryptForStorage(JSON.stringify(updatedData), userKey);
|
|
1493
|
-
const extraFields = updates.nextSendAt ? { next_send_at: updates.nextSendAt } : void 0;
|
|
1494
|
-
const result = await db.updateTaskByUuid(taskUuid, userId, encryptedPayload, extraFields);
|
|
1495
|
-
if (!result) {
|
|
1496
|
-
return { status: 409, body: { success: false, error: { code: "UPDATE_CONFLICT", message: "\u4EFB\u52A1\u66F4\u65B0\u5931\u8D25\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u88AB\u4FEE\u6539\u6216\u5220\u9664" } } };
|
|
1497
|
-
}
|
|
1498
|
-
return {
|
|
1499
|
-
status: 200,
|
|
1500
|
-
body: {
|
|
1501
|
-
success: true,
|
|
1502
|
-
data: {
|
|
1503
|
-
uuid: taskUuid,
|
|
1504
|
-
updatedFields: Object.keys(updates),
|
|
1505
|
-
updatedAt: result.updated_at
|
|
1506
|
-
}
|
|
1507
|
-
}
|
|
1508
|
-
};
|
|
1509
|
-
}
|
|
1510
|
-
return { PUT };
|
|
1511
|
-
}
|
|
1512
|
-
|
|
1513
|
-
// src/server/handlers/cancel-message.js
|
|
1514
|
-
function createCancelMessageHandler(ctx) {
|
|
1515
|
-
async function DELETE(url, headers) {
|
|
1516
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
|
|
1517
|
-
if (!tenantResult.ok) {
|
|
1518
|
-
return tenantResult.error;
|
|
1519
|
-
}
|
|
1520
|
-
const db = tenantResult.context.db;
|
|
1521
|
-
const u = new URL(url, "https://dummy");
|
|
1522
|
-
const taskUuid = u.searchParams.get("id");
|
|
1523
|
-
if (!taskUuid) {
|
|
1524
|
-
return { status: 400, body: { success: false, error: { code: "TASK_ID_REQUIRED", message: "\u7F3A\u5C11\u4EFB\u52A1ID" } } };
|
|
1525
|
-
}
|
|
1526
|
-
const userId = getHeader(headers, "x-user-id");
|
|
1527
|
-
if (!userId) {
|
|
1528
|
-
return { status: 400, body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26" } } };
|
|
1529
|
-
}
|
|
1530
|
-
if (!isValidUUIDv4(userId)) {
|
|
1531
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } } };
|
|
1532
|
-
}
|
|
1533
|
-
const deleted = await db.deleteTaskByUuid(taskUuid, userId);
|
|
1534
|
-
if (!deleted) {
|
|
1535
|
-
return {
|
|
1536
|
-
status: 404,
|
|
1537
|
-
body: { success: false, error: { code: "TASK_NOT_FOUND", message: "\u6307\u5B9A\u7684\u4EFB\u52A1\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664" } }
|
|
1538
|
-
};
|
|
1539
|
-
}
|
|
1540
|
-
return {
|
|
1541
|
-
status: 200,
|
|
1542
|
-
body: {
|
|
1543
|
-
success: true,
|
|
1544
|
-
data: { uuid: taskUuid, message: "\u4EFB\u52A1\u5DF2\u6210\u529F\u53D6\u6D88", deletedAt: (/* @__PURE__ */ new Date()).toISOString() }
|
|
1545
|
-
}
|
|
1546
|
-
};
|
|
1547
|
-
}
|
|
1548
|
-
return { DELETE };
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
// src/server/handlers/messages.js
|
|
1552
|
-
function createMessagesHandler(ctx) {
|
|
1553
|
-
async function GET(url, headers) {
|
|
1554
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers, { url });
|
|
1555
|
-
if (!tenantResult.ok) {
|
|
1556
|
-
return tenantResult.error;
|
|
1557
|
-
}
|
|
1558
|
-
const tenantCtx = tenantResult.context;
|
|
1559
|
-
const db = tenantCtx.db;
|
|
1560
|
-
const masterKey = tenantCtx.masterKey;
|
|
1561
|
-
const userId = getHeader(headers, "x-user-id");
|
|
1562
|
-
if (!userId) {
|
|
1563
|
-
return {
|
|
1564
|
-
status: 400,
|
|
1565
|
-
body: { success: false, error: { code: "USER_ID_REQUIRED", message: "\u5FC5\u987B\u63D0\u4F9B X-User-Id \u8BF7\u6C42\u5934" } }
|
|
1566
|
-
};
|
|
1567
|
-
}
|
|
1568
|
-
if (!isValidUUIDv4(userId)) {
|
|
1569
|
-
return {
|
|
1570
|
-
status: 400,
|
|
1571
|
-
body: { success: false, error: { code: "INVALID_USER_ID_FORMAT", message: "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F" } }
|
|
1572
|
-
};
|
|
1573
|
-
}
|
|
1574
|
-
const u = new URL(url, "https://dummy");
|
|
1575
|
-
const status = u.searchParams.get("status") || "all";
|
|
1576
|
-
const limit = Math.min(parseInt(u.searchParams.get("limit") || "20", 10), 100);
|
|
1577
|
-
const offset = parseInt(u.searchParams.get("offset") || "0", 10);
|
|
1578
|
-
if (isNaN(limit) || limit < 1) {
|
|
1579
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_PARAMETERS", message: "limit \u53C2\u6570\u65E0\u6548\uFF0C\u5FC5\u987B\u4E3A\u6B63\u6574\u6570" } } };
|
|
1580
|
-
}
|
|
1581
|
-
if (isNaN(offset) || offset < 0) {
|
|
1582
|
-
return { status: 400, body: { success: false, error: { code: "INVALID_PARAMETERS", message: "offset \u53C2\u6570\u65E0\u6548\uFF0C\u5FC5\u987B\u4E3A\u975E\u8D1F\u6574\u6570" } } };
|
|
1583
|
-
}
|
|
1584
|
-
const { tasks, total } = await db.listTasks(userId, { status, limit, offset });
|
|
1585
|
-
const userKey = await deriveUserEncryptionKey(userId, masterKey);
|
|
1586
|
-
const decryptedTasks = await Promise.all(tasks.map(async (task) => {
|
|
1587
|
-
const decrypted = JSON.parse(await decryptFromStorage(task.encrypted_payload, userKey));
|
|
1588
|
-
return {
|
|
1589
|
-
id: task.id,
|
|
1590
|
-
uuid: task.uuid,
|
|
1591
|
-
contactName: decrypted.contactName,
|
|
1592
|
-
messageType: task.message_type,
|
|
1593
|
-
messageSubtype: decrypted.messageSubtype,
|
|
1594
|
-
nextSendAt: task.next_send_at,
|
|
1595
|
-
recurrenceType: decrypted.recurrenceType,
|
|
1596
|
-
status: task.status,
|
|
1597
|
-
retryCount: task.retry_count,
|
|
1598
|
-
createdAt: task.created_at,
|
|
1599
|
-
updatedAt: task.updated_at,
|
|
1600
|
-
// Character ownership / client-side task identity, pulled from the
|
|
1601
|
-
// scheduling host's metadata so it can filter tasks by character
|
|
1602
|
-
// (contactName can collide across characters). Only these two
|
|
1603
|
-
// metadata fields are surfaced — the rest of metadata may hold
|
|
1604
|
-
// host-private data and stays server-side. Absent → null.
|
|
1605
|
-
charId: _nullishCoalesce(_optionalChain([decrypted, 'access', _7 => _7.metadata, 'optionalAccess', _8 => _8.charId]), () => ( null)),
|
|
1606
|
-
clientTaskId: _nullishCoalesce(_optionalChain([decrypted, 'access', _9 => _9.metadata, 'optionalAccess', _10 => _10.amsgClientTaskId]), () => ( null))
|
|
1607
|
-
};
|
|
1608
|
-
}));
|
|
1609
|
-
const responsePayload = {
|
|
1610
|
-
tasks: decryptedTasks,
|
|
1611
|
-
pagination: { total, limit, offset, hasMore: offset + limit < total }
|
|
1612
|
-
};
|
|
1613
|
-
const encryptedResponse = await encryptPayload(responsePayload, userKey);
|
|
1614
|
-
return {
|
|
1615
|
-
status: 200,
|
|
1616
|
-
body: {
|
|
1617
|
-
success: true,
|
|
1618
|
-
encrypted: true,
|
|
1619
|
-
version: 1,
|
|
1620
|
-
data: encryptedResponse
|
|
1621
|
-
}
|
|
1622
|
-
};
|
|
1623
|
-
}
|
|
1624
|
-
return { GET };
|
|
1625
|
-
}
|
|
1626
|
-
|
|
1627
|
-
// src/server/adapters/schema.sqlite.js
|
|
1628
|
-
var SQLITE_TABLE_SQL = `
|
|
1629
|
-
CREATE TABLE IF NOT EXISTS scheduled_messages (
|
|
1630
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1631
|
-
user_id TEXT NOT NULL,
|
|
1632
|
-
uuid TEXT,
|
|
1633
|
-
encrypted_payload TEXT NOT NULL,
|
|
1634
|
-
message_type TEXT NOT NULL CHECK (message_type IN ('fixed', 'prompted', 'auto', 'instant')),
|
|
1635
|
-
next_send_at TEXT NOT NULL,
|
|
1636
|
-
lease_until TEXT,
|
|
1637
|
-
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')),
|
|
1638
|
-
retry_count INTEGER NOT NULL DEFAULT 0,
|
|
1639
|
-
created_at TEXT NOT NULL,
|
|
1640
|
-
updated_at TEXT NOT NULL
|
|
1641
|
-
)
|
|
1642
|
-
`;
|
|
1643
|
-
var SQLITE_MIGRATIONS = [
|
|
1644
|
-
{
|
|
1645
|
-
name: "add_lease_until",
|
|
1646
|
-
sql: "ALTER TABLE scheduled_messages ADD COLUMN lease_until TEXT",
|
|
1647
|
-
description: "Task claim lease (2.6.0)"
|
|
1648
|
-
}
|
|
1649
|
-
];
|
|
1650
|
-
var SQLITE_INDEXES = [
|
|
1651
|
-
{
|
|
1652
|
-
name: "idx_pending_tasks_optimized",
|
|
1653
|
-
sql: `CREATE INDEX IF NOT EXISTS idx_pending_tasks_optimized
|
|
1654
|
-
ON scheduled_messages (status, next_send_at, id, retry_count)
|
|
1655
|
-
WHERE status = 'pending'`,
|
|
1656
|
-
description: "Main query index (Cron Job finds pending tasks)",
|
|
1657
|
-
critical: false
|
|
1658
|
-
},
|
|
1659
|
-
{
|
|
1660
|
-
name: "idx_cleanup_completed",
|
|
1661
|
-
sql: `CREATE INDEX IF NOT EXISTS idx_cleanup_completed
|
|
1662
|
-
ON scheduled_messages (status, updated_at)
|
|
1663
|
-
WHERE status IN ('sent', 'failed')`,
|
|
1664
|
-
description: "Cleanup query index",
|
|
1665
|
-
critical: false
|
|
1666
|
-
},
|
|
1667
|
-
{
|
|
1668
|
-
name: "idx_failed_retry",
|
|
1669
|
-
sql: `CREATE INDEX IF NOT EXISTS idx_failed_retry
|
|
1670
|
-
ON scheduled_messages (status, retry_count, next_send_at)
|
|
1671
|
-
WHERE status = 'failed' AND retry_count < 3`,
|
|
1672
|
-
description: "Failed retry index",
|
|
1673
|
-
critical: false
|
|
1674
|
-
},
|
|
1675
|
-
{
|
|
1676
|
-
name: "idx_user_id",
|
|
1677
|
-
sql: `CREATE INDEX IF NOT EXISTS idx_user_id
|
|
1678
|
-
ON scheduled_messages (user_id)`,
|
|
1679
|
-
description: "User task query index",
|
|
1680
|
-
critical: false
|
|
1681
|
-
},
|
|
1682
|
-
{
|
|
1683
|
-
name: "uidx_uuid",
|
|
1684
|
-
sql: `CREATE UNIQUE INDEX IF NOT EXISTS uidx_uuid
|
|
1685
|
-
ON scheduled_messages (uuid)
|
|
1686
|
-
WHERE uuid IS NOT NULL`,
|
|
1687
|
-
description: "UUID uniqueness guard",
|
|
1688
|
-
critical: true
|
|
1689
|
-
}
|
|
1690
|
-
];
|
|
1691
|
-
var CLIENT_STATE_TABLE_SQL = `
|
|
1692
|
-
CREATE TABLE IF NOT EXISTS client_state (
|
|
1693
|
-
user_id TEXT NOT NULL,
|
|
1694
|
-
namespace TEXT NOT NULL,
|
|
1695
|
-
key TEXT NOT NULL,
|
|
1696
|
-
value TEXT NOT NULL,
|
|
1697
|
-
updated_at INTEGER NOT NULL,
|
|
1698
|
-
PRIMARY KEY (user_id, namespace, key)
|
|
1699
|
-
)
|
|
1700
|
-
`;
|
|
1701
|
-
|
|
1702
|
-
// src/server/adapters/d1.js
|
|
1703
|
-
var UPDATABLE_COLUMNS = /* @__PURE__ */ new Set([
|
|
1704
|
-
"user_id",
|
|
1705
|
-
"uuid",
|
|
1706
|
-
"encrypted_payload",
|
|
1707
|
-
"message_type",
|
|
1708
|
-
"next_send_at",
|
|
1709
|
-
"lease_until",
|
|
1710
|
-
"status",
|
|
1711
|
-
"retry_count",
|
|
1712
|
-
"created_at",
|
|
1713
|
-
"updated_at"
|
|
1714
|
-
]);
|
|
1715
|
-
function escapeLikePrefix(prefix) {
|
|
1716
|
-
return prefix.replace(/[\\%_]/g, (ch) => `\\${ch}`);
|
|
1717
|
-
}
|
|
1718
|
-
var D1Adapter = class {
|
|
1719
|
-
/** @param {{ prepare: (sql: string) => any }} db - Cloudflare D1 binding */
|
|
1720
|
-
constructor(db) {
|
|
1721
|
-
this._db = db;
|
|
1722
|
-
}
|
|
1723
|
-
/** @private */
|
|
1724
|
-
_now() {
|
|
1725
|
-
return (/* @__PURE__ */ new Date()).toISOString();
|
|
1726
|
-
}
|
|
1727
|
-
/** @private */
|
|
1728
|
-
_iso(value) {
|
|
1729
|
-
const d = new Date(value);
|
|
1730
|
-
if (Number.isNaN(d.getTime())) {
|
|
1731
|
-
throw new Error(`[amsg-server D1] invalid timestamp: ${value}`);
|
|
1732
|
-
}
|
|
1733
|
-
return d.toISOString();
|
|
1734
|
-
}
|
|
1735
|
-
async initSchema() {
|
|
1736
|
-
await this._db.prepare(SQLITE_TABLE_SQL).run();
|
|
1737
|
-
await this._db.prepare(CLIENT_STATE_TABLE_SQL).run();
|
|
1738
|
-
for (const migration of SQLITE_MIGRATIONS) {
|
|
1739
|
-
try {
|
|
1740
|
-
await this._db.prepare(migration.sql).run();
|
|
1741
|
-
} catch (error) {
|
|
1742
|
-
if (!/duplicate column name/i.test(error.message || "")) throw error;
|
|
1743
|
-
}
|
|
1744
|
-
}
|
|
1745
|
-
const indexResults = [];
|
|
1746
|
-
for (const index of SQLITE_INDEXES) {
|
|
1747
|
-
try {
|
|
1748
|
-
await this._db.prepare(index.sql).run();
|
|
1749
|
-
indexResults.push({ name: index.name, status: "success", description: index.description, critical: !!index.critical });
|
|
1750
|
-
} catch (error) {
|
|
1751
|
-
indexResults.push({ name: index.name, status: "failed", description: index.description, critical: !!index.critical, error: error.message });
|
|
1752
|
-
}
|
|
1753
|
-
}
|
|
1754
|
-
const criticalFailures = indexResults.filter((i) => i.critical && i.status === "failed");
|
|
1755
|
-
if (criticalFailures.length > 0) {
|
|
1756
|
-
const names = criticalFailures.map((i) => i.name).join(", ");
|
|
1757
|
-
throw new Error(
|
|
1758
|
-
`Critical index creation failed (${names}). Please remove duplicate UUID rows and run initSchema again.`
|
|
1759
|
-
);
|
|
1760
|
-
}
|
|
1761
|
-
return {
|
|
1762
|
-
columnsCreated: 11,
|
|
1763
|
-
indexesCreated: indexResults.filter((r) => r.status === "success").length,
|
|
1764
|
-
indexesFailed: indexResults.filter((r) => r.status === "failed").length,
|
|
1765
|
-
columns: [],
|
|
1766
|
-
indexes: indexResults
|
|
1767
|
-
};
|
|
1768
|
-
}
|
|
1769
|
-
async dropSchema() {
|
|
1770
|
-
await this._db.prepare("DROP TABLE IF EXISTS scheduled_messages").run();
|
|
1771
|
-
await this._db.prepare("DROP TABLE IF EXISTS client_state").run();
|
|
1772
|
-
}
|
|
1773
|
-
async createTask(params) {
|
|
1774
|
-
const now = this._now();
|
|
1775
|
-
const nextSendAt = this._iso(params.next_send_at);
|
|
1776
|
-
const res = await this._db.prepare(
|
|
1777
|
-
`INSERT INTO scheduled_messages
|
|
1778
|
-
(user_id, uuid, encrypted_payload, next_send_at, message_type, status, retry_count, created_at, updated_at)
|
|
1779
|
-
VALUES (?, ?, ?, ?, ?, 'pending', 0, ?, ?)`
|
|
1780
|
-
).bind(params.user_id, params.uuid, params.encrypted_payload, nextSendAt, params.message_type, now, now).run();
|
|
1781
|
-
const id = res.meta.last_row_id;
|
|
1782
|
-
return this._db.prepare(
|
|
1783
|
-
`SELECT id, uuid, next_send_at, status, created_at FROM scheduled_messages WHERE id = ?`
|
|
1784
|
-
).bind(id).first();
|
|
1785
|
-
}
|
|
1786
|
-
async getTaskByUuid(uuid, userId) {
|
|
1787
|
-
return this._db.prepare(
|
|
1788
|
-
`SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
|
|
1789
|
-
FROM scheduled_messages
|
|
1790
|
-
WHERE uuid = ? AND user_id = ? AND status = 'pending'
|
|
1791
|
-
LIMIT 1`
|
|
1792
|
-
).bind(uuid, userId).first();
|
|
1793
|
-
}
|
|
1794
|
-
async getTaskByUuidOnly(uuid) {
|
|
1795
|
-
return this._db.prepare(
|
|
1796
|
-
`SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
|
|
1797
|
-
FROM scheduled_messages
|
|
1798
|
-
WHERE uuid = ? AND status = 'pending'
|
|
1799
|
-
LIMIT 1`
|
|
1800
|
-
).bind(uuid).first();
|
|
1801
|
-
}
|
|
1802
|
-
async updateTaskById(taskId, updates) {
|
|
1803
|
-
const sets = [];
|
|
1804
|
-
const values = [];
|
|
1805
|
-
for (const [key, value] of Object.entries(updates)) {
|
|
1806
|
-
if (!UPDATABLE_COLUMNS.has(key)) {
|
|
1807
|
-
throw new Error(`[amsg-server D1] rejected unknown update column: ${key}`);
|
|
1808
|
-
}
|
|
1809
|
-
sets.push(`${key} = ?`);
|
|
1810
|
-
values.push(key === "next_send_at" ? this._iso(value) : value);
|
|
1811
|
-
}
|
|
1812
|
-
if (!Object.prototype.hasOwnProperty.call(updates, "updated_at")) {
|
|
1813
|
-
sets.push("updated_at = ?");
|
|
1814
|
-
values.push(this._now());
|
|
1815
|
-
}
|
|
1816
|
-
values.push(taskId);
|
|
1817
|
-
await this._db.prepare(
|
|
1818
|
-
`UPDATE scheduled_messages SET ${sets.join(", ")} WHERE id = ?`
|
|
1819
|
-
).bind(...values).run();
|
|
1820
|
-
return this._db.prepare("SELECT * FROM scheduled_messages WHERE id = ?").bind(taskId).first();
|
|
1821
|
-
}
|
|
1822
|
-
async updateTaskByUuid(uuid, userId, encryptedPayload, extraFields) {
|
|
1823
|
-
const now = this._now();
|
|
1824
|
-
const sets = ["encrypted_payload = ?", "updated_at = ?"];
|
|
1825
|
-
const values = [encryptedPayload, now];
|
|
1826
|
-
if (extraFields) {
|
|
1827
|
-
for (const [key, value] of Object.entries(extraFields)) {
|
|
1828
|
-
if (!UPDATABLE_COLUMNS.has(key)) {
|
|
1829
|
-
throw new Error(`[amsg-server D1] rejected unknown update column: ${key}`);
|
|
1830
|
-
}
|
|
1831
|
-
sets.push(`${key} = ?`);
|
|
1832
|
-
values.push(key === "next_send_at" ? this._iso(value) : value);
|
|
1833
|
-
}
|
|
1834
|
-
}
|
|
1835
|
-
values.push(uuid, userId);
|
|
1836
|
-
const res = await this._db.prepare(
|
|
1837
|
-
`UPDATE scheduled_messages SET ${sets.join(", ")}
|
|
1838
|
-
WHERE uuid = ? AND user_id = ? AND status = 'pending'`
|
|
1839
|
-
).bind(...values).run();
|
|
1840
|
-
if (!res.meta.changes) return null;
|
|
1841
|
-
return { uuid, updated_at: now };
|
|
1842
|
-
}
|
|
1843
|
-
async deleteTaskById(taskId) {
|
|
1844
|
-
const res = await this._db.prepare("DELETE FROM scheduled_messages WHERE id = ?").bind(taskId).run();
|
|
1845
|
-
return res.meta.changes > 0;
|
|
1846
|
-
}
|
|
1847
|
-
async deleteTaskByUuid(uuid, userId) {
|
|
1848
|
-
const res = await this._db.prepare(
|
|
1849
|
-
"DELETE FROM scheduled_messages WHERE uuid = ? AND user_id = ?"
|
|
1850
|
-
).bind(uuid, userId).run();
|
|
1851
|
-
return res.meta.changes > 0;
|
|
1852
|
-
}
|
|
1853
|
-
async getPendingTasks(limit = 50) {
|
|
1854
|
-
const now = this._now();
|
|
1855
|
-
const res = await this._db.prepare(
|
|
1856
|
-
`SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count
|
|
1857
|
-
FROM scheduled_messages
|
|
1858
|
-
WHERE status = 'pending' AND next_send_at <= ?
|
|
1859
|
-
AND (lease_until IS NULL OR lease_until <= ?)
|
|
1860
|
-
ORDER BY next_send_at ASC
|
|
1861
|
-
LIMIT ?`
|
|
1862
|
-
).bind(now, now, limit).all();
|
|
1863
|
-
return res.results || [];
|
|
1864
|
-
}
|
|
1865
|
-
/**
|
|
1866
|
-
* 领取一条到点的任务:在 lease_until 上写下「这条归我管到什么时候」,
|
|
1867
|
-
* 本次投递期间别的 tick 领不走它。
|
|
1868
|
-
*
|
|
1869
|
-
* 租约写在自己的列上,next_send_at 全程不动——那一列是用户设的触发时刻,
|
|
1870
|
-
* 任务列表要读它、循环任务推进下一次也要拿它当基准。
|
|
1871
|
-
*
|
|
1872
|
-
* 两个 tick 抢同一行时只有一个能改到行,另一个拿到 changes = 0,据此跳过。
|
|
1873
|
-
* WHERE 里的两个条件各管一件事:
|
|
1874
|
-
* - lease_until 为空或已过期:没人正在跑这条。领了任务的 tick 中途没了
|
|
1875
|
-
* 也不会把行焊死,租约到期后自然可以被接手。
|
|
1876
|
-
* - next_send_at 等于读这行时看到的值:读出来之后用户又改了排期的话,
|
|
1877
|
-
* 这一跳就不该再按旧时刻发。
|
|
1878
|
-
*
|
|
1879
|
-
* 不加一个 'sending' 状态来表达「正在跑」:建表语句里 status 有
|
|
1880
|
-
* CHECK (status IN ('pending','sent','failed')),加值要重建表。
|
|
1881
|
-
*
|
|
1882
|
-
* expectedNextSendAt 按读到的原样比对,不做时区归一化——老部署里可能还留
|
|
1883
|
-
* 着非归一化写法的行(如 +08:00 结尾),归一化后反而对不上,那条任务会永
|
|
1884
|
-
* 远领不到。
|
|
1885
|
-
*
|
|
1886
|
-
* @param {number} taskId
|
|
1887
|
-
* @param {string} expectedNextSendAt - 读这行时拿到的 next_send_at 原值
|
|
1888
|
-
* @param {string|Date} leaseUntil - 租期末尾
|
|
1889
|
-
* @returns {Promise<boolean>} true = 领到了;false = 别人正拿着租约、排期被改过、或行已不是 pending
|
|
1890
|
-
*/
|
|
1891
|
-
async claimTask(taskId, expectedNextSendAt, leaseUntil) {
|
|
1892
|
-
const expected = typeof expectedNextSendAt === "string" ? expectedNextSendAt : this._iso(expectedNextSendAt);
|
|
1893
|
-
const res = await this._db.prepare(
|
|
1894
|
-
`UPDATE scheduled_messages
|
|
1895
|
-
SET lease_until = ?, updated_at = ?
|
|
1896
|
-
WHERE id = ? AND status = 'pending' AND next_send_at = ?
|
|
1897
|
-
AND (lease_until IS NULL OR lease_until <= ?)`
|
|
1898
|
-
).bind(this._iso(leaseUntil), this._now(), taskId, expected, this._now()).run();
|
|
1899
|
-
return (res.meta.changes || 0) > 0;
|
|
1900
|
-
}
|
|
1901
|
-
async listTasks(userId, opts = {}) {
|
|
1902
|
-
const { status = "all", limit = 20, offset = 0 } = opts;
|
|
1903
|
-
const conditions = ["user_id = ?"];
|
|
1904
|
-
const params = [userId];
|
|
1905
|
-
if (status !== "all") {
|
|
1906
|
-
conditions.push("status = ?");
|
|
1907
|
-
params.push(status);
|
|
1908
|
-
}
|
|
1909
|
-
const where = conditions.join(" AND ");
|
|
1910
|
-
const countRow = await this._db.prepare(
|
|
1911
|
-
`SELECT COUNT(*) as count FROM scheduled_messages WHERE ${where}`
|
|
1912
|
-
).bind(...params).first();
|
|
1913
|
-
const total = Number(countRow.count) || 0;
|
|
1914
|
-
const res = await this._db.prepare(
|
|
1915
|
-
`SELECT id, user_id, uuid, encrypted_payload, message_type, next_send_at, status, retry_count, created_at, updated_at
|
|
1916
|
-
FROM scheduled_messages
|
|
1917
|
-
WHERE ${where}
|
|
1918
|
-
ORDER BY next_send_at ASC
|
|
1919
|
-
LIMIT ? OFFSET ?`
|
|
1920
|
-
).bind(...params, limit, offset).all();
|
|
1921
|
-
return { tasks: res.results || [], total };
|
|
1922
|
-
}
|
|
1923
|
-
async cleanupOldTasks(days = 7) {
|
|
1924
|
-
const safeDays = Math.max(1, Math.floor(Number(days)));
|
|
1925
|
-
const cutoff = new Date(Date.now() - safeDays * 24 * 60 * 60 * 1e3).toISOString();
|
|
1926
|
-
const res = await this._db.prepare(
|
|
1927
|
-
`DELETE FROM scheduled_messages
|
|
1928
|
-
WHERE status IN ('sent', 'failed') AND updated_at < ?`
|
|
1929
|
-
).bind(cutoff).run();
|
|
1930
|
-
return res.meta.changes || 0;
|
|
1931
|
-
}
|
|
1932
|
-
async getTaskStatus(uuid, userId) {
|
|
1933
|
-
const row = await this._db.prepare(
|
|
1934
|
-
"SELECT status FROM scheduled_messages WHERE uuid = ? AND user_id = ? LIMIT 1"
|
|
1935
|
-
).bind(uuid, userId).first();
|
|
1936
|
-
return row ? row.status : null;
|
|
1937
|
-
}
|
|
1938
|
-
// ── client_state (single-user cloud state mirror) ──────────────────────
|
|
1939
|
-
/**
|
|
1940
|
-
* Batch upsert. Last-write-wins per (namespace, key): an entry older
|
|
1941
|
-
* than the stored row (updatedAt strictly lower) is skipped; equal or
|
|
1942
|
-
* newer overwrites. Values arrive pre-encrypted (the handler encrypts).
|
|
1943
|
-
*
|
|
1944
|
-
* `cleanups` 是删除项:在同一 batch 里先于 upsert 执行,`updated_at <= ?`
|
|
1945
|
-
* 条件保证陈旧批次删不动更新写入的行。两种形态——
|
|
1946
|
-
* - `{ namespace, keyPrefix, updatedAt }` 删 key 前缀下的所有行,用来清掉
|
|
1947
|
-
* 大值旧写入留下的切片行(见 lib/state-chunks.js);
|
|
1948
|
-
* - `{ namespace, key, updatedAt }` 删这一个 key,用来删整条状态(前缀会
|
|
1949
|
-
* 连带删掉同前缀的兄弟 key,删单条必须走精确匹配)。
|
|
1950
|
-
*
|
|
1951
|
-
* 删掉一整条状态就是这两种各来一条(切片行走前缀、根行走精确 key),
|
|
1952
|
-
* `entries` 传空数组即可——见 lib/client-state-store.js。
|
|
1953
|
-
*
|
|
1954
|
-
* Uses D1's batch() — one network round trip for the whole set (implicit
|
|
1955
|
-
* transaction). The client calls this endpoint inside its few-seconds
|
|
1956
|
-
* background window, so N sequential round trips could eat the whole
|
|
1957
|
-
* window. Bindings without batch() (e.g. the sqlite test shim, custom
|
|
1958
|
-
* adapters) fall back to a sequential loop.
|
|
1959
|
-
*
|
|
1960
|
-
* @param {string} userId
|
|
1961
|
-
* @param {Array<{ namespace: string, key: string, value: string, updatedAt: number }>} entries
|
|
1962
|
-
* @param {Array<{ namespace: string, key?: string, keyPrefix?: string, updatedAt: number }>} [cleanups]
|
|
1963
|
-
* @returns {Promise<{ upserted: number, skipped: number, outcomes: boolean[] }>}
|
|
1964
|
-
* `outcomes[i]` 对应 entries[i] 是否真的写入(changes > 0)。
|
|
1965
|
-
*/
|
|
1966
|
-
async upsertClientState(userId, entries, cleanups = []) {
|
|
1967
|
-
const UPSERT_SQL = `INSERT INTO client_state (user_id, namespace, key, value, updated_at)
|
|
1968
|
-
VALUES (?, ?, ?, ?, ?)
|
|
1969
|
-
ON CONFLICT (user_id, namespace, key) DO UPDATE SET
|
|
1970
|
-
value = excluded.value,
|
|
1971
|
-
updated_at = excluded.updated_at
|
|
1972
|
-
WHERE excluded.updated_at >= client_state.updated_at`;
|
|
1973
|
-
const CLEANUP_PREFIX_SQL = `DELETE FROM client_state
|
|
1974
|
-
WHERE user_id = ? AND namespace = ? AND key LIKE ? ESCAPE '\\' AND updated_at <= ?`;
|
|
1975
|
-
const CLEANUP_KEY_SQL = `DELETE FROM client_state
|
|
1976
|
-
WHERE user_id = ? AND namespace = ? AND key = ? AND updated_at <= ?`;
|
|
1977
|
-
const buildStatements = () => [
|
|
1978
|
-
...cleanups.map((c) => typeof c.key === "string" ? this._db.prepare(CLEANUP_KEY_SQL).bind(userId, c.namespace, c.key, c.updatedAt) : this._db.prepare(CLEANUP_PREFIX_SQL).bind(userId, c.namespace, `${escapeLikePrefix(c.keyPrefix)}%`, c.updatedAt)),
|
|
1979
|
-
...entries.map(
|
|
1980
|
-
(entry) => this._db.prepare(UPSERT_SQL).bind(userId, entry.namespace, entry.key, entry.value, entry.updatedAt)
|
|
1981
|
-
)
|
|
1982
|
-
];
|
|
1983
|
-
let results;
|
|
1984
|
-
if (typeof this._db.batch === "function") {
|
|
1985
|
-
results = await this._db.batch(buildStatements());
|
|
1986
|
-
} else {
|
|
1987
|
-
results = [];
|
|
1988
|
-
for (const stmt of buildStatements()) {
|
|
1989
|
-
results.push(await stmt.run());
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
const outcomes = results.slice(cleanups.length).map((res) => res.meta.changes > 0);
|
|
1993
|
-
let upserted = 0;
|
|
1994
|
-
let skipped = 0;
|
|
1995
|
-
for (const wrote of outcomes) {
|
|
1996
|
-
if (wrote) upserted++;
|
|
1997
|
-
else skipped++;
|
|
1998
|
-
}
|
|
1999
|
-
return { upserted, skipped, outcomes };
|
|
2000
|
-
}
|
|
2001
|
-
/**
|
|
2002
|
-
* All entries of one namespace (values still encrypted).
|
|
2003
|
-
*
|
|
2004
|
-
* @param {string} userId
|
|
2005
|
-
* @param {string} namespace
|
|
2006
|
-
* @returns {Promise<Array<{ namespace: string, key: string, value: string, updated_at: number }>>}
|
|
2007
|
-
*/
|
|
2008
|
-
async getClientState(userId, namespace) {
|
|
2009
|
-
const res = await this._db.prepare(
|
|
2010
|
-
`SELECT namespace, key, value, updated_at
|
|
2011
|
-
FROM client_state
|
|
2012
|
-
WHERE user_id = ? AND namespace = ?
|
|
2013
|
-
ORDER BY key ASC`
|
|
2014
|
-
).bind(userId, namespace).all();
|
|
2015
|
-
return res.results || [];
|
|
2016
|
-
}
|
|
2017
|
-
/**
|
|
2018
|
-
* Wipe every entry of this user.
|
|
2019
|
-
*
|
|
2020
|
-
* @param {string} userId
|
|
2021
|
-
* @returns {Promise<number>} rows deleted
|
|
2022
|
-
*/
|
|
2023
|
-
async clearClientState(userId) {
|
|
2024
|
-
const res = await this._db.prepare("DELETE FROM client_state WHERE user_id = ?").bind(userId).run();
|
|
2025
|
-
return res.meta.changes || 0;
|
|
2026
|
-
}
|
|
2027
|
-
};
|
|
2028
|
-
function createD1Adapter(db) {
|
|
2029
|
-
if (!db || typeof db.prepare !== "function") {
|
|
2030
|
-
throw new Error("[amsg-server] createD1Adapter requires a D1 database binding (env.DB)");
|
|
2031
|
-
}
|
|
2032
|
-
return new D1Adapter(db);
|
|
2033
|
-
}
|
|
2034
|
-
|
|
2035
|
-
// src/server/lib/constant-time.js
|
|
2036
|
-
async function constantTimeEqual(a, b) {
|
|
2037
|
-
const enc = new TextEncoder();
|
|
2038
|
-
const keyBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
|
|
2039
|
-
const key = await globalThis.crypto.subtle.importKey(
|
|
2040
|
-
"raw",
|
|
2041
|
-
keyBytes,
|
|
2042
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
2043
|
-
false,
|
|
2044
|
-
["sign"]
|
|
2045
|
-
);
|
|
2046
|
-
const da = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(String(a))));
|
|
2047
|
-
const db = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(String(b))));
|
|
2048
|
-
let diff = 0;
|
|
2049
|
-
for (let i = 0; i < da.length; i++) {
|
|
2050
|
-
diff |= da[i] ^ db[i];
|
|
2051
|
-
}
|
|
2052
|
-
return diff === 0;
|
|
2053
|
-
}
|
|
2054
|
-
|
|
2055
|
-
// src/server/tenant/single-user-context.js
|
|
2056
|
-
function createSingleUserContextManager({ db, masterKey, serverToken } = {}) {
|
|
2057
|
-
if (!db) throw new Error("[amsg-server single-user] db (adapter) is required");
|
|
2058
|
-
if (!masterKey) throw new Error("[amsg-server single-user] masterKey is required");
|
|
2059
|
-
const token = String(serverToken || "").trim();
|
|
2060
|
-
async function isAuthorized(headers) {
|
|
2061
|
-
if (!token) return true;
|
|
2062
|
-
const provided = getHeader(headers, "x-client-token");
|
|
2063
|
-
if (!provided) return false;
|
|
2064
|
-
return constantTimeEqual(provided, token);
|
|
2065
|
-
}
|
|
2066
|
-
async function resolveTenant(headers) {
|
|
2067
|
-
if (!await isAuthorized(headers)) {
|
|
2068
|
-
return {
|
|
2069
|
-
ok: false,
|
|
2070
|
-
error: {
|
|
2071
|
-
status: 401,
|
|
2072
|
-
body: { success: false, error: { code: "INVALID_CLIENT_TOKEN", message: "\u5171\u4EAB\u5BC6\u94A5\u65E0\u6548\u6216\u7F3A\u5931" } }
|
|
2073
|
-
}
|
|
2074
|
-
};
|
|
2075
|
-
}
|
|
2076
|
-
return {
|
|
2077
|
-
ok: true,
|
|
2078
|
-
context: { tenantId: "single", tokenType: "tenant", db, masterKey }
|
|
2079
|
-
};
|
|
2080
|
-
}
|
|
2081
|
-
async function initializeTenant() {
|
|
2082
|
-
const schema = await db.initSchema();
|
|
2083
|
-
return { tenantId: "single", schema };
|
|
2084
|
-
}
|
|
2085
|
-
return { resolveTenant, initializeTenant };
|
|
2086
|
-
}
|
|
2087
|
-
|
|
2088
|
-
// src/server/handlers/single-user-init.js
|
|
2089
|
-
function createSingleUserInitHandler(ctx) {
|
|
2090
|
-
async function POST(headers) {
|
|
2091
|
-
const auth = await ctx.tenantManager.resolveTenant(headers || {});
|
|
2092
|
-
if (!auth.ok) {
|
|
2093
|
-
return auth.error;
|
|
2094
|
-
}
|
|
2095
|
-
try {
|
|
2096
|
-
const result = await ctx.tenantManager.initializeTenant();
|
|
2097
|
-
return {
|
|
2098
|
-
status: 200,
|
|
2099
|
-
body: { success: true, data: { tenantId: result.tenantId, schema: result.schema } }
|
|
2100
|
-
};
|
|
2101
|
-
} catch (error) {
|
|
2102
|
-
return {
|
|
2103
|
-
status: 500,
|
|
2104
|
-
body: { success: false, error: { code: "INIT_FAILED", message: error.message } }
|
|
2105
|
-
};
|
|
2106
|
-
}
|
|
2107
|
-
}
|
|
2108
|
-
return { POST };
|
|
2109
|
-
}
|
|
2110
|
-
|
|
2111
|
-
// src/server/handlers/vapid-public-key.js
|
|
2112
|
-
function createVapidPublicKeyHandler(ctx) {
|
|
2113
|
-
async function GET(url, headers) {
|
|
2114
|
-
const effectiveHeaders = headers || url || {};
|
|
2115
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
|
|
2116
|
-
if (!tenantResult.ok) {
|
|
2117
|
-
return tenantResult.error;
|
|
2118
|
-
}
|
|
2119
|
-
const publicKey = ctx.vapid && ctx.vapid.publicKey;
|
|
2120
|
-
if (!publicKey) {
|
|
2121
|
-
return {
|
|
2122
|
-
status: 503,
|
|
2123
|
-
body: {
|
|
2124
|
-
success: false,
|
|
2125
|
-
error: {
|
|
2126
|
-
code: "VAPID_NOT_CONFIGURED",
|
|
2127
|
-
message: "VAPID \u516C\u94A5\u672A\u914D\u7F6E\uFF1A\u8BF7\u4E3A\u672C Worker \u8BBE\u7F6E VAPID_PUBLIC_KEY"
|
|
2128
|
-
}
|
|
2129
|
-
}
|
|
2130
|
-
};
|
|
2131
|
-
}
|
|
2132
|
-
return {
|
|
2133
|
-
status: 200,
|
|
2134
|
-
body: { success: true, publicKey }
|
|
2135
|
-
};
|
|
2136
|
-
}
|
|
2137
|
-
return { GET };
|
|
2138
|
-
}
|
|
2139
|
-
|
|
2140
|
-
// src/server/handlers/client-state.js
|
|
2141
|
-
var MAX_STATE_ENTRIES_PER_REQUEST = MAX_STATE_ENTRIES_PER_BATCH;
|
|
2142
|
-
function err(status, code, message, details) {
|
|
2143
|
-
const error = details === void 0 ? { code, message } : { code, message, details };
|
|
2144
|
-
return { status, body: { success: false, error } };
|
|
2145
|
-
}
|
|
2146
|
-
function requireUserId(headers) {
|
|
2147
|
-
const userId = getHeader(headers, "x-user-id");
|
|
2148
|
-
if (!userId) return { error: err(400, "USER_ID_REQUIRED", "\u7F3A\u5C11\u7528\u6237\u6807\u8BC6\u7B26") };
|
|
2149
|
-
if (!isValidUUIDv4(userId)) return { error: err(400, "INVALID_USER_ID_FORMAT", "X-User-Id \u5FC5\u987B\u662F UUID v4 \u683C\u5F0F") };
|
|
2150
|
-
return { userId };
|
|
2151
|
-
}
|
|
2152
|
-
function rejectEntry(entry, index, code, message, extra) {
|
|
2153
|
-
const rejection = { index, code, message, ...extra || {} };
|
|
2154
|
-
if (entry && typeof entry === "object") {
|
|
2155
|
-
if (typeof entry.namespace === "string") rejection.namespace = entry.namespace;
|
|
2156
|
-
if (typeof entry.key === "string") rejection.key = entry.key;
|
|
2157
|
-
}
|
|
2158
|
-
return rejection;
|
|
2159
|
-
}
|
|
2160
|
-
function validateEntry(entry, index, maxValueBytes) {
|
|
2161
|
-
if (!isPlainObject(entry)) {
|
|
2162
|
-
return rejectEntry(entry, index, "INVALID_STATE_ENTRY", `entries[${index}] \u5FC5\u987B\u662F\u5BF9\u8C61`);
|
|
2163
|
-
}
|
|
2164
|
-
if (typeof entry.namespace !== "string" || !entry.namespace.trim() || entry.namespace.length > MAX_NAMESPACE_CHARS) {
|
|
2165
|
-
return rejectEntry(entry, index, "INVALID_STATE_NAMESPACE", `entries[${index}].namespace \u5FC5\u987B\u662F 1-${MAX_NAMESPACE_CHARS} \u5B57\u7B26\u7684\u5B57\u7B26\u4E32`);
|
|
2166
|
-
}
|
|
2167
|
-
if (INTERNAL_STATE_CHAR_RE.test(entry.namespace)) {
|
|
2168
|
-
return rejectEntry(entry, index, "INVALID_STATE_NAMESPACE", `entries[${index}].namespace \u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26\uFF08\\u0000-\\u001f \u4E3A\u5E93\u5185\u90E8\u4FDD\u7559\uFF09`);
|
|
2169
|
-
}
|
|
2170
|
-
if (typeof entry.key !== "string" || !entry.key.trim() || entry.key.length > MAX_KEY_CHARS) {
|
|
2171
|
-
return rejectEntry(entry, index, "INVALID_STATE_KEY", `entries[${index}].key \u5FC5\u987B\u662F 1-${MAX_KEY_CHARS} \u5B57\u7B26\u7684\u5B57\u7B26\u4E32`);
|
|
2172
|
-
}
|
|
2173
|
-
if (INTERNAL_STATE_CHAR_RE.test(entry.key)) {
|
|
2174
|
-
return rejectEntry(entry, index, "INVALID_STATE_KEY", `entries[${index}].key \u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26\uFF08\\u0000-\\u001f \u4E3A\u5E93\u5185\u90E8\u4FDD\u7559\uFF09`);
|
|
2175
|
-
}
|
|
2176
|
-
if (typeof entry.value !== "string") {
|
|
2177
|
-
return rejectEntry(entry, index, "INVALID_STATE_VALUE", `entries[${index}].value \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\uFF08\u5BBF\u4E3B\u81EA\u884C\u5E8F\u5217\u5316\uFF09`);
|
|
2178
|
-
}
|
|
2179
|
-
const bytes = stateValueBytes(entry.value);
|
|
2180
|
-
if (bytes > maxValueBytes) {
|
|
2181
|
-
return rejectEntry(entry, index, "STATE_VALUE_TOO_LARGE", `entries[${index}].value \u8D85\u8FC7\u5355\u6761\u603B\u4E0A\u9650`, { bytes, maxBytes: maxValueBytes });
|
|
2182
|
-
}
|
|
2183
|
-
if (!Number.isInteger(entry.updatedAt) || entry.updatedAt <= 0) {
|
|
2184
|
-
return rejectEntry(entry, index, "INVALID_STATE_UPDATED_AT", `entries[${index}].updatedAt \u5FC5\u987B\u662F\u6B63\u6574\u6570\uFF08epoch \u6BEB\u79D2\uFF09`);
|
|
2185
|
-
}
|
|
2186
|
-
return null;
|
|
2187
|
-
}
|
|
2188
|
-
function createClientStateHandler(ctx) {
|
|
2189
|
-
async function PUT(headers, body) {
|
|
2190
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers);
|
|
2191
|
-
if (!tenantResult.ok) return tenantResult.error;
|
|
2192
|
-
const { db, masterKey } = tenantResult.context;
|
|
2193
|
-
if (getHeader(headers, "x-payload-encrypted") !== "true") {
|
|
2194
|
-
return err(400, "ENCRYPTION_REQUIRED", "\u8BF7\u6C42\u4F53\u5FC5\u987B\u52A0\u5BC6");
|
|
2195
|
-
}
|
|
2196
|
-
const gate = requireUserId(headers);
|
|
2197
|
-
if (gate.error) return gate.error;
|
|
2198
|
-
const { userId } = gate;
|
|
2199
|
-
if (getHeader(headers, "x-encryption-version") !== "1") {
|
|
2200
|
-
return err(400, "UNSUPPORTED_ENCRYPTION_VERSION", "\u52A0\u5BC6\u7248\u672C\u4E0D\u652F\u6301");
|
|
2201
|
-
}
|
|
2202
|
-
const parsedBody = parseEncryptedBody(body);
|
|
2203
|
-
if (!parsedBody.ok) return { status: 400, body: { success: false, error: parsedBody.error } };
|
|
2204
|
-
const userKey = await deriveUserEncryptionKey(userId, masterKey);
|
|
2205
|
-
let payload;
|
|
2206
|
-
try {
|
|
2207
|
-
payload = await decryptPayload(parsedBody.data, userKey);
|
|
2208
|
-
} catch (error) {
|
|
2209
|
-
if (error instanceof SyntaxError) {
|
|
2210
|
-
return err(400, "INVALID_PAYLOAD_FORMAT", "\u89E3\u5BC6\u540E\u7684\u6570\u636E\u4E0D\u662F\u6709\u6548 JSON");
|
|
2211
|
-
}
|
|
2212
|
-
return err(400, "DECRYPTION_FAILED", "\u8BF7\u6C42\u4F53\u89E3\u5BC6\u5931\u8D25");
|
|
2213
|
-
}
|
|
2214
|
-
if (!isPlainObject(payload)) return err(400, "INVALID_PAYLOAD_FORMAT", "\u89E3\u5BC6\u540E\u7684\u6570\u636E\u5FC5\u987B\u662F JSON \u5BF9\u8C61");
|
|
2215
|
-
const entries = payload.entries;
|
|
2216
|
-
if (!Array.isArray(entries) || entries.length === 0) {
|
|
2217
|
-
return err(400, "INVALID_STATE_ENTRIES", "entries \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4");
|
|
2218
|
-
}
|
|
2219
|
-
if (entries.length > MAX_STATE_ENTRIES_PER_REQUEST) {
|
|
2220
|
-
return err(400, "TOO_MANY_STATE_ENTRIES", `\u5355\u6B21\u6700\u591A ${MAX_STATE_ENTRIES_PER_REQUEST} \u6761`, { count: entries.length });
|
|
2221
|
-
}
|
|
2222
|
-
const maxValueBytes = Number.isInteger(ctx.maxStateValueBytes) && ctx.maxStateValueBytes > 0 ? ctx.maxStateValueBytes : DEFAULT_MAX_STATE_VALUE_BYTES;
|
|
2223
|
-
const accepted = [];
|
|
2224
|
-
const rejected = [];
|
|
2225
|
-
for (let i = 0; i < entries.length; i++) {
|
|
2226
|
-
const rejection = validateEntry(entries[i], i, maxValueBytes);
|
|
2227
|
-
if (rejection) rejected.push(rejection);
|
|
2228
|
-
else accepted.push(entries[i]);
|
|
2229
|
-
}
|
|
2230
|
-
if (typeof db.upsertClientState !== "function") {
|
|
2231
|
-
return err(501, "CLIENT_STATE_NOT_SUPPORTED", "\u5F53\u524D\u6570\u636E\u5E93\u9002\u914D\u5668\u4E0D\u652F\u6301 client_state");
|
|
2232
|
-
}
|
|
2233
|
-
const { upserted, skipped } = await writeClientStateEntries({ db, userId, userKey, entries: accepted });
|
|
2234
|
-
const data = { upserted, skipped };
|
|
2235
|
-
if (rejected.length > 0) data.rejected = rejected;
|
|
2236
|
-
return { status: 200, body: { success: true, data } };
|
|
2237
|
-
}
|
|
2238
|
-
async function GET(url, headers) {
|
|
2239
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers);
|
|
2240
|
-
if (!tenantResult.ok) return tenantResult.error;
|
|
2241
|
-
const { db, masterKey } = tenantResult.context;
|
|
2242
|
-
const gate = requireUserId(headers);
|
|
2243
|
-
if (gate.error) return gate.error;
|
|
2244
|
-
const { userId } = gate;
|
|
2245
|
-
const namespace = new URL(url, "https://dummy").searchParams.get("namespace") || "";
|
|
2246
|
-
if (!namespace.trim()) return err(400, "NAMESPACE_REQUIRED", "\u5FC5\u987B\u63D0\u4F9B namespace \u67E5\u8BE2\u53C2\u6570");
|
|
2247
|
-
if (INTERNAL_STATE_CHAR_RE.test(namespace)) {
|
|
2248
|
-
return err(400, "INVALID_STATE_NAMESPACE", "namespace \u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26\uFF08\\u0000-\\u001f \u4E3A\u5E93\u5185\u90E8\u4FDD\u7559\uFF09");
|
|
2249
|
-
}
|
|
2250
|
-
if (typeof db.getClientState !== "function") {
|
|
2251
|
-
return err(501, "CLIENT_STATE_NOT_SUPPORTED", "\u5F53\u524D\u6570\u636E\u5E93\u9002\u914D\u5668\u4E0D\u652F\u6301 client_state");
|
|
2252
|
-
}
|
|
2253
|
-
const userKey = await deriveUserEncryptionKey(userId, masterKey);
|
|
2254
|
-
const rows = await db.getClientState(userId, namespace);
|
|
2255
|
-
const decrypted = await resolveClientStateEntries(
|
|
2256
|
-
rows,
|
|
2257
|
-
() => db.getClientState(userId, chunkNamespaceFor(namespace)),
|
|
2258
|
-
(value) => decryptFromStorage(value, userKey)
|
|
2259
|
-
);
|
|
2260
|
-
const encryptedResponse = await encryptPayload({ namespace, entries: decrypted }, userKey);
|
|
2261
|
-
return { status: 200, body: { success: true, encrypted: true, version: 1, data: encryptedResponse } };
|
|
2262
|
-
}
|
|
2263
|
-
async function DELETE(url, headers) {
|
|
2264
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(headers);
|
|
2265
|
-
if (!tenantResult.ok) return tenantResult.error;
|
|
2266
|
-
const { db } = tenantResult.context;
|
|
2267
|
-
const gate = requireUserId(headers);
|
|
2268
|
-
if (gate.error) return gate.error;
|
|
2269
|
-
const { userId } = gate;
|
|
2270
|
-
if (typeof db.clearClientState !== "function") {
|
|
2271
|
-
return err(501, "CLIENT_STATE_NOT_SUPPORTED", "\u5F53\u524D\u6570\u636E\u5E93\u9002\u914D\u5668\u4E0D\u652F\u6301 client_state");
|
|
2272
|
-
}
|
|
2273
|
-
const deleted = await db.clearClientState(userId);
|
|
2274
|
-
return { status: 200, body: { success: true, data: { deleted } } };
|
|
2275
|
-
}
|
|
2276
|
-
return { PUT, GET, DELETE };
|
|
2277
|
-
}
|
|
2278
|
-
|
|
2279
|
-
// src/server/lib/version.js
|
|
2280
|
-
var SERVER_VERSION = true ? "2.6.0-next.8" : "0.0.0-dev";
|
|
2281
|
-
|
|
2282
|
-
// src/server/handlers/capabilities.js
|
|
2283
|
-
var SERVER_FEATURES = Object.freeze([
|
|
2284
|
-
"client-state",
|
|
2285
|
-
"client-state-chunking",
|
|
2286
|
-
"client-state-partial-failure",
|
|
2287
|
-
"agentic-hooks",
|
|
2288
|
-
"agentic-scratch",
|
|
2289
|
-
"agentic-write-state",
|
|
2290
|
-
"agentic-fire-tools",
|
|
2291
|
-
"vapid-public-key"
|
|
2292
|
-
]);
|
|
2293
|
-
function createCapabilitiesHandler(ctx) {
|
|
2294
|
-
async function GET(url, headers) {
|
|
2295
|
-
const effectiveHeaders = headers || url || {};
|
|
2296
|
-
const tenantResult = await ctx.tenantManager.resolveTenant(effectiveHeaders);
|
|
2297
|
-
if (!tenantResult.ok) {
|
|
2298
|
-
return tenantResult.error;
|
|
2299
|
-
}
|
|
2300
|
-
return {
|
|
2301
|
-
status: 200,
|
|
2302
|
-
body: { success: true, serverVersion: SERVER_VERSION, features: [...SERVER_FEATURES] }
|
|
2303
|
-
};
|
|
2304
|
-
}
|
|
2305
|
-
return { GET };
|
|
2306
|
-
}
|
|
2307
|
-
|
|
2308
|
-
// src/server/single-user.js
|
|
2309
|
-
function createSingleUserServer(config) {
|
|
2310
|
-
if (!config || !config.db) throw new Error("[amsg-server single-user] config.db is required");
|
|
2311
|
-
if (!config.masterKey) throw new Error("[amsg-server single-user] config.masterKey is required");
|
|
2312
|
-
const vapid = config.vapid || {};
|
|
2313
|
-
const tenantManager = createSingleUserContextManager({
|
|
2314
|
-
db: config.db,
|
|
2315
|
-
masterKey: config.masterKey,
|
|
2316
|
-
serverToken: config.serverToken
|
|
2317
|
-
});
|
|
2318
|
-
const ctx = {
|
|
2319
|
-
vapid: {
|
|
2320
|
-
email: vapid.email || "",
|
|
2321
|
-
publicKey: vapid.publicKey || "",
|
|
2322
|
-
privateKey: vapid.privateKey || ""
|
|
2323
|
-
},
|
|
2324
|
-
webpush: config.webpush || null,
|
|
2325
|
-
tenantManager,
|
|
2326
|
-
// Fire-time hooks (optional): the in-server instant path fires through
|
|
2327
|
-
// processMessagesByUuid with this ctx, so instant-type tasks can take
|
|
2328
|
-
// the agentic path too.
|
|
2329
|
-
hooks: config.hooks || null,
|
|
2330
|
-
maxToolIterations: config.maxToolIterations,
|
|
2331
|
-
totalTimeoutMs: config.totalTimeoutMs,
|
|
2332
|
-
maxStateValueBytes: config.maxStateValueBytes
|
|
2333
|
-
};
|
|
2334
|
-
return {
|
|
2335
|
-
ctx,
|
|
2336
|
-
handlers: {
|
|
2337
|
-
init: createSingleUserInitHandler(ctx),
|
|
2338
|
-
getUserKey: createGetUserKeyHandler(ctx),
|
|
2339
|
-
scheduleMessage: createScheduleMessageHandler(ctx),
|
|
2340
|
-
updateMessage: createUpdateMessageHandler(ctx),
|
|
2341
|
-
cancelMessage: createCancelMessageHandler(ctx),
|
|
2342
|
-
messages: createMessagesHandler(ctx),
|
|
2343
|
-
vapidPublicKey: createVapidPublicKeyHandler(ctx),
|
|
2344
|
-
clientState: createClientStateHandler(ctx),
|
|
2345
|
-
capabilities: createCapabilitiesHandler(ctx)
|
|
2346
|
-
}
|
|
2347
|
-
};
|
|
2348
|
-
}
|
|
2349
|
-
|
|
2350
|
-
// src/server/lib/webpush-webcrypto.js
|
|
2351
|
-
|
|
2352
|
-
var KEY_INFO_PREFIX = utf8("WebPush: info\0");
|
|
2353
|
-
var CEK_INFO = utf8("Content-Encoding: aes128gcm\0");
|
|
2354
|
-
var NONCE_INFO = utf8("Content-Encoding: nonce\0");
|
|
2355
|
-
var VAPID_DEFAULT_TTL = 60;
|
|
2356
|
-
var VAPID_TOKEN_LIFETIME = 12 * 3600;
|
|
2357
|
-
var RECORD_SIZE = 4096;
|
|
2358
|
-
var WEB_PUSH_MAX_BODY_BYTES = 4096;
|
|
2359
|
-
var WEB_PUSH_ENCRYPTION_OVERHEAD_BYTES = 16 + 4 + 1 + 65 + 1 + 16;
|
|
2360
|
-
var MAX_PUSH_PAYLOAD_BYTES = WEB_PUSH_MAX_BODY_BYTES - WEB_PUSH_ENCRYPTION_OVERHEAD_BYTES;
|
|
2361
|
-
var payloadEncoder = new TextEncoder();
|
|
2362
|
-
function measurePushPayload(payload) {
|
|
2363
|
-
const bytes = payloadEncoder.encode(typeof payload === "string" ? payload : String(payload)).length;
|
|
2364
|
-
return {
|
|
2365
|
-
bytes,
|
|
2366
|
-
maxBytes: MAX_PUSH_PAYLOAD_BYTES,
|
|
2367
|
-
remainingBytes: MAX_PUSH_PAYLOAD_BYTES - bytes,
|
|
2368
|
-
withinLimit: bytes <= MAX_PUSH_PAYLOAD_BYTES
|
|
2369
|
-
};
|
|
2370
|
-
}
|
|
2371
|
-
async function sendWebPush({ subscription, payload, vapid, ttl, fetch: fetchImpl }) {
|
|
2372
|
-
if (!subscription || typeof subscription.endpoint !== "string") {
|
|
2373
|
-
throw new Error("sendWebPush: invalid subscription");
|
|
2374
|
-
}
|
|
2375
|
-
if (typeof payload !== "string") {
|
|
2376
|
-
throw new Error("sendWebPush: payload must be a string");
|
|
2377
|
-
}
|
|
2378
|
-
if (!vapid || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
|
|
2379
|
-
throw new Error("VAPID_CONFIG_MISSING");
|
|
2380
|
-
}
|
|
2381
|
-
const subscriptionKeys = subscription.keys || {};
|
|
2382
|
-
if (typeof subscriptionKeys.p256dh !== "string" || typeof subscriptionKeys.auth !== "string") {
|
|
2383
|
-
throw new Error("sendWebPush: subscription.keys.p256dh and .auth are required");
|
|
2384
|
-
}
|
|
2385
|
-
const size = measurePushPayload(payload);
|
|
2386
|
-
if (!size.withinLimit) {
|
|
2387
|
-
const err2 = new Error(
|
|
2388
|
-
`sendWebPush: payload is ${size.bytes} bytes, over the ${MAX_PUSH_PAYLOAD_BYTES}-byte limit (push services cap the encrypted body at ${WEB_PUSH_MAX_BODY_BYTES} bytes; aes128gcm adds ${WEB_PUSH_ENCRYPTION_OVERHEAD_BYTES} bytes)`
|
|
2389
|
-
);
|
|
2390
|
-
err2.code = "PUSH_PAYLOAD_TOO_LARGE";
|
|
2391
|
-
err2.bytes = size.bytes;
|
|
2392
|
-
err2.maxBytes = MAX_PUSH_PAYLOAD_BYTES;
|
|
2393
|
-
throw err2;
|
|
2394
|
-
}
|
|
2395
|
-
const encryptedBody = await encryptPushPayload({
|
|
2396
|
-
plaintext: utf8(payload),
|
|
2397
|
-
uaPublicKey: _amsgshared.base64UrlToBytes.call(void 0, subscriptionKeys.p256dh),
|
|
2398
|
-
authSecret: _amsgshared.base64UrlToBytes.call(void 0, subscriptionKeys.auth)
|
|
2399
|
-
});
|
|
2400
|
-
const jwt = await buildVapidJwt({
|
|
2401
|
-
audience: originOf(subscription.endpoint),
|
|
2402
|
-
subject: _amsgshared.normalizeVapidSubject.call(void 0, vapid.email),
|
|
2403
|
-
publicKey: vapid.publicKey,
|
|
2404
|
-
privateKey: vapid.privateKey
|
|
2405
|
-
});
|
|
2406
|
-
const fetchFn = fetchImpl || globalThis.fetch;
|
|
2407
|
-
if (typeof fetchFn !== "function") {
|
|
2408
|
-
throw new Error("sendWebPush: no fetch implementation available");
|
|
2409
|
-
}
|
|
2410
|
-
const res = await fetchFn(subscription.endpoint, {
|
|
2411
|
-
method: "POST",
|
|
2412
|
-
headers: {
|
|
2413
|
-
"Content-Type": "application/octet-stream",
|
|
2414
|
-
"Content-Encoding": "aes128gcm",
|
|
2415
|
-
"TTL": String(Number.isFinite(ttl) ? ttl : VAPID_DEFAULT_TTL),
|
|
2416
|
-
"Authorization": `vapid t=${jwt}, k=${vapid.publicKey}`
|
|
2417
|
-
},
|
|
2418
|
-
body: encryptedBody
|
|
2419
|
-
});
|
|
2420
|
-
if (!res.ok) {
|
|
2421
|
-
const text = await safeReadText(res);
|
|
2422
|
-
const err2 = new Error(
|
|
2423
|
-
`Web Push delivery failed: ${res.status} ${res.statusText || ""}${text ? ` \u2014 ${text}` : ""}`
|
|
2424
|
-
);
|
|
2425
|
-
err2.code = "PUSH_SEND_FAILED";
|
|
2426
|
-
err2.statusCode = res.status;
|
|
2427
|
-
throw err2;
|
|
2428
|
-
}
|
|
2429
|
-
return {
|
|
2430
|
-
statusCode: res.status,
|
|
2431
|
-
body: await safeReadText(res),
|
|
2432
|
-
headers: res.headers
|
|
2433
|
-
};
|
|
2434
|
-
}
|
|
2435
|
-
async function encryptPushPayload({ plaintext, uaPublicKey, authSecret }) {
|
|
2436
|
-
const asKeyPair = await globalThis.crypto.subtle.generateKey(
|
|
2437
|
-
{ name: "ECDH", namedCurve: "P-256" },
|
|
2438
|
-
true,
|
|
2439
|
-
["deriveBits"]
|
|
2440
|
-
);
|
|
2441
|
-
const asPublicRaw = new Uint8Array(
|
|
2442
|
-
await globalThis.crypto.subtle.exportKey("raw", asKeyPair.publicKey)
|
|
2443
|
-
);
|
|
2444
|
-
const uaPublicCryptoKey = await globalThis.crypto.subtle.importKey(
|
|
2445
|
-
"raw",
|
|
2446
|
-
uaPublicKey,
|
|
2447
|
-
{ name: "ECDH", namedCurve: "P-256" },
|
|
2448
|
-
false,
|
|
2449
|
-
[]
|
|
2450
|
-
);
|
|
2451
|
-
const ecdhSecret = new Uint8Array(
|
|
2452
|
-
await globalThis.crypto.subtle.deriveBits(
|
|
2453
|
-
{ name: "ECDH", public: uaPublicCryptoKey },
|
|
2454
|
-
asKeyPair.privateKey,
|
|
2455
|
-
256
|
|
2456
|
-
)
|
|
2457
|
-
);
|
|
2458
|
-
const keyInfo = _amsgshared.concatBytes.call(void 0, KEY_INFO_PREFIX, uaPublicKey, asPublicRaw);
|
|
2459
|
-
const ikm = await hkdfSha256(authSecret, ecdhSecret, keyInfo, 32);
|
|
2460
|
-
const salt = randomBytes(16);
|
|
2461
|
-
const cekBytes = await hkdfSha256(salt, ikm, CEK_INFO, 16);
|
|
2462
|
-
const cek = await globalThis.crypto.subtle.importKey(
|
|
2463
|
-
"raw",
|
|
2464
|
-
cekBytes,
|
|
2465
|
-
{ name: "AES-GCM" },
|
|
2466
|
-
false,
|
|
2467
|
-
["encrypt"]
|
|
2468
|
-
);
|
|
2469
|
-
const nonce = await hkdfSha256(salt, ikm, NONCE_INFO, 12);
|
|
2470
|
-
const padded = _amsgshared.concatBytes.call(void 0, plaintext, new Uint8Array([2]));
|
|
2471
|
-
const ciphertext = new Uint8Array(
|
|
2472
|
-
await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, cek, padded)
|
|
2473
|
-
);
|
|
2474
|
-
const header = new Uint8Array(16 + 4 + 1 + asPublicRaw.byteLength);
|
|
2475
|
-
header.set(salt, 0);
|
|
2476
|
-
writeUint32BE(header, 16, RECORD_SIZE);
|
|
2477
|
-
header[20] = asPublicRaw.byteLength;
|
|
2478
|
-
header.set(asPublicRaw, 21);
|
|
2479
|
-
return _amsgshared.concatBytes.call(void 0, header, ciphertext);
|
|
2480
|
-
}
|
|
2481
|
-
async function hkdfSha256(salt, ikm, info, length) {
|
|
2482
|
-
const baseKey = await globalThis.crypto.subtle.importKey(
|
|
2483
|
-
"raw",
|
|
2484
|
-
_amsgshared.toUint8.call(void 0, ikm),
|
|
2485
|
-
{ name: "HKDF" },
|
|
2486
|
-
false,
|
|
2487
|
-
["deriveBits"]
|
|
2488
|
-
);
|
|
2489
|
-
const bits = await globalThis.crypto.subtle.deriveBits(
|
|
2490
|
-
{
|
|
2491
|
-
name: "HKDF",
|
|
2492
|
-
hash: "SHA-256",
|
|
2493
|
-
salt: _amsgshared.toUint8.call(void 0, salt),
|
|
2494
|
-
info: _amsgshared.toUint8.call(void 0, info)
|
|
2495
|
-
},
|
|
2496
|
-
baseKey,
|
|
2497
|
-
length * 8
|
|
2498
|
-
);
|
|
2499
|
-
return new Uint8Array(bits);
|
|
2500
|
-
}
|
|
2501
|
-
async function buildVapidJwt({ audience, subject, publicKey, privateKey }) {
|
|
2502
|
-
const header = jsonToBase64Url({ typ: "JWT", alg: "ES256" });
|
|
2503
|
-
const payload = jsonToBase64Url({
|
|
2504
|
-
aud: audience,
|
|
2505
|
-
exp: Math.floor(Date.now() / 1e3) + VAPID_TOKEN_LIFETIME,
|
|
2506
|
-
sub: subject
|
|
2507
|
-
});
|
|
2508
|
-
const signingInput = utf8(`${header}.${payload}`);
|
|
2509
|
-
const pubBytes = _amsgshared.base64UrlToBytes.call(void 0, publicKey);
|
|
2510
|
-
const privBytes = _amsgshared.base64UrlToBytes.call(void 0, privateKey);
|
|
2511
|
-
if (pubBytes.length !== 65 || pubBytes[0] !== 4) {
|
|
2512
|
-
throw new Error("VAPID publicKey must be a 65-byte uncompressed P-256 point (base64url).");
|
|
2513
|
-
}
|
|
2514
|
-
if (privBytes.length !== 32) {
|
|
2515
|
-
throw new Error("VAPID privateKey must be a 32-byte scalar (base64url).");
|
|
2516
|
-
}
|
|
2517
|
-
const jwk = {
|
|
2518
|
-
kty: "EC",
|
|
2519
|
-
crv: "P-256",
|
|
2520
|
-
d: bytesToBase64Url(privBytes),
|
|
2521
|
-
x: bytesToBase64Url(pubBytes.subarray(1, 33)),
|
|
2522
|
-
y: bytesToBase64Url(pubBytes.subarray(33, 65)),
|
|
2523
|
-
ext: true
|
|
2524
|
-
};
|
|
2525
|
-
const key = await globalThis.crypto.subtle.importKey(
|
|
2526
|
-
"jwk",
|
|
2527
|
-
jwk,
|
|
2528
|
-
{ name: "ECDSA", namedCurve: "P-256" },
|
|
2529
|
-
false,
|
|
2530
|
-
["sign"]
|
|
2531
|
-
);
|
|
2532
|
-
const sig = await globalThis.crypto.subtle.sign(
|
|
2533
|
-
{ name: "ECDSA", hash: "SHA-256" },
|
|
2534
|
-
key,
|
|
2535
|
-
signingInput
|
|
2536
|
-
);
|
|
2537
|
-
return `${header}.${payload}.${bytesToBase64Url(sig)}`;
|
|
2538
|
-
}
|
|
2539
|
-
function originOf(endpoint) {
|
|
2540
|
-
return new URL(endpoint).origin;
|
|
2541
|
-
}
|
|
2542
|
-
function writeUint32BE(buf, offset, value) {
|
|
2543
|
-
buf[offset] = value >>> 24 & 255;
|
|
2544
|
-
buf[offset + 1] = value >>> 16 & 255;
|
|
2545
|
-
buf[offset + 2] = value >>> 8 & 255;
|
|
2546
|
-
buf[offset + 3] = value & 255;
|
|
2547
|
-
}
|
|
2548
|
-
async function safeReadText(res) {
|
|
2549
|
-
try {
|
|
2550
|
-
return await res.text();
|
|
2551
|
-
} catch (e4) {
|
|
2552
|
-
return "";
|
|
2553
|
-
}
|
|
2554
|
-
}
|
|
2555
|
-
var SCHEDULED_DEFAULT_TTL = 2419200;
|
|
2556
|
-
function createWebCryptoWebPush(vapid = {}, { ttl = SCHEDULED_DEFAULT_TTL } = {}) {
|
|
2557
|
-
return {
|
|
2558
|
-
async sendNotification(subscription, payload) {
|
|
2559
|
-
return sendWebPush({
|
|
2560
|
-
subscription,
|
|
2561
|
-
payload,
|
|
2562
|
-
ttl,
|
|
2563
|
-
vapid: {
|
|
2564
|
-
email: vapid.email,
|
|
2565
|
-
publicKey: vapid.publicKey,
|
|
2566
|
-
privateKey: vapid.privateKey
|
|
2567
|
-
},
|
|
2568
|
-
fetch: globalThis.fetch
|
|
2569
|
-
});
|
|
2570
|
-
}
|
|
2571
|
-
};
|
|
2572
|
-
}
|
|
2573
|
-
|
|
2574
|
-
// src/server/cloudflare/single-user-worker.js
|
|
2575
|
-
function headersToObject(h) {
|
|
2576
|
-
const out = {};
|
|
2577
|
-
for (const [k, v] of h) out[k] = v;
|
|
2578
|
-
return out;
|
|
2579
|
-
}
|
|
2580
|
-
function jsonResponse(status, body, extraHeaders) {
|
|
2581
|
-
return new Response(JSON.stringify(body), {
|
|
2582
|
-
status,
|
|
2583
|
-
headers: { "Content-Type": "application/json; charset=utf-8", ...extraHeaders || {} }
|
|
2584
|
-
});
|
|
2585
|
-
}
|
|
2586
|
-
var CORS_ALLOW_HEADERS = "Content-Type, X-User-Id, X-Payload-Encrypted, X-Encryption-Version, X-Response-Encrypted, X-Client-Token";
|
|
2587
|
-
var CORS_ALLOW_METHODS = "GET, POST, PUT, DELETE, OPTIONS";
|
|
2588
|
-
function corsHeadersFor(cors, requestOrigin) {
|
|
2589
|
-
if (!cors || cors.origin == null) return null;
|
|
2590
|
-
const allowOrigin = typeof cors.origin === "function" ? cors.origin(requestOrigin) || null : cors.origin;
|
|
2591
|
-
if (!allowOrigin) return null;
|
|
2592
|
-
const headers = {
|
|
2593
|
-
"Access-Control-Allow-Origin": allowOrigin,
|
|
2594
|
-
"Access-Control-Allow-Methods": CORS_ALLOW_METHODS,
|
|
2595
|
-
"Access-Control-Allow-Headers": cors.allowHeaders || CORS_ALLOW_HEADERS,
|
|
2596
|
-
"Access-Control-Max-Age": String(_nullishCoalesce(cors.maxAge, () => ( 86400)))
|
|
2597
|
-
};
|
|
2598
|
-
if (allowOrigin !== "*") headers["Vary"] = "Origin";
|
|
2599
|
-
return headers;
|
|
2600
|
-
}
|
|
2601
|
-
function createSingleUserCloudflareWorker(buildConfig) {
|
|
2602
|
-
async function resolveConfig(env) {
|
|
2603
|
-
const cfg = await buildConfig(env);
|
|
2604
|
-
if (!cfg.db) cfg.db = createD1Adapter(env.DB);
|
|
2605
|
-
return cfg;
|
|
2606
|
-
}
|
|
2607
|
-
async function fetch2(request, env) {
|
|
2608
|
-
try {
|
|
2609
|
-
const cfg = await resolveConfig(env);
|
|
2610
|
-
const cors = corsHeadersFor(cfg.cors, request.headers.get("origin") || "");
|
|
2611
|
-
const method = request.method.toUpperCase();
|
|
2612
|
-
if (method === "OPTIONS") {
|
|
2613
|
-
return cors ? new Response(null, { status: 204, headers: cors }) : jsonResponse(404, { success: false, error: { code: "NOT_FOUND", message: "Unknown route" } });
|
|
2614
|
-
}
|
|
2615
|
-
const server = createSingleUserServer(cfg);
|
|
2616
|
-
const url = request.url;
|
|
2617
|
-
const pathname = new URL(url).pathname.replace(/\/+$/, "") || "/";
|
|
2618
|
-
const headers = headersToObject(request.headers);
|
|
2619
|
-
let result;
|
|
2620
|
-
if (method === "POST" && pathname.endsWith("/init-tenant")) {
|
|
2621
|
-
result = await server.handlers.init.POST(headers, await request.text());
|
|
2622
|
-
} else if (method === "GET" && pathname.endsWith("/get-user-key")) {
|
|
2623
|
-
result = await server.handlers.getUserKey.GET(url, headers);
|
|
2624
|
-
} else if (method === "POST" && pathname.endsWith("/schedule-message")) {
|
|
2625
|
-
result = await server.handlers.scheduleMessage.POST(headers, await request.text());
|
|
2626
|
-
} else if (method === "GET" && pathname.endsWith("/messages")) {
|
|
2627
|
-
result = await server.handlers.messages.GET(url, headers);
|
|
2628
|
-
} else if (method === "PUT" && pathname.endsWith("/update-message")) {
|
|
2629
|
-
result = await server.handlers.updateMessage.PUT(url, headers, await request.text());
|
|
2630
|
-
} else if (method === "DELETE" && pathname.endsWith("/cancel-message")) {
|
|
2631
|
-
result = await server.handlers.cancelMessage.DELETE(url, headers);
|
|
2632
|
-
} else if (method === "GET" && pathname.endsWith("/vapid-public-key")) {
|
|
2633
|
-
result = await server.handlers.vapidPublicKey.GET(url, headers);
|
|
2634
|
-
} else if (method === "GET" && pathname.endsWith("/capabilities")) {
|
|
2635
|
-
result = await server.handlers.capabilities.GET(url, headers);
|
|
2636
|
-
} else if (method === "PUT" && pathname.endsWith("/client-state")) {
|
|
2637
|
-
result = await server.handlers.clientState.PUT(headers, await request.text());
|
|
2638
|
-
} else if (method === "GET" && pathname.endsWith("/client-state")) {
|
|
2639
|
-
result = await server.handlers.clientState.GET(url, headers);
|
|
2640
|
-
} else if (method === "DELETE" && pathname.endsWith("/client-state")) {
|
|
2641
|
-
result = await server.handlers.clientState.DELETE(url, headers);
|
|
2642
|
-
} else {
|
|
2643
|
-
result = { status: 404, body: { success: false, error: { code: "NOT_FOUND", message: "Unknown route" } } };
|
|
2644
|
-
}
|
|
2645
|
-
return jsonResponse(result.status, result.body, cors);
|
|
2646
|
-
} catch (error) {
|
|
2647
|
-
console.error("[amsg single-user] fetch() unhandled error:", error && error.message);
|
|
2648
|
-
return jsonResponse(500, { success: false, error: { code: "INTERNAL_ERROR", message: "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF" } });
|
|
2649
|
-
}
|
|
2650
|
-
}
|
|
2651
|
-
async function scheduled(event, env) {
|
|
2652
|
-
const cfg = await resolveConfig(env);
|
|
2653
|
-
const vapid = cfg.vapid || {};
|
|
2654
|
-
if (!cfg.webpush || !vapid.email || !vapid.publicKey || !vapid.privateKey) {
|
|
2655
|
-
console.error("[amsg single-user] scheduled(): VAPID/webpush not configured; skipping tick");
|
|
2656
|
-
return;
|
|
2657
|
-
}
|
|
2658
|
-
try {
|
|
2659
|
-
await runScheduledTick({
|
|
2660
|
-
db: cfg.db,
|
|
2661
|
-
masterKey: cfg.masterKey,
|
|
2662
|
-
vapid,
|
|
2663
|
-
webpush: cfg.webpush,
|
|
2664
|
-
// Fire-time hooks (optional; see lib/agentic-fire.js). runScheduledTick
|
|
2665
|
-
// spreads its ctx into processSingleMessage, so these ride along.
|
|
2666
|
-
hooks: cfg.hooks || null,
|
|
2667
|
-
maxToolIterations: cfg.maxToolIterations,
|
|
2668
|
-
totalTimeoutMs: cfg.totalTimeoutMs,
|
|
2669
|
-
// hook 的 ctx.writeState() 用它判断单条 value 的上限,和 PUT /client-state 同一个配置。
|
|
2670
|
-
maxStateValueBytes: cfg.maxStateValueBytes,
|
|
2671
|
-
// 任务占位租期(默认 10 分钟,随 totalTimeoutMs 抬高)。
|
|
2672
|
-
claimLeaseMs: cfg.claimLeaseMs
|
|
2673
|
-
});
|
|
2674
|
-
} catch (error) {
|
|
2675
|
-
console.error("[amsg single-user] scheduled(): tick failed:", error && error.message);
|
|
2676
|
-
}
|
|
2677
|
-
}
|
|
2678
|
-
return { fetch: fetch2, scheduled };
|
|
2679
|
-
}
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
exports.validateAvatarUrl = _amsgshared.validateAvatarUrl; exports.isValidISO8601 = isValidISO8601; exports.isValidUrl = isValidUrl; exports.isValidUUID = isValidUUID; exports.isValidUUIDv4 = isValidUUIDv4; exports.validateSplitPattern = validateSplitPattern; exports.validateLlmMessagesArray = validateLlmMessagesArray; exports.validateScheduleMessagePayload = validateScheduleMessagePayload; exports.parseJsonBody = parseJsonBody; exports.getHeader = getHeader; exports.deriveUserEncryptionKey = deriveUserEncryptionKey; exports.decryptPayload = decryptPayload; exports.encryptForStorage = encryptForStorage; exports.decryptFromStorage = decryptFromStorage; exports.createGetUserKeyHandler = createGetUserKeyHandler; exports.createScheduleMessageHandler = createScheduleMessageHandler; exports.runScheduledTick = runScheduledTick; exports.createUpdateMessageHandler = createUpdateMessageHandler; exports.createCancelMessageHandler = createCancelMessageHandler; exports.createMessagesHandler = createMessagesHandler; exports.createD1Adapter = createD1Adapter; exports.createSingleUserServer = createSingleUserServer; exports.WEB_PUSH_MAX_BODY_BYTES = WEB_PUSH_MAX_BODY_BYTES; exports.WEB_PUSH_ENCRYPTION_OVERHEAD_BYTES = WEB_PUSH_ENCRYPTION_OVERHEAD_BYTES; exports.MAX_PUSH_PAYLOAD_BYTES = MAX_PUSH_PAYLOAD_BYTES; exports.measurePushPayload = measurePushPayload; exports.createWebCryptoWebPush = createWebCryptoWebPush; exports.createSingleUserCloudflareWorker = createSingleUserCloudflareWorker;
|