@alexsun-top/opencode-chat-room 0.7.8 → 0.8.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/CHANGELOG.md +14 -1
- package/LICENSE +21 -0
- package/README.md +45 -36
- package/README.zh-CN.md +50 -41
- package/dist/cli.js +2629 -350
- package/package.json +13 -3
- package/packages/chat-room-channeld/README.md +242 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
- package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
- package/packages/chat-room-channeld/src/adapter.ts +475 -0
- package/packages/chat-room-channeld/src/cli.ts +124 -0
- package/packages/chat-room-channeld/src/config.ts +207 -0
- package/packages/chat-room-channeld/src/delivery.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
- package/packages/chat-room-channeld/src/framing.ts +128 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
- package/packages/chat-room-channeld/src/host.ts +509 -0
- package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
- package/packages/chat-room-channeld/src/log.ts +26 -0
- package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
- package/packages/chat-room-channeld/src/protocol.ts +75 -0
- package/packages/chat-room-channeld/src/published.ts +37 -0
- package/packages/chat-room-channeld/src/rules.ts +127 -0
- package/packages/chat-room-channeld/src/state.ts +485 -0
- package/packages/chat-room-channeld/src/stats.ts +167 -0
- package/plugin.ts +22 -5
- package/server/addressing-routes.ts +130 -0
- package/server/assets/NOTICE.txt +2 -2
- package/server/assets/SHIKI-LICENSE +22 -0
- package/server/assets/base.css +9 -1
- package/server/assets/chat/doc-preview.js +3 -4
- package/server/assets/chat/forward.js +69 -0
- package/server/assets/chat/index.js +2 -0
- package/server/assets/chat/locales/de.js +5 -0
- package/server/assets/chat/locales/es.js +5 -0
- package/server/assets/chat/locales/fr.js +5 -0
- package/server/assets/chat/locales/it.js +5 -0
- package/server/assets/chat/locales/ja.js +5 -0
- package/server/assets/chat/locales/ko.js +5 -0
- package/server/assets/chat/markdown-footnotes.js +115 -0
- package/server/assets/chat/markdown.js +24 -35
- package/server/assets/chat/palette.js +1 -1
- package/server/assets/chat/replies.js +7 -1
- package/server/assets/chat/shiki.js +87 -0
- package/server/assets/chat/side-pane.js +8 -1
- package/server/assets/chat/state.js +14 -1
- package/server/assets/chat/system-messages.js +2 -0
- package/server/assets/code-highlight.css +20 -31
- package/server/assets/conversation.css +3 -2
- package/server/assets/doc-preview.css +2 -1
- package/server/assets/responsive.css +5 -0
- package/server/assets/shiki.bundle.js +152 -0
- package/server/channels.ts +314 -0
- package/server/chat-server.ts +27 -4
- package/server/chat.html +10 -3
- package/server/sw.js +1 -2
- package/skills/chatroom/SKILL.md +1 -1
- package/src/center/center-client.ts +79 -1
- package/src/config/file-config.ts +34 -0
- package/src/runtime/v2-plugin.ts +8 -2
- package/src/runtime/watch.ts +3 -2
- package/src/state/sqlite-state.ts +42 -11
- package/src/state/store.ts +9 -3
- package/src/tui/http.mjs +16 -2
- package/src/tui/main.mjs +1 -1
- package/server/assets/HIGHLIGHT-LICENSE +0 -29
- package/server/assets/highlight-10.7.3.min.js +0 -1358
package/dist/cli.js
CHANGED
|
@@ -1255,6 +1255,11 @@ async function readQuestions(file, roomID) {
|
|
|
1255
1255
|
const db = await openStateDatabase(file);
|
|
1256
1256
|
return db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL AND recalled_at IS NULL ORDER BY seq").all(roomID).map(rowMessage);
|
|
1257
1257
|
}
|
|
1258
|
+
async function readOpenQuestionRefs(file, roomID, limit = MAX_OPEN_QUESTION_REFS) {
|
|
1259
|
+
const db = await openStateDatabase(file);
|
|
1260
|
+
const take = Number.isSafeInteger(limit) ? Math.min(MAX_OPEN_QUESTION_REFS, Math.max(1, limit)) : MAX_OPEN_QUESTION_REFS;
|
|
1261
|
+
return db.query("SELECT id,seq FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL AND recalled_at IS NULL ORDER BY seq LIMIT ?").all(roomID, take).map((row) => ({ id: String(row.id), seq: Number(row.seq) }));
|
|
1262
|
+
}
|
|
1258
1263
|
async function countOpenQuestions(file, roomID) {
|
|
1259
1264
|
const db = await openStateDatabase(file);
|
|
1260
1265
|
const row = db.query("SELECT COUNT(*) AS count FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL AND recalled_at IS NULL").get(roomID);
|
|
@@ -1325,8 +1330,10 @@ async function sendReply(file, roomID, targetID, sessionID, text, clientMessageI
|
|
|
1325
1330
|
return { status: "ok", message: rowMessage(existing), duplicate: true };
|
|
1326
1331
|
}
|
|
1327
1332
|
const target = db.query("SELECT is_question,recalled_at FROM messages WHERE room_id=? AND id=?").get(roomID, targetID);
|
|
1328
|
-
if (!target
|
|
1333
|
+
if (!target)
|
|
1329
1334
|
return { status: "target" };
|
|
1335
|
+
if (target.recalled_at !== null)
|
|
1336
|
+
return { status: "recalled" };
|
|
1330
1337
|
if (target.is_question)
|
|
1331
1338
|
return { status: "question" };
|
|
1332
1339
|
const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID);
|
|
@@ -1464,22 +1471,33 @@ async function readInboxPage(file, sessionID, roomFilter, excludeSelf, limit = 1
|
|
|
1464
1471
|
return { member: members.length > 0, items, queuedTs, hasMore, recallVersion: version };
|
|
1465
1472
|
}).deferred();
|
|
1466
1473
|
}
|
|
1467
|
-
|
|
1474
|
+
function historyRowMessage(row) {
|
|
1475
|
+
const message = rowMessage(row);
|
|
1476
|
+
const recalledAt = row.recalled_at === null || row.recalled_at === undefined ? undefined : Number(row.recalled_at);
|
|
1477
|
+
return { ...message, ...recalledAt !== undefined ? { text: "", recalledAt, ...row.recalled_by ? { recalledBy: String(row.recalled_by) } : {} } : {}, seq: Number(row.seq) };
|
|
1478
|
+
}
|
|
1479
|
+
async function readHistoryPage(file, roomID, beforeSeq, limit = 100, excludeSessionID, excludeName = "", afterSeq) {
|
|
1468
1480
|
const db = await openStateDatabase(file);
|
|
1469
1481
|
return db.transaction(() => {
|
|
1470
1482
|
const take = Math.min(200, Math.max(1, limit));
|
|
1471
|
-
const
|
|
1472
|
-
|
|
1473
|
-
|
|
1483
|
+
const exclude = `(? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))`;
|
|
1484
|
+
if (afterSeq !== undefined) {
|
|
1485
|
+
const rows = db.query(`SELECT ${HISTORY_COLUMNS} FROM messages WHERE room_id=? AND seq>? AND ${exclude} ORDER BY seq ASC LIMIT ?`).all(roomID, afterSeq, excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1);
|
|
1486
|
+
const hasMore = rows.length > take;
|
|
1487
|
+
return { messages: rows.slice(0, take).map(historyRowMessage), nextBeforeSeq: null, hasMore, recallVersion: recallVersion(db, roomID) };
|
|
1488
|
+
}
|
|
1489
|
+
const rows = db.query(`SELECT ${HISTORY_COLUMNS} FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
|
|
1490
|
+
${exclude} ORDER BY seq DESC LIMIT ?`).all(...beforeSeq === undefined ? [roomID] : [roomID, beforeSeq], excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1);
|
|
1474
1491
|
const hasMore = rows.length > take;
|
|
1475
|
-
const messages = rows.slice(0, take).reverse().map(
|
|
1476
|
-
const message = rowMessage(row);
|
|
1477
|
-
const recalledAt = row.recalled_at === null || row.recalled_at === undefined ? undefined : Number(row.recalled_at);
|
|
1478
|
-
return { ...message, ...recalledAt !== undefined ? { text: "", recalledAt, ...row.recalled_by ? { recalledBy: String(row.recalled_by) } : {} } : {}, seq: Number(row.seq) };
|
|
1479
|
-
});
|
|
1492
|
+
const messages = rows.slice(0, take).reverse().map(historyRowMessage);
|
|
1480
1493
|
return { messages, nextBeforeSeq: hasMore ? messages[0]?.seq ?? null : null, hasMore, recallVersion: recallVersion(db, roomID) };
|
|
1481
1494
|
}).deferred();
|
|
1482
1495
|
}
|
|
1496
|
+
async function readMessage(file, roomID, messageID) {
|
|
1497
|
+
const db = await openStateDatabase(file);
|
|
1498
|
+
const row = db.query(`SELECT ${HISTORY_COLUMNS} FROM messages WHERE room_id=? AND id=?`).get(roomID, messageID);
|
|
1499
|
+
return row ? historyRowMessage(row) : undefined;
|
|
1500
|
+
}
|
|
1483
1501
|
async function readMessageReceipts(file, roomID, messageIDs) {
|
|
1484
1502
|
const db = await openStateDatabase(file);
|
|
1485
1503
|
return db.transaction(() => {
|
|
@@ -1613,7 +1631,7 @@ var databases2, ROOM_TASK_STATUSES, ROOM_TASK_COLUMNS = "id,room_id AS roomId,ti
|
|
|
1613
1631
|
status: row.status,
|
|
1614
1632
|
participants: jsonArray(row.participants),
|
|
1615
1633
|
steps: jsonArray(row.steps)
|
|
1616
|
-
}), pause2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), adminBindings = (room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null, roomBindings = (room) => [room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null], JOIN_REQUEST_COLUMNS = "session_id AS sessionID,participant_id AS participantId,name,protocol,receiver_owner_id AS receiverOwnerID,directory,host,is_agent AS isAgent,created_at AS createdAt", MAX_RETAINED_MESSAGES = 1e6, retentionCounters;
|
|
1634
|
+
}), pause2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), adminBindings = (room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null, roomBindings = (room) => [room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null], JOIN_REQUEST_COLUMNS = "session_id AS sessionID,participant_id AS participantId,name,protocol,receiver_owner_id AS receiverOwnerID,directory,host,is_agent AS isAgent,created_at AS createdAt", MAX_OPEN_QUESTION_REFS = 200, MAX_RETAINED_MESSAGES = 1e6, retentionCounters, HISTORY_COLUMNS = "seq,id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by";
|
|
1617
1635
|
var init_sqlite_state = __esm(() => {
|
|
1618
1636
|
init_room_service();
|
|
1619
1637
|
init_sqlite();
|
|
@@ -1623,7 +1641,7 @@ var init_sqlite_state = __esm(() => {
|
|
|
1623
1641
|
});
|
|
1624
1642
|
|
|
1625
1643
|
// src/state/store.ts
|
|
1626
|
-
import { Buffer } from "node:buffer";
|
|
1644
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
1627
1645
|
import path4 from "node:path";
|
|
1628
1646
|
import os3 from "node:os";
|
|
1629
1647
|
function statePath() {
|
|
@@ -1651,8 +1669,14 @@ async function readUnreadMessages(roomID, afterTs, limit = 100, sessionID, sende
|
|
|
1651
1669
|
async function readInboxMessages(sessionID, roomID, excludeSelf, limit = 100, afterTs) {
|
|
1652
1670
|
return readInboxPage(databasePath(), sessionID, roomID, excludeSelf, limit, afterTs);
|
|
1653
1671
|
}
|
|
1654
|
-
async function readHistory(roomID, beforeSeq, limit = 100, exclude) {
|
|
1655
|
-
return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
|
|
1672
|
+
async function readHistory(roomID, beforeSeq, limit = 100, exclude, afterSeq) {
|
|
1673
|
+
return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name, afterSeq);
|
|
1674
|
+
}
|
|
1675
|
+
async function readMessage2(roomID, messageID) {
|
|
1676
|
+
return readMessage(databasePath(), roomID, messageID);
|
|
1677
|
+
}
|
|
1678
|
+
async function readOpenQuestionRefs2(roomID, limit = MAX_OPEN_QUESTION_REFS) {
|
|
1679
|
+
return readOpenQuestionRefs(databasePath(), roomID, limit);
|
|
1656
1680
|
}
|
|
1657
1681
|
async function readQuestions2(roomID) {
|
|
1658
1682
|
return readQuestions(databasePath(), roomID);
|
|
@@ -1753,7 +1777,7 @@ function authHeader() {
|
|
|
1753
1777
|
if (!pwd) {
|
|
1754
1778
|
return "";
|
|
1755
1779
|
}
|
|
1756
|
-
return `Basic ${
|
|
1780
|
+
return `Basic ${Buffer2.from(`${process.env.OPENCODE_SERVER_USERNAME ?? "opencode"}:${pwd}`).toString("base64")}`;
|
|
1757
1781
|
}
|
|
1758
1782
|
function timeOf(ts) {
|
|
1759
1783
|
return new Date(ts).toLocaleTimeString("en-US", { hour12: false });
|
|
@@ -2500,6 +2524,24 @@ async function request(opts, path, method, body, extraHeaders) {
|
|
|
2500
2524
|
}
|
|
2501
2525
|
return data;
|
|
2502
2526
|
}
|
|
2527
|
+
async function getMessage(opts, roomId, messageId, sessionID) {
|
|
2528
|
+
return request(opts, `/rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}?sessionID=${encodeURIComponent(sessionID)}`, "GET");
|
|
2529
|
+
}
|
|
2530
|
+
async function catchUp(opts, roomId, params) {
|
|
2531
|
+
const { sessionID, afterSeq, limit } = params;
|
|
2532
|
+
if (afterSeq !== undefined && (!Number.isSafeInteger(afterSeq) || afterSeq < 0)) {
|
|
2533
|
+
throw new Error("afterSeq must be a non-negative integer");
|
|
2534
|
+
}
|
|
2535
|
+
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)) {
|
|
2536
|
+
throw new Error("limit must be between 1 and 200");
|
|
2537
|
+
}
|
|
2538
|
+
const query = new URLSearchParams({ sessionID });
|
|
2539
|
+
if (afterSeq !== undefined)
|
|
2540
|
+
query.set("afterSeq", String(afterSeq));
|
|
2541
|
+
if (limit !== undefined)
|
|
2542
|
+
query.set("limit", String(limit));
|
|
2543
|
+
return await request(opts, `/rooms/${encodeURIComponent(roomId)}/catch-up?${query}`, "GET");
|
|
2544
|
+
}
|
|
2503
2545
|
async function markQueued(opts, roomId, sessionID, ts) {
|
|
2504
2546
|
assertDeliveryLease();
|
|
2505
2547
|
return request(opts, "/queued", "POST", { roomId, sessionID, ts }).then(() => true).catch(() => false);
|
|
@@ -2665,6 +2707,29 @@ ${result.announcement.content}`;
|
|
|
2665
2707
|
await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks/${encodeURIComponent(args.taskId)}`, "DELETE", { sessionID });
|
|
2666
2708
|
return `task deleted: ${args.taskId}`;
|
|
2667
2709
|
}
|
|
2710
|
+
case "get_message": {
|
|
2711
|
+
if (!args.roomId)
|
|
2712
|
+
return "error: roomId is required; use a room UUID from the room list, not the room name";
|
|
2713
|
+
if (!args.messageId)
|
|
2714
|
+
return "error: messageId is required; use the full message ID returned by send, poll, or catch_up";
|
|
2715
|
+
return JSON.stringify(await getMessage(opts, args.roomId, args.messageId, sessionID));
|
|
2716
|
+
}
|
|
2717
|
+
case "catch_up": {
|
|
2718
|
+
if (!args.roomId)
|
|
2719
|
+
return "error: roomId is required; use a room UUID from the room list, not the room name";
|
|
2720
|
+
if (args.afterSeq !== undefined && (!Number.isSafeInteger(args.afterSeq) || args.afterSeq < 0)) {
|
|
2721
|
+
return "error: afterSeq must be a non-negative integer";
|
|
2722
|
+
}
|
|
2723
|
+
if (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1 || args.limit > 200)) {
|
|
2724
|
+
return "error: limit must be between 1 and 200";
|
|
2725
|
+
}
|
|
2726
|
+
const page = await catchUp(opts, args.roomId, {
|
|
2727
|
+
sessionID,
|
|
2728
|
+
...args.afterSeq === undefined ? {} : { afterSeq: args.afterSeq },
|
|
2729
|
+
...args.limit === undefined ? {} : { limit: args.limit }
|
|
2730
|
+
});
|
|
2731
|
+
return JSON.stringify(page);
|
|
2732
|
+
}
|
|
2668
2733
|
case "send": {
|
|
2669
2734
|
if (!args.roomId) {
|
|
2670
2735
|
return "error: roomId is required; use a room UUID from the room list, not the room name";
|
|
@@ -2672,7 +2737,14 @@ ${result.announcement.content}`;
|
|
|
2672
2737
|
if (!args.text?.trim()) {
|
|
2673
2738
|
return "error: text is required; pass a non-empty message body";
|
|
2674
2739
|
}
|
|
2675
|
-
const room = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/messages`, "POST", {
|
|
2740
|
+
const room = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/messages`, "POST", {
|
|
2741
|
+
sessionID,
|
|
2742
|
+
text: args.text.trim(),
|
|
2743
|
+
...args.isQuestion ? { isQuestion: true } : {},
|
|
2744
|
+
...args.replyToMessageID ? { replyToMessageID: args.replyToMessageID } : {},
|
|
2745
|
+
...args.parentMessageId ? { parentMessageId: args.parentMessageId } : {},
|
|
2746
|
+
...args.clientMessageID ? { clientMessageID: args.clientMessageID } : {}
|
|
2747
|
+
});
|
|
2676
2748
|
const parsed = toRoom(room);
|
|
2677
2749
|
const sentID = [...parsed.messages].reverse().find((message) => message.senderSessionID === sessionID && message.text === args.text.trim())?.id ?? parsed.messages.at(-1)?.id;
|
|
2678
2750
|
return `sent: ${args.text.trim()}
|
|
@@ -2778,6 +2850,16 @@ function optionalBoolean(value, where) {
|
|
|
2778
2850
|
throw new Error(`chatroom config: ${where} must be true or false`);
|
|
2779
2851
|
return value;
|
|
2780
2852
|
}
|
|
2853
|
+
function parseChanneld(value) {
|
|
2854
|
+
const raw = asRecord(value, "server.channeld");
|
|
2855
|
+
if (!raw)
|
|
2856
|
+
return;
|
|
2857
|
+
return {
|
|
2858
|
+
enabled: optionalBoolean(raw.enabled, "server.channeld.enabled"),
|
|
2859
|
+
config: optionalString(raw.config, "server.channeld.config"),
|
|
2860
|
+
stateFile: optionalString(raw.stateFile, "server.channeld.stateFile")
|
|
2861
|
+
};
|
|
2862
|
+
}
|
|
2781
2863
|
function parseServer(value) {
|
|
2782
2864
|
const raw = asRecord(value, "server");
|
|
2783
2865
|
if (!raw)
|
|
@@ -2796,7 +2878,8 @@ function parseServer(value) {
|
|
|
2796
2878
|
token: optionalString(raw.token, "server.token"),
|
|
2797
2879
|
stateDir: optionalString(raw.stateDir, "server.stateDir"),
|
|
2798
2880
|
wakeServeUrl: optionalString(raw.wakeServeUrl, "server.wakeServeUrl"),
|
|
2799
|
-
maxFileSizeMb
|
|
2881
|
+
maxFileSizeMb,
|
|
2882
|
+
channeld: parseChanneld(raw.channeld)
|
|
2800
2883
|
};
|
|
2801
2884
|
}
|
|
2802
2885
|
function parseClient(value) {
|
|
@@ -2976,13 +3059,21 @@ function resolveServerSettings(file, env = process.env) {
|
|
|
2976
3059
|
if (maxFileSizeMb !== undefined && (!Number.isFinite(maxFileSizeMb) || maxFileSizeMb <= 0)) {
|
|
2977
3060
|
throw new Error("CHAT_ROOM_MAX_FILE_SIZE_MB must be a positive finite number");
|
|
2978
3061
|
}
|
|
3062
|
+
const channeldRaw = envValue(env, "CHAT_ROOM_CHANNELD");
|
|
3063
|
+
const channeldConfig = envValue(env, "CHAT_ROOM_CHANNELD_CONFIG") ?? file?.server?.channeld?.config;
|
|
3064
|
+
const channeldEnabled = channeldRaw === undefined ? file?.server?.channeld?.enabled ?? Boolean(channeldConfig) : channeldRaw === "1" || channeldRaw === "true";
|
|
2979
3065
|
return {
|
|
2980
3066
|
host: envValue(env, "CHAT_ROOM_SERVER_HOST") ?? envValue(env, "HOST") ?? file?.server?.host ?? "0.0.0.0",
|
|
2981
3067
|
port,
|
|
2982
3068
|
token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.server?.token ?? file?.token,
|
|
2983
3069
|
stateDir: envValue(env, "CHAT_ROOM_STATE_DIR") ?? file?.server?.stateDir,
|
|
2984
3070
|
wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.server?.wakeServeUrl ?? "",
|
|
2985
|
-
maxFileSizeMb
|
|
3071
|
+
maxFileSizeMb,
|
|
3072
|
+
channeld: {
|
|
3073
|
+
enabled: channeldEnabled,
|
|
3074
|
+
config: channeldConfig,
|
|
3075
|
+
stateFile: file?.server?.channeld?.stateFile
|
|
3076
|
+
}
|
|
2986
3077
|
};
|
|
2987
3078
|
}
|
|
2988
3079
|
function resolveClientSettings(file, env = process.env) {
|
|
@@ -4256,7 +4347,7 @@ function createV2Setup(deps) {
|
|
|
4256
4347
|
});
|
|
4257
4348
|
toolRegistration = await context.tool.transform((editor) => editor.add({
|
|
4258
4349
|
name: "room",
|
|
4259
|
-
description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages;
|
|
4350
|
+
description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages; get_message fetches one message by ID (recalled messages come back as tombstones); catch_up pages messages after a seq cursor and is read-only (no read receipt or wake); send accepts parentMessageId to reply. List members, announcements and tasks; create, update and delete room tasks; manage reminders. In an approval room join returns pending: you are not a member yet; call join_status to check whether an administrator approved you. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
|
|
4260
4351
|
options: { codemode: false },
|
|
4261
4352
|
input: roomSchema(),
|
|
4262
4353
|
execute: async (args, toolContext) => {
|
|
@@ -4355,13 +4446,19 @@ The user invoked /room. Use the room tool to perform this command.`,
|
|
|
4355
4446
|
}
|
|
4356
4447
|
function roomSchema() {
|
|
4357
4448
|
return z2.object({
|
|
4358
|
-
action: z2.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
|
|
4449
|
+
action: z2.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "get_message", "catch_up", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
|
|
4359
4450
|
name: z2.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
|
|
4360
4451
|
roomId: z2.string().optional(),
|
|
4452
|
+
messageId: z2.string().optional().describe("For get_message: the full message ID returned by send, poll, or catch_up."),
|
|
4361
4453
|
resourceId: z2.string().optional(),
|
|
4362
4454
|
filePath: z2.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
|
|
4363
4455
|
text: z2.string().max(5000).optional(),
|
|
4364
4456
|
isQuestion: z2.boolean().optional(),
|
|
4457
|
+
parentMessageId: z2.string().optional().describe("For send: the ID of the message this one answers or replies to."),
|
|
4458
|
+
replyToMessageID: z2.string().optional().describe("Legacy alias of parentMessageId for send."),
|
|
4459
|
+
clientMessageID: z2.string().max(100).optional().describe("For send: idempotency key; retrying with the same ID and parent creates one message."),
|
|
4460
|
+
afterSeq: z2.number().int().min(0).optional().describe("For catch_up: return messages with seq greater than this cursor; omit to start at 0."),
|
|
4461
|
+
limit: z2.number().int().min(1).max(200).optional().describe("For catch_up: page size from 1 to 200; the server default is 50."),
|
|
4365
4462
|
announcementName: z2.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
|
|
4366
4463
|
content: z2.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
|
|
4367
4464
|
taskId: z2.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
|
|
@@ -5048,7 +5145,7 @@ var connection, centerUrl, centerToken, serveWakeUrl, runtimeContext, defaultRun
|
|
|
5048
5145
|
const explicitV2Join = runtime.protocol === "v2" && (args.action === "create" || args.action === "join");
|
|
5049
5146
|
const receiverOwnerID = explicitV2Join && runtime.transport.verifySession ? await runtime.transport.verifySession(context.sessionID) : undefined;
|
|
5050
5147
|
if (runtime.center.center) {
|
|
5051
|
-
if (args.action !== "poll") {
|
|
5148
|
+
if (args.action !== "poll" && args.action !== "get_message" && args.action !== "catch_up") {
|
|
5052
5149
|
checkCenterInbox(runtime.center, context.sessionID, runtime.transport);
|
|
5053
5150
|
}
|
|
5054
5151
|
return await centerAction(runtime.center, {
|
|
@@ -5187,6 +5284,12 @@ var connection, centerUrl, centerToken, serveWakeUrl, runtimeContext, defaultRun
|
|
|
5187
5284
|
if (!args.roomId) {
|
|
5188
5285
|
return "error: roomId is required; use a room UUID from the room list, not the room name";
|
|
5189
5286
|
}
|
|
5287
|
+
if (args.parentMessageId || args.replyToMessageID) {
|
|
5288
|
+
return "error: replies require central server mode (CHAT_ROOM_SERVER_URL)";
|
|
5289
|
+
}
|
|
5290
|
+
if (args.clientMessageID) {
|
|
5291
|
+
return "error: clientMessageID requires central server mode (CHAT_ROOM_SERVER_URL)";
|
|
5292
|
+
}
|
|
5190
5293
|
if (!args.text?.trim()) {
|
|
5191
5294
|
return "error: text is required; pass a non-empty message body";
|
|
5192
5295
|
}
|
|
@@ -5216,6 +5319,9 @@ ${formatRoom(svc, room)}`;
|
|
|
5216
5319
|
`) + (pollPage?.hasMore ? `
|
|
5217
5320
|
More unread messages remain; poll again.` : "");
|
|
5218
5321
|
}
|
|
5322
|
+
case "get_message":
|
|
5323
|
+
case "catch_up":
|
|
5324
|
+
return `error: ${args.action} requires central server mode (CHAT_ROOM_SERVER_URL)`;
|
|
5219
5325
|
default:
|
|
5220
5326
|
return "error: unsupported room action";
|
|
5221
5327
|
}
|
|
@@ -5271,14 +5377,19 @@ var init_plugin = __esm(() => {
|
|
|
5271
5377
|
restoreScans2 = new Map;
|
|
5272
5378
|
READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "join_status", "announcement_list", "announcement_read", "task_list"]);
|
|
5273
5379
|
roomArgs = z3.object({
|
|
5274
|
-
action: z3.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
|
|
5380
|
+
action: z3.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "get_message", "catch_up", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
|
|
5275
5381
|
name: z3.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
|
|
5276
5382
|
roomId: z3.string().optional().describe("Room UUID, not the room name. Required for resource actions and every room-scoped action."),
|
|
5277
|
-
messageId: z3.string().optional().describe("For recall: the full message ID returned by send
|
|
5383
|
+
messageId: z3.string().optional().describe("For recall and get_message: the full message ID returned by send, poll, or catch_up."),
|
|
5278
5384
|
resourceId: z3.string().optional().describe("Resource UUID returned by upload_resource. read_resource and delete_resource also require roomId."),
|
|
5279
5385
|
filePath: z3.string().optional().describe("Absolute path to a regular local file to upload; central mode only; requires host read permission."),
|
|
5280
5386
|
text: z3.string().max(5000).optional().describe("Message text, at most 5000 characters; required for send."),
|
|
5281
5387
|
isQuestion: z3.boolean().optional().describe("For send: mark the message as a question awaiting an answer."),
|
|
5388
|
+
parentMessageId: z3.string().optional().describe("For send: the ID of the message this one answers or replies to."),
|
|
5389
|
+
replyToMessageID: z3.string().optional().describe("Legacy alias of parentMessageId for send."),
|
|
5390
|
+
clientMessageID: z3.string().max(100).optional().describe("For send: idempotency key; retrying with the same ID and parent creates one message."),
|
|
5391
|
+
afterSeq: z3.number().int().min(0).optional().describe("For catch_up: return messages with seq greater than this cursor; omit to start at 0."),
|
|
5392
|
+
limit: z3.number().int().min(1).max(200).optional().describe("For catch_up: page size from 1 to 200; the server default is 50."),
|
|
5282
5393
|
announcementName: z3.string().optional().describe("Exact announcement name from announcement_list; distinct from participant or room name."),
|
|
5283
5394
|
content: z3.string().optional().describe("Announcement content, at most 5000 Unicode characters; required for announcement_write."),
|
|
5284
5395
|
taskId: z3.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
|
|
@@ -5314,7 +5425,7 @@ var init_plugin = __esm(() => {
|
|
|
5314
5425
|
}
|
|
5315
5426
|
});
|
|
5316
5427
|
room = tool({
|
|
5317
|
-
description:
|
|
5428
|
+
description: "Chat room operations: create, join, leave and list rooms; send, poll and recall messages; get_message fetches one message by ID (recalled messages come back as tombstones); catch_up pages messages after a seq cursor and is read-only (no read receipt or wake). Send accepts parentMessageId to reply to a message. List members, announcements and tasks; create, update and delete room tasks; manage reminders. Sent and polled messages carry full message IDs; recall takes roomId plus messageId and withdraws the message for everyone (agents their own, room admins any). Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. Resource actions need both roomId (the room UUID) and resourceId (the UUID in the marker); the marker alone does not identify the room. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads. Room joinPolicy \"approval\" makes join a pending request: you are not a member while pending, never claim otherwise, and use join_status to check whether a human administrator approved it.",
|
|
5318
5429
|
args: roomArgs.shape,
|
|
5319
5430
|
execute: roomExecute
|
|
5320
5431
|
});
|
|
@@ -5357,7 +5468,7 @@ var init_plugin = __esm(() => {
|
|
|
5357
5468
|
|
|
5358
5469
|
// server/http-server.ts
|
|
5359
5470
|
import { createServer } from "node:http";
|
|
5360
|
-
import { Buffer as
|
|
5471
|
+
import { Buffer as Buffer3 } from "node:buffer";
|
|
5361
5472
|
import { Readable as Readable2 } from "node:stream";
|
|
5362
5473
|
import { pipeline } from "node:stream/promises";
|
|
5363
5474
|
function requestURL(req, hostname, port) {
|
|
@@ -5383,7 +5494,7 @@ function sendJson(res, status, message) {
|
|
|
5383
5494
|
return;
|
|
5384
5495
|
}
|
|
5385
5496
|
const body = JSON.stringify({ error: message });
|
|
5386
|
-
res.writeHead(status, { "Content-Type": "application/json", "Content-Length":
|
|
5497
|
+
res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer3.byteLength(body) });
|
|
5387
5498
|
res.end(body);
|
|
5388
5499
|
}
|
|
5389
5500
|
function rejectTooLarge(req, res) {
|
|
@@ -5513,7 +5624,7 @@ var init_http_server = __esm(() => {
|
|
|
5513
5624
|
});
|
|
5514
5625
|
|
|
5515
5626
|
// src/runtime/watch.ts
|
|
5516
|
-
import { Buffer as
|
|
5627
|
+
import { Buffer as Buffer4 } from "node:buffer";
|
|
5517
5628
|
import { createHash as createHash6, randomBytes, timingSafeEqual } from "node:crypto";
|
|
5518
5629
|
import { existsSync as existsSync3, realpathSync } from "node:fs";
|
|
5519
5630
|
import { appendFile, chmod as chmod2, link, mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
@@ -5619,8 +5730,8 @@ async function reserveWatcher(record, beforePublish) {
|
|
|
5619
5730
|
function authorized(request, token) {
|
|
5620
5731
|
const supplied = request.headers.get("Authorization") ?? "";
|
|
5621
5732
|
const expected = `Bearer ${token}`;
|
|
5622
|
-
const a =
|
|
5623
|
-
const b =
|
|
5733
|
+
const a = Buffer4.from(supplied);
|
|
5734
|
+
const b = Buffer4.from(expected);
|
|
5624
5735
|
return a.length === b.length && timingSafeEqual(a, b);
|
|
5625
5736
|
}
|
|
5626
5737
|
async function watcherSweep(deps = defaultSweepDeps()) {
|
|
@@ -5765,7 +5876,7 @@ async function watchStatus() {
|
|
|
5765
5876
|
return watcherProcessMayExist(record.pid) && Date.now() - (record.createdAt ?? 0) < 30000 ? "starting" : "unavailable";
|
|
5766
5877
|
return await control(record) ? "running" : "unavailable";
|
|
5767
5878
|
}
|
|
5768
|
-
async function startWatcher(beforePublish) {
|
|
5879
|
+
async function startWatcher(beforePublish, readyTimeoutMs = 20000) {
|
|
5769
5880
|
await privateDirectory();
|
|
5770
5881
|
const own = { phase: "starting", token: randomBytes(32).toString("base64url"), nonce: randomBytes(16).toString("hex"), instanceID: randomBytes(16).toString("hex"), pid: process.pid, createdAt: Date.now() };
|
|
5771
5882
|
const reservation = await reserveWatcher(own, beforePublish);
|
|
@@ -5798,7 +5909,7 @@ async function startWatcher(beforePublish) {
|
|
|
5798
5909
|
childError = error;
|
|
5799
5910
|
});
|
|
5800
5911
|
child.unref();
|
|
5801
|
-
const deadline = Date.now() +
|
|
5912
|
+
const deadline = Date.now() + readyTimeoutMs;
|
|
5802
5913
|
while (Date.now() < deadline) {
|
|
5803
5914
|
if (childError) {
|
|
5804
5915
|
await removeRecord(own.token, own.nonce);
|
|
@@ -6150,6 +6261,128 @@ var init_history_route = __esm(() => {
|
|
|
6150
6261
|
init_store();
|
|
6151
6262
|
});
|
|
6152
6263
|
|
|
6264
|
+
// server/addressing-routes.ts
|
|
6265
|
+
function decode(value) {
|
|
6266
|
+
try {
|
|
6267
|
+
return decodeURIComponent(value);
|
|
6268
|
+
} catch {
|
|
6269
|
+
return;
|
|
6270
|
+
}
|
|
6271
|
+
}
|
|
6272
|
+
async function memberContext(roomID, sessionID) {
|
|
6273
|
+
return readState2((service, registry) => {
|
|
6274
|
+
const room = service.listRooms().find((candidate) => candidate.id === roomID);
|
|
6275
|
+
const entry = sessionID && sessionID.length <= MAX_SESSION ? registry[roomID]?.[sessionID] : undefined;
|
|
6276
|
+
const allowed = Boolean(room && entry) && (room.kind === "direct" ? Boolean(room.directSessionIDs?.includes(sessionID)) : service.containsParticipant(roomID, entry.name));
|
|
6277
|
+
return {
|
|
6278
|
+
allowed,
|
|
6279
|
+
name: entry?.name ?? "",
|
|
6280
|
+
roomKind: room?.kind === "direct" ? "direct" : "group",
|
|
6281
|
+
senderNames: new Map([...room?.participants.values() ?? []].map((participant) => [participant.id, participant.name]))
|
|
6282
|
+
};
|
|
6283
|
+
});
|
|
6284
|
+
}
|
|
6285
|
+
function extractResourceIDs(text) {
|
|
6286
|
+
return [...new Set([...text.matchAll(RESOURCE_MARKER)].map((match) => match[1]))];
|
|
6287
|
+
}
|
|
6288
|
+
function messageView(message, senderName) {
|
|
6289
|
+
if (message.recalledAt !== undefined) {
|
|
6290
|
+
return {
|
|
6291
|
+
id: message.id,
|
|
6292
|
+
roomId: message.roomId,
|
|
6293
|
+
seq: message.seq,
|
|
6294
|
+
senderId: message.senderId,
|
|
6295
|
+
createdAt: message.createdAt,
|
|
6296
|
+
recalled: true,
|
|
6297
|
+
recalledAt: message.recalledAt,
|
|
6298
|
+
recalledBy: message.recalledBy ?? null,
|
|
6299
|
+
text: null,
|
|
6300
|
+
unavailable: "recalled",
|
|
6301
|
+
resourceIDs: []
|
|
6302
|
+
};
|
|
6303
|
+
}
|
|
6304
|
+
return {
|
|
6305
|
+
id: message.id,
|
|
6306
|
+
roomId: message.roomId,
|
|
6307
|
+
seq: message.seq,
|
|
6308
|
+
senderId: message.senderId,
|
|
6309
|
+
senderName,
|
|
6310
|
+
text: message.text,
|
|
6311
|
+
createdAt: message.createdAt,
|
|
6312
|
+
isQuestion: message.isQuestion === true,
|
|
6313
|
+
parentMessageId: message.answerToMessageID ?? null,
|
|
6314
|
+
answeredByMessageId: message.answeredByMessageID ?? null,
|
|
6315
|
+
recalled: false,
|
|
6316
|
+
resourceIDs: extractResourceIDs(message.text)
|
|
6317
|
+
};
|
|
6318
|
+
}
|
|
6319
|
+
async function getMessage2(req, url, match) {
|
|
6320
|
+
if (req.method !== "GET")
|
|
6321
|
+
return json({ error: "method not allowed" }, 405);
|
|
6322
|
+
const roomID = decode(match[1]), messageID = decode(match[2]);
|
|
6323
|
+
if (roomID === undefined || messageID === undefined)
|
|
6324
|
+
return json({ error: "not found" }, 404);
|
|
6325
|
+
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
6326
|
+
const access = await memberContext(roomID, sessionID);
|
|
6327
|
+
if (!access.allowed)
|
|
6328
|
+
return json({ error: "not found" }, 404);
|
|
6329
|
+
const message = await readMessage2(roomID, messageID);
|
|
6330
|
+
if (!message)
|
|
6331
|
+
return json({ error: "not found" }, 404);
|
|
6332
|
+
return json(messageView(message, access.senderNames.get(message.senderId) ?? message.senderId));
|
|
6333
|
+
}
|
|
6334
|
+
async function catchUp2(req, url, match) {
|
|
6335
|
+
if (req.method !== "GET")
|
|
6336
|
+
return json({ error: "method not allowed" }, 405);
|
|
6337
|
+
const roomID = decode(match[1]);
|
|
6338
|
+
if (roomID === undefined)
|
|
6339
|
+
return json({ error: "not found" }, 404);
|
|
6340
|
+
const afterText = url.searchParams.get("afterSeq");
|
|
6341
|
+
const limitText = url.searchParams.get("limit");
|
|
6342
|
+
if (afterText !== null && !/^\d+$/.test(afterText) || limitText !== null && !/^\d+$/.test(limitText)) {
|
|
6343
|
+
return json({ error: "afterSeq must be a non-negative integer and limit must be 1-200" }, 400);
|
|
6344
|
+
}
|
|
6345
|
+
const afterSeq = afterText === null ? 0 : Number(afterText);
|
|
6346
|
+
const limit = limitText === null ? DEFAULT_LIMIT : Number(limitText);
|
|
6347
|
+
if (!Number.isSafeInteger(afterSeq) || !Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
6348
|
+
return json({ error: "afterSeq must be a non-negative integer and limit must be 1-200" }, 400);
|
|
6349
|
+
}
|
|
6350
|
+
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
6351
|
+
const access = await memberContext(roomID, sessionID);
|
|
6352
|
+
if (!access.allowed)
|
|
6353
|
+
return json({ error: "not found" }, 404);
|
|
6354
|
+
const page = await readHistory(roomID, undefined, limit, undefined, afterSeq);
|
|
6355
|
+
const messages = page.messages.map((message) => messageView(message, access.senderNames.get(message.senderId) ?? message.senderId));
|
|
6356
|
+
const unreadMentions = page.messages.filter((message) => message.recalledAt === undefined && explicitlyAddresses(message, access.name, sessionID, access.roomKind)).map((message) => ({ id: message.id, seq: message.seq }));
|
|
6357
|
+
const [unansweredQuestions, unansweredQuestionCount] = await Promise.all([
|
|
6358
|
+
readOpenQuestionRefs2(roomID),
|
|
6359
|
+
countOpenQuestions2(roomID)
|
|
6360
|
+
]);
|
|
6361
|
+
return json({
|
|
6362
|
+
messages,
|
|
6363
|
+
nextCursor: page.messages.at(-1)?.seq ?? afterSeq,
|
|
6364
|
+
hasMore: page.hasMore,
|
|
6365
|
+
unreadMentions,
|
|
6366
|
+
unreadMentionCount: unreadMentions.length,
|
|
6367
|
+
unansweredQuestions,
|
|
6368
|
+
unansweredQuestionCount
|
|
6369
|
+
});
|
|
6370
|
+
}
|
|
6371
|
+
async function addressingRoutes(req, url) {
|
|
6372
|
+
const message = url.pathname.match(/^\/rooms\/([^/]+)\/messages\/([^/]+)$/);
|
|
6373
|
+
if (message)
|
|
6374
|
+
return getMessage2(req, url, message);
|
|
6375
|
+
const resume = url.pathname.match(/^\/rooms\/([^/]+)\/catch-up$/);
|
|
6376
|
+
if (resume)
|
|
6377
|
+
return catchUp2(req, url, resume);
|
|
6378
|
+
return;
|
|
6379
|
+
}
|
|
6380
|
+
var json = (body, status = 200) => Response.json(body, { status }), MAX_SESSION = 128, DEFAULT_LIMIT = 50, MAX_LIMIT = 200, RESOURCE_MARKER;
|
|
6381
|
+
var init_addressing_routes = __esm(() => {
|
|
6382
|
+
init_store();
|
|
6383
|
+
RESOURCE_MARKER = /\[\[resource:([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\]\]/gi;
|
|
6384
|
+
});
|
|
6385
|
+
|
|
6153
6386
|
// server/json-body.ts
|
|
6154
6387
|
async function jsonObject(req) {
|
|
6155
6388
|
try {
|
|
@@ -6165,57 +6398,57 @@ async function messageRecallRoutes(req, url) {
|
|
|
6165
6398
|
const recall = url.pathname.match(/^\/rooms\/([^/]+)\/messages\/([^/]+)\/recall$/);
|
|
6166
6399
|
if (recall) {
|
|
6167
6400
|
if (req.method !== "POST")
|
|
6168
|
-
return
|
|
6401
|
+
return json2({ error: "method not allowed" }, 405);
|
|
6169
6402
|
const roomID = decodeURIComponent(recall[1]);
|
|
6170
6403
|
const messageID = decodeURIComponent(recall[2]);
|
|
6171
6404
|
const body = await jsonObject(req);
|
|
6172
6405
|
if (!body)
|
|
6173
|
-
return
|
|
6406
|
+
return json2({ error: "JSON object body is required" }, 400);
|
|
6174
6407
|
const sessionID = typeof body.sessionID === "string" ? body.sessionID.trim() : "";
|
|
6175
|
-
if (!sessionID || sessionID.length >
|
|
6176
|
-
return
|
|
6408
|
+
if (!sessionID || sessionID.length > MAX_SESSION2)
|
|
6409
|
+
return json2({ error: "sessionID is required" }, 400);
|
|
6177
6410
|
const result = await recallMessage2(roomID, messageID, sessionID);
|
|
6178
6411
|
if (result.status === "missing")
|
|
6179
|
-
return
|
|
6412
|
+
return json2({ error: "message not found" }, 404);
|
|
6180
6413
|
if (result.status === "member")
|
|
6181
|
-
return
|
|
6414
|
+
return json2({ error: "session is not a room member" }, 409);
|
|
6182
6415
|
if (result.status === "forbidden")
|
|
6183
|
-
return
|
|
6416
|
+
return json2({ error: "not allowed to recall this message" }, 403);
|
|
6184
6417
|
if (result.status !== "ok")
|
|
6185
|
-
return
|
|
6186
|
-
return
|
|
6418
|
+
return json2({ error: "recall failed" }, 409);
|
|
6419
|
+
return json2({ ok: true, messageID: result.messageID, recalledAt: result.recalledAt, recalledBy: result.recalledBy });
|
|
6187
6420
|
}
|
|
6188
6421
|
const content = url.pathname.match(/^\/rooms\/([^/]+)\/messages\/([^/]+)\/content$/);
|
|
6189
6422
|
if (!content)
|
|
6190
6423
|
return;
|
|
6191
6424
|
if (req.method !== "GET")
|
|
6192
|
-
return
|
|
6425
|
+
return json2({ error: "method not allowed" }, 405);
|
|
6193
6426
|
const roomID = decodeURIComponent(content[1]);
|
|
6194
6427
|
const messageID = decodeURIComponent(content[2]);
|
|
6195
6428
|
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
6196
|
-
if (!sessionID || sessionID.length >
|
|
6197
|
-
return
|
|
6429
|
+
if (!sessionID || sessionID.length > MAX_SESSION2)
|
|
6430
|
+
return json2({ error: "sessionID is required" }, 400);
|
|
6198
6431
|
const result = await revealMessageContent2(roomID, messageID, sessionID);
|
|
6199
6432
|
if (result.status === "missing")
|
|
6200
|
-
return
|
|
6433
|
+
return json2({ error: "message not found" }, 404);
|
|
6201
6434
|
if (result.status === "member")
|
|
6202
|
-
return
|
|
6435
|
+
return json2({ error: "session is not a room member" }, 409);
|
|
6203
6436
|
if (result.status === "hidden")
|
|
6204
|
-
return
|
|
6437
|
+
return json2({ error: "message is not recalled" }, 409);
|
|
6205
6438
|
if (result.status !== "ok")
|
|
6206
|
-
return
|
|
6207
|
-
return
|
|
6439
|
+
return json2({ error: "message not found" }, 404);
|
|
6440
|
+
return json2({ messageID: result.messageID, text: result.text, senderId: result.senderId, createdAt: result.createdAt, recalledAt: result.recalledAt });
|
|
6208
6441
|
}
|
|
6209
|
-
var
|
|
6442
|
+
var json2 = (body, status = 200) => Response.json(body, { status }), MAX_SESSION2 = 128;
|
|
6210
6443
|
var init_message_recall_routes = __esm(() => {
|
|
6211
6444
|
init_store();
|
|
6212
6445
|
});
|
|
6213
6446
|
|
|
6214
6447
|
// server/admin-state.ts
|
|
6215
|
-
import { Buffer as
|
|
6448
|
+
import { Buffer as Buffer5 } from "node:buffer";
|
|
6216
6449
|
import { createHash as createHash7, randomBytes as randomBytes2, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
6217
6450
|
function matchesHash(value, stored) {
|
|
6218
|
-
const left =
|
|
6451
|
+
const left = Buffer5.from(hash2(value), "hex"), right = Buffer5.from(stored, "hex");
|
|
6219
6452
|
return right.length === 32 && timingSafeEqual2(left, right);
|
|
6220
6453
|
}
|
|
6221
6454
|
async function ensureAdminSchema() {
|
|
@@ -6604,12 +6837,12 @@ async function roomManagement(req, url) {
|
|
|
6604
6837
|
if (req.method === "POST" && p === "/direct") {
|
|
6605
6838
|
const body = await objectBody(req);
|
|
6606
6839
|
if (!body)
|
|
6607
|
-
return
|
|
6840
|
+
return json3({ error: "JSON object body is required" }, 400);
|
|
6608
6841
|
const roomId = typeof body.roomId === "string" ? body.roomId : "";
|
|
6609
6842
|
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
6610
6843
|
const targetSessionID = typeof body.targetSessionID === "string" ? body.targetSessionID : "";
|
|
6611
6844
|
if (!roomId || !sessionID || !targetSessionID || sessionID === targetSessionID || sessionID.length > 128 || targetSessionID.length > 128)
|
|
6612
|
-
return
|
|
6845
|
+
return json3({ error: "roomId and distinct sessionIDs are required" }, 400);
|
|
6613
6846
|
const result = await mutate((svc, registry) => {
|
|
6614
6847
|
svc.getRoom(roomId);
|
|
6615
6848
|
const actor = registry[roomId]?.[sessionID], target = registry[roomId]?.[targetSessionID];
|
|
@@ -6635,18 +6868,18 @@ async function roomManagement(req, url) {
|
|
|
6635
6868
|
}
|
|
6636
6869
|
return { room: direct, created: !existing };
|
|
6637
6870
|
});
|
|
6638
|
-
return
|
|
6871
|
+
return json3(await roomPayload(result.room), result.created ? 201 : 200);
|
|
6639
6872
|
}
|
|
6640
6873
|
const kick = p.match(/^\/rooms\/([^/]+)\/kick$/);
|
|
6641
6874
|
if (kick && req.method === "POST") {
|
|
6642
6875
|
const roomId = decodeURIComponent(kick[1]);
|
|
6643
6876
|
const body = await objectBody(req);
|
|
6644
6877
|
if (!body)
|
|
6645
|
-
return
|
|
6878
|
+
return json3({ error: "JSON object body is required" }, 400);
|
|
6646
6879
|
const actor = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
6647
6880
|
const target = typeof body.targetSessionID === "string" ? body.targetSessionID : "";
|
|
6648
6881
|
if (!actor || !target || actor === target || actor.length > 128 || target.length > 128)
|
|
6649
|
-
return
|
|
6882
|
+
return json3({ error: "distinct sessionIDs are required" }, 400);
|
|
6650
6883
|
const agentBinding = await tx((db) => {
|
|
6651
6884
|
const b = binding(db, roomId);
|
|
6652
6885
|
return b && b.target_room_id === roomId && b.session_id === actor && validCurrent(db, b) && hasAdminCapability(req, b) ? b : undefined;
|
|
@@ -6695,29 +6928,29 @@ async function roomManagement(req, url) {
|
|
|
6695
6928
|
return { message, target };
|
|
6696
6929
|
});
|
|
6697
6930
|
clearPendingAdmission(result.target, roomId, Number.MAX_SAFE_INTEGER);
|
|
6698
|
-
return
|
|
6931
|
+
return json3({ ok: true, createdAt: result.message.createdAt });
|
|
6699
6932
|
}
|
|
6700
6933
|
const edit = p.match(/^\/rooms\/([^/]+)$/);
|
|
6701
6934
|
if (edit && req.method === "PATCH") {
|
|
6702
6935
|
const roomId = decodeURIComponent(edit[1]);
|
|
6703
6936
|
const body = await objectBody(req);
|
|
6704
6937
|
if (!body)
|
|
6705
|
-
return
|
|
6938
|
+
return json3({ error: "JSON object body is required" }, 400);
|
|
6706
6939
|
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
6707
6940
|
if (!sessionID || sessionID.length > 128)
|
|
6708
|
-
return
|
|
6941
|
+
return json3({ error: "sessionID is required" }, 400);
|
|
6709
6942
|
if (body.name !== undefined && (typeof body.name !== "string" || !body.name.trim() || body.name.trim().length > 64))
|
|
6710
|
-
return
|
|
6943
|
+
return json3({ error: "name must be 1-64 characters" }, 400);
|
|
6711
6944
|
if (body.description !== undefined && (typeof body.description !== "string" || body.description.length > 2000))
|
|
6712
|
-
return
|
|
6945
|
+
return json3({ error: "description too long (max 2000)" }, 400);
|
|
6713
6946
|
if (body.joinPolicy !== undefined && body.joinPolicy !== "open" && body.joinPolicy !== "approval")
|
|
6714
|
-
return
|
|
6947
|
+
return json3({ error: "joinPolicy must be open or approval" }, 400);
|
|
6715
6948
|
if (body.adminSessionID !== undefined && body.adminSessionID !== null && (typeof body.adminSessionID !== "string" || body.adminSessionID.length > 128))
|
|
6716
|
-
return
|
|
6949
|
+
return json3({ error: "invalid adminSessionID" }, 400);
|
|
6717
6950
|
if (body.adminIds !== undefined && (!Array.isArray(body.adminIds) || body.adminIds.length > 50 || body.adminIds.some((name) => typeof name !== "string" || !name.trim() || name.trim().length > 64)))
|
|
6718
|
-
return
|
|
6951
|
+
return json3({ error: "adminIds must be up to 50 member names" }, 400);
|
|
6719
6952
|
if (body.successorId !== undefined && body.successorId !== null && (typeof body.successorId !== "string" || !body.successorId.trim() || body.successorId.trim().length > 64))
|
|
6720
|
-
return
|
|
6953
|
+
return json3({ error: "successorId must be a member name or null" }, 400);
|
|
6721
6954
|
const successorId = typeof body.successorId === "string" ? body.successorId.trim() : body.successorId === null ? null : undefined;
|
|
6722
6955
|
const adminIds = Array.isArray(body.adminIds) ? [...new Set(body.adminIds.map((name) => name.trim()))] : undefined;
|
|
6723
6956
|
const name = typeof body.name === "string" ? body.name.trim() : undefined;
|
|
@@ -6725,7 +6958,7 @@ async function roomManagement(req, url) {
|
|
|
6725
6958
|
const joinPolicy = body.joinPolicy === "open" || body.joinPolicy === "approval" ? body.joinPolicy : undefined;
|
|
6726
6959
|
const adminSessionID = typeof body.adminSessionID === "string" ? body.adminSessionID : body.adminSessionID === null ? null : undefined;
|
|
6727
6960
|
if (body.ownerId !== undefined && (typeof body.ownerId !== "string" || !body.ownerId.trim() || body.ownerId.trim().length > 64))
|
|
6728
|
-
return
|
|
6961
|
+
return json3({ error: "ownerId must be 1-64 characters" }, 400);
|
|
6729
6962
|
const nextOwner = typeof body.ownerId === "string" ? body.ownerId.trim() : undefined;
|
|
6730
6963
|
const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
|
|
6731
6964
|
const room = svc.getRoom(roomId);
|
|
@@ -6849,18 +7082,18 @@ async function roomManagement(req, url) {
|
|
|
6849
7082
|
return { room };
|
|
6850
7083
|
});
|
|
6851
7084
|
if ("error" in result)
|
|
6852
|
-
return
|
|
6853
|
-
return
|
|
7085
|
+
return json3({ error: result.error }, result.status);
|
|
7086
|
+
return json3(await roomPayload(result.room));
|
|
6854
7087
|
}
|
|
6855
7088
|
const remove = p.match(/^\/rooms\/([^/]+)$/);
|
|
6856
7089
|
if (remove && req.method === "DELETE") {
|
|
6857
7090
|
const roomId = decodeURIComponent(remove[1]);
|
|
6858
7091
|
const body = await objectBody(req);
|
|
6859
7092
|
if (!body)
|
|
6860
|
-
return
|
|
7093
|
+
return json3({ error: "JSON object body is required" }, 400);
|
|
6861
7094
|
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
6862
7095
|
if (!sessionID || sessionID.length > 128)
|
|
6863
|
-
return
|
|
7096
|
+
return json3({ error: "sessionID is required" }, 400);
|
|
6864
7097
|
const sessions = await mutate((svc, registry) => {
|
|
6865
7098
|
const room = svc.getRoom(roomId);
|
|
6866
7099
|
const actor = registry[roomId]?.[sessionID];
|
|
@@ -6876,11 +7109,11 @@ async function roomManagement(req, url) {
|
|
|
6876
7109
|
await removeRoomResources(roomId).catch(() => console.error("failed to clean deleted room resources", roomId));
|
|
6877
7110
|
for (const sid of sessions)
|
|
6878
7111
|
clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
|
|
6879
|
-
return
|
|
7112
|
+
return json3({ ok: true });
|
|
6880
7113
|
}
|
|
6881
7114
|
return;
|
|
6882
7115
|
}
|
|
6883
|
-
var
|
|
7116
|
+
var json3 = (body, status = 200) => Response.json(body, { status }), mutate = (fn) => writeState(fn);
|
|
6884
7117
|
var init_newrooms = __esm(() => {
|
|
6885
7118
|
init_room_service();
|
|
6886
7119
|
init_store();
|
|
@@ -6903,7 +7136,7 @@ async function announcementRoutes(req, url) {
|
|
|
6903
7136
|
roomID = decodeURIComponent(match[1]);
|
|
6904
7137
|
name = match[2] === undefined ? undefined : decodeURIComponent(match[2]);
|
|
6905
7138
|
} catch {
|
|
6906
|
-
return
|
|
7139
|
+
return json4({ error: "invalid path" }, 400);
|
|
6907
7140
|
}
|
|
6908
7141
|
const roomExists = await readState2((svc) => {
|
|
6909
7142
|
try {
|
|
@@ -6914,38 +7147,38 @@ async function announcementRoutes(req, url) {
|
|
|
6914
7147
|
}
|
|
6915
7148
|
});
|
|
6916
7149
|
if (!roomExists)
|
|
6917
|
-
return
|
|
7150
|
+
return json4({ error: "room not found" }, 404);
|
|
6918
7151
|
if (req.method === "GET") {
|
|
6919
7152
|
if (!name)
|
|
6920
|
-
return
|
|
7153
|
+
return json4({ announcements: await listAnnouncements2(roomID) });
|
|
6921
7154
|
if (validateAnnouncement(name))
|
|
6922
|
-
return
|
|
7155
|
+
return json4({ error: "invalid announcement name" }, 400);
|
|
6923
7156
|
const announcement = await getAnnouncement2(roomID, name);
|
|
6924
|
-
return announcement ?
|
|
7157
|
+
return announcement ? json4({ announcement }) : json4({ error: "announcement not found" }, 404);
|
|
6925
7158
|
}
|
|
6926
7159
|
let body;
|
|
6927
7160
|
try {
|
|
6928
7161
|
body = await req.json();
|
|
6929
7162
|
} catch {
|
|
6930
|
-
return
|
|
7163
|
+
return json4({ error: "invalid JSON body" }, 400);
|
|
6931
7164
|
}
|
|
6932
7165
|
if (!object(body) || typeof body.sessionID !== "string" || !body.sessionID)
|
|
6933
|
-
return
|
|
7166
|
+
return json4({ error: "sessionID is required" }, 400);
|
|
6934
7167
|
const member = await readState2((_svc, registry) => Boolean(registry[roomID]?.[body.sessionID]));
|
|
6935
7168
|
if (!member)
|
|
6936
|
-
return
|
|
7169
|
+
return json4({ error: "not a room member" }, 403);
|
|
6937
7170
|
if (req.method === "PUT") {
|
|
6938
7171
|
const error = validateAnnouncement(name, body.content, true);
|
|
6939
7172
|
if (error)
|
|
6940
|
-
return
|
|
7173
|
+
return json4({ error }, 400);
|
|
6941
7174
|
const announcement = await putAnnouncement2(roomID, name.trim(), body.content);
|
|
6942
|
-
return announcement ?
|
|
7175
|
+
return announcement ? json4({ announcement }) : json4({ error: "room not found" }, 404);
|
|
6943
7176
|
}
|
|
6944
7177
|
if (!name || validateAnnouncement(name))
|
|
6945
|
-
return
|
|
6946
|
-
return await deleteAnnouncement2(roomID, name) ?
|
|
7178
|
+
return json4({ error: "invalid announcement name" }, 400);
|
|
7179
|
+
return await deleteAnnouncement2(roomID, name) ? json4({ ok: true }) : json4({ error: "announcement not found" }, 404);
|
|
6947
7180
|
}
|
|
6948
|
-
var
|
|
7181
|
+
var json4 = (body, status = 200) => Response.json(body, { status }), object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6949
7182
|
var init_announcement_routes = __esm(() => {
|
|
6950
7183
|
init_announcements();
|
|
6951
7184
|
init_store();
|
|
@@ -6953,7 +7186,7 @@ var init_announcement_routes = __esm(() => {
|
|
|
6953
7186
|
|
|
6954
7187
|
// server/task-routes.ts
|
|
6955
7188
|
function sessionID(value) {
|
|
6956
|
-
return typeof value === "string" && value.length > 0 && value.length <=
|
|
7189
|
+
return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION3 ? value : undefined;
|
|
6957
7190
|
}
|
|
6958
7191
|
async function taskRoutes(req, url) {
|
|
6959
7192
|
const collection = url.pathname.match(/^\/rooms\/([^/]+)\/tasks$/);
|
|
@@ -6965,48 +7198,48 @@ async function taskRoutes(req, url) {
|
|
|
6965
7198
|
roomID = decodeURIComponent((collection ?? item)[1]);
|
|
6966
7199
|
taskID = item ? decodeURIComponent(item[2]) : undefined;
|
|
6967
7200
|
} catch {
|
|
6968
|
-
return
|
|
7201
|
+
return json5({ error: "invalid path" }, 400);
|
|
6969
7202
|
}
|
|
6970
7203
|
if (collection) {
|
|
6971
7204
|
if (req.method === "GET") {
|
|
6972
7205
|
const session = sessionID(url.searchParams.get("sessionID"));
|
|
6973
7206
|
if (!session)
|
|
6974
|
-
return
|
|
7207
|
+
return json5({ error: "sessionID is required" }, 400);
|
|
6975
7208
|
const result = await listTasks(roomID, session);
|
|
6976
|
-
return "error" in result ?
|
|
7209
|
+
return "error" in result ? json5({ error: result.error }, result.status) : json5({ tasks: result.tasks });
|
|
6977
7210
|
}
|
|
6978
7211
|
if (req.method !== "POST" && req.method !== "DELETE")
|
|
6979
|
-
return
|
|
7212
|
+
return json5({ error: "method not allowed" }, 405);
|
|
6980
7213
|
const body = await jsonObject(req);
|
|
6981
7214
|
if (!body)
|
|
6982
|
-
return
|
|
7215
|
+
return json5({ error: "JSON object body is required" }, 400);
|
|
6983
7216
|
const session = sessionID(body.sessionID);
|
|
6984
7217
|
if (!session)
|
|
6985
|
-
return
|
|
7218
|
+
return json5({ error: "sessionID is required" }, 400);
|
|
6986
7219
|
if (req.method === "DELETE") {
|
|
6987
7220
|
const result = await clearCompletedTasks(roomID, session);
|
|
6988
|
-
return "error" in result ?
|
|
7221
|
+
return "error" in result ? json5({ error: result.error }, result.status) : json5({ ok: true, count: result.count });
|
|
6989
7222
|
}
|
|
6990
7223
|
const fields = { title: body.title, description: body.description, assignee: body.assignee, dueDate: body.dueDate, participants: body.participants, conclusion: body.conclusion, steps: body.steps };
|
|
6991
7224
|
const result = await createTask(roomID, session, fields);
|
|
6992
|
-
return "error" in result ?
|
|
7225
|
+
return "error" in result ? json5({ error: result.error }, result.status) : json5({ task: result.task }, 201);
|
|
6993
7226
|
}
|
|
6994
7227
|
if (req.method !== "PATCH" && req.method !== "DELETE")
|
|
6995
|
-
return
|
|
7228
|
+
return json5({ error: "method not allowed" }, 405);
|
|
6996
7229
|
const body = await jsonObject(req);
|
|
6997
7230
|
if (!body)
|
|
6998
|
-
return
|
|
7231
|
+
return json5({ error: "JSON object body is required" }, 400);
|
|
6999
7232
|
const session = sessionID(body.sessionID);
|
|
7000
7233
|
if (!session)
|
|
7001
|
-
return
|
|
7234
|
+
return json5({ error: "sessionID is required" }, 400);
|
|
7002
7235
|
if (req.method === "DELETE") {
|
|
7003
7236
|
const result = await deleteTask(roomID, taskID, session);
|
|
7004
|
-
return "error" in result ?
|
|
7237
|
+
return "error" in result ? json5({ error: result.error }, result.status) : json5({ ok: true });
|
|
7005
7238
|
}
|
|
7006
7239
|
const result = await updateTask(roomID, taskID, session, { title: body.title, description: body.description, assignee: body.assignee, status: body.status, dueDate: body.dueDate, participants: body.participants, conclusion: body.conclusion, steps: body.steps });
|
|
7007
|
-
return "error" in result ?
|
|
7240
|
+
return "error" in result ? json5({ error: result.error }, result.status) : json5({ task: result.task });
|
|
7008
7241
|
}
|
|
7009
|
-
var
|
|
7242
|
+
var json5 = (body, status = 200) => Response.json(body, { status }), MAX_SESSION3 = 128;
|
|
7010
7243
|
var init_task_routes = __esm(() => {
|
|
7011
7244
|
init_tasks();
|
|
7012
7245
|
});
|
|
@@ -7025,14 +7258,14 @@ async function memberRoutes(req, url) {
|
|
|
7025
7258
|
if (req.method === "POST" && url.pathname === "/read") {
|
|
7026
7259
|
const body = await jsonObject(req);
|
|
7027
7260
|
if (!body)
|
|
7028
|
-
return
|
|
7261
|
+
return json6({ error: "JSON object body is required" }, 400);
|
|
7029
7262
|
const ts = body.ts;
|
|
7030
7263
|
const roomId = String(body.roomId ?? "");
|
|
7031
7264
|
const sessionID = String(body.sessionID ?? "");
|
|
7032
7265
|
const messageIDs = body.messageIDs;
|
|
7033
7266
|
const hasReceipts = messageIDs !== undefined;
|
|
7034
7267
|
if (body.ts === undefined || body.ts === null || !roomId || !sessionID || typeof ts !== "number" || !Number.isSafeInteger(ts) || ts <= 0 || hasReceipts && (!Array.isArray(messageIDs) || !messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => typeof id !== "string" || !id || id.length > 128) || typeof body.membershipID !== "string" || !body.membershipID || body.membershipID.length > 128 || typeof body.evidence !== "string" || !["displayed", "tool", "context"].includes(body.evidence) || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID))) {
|
|
7035
|
-
return
|
|
7268
|
+
return json6({ error: "invalid read acknowledgement" }, 400);
|
|
7036
7269
|
}
|
|
7037
7270
|
if (hasReceipts) {
|
|
7038
7271
|
const result = await acknowledgeReadWithReceipts(roomId, sessionID, ts, messageIDs, body.evidence, {
|
|
@@ -7040,45 +7273,45 @@ async function memberRoutes(req, url) {
|
|
|
7040
7273
|
...typeof body.receiverOwnerID === "string" ? { receiverOwnerID: body.receiverOwnerID } : {}
|
|
7041
7274
|
});
|
|
7042
7275
|
if (result.status === "membership")
|
|
7043
|
-
return
|
|
7276
|
+
return json6({ error: "membership generation mismatch" }, 409);
|
|
7044
7277
|
if (result.status === "messageIDs")
|
|
7045
|
-
return
|
|
7278
|
+
return json6({ error: "message IDs do not belong to this room" }, 400);
|
|
7046
7279
|
if (result.status !== "ok")
|
|
7047
|
-
return
|
|
7280
|
+
return json6({ error: "read acknowledgement rejected" }, 400);
|
|
7048
7281
|
clearPendingAdmission(sessionID, roomId, result.readThroughTs ?? 0);
|
|
7049
7282
|
touchActive(sessionID);
|
|
7050
|
-
return
|
|
7283
|
+
return json6({ ok: true, acceptedIDs: result.acceptedIDs });
|
|
7051
7284
|
}
|
|
7052
7285
|
const actualTs = await acknowledgeRead2(roomId, sessionID, ts);
|
|
7053
7286
|
if (actualTs === null)
|
|
7054
|
-
return
|
|
7287
|
+
return json6({ error: "registry entry not found" }, 404);
|
|
7055
7288
|
clearPendingAdmission(sessionID, roomId, actualTs);
|
|
7056
7289
|
touchActive(sessionID);
|
|
7057
|
-
return
|
|
7290
|
+
return json6({ ok: true });
|
|
7058
7291
|
}
|
|
7059
7292
|
const receiptRoute = url.pathname.match(/^\/rooms\/([^/]+)\/receipts$/);
|
|
7060
7293
|
if (req.method === "POST" && receiptRoute) {
|
|
7061
7294
|
const body = await req.json();
|
|
7062
7295
|
if (!object2(body))
|
|
7063
|
-
return
|
|
7296
|
+
return json6({ error: "JSON object body is required" }, 400);
|
|
7064
7297
|
const { sessionID, membershipID, evidence } = body;
|
|
7065
7298
|
const ids = body.messageIDs;
|
|
7066
7299
|
const ownerID = body.receiverOwnerID;
|
|
7067
7300
|
if (typeof sessionID !== "string" || !sessionID || sessionID.length > 128 || typeof membershipID !== "string" || !membershipID || membershipID.length > 128 || !Array.isArray(ids) || !ids.length || ids.length > 500 || ids.some((id) => typeof id !== "string" || !id || id.length > 128) || typeof evidence !== "string" || !["displayed", "tool", "context"].includes(evidence) || ownerID !== undefined && !isReceiverOwnerID(ownerID))
|
|
7068
|
-
return
|
|
7301
|
+
return json6({ error: "invalid message receipt" }, 400);
|
|
7069
7302
|
const identity = { membershipID, ...typeof ownerID === "string" ? { receiverOwnerID: ownerID } : {} };
|
|
7070
7303
|
const result = await recordMessageReceipts(decodeURIComponent(receiptRoute[1]), sessionID, ids, evidence, identity);
|
|
7071
7304
|
if (result.status === "membership")
|
|
7072
|
-
return
|
|
7305
|
+
return json6({ error: "membership generation mismatch" }, 409);
|
|
7073
7306
|
if (result.status === "messageIDs")
|
|
7074
|
-
return
|
|
7075
|
-
return
|
|
7307
|
+
return json6({ error: "message IDs do not belong to this room" }, 400);
|
|
7308
|
+
return json6({ acceptedIDs: result.acceptedIDs });
|
|
7076
7309
|
}
|
|
7077
7310
|
const match = url.pathname.match(/^\/rooms\/([^/]+)\/(members|receipts)$/);
|
|
7078
7311
|
if (req.method === "GET" && match) {
|
|
7079
7312
|
const roomID = decodeURIComponent(match[1]);
|
|
7080
7313
|
if (match[2] === "members")
|
|
7081
|
-
return
|
|
7314
|
+
return json6(await readState2((svc, registry) => {
|
|
7082
7315
|
svc.getRoom(roomID);
|
|
7083
7316
|
return Object.entries(registry[roomID] ?? {}).map(([sessionID, entry]) => ({
|
|
7084
7317
|
sessionID,
|
|
@@ -7097,25 +7330,25 @@ async function memberRoutes(req, url) {
|
|
|
7097
7330
|
const filter = url.searchParams.get("messageIDs");
|
|
7098
7331
|
const ids = filter === null ? undefined : filter.split(",");
|
|
7099
7332
|
if (ids && (!ids.length || ids.length > 500 || ids.some((id) => !id || id.length > 128)))
|
|
7100
|
-
return
|
|
7333
|
+
return json6({ error: "invalid message IDs" }, 400);
|
|
7101
7334
|
const receipts = await readReceipts(roomID, ids);
|
|
7102
7335
|
if (!receipts)
|
|
7103
|
-
return
|
|
7104
|
-
return
|
|
7336
|
+
return json6({ error: "message IDs do not belong to this room" }, 400);
|
|
7337
|
+
return json6({ receipts: receipts.map((item) => ({ messageID: item.messageID, readers: item.readers.map((reader) => ({ ...reader, currentMember: Boolean(registry[reader.sessionID]) })) })), semantics: "per-message" });
|
|
7105
7338
|
}
|
|
7106
7339
|
if (req.method !== "POST" || url.pathname !== "/presence")
|
|
7107
7340
|
return;
|
|
7108
7341
|
const body = await req.json();
|
|
7109
7342
|
if (!object2(body) || !Array.isArray(body.sessions) || body.sessions.length > 200)
|
|
7110
|
-
return
|
|
7343
|
+
return json6({ error: "sessions must be an array of at most 200 reports" }, 400);
|
|
7111
7344
|
const ownerID = body.ownerID;
|
|
7112
7345
|
const sequence = body.sequence;
|
|
7113
7346
|
if (ownerID !== undefined && !isReceiverOwnerID(ownerID) || ownerID === undefined && sequence !== undefined || ownerID !== undefined && (typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence <= 0))
|
|
7114
|
-
return
|
|
7347
|
+
return json6({ error: "invalid owner sequence" }, 400);
|
|
7115
7348
|
const reports = new Map;
|
|
7116
7349
|
for (const item of body.sessions) {
|
|
7117
7350
|
if (!object2(item) || typeof item.sessionID !== "string" || !item.sessionID || item.sessionID.length > 128 || typeof item.state !== "string" || !states.has(item.state) || item.receiverOwnerID !== undefined && (!isReceiverOwnerID(item.receiverOwnerID) || item.receiverOwnerID !== ownerID) || ownerID === undefined && item.receiverOwnerID !== undefined)
|
|
7118
|
-
return
|
|
7351
|
+
return json6({ error: "invalid presence report" }, 400);
|
|
7119
7352
|
reports.set(item.sessionID, {
|
|
7120
7353
|
sessionID: item.sessionID,
|
|
7121
7354
|
state: item.state,
|
|
@@ -7123,9 +7356,9 @@ async function memberRoutes(req, url) {
|
|
|
7123
7356
|
});
|
|
7124
7357
|
}
|
|
7125
7358
|
const result = await reportPresence([...reports.values()], ownerID, sequence);
|
|
7126
|
-
return
|
|
7359
|
+
return json6({ updatedSessionIDs: result.stale ? [] : result.updatedSessionIDs });
|
|
7127
7360
|
}
|
|
7128
|
-
var
|
|
7361
|
+
var json6 = (body, status = 200) => Response.json(body, { status }), states;
|
|
7129
7362
|
var init_member_routes = __esm(() => {
|
|
7130
7363
|
init_store();
|
|
7131
7364
|
init_receiver_owner();
|
|
@@ -7162,64 +7395,64 @@ async function resourceRoutes(req, url) {
|
|
|
7162
7395
|
const sessionID = req.headers.get("x-session-id") ?? "";
|
|
7163
7396
|
const entry = await readState2((_svc, registry) => registry[roomID]?.[sessionID]);
|
|
7164
7397
|
if (!entry)
|
|
7165
|
-
return
|
|
7398
|
+
return json7({ error: "forbidden" }, 403);
|
|
7166
7399
|
const rawLimit = Number(url.searchParams.get("limit") ?? 500);
|
|
7167
7400
|
const rawOffset = Number(url.searchParams.get("offset") ?? 0);
|
|
7168
7401
|
const limit = Number.isSafeInteger(rawLimit) ? Math.min(1000, Math.max(1, rawLimit)) : 500;
|
|
7169
7402
|
const offset = Number.isSafeInteger(rawOffset) ? Math.max(0, rawOffset) : 0;
|
|
7170
7403
|
const before = url.searchParams.get("before");
|
|
7171
7404
|
const page = await listRoomResources(roomID, limit, offset, before && uuid3.test(before) ? before : undefined);
|
|
7172
|
-
return
|
|
7405
|
+
return json7({ resources: page.items, total: page.total, limit, offset }, 200);
|
|
7173
7406
|
}
|
|
7174
7407
|
if (upload) {
|
|
7175
7408
|
const sessionID = req.headers.get("x-session-id") ?? "";
|
|
7176
7409
|
const entry = await readState2((_svc, registry) => registry[roomID]?.[sessionID]);
|
|
7177
7410
|
if (!entry)
|
|
7178
|
-
return
|
|
7411
|
+
return json7({ error: "forbidden" }, 403);
|
|
7179
7412
|
const encoded = req.headers.get("x-file-name");
|
|
7180
7413
|
if (!encoded)
|
|
7181
|
-
return
|
|
7414
|
+
return json7({ error: "invalid filename" }, 400);
|
|
7182
7415
|
let filename;
|
|
7183
7416
|
try {
|
|
7184
7417
|
filename = decodeURIComponent(encoded);
|
|
7185
7418
|
} catch {
|
|
7186
|
-
return
|
|
7419
|
+
return json7({ error: "invalid filename" }, 400);
|
|
7187
7420
|
}
|
|
7188
7421
|
if (!filename || filename.length > 255 || /[\\/\r\n\0]/.test(filename) || filename === "." || filename === "..")
|
|
7189
|
-
return
|
|
7422
|
+
return json7({ error: "invalid filename" }, 400);
|
|
7190
7423
|
const requestedID = req.headers.get("x-resource-id");
|
|
7191
7424
|
if (requestedID !== null && !uuid3.test(requestedID))
|
|
7192
|
-
return
|
|
7425
|
+
return json7({ error: "invalid resource id" }, 400);
|
|
7193
7426
|
const resource = await uploadResource(roomID, filename, req.body ?? new Blob([]).stream(), maxResourceBytes(), { sessionID, name: entry.name }, requestedID ?? undefined);
|
|
7194
|
-
return
|
|
7427
|
+
return json7({ resource }, 201);
|
|
7195
7428
|
}
|
|
7196
7429
|
const id = decodeURIComponent(item[2]);
|
|
7197
7430
|
if (!uuid3.test(id))
|
|
7198
|
-
return
|
|
7431
|
+
return json7({ error: "resource not found" }, 404);
|
|
7199
7432
|
const resource = await findResource(roomID, id);
|
|
7200
7433
|
if (!resource)
|
|
7201
|
-
return
|
|
7434
|
+
return json7({ error: "resource not found" }, 404);
|
|
7202
7435
|
if (req.method === "DELETE") {
|
|
7203
7436
|
const sessionID = req.headers.get("x-session-id") ?? "";
|
|
7204
7437
|
const context = await readState2((svc, registry) => ({ room: svc.getRoom(roomID), entry: registry[roomID]?.[sessionID] }));
|
|
7205
7438
|
if (!context.entry)
|
|
7206
|
-
return
|
|
7439
|
+
return json7({ error: "forbidden" }, 403);
|
|
7207
7440
|
const ownAgentUpload = !isUser(context.entry) && resource.uploaderSessionID === sessionID;
|
|
7208
7441
|
if (!isRoomAdmin(context.room, context.entry) && !ownAgentUpload)
|
|
7209
|
-
return
|
|
7442
|
+
return json7({ error: "forbidden" }, 403);
|
|
7210
7443
|
await deleteResource(roomID, id);
|
|
7211
|
-
return
|
|
7444
|
+
return json7({ ok: true });
|
|
7212
7445
|
}
|
|
7213
7446
|
if (!item[3])
|
|
7214
|
-
return
|
|
7447
|
+
return json7({ resource });
|
|
7215
7448
|
return await content2(req, resource);
|
|
7216
7449
|
} catch (error) {
|
|
7217
7450
|
if (error instanceof URIError)
|
|
7218
|
-
return
|
|
7451
|
+
return json7({ error: "invalid resource request" }, 400);
|
|
7219
7452
|
const status = typeof error === "object" && error !== null && "status" in error ? Number(error.status) : 500;
|
|
7220
7453
|
if (status >= 400 && status < 500)
|
|
7221
|
-
return
|
|
7222
|
-
return
|
|
7454
|
+
return json7({ error: status === 413 ? "file exceeds maximum size" : status === 404 ? "resource not found" : status === 403 ? "forbidden" : "invalid resource request" }, status);
|
|
7455
|
+
return json7({ error: "internal server error" }, 500);
|
|
7223
7456
|
}
|
|
7224
7457
|
}
|
|
7225
7458
|
async function content2(req, resource) {
|
|
@@ -7261,7 +7494,7 @@ async function content2(req, resource) {
|
|
|
7261
7494
|
headers.set("Content-Range", `bytes ${start}-${end}/${info.size}`);
|
|
7262
7495
|
return new Response(Readable3.toWeb(createReadStream2(path, { start, end })), { status, headers });
|
|
7263
7496
|
}
|
|
7264
|
-
var
|
|
7497
|
+
var json7 = (body, status = 200) => Response.json(body, { status }), uuid3, safeHeaders;
|
|
7265
7498
|
var init_resource_routes = __esm(() => {
|
|
7266
7499
|
init_resources();
|
|
7267
7500
|
init_store();
|
|
@@ -7279,8 +7512,8 @@ async function adminRoutes(request, url) {
|
|
|
7279
7512
|
return await rootRoutes(request, url);
|
|
7280
7513
|
} catch (error) {
|
|
7281
7514
|
if (error instanceof SyntaxError || error instanceof URIError)
|
|
7282
|
-
return
|
|
7283
|
-
return
|
|
7515
|
+
return json8({ error: "invalid request" }, 400);
|
|
7516
|
+
return json8({ error: "admin request failed" }, 500);
|
|
7284
7517
|
}
|
|
7285
7518
|
}
|
|
7286
7519
|
async function rootRoutes(request, url) {
|
|
@@ -7290,13 +7523,13 @@ async function rootRoutes(request, url) {
|
|
|
7290
7523
|
return claimBinding(request, decodeURIComponent(claim[1]));
|
|
7291
7524
|
const room = path.match(/^\/admin\/rooms\/([^/]+)(?:\/(overview|history))?$/);
|
|
7292
7525
|
if (!room)
|
|
7293
|
-
return
|
|
7526
|
+
return json8({ error: "not found" }, 404);
|
|
7294
7527
|
const roomID = decodeURIComponent(room[1]);
|
|
7295
7528
|
if (request.method === "GET" && room[2] === "overview")
|
|
7296
7529
|
return overview(request, roomID);
|
|
7297
7530
|
if (request.method === "GET" && room[2] === "history")
|
|
7298
7531
|
return history(request, url, roomID);
|
|
7299
|
-
return
|
|
7532
|
+
return json8({ error: "method not allowed" }, 405);
|
|
7300
7533
|
}
|
|
7301
7534
|
function bounded(value, max) {
|
|
7302
7535
|
return typeof value === "string" && value.trim().length > 0 && value.length <= max;
|
|
@@ -7304,7 +7537,7 @@ function bounded(value, max) {
|
|
|
7304
7537
|
async function claimBinding(request, roomID) {
|
|
7305
7538
|
const body = await request.json();
|
|
7306
7539
|
if (!object3(body) || !bounded(body.sessionID, 128) || typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 || !bounded(body.enrollmentKey, 256))
|
|
7307
|
-
return
|
|
7540
|
+
return json8({ error: "invalid claim" }, 400);
|
|
7308
7541
|
const { sessionID, receiverOwnerID, enrollmentKey } = body;
|
|
7309
7542
|
const result = await tx((db) => {
|
|
7310
7543
|
const b = binding(db, roomID);
|
|
@@ -7314,7 +7547,7 @@ async function claimBinding(request, roomID) {
|
|
|
7314
7547
|
const saved = run(db, "UPDATE admin_rooms SET capability_hash=?,enrollment_hash='',enrollment_expires=0 WHERE room_id=? AND generation=? AND enrollment_hash=? AND enrollment_expires>?", digest(capability), roomID, b.generation, b.enrollment_hash, Date.now());
|
|
7315
7548
|
return saved.changes === 1 ? { capability, adminRoom: publicRoom({ ...b, capability_hash: digest(capability) }) } : null;
|
|
7316
7549
|
});
|
|
7317
|
-
return result ?
|
|
7550
|
+
return result ? json8(result) : json8({ error: "claim rejected" }, 409);
|
|
7318
7551
|
}
|
|
7319
7552
|
async function overview(request, roomID) {
|
|
7320
7553
|
const result = await tx((db) => {
|
|
@@ -7330,16 +7563,16 @@ async function overview(request, roomID) {
|
|
|
7330
7563
|
const rooms = many(db, "SELECT id,name,created_at AS createdAt FROM rooms WHERE id=?", roomID).map((room) => ({ ...room, members: many(db, "SELECT g.session_id AS sessionID,g.name,g.protocol,g.receiver_owner_id AS receiverOwnerID,g.work_state AS workState,g.last_seen_at AS lastSeenAt FROM registry g WHERE g.room_id=? ORDER BY g.name", room.id) }));
|
|
7331
7564
|
return { rooms };
|
|
7332
7565
|
});
|
|
7333
|
-
return "status" in result ?
|
|
7566
|
+
return "status" in result ? json8({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "binding is no longer active" }, result.status) : json8(result);
|
|
7334
7567
|
}
|
|
7335
7568
|
async function history(request, url, roomID) {
|
|
7336
7569
|
const targetRoomID = url.searchParams.get("targetRoomId") ?? "";
|
|
7337
7570
|
if (!bounded(targetRoomID, 128))
|
|
7338
|
-
return
|
|
7571
|
+
return json8({ error: "invalid history request" }, 400);
|
|
7339
7572
|
const rawLimit = url.searchParams.get("limit");
|
|
7340
7573
|
const limit = rawLimit === null ? 20 : Number(rawLimit);
|
|
7341
7574
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 50)
|
|
7342
|
-
return
|
|
7575
|
+
return json8({ error: "invalid history request" }, 400);
|
|
7343
7576
|
const allowed = await tx((db) => {
|
|
7344
7577
|
const b = binding(db, roomID);
|
|
7345
7578
|
if (!b)
|
|
@@ -7353,12 +7586,12 @@ async function history(request, url, roomID) {
|
|
|
7353
7586
|
return 200;
|
|
7354
7587
|
});
|
|
7355
7588
|
if (allowed !== 200)
|
|
7356
|
-
return
|
|
7589
|
+
return json8({ error: allowed === 401 ? "unauthorized" : allowed === 404 ? "room not found" : "binding is no longer active" }, allowed);
|
|
7357
7590
|
if (targetRoomID !== roomID)
|
|
7358
|
-
return
|
|
7359
|
-
return
|
|
7591
|
+
return json8({ error: "room is outside this administrator's scope" }, 403);
|
|
7592
|
+
return json8(await readHistoryPage(databasePath(), roomID, undefined, limit));
|
|
7360
7593
|
}
|
|
7361
|
-
var
|
|
7594
|
+
var json8 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } }), object3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
7362
7595
|
var init_admin_routes = __esm(async () => {
|
|
7363
7596
|
init_store();
|
|
7364
7597
|
init_sqlite_state();
|
|
@@ -7439,37 +7672,37 @@ async function joinRequestRoutes(req, url) {
|
|
|
7439
7672
|
const roomID = decodeURIComponent(status[1]);
|
|
7440
7673
|
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
7441
7674
|
if (!bounded2(sessionID))
|
|
7442
|
-
return
|
|
7675
|
+
return json9({ error: "sessionID is required" }, 400);
|
|
7443
7676
|
const joined = await readState2((svc, registry) => {
|
|
7444
7677
|
svc.getRoom(roomID);
|
|
7445
7678
|
return Boolean(registry[roomID]?.[sessionID]);
|
|
7446
7679
|
});
|
|
7447
7680
|
if (joined)
|
|
7448
|
-
return
|
|
7449
|
-
return
|
|
7681
|
+
return json9({ status: "joined" });
|
|
7682
|
+
return json9({ status: await readJoinRequest2(roomID, sessionID) ? "pending" : "none" });
|
|
7450
7683
|
}
|
|
7451
7684
|
if (list && req.method === "DELETE") {
|
|
7452
7685
|
const roomID = decodeURIComponent(list[1]);
|
|
7453
7686
|
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
7454
7687
|
if (!bounded2(sessionID))
|
|
7455
|
-
return
|
|
7688
|
+
return json9({ error: "sessionID is required" }, 400);
|
|
7456
7689
|
const removed = await writeSqliteStateWithDatabase(databasePath(), (svc, _registry, db) => {
|
|
7457
7690
|
svc.getRoom(roomID);
|
|
7458
7691
|
return removeJoinRequest(db, roomID, sessionID);
|
|
7459
7692
|
});
|
|
7460
|
-
return removed ?
|
|
7693
|
+
return removed ? json9({ ok: true }) : json9({ error: "join request not found" }, 404);
|
|
7461
7694
|
}
|
|
7462
7695
|
if (list && req.method === "GET") {
|
|
7463
7696
|
const roomID = decodeURIComponent(list[1]);
|
|
7464
7697
|
const actor = url.searchParams.get("sessionID") ?? "";
|
|
7465
7698
|
if (!bounded2(actor))
|
|
7466
|
-
return
|
|
7699
|
+
return json9({ error: "sessionID is required" }, 400);
|
|
7467
7700
|
const human = await humanReviewer(roomID, actor);
|
|
7468
7701
|
const agent = !human && await agentReviewer(req, roomID, actor);
|
|
7469
7702
|
if (!human && !agent)
|
|
7470
|
-
return
|
|
7703
|
+
return json9({ error: "only room administrators can review join requests" }, 403);
|
|
7471
7704
|
const requests = await listJoinRequests2(roomID, agent);
|
|
7472
|
-
return
|
|
7705
|
+
return json9({ requests: requests.map(({ sessionID, participantId, name, isAgent, createdAt }) => ({ sessionID, participantId, name, isAgent, createdAt })) });
|
|
7473
7706
|
}
|
|
7474
7707
|
if (action && req.method === "POST") {
|
|
7475
7708
|
const roomID = decodeURIComponent(action[1]);
|
|
@@ -7477,10 +7710,10 @@ async function joinRequestRoutes(req, url) {
|
|
|
7477
7710
|
const decision = action[3];
|
|
7478
7711
|
const body = await req.json();
|
|
7479
7712
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
7480
|
-
return
|
|
7713
|
+
return json9({ error: "JSON object body is required" }, 400);
|
|
7481
7714
|
const actor = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
7482
7715
|
if (!bounded2(actor))
|
|
7483
|
-
return
|
|
7716
|
+
return json9({ error: "sessionID is required" }, 400);
|
|
7484
7717
|
const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
|
|
7485
7718
|
const room = svc.getRoom(roomID);
|
|
7486
7719
|
const actorEntry = registry[roomID]?.[actor];
|
|
@@ -7519,11 +7752,11 @@ async function joinRequestRoutes(req, url) {
|
|
|
7519
7752
|
});
|
|
7520
7753
|
return { ok: true };
|
|
7521
7754
|
});
|
|
7522
|
-
return "ok" in result ?
|
|
7755
|
+
return "ok" in result ? json9({ ok: true }) : json9({ error: result.error }, result.status);
|
|
7523
7756
|
}
|
|
7524
|
-
return
|
|
7757
|
+
return json9({ error: "method not allowed" }, 405);
|
|
7525
7758
|
}
|
|
7526
|
-
var
|
|
7759
|
+
var json9 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
|
|
7527
7760
|
var init_join_requests = __esm(() => {
|
|
7528
7761
|
init_store();
|
|
7529
7762
|
init_sqlite_state();
|
|
@@ -7672,16 +7905,16 @@ async function roomReminderRoutes(req, url) {
|
|
|
7672
7905
|
return null;
|
|
7673
7906
|
return db.query("SELECT * FROM room_reminders WHERE room_id=? ORDER BY created_at,id").all(room);
|
|
7674
7907
|
});
|
|
7675
|
-
return items ?
|
|
7908
|
+
return items ? json10({ reminders: items.map(output) }) : json10({ error: "room not found or session is not a current member" }, 404);
|
|
7676
7909
|
}
|
|
7677
7910
|
if (req.method !== "POST" && req.method !== "PATCH" && req.method !== "DELETE")
|
|
7678
|
-
return
|
|
7911
|
+
return json10({ error: "method not allowed" }, 405);
|
|
7679
7912
|
const body = await req.json();
|
|
7680
7913
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
7681
|
-
return
|
|
7914
|
+
return json10({ error: "JSON object body is required" }, 400);
|
|
7682
7915
|
const input = body, session = input.sessionID;
|
|
7683
7916
|
if (typeof session !== "string" || !session || session.length > 128)
|
|
7684
|
-
return
|
|
7917
|
+
return json10({ error: "sessionID is required" }, 400);
|
|
7685
7918
|
const result = await withStateTransaction(dbFile(), (db) => {
|
|
7686
7919
|
const who = member(db, room, session);
|
|
7687
7920
|
if (!who)
|
|
@@ -7733,7 +7966,7 @@ async function roomReminderRoutes(req, url) {
|
|
|
7733
7966
|
}
|
|
7734
7967
|
});
|
|
7735
7968
|
const { status, ...bodyOut } = result;
|
|
7736
|
-
return
|
|
7969
|
+
return json10(bodyOut, status);
|
|
7737
7970
|
}
|
|
7738
7971
|
async function tickRoomReminders(now = Date.now(), wake) {
|
|
7739
7972
|
await initializeReminderSchema(dbFile());
|
|
@@ -7789,164 +8022,2197 @@ function startRoomReminderScheduler(wake) {
|
|
|
7789
8022
|
}, 1000);
|
|
7790
8023
|
timer2.unref?.();
|
|
7791
8024
|
}
|
|
7792
|
-
var
|
|
8025
|
+
var json10 = (body, status = 200) => Response.json(body, { status }), dbFile = () => databasePath(), timer2;
|
|
7793
8026
|
var init_room_reminders = __esm(() => {
|
|
7794
8027
|
init_store();
|
|
7795
8028
|
init_sqlite_state();
|
|
7796
8029
|
});
|
|
7797
8030
|
|
|
7798
|
-
//
|
|
7799
|
-
import {
|
|
7800
|
-
|
|
7801
|
-
|
|
7802
|
-
|
|
7803
|
-
function parsePort(value) {
|
|
7804
|
-
const port = Number(value);
|
|
7805
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
7806
|
-
throw new Error(`Invalid server port "${value}": expected an integer from 1 to 65535`);
|
|
8031
|
+
// packages/chat-room-channeld/src/config.ts
|
|
8032
|
+
import { parse as parseYaml2 } from "yaml";
|
|
8033
|
+
function record2(value, where) {
|
|
8034
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
8035
|
+
throw new ConfigError(`config: ${where} must be a mapping`);
|
|
7807
8036
|
}
|
|
7808
|
-
return
|
|
8037
|
+
return value;
|
|
7809
8038
|
}
|
|
7810
|
-
function
|
|
7811
|
-
|
|
8039
|
+
function stringValue(value, where) {
|
|
8040
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
8041
|
+
throw new ConfigError(`config: ${where} must be a non-empty string`);
|
|
8042
|
+
}
|
|
8043
|
+
return value;
|
|
7812
8044
|
}
|
|
7813
|
-
function
|
|
7814
|
-
|
|
8045
|
+
function identifierValue(value, where) {
|
|
8046
|
+
const text = stringValue(value, where);
|
|
8047
|
+
if (!IDENTIFIER.test(text)) {
|
|
8048
|
+
throw new ConfigError(`config: ${where} must match /^[A-Za-z0-9._-]+$/ (letters, digits, dot, underscore, hyphen; "/" is not allowed)`);
|
|
8049
|
+
}
|
|
8050
|
+
return text;
|
|
7815
8051
|
}
|
|
7816
|
-
|
|
7817
|
-
|
|
7818
|
-
|
|
7819
|
-
|
|
7820
|
-
|
|
8052
|
+
function optionalString2(value, where) {
|
|
8053
|
+
if (value === undefined)
|
|
8054
|
+
return;
|
|
8055
|
+
return stringValue(value, where);
|
|
8056
|
+
}
|
|
8057
|
+
function arrayValue(value, where) {
|
|
8058
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
8059
|
+
throw new ConfigError(`config: ${where} must be a non-empty array`);
|
|
7821
8060
|
}
|
|
7822
|
-
|
|
7823
|
-
|
|
7824
|
-
|
|
7825
|
-
|
|
7826
|
-
|
|
7827
|
-
|
|
7828
|
-
|
|
7829
|
-
|
|
7830
|
-
|
|
7831
|
-
|
|
8061
|
+
return value;
|
|
8062
|
+
}
|
|
8063
|
+
function parseTarget(value, where) {
|
|
8064
|
+
const raw = record2(value, where);
|
|
8065
|
+
return {
|
|
8066
|
+
platform: identifierValue(raw.platform, `${where}.platform`),
|
|
8067
|
+
account: identifierValue(raw.account, `${where}.account`),
|
|
8068
|
+
room: identifierValue(raw.room, `${where}.room`)
|
|
8069
|
+
};
|
|
8070
|
+
}
|
|
8071
|
+
function parseTransform(value, where) {
|
|
8072
|
+
const raw = record2(value, where);
|
|
8073
|
+
switch (raw.op) {
|
|
8074
|
+
case "prefix-source":
|
|
8075
|
+
case "trim":
|
|
8076
|
+
case "quote-preview":
|
|
8077
|
+
return { op: raw.op };
|
|
8078
|
+
case "truncate": {
|
|
8079
|
+
if (typeof raw.max !== "number" || !Number.isInteger(raw.max) || raw.max < 1) {
|
|
8080
|
+
throw new ConfigError(`config: ${where}.max must be a positive integer`);
|
|
7832
8081
|
}
|
|
7833
|
-
|
|
8082
|
+
return { op: "truncate", max: raw.max };
|
|
8083
|
+
}
|
|
8084
|
+
default:
|
|
8085
|
+
throw new ConfigError(`config: ${where}.op must be one of prefix-source, trim, truncate, quote-preview`);
|
|
7834
8086
|
}
|
|
7835
|
-
|
|
7836
|
-
|
|
7837
|
-
|
|
7838
|
-
|
|
7839
|
-
|
|
7840
|
-
|
|
7841
|
-
})
|
|
8087
|
+
}
|
|
8088
|
+
function parseAccount(value, where) {
|
|
8089
|
+
const raw = record2(value, where);
|
|
8090
|
+
const adapter = record2(raw.adapter, `${where}.adapter`);
|
|
8091
|
+
const command = arrayValue(adapter.command, `${where}.adapter.command`).map((item, index) => stringValue(item, `${where}.adapter.command[${index}]`));
|
|
8092
|
+
return {
|
|
8093
|
+
id: identifierValue(raw.id, `${where}.id`),
|
|
8094
|
+
platform: identifierValue(raw.platform, `${where}.platform`),
|
|
8095
|
+
adapter: { command, runtime: optionalString2(adapter.runtime, `${where}.adapter.runtime`) }
|
|
8096
|
+
};
|
|
8097
|
+
}
|
|
8098
|
+
function parseRule(value, where) {
|
|
8099
|
+
const raw = record2(value, where);
|
|
8100
|
+
const from = record2(raw.from, `${where}.from`);
|
|
8101
|
+
const version = raw.version;
|
|
8102
|
+
if (typeof version !== "number" || !Number.isInteger(version) || version < 1) {
|
|
8103
|
+
throw new ConfigError(`config: ${where}.version must be a positive integer`);
|
|
7842
8104
|
}
|
|
7843
|
-
|
|
7844
|
-
|
|
7845
|
-
|
|
7846
|
-
|
|
7847
|
-
const version = await chatVersionTag() || "dev";
|
|
7848
|
-
return new Response(body.replaceAll("{{version}}", version), {
|
|
7849
|
-
headers: {
|
|
7850
|
-
"Content-Type": "text/javascript; charset=utf-8",
|
|
7851
|
-
"Cache-Control": "no-store",
|
|
7852
|
-
"Service-Worker-Allowed": "/"
|
|
7853
|
-
}
|
|
7854
|
-
});
|
|
8105
|
+
const transforms = raw.transforms === undefined ? [] : arrayValueAllowEmpty(raw.transforms, `${where}.transforms`).map((item, index) => parseTransform(item, `${where}.transforms[${index}]`));
|
|
8106
|
+
const missingParent = optionalString2(raw.onMissingParent, `${where}.onMissingParent`);
|
|
8107
|
+
if (missingParent !== undefined && missingParent !== "quote_or_unthreaded" && missingParent !== "drop") {
|
|
8108
|
+
throw new ConfigError(`config: ${where}.onMissingParent must be quote_or_unthreaded or drop`);
|
|
7855
8109
|
}
|
|
7856
|
-
|
|
7857
|
-
|
|
8110
|
+
const unsupported = optionalString2(raw.onUnsupported, `${where}.onUnsupported`);
|
|
8111
|
+
if (unsupported !== undefined && unsupported !== "text_with_notice" && unsupported !== "drop") {
|
|
8112
|
+
throw new ConfigError(`config: ${where}.onUnsupported must be text_with_notice or drop`);
|
|
8113
|
+
}
|
|
8114
|
+
return {
|
|
8115
|
+
id: stringValue(raw.id, `${where}.id`),
|
|
8116
|
+
version,
|
|
8117
|
+
from: {
|
|
8118
|
+
...parseTarget({ platform: from.platform, account: from.account, room: from.room }, `${where}.from`),
|
|
8119
|
+
event: optionalString2(from.event, `${where}.from.event`)
|
|
8120
|
+
},
|
|
8121
|
+
transforms,
|
|
8122
|
+
to: arrayValue(raw.to, `${where}.to`).map((item, index) => parseTarget(item, `${where}.to[${index}]`)),
|
|
8123
|
+
onMissingParent: missingParent ?? "quote_or_unthreaded",
|
|
8124
|
+
onUnsupported: unsupported ?? "text_with_notice"
|
|
8125
|
+
};
|
|
8126
|
+
}
|
|
8127
|
+
function arrayValueAllowEmpty(value, where) {
|
|
8128
|
+
if (!Array.isArray(value))
|
|
8129
|
+
throw new ConfigError(`config: ${where} must be an array`);
|
|
8130
|
+
return value;
|
|
8131
|
+
}
|
|
8132
|
+
function parseConfig(value) {
|
|
8133
|
+
const raw = record2(value, "root");
|
|
8134
|
+
const stateFile = stringValue(raw.stateFile, "stateFile");
|
|
8135
|
+
const accounts = arrayValue(raw.accounts, "accounts").map((item, index) => parseAccount(item, `accounts[${index}]`));
|
|
8136
|
+
const rules = raw.rules === undefined ? [] : arrayValueAllowEmpty(raw.rules, "rules").map((item, index) => parseRule(item, `rules[${index}]`));
|
|
8137
|
+
const accountIds = new Set;
|
|
8138
|
+
for (const account of accounts) {
|
|
8139
|
+
if (accountIds.has(account.id))
|
|
8140
|
+
throw new ConfigError(`config: duplicate account id "${account.id}"`);
|
|
8141
|
+
accountIds.add(account.id);
|
|
8142
|
+
}
|
|
8143
|
+
const ruleKeys = new Set;
|
|
8144
|
+
for (const rule of rules) {
|
|
8145
|
+
const key = `${rule.id}@${rule.version}`;
|
|
8146
|
+
if (ruleKeys.has(key))
|
|
8147
|
+
throw new ConfigError(`config: duplicate rule "${rule.id}" version ${rule.version}`);
|
|
8148
|
+
ruleKeys.add(key);
|
|
8149
|
+
}
|
|
8150
|
+
return { stateFile, accounts, rules };
|
|
8151
|
+
}
|
|
8152
|
+
var ConfigError, IDENTIFIER;
|
|
8153
|
+
var init_config = __esm(() => {
|
|
8154
|
+
ConfigError = class ConfigError extends Error {
|
|
8155
|
+
constructor(message) {
|
|
8156
|
+
super(message);
|
|
8157
|
+
this.name = "ConfigError";
|
|
8158
|
+
}
|
|
8159
|
+
};
|
|
8160
|
+
IDENTIFIER = /^[A-Za-z0-9._-]+$/;
|
|
8161
|
+
});
|
|
8162
|
+
|
|
8163
|
+
// packages/chat-room-channeld/src/protocol.ts
|
|
8164
|
+
function hostRequestId(sequence) {
|
|
8165
|
+
return `${HOST_ID_PREFIX}${sequence}`;
|
|
8166
|
+
}
|
|
8167
|
+
function rpcRequest(id, method, params) {
|
|
8168
|
+
return params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
|
|
8169
|
+
}
|
|
8170
|
+
function rpcResult(id, result) {
|
|
8171
|
+
return { jsonrpc: "2.0", id, result };
|
|
8172
|
+
}
|
|
8173
|
+
function rpcError(id, code, message, data) {
|
|
8174
|
+
const error = data === undefined ? { code, message } : { code, message, data };
|
|
8175
|
+
return { jsonrpc: "2.0", id, error };
|
|
8176
|
+
}
|
|
8177
|
+
var PROTOCOL_VERSION = 1, EVENT_SCHEMA_VERSION = 1, MAX_FRAME_BYTES = 1048576, HOST_ID_PREFIX = "host-", RPC_METHOD_NOT_FOUND = -32601, RPC_INTERNAL_ERROR = -32603;
|
|
8178
|
+
|
|
8179
|
+
// packages/chat-room-channeld/src/framing.ts
|
|
8180
|
+
import { StringDecoder } from "node:string_decoder";
|
|
8181
|
+
function parseFrame(line) {
|
|
8182
|
+
const text = line.trim();
|
|
8183
|
+
if (!text)
|
|
8184
|
+
throw new Error("empty frame");
|
|
8185
|
+
let value;
|
|
8186
|
+
try {
|
|
8187
|
+
value = JSON.parse(text);
|
|
8188
|
+
} catch (error) {
|
|
8189
|
+
throw new Error(`invalid JSON frame: ${error instanceof Error ? error.message : String(error)}`);
|
|
8190
|
+
}
|
|
8191
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
8192
|
+
throw new Error("frame must be a JSON object");
|
|
8193
|
+
}
|
|
8194
|
+
return value;
|
|
8195
|
+
}
|
|
8196
|
+
function createFrameReader(onMessage, onError) {
|
|
8197
|
+
const decoder = new StringDecoder("utf8");
|
|
8198
|
+
let parts = [];
|
|
8199
|
+
let bytes = 0;
|
|
8200
|
+
let discarding = false;
|
|
8201
|
+
const dispatch = () => {
|
|
8202
|
+
const text = discarding ? "" : parts.join("");
|
|
8203
|
+
const wasDiscarding = discarding;
|
|
8204
|
+
parts = [];
|
|
8205
|
+
bytes = 0;
|
|
8206
|
+
discarding = false;
|
|
8207
|
+
if (wasDiscarding || !text.trim())
|
|
8208
|
+
return;
|
|
7858
8209
|
try {
|
|
7859
|
-
|
|
7860
|
-
} catch {
|
|
7861
|
-
|
|
8210
|
+
onMessage(parseFrame(text));
|
|
8211
|
+
} catch (error) {
|
|
8212
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
7862
8213
|
}
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
|
|
7868
|
-
if (
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
8214
|
+
};
|
|
8215
|
+
const consume = (segment) => {
|
|
8216
|
+
const decoded = decoder.write(segment);
|
|
8217
|
+
if (discarding)
|
|
8218
|
+
return;
|
|
8219
|
+
if (bytes + segment.length > MAX_FRAME_BYTES) {
|
|
8220
|
+
parts = [];
|
|
8221
|
+
bytes = 0;
|
|
8222
|
+
discarding = true;
|
|
8223
|
+
onError(new Error(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`));
|
|
8224
|
+
return;
|
|
8225
|
+
}
|
|
8226
|
+
bytes += segment.length;
|
|
8227
|
+
parts.push(decoded);
|
|
8228
|
+
};
|
|
8229
|
+
return (chunk) => {
|
|
8230
|
+
let start = 0;
|
|
8231
|
+
while (start <= chunk.length) {
|
|
8232
|
+
const newline = chunk.indexOf(10, start);
|
|
8233
|
+
const end = newline === -1 ? chunk.length : newline;
|
|
8234
|
+
consume(chunk.subarray(start, end));
|
|
8235
|
+
if (newline === -1)
|
|
8236
|
+
return;
|
|
8237
|
+
dispatch();
|
|
8238
|
+
start = newline + 1;
|
|
8239
|
+
}
|
|
8240
|
+
};
|
|
8241
|
+
}
|
|
8242
|
+
function writeError(error) {
|
|
8243
|
+
const code = error?.code;
|
|
8244
|
+
if (code && GONE_CODES.has(code))
|
|
8245
|
+
return new AdapterGoneError(`adapter stream is gone (${code})`);
|
|
8246
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
8247
|
+
}
|
|
8248
|
+
function writeFrame(stream, value) {
|
|
8249
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
8250
|
+
throw new TypeError("frame must be a JSON object");
|
|
7872
8251
|
}
|
|
7873
|
-
|
|
7874
|
-
|
|
8252
|
+
const writable = stream;
|
|
8253
|
+
if (writable.destroyed || writable.writableEnded) {
|
|
8254
|
+
throw new AdapterGoneError("adapter stream is closed");
|
|
7875
8255
|
}
|
|
7876
|
-
|
|
7877
|
-
|
|
8256
|
+
const line = `${JSON.stringify(value)}
|
|
8257
|
+
`;
|
|
8258
|
+
if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES) {
|
|
8259
|
+
throw new RangeError(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`);
|
|
7878
8260
|
}
|
|
7879
|
-
|
|
7880
|
-
const
|
|
7881
|
-
|
|
7882
|
-
|
|
7883
|
-
|
|
7884
|
-
|
|
7885
|
-
|
|
7886
|
-
|
|
7887
|
-
if (resource)
|
|
7888
|
-
return resource;
|
|
7889
|
-
const history = await historyRoute(url);
|
|
7890
|
-
if (history)
|
|
7891
|
-
return history;
|
|
7892
|
-
const recall = await messageRecallRoutes(req, url);
|
|
7893
|
-
if (recall)
|
|
7894
|
-
return recall;
|
|
7895
|
-
if (req.method === "GET" && p === "/rooms/summary") {
|
|
7896
|
-
const rooms = await read((svc) => svc.listRooms().map((r) => ({
|
|
7897
|
-
id: r.id,
|
|
7898
|
-
name: r.name,
|
|
7899
|
-
latestMsgTs: r.messages.at(-1)?.createdAt ?? 0
|
|
7900
|
-
})));
|
|
7901
|
-
return json10(rooms);
|
|
7902
|
-
}
|
|
7903
|
-
if (req.method === "GET" && p === "/receiver/memberships") {
|
|
7904
|
-
const ownerID = url.searchParams.get("ownerID");
|
|
7905
|
-
if (!isReceiverOwnerID(ownerID))
|
|
7906
|
-
return json10({ error: "invalid ownerID" }, 400);
|
|
7907
|
-
const sessionIDs = await readState2((_svc, registry) => {
|
|
7908
|
-
return [...new Set(Object.values(registry).flatMap((entries) => Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id)))];
|
|
8261
|
+
return new Promise((resolve, reject) => {
|
|
8262
|
+
const fail = (error) => reject(writeError(error));
|
|
8263
|
+
try {
|
|
8264
|
+
stream.write(line, (error) => {
|
|
8265
|
+
if (error)
|
|
8266
|
+
fail(error);
|
|
8267
|
+
else
|
|
8268
|
+
resolve();
|
|
7909
8269
|
});
|
|
7910
|
-
|
|
8270
|
+
} catch (error) {
|
|
8271
|
+
fail(error);
|
|
7911
8272
|
}
|
|
7912
|
-
|
|
7913
|
-
|
|
7914
|
-
|
|
7915
|
-
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
8273
|
+
});
|
|
8274
|
+
}
|
|
8275
|
+
var AdapterGoneError, GONE_CODES;
|
|
8276
|
+
var init_framing = __esm(() => {
|
|
8277
|
+
AdapterGoneError = class AdapterGoneError extends Error {
|
|
8278
|
+
code = "ADAPTER_GONE";
|
|
8279
|
+
constructor(message) {
|
|
8280
|
+
super(message);
|
|
8281
|
+
this.name = "AdapterGoneError";
|
|
7920
8282
|
}
|
|
7921
|
-
|
|
7922
|
-
|
|
7923
|
-
|
|
7924
|
-
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
8283
|
+
};
|
|
8284
|
+
GONE_CODES = new Set(["EPIPE", "ERR_STREAM_DESTROYED", "ERR_STREAM_WRITE_AFTER_END"]);
|
|
8285
|
+
});
|
|
8286
|
+
|
|
8287
|
+
// packages/chat-room-channeld/src/log.ts
|
|
8288
|
+
function write(level, message, fields = {}) {
|
|
8289
|
+
const parts = [new Date().toISOString(), level, message];
|
|
8290
|
+
if (fields.account)
|
|
8291
|
+
parts.push(`account=${fields.account}`);
|
|
8292
|
+
if (fields.delivery)
|
|
8293
|
+
parts.push(`delivery=${fields.delivery}`);
|
|
8294
|
+
if (fields.event)
|
|
8295
|
+
parts.push(`event=${fields.event}`);
|
|
8296
|
+
process.stderr.write(`${parts.join(" ")}
|
|
8297
|
+
`);
|
|
8298
|
+
}
|
|
8299
|
+
var log;
|
|
8300
|
+
var init_log = __esm(() => {
|
|
8301
|
+
log = {
|
|
8302
|
+
info(message, fields) {
|
|
8303
|
+
write("INFO", message, fields);
|
|
8304
|
+
},
|
|
8305
|
+
warn(message, fields) {
|
|
8306
|
+
write("WARN", message, fields);
|
|
8307
|
+
},
|
|
8308
|
+
error(message, fields) {
|
|
8309
|
+
write("ERROR", message, fields);
|
|
8310
|
+
}
|
|
8311
|
+
};
|
|
8312
|
+
});
|
|
8313
|
+
|
|
8314
|
+
// packages/chat-room-channeld/src/adapter.ts
|
|
8315
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
8316
|
+
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
8317
|
+
|
|
8318
|
+
class AdapterProcess {
|
|
8319
|
+
#account;
|
|
8320
|
+
#onIngest;
|
|
8321
|
+
#onExit;
|
|
8322
|
+
#onUnavailable;
|
|
8323
|
+
#initializeTimeoutMs;
|
|
8324
|
+
#sendTimeoutMs;
|
|
8325
|
+
#pending = new Map;
|
|
8326
|
+
#stderrDecoder = new StringDecoder2("utf8");
|
|
8327
|
+
#child;
|
|
8328
|
+
#sequence = 0;
|
|
8329
|
+
#stderrTail = "";
|
|
8330
|
+
#started = false;
|
|
8331
|
+
#stopping = false;
|
|
8332
|
+
#gone = false;
|
|
8333
|
+
#pollutionError;
|
|
8334
|
+
constructor(options) {
|
|
8335
|
+
this.#account = options.account;
|
|
8336
|
+
this.#onIngest = options.onIngest;
|
|
8337
|
+
this.#onExit = options.onExit;
|
|
8338
|
+
this.#onUnavailable = options.onUnavailable;
|
|
8339
|
+
this.#initializeTimeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;
|
|
8340
|
+
this.#sendTimeoutMs = options.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
|
|
8341
|
+
}
|
|
8342
|
+
get accountId() {
|
|
8343
|
+
return this.#account.id;
|
|
8344
|
+
}
|
|
8345
|
+
async start() {
|
|
8346
|
+
if (this.#child)
|
|
8347
|
+
throw new Error(`adapter ${this.#account.id} already started`);
|
|
8348
|
+
const [command, ...args] = this.#account.adapter.command;
|
|
8349
|
+
if (!command)
|
|
8350
|
+
throw new Error(`adapter ${this.#account.id} has an empty command`);
|
|
8351
|
+
const child = spawn2(command, args, {
|
|
8352
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
8353
|
+
env: {
|
|
8354
|
+
...process.env,
|
|
8355
|
+
CHANNELD_ACCOUNT_ID: this.#account.id,
|
|
8356
|
+
CHANNELD_PLATFORM: this.#account.platform
|
|
8357
|
+
}
|
|
8358
|
+
});
|
|
8359
|
+
this.#child = child;
|
|
8360
|
+
this.#attach(child);
|
|
8361
|
+
try {
|
|
8362
|
+
await this.#call("initialize", {
|
|
8363
|
+
protocolVersions: [PROTOCOL_VERSION],
|
|
8364
|
+
eventSchemas: [EVENT_SCHEMA_VERSION],
|
|
8365
|
+
sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
|
|
8366
|
+
platform: this.#account.platform,
|
|
8367
|
+
accounts: [this.#account.id],
|
|
8368
|
+
maxFrameBytes: MAX_FRAME_BYTES
|
|
8369
|
+
}, this.#initializeTimeoutMs);
|
|
8370
|
+
await this.#call("start", { accounts: [this.#account.id], cursors: {} }, this.#initializeTimeoutMs);
|
|
8371
|
+
} catch (error) {
|
|
8372
|
+
const tail = this.#stderrTail.trim();
|
|
8373
|
+
const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
|
|
8374
|
+
this.#stopping = true;
|
|
8375
|
+
this.#killNow();
|
|
8376
|
+
throw new Error(`adapter ${this.#account.id} failed to start: ${message}${tail ? `
|
|
8377
|
+
stderr:
|
|
8378
|
+
${tail}` : ""}`);
|
|
8379
|
+
}
|
|
8380
|
+
this.#started = true;
|
|
8381
|
+
log.info("adapter started", { account: this.#account.id });
|
|
8382
|
+
}
|
|
8383
|
+
async send(deliveryId, attemptId, idempotencyKey, target, payload) {
|
|
8384
|
+
if (!this.#started || !this.#child) {
|
|
8385
|
+
return { state: "unknown", detail: "adapter is not running" };
|
|
8386
|
+
}
|
|
8387
|
+
try {
|
|
8388
|
+
const result = await this.#call("send", { deliveryId, attemptId, idempotencyKey, target, payload }, this.#sendTimeoutMs);
|
|
8389
|
+
const raw = result ?? {};
|
|
8390
|
+
if (!raw.state || !SEND_STATES.includes(raw.state)) {
|
|
8391
|
+
return { state: "unknown", detail: `adapter returned invalid state: ${String(raw.state)}` };
|
|
8392
|
+
}
|
|
8393
|
+
return {
|
|
8394
|
+
state: raw.state,
|
|
8395
|
+
providerMessage: raw.providerMessage,
|
|
8396
|
+
retryAfterMs: raw.retryAfterMs,
|
|
8397
|
+
detail: raw.detail
|
|
8398
|
+
};
|
|
8399
|
+
} catch (error) {
|
|
8400
|
+
return { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
|
|
8401
|
+
}
|
|
8402
|
+
}
|
|
8403
|
+
async stop() {
|
|
8404
|
+
if (this.#stopping)
|
|
8405
|
+
return;
|
|
8406
|
+
this.#stopping = true;
|
|
8407
|
+
this.#started = false;
|
|
8408
|
+
const child = this.#child;
|
|
8409
|
+
this.#rejectPending(new AdapterGoneError(`adapter ${this.#account.id} stopped`));
|
|
8410
|
+
if (!child) {
|
|
8411
|
+
this.#cleanup();
|
|
8412
|
+
return;
|
|
8413
|
+
}
|
|
8414
|
+
try {
|
|
8415
|
+
try {
|
|
8416
|
+
await this.#call("shutdown", {}, 1000);
|
|
8417
|
+
} catch {}
|
|
8418
|
+
try {
|
|
8419
|
+
child.stdin.end();
|
|
8420
|
+
} catch {}
|
|
8421
|
+
if (await this.#waitForExit(2000))
|
|
8422
|
+
return;
|
|
8423
|
+
child.kill("SIGTERM");
|
|
8424
|
+
if (await this.#waitForExit(1000))
|
|
8425
|
+
return;
|
|
8426
|
+
child.kill("SIGKILL");
|
|
8427
|
+
await this.#waitForExit(1000);
|
|
8428
|
+
} catch (error) {
|
|
8429
|
+
try {
|
|
8430
|
+
log.warn(`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`, { account: this.#account.id });
|
|
8431
|
+
} catch {}
|
|
8432
|
+
} finally {
|
|
8433
|
+
this.#cleanup();
|
|
8434
|
+
}
|
|
8435
|
+
}
|
|
8436
|
+
#attach(child) {
|
|
8437
|
+
child.stdin.on("error", (error) => this.#handleStdioError("stdin", error));
|
|
8438
|
+
child.stdout.on("error", (error) => this.#handleStdioError("stdout", error));
|
|
8439
|
+
child.stderr.on("error", (error) => this.#handleStdioError("stderr", error));
|
|
8440
|
+
const read = createFrameReader((message) => {
|
|
8441
|
+
this.#dispatch(message).catch((error) => {
|
|
8442
|
+
this.#markGone(`adapter ${this.#account.id} dispatch failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
8443
|
+
});
|
|
8444
|
+
}, (error) => this.#handleStdoutPollution(error));
|
|
8445
|
+
child.stdout.on("data", (chunk) => read(chunk));
|
|
8446
|
+
child.stderr.on("data", (chunk) => {
|
|
8447
|
+
const text = this.#stderrDecoder.write(chunk);
|
|
8448
|
+
this.#stderrTail = `${this.#stderrTail}${text}`.slice(-STDERR_TAIL_LIMIT);
|
|
8449
|
+
for (const line of text.split(`
|
|
8450
|
+
`)) {
|
|
8451
|
+
if (line.trim())
|
|
8452
|
+
log.info(line, { account: this.#account.id });
|
|
8453
|
+
}
|
|
8454
|
+
});
|
|
8455
|
+
child.on("error", (error) => {
|
|
8456
|
+
this.#markGone(`adapter process error: ${error.message}`);
|
|
8457
|
+
});
|
|
8458
|
+
child.once("exit", (code, signal) => {
|
|
8459
|
+
this.#detachStreams(child);
|
|
8460
|
+
this.#child = undefined;
|
|
8461
|
+
this.#rejectPending(new Error(`adapter exited (code=${code} signal=${signal})`));
|
|
8462
|
+
if (!this.#stopping && !this.#gone && this.#started) {
|
|
8463
|
+
log.error(`adapter exited code=${code ?? "null"} signal=${signal ?? "none"}`, {
|
|
8464
|
+
account: this.#account.id
|
|
8465
|
+
});
|
|
8466
|
+
this.#onExit(code, signal);
|
|
8467
|
+
}
|
|
8468
|
+
this.#started = false;
|
|
8469
|
+
});
|
|
8470
|
+
}
|
|
8471
|
+
#handleStdioError(streamName, error) {
|
|
8472
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
8473
|
+
this.#markGone(`adapter ${this.#account.id} ${streamName} error: ${message}`);
|
|
8474
|
+
}
|
|
8475
|
+
async#dispatch(message) {
|
|
8476
|
+
const id = message.id;
|
|
8477
|
+
if (id !== undefined && typeof message.method === "string") {
|
|
8478
|
+
await this.#handleRequest(id, message.method, message.params);
|
|
8479
|
+
return;
|
|
8480
|
+
}
|
|
8481
|
+
if (id === undefined) {
|
|
8482
|
+
log.warn("adapter frame has no id", { account: this.#account.id });
|
|
8483
|
+
return;
|
|
8484
|
+
}
|
|
8485
|
+
const pending = this.#pending.get(String(id));
|
|
8486
|
+
if (!pending) {
|
|
8487
|
+
log.warn(`adapter response for unknown id ${String(id)}`, { account: this.#account.id });
|
|
8488
|
+
return;
|
|
8489
|
+
}
|
|
8490
|
+
this.#pending.delete(String(id));
|
|
8491
|
+
clearTimeout(pending.timer);
|
|
8492
|
+
const rpcFailure = message.error;
|
|
8493
|
+
if (rpcFailure) {
|
|
8494
|
+
pending.reject(new Error(rpcFailure.message ?? "adapter JSON-RPC error"));
|
|
8495
|
+
return;
|
|
8496
|
+
}
|
|
8497
|
+
pending.resolve(message.result);
|
|
8498
|
+
}
|
|
8499
|
+
async#handleRequest(id, method, params) {
|
|
8500
|
+
const child = this.#child;
|
|
8501
|
+
if (!child)
|
|
8502
|
+
return;
|
|
8503
|
+
try {
|
|
8504
|
+
if (method === "ingest") {
|
|
8505
|
+
const result = await this.#onIngest(params);
|
|
8506
|
+
await writeFrame(child.stdin, rpcResult(id, result.duplicate ? { duplicate: true } : { committed: true }));
|
|
8507
|
+
} else if (method === "ping") {
|
|
8508
|
+
await writeFrame(child.stdin, rpcResult(id, { pong: true }));
|
|
8509
|
+
} else {
|
|
8510
|
+
await writeFrame(child.stdin, rpcError(id, RPC_METHOD_NOT_FOUND, `method not found: ${method}`));
|
|
8511
|
+
}
|
|
8512
|
+
} catch (error) {
|
|
8513
|
+
if (error instanceof AdapterGoneError) {
|
|
8514
|
+
this.#markGone(error.message);
|
|
8515
|
+
return;
|
|
8516
|
+
}
|
|
8517
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
8518
|
+
const code = error?.code;
|
|
8519
|
+
if (code !== "ingest_buffer_overflow") {
|
|
8520
|
+
try {
|
|
8521
|
+
log.error(`adapter request ${method} failed: ${message}`, { account: this.#account.id });
|
|
8522
|
+
} catch {}
|
|
8523
|
+
}
|
|
8524
|
+
try {
|
|
8525
|
+
await writeFrame(child.stdin, rpcError(id, RPC_INTERNAL_ERROR, message));
|
|
8526
|
+
} catch (writeError) {
|
|
8527
|
+
if (writeError instanceof AdapterGoneError)
|
|
8528
|
+
this.#markGone(writeError.message);
|
|
8529
|
+
}
|
|
8530
|
+
}
|
|
8531
|
+
}
|
|
8532
|
+
#handleStdoutPollution(error) {
|
|
8533
|
+
if (this.#pollutionError)
|
|
8534
|
+
return;
|
|
8535
|
+
const message = `adapter ${this.#account.id} wrote non-protocol output to stdout; adapter stdout may contain protocol frames only, logs must go to stderr`;
|
|
8536
|
+
this.#pollutionError = new Error(message);
|
|
8537
|
+
try {
|
|
8538
|
+
log.error(message, { account: this.#account.id });
|
|
8539
|
+
} catch {}
|
|
8540
|
+
this.#markGone(message, false);
|
|
8541
|
+
}
|
|
8542
|
+
#markGone(reason, logReason = true) {
|
|
8543
|
+
if (this.#gone)
|
|
8544
|
+
return;
|
|
8545
|
+
this.#gone = true;
|
|
8546
|
+
this.#stopping = true;
|
|
8547
|
+
this.#started = false;
|
|
8548
|
+
if (logReason) {
|
|
8549
|
+
try {
|
|
8550
|
+
log.warn(reason, { account: this.#account.id });
|
|
8551
|
+
} catch {}
|
|
8552
|
+
}
|
|
8553
|
+
try {
|
|
8554
|
+
this.#onUnavailable?.(reason);
|
|
8555
|
+
} catch (error) {
|
|
8556
|
+
try {
|
|
8557
|
+
log.error(`adapter unavailable handler failed: ${error instanceof Error ? error.message : String(error)}`, { account: this.#account.id });
|
|
8558
|
+
} catch {}
|
|
8559
|
+
}
|
|
8560
|
+
this.#rejectPending(new AdapterGoneError(reason));
|
|
8561
|
+
try {
|
|
8562
|
+
this.#child?.kill("SIGKILL");
|
|
8563
|
+
} catch {}
|
|
8564
|
+
}
|
|
8565
|
+
#call(method, params, timeoutMs) {
|
|
8566
|
+
return new Promise((resolve, reject) => {
|
|
8567
|
+
if (this.#gone) {
|
|
8568
|
+
reject(new AdapterGoneError(`adapter ${this.#account.id} is gone`));
|
|
8569
|
+
return;
|
|
8570
|
+
}
|
|
8571
|
+
if (this.#pollutionError) {
|
|
8572
|
+
reject(this.#pollutionError);
|
|
8573
|
+
return;
|
|
8574
|
+
}
|
|
8575
|
+
const child = this.#child;
|
|
8576
|
+
if (!child || child.stdin.destroyed || child.stdin.writableEnded) {
|
|
8577
|
+
const error = new AdapterGoneError(`adapter ${this.#account.id} is not running`);
|
|
8578
|
+
reject(error);
|
|
8579
|
+
if (!this.#stopping)
|
|
8580
|
+
this.#markGone(error.message);
|
|
8581
|
+
return;
|
|
8582
|
+
}
|
|
8583
|
+
const id = hostRequestId(++this.#sequence);
|
|
8584
|
+
const timer = setTimeout(() => {
|
|
8585
|
+
this.#pending.delete(id);
|
|
8586
|
+
reject(new Error(`${method} timed out after ${timeoutMs}ms`));
|
|
8587
|
+
}, timeoutMs);
|
|
8588
|
+
this.#pending.set(id, {
|
|
8589
|
+
resolve: (value) => {
|
|
8590
|
+
clearTimeout(timer);
|
|
8591
|
+
resolve(value);
|
|
8592
|
+
},
|
|
8593
|
+
reject: (error) => {
|
|
8594
|
+
clearTimeout(timer);
|
|
8595
|
+
reject(error);
|
|
8596
|
+
},
|
|
8597
|
+
timer
|
|
8598
|
+
});
|
|
8599
|
+
const failedWrite = (error) => {
|
|
8600
|
+
this.#pending.delete(id);
|
|
8601
|
+
clearTimeout(timer);
|
|
8602
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
8603
|
+
if (error instanceof AdapterGoneError && !this.#stopping)
|
|
8604
|
+
this.#markGone(error.message);
|
|
8605
|
+
};
|
|
8606
|
+
try {
|
|
8607
|
+
writeFrame(child.stdin, rpcRequest(id, method, params)).catch(failedWrite);
|
|
8608
|
+
} catch (error) {
|
|
8609
|
+
failedWrite(error);
|
|
8610
|
+
}
|
|
8611
|
+
});
|
|
8612
|
+
}
|
|
8613
|
+
#waitForExit(ms) {
|
|
8614
|
+
const child = this.#child;
|
|
8615
|
+
if (!child || child.exitCode !== null || child.signalCode !== null)
|
|
8616
|
+
return Promise.resolve(true);
|
|
8617
|
+
return new Promise((resolve) => {
|
|
8618
|
+
const timer = setTimeout(() => {
|
|
8619
|
+
child.off("exit", onExit);
|
|
8620
|
+
resolve(false);
|
|
8621
|
+
}, ms);
|
|
8622
|
+
const onExit = () => {
|
|
8623
|
+
clearTimeout(timer);
|
|
8624
|
+
resolve(true);
|
|
8625
|
+
};
|
|
8626
|
+
child.once("exit", onExit);
|
|
8627
|
+
});
|
|
8628
|
+
}
|
|
8629
|
+
#rejectPending(error) {
|
|
8630
|
+
for (const [id, pending] of this.#pending) {
|
|
8631
|
+
this.#pending.delete(id);
|
|
8632
|
+
clearTimeout(pending.timer);
|
|
8633
|
+
pending.reject(error);
|
|
8634
|
+
}
|
|
8635
|
+
}
|
|
8636
|
+
#detachStreams(child) {
|
|
8637
|
+
for (const stream of [child.stdin, child.stdout, child.stderr]) {
|
|
8638
|
+
stream.removeAllListeners();
|
|
8639
|
+
stream.on("error", () => {});
|
|
8640
|
+
}
|
|
8641
|
+
child.removeAllListeners();
|
|
8642
|
+
child.on("error", () => {});
|
|
8643
|
+
}
|
|
8644
|
+
#killNow() {
|
|
8645
|
+
const child = this.#child;
|
|
8646
|
+
this.#child = undefined;
|
|
8647
|
+
this.#started = false;
|
|
8648
|
+
this.#rejectPending(new Error("adapter failed to start"));
|
|
8649
|
+
if (child) {
|
|
8650
|
+
this.#detachStreams(child);
|
|
8651
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
8652
|
+
child.kill("SIGKILL");
|
|
8653
|
+
}
|
|
8654
|
+
}
|
|
8655
|
+
#cleanup() {
|
|
8656
|
+
const child = this.#child;
|
|
8657
|
+
this.#child = undefined;
|
|
8658
|
+
this.#started = false;
|
|
8659
|
+
this.#rejectPending(new Error("adapter stopped"));
|
|
8660
|
+
if (!child)
|
|
8661
|
+
return;
|
|
8662
|
+
this.#detachStreams(child);
|
|
8663
|
+
}
|
|
8664
|
+
}
|
|
8665
|
+
var SEND_STATES, STDERR_TAIL_LIMIT = 4096, DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4, DEFAULT_SEND_TIMEOUT_MS = 15000;
|
|
8666
|
+
var init_adapter = __esm(() => {
|
|
8667
|
+
init_framing();
|
|
8668
|
+
init_log();
|
|
8669
|
+
SEND_STATES = [
|
|
8670
|
+
"sent",
|
|
8671
|
+
"retryable",
|
|
8672
|
+
"rate_limited",
|
|
8673
|
+
"permanent",
|
|
8674
|
+
"unsupported",
|
|
8675
|
+
"unknown"
|
|
8676
|
+
];
|
|
8677
|
+
});
|
|
8678
|
+
|
|
8679
|
+
// packages/chat-room-channeld/src/rules.ts
|
|
8680
|
+
function targetKey(endpoint) {
|
|
8681
|
+
const parts = [endpoint.platform, endpoint.accountId, endpoint.roomId];
|
|
8682
|
+
if (parts.some((part) => !part || part.includes("/"))) {
|
|
8683
|
+
throw new ConfigError('config: platform, account and room must be non-empty and must not contain "/"');
|
|
8684
|
+
}
|
|
8685
|
+
return parts.join("/");
|
|
8686
|
+
}
|
|
8687
|
+
function sameEndpoint(left, right) {
|
|
8688
|
+
return left.platform === right.platform && left.accountId === right.accountId && left.roomId === right.roomId;
|
|
8689
|
+
}
|
|
8690
|
+
function matchRules(config, event) {
|
|
8691
|
+
if (event.kind === "result.published")
|
|
8692
|
+
return [];
|
|
8693
|
+
const latest = new Map;
|
|
8694
|
+
for (const rule of config.rules) {
|
|
8695
|
+
const current = latest.get(rule.id);
|
|
8696
|
+
if (!current || rule.version > current.version)
|
|
8697
|
+
latest.set(rule.id, rule);
|
|
8698
|
+
}
|
|
8699
|
+
return [...latest.values()].filter((rule) => {
|
|
8700
|
+
const { from } = rule;
|
|
8701
|
+
return from.platform === event.source.platform && from.account === event.source.accountId && from.room === event.source.roomId && (from.event === undefined || from.event === event.kind);
|
|
8702
|
+
}).sort((left, right) => left.id === right.id ? left.version - right.version : left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
|
|
8703
|
+
}
|
|
8704
|
+
function renderForTarget(rule, event, target) {
|
|
8705
|
+
let text = event.content?.text ?? "";
|
|
8706
|
+
if (!text)
|
|
8707
|
+
return { text: "", degraded: "empty" };
|
|
8708
|
+
for (const transform of rule.transforms) {
|
|
8709
|
+
switch (transform.op) {
|
|
8710
|
+
case "prefix-source":
|
|
8711
|
+
text = `[${event.source.platform}/${event.source.roomId}] ${text}`;
|
|
8712
|
+
break;
|
|
8713
|
+
case "trim":
|
|
8714
|
+
text = text.trim();
|
|
8715
|
+
break;
|
|
8716
|
+
case "truncate":
|
|
8717
|
+
if (text.length > transform.max)
|
|
8718
|
+
text = `${text.slice(0, transform.max)}…`;
|
|
8719
|
+
break;
|
|
8720
|
+
case "quote-preview": {
|
|
8721
|
+
const quote = event.selectedMessage?.text?.trim();
|
|
8722
|
+
if (quote) {
|
|
8723
|
+
const short = quote.length > QUOTE_PREVIEW_LIMIT ? `${quote.slice(0, QUOTE_PREVIEW_LIMIT)}…` : quote;
|
|
8724
|
+
text = `${text}
|
|
8725
|
+
> ${short}`;
|
|
8726
|
+
}
|
|
8727
|
+
break;
|
|
8728
|
+
}
|
|
8729
|
+
}
|
|
8730
|
+
}
|
|
8731
|
+
if (!text)
|
|
8732
|
+
return { text: "", degraded: "empty" };
|
|
8733
|
+
return { text };
|
|
8734
|
+
}
|
|
8735
|
+
function planPayload(rule, event, target) {
|
|
8736
|
+
const rendered = renderForTarget(rule, event, {
|
|
8737
|
+
platform: target.platform,
|
|
8738
|
+
account: target.accountId,
|
|
8739
|
+
room: target.roomId
|
|
8740
|
+
});
|
|
8741
|
+
let payload;
|
|
8742
|
+
if (rendered.degraded === "empty") {
|
|
8743
|
+
if (rule.onUnsupported === "drop")
|
|
8744
|
+
return { dropped: "rendered text is empty" };
|
|
8745
|
+
payload = { text: UNSUPPORTED_NOTICE, degraded: "empty" };
|
|
8746
|
+
} else {
|
|
8747
|
+
payload = { text: rendered.text };
|
|
8748
|
+
}
|
|
8749
|
+
if (event.parent) {
|
|
8750
|
+
if (sameEndpoint(event.parent.endpoint, target)) {
|
|
8751
|
+
payload.parent = event.parent;
|
|
8752
|
+
} else if (rule.onMissingParent === "drop") {
|
|
8753
|
+
return { dropped: "parent message mapping is unavailable" };
|
|
8754
|
+
} else {
|
|
8755
|
+
payload.degraded = "unthreaded";
|
|
8756
|
+
}
|
|
8757
|
+
}
|
|
8758
|
+
return { payload };
|
|
8759
|
+
}
|
|
8760
|
+
var QUOTE_PREVIEW_LIMIT = 280, UNSUPPORTED_NOTICE = "attachment/format unsupported";
|
|
8761
|
+
var init_rules = __esm(() => {
|
|
8762
|
+
init_config();
|
|
8763
|
+
});
|
|
8764
|
+
|
|
8765
|
+
// packages/chat-room-channeld/src/published.ts
|
|
8766
|
+
function buildPublishedResult(delivery, receipt, now) {
|
|
8767
|
+
const occurredAt = new Date(now).toISOString();
|
|
8768
|
+
return {
|
|
8769
|
+
schemaVersion: EVENT_SCHEMA_VERSION,
|
|
8770
|
+
eventId: `result-${delivery.deliveryId}`,
|
|
8771
|
+
kind: "result.published",
|
|
8772
|
+
source: { platform: "channeld", accountId: "host", roomId: delivery.deliveryId },
|
|
8773
|
+
actor: { platform: "channeld", identityNamespace: "system", nativeUserId: "channeld" },
|
|
8774
|
+
sourceDedupKey: `${PUBLISHED_RESULT_PREFIX}${delivery.deliveryId}`,
|
|
8775
|
+
cause: { rootEventId: delivery.eventId, visitedEndpoints: [], hopCount: 1 },
|
|
8776
|
+
occurredAt,
|
|
8777
|
+
receivedAt: occurredAt,
|
|
8778
|
+
forwardEventId: delivery.eventId,
|
|
8779
|
+
deliveryId: delivery.deliveryId,
|
|
8780
|
+
receiptId: receipt?.receiptId ?? null,
|
|
8781
|
+
state: delivery.state,
|
|
8782
|
+
target: delivery.target
|
|
8783
|
+
};
|
|
8784
|
+
}
|
|
8785
|
+
var PUBLISHED_RESULT_PREFIX = "result.published:";
|
|
8786
|
+
var init_published = () => {};
|
|
8787
|
+
|
|
8788
|
+
// packages/chat-room-channeld/src/stats.ts
|
|
8789
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
8790
|
+
function count(db, sql) {
|
|
8791
|
+
const row = db.prepare(sql).get();
|
|
8792
|
+
return Number(row.count);
|
|
8793
|
+
}
|
|
8794
|
+
function accountKey(target) {
|
|
8795
|
+
const first = target.indexOf("/");
|
|
8796
|
+
if (first < 0)
|
|
8797
|
+
return target;
|
|
8798
|
+
const second = target.indexOf("/", first + 1);
|
|
8799
|
+
return second === -1 ? target : target.slice(0, second);
|
|
8800
|
+
}
|
|
8801
|
+
function readChannelStats(path, now = Date.now()) {
|
|
8802
|
+
let db;
|
|
8803
|
+
try {
|
|
8804
|
+
db = new DatabaseSync2(path, { readOnly: true });
|
|
8805
|
+
db.exec("PRAGMA busy_timeout = 2000");
|
|
8806
|
+
const names = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => String(row.name)));
|
|
8807
|
+
if (REQUIRED_TABLES.some((table) => !names.has(table))) {
|
|
8808
|
+
throw new Error(`channel state not found: ${path}`);
|
|
8809
|
+
}
|
|
8810
|
+
const stateCounts = {};
|
|
8811
|
+
const accounts = new Map;
|
|
8812
|
+
let oldestBacklogAt = null;
|
|
8813
|
+
const rows = db.prepare("SELECT target, state, created_at FROM channel_deliveries").all();
|
|
8814
|
+
for (const row of rows) {
|
|
8815
|
+
const state = String(row.state);
|
|
8816
|
+
stateCounts[state] = (stateCounts[state] ?? 0) + 1;
|
|
8817
|
+
const key = accountKey(String(row.target));
|
|
8818
|
+
let account = accounts.get(key);
|
|
8819
|
+
if (!account) {
|
|
8820
|
+
account = {
|
|
8821
|
+
account: key,
|
|
8822
|
+
queueDepth: 0,
|
|
8823
|
+
oldestBacklogAt: null,
|
|
8824
|
+
unknown: 0,
|
|
8825
|
+
retryable: 0,
|
|
8826
|
+
rateLimited: 0
|
|
8827
|
+
};
|
|
8828
|
+
accounts.set(key, account);
|
|
8829
|
+
}
|
|
8830
|
+
if (state === "unknown")
|
|
8831
|
+
account.unknown += 1;
|
|
8832
|
+
if (state === "retryable")
|
|
8833
|
+
account.retryable += 1;
|
|
8834
|
+
if (state === "rate_limited")
|
|
8835
|
+
account.rateLimited += 1;
|
|
8836
|
+
if (QUEUE_STATES.has(state)) {
|
|
8837
|
+
const createdAt = Number(row.created_at);
|
|
8838
|
+
account.queueDepth += 1;
|
|
8839
|
+
if (account.oldestBacklogAt === null || createdAt < account.oldestBacklogAt) {
|
|
8840
|
+
account.oldestBacklogAt = createdAt;
|
|
8841
|
+
}
|
|
8842
|
+
if (oldestBacklogAt === null || createdAt < oldestBacklogAt) {
|
|
8843
|
+
oldestBacklogAt = createdAt;
|
|
8844
|
+
}
|
|
8845
|
+
}
|
|
8846
|
+
}
|
|
8847
|
+
const pending = stateCounts.pending ?? 0;
|
|
8848
|
+
const retryable = stateCounts.retryable ?? 0;
|
|
8849
|
+
const rateLimited = stateCounts.rate_limited ?? 0;
|
|
8850
|
+
const failed = (stateCounts.permanent ?? 0) + (stateCounts.unsupported ?? 0) + (stateCounts.exhausted ?? 0);
|
|
8851
|
+
return {
|
|
8852
|
+
generatedAt: now,
|
|
8853
|
+
events: count(db, "SELECT COUNT(*) AS count FROM channel_events"),
|
|
8854
|
+
publishedResults: count(db, "SELECT COUNT(*) AS count FROM channel_events WHERE json_extract(payload, '$.kind') = 'result.published'"),
|
|
8855
|
+
eventsWithoutDeliveries: count(db, `SELECT COUNT(*) AS count FROM channel_events e
|
|
8856
|
+
WHERE json_extract(e.payload, '$.kind') IS NOT 'result.published'
|
|
8857
|
+
AND NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.event_id = e.event_id)`),
|
|
8858
|
+
deliveriesWithoutEvent: count(db, `SELECT COUNT(*) AS count FROM channel_deliveries d
|
|
8859
|
+
WHERE NOT EXISTS (SELECT 1 FROM channel_events e WHERE e.event_id = d.event_id)`),
|
|
8860
|
+
receiptsWithoutDelivery: count(db, `SELECT COUNT(*) AS count FROM channel_receipts r
|
|
8861
|
+
WHERE NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.delivery_id = r.delivery_id)`),
|
|
8862
|
+
deliveries: {
|
|
8863
|
+
total: rows.length,
|
|
8864
|
+
pending,
|
|
8865
|
+
inFlight: stateCounts.in_flight ?? 0,
|
|
8866
|
+
retryable,
|
|
8867
|
+
rateLimited,
|
|
8868
|
+
paused: stateCounts.paused ?? 0,
|
|
8869
|
+
unknown: stateCounts.unknown ?? 0,
|
|
8870
|
+
sent: stateCounts.sent ?? 0,
|
|
8871
|
+
failed
|
|
8872
|
+
},
|
|
8873
|
+
queueDepth: pending + retryable + rateLimited,
|
|
8874
|
+
oldestBacklogAt,
|
|
8875
|
+
oldestBacklogAgeMs: oldestBacklogAt === null ? null : now - oldestBacklogAt,
|
|
8876
|
+
accounts: [...accounts.values()].sort((left, right) => left.account < right.account ? -1 : left.account > right.account ? 1 : 0)
|
|
8877
|
+
};
|
|
8878
|
+
} catch (error) {
|
|
8879
|
+
if (error instanceof Error && error.message.startsWith("channel state not found:"))
|
|
8880
|
+
throw error;
|
|
8881
|
+
throw new Error(`channel state not found: ${path}`);
|
|
8882
|
+
} finally {
|
|
8883
|
+
try {
|
|
8884
|
+
db?.close();
|
|
8885
|
+
} catch {}
|
|
8886
|
+
}
|
|
8887
|
+
}
|
|
8888
|
+
var REQUIRED_TABLES, QUEUE_STATES;
|
|
8889
|
+
var init_stats = __esm(() => {
|
|
8890
|
+
REQUIRED_TABLES = ["channel_events", "channel_deliveries", "channel_receipts"];
|
|
8891
|
+
QUEUE_STATES = new Set(["pending", "retryable", "rate_limited"]);
|
|
8892
|
+
});
|
|
8893
|
+
|
|
8894
|
+
// packages/chat-room-channeld/src/state.ts
|
|
8895
|
+
import { randomUUID as randomUUID14 } from "node:crypto";
|
|
8896
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
8897
|
+
function isTerminalDeliveryState(state) {
|
|
8898
|
+
return TERMINAL_DELIVERY_STATES.includes(state);
|
|
8899
|
+
}
|
|
8900
|
+
function transaction(db, fn) {
|
|
8901
|
+
db.exec("BEGIN IMMEDIATE");
|
|
8902
|
+
try {
|
|
8903
|
+
const value = fn();
|
|
8904
|
+
db.exec("COMMIT");
|
|
8905
|
+
return value;
|
|
8906
|
+
} catch (error) {
|
|
8907
|
+
try {
|
|
8908
|
+
db.exec("ROLLBACK");
|
|
8909
|
+
} catch {}
|
|
8910
|
+
throw error;
|
|
8911
|
+
}
|
|
8912
|
+
}
|
|
8913
|
+
function toDelivery(row) {
|
|
8914
|
+
return {
|
|
8915
|
+
deliveryId: String(row.delivery_id),
|
|
8916
|
+
eventId: String(row.event_id),
|
|
8917
|
+
ruleId: String(row.rule_id),
|
|
8918
|
+
ruleVersion: Number(row.rule_version),
|
|
8919
|
+
target: String(row.target),
|
|
8920
|
+
idempotencyKey: String(row.idempotency_key),
|
|
8921
|
+
payload: String(row.payload),
|
|
8922
|
+
state: String(row.state),
|
|
8923
|
+
attemptCount: Number(row.attempt_count),
|
|
8924
|
+
nextAttemptAt: row.next_attempt_at === null ? null : Number(row.next_attempt_at),
|
|
8925
|
+
lastError: row.last_error === null ? null : String(row.last_error),
|
|
8926
|
+
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
8927
|
+
createdAt: Number(row.created_at),
|
|
8928
|
+
updatedAt: Number(row.updated_at)
|
|
8929
|
+
};
|
|
8930
|
+
}
|
|
8931
|
+
function toReceipt(row) {
|
|
8932
|
+
return {
|
|
8933
|
+
receiptId: String(row.receipt_id),
|
|
8934
|
+
deliveryId: String(row.delivery_id),
|
|
8935
|
+
attemptId: String(row.attempt_id),
|
|
8936
|
+
state: String(row.state),
|
|
8937
|
+
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
8938
|
+
detail: row.detail === null ? null : String(row.detail),
|
|
8939
|
+
observedAt: Number(row.observed_at)
|
|
8940
|
+
};
|
|
8941
|
+
}
|
|
8942
|
+
function openState(path) {
|
|
8943
|
+
const db = new DatabaseSync3(path);
|
|
8944
|
+
db.exec(SCHEMA);
|
|
8945
|
+
let closed = false;
|
|
8946
|
+
function getDelivery(deliveryId) {
|
|
8947
|
+
const row = db.prepare("SELECT * FROM channel_deliveries WHERE delivery_id = ?").get(deliveryId);
|
|
8948
|
+
return row ? toDelivery(row) : undefined;
|
|
8949
|
+
}
|
|
8950
|
+
return {
|
|
8951
|
+
commitIngest(event) {
|
|
8952
|
+
return transaction(db, () => {
|
|
8953
|
+
const existing = db.prepare("SELECT event_id FROM channel_events WHERE dedup_key = ?").get(event.sourceDedupKey);
|
|
8954
|
+
if (existing) {
|
|
8955
|
+
return { duplicate: true, existingEventId: String(existing.event_id) };
|
|
8956
|
+
}
|
|
8957
|
+
const max = db.prepare("SELECT COALESCE(MAX(ingress_seq), 0) AS seq FROM channel_events").get();
|
|
8958
|
+
const ingressSeq = event.ingressSeq ?? Number(max.seq) + 1;
|
|
8959
|
+
const stored = { ...event, ingressSeq };
|
|
8960
|
+
db.prepare(`INSERT INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
|
|
8961
|
+
VALUES (?, ?, ?, ?, ?)`).run(event.eventId, event.sourceDedupKey, JSON.stringify(stored), ingressSeq, Date.now());
|
|
8962
|
+
return { duplicate: false, eventId: event.eventId, ingressSeq };
|
|
8963
|
+
});
|
|
8964
|
+
},
|
|
8965
|
+
enqueueDeliveries(triggerEventId, rule, targets, payloads) {
|
|
8966
|
+
if (targets.length !== payloads.length) {
|
|
8967
|
+
throw new Error("enqueueDeliveries: targets and payloads must have the same length");
|
|
8968
|
+
}
|
|
8969
|
+
const now = Date.now();
|
|
8970
|
+
const created = [];
|
|
8971
|
+
transaction(db, () => {
|
|
8972
|
+
const insert = db.prepare(`INSERT OR IGNORE INTO channel_deliveries
|
|
8973
|
+
(delivery_id, event_id, rule_id, rule_version, target, idempotency_key, payload, state, created_at, updated_at)
|
|
8974
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`);
|
|
8975
|
+
targets.forEach((target, index) => {
|
|
8976
|
+
const key = `${target.platform}/${target.account}/${target.room}`;
|
|
8977
|
+
const idempotencyKey = `${triggerEventId}:${rule.id}:${rule.version}:0:${key}`;
|
|
8978
|
+
const deliveryId = `dlv-${randomUUID14()}`;
|
|
8979
|
+
const result = insert.run(deliveryId, triggerEventId, rule.id, rule.version, key, idempotencyKey, payloads[index] ?? "", now, now);
|
|
8980
|
+
if (Number(result.changes) > 0)
|
|
8981
|
+
created.push({ deliveryId, target: key });
|
|
8982
|
+
});
|
|
8983
|
+
});
|
|
8984
|
+
return created;
|
|
8985
|
+
},
|
|
8986
|
+
nextPendingDelivery(accountKey, now) {
|
|
8987
|
+
const prefix = `${accountKey.replace(/\/+$/, "")}/`;
|
|
8988
|
+
const row = db.prepare(`SELECT * FROM channel_deliveries
|
|
8989
|
+
WHERE substr(target, 1, length(?)) = ?
|
|
8990
|
+
AND state IN ('pending', 'retryable', 'rate_limited')
|
|
8991
|
+
AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
|
|
8992
|
+
ORDER BY created_at ASC, delivery_id ASC
|
|
8993
|
+
LIMIT 1`).get(prefix, prefix, now);
|
|
8994
|
+
return row ? toDelivery(row) : undefined;
|
|
8995
|
+
},
|
|
8996
|
+
markDelivery(deliveryId, state, patch = {}) {
|
|
8997
|
+
if (!DELIVERY_STATES.includes(state))
|
|
8998
|
+
throw new Error(`unknown delivery state: ${state}`);
|
|
8999
|
+
const current = getDelivery(deliveryId);
|
|
9000
|
+
if (!current)
|
|
9001
|
+
throw new Error(`delivery not found: ${deliveryId}`);
|
|
9002
|
+
const terminal = isTerminalDeliveryState(state);
|
|
9003
|
+
const nextAttemptAt = patch.nextAttemptAt !== undefined ? patch.nextAttemptAt : terminal ? null : current.nextAttemptAt;
|
|
9004
|
+
db.prepare(`UPDATE channel_deliveries
|
|
9005
|
+
SET state = ?, attempt_count = ?, next_attempt_at = ?, last_error = ?, provider_message = ?, updated_at = ?
|
|
9006
|
+
WHERE delivery_id = ?`).run(state, patch.attemptCount ?? current.attemptCount, nextAttemptAt, patch.lastError !== undefined ? patch.lastError : current.lastError, patch.providerMessage !== undefined ? patch.providerMessage : current.providerMessage, Date.now(), deliveryId);
|
|
9007
|
+
},
|
|
9008
|
+
recordSent(input) {
|
|
9009
|
+
const receiptId = `rcp-${randomUUID14()}`;
|
|
9010
|
+
transaction(db, () => {
|
|
9011
|
+
db.prepare(`INSERT INTO channel_receipts
|
|
9012
|
+
(receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
|
|
9013
|
+
VALUES (?, ?, ?, 'sent', ?, ?, ?)`).run(receiptId, input.deliveryId, input.attemptId, input.providerMessage, input.detail ?? null, input.observedAt ?? Date.now());
|
|
9014
|
+
if (input.echo) {
|
|
9015
|
+
db.prepare(`INSERT OR IGNORE INTO channel_echoes
|
|
9016
|
+
(endpoint, native_message_id, logical_message_id, delivery_id)
|
|
9017
|
+
VALUES (?, ?, ?, ?)`).run(input.echo.endpoint, input.echo.nativeMessageId, input.echo.logicalMessageId, input.deliveryId);
|
|
9018
|
+
}
|
|
9019
|
+
});
|
|
9020
|
+
return receiptId;
|
|
9021
|
+
},
|
|
9022
|
+
pauseAccountDeliveries(accountKey, reason) {
|
|
9023
|
+
const prefix = `${accountKey.replace(/\/+$/, "")}/`;
|
|
9024
|
+
const result = db.prepare(`UPDATE channel_deliveries
|
|
9025
|
+
SET state = 'paused', next_attempt_at = NULL, last_error = ?, updated_at = ?
|
|
9026
|
+
WHERE substr(target, 1, length(?)) = ?
|
|
9027
|
+
AND state IN ('pending', 'retryable', 'rate_limited')`).run(reason, Date.now(), prefix, prefix);
|
|
9028
|
+
return Number(result.changes);
|
|
9029
|
+
},
|
|
9030
|
+
abandonUnconfiguredDeliveries(configuredAccountKeys) {
|
|
9031
|
+
const configured = [...new Set(configuredAccountKeys)];
|
|
9032
|
+
const accountKeySql = `CASE WHEN instr(target, '/') > 0
|
|
9033
|
+
AND instr(substr(target, instr(target, '/') + 1), '/') > 0
|
|
9034
|
+
THEN substr(target, 1, instr(target, '/') + instr(substr(target, instr(target, '/') + 1), '/') - 1)
|
|
9035
|
+
ELSE target END`;
|
|
9036
|
+
const filter = configured.length > 0 ? `AND (${accountKeySql}) NOT IN (${configured.map(() => "?").join(", ")})` : "";
|
|
9037
|
+
const rows = db.prepare(`SELECT * FROM channel_deliveries
|
|
9038
|
+
WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
|
|
9039
|
+
${filter}
|
|
9040
|
+
ORDER BY created_at ASC, delivery_id ASC`).all(...configured);
|
|
9041
|
+
if (rows.length === 0)
|
|
9042
|
+
return [];
|
|
9043
|
+
transaction(db, () => db.prepare(`UPDATE channel_deliveries
|
|
9044
|
+
SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
|
|
9045
|
+
WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
|
|
9046
|
+
${filter}`).run("account is not configured; add it back to retry", Date.now(), ...configured));
|
|
9047
|
+
return rows.map((row) => ({ ...toDelivery(row), state: "unknown" }));
|
|
9048
|
+
},
|
|
9049
|
+
resumePausedDeliveries() {
|
|
9050
|
+
const result = db.prepare(`UPDATE channel_deliveries
|
|
9051
|
+
SET state = 'pending', next_attempt_at = NULL, updated_at = ?
|
|
9052
|
+
WHERE state = 'paused'`).run(Date.now());
|
|
9053
|
+
return Number(result.changes);
|
|
9054
|
+
},
|
|
9055
|
+
recoverInFlightDeliveries() {
|
|
9056
|
+
const result = db.prepare(`UPDATE channel_deliveries
|
|
9057
|
+
SET state = 'pending', next_attempt_at = NULL,
|
|
9058
|
+
last_error = 'recovered stale in_flight after restart', updated_at = ?
|
|
9059
|
+
WHERE state = 'in_flight'`).run(Date.now());
|
|
9060
|
+
return Number(result.changes);
|
|
9061
|
+
},
|
|
9062
|
+
recordReceipt(input) {
|
|
9063
|
+
const receiptId = `rcp-${randomUUID14()}`;
|
|
9064
|
+
db.prepare(`INSERT INTO channel_receipts
|
|
9065
|
+
(receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
|
|
9066
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(receiptId, input.deliveryId, input.attemptId, input.state, input.providerMessage ?? null, input.detail ?? null, input.observedAt ?? Date.now());
|
|
9067
|
+
return receiptId;
|
|
9068
|
+
},
|
|
9069
|
+
recordPublishedResult(delivery, receipt) {
|
|
9070
|
+
const now = Date.now();
|
|
9071
|
+
const event = buildPublishedResult(delivery, receipt, now);
|
|
9072
|
+
db.prepare(`INSERT OR IGNORE INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
|
|
9073
|
+
VALUES (?, ?, ?, NULL, ?)`).run(event.eventId, event.sourceDedupKey, JSON.stringify(event), now);
|
|
9074
|
+
},
|
|
9075
|
+
getPublishedResult(deliveryId) {
|
|
9076
|
+
const row = db.prepare("SELECT payload FROM channel_events WHERE dedup_key = ?").get(`${PUBLISHED_RESULT_PREFIX}${deliveryId}`);
|
|
9077
|
+
return row ? JSON.parse(String(row.payload)) : undefined;
|
|
9078
|
+
},
|
|
9079
|
+
recordEcho(endpoint, nativeMessageId, logicalMessageId, deliveryId) {
|
|
9080
|
+
db.prepare(`INSERT OR IGNORE INTO channel_echoes
|
|
9081
|
+
(endpoint, native_message_id, logical_message_id, delivery_id)
|
|
9082
|
+
VALUES (?, ?, ?, ?)`).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null);
|
|
9083
|
+
},
|
|
9084
|
+
findEcho(endpoint, nativeMessageId) {
|
|
9085
|
+
const row = db.prepare("SELECT logical_message_id FROM channel_echoes WHERE endpoint = ? AND native_message_id = ?").get(endpoint, nativeMessageId);
|
|
9086
|
+
return row ? String(row.logical_message_id) : undefined;
|
|
9087
|
+
},
|
|
9088
|
+
getDelivery,
|
|
9089
|
+
getEvent(eventId) {
|
|
9090
|
+
const row = db.prepare("SELECT payload FROM channel_events WHERE event_id = ?").get(eventId);
|
|
9091
|
+
return row ? JSON.parse(String(row.payload)) : undefined;
|
|
9092
|
+
},
|
|
9093
|
+
listDeliveries() {
|
|
9094
|
+
return db.prepare("SELECT * FROM channel_deliveries ORDER BY created_at ASC, delivery_id ASC").all().map(toDelivery);
|
|
9095
|
+
},
|
|
9096
|
+
listReceipts(deliveryId) {
|
|
9097
|
+
return db.prepare("SELECT * FROM channel_receipts WHERE delivery_id = ? ORDER BY observed_at ASC, receipt_id ASC").all(deliveryId).map(toReceipt);
|
|
9098
|
+
},
|
|
9099
|
+
countEvents() {
|
|
9100
|
+
const row = db.prepare("SELECT COUNT(*) AS count FROM channel_events WHERE dedup_key NOT LIKE ?").get(`${PUBLISHED_RESULT_PREFIX}%`);
|
|
9101
|
+
return Number(row.count);
|
|
9102
|
+
},
|
|
9103
|
+
close() {
|
|
9104
|
+
if (closed)
|
|
9105
|
+
return;
|
|
9106
|
+
closed = true;
|
|
9107
|
+
db.close();
|
|
9108
|
+
}
|
|
9109
|
+
};
|
|
9110
|
+
}
|
|
9111
|
+
var DELIVERY_STATES, TERMINAL_DELIVERY_STATES, SCHEMA = `
|
|
9112
|
+
CREATE TABLE IF NOT EXISTS channel_events (
|
|
9113
|
+
event_id TEXT PRIMARY KEY,
|
|
9114
|
+
dedup_key TEXT NOT NULL UNIQUE,
|
|
9115
|
+
payload TEXT NOT NULL,
|
|
9116
|
+
ingress_seq INTEGER,
|
|
9117
|
+
committed_at INTEGER NOT NULL
|
|
9118
|
+
);
|
|
9119
|
+
CREATE TABLE IF NOT EXISTS channel_deliveries (
|
|
9120
|
+
delivery_id TEXT PRIMARY KEY,
|
|
9121
|
+
event_id TEXT NOT NULL,
|
|
9122
|
+
rule_id TEXT NOT NULL,
|
|
9123
|
+
rule_version INTEGER NOT NULL,
|
|
9124
|
+
target TEXT NOT NULL,
|
|
9125
|
+
idempotency_key TEXT NOT NULL UNIQUE,
|
|
9126
|
+
payload TEXT NOT NULL,
|
|
9127
|
+
state TEXT NOT NULL,
|
|
9128
|
+
attempt_count INTEGER NOT NULL DEFAULT 0,
|
|
9129
|
+
next_attempt_at INTEGER,
|
|
9130
|
+
last_error TEXT,
|
|
9131
|
+
provider_message TEXT,
|
|
9132
|
+
created_at INTEGER NOT NULL,
|
|
9133
|
+
updated_at INTEGER NOT NULL
|
|
9134
|
+
);
|
|
9135
|
+
CREATE TABLE IF NOT EXISTS channel_receipts (
|
|
9136
|
+
receipt_id TEXT PRIMARY KEY,
|
|
9137
|
+
delivery_id TEXT NOT NULL,
|
|
9138
|
+
attempt_id TEXT NOT NULL,
|
|
9139
|
+
state TEXT NOT NULL,
|
|
9140
|
+
provider_message TEXT,
|
|
9141
|
+
detail TEXT,
|
|
9142
|
+
observed_at INTEGER NOT NULL
|
|
9143
|
+
);
|
|
9144
|
+
CREATE TABLE IF NOT EXISTS channel_echoes (
|
|
9145
|
+
endpoint TEXT NOT NULL,
|
|
9146
|
+
native_message_id TEXT NOT NULL,
|
|
9147
|
+
logical_message_id TEXT NOT NULL,
|
|
9148
|
+
delivery_id TEXT,
|
|
9149
|
+
PRIMARY KEY (endpoint, native_message_id)
|
|
9150
|
+
);
|
|
9151
|
+
`;
|
|
9152
|
+
var init_state = __esm(() => {
|
|
9153
|
+
init_published();
|
|
9154
|
+
init_stats();
|
|
9155
|
+
DELIVERY_STATES = [
|
|
9156
|
+
"pending",
|
|
9157
|
+
"in_flight",
|
|
9158
|
+
"sent",
|
|
9159
|
+
"retryable",
|
|
9160
|
+
"rate_limited",
|
|
9161
|
+
"permanent",
|
|
9162
|
+
"unsupported",
|
|
9163
|
+
"unknown",
|
|
9164
|
+
"exhausted",
|
|
9165
|
+
"paused"
|
|
9166
|
+
];
|
|
9167
|
+
TERMINAL_DELIVERY_STATES = [
|
|
9168
|
+
"sent",
|
|
9169
|
+
"permanent",
|
|
9170
|
+
"unsupported",
|
|
9171
|
+
"exhausted",
|
|
9172
|
+
"unknown"
|
|
9173
|
+
];
|
|
9174
|
+
});
|
|
9175
|
+
|
|
9176
|
+
// packages/chat-room-channeld/src/delivery.ts
|
|
9177
|
+
function notifyDeliveryResult(state, deliveryId, handler, options) {
|
|
9178
|
+
if (options.notified.has(deliveryId))
|
|
9179
|
+
return;
|
|
9180
|
+
const delivery = state.getDelivery(deliveryId);
|
|
9181
|
+
if (!delivery || !isTerminalDeliveryState(delivery.state))
|
|
9182
|
+
return;
|
|
9183
|
+
const receipt = options.attemptId ? state.listReceipts(deliveryId).find((item) => item.attemptId === options.attemptId) : undefined;
|
|
9184
|
+
options.notified.add(deliveryId);
|
|
9185
|
+
try {
|
|
9186
|
+
state.recordPublishedResult(delivery, receipt);
|
|
9187
|
+
} catch (error) {
|
|
9188
|
+
log.warn(`could not record result.published: ${error instanceof Error ? error.message : String(error)}`, {
|
|
9189
|
+
delivery: deliveryId
|
|
9190
|
+
});
|
|
9191
|
+
}
|
|
9192
|
+
if (!handler)
|
|
9193
|
+
return;
|
|
9194
|
+
try {
|
|
9195
|
+
handler(state.getEvent(delivery.eventId), delivery, receipt);
|
|
9196
|
+
} catch (error) {
|
|
9197
|
+
log.warn(`onDeliveryResult failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
9198
|
+
delivery: deliveryId
|
|
9199
|
+
});
|
|
9200
|
+
}
|
|
9201
|
+
}
|
|
9202
|
+
function applyReceipt(state, row, attemptId, accountId, receipt, now) {
|
|
9203
|
+
const providerMessage = receipt.providerMessage ? JSON.stringify(receipt.providerMessage) : undefined;
|
|
9204
|
+
switch (receipt.state) {
|
|
9205
|
+
case "sent": {
|
|
9206
|
+
state.markDelivery(row.deliveryId, "sent", {
|
|
9207
|
+
providerMessage: providerMessage ?? null,
|
|
9208
|
+
lastError: null
|
|
9209
|
+
});
|
|
9210
|
+
const echo = receipt.providerMessage?.nativeMessageId && receipt.providerMessage.endpoint ? {
|
|
9211
|
+
endpoint: targetKey(receipt.providerMessage.endpoint),
|
|
9212
|
+
nativeMessageId: receipt.providerMessage.nativeMessageId,
|
|
9213
|
+
logicalMessageId: row.eventId
|
|
9214
|
+
} : undefined;
|
|
9215
|
+
state.recordSent({
|
|
9216
|
+
deliveryId: row.deliveryId,
|
|
9217
|
+
attemptId,
|
|
9218
|
+
providerMessage: providerMessage ?? null,
|
|
9219
|
+
detail: receipt.detail ?? null,
|
|
9220
|
+
echo
|
|
9221
|
+
});
|
|
9222
|
+
log.info("delivery sent", { account: accountId, delivery: row.deliveryId });
|
|
9223
|
+
break;
|
|
9224
|
+
}
|
|
9225
|
+
case "retryable":
|
|
9226
|
+
case "rate_limited": {
|
|
9227
|
+
if (attemptCount(row) >= MAX_ATTEMPTS) {
|
|
9228
|
+
state.markDelivery(row.deliveryId, "exhausted", {
|
|
9229
|
+
lastError: receipt.detail ?? "attempt limit reached"
|
|
9230
|
+
});
|
|
9231
|
+
state.recordReceipt({
|
|
9232
|
+
deliveryId: row.deliveryId,
|
|
9233
|
+
attemptId,
|
|
9234
|
+
state: "exhausted",
|
|
9235
|
+
detail: receipt.detail ?? "attempt limit reached"
|
|
9236
|
+
});
|
|
9237
|
+
log.error(`delivery exhausted after ${attemptCount(row)} attempts`, {
|
|
9238
|
+
account: accountId,
|
|
9239
|
+
delivery: row.deliveryId
|
|
9240
|
+
});
|
|
9241
|
+
break;
|
|
9242
|
+
}
|
|
9243
|
+
const delay = receipt.retryAfterMs ?? Math.min(2 ** attemptCount(row) * RETRY_BASE_MS, MAX_BACKOFF_MS);
|
|
9244
|
+
state.markDelivery(row.deliveryId, receipt.state, {
|
|
9245
|
+
nextAttemptAt: now + delay,
|
|
9246
|
+
lastError: receipt.detail ?? null
|
|
9247
|
+
});
|
|
9248
|
+
state.recordReceipt({
|
|
9249
|
+
deliveryId: row.deliveryId,
|
|
9250
|
+
attemptId,
|
|
9251
|
+
state: receipt.state,
|
|
9252
|
+
detail: receipt.detail ?? null
|
|
9253
|
+
});
|
|
9254
|
+
log.warn(`delivery ${receipt.state}; retry in ${delay}ms`, {
|
|
9255
|
+
account: accountId,
|
|
9256
|
+
delivery: row.deliveryId
|
|
9257
|
+
});
|
|
9258
|
+
break;
|
|
9259
|
+
}
|
|
9260
|
+
case "unknown": {
|
|
9261
|
+
state.markDelivery(row.deliveryId, "unknown", {
|
|
9262
|
+
lastError: receipt.detail ?? "unknown platform outcome"
|
|
9263
|
+
});
|
|
9264
|
+
state.recordReceipt({
|
|
9265
|
+
deliveryId: row.deliveryId,
|
|
9266
|
+
attemptId,
|
|
9267
|
+
state: "unknown",
|
|
9268
|
+
detail: receipt.detail ?? null
|
|
9269
|
+
});
|
|
9270
|
+
log.warn("delivery unknown; not retried", { account: accountId, delivery: row.deliveryId });
|
|
9271
|
+
break;
|
|
9272
|
+
}
|
|
9273
|
+
case "permanent":
|
|
9274
|
+
case "unsupported": {
|
|
9275
|
+
state.markDelivery(row.deliveryId, receipt.state, {
|
|
9276
|
+
lastError: receipt.detail ?? null
|
|
9277
|
+
});
|
|
9278
|
+
state.recordReceipt({
|
|
9279
|
+
deliveryId: row.deliveryId,
|
|
9280
|
+
attemptId,
|
|
9281
|
+
state: receipt.state,
|
|
9282
|
+
detail: receipt.detail ?? null
|
|
9283
|
+
});
|
|
9284
|
+
log.error(`delivery ${receipt.state}`, { account: accountId, delivery: row.deliveryId });
|
|
9285
|
+
break;
|
|
9286
|
+
}
|
|
9287
|
+
}
|
|
9288
|
+
}
|
|
9289
|
+
function attemptCount(row) {
|
|
9290
|
+
return row.attemptCount + 1;
|
|
9291
|
+
}
|
|
9292
|
+
var MAX_ATTEMPTS = 8, MAX_BACKOFF_MS = 30000, RETRY_BASE_MS = 500;
|
|
9293
|
+
var init_delivery = __esm(() => {
|
|
9294
|
+
init_log();
|
|
9295
|
+
init_rules();
|
|
9296
|
+
init_state();
|
|
9297
|
+
});
|
|
9298
|
+
|
|
9299
|
+
// packages/chat-room-channeld/src/host-helpers.ts
|
|
9300
|
+
function parseTarget2(value) {
|
|
9301
|
+
const parts = value.split("/");
|
|
9302
|
+
if (parts.length !== 3)
|
|
9303
|
+
return;
|
|
9304
|
+
const [platform, accountId, roomId] = parts;
|
|
9305
|
+
if (!platform || !accountId || !roomId)
|
|
9306
|
+
return;
|
|
9307
|
+
return { platform, accountId, roomId };
|
|
9308
|
+
}
|
|
9309
|
+
function startFailureReason(accountId, error) {
|
|
9310
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
9311
|
+
const prefix = `adapter ${accountId} failed to start: `;
|
|
9312
|
+
return message.startsWith(prefix) ? message.slice(prefix.length) : message;
|
|
9313
|
+
}
|
|
9314
|
+
function validateTargets(config) {
|
|
9315
|
+
const accounts = new Map(config.accounts.map((account) => [account.id, account]));
|
|
9316
|
+
for (const rule of config.rules) {
|
|
9317
|
+
for (const target of rule.to) {
|
|
9318
|
+
const account = accounts.get(target.account);
|
|
9319
|
+
if (!account) {
|
|
9320
|
+
throw new Error(`config: rule "${rule.id}" targets unknown account "${target.account}"`);
|
|
9321
|
+
}
|
|
9322
|
+
if (account.platform !== target.platform) {
|
|
9323
|
+
throw new Error(`config: rule "${rule.id}" targets platform "${target.platform}" but account "${target.account}" is "${account.platform}"`);
|
|
9324
|
+
}
|
|
9325
|
+
}
|
|
9326
|
+
}
|
|
9327
|
+
}
|
|
9328
|
+
function toEndpoint(config, ruleId, target) {
|
|
9329
|
+
const account = config.accounts.find((item) => item.id === target.account);
|
|
9330
|
+
if (!account) {
|
|
9331
|
+
throw new Error(`config: rule "${ruleId}" targets unknown account "${target.account}"`);
|
|
9332
|
+
}
|
|
9333
|
+
return { platform: target.platform, accountId: account.id, roomId: target.room };
|
|
9334
|
+
}
|
|
9335
|
+
|
|
9336
|
+
// packages/chat-room-channeld/src/ingest-gate.ts
|
|
9337
|
+
class IngestGate {
|
|
9338
|
+
#onOverflow;
|
|
9339
|
+
#gates = new Map;
|
|
9340
|
+
constructor(onOverflow) {
|
|
9341
|
+
this.#onOverflow = onOverflow;
|
|
9342
|
+
}
|
|
9343
|
+
begin(accountId) {
|
|
9344
|
+
const gate = this.#gate(accountId);
|
|
9345
|
+
gate.sends += 1;
|
|
9346
|
+
}
|
|
9347
|
+
async finish(accountId, process2) {
|
|
9348
|
+
const gate = this.#gates.get(accountId);
|
|
9349
|
+
if (!gate)
|
|
9350
|
+
return;
|
|
9351
|
+
gate.sends = Math.max(0, gate.sends - 1);
|
|
9352
|
+
if (gate.sends > 0 || gate.draining)
|
|
9353
|
+
return;
|
|
9354
|
+
gate.draining = true;
|
|
9355
|
+
try {
|
|
9356
|
+
while (gate.queue.length > 0) {
|
|
9357
|
+
const item = gate.queue.shift();
|
|
9358
|
+
try {
|
|
9359
|
+
item.resolve(await process2(item.event));
|
|
9360
|
+
} catch (error) {
|
|
9361
|
+
item.reject(error instanceof Error ? error : new Error(String(error)));
|
|
9362
|
+
}
|
|
9363
|
+
}
|
|
9364
|
+
} finally {
|
|
9365
|
+
gate.draining = false;
|
|
9366
|
+
if (gate.sends === 0 && gate.queue.length === 0)
|
|
9367
|
+
this.#gates.delete(accountId);
|
|
9368
|
+
}
|
|
9369
|
+
}
|
|
9370
|
+
async run(accountId, event, process2) {
|
|
9371
|
+
const gate = this.#gates.get(accountId);
|
|
9372
|
+
if (!gate || !gate.draining && gate.sends === 0)
|
|
9373
|
+
return process2(event);
|
|
9374
|
+
if (gate.overflow)
|
|
9375
|
+
throw gate.overflow;
|
|
9376
|
+
if (gate.queue.length >= MAX_BUFFERED_INGESTS) {
|
|
9377
|
+
const error = new Error(`ingest buffer overflow for account ${accountId}; limit ${MAX_BUFFERED_INGESTS}; event ${event.eventId} dropped`);
|
|
9378
|
+
error.code = "ingest_buffer_overflow";
|
|
9379
|
+
gate.overflow = error;
|
|
9380
|
+
try {
|
|
9381
|
+
log.error(error.message, { account: accountId, event: event.eventId });
|
|
9382
|
+
} catch {}
|
|
9383
|
+
try {
|
|
9384
|
+
this.#onOverflow(accountId, event, error);
|
|
9385
|
+
} catch (callbackError) {
|
|
9386
|
+
try {
|
|
9387
|
+
log.error(`overflow handler failed: ${callbackError instanceof Error ? callbackError.message : String(callbackError)}`, { account: accountId });
|
|
9388
|
+
} catch {}
|
|
9389
|
+
}
|
|
9390
|
+
throw error;
|
|
9391
|
+
}
|
|
9392
|
+
return new Promise((resolve, reject) => {
|
|
9393
|
+
gate.queue.push({ event, resolve, reject });
|
|
9394
|
+
});
|
|
9395
|
+
}
|
|
9396
|
+
#gate(accountId) {
|
|
9397
|
+
const existing = this.#gates.get(accountId);
|
|
9398
|
+
if (existing)
|
|
9399
|
+
return existing;
|
|
9400
|
+
const gate = { sends: 0, draining: false, queue: [] };
|
|
9401
|
+
this.#gates.set(accountId, gate);
|
|
9402
|
+
return gate;
|
|
9403
|
+
}
|
|
9404
|
+
}
|
|
9405
|
+
var MAX_BUFFERED_INGESTS = 100;
|
|
9406
|
+
var init_ingest_gate = __esm(() => {
|
|
9407
|
+
init_log();
|
|
9408
|
+
});
|
|
9409
|
+
|
|
9410
|
+
// packages/chat-room-channeld/src/host.ts
|
|
9411
|
+
function defaultSpawnAdapter(account, context) {
|
|
9412
|
+
return new AdapterProcess({ account, ...context });
|
|
9413
|
+
}
|
|
9414
|
+
|
|
9415
|
+
class ChannelHost {
|
|
9416
|
+
#config;
|
|
9417
|
+
#stateFactory;
|
|
9418
|
+
#spawnAdapter;
|
|
9419
|
+
#now;
|
|
9420
|
+
#deliveryIntervalMs;
|
|
9421
|
+
#onDeliveryResult;
|
|
9422
|
+
#adapters = new Map;
|
|
9423
|
+
#timers = new Map;
|
|
9424
|
+
#inFlight = new Map;
|
|
9425
|
+
#notified = new Set;
|
|
9426
|
+
#active = new Set;
|
|
9427
|
+
#disabled = new Set;
|
|
9428
|
+
#gate = new IngestGate((accountId, _event, _error) => {
|
|
9429
|
+
this.#disableAccount(accountId, "ingest barrier limit reached");
|
|
9430
|
+
});
|
|
9431
|
+
#state;
|
|
9432
|
+
#running = false;
|
|
9433
|
+
#starting = false;
|
|
9434
|
+
#idleTimer;
|
|
9435
|
+
#rejectionHandler;
|
|
9436
|
+
constructor(config, deps = {}) {
|
|
9437
|
+
this.#config = config;
|
|
9438
|
+
this.#stateFactory = deps.stateFactory ?? openState;
|
|
9439
|
+
this.#spawnAdapter = deps.spawnAdapter ?? defaultSpawnAdapter;
|
|
9440
|
+
this.#now = deps.now ?? Date.now;
|
|
9441
|
+
this.#deliveryIntervalMs = deps.deliveryIntervalMs ?? 200;
|
|
9442
|
+
this.#onDeliveryResult = deps.onDeliveryResult;
|
|
9443
|
+
}
|
|
9444
|
+
get disabledAccounts() {
|
|
9445
|
+
return [...this.#disabled];
|
|
9446
|
+
}
|
|
9447
|
+
targetStatus(platform, accountId) {
|
|
9448
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
9449
|
+
if (!account || account.platform !== platform)
|
|
9450
|
+
return "missing";
|
|
9451
|
+
return this.#disabled.has(accountId) ? "disabled" : "ready";
|
|
9452
|
+
}
|
|
9453
|
+
async start() {
|
|
9454
|
+
if (this.#running)
|
|
9455
|
+
throw new Error("host is already running");
|
|
9456
|
+
validateTargets(this.#config);
|
|
9457
|
+
const state = this.#stateFactory(this.#config.stateFile);
|
|
9458
|
+
this.#state = state;
|
|
9459
|
+
this.#installRejectionGuard();
|
|
9460
|
+
const configuredKeys = this.#config.accounts.map((account) => `${account.platform}/${account.id}`);
|
|
9461
|
+
const abandoned = state.abandonUnconfiguredDeliveries(configuredKeys);
|
|
9462
|
+
if (abandoned.length > 0) {
|
|
9463
|
+
log.warn(`abandoned ${abandoned.length} deliveries for unconfigured accounts`);
|
|
9464
|
+
for (const row of abandoned) {
|
|
9465
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { notified: this.#notified });
|
|
9466
|
+
}
|
|
9467
|
+
}
|
|
9468
|
+
const resumed = state.resumePausedDeliveries();
|
|
9469
|
+
if (resumed > 0)
|
|
9470
|
+
log.info(`resumed ${resumed} paused deliveries`);
|
|
9471
|
+
const recovered = state.recoverInFlightDeliveries();
|
|
9472
|
+
if (recovered > 0)
|
|
9473
|
+
log.warn(`recovered ${recovered} stale in-flight deliveries`);
|
|
9474
|
+
this.#running = true;
|
|
9475
|
+
this.#starting = true;
|
|
9476
|
+
const started = [];
|
|
9477
|
+
const failures = [];
|
|
9478
|
+
const tasks = this.#config.accounts.map(async (account) => {
|
|
9479
|
+
let adapter;
|
|
9480
|
+
try {
|
|
9481
|
+
adapter = this.#spawnAdapter(account, {
|
|
9482
|
+
onIngest: (event) => this.ingest(event),
|
|
9483
|
+
onExit: (code, signal) => this.#handleExit(account.id, code, signal),
|
|
9484
|
+
onUnavailable: (reason) => this.#disableAccount(account.id, reason)
|
|
9485
|
+
});
|
|
9486
|
+
this.#adapters.set(account.id, adapter);
|
|
9487
|
+
await adapter.start();
|
|
9488
|
+
this.#schedule(account.id);
|
|
9489
|
+
return { id: account.id };
|
|
9490
|
+
} catch (error) {
|
|
9491
|
+
const reason = startFailureReason(account.id, error);
|
|
9492
|
+
this.#disabled.add(account.id);
|
|
9493
|
+
log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
|
|
9494
|
+
if (adapter) {
|
|
9495
|
+
try {
|
|
9496
|
+
await adapter.stop();
|
|
9497
|
+
} catch {}
|
|
9498
|
+
}
|
|
9499
|
+
return { id: account.id, reason };
|
|
9500
|
+
}
|
|
9501
|
+
});
|
|
9502
|
+
const settled = await Promise.allSettled(tasks);
|
|
9503
|
+
this.#starting = false;
|
|
9504
|
+
settled.forEach((result, index) => {
|
|
9505
|
+
const account = this.#config.accounts[index];
|
|
9506
|
+
if (result.status === "fulfilled") {
|
|
9507
|
+
const { id, reason } = result.value;
|
|
9508
|
+
if (reason)
|
|
9509
|
+
failures.push({ id, reason });
|
|
9510
|
+
else
|
|
9511
|
+
started.push(id);
|
|
9512
|
+
} else {
|
|
9513
|
+
const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
|
|
9514
|
+
failures.push({ id: account.id, reason });
|
|
9515
|
+
this.#disabled.add(account.id);
|
|
9516
|
+
log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
|
|
9517
|
+
}
|
|
9518
|
+
});
|
|
9519
|
+
for (const account of this.#config.accounts) {
|
|
9520
|
+
if (this.#disabled.has(account.id)) {
|
|
9521
|
+
state.pauseAccountDeliveries(`${account.platform}/${account.id}`, "account disabled until restart");
|
|
9522
|
+
}
|
|
9523
|
+
}
|
|
9524
|
+
const usable = started.filter((accountId) => !this.#disabled.has(accountId));
|
|
9525
|
+
if (usable.length === 0) {
|
|
9526
|
+
this.#running = false;
|
|
9527
|
+
this.#starting = false;
|
|
9528
|
+
this.#clearIdle();
|
|
9529
|
+
this.#removeRejectionGuard();
|
|
9530
|
+
for (const timer of this.#timers.values())
|
|
9531
|
+
clearTimeout(timer);
|
|
9532
|
+
this.#timers.clear();
|
|
9533
|
+
await this.#stopAdapters();
|
|
9534
|
+
state.close();
|
|
9535
|
+
this.#state = undefined;
|
|
9536
|
+
this.#disabled.clear();
|
|
9537
|
+
const detail = failures.map((failure) => `${failure.id}: ${failure.reason}`).join("; ");
|
|
9538
|
+
throw new Error(`no adapters started${detail ? `: ${detail}` : ""}`);
|
|
9539
|
+
}
|
|
9540
|
+
for (const failure of failures) {
|
|
9541
|
+
log.warn(`account ${failure.id} disabled until restart; queued deliveries paused`, {
|
|
9542
|
+
account: failure.id
|
|
9543
|
+
});
|
|
9544
|
+
}
|
|
9545
|
+
log.info(`host started: ${usable.length} accounts, ${failures.length} disabled, ${this.#config.rules.length} rules`);
|
|
9546
|
+
}
|
|
9547
|
+
async ingest(event) {
|
|
9548
|
+
return this.#gate.run(event.source.accountId, event, (item) => this.#processIngest(item));
|
|
9549
|
+
}
|
|
9550
|
+
async#processIngest(event) {
|
|
9551
|
+
const state = this.#state;
|
|
9552
|
+
if (!state)
|
|
9553
|
+
throw new Error("host is not running");
|
|
9554
|
+
if (event.message) {
|
|
9555
|
+
const endpoint = targetKey(event.message.endpoint);
|
|
9556
|
+
if (state.findEcho(endpoint, event.message.nativeMessageId)) {
|
|
9557
|
+
log.info("echo ingest skipped", { event: event.eventId });
|
|
9558
|
+
return { duplicate: false, eventId: event.eventId };
|
|
9559
|
+
}
|
|
9560
|
+
}
|
|
9561
|
+
const result = state.commitIngest(event);
|
|
9562
|
+
if (result.duplicate) {
|
|
9563
|
+
log.info("duplicate ingest skipped", { event: result.existingEventId });
|
|
9564
|
+
return { duplicate: true, eventId: result.existingEventId };
|
|
9565
|
+
}
|
|
9566
|
+
const stored = { ...event, ingressSeq: result.ingressSeq };
|
|
9567
|
+
log.info(`ingested ${stored.kind}`, { event: stored.eventId });
|
|
9568
|
+
if (stored.kind === "message.forward_requested") {
|
|
9569
|
+
const selected = stored.selectedMessage;
|
|
9570
|
+
const reason = !selected ? "selectedMessage is required" : !sameEndpoint(selected.endpoint, stored.source) ? "selectedMessage is outside the source room" : undefined;
|
|
9571
|
+
if (reason) {
|
|
9572
|
+
log.warn(`forward rejected: ${reason}`, { event: stored.eventId });
|
|
9573
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
9574
|
+
}
|
|
9575
|
+
}
|
|
9576
|
+
const requestedTarget = stored.kind === "message.forward_requested" ? stored.requestedTarget : undefined;
|
|
9577
|
+
for (const rule of matchRules(this.#config, stored)) {
|
|
9578
|
+
const targets = [];
|
|
9579
|
+
const payloads = [];
|
|
9580
|
+
for (const target of rule.to) {
|
|
9581
|
+
const endpoint = toEndpoint(this.#config, rule.id, target);
|
|
9582
|
+
if (requestedTarget && !sameEndpoint(endpoint, requestedTarget))
|
|
9583
|
+
continue;
|
|
9584
|
+
const plan = planPayload(rule, stored, endpoint);
|
|
9585
|
+
if ("dropped" in plan) {
|
|
9586
|
+
log.warn(`rule ${rule.id}@${rule.version} dropped delivery to ${targetKey(endpoint)}: ${plan.dropped}`, { event: stored.eventId });
|
|
9587
|
+
continue;
|
|
9588
|
+
}
|
|
9589
|
+
targets.push(target);
|
|
9590
|
+
payloads.push(JSON.stringify(plan.payload));
|
|
9591
|
+
}
|
|
9592
|
+
if (targets.length === 0)
|
|
9593
|
+
continue;
|
|
9594
|
+
const created = state.enqueueDeliveries(stored.eventId, rule, targets, payloads);
|
|
9595
|
+
for (const delivery of created) {
|
|
9596
|
+
const endpoint = parseTarget2(delivery.target);
|
|
9597
|
+
if (endpoint && this.#disabled.has(endpoint.accountId)) {
|
|
9598
|
+
state.markDelivery(delivery.deliveryId, "paused", {
|
|
9599
|
+
lastError: "account disabled until restart"
|
|
9600
|
+
});
|
|
9601
|
+
}
|
|
9602
|
+
log.info(`delivery enqueued rule=${rule.id}@${rule.version}`, {
|
|
9603
|
+
delivery: delivery.deliveryId,
|
|
9604
|
+
event: stored.eventId
|
|
9605
|
+
});
|
|
9606
|
+
}
|
|
9607
|
+
}
|
|
9608
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
9609
|
+
}
|
|
9610
|
+
async stop() {
|
|
9611
|
+
if (!this.#running && !this.#state) {
|
|
9612
|
+
this.#clearIdle();
|
|
9613
|
+
this.#removeRejectionGuard();
|
|
9614
|
+
return;
|
|
9615
|
+
}
|
|
9616
|
+
this.#running = false;
|
|
9617
|
+
this.#starting = false;
|
|
9618
|
+
this.#clearIdle();
|
|
9619
|
+
for (const timer of this.#timers.values())
|
|
9620
|
+
clearTimeout(timer);
|
|
9621
|
+
this.#timers.clear();
|
|
9622
|
+
await Promise.allSettled([...this.#active]);
|
|
9623
|
+
await this.#stopAdapters();
|
|
9624
|
+
this.#state?.close();
|
|
9625
|
+
this.#state = undefined;
|
|
9626
|
+
this.#adapters.clear();
|
|
9627
|
+
this.#inFlight.clear();
|
|
9628
|
+
this.#notified.clear();
|
|
9629
|
+
this.#disabled.clear();
|
|
9630
|
+
this.#removeRejectionGuard();
|
|
9631
|
+
log.info("host stopped");
|
|
9632
|
+
}
|
|
9633
|
+
#schedule(accountId) {
|
|
9634
|
+
if (!this.#running || this.#disabled.has(accountId))
|
|
9635
|
+
return;
|
|
9636
|
+
const timer = setTimeout(() => {
|
|
9637
|
+
this.#timers.delete(accountId);
|
|
9638
|
+
if (!this.#running)
|
|
9639
|
+
return;
|
|
9640
|
+
const task = this.#drainOnce(accountId).catch((error) => {
|
|
9641
|
+
log.error(`delivery loop failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
9642
|
+
account: accountId
|
|
9643
|
+
});
|
|
9644
|
+
}).finally(() => {
|
|
9645
|
+
this.#active.delete(task);
|
|
9646
|
+
this.#schedule(accountId);
|
|
9647
|
+
});
|
|
9648
|
+
this.#active.add(task);
|
|
9649
|
+
}, this.#deliveryIntervalMs);
|
|
9650
|
+
this.#timers.set(accountId, timer);
|
|
9651
|
+
}
|
|
9652
|
+
async#drainOnce(accountId) {
|
|
9653
|
+
if (!this.#running || this.#disabled.has(accountId))
|
|
9654
|
+
return;
|
|
9655
|
+
const state = this.#state;
|
|
9656
|
+
const adapter = this.#adapters.get(accountId);
|
|
9657
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
9658
|
+
if (!state || !adapter || !account)
|
|
9659
|
+
return;
|
|
9660
|
+
const accountKey = `${account.platform}/${account.id}`;
|
|
9661
|
+
const row = state.nextPendingDelivery(accountKey, this.#now());
|
|
9662
|
+
if (!row)
|
|
9663
|
+
return;
|
|
9664
|
+
await this.#deliver(state, adapter, accountId, row);
|
|
9665
|
+
}
|
|
9666
|
+
async#deliver(state, adapter, accountId, row) {
|
|
9667
|
+
const target = parseTarget2(row.target);
|
|
9668
|
+
if (!target) {
|
|
9669
|
+
state.markDelivery(row.deliveryId, "permanent", { lastError: `invalid target: ${row.target}` });
|
|
9670
|
+
state.recordReceipt({
|
|
9671
|
+
deliveryId: row.deliveryId,
|
|
9672
|
+
attemptId: "invalid-target",
|
|
9673
|
+
state: "permanent",
|
|
9674
|
+
detail: `invalid target: ${row.target}`
|
|
9675
|
+
});
|
|
9676
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId: "invalid-target", notified: this.#notified });
|
|
9677
|
+
log.error(`invalid target ${row.target}`, { account: accountId, delivery: row.deliveryId });
|
|
9678
|
+
return;
|
|
9679
|
+
}
|
|
9680
|
+
const attempt = row.attemptCount + 1;
|
|
9681
|
+
const attemptId = `att-${row.deliveryId}-${attempt}`;
|
|
9682
|
+
state.markDelivery(row.deliveryId, "in_flight", { attemptCount: attempt });
|
|
9683
|
+
const inFlight = this.#inFlight.get(accountId) ?? new Set;
|
|
9684
|
+
this.#inFlight.set(accountId, inFlight);
|
|
9685
|
+
inFlight.add(row.deliveryId);
|
|
9686
|
+
this.#gate.begin(accountId);
|
|
9687
|
+
try {
|
|
9688
|
+
let receipt;
|
|
9689
|
+
try {
|
|
9690
|
+
receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, JSON.parse(row.payload));
|
|
9691
|
+
} catch (error) {
|
|
9692
|
+
receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
|
|
9693
|
+
} finally {
|
|
9694
|
+
inFlight.delete(row.deliveryId);
|
|
9695
|
+
}
|
|
9696
|
+
applyReceipt(state, row, attemptId, accountId, receipt, this.#now());
|
|
9697
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId, notified: this.#notified });
|
|
9698
|
+
} finally {
|
|
9699
|
+
await this.#gate.finish(accountId, (event) => this.#processIngest(event));
|
|
9700
|
+
if (this.#disabled.has(accountId)) {
|
|
9701
|
+
this.#pauseAccountDeliveries(accountId, "account disabled until restart");
|
|
9702
|
+
}
|
|
9703
|
+
}
|
|
9704
|
+
}
|
|
9705
|
+
#pauseAccountDeliveries(accountId, reason) {
|
|
9706
|
+
const state = this.#state;
|
|
9707
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
9708
|
+
if (!state || !account)
|
|
9709
|
+
return;
|
|
9710
|
+
try {
|
|
9711
|
+
const paused = state.pauseAccountDeliveries(`${account.platform}/${account.id}`, reason);
|
|
9712
|
+
if (paused > 0) {
|
|
9713
|
+
log.info(`paused ${paused} deliveries for disabled account`, { account: accountId });
|
|
9714
|
+
}
|
|
9715
|
+
} catch (error) {
|
|
9716
|
+
this.#safeWarn(`could not pause deliveries: ${error instanceof Error ? error.message : String(error)}`, accountId);
|
|
9717
|
+
}
|
|
9718
|
+
}
|
|
9719
|
+
#disableAccount(accountId, reason) {
|
|
9720
|
+
if (this.#disabled.has(accountId))
|
|
9721
|
+
return;
|
|
9722
|
+
this.#disabled.add(accountId);
|
|
9723
|
+
const timer = this.#timers.get(accountId);
|
|
9724
|
+
if (timer) {
|
|
9725
|
+
clearTimeout(timer);
|
|
9726
|
+
this.#timers.delete(accountId);
|
|
9727
|
+
}
|
|
9728
|
+
const state = this.#state;
|
|
9729
|
+
const inFlight = this.#inFlight.get(accountId);
|
|
9730
|
+
if (state && inFlight && inFlight.size > 0) {
|
|
9731
|
+
for (const deliveryId of inFlight) {
|
|
9732
|
+
try {
|
|
9733
|
+
state.markDelivery(deliveryId, "unknown", { lastError: reason });
|
|
9734
|
+
notifyDeliveryResult(state, deliveryId, this.#onDeliveryResult, { notified: this.#notified });
|
|
9735
|
+
} catch (error) {
|
|
9736
|
+
this.#safeWarn(`could not mark delivery unknown: ${error instanceof Error ? error.message : String(error)}`, accountId, deliveryId);
|
|
9737
|
+
}
|
|
9738
|
+
}
|
|
9739
|
+
this.#inFlight.delete(accountId);
|
|
9740
|
+
this.#safeWarn(`marked ${inFlight.size} in-flight deliveries unknown`, accountId);
|
|
9741
|
+
}
|
|
9742
|
+
this.#pauseAccountDeliveries(accountId, reason);
|
|
9743
|
+
try {
|
|
9744
|
+
log.error(`account ${accountId} disabled: ${reason}`, { account: accountId });
|
|
9745
|
+
} catch {}
|
|
9746
|
+
try {
|
|
9747
|
+
const adapter = this.#adapters.get(accountId);
|
|
9748
|
+
if (adapter) {
|
|
9749
|
+
adapter.stop().catch((error) => {
|
|
9750
|
+
this.#safeWarn(`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`, accountId);
|
|
9751
|
+
});
|
|
9752
|
+
}
|
|
9753
|
+
} catch (error) {
|
|
9754
|
+
this.#safeWarn(`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`, accountId);
|
|
9755
|
+
}
|
|
9756
|
+
this.#maybeIdle();
|
|
9757
|
+
}
|
|
9758
|
+
#handleExit(accountId, code, signal) {
|
|
9759
|
+
try {
|
|
9760
|
+
this.#disableAccount(accountId, `adapter exited (code=${code} signal=${signal})`);
|
|
9761
|
+
} catch (error) {
|
|
9762
|
+
this.#safeWarn(`disable after adapter exit failed: ${error instanceof Error ? error.message : String(error)}`, accountId);
|
|
9763
|
+
}
|
|
9764
|
+
}
|
|
9765
|
+
#safeWarn(message, accountId, deliveryId) {
|
|
9766
|
+
try {
|
|
9767
|
+
log.warn(message, { account: accountId, delivery: deliveryId });
|
|
9768
|
+
} catch {}
|
|
9769
|
+
}
|
|
9770
|
+
#maybeIdle() {
|
|
9771
|
+
try {
|
|
9772
|
+
if (!this.#running || this.#starting || this.#idleTimer)
|
|
9773
|
+
return;
|
|
9774
|
+
if (!this.#config.accounts.every((account) => this.#disabled.has(account.id)))
|
|
9775
|
+
return;
|
|
9776
|
+
log.warn("all accounts disabled; host idle until restart");
|
|
9777
|
+
this.#idleTimer = setInterval(() => {}, 60000);
|
|
9778
|
+
} catch {}
|
|
9779
|
+
}
|
|
9780
|
+
#clearIdle() {
|
|
9781
|
+
if (!this.#idleTimer)
|
|
9782
|
+
return;
|
|
9783
|
+
clearInterval(this.#idleTimer);
|
|
9784
|
+
this.#idleTimer = undefined;
|
|
9785
|
+
}
|
|
9786
|
+
#installRejectionGuard() {
|
|
9787
|
+
if (this.#rejectionHandler)
|
|
9788
|
+
return;
|
|
9789
|
+
this.#rejectionHandler = (reason) => {
|
|
9790
|
+
try {
|
|
9791
|
+
log.error(`unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
9792
|
+
} catch {}
|
|
9793
|
+
};
|
|
9794
|
+
process.on("unhandledRejection", this.#rejectionHandler);
|
|
9795
|
+
}
|
|
9796
|
+
#removeRejectionGuard() {
|
|
9797
|
+
const handler = this.#rejectionHandler;
|
|
9798
|
+
if (!handler)
|
|
9799
|
+
return;
|
|
9800
|
+
this.#rejectionHandler = undefined;
|
|
9801
|
+
try {
|
|
9802
|
+
process.off("unhandledRejection", handler);
|
|
9803
|
+
} catch {}
|
|
9804
|
+
}
|
|
9805
|
+
async#stopAdapters() {
|
|
9806
|
+
await Promise.allSettled([...this.#adapters.values()].map((adapter) => adapter.stop()));
|
|
9807
|
+
this.#adapters.clear();
|
|
9808
|
+
}
|
|
9809
|
+
}
|
|
9810
|
+
function createHost(config, deps = {}) {
|
|
9811
|
+
return new ChannelHost(config, deps);
|
|
9812
|
+
}
|
|
9813
|
+
var init_host = __esm(() => {
|
|
9814
|
+
init_adapter();
|
|
9815
|
+
init_delivery();
|
|
9816
|
+
init_ingest_gate();
|
|
9817
|
+
init_log();
|
|
9818
|
+
init_rules();
|
|
9819
|
+
init_state();
|
|
9820
|
+
});
|
|
9821
|
+
|
|
9822
|
+
// server/channels.ts
|
|
9823
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "node:fs";
|
|
9824
|
+
import { randomUUID as randomUUID15 } from "node:crypto";
|
|
9825
|
+
import path14 from "node:path";
|
|
9826
|
+
import { parse as parseYaml3 } from "yaml";
|
|
9827
|
+
function loadChannelConfig(file, stateFile) {
|
|
9828
|
+
let text;
|
|
9829
|
+
try {
|
|
9830
|
+
text = readFileSync4(file, "utf8");
|
|
9831
|
+
} catch {
|
|
9832
|
+
throw new Error(`channeld config: cannot read ${file}`);
|
|
9833
|
+
}
|
|
9834
|
+
let raw;
|
|
9835
|
+
try {
|
|
9836
|
+
raw = parseYaml3(text);
|
|
9837
|
+
} catch {
|
|
9838
|
+
throw new Error(`channeld config: ${file} is not valid YAML/JSON`);
|
|
9839
|
+
}
|
|
9840
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
9841
|
+
throw new Error(`channeld config: ${file} must contain a mapping`);
|
|
9842
|
+
}
|
|
9843
|
+
return parseConfig({ ...raw, stateFile });
|
|
9844
|
+
}
|
|
9845
|
+
function resolveChannelStateFile(stateDir, configured) {
|
|
9846
|
+
const file = configured ? path14.isAbsolute(configured) ? configured : path14.resolve(stateDir, configured) : path14.join(stateDir, "channeld.sqlite");
|
|
9847
|
+
if (path14.resolve(file) === path14.join(stateDir, "chat-room.sqlite")) {
|
|
9848
|
+
throw new Error("chatroom config: server.channeld.stateFile must not be the room database");
|
|
9849
|
+
}
|
|
9850
|
+
return file;
|
|
9851
|
+
}
|
|
9852
|
+
function deliverySystemMessage(delivery, receipt) {
|
|
9853
|
+
if (delivery.state === "sent")
|
|
9854
|
+
return `Forwarded to ${delivery.target}`;
|
|
9855
|
+
const raw = receipt?.detail || delivery.lastError || receipt?.state || delivery.state;
|
|
9856
|
+
const reason = String(raw).replace(/[\r\n;]+/g, " ").trim().slice(0, 500) || delivery.state;
|
|
9857
|
+
return `Forward to ${delivery.target} failed: ${reason}`;
|
|
9858
|
+
}
|
|
9859
|
+
function createDeliveryResultHandler() {
|
|
9860
|
+
const notified = new Set;
|
|
9861
|
+
return (event, delivery, receipt) => {
|
|
9862
|
+
if (!isTerminalDeliveryState(delivery.state))
|
|
9863
|
+
return;
|
|
9864
|
+
if (notified.has(delivery.deliveryId))
|
|
9865
|
+
return;
|
|
9866
|
+
const source = event?.source;
|
|
9867
|
+
if (event?.kind !== "message.forward_requested" || source?.platform !== "chatroom" || source.accountId !== "center")
|
|
9868
|
+
return;
|
|
9869
|
+
notified.add(delivery.deliveryId);
|
|
9870
|
+
const text = deliverySystemMessage(delivery, receipt);
|
|
9871
|
+
writeState((svc) => {
|
|
9872
|
+
svc.addEvent(source.roomId, text);
|
|
9873
|
+
}).catch((error) => {
|
|
9874
|
+
console.warn(`[chat-room] could not write the channeld result message: ${error instanceof Error ? error.message : String(error)}`);
|
|
9875
|
+
});
|
|
9876
|
+
};
|
|
9877
|
+
}
|
|
9878
|
+
async function startChannels(settings, deps = {}) {
|
|
9879
|
+
if (!settings.channeld?.enabled)
|
|
9880
|
+
return;
|
|
9881
|
+
const configPath = settings.channeld.config;
|
|
9882
|
+
if (!configPath) {
|
|
9883
|
+
throw new Error("chatroom config: server.channeld is enabled but no config file is set (server.channeld.config or CHAT_ROOM_CHANNELD_CONFIG)");
|
|
9884
|
+
}
|
|
9885
|
+
const stateDir = path14.dirname(databasePath());
|
|
9886
|
+
const stateFile = resolveChannelStateFile(stateDir, settings.channeld.stateFile);
|
|
9887
|
+
const config = loadChannelConfig(configPath, stateFile);
|
|
9888
|
+
mkdirSync3(stateDir, { recursive: true, mode: 448 });
|
|
9889
|
+
const host = createHost(config, {
|
|
9890
|
+
spawnAdapter: deps.spawnAdapter,
|
|
9891
|
+
deliveryIntervalMs: deps.deliveryIntervalMs,
|
|
9892
|
+
onDeliveryResult: createDeliveryResultHandler()
|
|
9893
|
+
});
|
|
9894
|
+
try {
|
|
9895
|
+
await host.start();
|
|
9896
|
+
} catch (error) {
|
|
9897
|
+
console.warn(`[chat-room] channeld disabled: ${error instanceof Error ? error.message : String(error)}`);
|
|
9898
|
+
await stopChannels({ host, config });
|
|
9899
|
+
return;
|
|
9900
|
+
}
|
|
9901
|
+
return { host, config };
|
|
9902
|
+
}
|
|
9903
|
+
async function stopChannels(runtime) {
|
|
9904
|
+
if (!runtime)
|
|
9905
|
+
return;
|
|
9906
|
+
try {
|
|
9907
|
+
await runtime.host.stop();
|
|
9908
|
+
} catch (error) {
|
|
9909
|
+
console.warn(`[chat-room] channeld stop failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
9910
|
+
}
|
|
9911
|
+
}
|
|
9912
|
+
function parseTarget3(value) {
|
|
9913
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
9914
|
+
return;
|
|
9915
|
+
const raw = value;
|
|
9916
|
+
if (typeof raw.platform !== "string" || !IDENTIFIER2.test(raw.platform) || typeof raw.account !== "string" || !IDENTIFIER2.test(raw.account) || typeof raw.room !== "string" || !IDENTIFIER2.test(raw.room))
|
|
9917
|
+
return;
|
|
9918
|
+
return { platform: raw.platform, account: raw.account, room: raw.room };
|
|
9919
|
+
}
|
|
9920
|
+
function decodeSegment(segment) {
|
|
9921
|
+
try {
|
|
9922
|
+
return decodeURIComponent(segment);
|
|
9923
|
+
} catch {
|
|
9924
|
+
return;
|
|
9925
|
+
}
|
|
9926
|
+
}
|
|
9927
|
+
async function memberName(roomId, sessionID) {
|
|
9928
|
+
const db = await openStateDatabase(databasePath());
|
|
9929
|
+
const row = db.query(`SELECT g.name FROM registry g
|
|
9930
|
+
JOIN rooms r ON r.id = g.room_id
|
|
9931
|
+
JOIN participants p ON p.room_id = g.room_id
|
|
9932
|
+
AND p.id = CASE WHEN r.kind = 'direct' THEN g.session_id ELSE g.name END
|
|
9933
|
+
WHERE g.room_id = ? AND g.session_id = ?`).get(roomId, sessionID);
|
|
9934
|
+
return row?.name;
|
|
9935
|
+
}
|
|
9936
|
+
async function readForwardableMessage(roomId, messageId, sessionID) {
|
|
9937
|
+
if (!await memberName(roomId, sessionID))
|
|
9938
|
+
return;
|
|
9939
|
+
const db = await openStateDatabase(databasePath());
|
|
9940
|
+
const row = db.query("SELECT text, created_at, recalled_at FROM messages WHERE room_id = ? AND id = ?").get(roomId, messageId);
|
|
9941
|
+
if (!row || row.recalled_at !== null)
|
|
9942
|
+
return;
|
|
9943
|
+
return { text: row.text, createdAt: Number(row.created_at) };
|
|
9944
|
+
}
|
|
9945
|
+
async function isRoomMember(roomId, sessionID) {
|
|
9946
|
+
return Boolean(await memberName(roomId, sessionID));
|
|
9947
|
+
}
|
|
9948
|
+
function forwardTargets(runtime, roomId) {
|
|
9949
|
+
const probe = {
|
|
9950
|
+
schemaVersion: EVENT_SCHEMA_VERSION,
|
|
9951
|
+
eventId: "forward-targets",
|
|
9952
|
+
kind: "message.forward_requested",
|
|
9953
|
+
source: { platform: "chatroom", accountId: "center", roomId },
|
|
9954
|
+
actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: "" },
|
|
9955
|
+
sourceDedupKey: "forward-targets",
|
|
9956
|
+
receivedAt: new Date(0).toISOString()
|
|
9957
|
+
};
|
|
9958
|
+
const config = runtime.config;
|
|
9959
|
+
const seen = new Set;
|
|
9960
|
+
const targets = [];
|
|
9961
|
+
for (const rule of matchRules(config, probe)) {
|
|
9962
|
+
for (const target of rule.to) {
|
|
9963
|
+
if (runtime.host.targetStatus(target.platform, target.account) !== "ready")
|
|
9964
|
+
continue;
|
|
9965
|
+
const key = `${target.platform}/${target.account}/${target.room}`;
|
|
9966
|
+
if (seen.has(key))
|
|
9967
|
+
continue;
|
|
9968
|
+
seen.add(key);
|
|
9969
|
+
targets.push(target);
|
|
9970
|
+
}
|
|
9971
|
+
}
|
|
9972
|
+
return targets;
|
|
9973
|
+
}
|
|
9974
|
+
async function channelRoutes(req, url, runtime) {
|
|
9975
|
+
if (!runtime)
|
|
9976
|
+
return;
|
|
9977
|
+
if (url.pathname === "/channeld/status") {
|
|
9978
|
+
if (req.method !== "GET")
|
|
9979
|
+
return json11({ error: "method not allowed" }, 405);
|
|
9980
|
+
try {
|
|
9981
|
+
return json11(readChannelStats(runtime.config.stateFile));
|
|
9982
|
+
} catch {
|
|
9983
|
+
return json11({ error: "channel state unavailable" }, 503);
|
|
9984
|
+
}
|
|
9985
|
+
}
|
|
9986
|
+
const forward = url.pathname.match(/^\/rooms\/([^/]+)\/forward$/);
|
|
9987
|
+
if (forward) {
|
|
9988
|
+
if (req.method !== "POST")
|
|
9989
|
+
return json11({ error: "method not allowed" }, 405);
|
|
9990
|
+
const roomId = decodeSegment(forward[1]);
|
|
9991
|
+
if (!roomId)
|
|
9992
|
+
return json11({ error: "message not found" }, 404);
|
|
9993
|
+
const body = await jsonObject(req);
|
|
9994
|
+
if (!body)
|
|
9995
|
+
return json11({ error: "JSON object body is required" }, 400);
|
|
9996
|
+
const sessionID = typeof body.sessionID === "string" ? body.sessionID.trim() : "";
|
|
9997
|
+
const messageId = typeof body.messageId === "string" ? body.messageId.trim() : "";
|
|
9998
|
+
if (!sessionID || sessionID.length > MAX_SESSION4 || !messageId || messageId.length > MAX_SESSION4) {
|
|
9999
|
+
return json11({ error: "sessionID and messageId are required" }, 400);
|
|
10000
|
+
}
|
|
10001
|
+
const target = parseTarget3(body.target);
|
|
10002
|
+
if (!target)
|
|
10003
|
+
return json11({ error: "target must contain platform, account, and room identifiers" }, 400);
|
|
10004
|
+
const requestId = body.requestId === undefined ? undefined : typeof body.requestId === "string" && body.requestId.trim() && body.requestId.trim().length <= MAX_REQUEST_ID ? body.requestId.trim() : null;
|
|
10005
|
+
if (requestId === null)
|
|
10006
|
+
return json11({ error: `requestId must be a non-empty string (max ${MAX_REQUEST_ID})` }, 400);
|
|
10007
|
+
const message = await readForwardableMessage(roomId, messageId, sessionID);
|
|
10008
|
+
if (!message)
|
|
10009
|
+
return json11({ error: "message not found" }, 404);
|
|
10010
|
+
if (runtime.host.targetStatus(target.platform, target.account) !== "ready") {
|
|
10011
|
+
return json11({ error: "forward target is unavailable" }, 409);
|
|
10012
|
+
}
|
|
10013
|
+
const source = { platform: "chatroom", accountId: "center", roomId };
|
|
10014
|
+
const requestedTarget = { platform: target.platform, accountId: target.account, roomId: target.room };
|
|
10015
|
+
const event = {
|
|
10016
|
+
schemaVersion: EVENT_SCHEMA_VERSION,
|
|
10017
|
+
eventId: `fwd-${randomUUID15()}`,
|
|
10018
|
+
kind: "message.forward_requested",
|
|
10019
|
+
source,
|
|
10020
|
+
actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: sessionID },
|
|
10021
|
+
...requestId ? { providerEventId: requestId } : {},
|
|
10022
|
+
sourceDedupKey: `forward:${messageId}:${targetKey(requestedTarget)}`,
|
|
10023
|
+
selectedMessage: { endpoint: source, nativeMessageId: messageId, text: message.text },
|
|
10024
|
+
requestedTarget,
|
|
10025
|
+
occurredAt: new Date(message.createdAt).toISOString(),
|
|
10026
|
+
receivedAt: new Date().toISOString(),
|
|
10027
|
+
content: { text: message.text }
|
|
10028
|
+
};
|
|
10029
|
+
const result = await runtime.host.ingest(event);
|
|
10030
|
+
return json11({ eventId: result.eventId ?? event.eventId }, 202);
|
|
10031
|
+
}
|
|
10032
|
+
const targets = url.pathname.match(/^\/rooms\/([^/]+)\/forward-targets$/);
|
|
10033
|
+
if (!targets)
|
|
10034
|
+
return;
|
|
10035
|
+
if (req.method !== "GET")
|
|
10036
|
+
return json11({ error: "method not allowed" }, 405);
|
|
10037
|
+
const roomId = decodeSegment(targets[1]);
|
|
10038
|
+
if (!roomId)
|
|
10039
|
+
return json11({ error: "room not found" }, 404);
|
|
10040
|
+
const sessionID = (url.searchParams.get("sessionID") ?? "").trim();
|
|
10041
|
+
if (!sessionID || sessionID.length > MAX_SESSION4)
|
|
10042
|
+
return json11({ error: "sessionID is required" }, 400);
|
|
10043
|
+
if (!await isRoomMember(roomId, sessionID))
|
|
10044
|
+
return json11({ error: "room not found" }, 404);
|
|
10045
|
+
return json11({ targets: forwardTargets(runtime, roomId) });
|
|
10046
|
+
}
|
|
10047
|
+
var json11 = (body, status = 200) => Response.json(body, { status }), IDENTIFIER2, MAX_SESSION4 = 128, MAX_REQUEST_ID = 200;
|
|
10048
|
+
var init_channels = __esm(() => {
|
|
10049
|
+
init_store();
|
|
10050
|
+
init_sqlite_state();
|
|
10051
|
+
init_config();
|
|
10052
|
+
init_host();
|
|
10053
|
+
init_rules();
|
|
10054
|
+
init_state();
|
|
10055
|
+
IDENTIFIER2 = /^[A-Za-z0-9._-]{1,128}$/;
|
|
10056
|
+
});
|
|
10057
|
+
|
|
10058
|
+
// server/chat-server.ts
|
|
10059
|
+
import { existsSync as existsSync4, promises as fs5 } from "node:fs";
|
|
10060
|
+
import path15 from "node:path";
|
|
10061
|
+
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
10062
|
+
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
10063
|
+
function parsePort(value) {
|
|
10064
|
+
const port = Number(value);
|
|
10065
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
10066
|
+
throw new Error(`Invalid server port "${value}": expected an integer from 1 to 65535`);
|
|
10067
|
+
}
|
|
10068
|
+
return port;
|
|
10069
|
+
}
|
|
10070
|
+
function mutate2(fn) {
|
|
10071
|
+
return writeState(fn);
|
|
10072
|
+
}
|
|
10073
|
+
function read(fn) {
|
|
10074
|
+
return readState2(fn);
|
|
10075
|
+
}
|
|
10076
|
+
async function handle(req) {
|
|
10077
|
+
const url = new URL(req.url);
|
|
10078
|
+
const p = url.pathname;
|
|
10079
|
+
if (req.method === "GET" && p === "/") {
|
|
10080
|
+
return Response.redirect(new URL("/chat", url).toString(), 302);
|
|
10081
|
+
}
|
|
10082
|
+
if (req.method === "GET" && p === "/chat") {
|
|
10083
|
+
const html = await fs5.readFile(path15.join(here, "chat.html"), "utf8").catch(() => null);
|
|
10084
|
+
if (html === null) {
|
|
10085
|
+
return json12({ error: "chat page not found" }, 404);
|
|
10086
|
+
}
|
|
10087
|
+
const version = await chatVersionTag();
|
|
10088
|
+
return new Response(html.replaceAll("{{version}}", version).replaceAll("{{channeld}}", channels ? "on" : "off"), {
|
|
10089
|
+
headers: {
|
|
10090
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
10091
|
+
"Cache-Control": "no-store"
|
|
10092
|
+
}
|
|
10093
|
+
});
|
|
10094
|
+
}
|
|
10095
|
+
if (req.method === "GET" && p === "/manifest.webmanifest") {
|
|
10096
|
+
const body = await fs5.readFile(path15.join(here, "manifest.webmanifest"), "utf8").catch(() => null);
|
|
10097
|
+
if (body === null)
|
|
10098
|
+
return json12({ error: "manifest not found" }, 404);
|
|
10099
|
+
return new Response(body, {
|
|
10100
|
+
headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-store" }
|
|
10101
|
+
});
|
|
10102
|
+
}
|
|
10103
|
+
if (req.method === "GET" && p === "/sw.js") {
|
|
10104
|
+
const body = await fs5.readFile(path15.join(here, "sw.js"), "utf8").catch(() => null);
|
|
10105
|
+
if (body === null)
|
|
10106
|
+
return json12({ error: "service worker not found" }, 404);
|
|
10107
|
+
const version = await chatVersionTag() || "dev";
|
|
10108
|
+
return new Response(body.replaceAll("{{version}}", version), {
|
|
10109
|
+
headers: {
|
|
10110
|
+
"Content-Type": "text/javascript; charset=utf-8",
|
|
10111
|
+
"Cache-Control": "no-store",
|
|
10112
|
+
"Service-Worker-Allowed": "/"
|
|
10113
|
+
}
|
|
10114
|
+
});
|
|
10115
|
+
}
|
|
10116
|
+
if (req.method === "GET" && p.startsWith("/assets/")) {
|
|
10117
|
+
let relative;
|
|
10118
|
+
try {
|
|
10119
|
+
relative = decodeURIComponent(p.slice("/assets/".length));
|
|
10120
|
+
} catch {
|
|
10121
|
+
return json12({ error: "invalid asset path" }, 400);
|
|
10122
|
+
}
|
|
10123
|
+
const root = path15.resolve(here, "assets");
|
|
10124
|
+
const file = path15.resolve(root, relative);
|
|
10125
|
+
if (!relative || !file.startsWith(`${root}${path15.sep}`) || !/\.(?:css|js|mjs|svg|png|jpg|woff2?)$/i.test(file))
|
|
10126
|
+
return json12({ error: "not found" }, 404);
|
|
10127
|
+
const data = await fs5.readFile(file).catch(() => null);
|
|
10128
|
+
if (!data)
|
|
10129
|
+
return json12({ error: "not found" }, 404);
|
|
10130
|
+
const type = file.endsWith(".css") ? "text/css" : file.endsWith(".svg") ? "image/svg+xml" : /\.(?:js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".png") ? "image/png" : file.endsWith(".jpg") ? "image/jpeg" : "font/woff2";
|
|
10131
|
+
return new Response(data, { headers: { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
|
|
10132
|
+
}
|
|
10133
|
+
if (["POST", "PUT", "PATCH", "DELETE"].includes(req.method) && !req.headers.get("content-type")?.includes("application/json") && !(/^\/rooms\/[^/]+\/resources$/.test(p) && req.method === "POST")) {
|
|
10134
|
+
return json12({ error: "content-type must be application/json" }, 415);
|
|
10135
|
+
}
|
|
10136
|
+
if (token && req.headers.get("authorization") !== `Bearer ${token}`) {
|
|
10137
|
+
return json12({ error: "unauthorized" }, 401);
|
|
10138
|
+
}
|
|
10139
|
+
try {
|
|
10140
|
+
const reminders = await roomReminderRoutes(req, url);
|
|
10141
|
+
if (reminders)
|
|
10142
|
+
return reminders;
|
|
10143
|
+
const admin = await adminRoutes(req, url);
|
|
10144
|
+
if (admin)
|
|
10145
|
+
return admin;
|
|
10146
|
+
const resource = await resourceRoutes(req, url);
|
|
10147
|
+
if (resource)
|
|
10148
|
+
return resource;
|
|
10149
|
+
const history = await historyRoute(url);
|
|
10150
|
+
if (history)
|
|
10151
|
+
return history;
|
|
10152
|
+
const addressing = await addressingRoutes(req, url);
|
|
10153
|
+
if (addressing)
|
|
10154
|
+
return addressing;
|
|
10155
|
+
const recall = await messageRecallRoutes(req, url);
|
|
10156
|
+
if (recall)
|
|
10157
|
+
return recall;
|
|
10158
|
+
const channel = await channelRoutes(req, url, channels);
|
|
10159
|
+
if (channel)
|
|
10160
|
+
return channel;
|
|
10161
|
+
if (req.method === "GET" && p === "/rooms/summary") {
|
|
10162
|
+
const rooms = await read((svc) => svc.listRooms().map((r) => ({
|
|
10163
|
+
id: r.id,
|
|
10164
|
+
name: r.name,
|
|
10165
|
+
latestMsgTs: r.messages.at(-1)?.createdAt ?? 0
|
|
10166
|
+
})));
|
|
10167
|
+
return json12(rooms);
|
|
10168
|
+
}
|
|
10169
|
+
if (req.method === "GET" && p === "/receiver/memberships") {
|
|
10170
|
+
const ownerID = url.searchParams.get("ownerID");
|
|
10171
|
+
if (!isReceiverOwnerID(ownerID))
|
|
10172
|
+
return json12({ error: "invalid ownerID" }, 400);
|
|
10173
|
+
const sessionIDs = await readState2((_svc, registry) => {
|
|
10174
|
+
return [...new Set(Object.values(registry).flatMap((entries) => Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id)))];
|
|
10175
|
+
});
|
|
10176
|
+
return json12({ sessionIDs });
|
|
10177
|
+
}
|
|
10178
|
+
if (req.method === "GET" && p === "/rooms") {
|
|
10179
|
+
const caller = url.searchParams.get("sessionID");
|
|
10180
|
+
const rows = await readState2((svc, registry) => svc.listRooms().filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller)).map((room) => ({ room, entry: caller ? registry[room.id]?.[caller] : undefined })));
|
|
10181
|
+
const rooms = [];
|
|
10182
|
+
for (const { room, entry } of rows) {
|
|
10183
|
+
rooms.push({ ...await roomPayload(room), joined: Boolean(entry), ...entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {} });
|
|
10184
|
+
}
|
|
10185
|
+
return json12(rooms);
|
|
10186
|
+
}
|
|
10187
|
+
const members = await memberRoutes(req, url);
|
|
10188
|
+
if (members)
|
|
10189
|
+
return members;
|
|
10190
|
+
const joinRequests = await joinRequestRoutes(req, url);
|
|
10191
|
+
if (joinRequests)
|
|
10192
|
+
return joinRequests;
|
|
10193
|
+
const management = await roomManagement(req, url);
|
|
10194
|
+
if (management)
|
|
10195
|
+
return management;
|
|
10196
|
+
if (req.method === "POST" && p === "/rooms") {
|
|
10197
|
+
const body = await jsonObject(req);
|
|
7932
10198
|
if (!body)
|
|
7933
|
-
return
|
|
10199
|
+
return json12({ error: "JSON object body is required" }, 400);
|
|
7934
10200
|
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
7935
|
-
return
|
|
10201
|
+
return json12({ error: "invalid receiver ownership" }, 400);
|
|
7936
10202
|
}
|
|
7937
10203
|
const name = body.name?.trim();
|
|
7938
10204
|
if (!name) {
|
|
7939
|
-
return
|
|
10205
|
+
return json12({ error: "name is required" }, 400);
|
|
7940
10206
|
}
|
|
7941
10207
|
if (name.length > 64) {
|
|
7942
|
-
return
|
|
10208
|
+
return json12({ error: "name too long (max 64)" }, 400);
|
|
7943
10209
|
}
|
|
7944
10210
|
const owner = (body.ownerId ?? "").trim() || "访客";
|
|
7945
10211
|
if (owner.length > 64) {
|
|
7946
|
-
return
|
|
10212
|
+
return json12({ error: "ownerId too long (max 64)" }, 400);
|
|
7947
10213
|
}
|
|
7948
10214
|
if (body.joinPolicy !== undefined && body.joinPolicy !== "open" && body.joinPolicy !== "approval") {
|
|
7949
|
-
return
|
|
10215
|
+
return json12({ error: "joinPolicy must be open or approval" }, 400);
|
|
7950
10216
|
}
|
|
7951
10217
|
const joinPolicy = body.joinPolicy === "approval" ? "approval" : body.joinPolicy === "open" ? "open" : undefined;
|
|
7952
10218
|
const room = await mutate2((svc, reg) => {
|
|
@@ -7956,7 +10222,7 @@ async function handle(req) {
|
|
|
7956
10222
|
regRoom[body.sessionID] = {
|
|
7957
10223
|
serverUrl: "",
|
|
7958
10224
|
apiPrefix: "/api",
|
|
7959
|
-
membershipID:
|
|
10225
|
+
membershipID: randomUUID16(),
|
|
7960
10226
|
...body.protocol === "v2" ? { protocol: "v2" } : {},
|
|
7961
10227
|
...body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {},
|
|
7962
10228
|
name: owner,
|
|
@@ -7969,7 +10235,7 @@ async function handle(req) {
|
|
|
7969
10235
|
}
|
|
7970
10236
|
return created;
|
|
7971
10237
|
});
|
|
7972
|
-
return
|
|
10238
|
+
return json12(await roomPayload(room), 201);
|
|
7973
10239
|
}
|
|
7974
10240
|
if (req.method === "GET" && p === "/inbox") {
|
|
7975
10241
|
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
@@ -7978,11 +10244,11 @@ async function handle(req) {
|
|
|
7978
10244
|
const afterTs = afterValue === null ? undefined : Number(afterValue);
|
|
7979
10245
|
const recallVersionValue = url.searchParams.get("recallVersion");
|
|
7980
10246
|
if (url.searchParams.has("recallVersion") && (recallVersionValue === "" || !/^\d+$/.test(recallVersionValue ?? "") || !Number.isSafeInteger(Number(recallVersionValue)))) {
|
|
7981
|
-
return
|
|
10247
|
+
return json12({ error: "recallVersion must be a non-negative safe integer" }, 400);
|
|
7982
10248
|
}
|
|
7983
10249
|
const clientRecallVersion = recallVersionValue === null ? undefined : Number(recallVersionValue);
|
|
7984
10250
|
if (url.searchParams.has("afterTs") && (afterValue === "" || !/^\d+$/.test(afterValue ?? "") || !Number.isSafeInteger(afterTs) || afterTs < 0 || !roomFilter || url.searchParams.get("excludeSelf") !== "0")) {
|
|
7985
|
-
return
|
|
10251
|
+
return json12({ error: "afterTs requires a roomId and excludeSelf=0, with a non-negative safe integer value" }, 400);
|
|
7986
10252
|
}
|
|
7987
10253
|
const excludeSelf = url.searchParams.get("excludeSelf") === "1";
|
|
7988
10254
|
const timeout = Math.min(Math.max(Number(url.searchParams.get("timeout") ?? 0) || 0, 0), 30000);
|
|
@@ -7993,59 +10259,59 @@ async function handle(req) {
|
|
|
7993
10259
|
await sleep(Math.max(1, Math.min(500, deadline - Date.now())));
|
|
7994
10260
|
result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
|
|
7995
10261
|
}
|
|
7996
|
-
return
|
|
10262
|
+
return json12(result);
|
|
7997
10263
|
}
|
|
7998
10264
|
if (req.method === "POST" && p === "/queued") {
|
|
7999
10265
|
const body = await jsonObject(req);
|
|
8000
10266
|
if (!body)
|
|
8001
|
-
return
|
|
10267
|
+
return json12({ error: "JSON object body is required" }, 400);
|
|
8002
10268
|
const ts = Number(body.ts);
|
|
8003
10269
|
const roomId = String(body.roomId ?? "");
|
|
8004
10270
|
const sessionID = String(body.sessionID ?? "");
|
|
8005
10271
|
if (body.ts === undefined || body.ts === null || !roomId || !sessionID || !Number.isFinite(ts)) {
|
|
8006
|
-
return
|
|
10272
|
+
return json12({ error: "roomId/sessionID/finite ts are required" }, 400);
|
|
8007
10273
|
}
|
|
8008
10274
|
const updated = await acknowledgeQueued2(roomId, sessionID, ts);
|
|
8009
10275
|
if (updated === null) {
|
|
8010
|
-
return
|
|
10276
|
+
return json12({ error: "registry entry not found" }, 404);
|
|
8011
10277
|
}
|
|
8012
10278
|
clearPendingAdmission(sessionID, roomId, updated);
|
|
8013
10279
|
touchActive(sessionID);
|
|
8014
|
-
return
|
|
10280
|
+
return json12({ ok: true });
|
|
8015
10281
|
}
|
|
8016
10282
|
if (req.method === "POST" && p === "/active") {
|
|
8017
10283
|
const body = await jsonObject(req);
|
|
8018
10284
|
if (!body)
|
|
8019
|
-
return
|
|
10285
|
+
return json12({ error: "JSON object body is required" }, 400);
|
|
8020
10286
|
touchActive(String(body.sessionID ?? ""));
|
|
8021
|
-
return
|
|
10287
|
+
return json12({ ok: true });
|
|
8022
10288
|
}
|
|
8023
10289
|
if (req.method === "POST" && p === "/wake-claim") {
|
|
8024
10290
|
const body = await jsonObject(req);
|
|
8025
10291
|
if (!body)
|
|
8026
|
-
return
|
|
10292
|
+
return json12({ error: "JSON object body is required" }, 400);
|
|
8027
10293
|
const sessionID = String(body.sessionID ?? "");
|
|
8028
10294
|
const ok = claimWake(sessionID);
|
|
8029
|
-
return
|
|
10295
|
+
return json12({ ok });
|
|
8030
10296
|
}
|
|
8031
10297
|
const m = p.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
|
|
8032
10298
|
if (m) {
|
|
8033
10299
|
const roomId = decodeURIComponent(m[1]);
|
|
8034
10300
|
const body = await jsonObject(req);
|
|
8035
10301
|
if (!body)
|
|
8036
|
-
return
|
|
10302
|
+
return json12({ error: "JSON object body is required" }, 400);
|
|
8037
10303
|
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
8038
10304
|
if (req.method === "POST" && m[2] === "join") {
|
|
8039
10305
|
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
8040
|
-
return
|
|
10306
|
+
return json12({ error: "invalid receiver ownership" }, 400);
|
|
8041
10307
|
}
|
|
8042
10308
|
const id = typeof body.participantId === "string" ? body.participantId.trim() : "";
|
|
8043
10309
|
const name = typeof body.participantName === "string" ? body.participantName.trim() : "";
|
|
8044
10310
|
if (!id || !name || !sessionID) {
|
|
8045
|
-
return
|
|
10311
|
+
return json12({ error: "participantId/participantName/sessionID are required" }, 400);
|
|
8046
10312
|
}
|
|
8047
10313
|
if (id.length > 64 || name.length > 64) {
|
|
8048
|
-
return
|
|
10314
|
+
return json12({ error: "name too long (max 64)" }, 400);
|
|
8049
10315
|
}
|
|
8050
10316
|
const result = await writeSqliteStateWithDatabase(databasePath(), (svc, reg, db) => {
|
|
8051
10317
|
const currentRoom = svc.getRoom(roomId);
|
|
@@ -8080,14 +10346,14 @@ async function handle(req) {
|
|
|
8080
10346
|
}) };
|
|
8081
10347
|
});
|
|
8082
10348
|
if ("status" in result)
|
|
8083
|
-
return
|
|
10349
|
+
return json12({ error: result.error }, result.status);
|
|
8084
10350
|
if ("pending" in result)
|
|
8085
|
-
return
|
|
10351
|
+
return json12({
|
|
8086
10352
|
status: "pending",
|
|
8087
10353
|
message: "Join request submitted. You are not a member yet; a human administrator must approve it before you can send or poll."
|
|
8088
10354
|
}, 202);
|
|
8089
10355
|
touchActive(sessionID);
|
|
8090
|
-
return
|
|
10356
|
+
return json12(await roomPayload(result.room), 201);
|
|
8091
10357
|
}
|
|
8092
10358
|
if (req.method === "POST" && m[2] === "leave") {
|
|
8093
10359
|
await mutate2((svc, reg) => {
|
|
@@ -8120,54 +10386,56 @@ async function handle(req) {
|
|
|
8120
10386
|
settleAdmins(svc.getRoom(roomId), reg[roomId] ?? {});
|
|
8121
10387
|
settleOwner(svc.getRoom(roomId), reg[roomId] ?? {});
|
|
8122
10388
|
});
|
|
8123
|
-
return
|
|
10389
|
+
return json12({ ok: true });
|
|
8124
10390
|
}
|
|
8125
10391
|
if (req.method === "POST" && m[2] === "messages") {
|
|
8126
10392
|
const isQuestion = body.isQuestion;
|
|
8127
10393
|
if (isQuestion !== undefined && typeof isQuestion !== "boolean")
|
|
8128
|
-
return
|
|
10394
|
+
return json12({ error: "isQuestion must be a boolean" }, 400);
|
|
8129
10395
|
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
8130
10396
|
if (!text) {
|
|
8131
|
-
return
|
|
10397
|
+
return json12({ error: "text is required" }, 400);
|
|
8132
10398
|
}
|
|
8133
10399
|
if (text.length > 5000) {
|
|
8134
|
-
return
|
|
10400
|
+
return json12({ error: "text too long (max 5000)" }, 400);
|
|
8135
10401
|
}
|
|
8136
|
-
const replyTo = body.replyToMessageID;
|
|
10402
|
+
const replyTo = body.replyToMessageID ?? body.parentMessageId;
|
|
8137
10403
|
if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo))
|
|
8138
|
-
return
|
|
10404
|
+
return json12({ error: "parentMessageId must be a non-empty message ID" }, 400);
|
|
8139
10405
|
const clientMessageID = body.clientMessageID;
|
|
8140
10406
|
if (clientMessageID !== undefined && (typeof clientMessageID !== "string" || !clientMessageID || clientMessageID.length > 100)) {
|
|
8141
|
-
return
|
|
10407
|
+
return json12({ error: "clientMessageID must be a non-empty string (max 100)" }, 400);
|
|
8142
10408
|
}
|
|
8143
10409
|
if (replyTo !== undefined) {
|
|
8144
10410
|
const result = await sendReply2(roomId, replyTo, sessionID, text, clientMessageID);
|
|
8145
10411
|
if (result.status !== "ok") {
|
|
8146
10412
|
if (result.status === "missing")
|
|
8147
|
-
return
|
|
10413
|
+
return json12({ error: "room not found" }, 404);
|
|
8148
10414
|
if (result.status === "target")
|
|
8149
|
-
return
|
|
10415
|
+
return json12({ error: "reply target not found in room" }, 404);
|
|
10416
|
+
if (result.status === "recalled")
|
|
10417
|
+
return json12({ error: "reply target was recalled" }, 409);
|
|
8150
10418
|
if (result.status === "question")
|
|
8151
|
-
return
|
|
8152
|
-
return
|
|
10419
|
+
return json12({ error: "use the question answers endpoint to reply to a question" }, 409);
|
|
10420
|
+
return json12({ error: "not found" }, 404);
|
|
8153
10421
|
}
|
|
8154
10422
|
touchActive(sessionID);
|
|
8155
10423
|
const room = await read((svc) => svc.getRoom(roomId));
|
|
8156
10424
|
if (!result.duplicate)
|
|
8157
10425
|
wakeMentionedSessions(serveWakeUrl2, roomId, room.name, text, sessionID, result.message);
|
|
8158
|
-
return
|
|
10426
|
+
return json12(await roomPayload(room), 201);
|
|
8159
10427
|
}
|
|
8160
10428
|
const result = await appendRoomMessage2(roomId, sessionID, text, isQuestion === true, clientMessageID);
|
|
8161
10429
|
if (result.status !== "ok") {
|
|
8162
10430
|
if (result.status === "missing")
|
|
8163
|
-
return
|
|
8164
|
-
return
|
|
10431
|
+
return json12({ error: "room not found" }, 404);
|
|
10432
|
+
return json12({ error: "session is not a room member" }, 409);
|
|
8165
10433
|
}
|
|
8166
10434
|
touchActive(sessionID);
|
|
8167
10435
|
const room = await read((svc) => svc.getRoom(roomId));
|
|
8168
10436
|
if (!result.duplicate)
|
|
8169
10437
|
wakeMentionedSessions(serveWakeUrl2, roomId, room.name, text, sessionID, result.message);
|
|
8170
|
-
return
|
|
10438
|
+
return json12(await roomPayload(room), 201);
|
|
8171
10439
|
}
|
|
8172
10440
|
}
|
|
8173
10441
|
const questions = p.match(/^\/rooms\/([^/]+)\/questions$/);
|
|
@@ -8175,8 +10443,8 @@ async function handle(req) {
|
|
|
8175
10443
|
const roomId = decodeURIComponent(questions[1]);
|
|
8176
10444
|
const exists = await read((svc) => svc.listRooms().some((room) => room.id === roomId));
|
|
8177
10445
|
if (!exists)
|
|
8178
|
-
return
|
|
8179
|
-
return
|
|
10446
|
+
return json12({ error: "room not found" }, 404);
|
|
10447
|
+
return json12({ questions: await readQuestions2(roomId) });
|
|
8180
10448
|
}
|
|
8181
10449
|
const answer = p.match(/^\/rooms\/([^/]+)\/questions\/([^/]+)\/answers$/);
|
|
8182
10450
|
if (req.method === "POST" && answer) {
|
|
@@ -8184,30 +10452,30 @@ async function handle(req) {
|
|
|
8184
10452
|
const questionID = decodeURIComponent(answer[2]);
|
|
8185
10453
|
const body = await req.json();
|
|
8186
10454
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
8187
|
-
return
|
|
10455
|
+
return json12({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
|
|
8188
10456
|
const input = body;
|
|
8189
10457
|
if (typeof input.sessionID !== "string" || !input.sessionID || typeof input.text !== "string" || !input.text.trim() || input.text.trim().length > 5000)
|
|
8190
|
-
return
|
|
10458
|
+
return json12({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
|
|
8191
10459
|
const result = await answerQuestion2(roomId, questionID, input.sessionID, input.text.trim());
|
|
8192
10460
|
if (result.status === "missing")
|
|
8193
|
-
return
|
|
10461
|
+
return json12({ error: "room not found" }, 404);
|
|
8194
10462
|
if (result.status === "question")
|
|
8195
|
-
return
|
|
10463
|
+
return json12({ error: "question not found" }, 404);
|
|
8196
10464
|
if (result.status === "member")
|
|
8197
|
-
return
|
|
10465
|
+
return json12({ error: "session is not a room member" }, 409);
|
|
8198
10466
|
if (result.status === "answered")
|
|
8199
|
-
return
|
|
10467
|
+
return json12({ error: "question already answered" }, 409);
|
|
8200
10468
|
if (result.status !== "ok")
|
|
8201
|
-
return
|
|
10469
|
+
return json12({ error: "question not found" }, 404);
|
|
8202
10470
|
touchActive(input.sessionID);
|
|
8203
10471
|
const room = await read((svc) => svc.getRoom(roomId));
|
|
8204
10472
|
wakeMentionedSessions(serveWakeUrl2, roomId, room.name, result.answer.text, input.sessionID, result.answer);
|
|
8205
|
-
return
|
|
10473
|
+
return json12({ questionID, answer: result.answer }, 201);
|
|
8206
10474
|
}
|
|
8207
10475
|
const g = p.match(/^\/rooms\/([^/]+)$/);
|
|
8208
10476
|
if (g && req.method === "GET") {
|
|
8209
10477
|
const room = await read((svc) => svc.getRoom(decodeURIComponent(g[1])));
|
|
8210
|
-
return
|
|
10478
|
+
return json12(await roomPayload(room));
|
|
8211
10479
|
}
|
|
8212
10480
|
const r = p.match(/^\/rooms\/([^/]+)\/registry$/);
|
|
8213
10481
|
if (r && req.method === "GET") {
|
|
@@ -8229,22 +10497,22 @@ async function handle(req) {
|
|
|
8229
10497
|
}
|
|
8230
10498
|
]));
|
|
8231
10499
|
});
|
|
8232
|
-
return
|
|
10500
|
+
return json12(reg);
|
|
8233
10501
|
}
|
|
8234
|
-
return
|
|
10502
|
+
return json12({ error: "not found" }, 404);
|
|
8235
10503
|
} catch (err) {
|
|
8236
10504
|
if (err instanceof SyntaxError)
|
|
8237
|
-
return
|
|
10505
|
+
return json12({ error: "invalid JSON body" }, 400);
|
|
8238
10506
|
if (err instanceof RoomError) {
|
|
8239
|
-
return
|
|
10507
|
+
return json12({ error: err.message }, err.code === "ROOM_NOT_FOUND" ? 404 : err.code === "NOT_OWNER" ? 403 : 409);
|
|
8240
10508
|
}
|
|
8241
|
-
return
|
|
10509
|
+
return json12({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
8242
10510
|
}
|
|
8243
10511
|
}
|
|
8244
|
-
var moduleDir, here, versionTag, chatVersionTag = () => versionTag ??= fs5.readFile(
|
|
10512
|
+
var moduleDir, here, versionTag, chatVersionTag = () => versionTag ??= fs5.readFile(path15.join(here, "../package.json"), "utf8").then((text) => {
|
|
8245
10513
|
const pkg = JSON.parse(text);
|
|
8246
10514
|
return typeof pkg?.version === "string" && pkg.version ? `v${pkg.version}` : "";
|
|
8247
|
-
}).catch(() => ""), settings, hostname, displayHostname, port, token, serveWakeUrl2,
|
|
10515
|
+
}).catch(() => ""), settings, hostname, displayHostname, port, token, channels, serveWakeUrl2, json12 = (body, status = 200) => new Response(JSON.stringify(body), {
|
|
8248
10516
|
status,
|
|
8249
10517
|
headers: { "Content-Type": "application/json" }
|
|
8250
10518
|
}), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), config, chat_server_default;
|
|
@@ -8257,6 +10525,7 @@ var init_chat_server = __esm(async () => {
|
|
|
8257
10525
|
init_receiver_owner();
|
|
8258
10526
|
init_wake();
|
|
8259
10527
|
init_history_route();
|
|
10528
|
+
init_addressing_routes();
|
|
8260
10529
|
init_message_recall_routes();
|
|
8261
10530
|
init_room_payload();
|
|
8262
10531
|
init_room_owner();
|
|
@@ -8267,11 +10536,12 @@ var init_chat_server = __esm(async () => {
|
|
|
8267
10536
|
init_join_requests();
|
|
8268
10537
|
init_room_join();
|
|
8269
10538
|
init_room_reminders();
|
|
10539
|
+
init_channels();
|
|
8270
10540
|
init_file_config();
|
|
8271
10541
|
init_http_server();
|
|
8272
10542
|
await init_admin_routes();
|
|
8273
|
-
moduleDir =
|
|
8274
|
-
here = existsSync4(
|
|
10543
|
+
moduleDir = path15.dirname(fileURLToPath4(import.meta.url));
|
|
10544
|
+
here = existsSync4(path15.join(moduleDir, "chat.html")) ? moduleDir : path15.resolve(moduleDir, "../server");
|
|
8275
10545
|
settings = resolveServerSettings(loadRoomConfig());
|
|
8276
10546
|
hostname = settings.host;
|
|
8277
10547
|
displayHostname = hostname.includes(":") ? `[${hostname}]` : hostname;
|
|
@@ -8291,6 +10561,15 @@ var init_chat_server = __esm(async () => {
|
|
|
8291
10561
|
maxRequestBodySize: Math.max(128 * 1024 * 1024, maxResourceBytes())
|
|
8292
10562
|
};
|
|
8293
10563
|
chat_server_default = config;
|
|
10564
|
+
channels = await startChannels(settings);
|
|
10565
|
+
if (channels) {
|
|
10566
|
+
let stopping;
|
|
10567
|
+
const stop = () => {
|
|
10568
|
+
stopping ??= stopChannels(channels).finally(() => process.exit(0));
|
|
10569
|
+
};
|
|
10570
|
+
process.once("SIGINT", stop);
|
|
10571
|
+
process.once("SIGTERM", stop);
|
|
10572
|
+
}
|
|
8294
10573
|
if (false)
|
|
8295
10574
|
;
|
|
8296
10575
|
console.log(`chat-room center listening on http://${displayHostname}:${port}${token ? " (token auth on)" : ""}`);
|